Skip to content

Instantly share code, notes, and snippets.

@nery
Created January 25, 2013 18:14

Revisions

  1. nery created this gist Jan 25, 2013.
    41 changes: 41 additions & 0 deletions jQueryGeoIp.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    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);