问题
I'm trying to get latitude and longitude of specific addresses using addressList = geoCoder.getFromLocationName(locationName, 1);
For most addresses this works just fine, but there are some valid addresses, like "Lentoasemantie 1, Vantaa", which returns empty array. The strange thing is that the valid addresses used to work 4 days ago, but not anymore while most of the addresses continue to work.
So, this looks like Google backend problem and I'm wondering should I report this to Google (where / how?) or switch away from using Geocoder, because it's inherently unreliable?
回答1:
Geocoder Android API is not as efficient as the Google Maps Geocoding API so I suggest you to use this one instead of Geocoder. You can find below the function to get location from address through Volley queue (For Lentoasemantie 1, Vantaa, it works) :
public void getLocationFromAddress(String address) {
String url = "https://maps.googleapis.com/maps/api/geocode/json?address="
+ Uri.encode(address) + "&sensor=true&key=API_KEY";
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest stateReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
JSONObject location;
try {
// Get JSON Array called "results" and then get the 0th
// complete object as JSON
location = response.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
// Get the value of the attribute whose name is
// "formatted_string"
if (location.getDouble("lat") != 0 && location.getDouble("lng") != 0) {
LatLng latLng = new LatLng(location.getDouble("lat"), location.getDouble("lng"));
//Do what you want
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
});
// add it to the queue
queue.add(stateReq);
}
来源:https://stackoverflow.com/questions/39063590/android-geocoder-getfromlocationname-fails-with-valid-address