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:
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;
}
})
});
});
}
});
For what it's worth, I was looking for something similar and am trying https://plus.codes/
If you strip the encoded bit it yields a fairly consistent city, state, country name:
const extractCityName = latlng => {
googleMapsClient.reverseGeocode({ latlng }, (err, response) => {
if (!err) {
return response.json.plus_code.compound_code.split(' ').slice(1).join(' ');
}
});
};
// examples:
console.log(extractCityName(40.6599718,-73.9817292));
// New York, NY, USA
console.log(extractCityName(37.386052, -122.083851));
// Mountain View, CA, USA
console.log(extractCityName(51.507351, -0.127758));
// Westminster, London, UK
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:
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" ]
}