我正在使用Google自动完成地点API在我的应用程序中搜索地点,现在我想获取我搜索的位置的纬度和经度。如何从Google在Android中返回的自动完成地点API结果中获取纬度和经度?
我正在使用Google自动完成地点API在我的应用程序中搜索地点,现在我想获取我搜索的位置的纬度和经度。如何从Google在Android中返回的自动完成地点API结果中获取纬度和经度?
我得到了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中也会有类似的方法。
implementation("com.google.android.libraries.places:places:3.1.0")
Places.initialize(applicationContext, "YOUR_API_KEY")
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)
}
}
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();
}
});