Aymen Kareem Aymen Kareem - 1 month ago 11
Javascript Question

Why Location Determination Does Not Work in JavaScript?

The following code is for determining location. However, It didn't work with me.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to get your coordinates.</p>

<input type="button" value="try it" onclick="getLocation()" />

<p id="demo"></p>

</body>
</html>
<script>
var x = document.getElementById("demo");

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function showPosition(position) {alert("Latitude: ");},function error1(){},{enableHighAccuracy: true, timeout: 5000});
} else {
alert("Geolocation is not supported by this browser.");
}
}


</script>


Any one knows why it did not work?

Answer

For your error callback function you need to have more detailed error reporting:

var browserGeolocationFail = function(error) {
  switch (error.code) {
    case error.TIMEOUT:
      alert("Browser geolocation error !\n\nTimeout.");
      break;
    case error.PERMISSION_DENIED:
      if(error.message.indexOf("Only secure origins are allowed") == 0) 
      {
          alert('Only secure origins are allowed');
      }
      else
      {
          alert("Please enable location services on.");
      }
      break;
    case error.POSITION_UNAVAILABLE:
      alert("Browser geolocation error !\n\nPosition unavailable.");
      break;
  }
};

function getLocation() 
{
        if (navigator.geolocation) 
        {
            navigator.geolocation.getCurrentPosition(
                function showPosition(position) {alert("Latitude: ");},
                browserGeolocationFail,
                {enableHighAccuracy: true, timeout: 5000});
        }   
        else 
        {
            alert("Geolocation is not supported by this browser.");
        }
}