从 PlaceAutocompleteFragment android (Google Places API) 获取国家/地区代码

2023-12-31

在 Android 版 Google Places API 中,我使用 PlaceAutocompleteFragment 来显示城市/国家。
这里正在获取地址、名称、placeId 等。
Place对象仅包含这些字段。

@Override
public void onPlaceSelected(Place place) {

    Log.i(TAG, "Place Selected: " + place.getName());

    // Format the returned place's details and display them in the TextView.
    mPlaceDetailsText.setText(formatPlaceDetails(getResources(), place.getName(), place.getId(),
            place.getAddress(), place.getPhoneNumber()+" "+place.getAttributions()+" :: "+place.getLocale(), place.getWebsiteUri()));

}

但我也想要国家代码。有没有办法从地方 API 获取国家代码? 如果没有,是否有任何替代服务可以在键入时获取国家/地区名称和代码?


通过检索 Place 对象,您可以获得关联的 Locale 对象:

Locale locale = place.getLocale();

使用此 Locale 对象,您可以通过以下方式获取国家/地区代码:

locale.getCountry();

以及国家名称:

locale.getDisplayCountry();

您可以在文档中查看更多可用的方法:http://developer.android.com/reference/java/util/Locale.html http://developer.android.com/reference/java/util/Locale.html

EDIT :

如果 Place 对象中的 Locale 为 null,您可以使用 Geocoder 从 GPS 坐标获取信息:

LatLng coordinates = place.getLatLng(); // Get the coordinates from your place
Geocoder geocoder = new Geocoder(this, Locale.getDefault());

List<Address> addresses = geocoder.getFromLocation(
                coordinates.latitude,
                coordinates.longitude,
                1); // Only retrieve 1 address
Address address = addresses.get(0);

然后你就可以调用这些方法来获取你想要的信息

address.getCountryCode();
address.getCountryName();

Address 对象的更多方法:http://developer.android.com/reference/android/location/Address.html http://developer.android.com/reference/android/location/Address.html

请注意,应在后台线程上调用地理编码器方法,以免阻塞 UI,并且也可能无法检索到答案。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 PlaceAutocompleteFragment android (Google Places API) 获取国家/地区代码 的相关文章