HTML5 Game - Use getCurrentPosition to Find Browser Location

Description

Use getCurrentPosition to Find Browser Location

Demo

ResultView the demo in separate window

<!DOCTYPE html>  
         <html> 
         <head> 
         <meta charset="UTF-8" /> 
         <title>10.1 Find Me</title> 
         <script> 

         // Initialize the page with other event listeners 
         function init() { /*from w  w  w  . j  a  v  a  2  s . com*/
          let btnFindMe = document.getElementById('findMe'); 
          btnFindMe.addEventListener('click',findMe,false); 
         } 

         // success callback function for getCurrentPosition 
         function geoSuccess(position) { 

          // grab the position DOMTimeStamp for display 
          let dateDisplay = new Date(position.timestamp); 

          // get reference to result div 
          let myLocationDiv = document.getElementById('myLocation'); 

          // display the coords and timestamp object fields 
          myLocationDiv.innerHTML = 'Lat: ' + position.coords.latitude + '<br>' + 
            'Lng: ' + position.coords.longitude + '<br>' + 
            'Accuracy: ' + position.coords.accuracy + '<br>' +  
            'Altitude (opt): ' + position.coords.altitude + '<br>' + 
            'Alt. Accuracy (opt): ' + position.coords.altitudeAccuracy + '<br>' +  
            'Heading (opt): ' + position.coords.heading + '<br>' +  
            'Speed (opt): ' + position.coords.speed + '<br>' +  
            'Position DOMTimeStamp: ' + position.timestamp + '<br>' +  
            'Time Date Stamp: ' + dateDisplay.toLocaleString(); 
         } 

         // function called from button click to find position 
         function findMe() { 
          let myLocationDiv = document.getElementById('myLocation'); 
  // check for geolocation support 
  if (navigator.geolocation) { 
    // make asynchronous getCurrentPosition call 
    navigator.geolocation.getCurrentPosition(geoSuccess); 
    myLocationDiv.innerHTML = 'Retrieving your location.'; 
  } else { 
    // geolocation not supported 
    myLocationDiv.innerHTML = 'Geolocation API Not Supported'; 
  } 
} 

// Initialize the page on load 
window.addEventListener('load',init,false); 

</script> 
</head> 
<body> 
<div id='btnFindMe'> 
  <button id="findMe">Find Me</button> 
</div> 
<div id="myLocation"></div> 
</body> 
</html>

Related Topic