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

后端 未结 6 1457
醉话见心
醉话见心 2021-01-01 16:21

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 info

相关标签:
6条回答
  • 2021-01-01 16:47
    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);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-01 16:48

    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;
     }
    
    0 讨论(0)
  • 2021-01-01 16:49
    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);
            }
        }
    
    0 讨论(0)
  • 2021-01-01 16:59

    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/).

    0 讨论(0)
  • 2021-01-01 17:07

    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")
                    }
                }
            }
    
    0 讨论(0)
  • 2021-01-01 17:10

    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()));
    
    0 讨论(0)
提交回复
热议问题