在Android中,如何使用纬度和经度获取用户的邮政编码?

时间:2016-06-02 04:38:16

标签: android google-maps geolocation

我正在构建一个应用程序,在获得纬度和经度后需要访问用户的邮政编码。如何使用lat和lng获取zip?

2 个答案:

答案 0 :(得分:3)

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());

addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

String address = addresses.get(0).getAddressLine(0); // 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();
String knownName = addresses.get(0).getFeatureName();

官方文档:https://developer.android.com/reference/android/location/Address.html

https://developer.android.com/training/location/display-address.html

答案 1 :(得分:0)

除了原生Geocoder类,您还可以使用Geocoding API Web服务。 Web服务具有反向地理编码功能:

https://developers.google.com/maps/documentation/geocoding/intro?hl=en#ReverseGeocoding

因此,您可以指定要返回的纬度,经度和结果类型。

在您的用例中,它应该类似于:

https://maps.googleapis.com/maps/api/geocode/json?latlng=37.8959524%2C-80.349527&result_type=postal_code&key=YOUR_API_KEY

在Android中,您可以使用AndroidHttpClient类来执行HTTP请求:

https://developer.android.com/reference/android/net/http/AndroidHttpClient.html