Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the zipcode of a user using AngularJS

I need to populate some data based on the zipcode of the user visiting the site.

Could somebody tell me how to retrieve the zipcode of the location of that user?

I am using AngularJS on my app.

like image 333
skip Avatar asked Aug 18 '14 00:08

skip


1 Answers

OK. It is a bit involved, but here is how I would do it, if I were you.

First, you would use the geolocation API as follows:

window.navigator.geolocation.getCurrentPosition(function(pos){
    console.log(pos);
});

Inside your callback, you will get a position object. It looks like this:

{
  "timestamp":1408324851386,
  "coords"{
    "speed":null,
    "heading":null,
    "altitudeAccuracy":null,
    "accuracy":30,
    "altitude":null,
    "longitude":-111.8942634,
    "latitude":40.7288257
  }
} 

Then, you can take the latitude and longitude and call your server to translate it into a ZIP code. Getting the lat/long is the hard part. Doing the math to turn that into a zip is easy.

An alternative to calling your own server to translate the lat/long into a zip, you could call Google Maps' reverse lookup API. You give it a lat long, and it gives you an address, complete with a ZIP. See HERE for how to do that.

DISCLAIMER: This won't work in IE8, as the geolocation API wasn't introduced until IE9. It will work in all other browsers (besides Opera Mini, #NBD).

HERE IS A FULL WORKING EXAMPLE I just tried this out, and it found my house, no problem.

window.navigator.geolocation.getCurrentPosition(function(pos){
  console.log(pos);
  $http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+pos.coords.latitude+','+pos.coords.longitude+'&sensor=true').then(function(res){
    console.log(res.data);
  });
})
like image 95
frosty Avatar answered Nov 16 '22 08:11

frosty