Posted By

vagrantradio on 03/30/11


Tagged

geolocation


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

chrisaiv
AllKnightAccess
jarc100


Zip code from HTML5 Geolocation


 / Published in: JavaScript
 

  1. function retrieve_zip(callback)
  2. {
  3. try { if(!google) { google = 0; } } catch(err) { google = 0; } // Stupid Exceptions
  4. if(navigator.geolocation) // FireFox/HTML5 GeoLocation
  5. {
  6. navigator.geolocation.getCurrentPosition(function(position)
  7. {
  8. zip_from_latlng(position.coords.latitude,position.coords.longitude,callback);
  9. });
  10. }
  11. else if(google && google.gears) // Google Gears GeoLocation
  12. {
  13. var geloc = google.gears.factory.create('beta.geolocation');
  14. geloc.getPermission();
  15. geloc.getCurrentPosition(function(position)
  16. {
  17. zip_from_latlng(position.latitude,position.longitude,callback);
  18. },function(err){});
  19. }
  20. }
  21. function zip_from_latlng(latitude,longitude,callback)
  22. {
  23. // Setup the Script using Geonames.org's WebService
  24. var script = document.createElement("script");
  25. script.src = "http://ws.geonames.org/findNearbyPostalCodesJSON?lat=" + latitude + "&lng=" + longitude + "&callback=" + callback;
  26. // Run the Script
  27. document.getElementsByTagName("head")[0].appendChild(script);
  28. }
  29. function example_callback(json)
  30. {
  31. // Now we have the data! If you want to just assume it's the 'closest' zipcode, we have that below:
  32. zip = json.postalCodes[0].postalCode;
  33. country = json.postalCodes[0].countryCode;
  34. state = json.postalCodes[0].adminName1;
  35. county = json.postalCodes[0].adminName2;
  36. place = json.postalCodes[0].placeName;
  37. alert(zip);
  38. }
  39. retrieve_zip("example_callback"); // Alert the User's Zipcode

Report this snippet  

You need to login to post a comment.