从PlaceAutocompleteFragment android(Google Places API)获取国家/地区代码 [英] Get country code from PlaceAutocompleteFragment android (Google Places API)

查看:233
本文介绍了从PlaceAutocompleteFragment android(Google Places API)获取国家/地区代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Google Places API for Android, I am using PlaceAutocompleteFragment for displaying the city/country.
Here am getting the address, name, placeId, etc.
Place object contains only these fields.

@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获取国家代码吗? 如果否,是否还有其他服务来获取国家/地区名称&键入时输入代码?

But I want country code also. Is there any way to get the country code from places API ? If no, Is there any alternate service for getting the country name & code while typing ?

推荐答案

检索Place对象后,您可以获取与Locale相关的对象:

With the Place object retrieved, you can get the Locale object associated :

Locale locale = place.getLocale();

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

With this Locale object you can then get the Country code via :

locale.getCountry();

国家名称:

locale.getDisplayCountry();

您可以在docs上找到更多可用的方法: http://developer.android.com/reference/java/util/Locale.html

You can look to more available methods at the docs : http://developer.android.com/reference/java/util/Locale.html

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

If Locale from the Place object is null you can use a Geocoder to get information from GPS coordinates :

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);

然后,您可以调用这些方法来获取所需的信息

Then you can call these methods to get the informations you want

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

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

More methods on the Address objects : http://developer.android.com/reference/android/location/Address.html

请注意,应该在后台线程上调用Geocoder方法,以免阻塞UI,并且它也可能无法获取答案.

Be aware that the Geocoder methods should be call on a background thread to not block the UI and that it could also retrieve no answer.

这篇关于从PlaceAutocompleteFragment android(Google Places API)获取国家/地区代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