현재 장소

플랫폼 선택: Android iOS

Android용 Places SDK를 사용하면 현재 보고된 기기에서 장소를 찾을 수 있습니다. 장소의 예로는 지역 비즈니스, 관심 장소, 지리적 위치가 있습니다.

권한

라이브러리가 사용하는 모든 권한을 매니페스트에서 선언하므로 라이브러리를 사용하기 위해 앱의 매니페스트에서 추가 권한을 선언할 필요가 없습니다. 그러나 앱에서 PlacesClient.findCurrentPlace()를 사용한다면 런타임에 위치 정보 액세스 권한을 요청해야 합니다.

앱에서 PlacesClient.findCurrentPlace()를 사용하지 않는다면 매니페스트에 다음을 추가하여 라이브러리에서 도입한 ACCESS_FINE_LOCATIONACCESS_COARSE_LOCATION 권한을 명시적으로 삭제합니다.

<manifest ... xmlns:tools="http://schemas.android.com/tools">
    ...
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" tools:node="remove"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" tools:node="remove"/>
    ...
</manifest>

권한에 관해 자세히 알아보고 EasyPermissions를 사용해 시작해 보세요.

현재 위치 가져오기

현재 기기가 있는 지역 비즈니스 또는 기타 장소를 찾으려면 다음 단계를 따르세요.

  1. ContextCompat.checkSelfPermission를 호출하여 사용자가 기기 위치에 액세스할 수 있는 권한을 부여했는지 확인합니다. 앱에는 사용자에게 권한을 요청하고 결과를 처리하는 코드도 포함되어야 합니다. 자세한 내용은 앱 권한 요청을 참조하세요.
  2. FindCurrentPlaceRequest를 만들고 Place.FieldList를 전달하고 앱에서 요청해야 하는 장소 데이터 유형을 지정합니다.
  3. PlacesClient.findCurrentPlace()를 호출하여 이전 단계에서 만든 FindCurrentPlaceRequest를 전달합니다.
  4. FindCurrentPlaceResponse에서 PlaceLikelihood 목록을 가져옵니다.

필드는 장소 검색 결과에 해당하며 기본, 연락처, 분위기 등 세 결제 카테고리로 분류됩니다. 기본 필드에는 기본 요율로 청구되며 추가 요금이 발생하지 않습니다. 연락처 및 분위기 필드에는 더 높은 요율로 청구됩니다. 장소 데이터 요청에 대해 요금이 청구되는 방법에 대한 자세한 내용은 사용량 및 결제를 참고하세요.

이 API는 TaskFindCurrentPlaceResponse를 반환합니다. FindCurrentPlaceResponse에는 기기가 있을 만한 장소를 나타내는 PlaceLikelihood 객체의 목록이 포함됩니다. 각 장소의 결과에는 해당 장소가 올바른 장소일 가능성의 표시가 포함됩니다. 지정된 기기 위치에 해당하는 알려진 장소가 없으면 목록이 비어 있을 수 있습니다.

PlaceLikelihood.getPlace()를 호출하여 Place 객체를 가져오고 PlaceLikelihood.getLikelihood()를 호출하여 장소의 일치 가능성 평점을 가져올 수 있습니다. 값이 클수록 장소가 가장 잘 일치할 확률이 높습니다.

다음 코드 샘플은 기기가 있을 가능성이 높은 장소의 목록을 검색하고 각 장소의 이름과 유사도를 기록합니다.

Kotlin



// Use fields to define the data types to return.
val placeFields: List<Place.Field> = listOf(Place.Field.NAME)

// Use the builder to create a FindCurrentPlaceRequest.
val request: FindCurrentPlaceRequest = FindCurrentPlaceRequest.newInstance(placeFields)

// Call findCurrentPlace and handle the response (first check that the user has granted permission).
if (ContextCompat.checkSelfPermission(this, permission.ACCESS_FINE_LOCATION) ==
    PackageManager.PERMISSION_GRANTED) {

    val placeResponse = placesClient.findCurrentPlace(request)
    placeResponse.addOnCompleteListener { task ->
        if (task.isSuccessful) {
            val response = task.result
            for (placeLikelihood: PlaceLikelihood in response?.placeLikelihoods ?: emptyList()) {
                Log.i(
                    TAG,
                    "Place '${placeLikelihood.place.name}' has likelihood: ${placeLikelihood.likelihood}"
                )
            }
        } else {
            val exception = task.exception
            if (exception is ApiException) {
                Log.e(TAG, "Place not found: ${exception.statusCode}")
            }
        }
    }
} else {
    // A local method to request required permissions;
    // See https://developer.android.com/training/permissions/requesting
    getLocationPermission()
}

      

Java


// Use fields to define the data types to return.
List<Place.Field> placeFields = Collections.singletonList(Place.Field.NAME);

// Use the builder to create a FindCurrentPlaceRequest.
FindCurrentPlaceRequest request = FindCurrentPlaceRequest.newInstance(placeFields);

// Call findCurrentPlace and handle the response (first check that the user has granted permission).
if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    Task<FindCurrentPlaceResponse> placeResponse = placesClient.findCurrentPlace(request);
    placeResponse.addOnCompleteListener(task -> {
        if (task.isSuccessful()){
            FindCurrentPlaceResponse response = task.getResult();
            for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) {
                Log.i(TAG, String.format("Place '%s' has likelihood: %f",
                    placeLikelihood.getPlace().getName(),
                    placeLikelihood.getLikelihood()));
            }
        } else {
            Exception exception = task.getException();
            if (exception instanceof ApiException) {
                ApiException apiException = (ApiException) exception;
                Log.e(TAG, "Place not found: " + apiException.getStatusCode());
            }
        }
    });
} else {
    // A local method to request required permissions;
    // See https://developer.android.com/training/permissions/requesting
    getLocationPermission();
}

      

유사도 값에 대한 유의 사항:

  • 가능성은 단일 요청에 대해 반환된 장소 목록 내에서 장소가 최적 일치가 될 상대적인 확률을 제공합니다. 여러 요청에서 가능성을 비교할 수는 없습니다.
  • 가능성 값은 0.0과 1.0 사이입니다.

예를 들어 올바른 장소가 Place A일 가능성 55% 와 Place B인 35% 유사도를 나타내려면 응답에 2개의 멤버가 포함됩니다. 즉, 유사도가 0.55인 Place A와 유사도가 0.35인 Place B입니다.

앱에 특성 표시

앱이 PlacesClient.findCurrentPlace()에서 획득한 정보를 표시할 때 저작자 표시도 표시해야 합니다. 저작자 표시에 관한 문서를 참고하세요.