android - 从 PlaceAutocompleteFragment android (Google Places API) 获取国家代码

标签 android google-places-api

在适用于 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()));

}

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

最佳答案

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

Locale locale = place.getLocale();

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

locale.getCountry();

国家名称:

locale.getDisplayCountry();

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

编辑:

如果 Place 对象的 Locale 为空,您可以使用 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();

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

请注意,应在后台线程上调用 Geocoder 方法以不阻塞 UI,并且它也可能检索不到任何答案。

关于android - 从 PlaceAutocompleteFragment android (Google Places API) 获取国家代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37051900/

相关文章:

android - 检测用户何时将数据输入 edittext 立即显示答案

java - 致命异常 : main (School Project)

java - 如何减小我的 Android 应用程序的大小?

google-maps - Google API 上的 Google API 配额自动完成

google-maps - 如何使用 Google Places API 搜索特定类型的地点?

Android应用程序实现谷歌自动完成2个输入的 Activity

google-maps - 获取特定地址组件的 place_id

android - 为 Android XML 文件设置默认编辑器

google-places-api - Google Places Search - Next Page Token 返回相同的结果

java - 应用内购买 - 如何处理第二次点击?