sitelink1 http://webnautes.tistory.com/1080 
sitelink2  
sitelink3  

Google Maps Android API를 안드로이드에서 사용하는 방법과  GoogleApiClient를 이용하여 현재 위치를 구글맵에 표시하는 내용을 다음 포스팅에서 다루었습니다. 이번에는 Places API Web Service를 이용하여 현재 위치 주변의 음식점 정보를 구글맵에 표시하는 내용을 다룹니다.

 

[Android/Google Map] - Google Maps Android API v2 예제

[Android/Google Map] - GoogleApiClient를 사용하여 Android Google Map에 현재 위치 표시하기

 

 

Places API Web Service 키 얻기

Google Map에 현재 위치 주변의 음식점 표시하기

실행 결과

 

 

 

Places API Web Service 키 얻기

Google Developers Console(https://console.developers.google.com/project )에 방문합니다. 

 

1. 프로젝트 만들기를 선택합니다.

 

 

2. 프로젝트 이름을 적어주고 만들기를 선택합니다.

 

3. 검색창에 place를 입력하여 검색되는 Google Places API Web Services를 선택합니다.

 

4.  사용 설정을 선택하면 잠시후 사용중지로 변합니다. 이제 Google Places API Web Services가 활성화 되었습니다.

 

5. 사용자 인증 정보 만들기를 선택합니다.

 

6. 어떤 사용자 인증 정보가 필요한가요?를 선택합니다.

 

7. API키가 생성되었습니다. 메모장에 복사해두고 완료를 선택합니다. 

 

 

Google Map에 현재 위치 주변의 음식점 표시하기

Places API Web Service에서 제공하는 REST API를 이용하여 현재 위치 주변의 음식점에 대한 정보를 요청하여 획득된 JSON을 파싱하는 작업을 해주면  되지만 여기에서는 간단하게 구현이 가능한 Android-Google-Places-API를 사용했습니다.

Android-Google-Places-API( https://github.com/nomanr/Android-Google-Places-API )

 

다음 포스팅에서 작성했던 코드를 수정해서 진행했습니다.

[Android/Google Map] - GoogleApiClient를 사용하여 Android Google Map에 현재 위치 표시하기

 

activity_main.xml에 버튼을 추가하고 android:layout_weight 속성을 추가합니다. 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

              xmlns:tools="http://schemas.android.com/tools"

              android:layout_width="match_parent"

              android:layout_height="match_parent"

              android:orientation="vertical"

              tools:context=".MainActivity" >

    <fragment

        android:id="@+id/map"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_weight="0.8"

        class="com.google.android.gms.maps.MapFragment" />

 

    <Button

        android:text="장소검색"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_weight="0.2"

        android:id="@+id/button"/>

</LinearLayout>

 

Colored by Color Scripter

cs

 

 

build.gradle 파일에 붉은색으로 표시한 한 줄을 추가해줍니다.

1

2

3

4

5

6

7

8

9

10

11

dependencies {

    compile fileTree(include: ['*.jar'], dir: 'libs')

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {

        exclude group: 'com.android.support', module: 'support-annotations'

    })

    compile 'com.android.support:appcompat-v7:25.0.1'

    testCompile 'junit:junit:4.12'

    compile 'com.google.android.gms:play-services:10.0.0'

    compile 'com.android.support:multidex:1.0.1'

    compile 'noman.placesapi:placesAPI:1.0.0'

}

Colored by Color Scripter

cs

 

 

수정한 MainActivity.java 파일입니다. onCreate 메소드에서 아래위치에 메모장에 저장했던 Places API Web Service 키를 입력해주어야 합니다. 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

        previous_marker = new ArrayList<Marker>();

 

        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

 

                googleMap.clear();//지도 클리어

 

                if ( previous_marker != null)

                previous_marker.clear();//지역정보 마커 클리어

 

                new NRPlaces.Builder()

                        .listener(MainActivity.this)

                        .key("Places API Web Service의 키")

                        .latlng(currentPosition.latitude, currentPosition.longitude)//현재 위치

                        .radius(500) //500 미터 내에서 검색

                        .type(PlaceType.RESTAURANT) //음식점

                        .build()

                        .execute();

            }

        });

Colored by Color Scripter

cs

 

