vinnizworld
2/21/2016 - 11:42 AM

Gives back City Name based on given latitude/longitude values.

Gives back City Name based on given latitude/longitude values.

/*
 * Pass it your string of latlong and it'll return a promise to come back with the locality, city.
 * 
 * getCity('12.9715987,77.5945627').done(function(cityName){
 *  $elem.val( cityName )
 * });
 *
 * Info: jQuery is required for $.Deferred() and $.getJSON to work!
 * Regardless of everything modify it as per your convenience :)
 */

function getCity(latlng) {
    var $ = jQuery;
    var def = $.Deferred();

    $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latlng)
      .done(function(data){
        var location;
        if( data.results && data.results.length ) {
            var components = data.results[0];
            if( components.formatted_address ) {
                location = components.formatted_address;
                return def.resolve(location);
            }
        }

        return def.reject();
    })
    .fail(function(){
        def.reject();
    });

    return def.promise();
}