본문 바로가기

캡스톤

Google Places API로 주변 카페 탐색

https://webnautes.tistory.com/1080

 

Places API Web Service를 사용하여 Android Google Map에 현재 위치 주변의 음식점 표시하기

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

webnautes.tistory.com

이 블로그를 참고하였습니다.

 

 

앞선 두 포스팅을 이어서 해야합니다.

 

 

첫번째로 Places API Web Service 키를 얻어야 합니다.

맨 처음 포스팅이였던 Google Developers Console 사이트에서 생성했던 프로젝트를 선택합니다.

 

https://console.developers.google.com/apis/dashboard?folder=&organizationId=&project=map-test-273913

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com

 

Places API를 추가 해줍니다.

 

 

activity_main.xml에 버튼을 추가하고 지도와 버튼을 조정합니다.

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
<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/layout_main"
    android:orientation="vertical"
    tools:context=".MainActivity" >
 
    <fragment
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.8"
        android:id="@+id/map"
        tools:context=".MapsActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment" />
 
    <Button
        android:text="장소검색"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.2"
        android:id="@+id/button"/>
 
</LinearLayout>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

build.gradle파일에서 minSdkVersion15 이상으로 사용해야합니다.

1
        minSdkVersion 21

 

Android-Google-Places-API 라이브러리를 추가해줍니다.

1
    implementation 'noman.placesapi:placesAPI:1.1.3'

 

MainActivity에서 PlacesListener 인터페이스를 구현해줍니다.

1
2
3
4
5
public class MainActivity extends AppCompatActivity
        implements 
        OnMapReadyCallback, 
        ActivityCompat.OnRequestPermissionsResultCallback, 
        PlacesListener{
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

밑에도 추가해 줍니다.

1
2
3
import noman.googleplaces.PlacesException;
import noman.googleplaces.PlacesListener;

 

다음 4개 메소드를 추가해줍니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Override
public void onPlacesFailure(PlacesException e) {
    
}
 
@Override
public void onPlacesStart() {
 
}
 
@Override
public void onPlacesSuccess(List<Place> places) {
 
}
 
@Override
public void onPlacesFinished() {
 
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

변수를 추가해 줍니다.

1
List<Marker> previous_marker = null;

 

onPlacesSuccess 메소드의 파라미터 타입에 final을 추가해주고 다음 코드를 입력합니다.

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
@Override
public void onPlacesSuccess(final List<Place> places) {
 
       runOnUiThread(new Runnable() {
            @Override
            public void run() {
                for (noman.googleplaces.Place place : places) {
 
                    LatLng latLng
                            = new LatLng(place.getLatitude()
                            , place.getLongitude());
 
                    String markerSnippet = getCurrentAddress(latLng);
 
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(latLng);
                    markerOptions.title(place.getName());
                    markerOptions.snippet(markerSnippet);
                    Marker item = mMap.addMarker(markerOptions);
                    previous_marker.add(item);
 
                }
 
                //중복 마커 제거
                HashSet<Marker> hashSet = new HashSet<Marker>();
                hashSet.addAll(previous_marker);
                previous_marker.clear();
                previous_marker.addAll(hashSet);
 
            }
        });
 
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

showPlaceInformation() 메소드를 추가해줍니다. 

 "Places API Web Service 키" 부분에 따로 복사해둔 키를 입력합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void showPlaceInformation(LatLng location)
{
    mMap.clear();//지도 클리어
 
    if (previous_marker != null)
        previous_marker.clear();//지역정보 마커 클리어
 
    new NRPlaces.Builder()
            .listener(MainActivity.this)
            .key("Places API Web Service 키")
            .latlng(location.latitude, location.longitude)//현재 위치
            .radius(500//500 미터 내에서 검색
            .type(PlaceType.RESTAURANT) //음식점
            .build()
            .execute();
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

onCreate 메소드에  ArrayList 초기화와 버튼 클릭시 showPlaceInformation() 메소드를 호출하는 코드를 추가합니다.

1
2
3
4
5
6
7
8
9
10
 
previous_marker = new ArrayList<Marker>();
 
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        showPlaceInformation(currentPosition);
    }
});
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

결과입니다.

 

 

참고로 카페 말고도 다른 장소 탐색도 가능합니다.

https://developers.google.com/places/web-service/supported_types?hl=ko

 

Place Types  |  Places API  |  Google Developers

This page lists the supported values for the types property. Table 1 lists the types that are supported for place searches, and can be returned with Place details results, and as part of autocomplete place predictions. Table 2 lists additional types that c

developers.google.com

 

이 포스팅을 끝으로 지도 기능을 마치겠습니다.