지도상에 주변 음식점의 위치를 마커로 그리는 부분입니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

   @Override

    public void onPlacesSuccess(final List<noman.googleplaces.Place> places) {

        Log.i("PlacesAPI", "onPlacesSuccess()");

 

        runOnUiThread(new Runnable() {

            @Override

            public void run() {

                for (noman.googleplaces.Place place : places) {

 

                    LatLng latLng = new LatLng(place.getLatitude(), place.getLongitude());

 

                    MarkerOptions markerOptions = new MarkerOptions();

                    markerOptions.position(latLng);

                    markerOptions.title(place.getName());

                    markerOptions.snippet(place.getVicinity());

                    Marker item = googleMap.addMarker(markerOptions);

                    previous_marker.add(item);

 

                }

 

                //중복 마커 제거

                HashSet<Marker> hashSet = new HashSet<Marker>();

                hashSet.addAll(previous_marker);

                previous_marker.clear();

                previous_marker.addAll(hashSet);

 

            }

        });

    }

Colored by Color Scripter

cs

 

전체 소스코드입니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

package com.tistory.webnautes.googlemap;

 

import android.Manifest;

import android.app.Activity;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.location.Address;

import android.location.Geocoder;

import android.location.Location;

import android.location.LocationManager;

import android.os.Build;

import android.os.Bundle;

import android.support.annotation.NonNull;

import android.support.annotation.Nullable;

import android.support.v4.app.ActivityCompat;

import android.support.v7.app.AlertDialog;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

 

import com.google.android.gms.common.ConnectionResult;

import com.google.android.gms.common.api.GoogleApiClient;

import com.google.android.gms.location.LocationListener;

import com.google.android.gms.location.LocationRequest;

import com.google.android.gms.location.LocationServices;

import com.google.android.gms.maps.CameraUpdateFactory;

import com.google.android.gms.maps.GoogleMap;

import com.google.android.gms.maps.MapFragment;

import com.google.android.gms.maps.OnMapReadyCallback;

import com.google.android.gms.maps.model.LatLng;

import com.google.android.gms.maps.model.Marker;

import com.google.android.gms.maps.model.MarkerOptions;

 

import java.io.IOException;

import java.util.ArrayList;

import java.util.Collections;

import java.util.HashSet;

import java.util.List;

import java.util.Locale;

import java.util.Set;

 

import noman.googleplaces.NRPlaces;

import noman.googleplaces.PlaceType;

import noman.googleplaces.PlacesException;

import noman.googleplaces.PlacesListener;

 

 

