Get city name and postal code from Google Place AP

2020-03-01 05:14发布

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?

6条回答
太酷不给撩
2楼-- · 2020-03-01 05:36

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()));
查看更多
你好瞎i
3楼-- · 2020-03-01 05:45

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楼-- · 2020-03-01 05:47

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;
 }
查看更多
贪生不怕死
5楼-- · 2020-03-01 05:48
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);
        }
    }
查看更多
够拽才男人
6楼-- · 2020-03-01 05:49
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);
        }
    }
}
查看更多
Emotional °昔
7楼-- · 2020-03-01 05:53

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")
                }
            }
        }
查看更多
登录 后发表回答