从Android上的Google Place API获取城市名称和邮政编码

时间:2015-04-21 23:08:33

标签: android google-places-api postal-code city

我正在使用Google Place API for Android自动填充功能

一切正常,但当我得到here所示的结果时,我没有城市和邮政编码信息。

    private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
        = new ResultCallback<PlaceBuffer>() {
    @Override
    public void onResult(PlaceBuffer places) {
        if (!places.getStatus().isSuccess()) {
            // Request did not complete successfully
            Log.e(TAG, "Place query did not complete. Error: " + places.getStatus().toString());

            return;
        }
        // Get the Place object from the buffer.
        final Place place = places.get(0);

        // Format details of the place for display and show it in a TextView.
        mPlaceDetailsText.setText(formatPlaceDetails(getResources(), place.getName(),
                place.getId(), place.getAddress(), place.getPhoneNumber(),
                place.getWebsiteUri()));

        Log.i(TAG, "Place details received: " + place.getName());
    }
};

Place类不包含该信息。我可以获得完整的人类可读地址,lat和long等。

如何从自动填充结果中获取城市和邮政编码?

6 个答案:

答案 0 :(得分:26)

您无法正常从地点检索城市名称,
但你可以很容易地用这种方式得到它:
1)从你的地方获取坐标(或者你得到它们);
2)使用Geocoder按坐标检索城市 可以这样做:

private Geocoder mGeocoder = new Geocoder(getActivity(), Locale.getDefault());

// ... 

 private String getCityNameByCoordinates(double lat, double lon) throws IOException {

     List<Address> addresses = mGeocoder.getFromLocation(lat, lon, 1);
     if (addresses != null && addresses.size() > 0) {
         return addresses.get(0).getLocality();
     }
     return null;
 }

答案 1 :(得分:15)

可以分两步检索城市名称和邮政编码

1)对https://maps.googleapis.com/maps/api/place/autocomplete/json?key=API_KEY&input=your_inpur_char进行网络服务呼叫。 JSON包含可在步骤2中使用的place_id字段。

2)再次拨打https://maps.googleapis.com/maps/api/place/details/json?key=API_KEY&placeid=place_id_retrieved_in_step_1的网络服务电话。这将返回包含address_components的JSON。循环遍历types以查找localitypostal_code可以为您提供城市名称和邮政编码。

实现它的代码

JSONArray addressComponents = jsonObj.getJSONObject("result").getJSONArray("address_components");
        for(int i = 0; i < addressComponents.length(); i++) {
            JSONArray typesArray = addressComponents.getJSONObject(i).getJSONArray("types");
            for (int j = 0; j < typesArray.length(); j++) {
                if (typesArray.get(j).toString().equalsIgnoreCase("postal_code")) {
                    postalCode = addressComponents.getJSONObject(i).getString("long_name");
                }
                if (typesArray.get(j).toString().equalsIgnoreCase("locality")) {
                    city = addressComponents.getJSONObject(i).getString("long_name")
                }
            }
        }

答案 2 :(得分:9)

很遗憾,此时此信息无法通过Android API提供。

可以使用Places API网络服务(https://developers.google.com/places/webservice/)。

答案 3 :(得分:2)

<button>

// ......

try{
    getPlaceInfo(place.getLatLng().latitude,place.getLatLng().longitude);
catch (Exception e){
    e.printStackTrace();
}

答案 4 :(得分:1)

private Geocoder geocoder;
private final int REQUEST_PLACE_ADDRESS = 40;

onCreate

Places.initialize(context, getString(R.string.google_api_key));

Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, Arrays.asList(Place.Field.ADDRESS_COMPONENTS, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG)).build(context);
startActivityForResult(intent, REQUEST_PLACE_ADDRESS);

onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_PLACE_ADDRESS && resultCode == Activity.RESULT_OK) {
        Place place = Autocomplete.getPlaceFromIntent(data);
        Log.e("Data",Place_Data: Name: " + place.getName() + "\tLatLng: " + place.getLatLng() + "\tAddress: " + place.getAddress() + "\tAddress Component: " + place.getAddressComponents());

        try {
            List<Address> addresses;
            geocoder = new Geocoder(context, Locale.getDefault());

            try {
                addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
                String address1 = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                String address2 = addresses.get(0).getAddressLine(1); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                String city = addresses.get(0).getLocality();
                String state = addresses.get(0).getAdminArea();
                String country = addresses.get(0).getCountryName();
                String postalCode = addresses.get(0).getPostalCode();

                Log.e("Address1: ", "" + address1);
                Log.e("Address2: ", "" + address2);
                Log.e("AddressCity: ", "" + city);
                Log.e("AddressState: ", "" + state);
                Log.e("AddressCountry: ", "" + country);
                Log.e("AddressPostal: ", "" + postalCode);
                Log.e("AddressLatitude: ", "" + place.getLatLng().latitude);
                Log.e("AddressLongitude: ", "" + place.getLatLng().longitude);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //setMarker(latLng);
        }
    }
}

答案 5 :(得分:-2)

不是最好的方法,但以下内容可能很有用:

 Log.i(TAG, "Place city and postal code: " + place.getAddress().subSequence(place.getName().length(),place.getAddress().length()));