[html5] geolocation

Viewer

copydownloadembedprintName: geolocation
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Getting Current Position</title>
  6. <script>
  7.     // Set global variable
  8.     var watchID;
  9.  
  10.     function showPosition() {
  11.         if(navigator.geolocation) {
  12.             watchID = navigator.geolocation.watchPosition(successCallback);
  13.         } else {
  14.             alert("Sorry, your browser does not support HTML5 geolocation.");
  15.         }
  16.     }
  17.     function successCallback(position) {
  18.         toggleWatchBtn.innerHTML = "Stop Watching";
  19.         
  20.         // Check position has been changed or not before doing anything
  21.         if(prevLat != position.coords.latitude || prevLong != position.coords.longitude) {
  22.             
  23.             // Set previous location
  24.             var prevLat = position.coords.latitude;
  25.             var prevLong = position.coords.longitude;
  26.             
  27.             // Get current position
  28.             var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
  29.             document.getElementById("result").innerHTML = positionInfo;
  30.             
  31.         }
  32.         
  33.     }
  34.     function startWatch() {
  35.         var result = document.getElementById("result");
  36.         
  37.         var toggleWatchBtn = document.getElementById("toggleWatchBtn");
  38.         
  39.         toggleWatchBtn.onclick = function() {
  40.             if(watchID) {
  41.                 toggleWatchBtn.innerHTML = "Start Watching";
  42.                 navigator.geolocation.clearWatch(watchID);
  43.                 watchID = false;
  44.             } else {
  45.                 toggleWatchBtn.innerHTML = "Aquiring Geo Location...";
  46.                 showPosition();
  47.             }
  48.         }
  49.     }
  50.     
  51.     // Initialise the whole system (above)
  52.     window.onload = startWatch;
  53. </script>
  54. </head>
  55. <body>
  56.     <button type="button" id="toggleWatchBtn">Start Watching</button>
  57.     <div id="result">
  58.         <!--Position information will be inserted here-->
  59.     </div>   
  60. </body>
  61. </html>

Editor

You can edit this paste and save as new:


File Description
  • geolocation
  • Paste Code
  • 29 Nov-2020
  • 2 Kb
You can Share it: