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

后端 未结 6 1499
醉话见心
醉话见心 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 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")
                    }
                }
            }
    

提交回复
热议问题