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

Ano*_*n G 3 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()));
Run Code Online (Sandbox Code Playgroud)

}

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

Gau*_*ier 11

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

Locale locale = place.getLocale();
Run Code Online (Sandbox Code Playgroud)

使用此Locale对象,您可以通过以下方式获取Country代码:

locale.getCountry();
Run Code Online (Sandbox Code Playgroud)

和国家名称:

locale.getDisplayCountry();
Run Code Online (Sandbox Code Playgroud)

您可以在文档中查找更多可用的方法: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);
Run Code Online (Sandbox Code Playgroud)

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

address.getCountryCode();
address.getCountryName();
Run Code Online (Sandbox Code Playgroud)

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

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