Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  175] [ 5]  / answers: 1 / hits: 9178  / 10 Years ago, wed, december 17, 2014, 12:00:00

Using the Google Maps Geocoding API, i'm able to get the formatted address for a particular coordinate. To get the exact city name, I'm doing the following:



$.ajax({
url: 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=false',
success: function(data){
var formatted = data.results;
var address_array = formatted[6].formatted_address.split(',');
var city = address_array[0];
}
});


where lat and long are derived using the browser coordinates. My problem is the following:



From coordinates 19.2100 and 72.1800, I get the city as Mumbai, but from a similar set of coordinates about 3Km away, I get city as Mumbai Suburban. How can I get Mumbai without changing the success function of my code? It seems to me that the result array doesn't always stick to the same format which creates problems in my displaying of the city name.


More From » google-maps

 Answers
1

You need to look at the type of the result, not the absolute index in the array of results. Iterate through the results array looking for the entry which has the appropriate type. Looks like that would be:




  • locality indicates an incorporated city or town political entity



But data may vary with region.



related question: Grabbing country from google geocode jquery



Looks like you want the entry with both the 'locality' and the 'political' types:



{
long_name : Mumbai,
short_name : Mumbai,
types : [ locality, political ]
}

[#40575] Tuesday, December 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;