현재 장소

플랫폼 선택: 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 사이입니다.

예를 들어 올바른 장소가 장소 A일 확률이 55% 이고 정확한 장소가 장소 B일 확률이 35% 임을 나타내면 응답에는 유사도가 0.55인 장소 A와 유사도가 0.35인 장소 B라는 두 멤버가 있습니다.

앱에 특성 표시

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