Skip to content

Instantly share code, notes, and snippets.

@vinaydotblog
Last active November 18, 2017 16:34
Show Gist options
  • Save vinaydotblog/34d9b2292e27f0bfee28 to your computer and use it in GitHub Desktop.
Save vinaydotblog/34d9b2292e27f0bfee28 to your computer and use it in GitHub Desktop.
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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment