通过自动完成地点API返回的place_id获取纬度和经度

56

我正在使用Google自动完成地点API在我的应用程序中搜索地点,现在我想获取我搜索的位置的纬度和经度。如何从Google在Android中返回的自动完成地点API结果中获取纬度和经度?


使用Geocoder。请参考:http://developer.android.com/reference/android/location/Geocoder.html - shyam
当前API不允许像Web API那样使用一个请求完成此操作。请点赞 https://issuetracker.google.com/issues/35828699,以请求在预测响应中公开坐标。 - AlexKorovyansky
这是正确的解决方案 https://stackoverflow.com/a/70751725/6236752 - Nouman Ch
13个回答

0

我得到了Muhammad Yasir的答案,解决了这个问题,非常简单。

    List<Place.Field> placeFields = Arrays.asList(Place.Field.LAT_LNG, Place.Field.ADDRESS_COMPONENTS);
    autocompleteFragment.setPlaceFields(placeFields);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            LatLng latLng = place.getLatLng(); // This will have required latitude and longitude
         }
   }

您可以像名称、地址等列表中一样指定任何字段。

注意:这个答案是针对Android Java的,但我认为在其他语言如JavaScript中也会有类似的方法。


0
使用Google Places API
implementation("com.google.android.libraries.places:places:3.1.0")

在应用程序的文件中的onCreate()函数中进行初始化。
Places.initialize(applicationContext, "YOUR_API_KEY")

然后调用函数通过placeId获取LatLng。
val client = Places.createClient(androidContext())

suspend fun getPlaceCoordinatesById(placeId: String): LatLng? = suspendCoroutine { continuation ->
    placesClient.fetchPlace(
        FetchPlaceRequest.newInstance(placeId, listOf(Place.Field.LAT_LNG))
    ).addOnSuccessListener {
        continuation.resume(it.place.latLng)
    }.addOnFailureListener {
        Log.e(this.toString(), it.stackTraceToString())
        continuation.resume(null)
    }
}

-1
Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId)
  .setResultCallback(new ResultCallback < PlaceBuffer > () {
    @Override
    public void onResult(PlaceBuffer places) {
      if (places.getStatus().isSuccess() && places.getCount() > 0) {
        final Place myPlace = places.get(0);
        Log.i(TAG, "Place found: " + myPlace.getName());
        LatLng latlangObj = myPlace.getLatLng();
        Log.v("latitude:", "" + latlangObj.latitude);
        Log.v("longitude:", "" + latlangObj.longitude);
      } else {
        Log.e(TAG, "Place not found");
      }
      places.release();
    }
  });

使用此方法从placeid获取lat和lang。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接