可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答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
See this result, looks like you want the entry with both the 'locality' and the 'political' types:
{ "long_name" : "Mumbai", "short_name" : "Mumbai", "types" : [ "locality", "political" ] }
回答2:
So I was trying to figure this out today and I came to this solution if it helps anyone. Google maps comes with the Geocoder built in now so you just create a geocoder object once the API has loaded.
You can easily wrap that in a function and just return an object with the city, state, and postal code. This site was helpful in allowing me to see what the different 'types' mean: Reverse Geocoding
var geocoder = new google.maps.Geocoder, latitude = 28.54, //sub in your latitude longitude = -81.39, //sub in your longitude postal_code, city, state; geocoder.geocode({'location': {lat:latitude, lng:longitude}}, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { results.forEach(function(element){ element.address_components.forEach(function(element2){ element2.types.forEach(function(element3){ switch(element3){ case 'postal_code': postal_code = element2.long_name; break; case 'administrative_area_level_1': state = element2.long_name; break; case 'locality': city = element2.long_name; break; } }) }); }); } });