Skip to content

Instantly share code, notes, and snippets.

@nery
Created January 25, 2013 18:14
Show Gist options
  • Save nery/4636602 to your computer and use it in GitHub Desktop.
Save nery/4636602 to your computer and use it in GitHub Desktop.
A ajax call to get a postal code from a geo location
var getLocation = function() {
if (navigator.geolocation) {
//get current position and pass the results to getPostalCode
return navigator.geolocation.getCurrentPosition();
} else {
return false;
}
};
var getPostalCode = function(position) {
$.ajax({
type: "POST",
url: 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&sensor=true',
dataType: "json",
beforeSend: function(){
// do something before the request such as show a loading image
},
error: function(err){
// handle errors
},
success: function(data) {
var addresses = data.results; // cache results in a local var
$.each(addresses, function(i){ // iterate through to find a postal code
if(this.types[0]=="postal_code"){ // check that the type is a postal code
var postal=this['address_components'][0]['long_name']; // grab postal string
if(postal.length > 3){ // is the result is more then 3 letter shorthand use it
// do something with your result and then lets break the iteration
console.log(postal);
return false;
}
}
});
} // end success
}); // end ajax
};
var geo = getLocation();
getPostalCode(geo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment