【问题标题】:Get city name and postal code from Google Place API on Android从 Android 上的 Google Place API 获取城市名称和邮政编码
【发布时间】:2015-06-29 08:33:21
【问题描述】:

我正在使用带有自动完成功能的 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 类不包含该信息。我可以获得完整的人类可读地址、经纬度等。

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

【问题讨论】:

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


    【解决方案1】:

    您通常无法从 Place 中检索城市名称,
    但是您可以通过这种方式轻松获得它:
    1) 从你的地方获取坐标(或者你得到它们);
    2) 使用地理编码器按坐标检索城市。
    可以这样做:

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

    【讨论】:

    • ...必须添加一个 try 和 catch 块来处理 IOException 否则它将无法编译。
    • 它将编译。仔细检查方法声明
    【解决方案2】:

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

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

    【讨论】:

    • 请注意 - 这种技术可能会在某些地方引起问题 - 我特别在纽约的一些地址遇到了这个问题 - 史泰登岛、布鲁克林和布朗克斯,以及克利夫顿公园的地址使用“sublocality” "、"administrative_area_level_3" 或其他类型,而不是地址中使用的正确“城市”名称的“locality”
    【解决方案3】:

    很遗憾,目前无法通过 Android API 获得此信息。

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

    【讨论】:

    • 是的,我最终分两步完成(第二步是调用 Web 服务)。太奇怪了,没有这些信息,也没有办法检索它!
    【解决方案4】:
    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);
            }
        }
    }
    

    【讨论】:

    • 欢迎@AmitSharma
    【解决方案5】:

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

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

    【讨论】:

    猜你喜欢
    • 2012-05-07
    • 1970-01-01
    • 2020-10-08
    • 2013-04-05
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    相关资源
    最近更新 更多