How to get the zipcode of a user using AngularJS
Asked Answered
L

2

6

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.

Lilylilyan answered 18/8, 2014 at 0:1 Comment(1)
var zipCode = window.prompt('Please enter your ZIP code (if you have one)').Pesthouse
L
12

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);
  });
})
Lustring answered 18/8, 2014 at 1:27 Comment(3)
When you call getCurrentPosition, it will popup in the user's browser and they have to approve it. It won't be invisible to the user. They will see that you are requesting their position.Lustring
Can you share this easy math to turn coordinates into a zip code? I don't see how it could only involve math unless zipcode boundaries are created using some formulaEversion
I used the Google maps API to do that. Not math. You are right. That would take a serious setup to calculate. The Google maps API makes it simple and free, under a certain limit.Lustring
M
0

There doesn't seem to be any built-in method for determining this, you'll have to use a map service or zipcode database.

Manrope answered 18/8, 2014 at 0:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.