Get city name and postal code from Google Place API on Android

梦想的初衷 提交于 2019-12-30 05:53:09

问题


I'm using Google Place API for Android with autocomplete

Everything works fine, but when I get the result as shown here, I don't have the city and postal code information.

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

The Place class doesn't contain that information. I can get the full human readable address, the lat and long, etc.

How can I get the city and postal code from the autocomplete result?


回答1:


You can not normally retrieve city name from the Place,
but you can easily get it in this way:
1) Get coordinates from your Place (or however you get them);
2) Use Geocoder to retrieve city by coordinates.
It can be done like this:

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



回答2:


City name and postal code can be retrieved in 2 steps

1) Making a web-service call to https://maps.googleapis.com/maps/api/place/autocomplete/json?key=API_KEY&input=your_inpur_char. The JSON contains the place_id field which can be used in step 2.

2) Make another web-service call to https://maps.googleapis.com/maps/api/place/details/json?key=API_KEY&placeid=place_id_retrieved_in_step_1. This will return a JSON which contains address_components. Looping through the types to find locality and postal_code can give you the city name and postal code.

Code to achieve it

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")
                }
            }
        }



回答3:


Unfortunately this information isn't available via the Android API at this time.

It is available using the Places API Web Service (https://developers.google.com/places/webservice/).




回答4:


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

//......

private void getPlaceInfo(double lat, double lon) throws IOException {
        List<Address> addresses = mGeocoder.getFromLocation(lat, lon, 1);
        if (addresses.get(0).getPostalCode() != null) {
            String ZIP = addresses.get(0).getPostalCode();
            Log.d("ZIP CODE",ZIP);
        }

        if (addresses.get(0).getLocality() != null) {
            String city = addresses.get(0).getLocality();
            Log.d("CITY",city);
        }

        if (addresses.get(0).getAdminArea() != null) {
            String state = addresses.get(0).getAdminArea();
            Log.d("STATE",state);
        }

        if (addresses.get(0).getCountryName() != null) {
            String country = addresses.get(0).getCountryName();
            Log.d("COUNTRY",country);
        }
    }



回答5:


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



回答6:


Not the best way, but the following can be useful:

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


来源:https://stackoverflow.com/questions/29784783/get-city-name-and-postal-code-from-google-place-api-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!