public class MainActivity extends Activity implements

        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,

        LocationListener, OnMapReadyCallback, PlacesListener {

 

    private static final String TAG = "@@@";

    private GoogleApiClient mGoogleApiClient = null;

    private LocationRequest mLocationRequest;

    private static final int REQUEST_CODE_LOCATION = 2000;//임의의 정수로 정의

    private static final int REQUEST_CODE_GPS = 2001;//임의의 정수로 정의

    private GoogleMap googleMap;

    LocationManager locationManager;

    MapFragment mapFragment;

    boolean setGPS = false;

    LatLng SEOUL = new LatLng(37.56, 126.97);

    LatLng currentPosition;

    Marker current_marker =null;

    List<Marker> previous_marker = null;

 

    protected synchronized void buildGoogleApiClient() {

        mGoogleApiClient = new GoogleApiClient.Builder(this)

                .addConnectionCallbacks(this)

                .addOnConnectionFailedListener(this)

                .addApi(LocationServices.API)

                .build();

 

        mGoogleApiClient.connect();

 

 

    }

 

 

    //GPS 활성화를 위한 다이얼로그 보여주기

    private void showGPSDisabledAlertToUser() {

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

        alertDialogBuilder.setMessage("GPS가 비활성화 되어있습니다. 활성화 할까요?")

                .setCancelable(false)

                .setPositiveButton("설정", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {

                        Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);

                        startActivityForResult(callGPSSettingIntent, REQUEST_CODE_GPS);

                    }

                });

 

        alertDialogBuilder.setNegativeButton("취소", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {

                dialog.cancel();

            }

        });

        AlertDialog alert = alertDialogBuilder.create();

        alert.show();

    }

 

 

    //GPS 활성화를 위한 다이얼로그의 결과 처리

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

 

        switch (requestCode) {

            case REQUEST_CODE_GPS:

                //Log.d(TAG,""+resultCode);

                //if (resultCode == RESULT_OK)

                //사용자가 GPS 활성 시켰는지 검사

                if (locationManager == null)

                    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

 

                if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

                    // GPS 가 ON으로 변경되었을 때의 처리.

                    setGPS = true;

 

                    mapFragment.getMapAsync(MainActivity.this);

                }

                break;

        }

    }

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

 

        mapFragment = (MapFragment) getFragmentManager()

                .findFragmentById(R.id.map);

        mapFragment.getMapAsync(this);

 

        previous_marker = new ArrayList<Marker>();

 

        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

 

                googleMap.clear();//지도 클리어

 

                if ( previous_marker != null)

                previous_marker.clear();//지역정보 마커 클리어

 

                new NRPlaces.Builder()

                        .listener(MainActivity.this)

                        .key("Places API Web Service의 키")

                        .latlng(currentPosition.latitude, currentPosition.longitude)//현재 위치

                        .radius(500) //500 미터 내에서 검색

                        .type(PlaceType.RESTAURANT) //음식점

                        .build()

                        .execute();

            }

        });

    }

 

 

    public boolean checkLocationPermission()

    {

        Log.d( TAG, "checkLocationPermission");

 

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED

                    && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

 

                //퍼미션 요청을 위해 UI를 보여줘야 하는지 검사

                if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {

                    // Show an expanation to the user *asynchronously* -- don't block

                    // this thread waiting for the user's response! After the user

                    // sees the explanation, try again to request the permission.

 

                    //Prompt the user once explanation has been shown;

                    requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_LOCATION);

 

                } else

                    //UI보여줄 필요 없이 요청

                    requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_LOCATION);

 

                return false;

            } else {

 

                Log.d( TAG, "checkLocationPermission"+"이미 퍼미션 획득한 경우");

 

                if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS)

                {

                    Log.d(TAG, "checkLocationPermission Version >= M");

                    showGPSDisabledAlertToUser();

                }

 

                if (mGoogleApiClient == null) {

                    Log.d( TAG, "checkLocationPermission "+"mGoogleApiClient==NULL");

                    buildGoogleApiClient();

                }

                else  Log.d( TAG, "checkLocationPermission "+"mGoogleApiClient!=NULL");

 

                if ( mGoogleApiClient.isConnected() ) Log.d( TAG, "checkLocationPermission"+"mGoogleApiClient 연결되 있음");

                else Log.d( TAG, "checkLocationPermission"+"mGoogleApiClient 끊어져 있음");

 

 

                mGoogleApiClient.reconnect();//이미 연결되 있는 경우이므로 다시 연결

 

                googleMap.setMyLocationEnabled(true);

            }

        }

        else {

            if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS)

            {

                Log.d(TAG, "checkLocationPermission Version < M");

                showGPSDisabledAlertToUser();

            }

 

            if (mGoogleApiClient == null) {

                buildGoogleApiClient();

            }

            googleMap.setMyLocationEnabled(true);

        }

 

        return true;

    }

 

    @Override

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {

            case REQUEST_CODE_LOCATION: {

 

                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)

                {

                    //퍼미션이 허가된 경우

                    if ((ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED

                            || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED))

                    {

 

                        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS)

                        {

                            Log.d(TAG, "onRequestPermissionsResult");

                            showGPSDisabledAlertToUser();

                        }

 

 

                        if (mGoogleApiClient == null) {

                            buildGoogleApiClient();

                        }

                        googleMap.setMyLocationEnabled(true);

                    }

                } else {

                    Toast.makeText(this, "퍼미션 취소", Toast.LENGTH_LONG).show();

                }

                return;

            }

        }

    }

 

    @Override

    public void onMapReady(GoogleMap map)

    {

        googleMap = map;

 

        googleMap.moveCamera(CameraUpdateFactory.newLatLng(SEOUL));

        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

 

 

        googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {

 

            @Override

            public void onMapLoaded() {

                Log.d( TAG, "onMapLoaded" );

 

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)

                {

                    checkLocationPermission();

                }

                else

                {

 

                    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !setGPS)

                    {

                        Log.d(TAG, "onMapLoaded");

                        showGPSDisabledAlertToUser();

                    }

 

                    if (mGoogleApiClient == null) {

                        buildGoogleApiClient();

                    }

                    googleMap.setMyLocationEnabled(true);

                }

 

            }

        });

 

 

        //구글 플레이 서비스 초기화

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)

        {

            if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED

                    || ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)

            {

                buildGoogleApiClient();

 

                googleMap.setMyLocationEnabled(true);

            }

            else

            {

                googleMap.moveCamera(CameraUpdateFactory.newLatLng(SEOUL));

                googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

            }

        }

        else

        {

            buildGoogleApiClient();

            googleMap.setMyLocationEnabled(true);

        }

    }

 

 

    //성공적으로 GoogleApiClient 객체 연결되었을 때 실행

    @Override

    public void onConnected(@Nullable Bundle bundle) {

        Log.d( TAG, "onConnected" );

 

        if ( locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))

            setGPS = true;

 

        mLocationRequest = new LocationRequest();

        //mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        mLocationRequest.setInterval(1000);

        mLocationRequest.setFastestInterval(1000);

 

 

        if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED

                || ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

 

            Log.d( TAG, "onConnected " + "getLocationAvailability mGoogleApiClient.isConnected()="+mGoogleApiClient.isConnected() );

            if ( !mGoogleApiClient.isConnected()  ) mGoogleApiClient.connect();

 

 

            // LocationAvailability locationAvailability = LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient);

 

            if ( setGPS && mGoogleApiClient.isConnected() )//|| locationAvailability.isLocationAvailable() )

            {

                Log.d( TAG, "onConnected " + "requestLocationUpdates" );

                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

 

                Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                if ( location == null ) return;

 

                //현재 위치에 마커 생성

                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

                MarkerOptions markerOptions = new MarkerOptions();

                markerOptions.position(latLng);

                markerOptions.title("현재위치");

                googleMap.addMarker(markerOptions);

 

                //지도 상에서 보여주는 영역 이동

                googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

                googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

            }

 

        }

 

    }

 

 

    @Override

    public void onConnectionFailed(ConnectionResult result) {

        Log.d(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());

    }

 

    @Override

    public void onConnectionSuspended(int cause) {

        //구글 플레이 서비스 연결이 해제되었을 때, 재연결 시도

        Log.d(TAG, "Connection suspended");

        mGoogleApiClient.connect();

    }

 

    @Override

    protected void onStart() {

        super.onStart();

 

        if (mGoogleApiClient != null)

            mGoogleApiClient.connect();

    }

 

    @Override

    public void onResume() {

        super.onResume();

        if (mGoogleApiClient != null)

            mGoogleApiClient.connect();

    }

 

    @Override

    protected void onStop() {

 

        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {

            mGoogleApiClient.disconnect();

        }

        super.onStop();

    }

 

 

    @Override

    public void onPause() {

        if ( mGoogleApiClient != null && mGoogleApiClient.isConnected()) {

            mGoogleApiClient.disconnect();

        }

 

        super.onPause();

    }

 

    @Override

    protected void onDestroy() {

 

        Log.d( TAG, "OnDestroy");

 

        if (mGoogleApiClient != null) {

            mGoogleApiClient.unregisterConnectionCallbacks(this);

            mGoogleApiClient.unregisterConnectionFailedListener(this);

 

            if (mGoogleApiClient.isConnected()) {

                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

            }

 

            mGoogleApiClient.disconnect();

            mGoogleApiClient = null;

        }

 

        super.onDestroy();

    }

 

 

    @Override

    public void onLocationChanged(Location location) {

 

        currentPosition = new LatLng( location.getLatitude(), location.getLongitude() );

        String errorMessage = "";

 

        if (current_marker != null )

            current_marker.remove();

 

        //현재 위치에 마커 생성

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

        MarkerOptions markerOptions = new MarkerOptions();

        markerOptions.position(latLng);

        markerOptions.title("현재위치");

        current_marker = googleMap.addMarker(markerOptions);

 

        //지도 상에서 보여주는 영역 이동

        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

        googleMap.getUiSettings().setCompassEnabled(true);

 

 

        //지오코더... GPS를 주소로 변환

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());

 

        // Address found using the Geocoder.

        List<Address> addresses = null;

 

        try {

            // Using getFromLocation() returns an array of Addresses for the area immediately

            // surrounding the given latitude and longitude. The results are a best guess and are

            // not guaranteed to be accurate.

            addresses = geocoder.getFromLocation(

                    location.getLatitude(),

                    location.getLongitude(),

                    // In this sample, we get just a single address.

                    1);

        } catch (IOException ioException) {

            // Catch network or other I/O problems.

            errorMessage = "지오코더 서비스 사용불가";

            Toast.makeText( this, errorMessage, Toast.LENGTH_LONG).show();

        } catch (IllegalArgumentException illegalArgumentException) {

            // Catch invalid latitude or longitude values.

            errorMessage = "잘못된 GPS 좌표";

            Toast.makeText( this, errorMessage, Toast.LENGTH_LONG).show();

 

        }

 

        // Handle case where no address was found.

        if (addresses == null || addresses.size()  == 0) {

            if (errorMessage.isEmpty()) {

                errorMessage = "주소 미발견";

                Log.e(TAG, errorMessage);

            }

            Toast.makeText( this, errorMessage, Toast.LENGTH_LONG).show();

        } else {

            Address address = addresses.get(0);

            Toast.makeText( this, address.getAddressLine(0).toString(), Toast.LENGTH_LONG).show();

        }

    }

 

 

    @Override

    public void onPlacesFailure(PlacesException e) {

        Log.i("PlacesAPI", "onPlacesFailure()");

    }

 

    @Override

    public void onPlacesStart() {

        Log.i("PlacesAPI", "onPlacesStart()");

    }

 

    @Override

    public void onPlacesSuccess(final List<noman.googleplaces.Place> places) {

        Log.i("PlacesAPI", "onPlacesSuccess()");

 

        runOnUiThread(new Runnable() {

            @Override

            public void run() {

                for (noman.googleplaces.Place place : places) {

 

                    LatLng latLng = new LatLng(place.getLatitude(), place.getLongitude());

 

                    MarkerOptions markerOptions = new MarkerOptions();

                    markerOptions.position(latLng);

                    markerOptions.title(place.getName());

                    markerOptions.snippet(place.getVicinity());

                    Marker item = googleMap.addMarker(markerOptions);

                    previous_marker.add(item);

 

                }

 

                //중복 마커 제거

                HashSet<Marker> hashSet = new HashSet<Marker>();

                hashSet.addAll(previous_marker);

                previous_marker.clear();

                previous_marker.addAll(hashSet);

 

            }

        });

    }

 

    @Override

    public void onPlacesFinished() {

        Log.i("PlacesAPI", "onPlacesFinished()");

    }

}

