Basic Javascript Geolocation Script (HTML 5 Spec)


/ Published in: JavaScript
Save to your folder(s)

Simple Javascript test of the HTML 5 geolocation API spec


Copy this code and paste it in your HTML
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. var messageDiv = document.getElementById('message');
  6.  
  7. function initLocation ( ) {
  8.  
  9. // Try HTML5-spec geolocation: http://dev.w3.org/geo/api/spec-source.html
  10. var geolocation = navigator.geolocation;
  11.  
  12. if (geolocation) {
  13. // Try Catch
  14. try {
  15. // getCurrentPosition function as stated in the spec
  16. navigator.geolocation.getCurrentPosition(
  17. successCallback,
  18. errorCallback
  19. );
  20.  
  21. } catch (err) {
  22. messageDiv.innerHTML = 'Error';
  23. }
  24. } else {
  25. messageDiv.innerHTML = 'Your browser is not capable of looking up your location.';
  26. }
  27.  
  28. }
  29.  
  30. function successCallback ( location ) {
  31. message.innerHTML="<p>Longitude: " + location.coords.longitude + "</p>";
  32. message.innerHTML+="<p>Latitude: " + location.coords.latitude + "</p>";
  33. message.innerHTML+="<p>Accuracy: " + location.coords.accuracy + "</p>";
  34. }
  35.  
  36. function errorCallback ( ) {
  37. messageDiv.innerHTML = 'There was an error looking up your position';
  38. }
  39. </script>
  40. </head>
  41.  
  42. <body onload="initLocation()">
  43. <div id="message">Looking Up Location</div>
  44. </body>
  45. </html>

URL: http://dev.w3.org/geo/api/spec-source.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.