Get a specific city name on Google maps reverse geocoding

Using the Google Maps geocoding API, I can get a formatted address for a specific coordinate. To get the exact name of the city, I do 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 latthey longare displayed using browser coordinates. My problem is this:

From the coordinates 19.2100and 72.1800, I get the city as Mumbai, but from a similar set of coordinates of about 3 km, I get the city as Mumbai Suburban. How can I get Mumbaiwithout changing the success function of my code? It seems to me that the array of results does not always adhere to the same format, which creates problems when displaying the name of the city.

+4
3

, . , , . , :

.

: Google Geocode JQuery

, "" "":

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

, , , - . Google Geocoder, API.

, . , "":

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;
          }
        })
      });
    });
  }
});
+3

For what it's worth, I was looking for something similar and trying https://plus.codes/

If you delete the encoded bit, this gives a pretty consistent name for the city, state, country:

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
0
source

All Articles