Colored by Color Scripter

cs

 

실행 결과

 

실행하면 현재 위치가 지도에 표시되고 있습니다. 

 

장소 검색 버튼을 누르면 현재 위치 주변의 음식점 위치들이 지도에 표시됩니다.

 

음식점 위치를 표시하는 마커 하나를 선택하면 음식점 이름과 주소가 나타납니다.

장소 검색버튼을 다시 누르면 기존 마커들을 다지우고 새로 음식점 마커들을 표시합니다.

번호 제목 글쓴이 날짜 조회 수
» Google Map에 현재 위치 주변의 음식점 표시하기 황제낙엽 2017.01.23 8460
37 TTS 이용하기 (구글, 네이버, KT) file 황제낙엽 2018.11.01 1001
36 피들러(Fiddler)를 이용하여 모바일 네트웍 감시 file 황제낙엽 2020.02.24 735
35 팬(Pan), 스와이프(Swipe), 스크롤(Scroll), 플릭(Flick) file 황제낙엽 2017.09.11 630
34 cordova 플러그인을 이용하여 GPS 활성화 황제낙엽 2017.01.14 588
33 음성합성(이하 TTS)관련 사양조사 및 시장조사 file 황제낙엽 2018.11.01 419
32 [Mysql] 위도 경도를 이용해 특정 거리안에 위치(거리) 구하기 황제낙엽 2017.01.25 357
31 Google Maps Geolocation API를 이용한 현재위치 검색 file 황제낙엽 2017.01.14 343
30 위치정보(GeoLocation)에서 위도와 경도로 두 지점간 거리(distance) 구하는 오라클 Function 황제낙엽 2017.01.25 249
29 모바일웹 SMS 황제낙엽 2019.09.28 239
28 원격 데스크톱 환경을 위한 터치에 대한 제스쳐 목록 정의 황제낙엽 2018.06.12 239
27 [jQuery Mobile] List view 황제낙엽 2012.11.15 221
26 Geolocation API를 이용해 위치 정보를 알아내기 file 황제낙엽 2016.12.03 196
25 [JS] navigator geolocation 현재 접속 위치 가져오기 황제낙엽 2016.12.03 179
24 모바일 크롬에서 단축 아이콘 생성 - WebApp 만들기 file 황제낙엽 2016.12.03 165
23 PhoneGap, Accelerator Titanium, Appspresso 황제낙엽 2013.11.29 138
22 [모바일 브라우저] Android 기기 원격 디버깅 시작하기 (PC크롬에서 모바일크롬 디버깅) file 황제낙엽 2019.01.14 125
21 Galaxy Z Fold3 5G Specifications 황제낙엽 2022.03.07 101
20 [Android] / 안드로이드 / googlemap distance / 구글맵 두 위치 사이의 거리 구하기 황제낙엽 2017.01.23 97
19 안드로이드 모바일 브라우저 캐시 지우기 황제낙엽 2019.07.23 90