Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get definite City name in Google maps reverse geocoding

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.

like image 749
Newtt Avatar asked Dec 17 '14 11:12

Newtt


1 Answers

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;
          }
        })
      });
    });
  }
});
like image 65
HaulinOats Avatar answered Sep 21 '22 01:09

HaulinOats