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

时间:2016-05-05 13:27:33

标签: android google-places-api

在Google Places API for Android中,我使用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获取国家/地区代码? 如果不是,是否有任何替代服务来获取国家名称&键入时的代码?

2 个答案:

答案 0 :(得分:11)

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

Locale locale = place.getLocale();

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

locale.getCountry();

国家/地区名称为:

locale.getDisplayCountry();

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

编辑:

如果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();

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

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

答案 1 :(得分:0)

这将提供正确的国家/地区代码。

TelephonyManager tm = (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();