/* * 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 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].address_components; for(var i = 0; i < components.length; i++) { if( ~components[i].types.indexOf('locality') ) { location = components[i].long_name; break; } } if(location) return def.resolve(location); } return def.reject(); }) .fail(function(){ def.reject(); }); return def.promise(); }