How To Get Full Address From Passing Latitude And Latitude?
Solution 1:
There is a known issue that Geocoder doesn't always returns a value. See Geocoder doesn't always return a value and geocoder.getFromLocationName returns only null. You can try to send a request 3 times in a for loop. It should be able to return atleast once. If not then, their might be a connection issue or can be other issues like server did not reply to your request. For me sometimes it never returned anything even if it was connected to internet. Then, I used this much more reliable way to get the address everytime:
//lat, lng are Double variables containing latitude and longitude values. publicJSONObjectgetLocationInfo() {
//Http RequestHttpGet httpGet = newHttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true");
HttpClient client = newDefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = newStringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
//Create a JSON from the String that was return.JSONObject jsonObject = newJSONObject();
try {
jsonObject = newJSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
I called the function as follows to get the complete address:
JSONObject ret = getLocationInfo(); //Get the JSON that is returned from the API callJSONObject location;
String location_string;
//Parse to get the value corresponding to `formatted_address` key. try {
location = ret.getJSONArray("results").getJSONObject(0);
location_string = location.getString("formatted_address");
Log.d("test", "formattted address:" + location_string);
} catch (JSONException e1) {
e1.printStackTrace();
}
You can call this inside AsyncTask
or a new thread. I used Asynctask
for the same.
Hope this helps.This worked for me. If you replace the URL with the lat and longitude coordinates and see the returned JSON object in a web browser. You'll see what just happened.
Post a Comment for "How To Get Full Address From Passing Latitude And Latitude?"