0

So I am trying to use getCurrentPosition to display the latitude and longitude coordinates but nothing gets displayed. I test to see if the browser accepts it and the error message does not pop up.

Javascript:

window.onload = Location;


var x = document.getElementById("location");


function Location() {
  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(show);
  } else {
    x.innerHTML = "Not working";
  }

}

function show(position) {
  x.innerHTML = position.coords.latitude;
}
D0nK3Y_D0nK
  • 63
  • 1
  • 4
  • 8
  • JSFiddle by default runs the code in a onload event, so setting `window.onload = getLocation;` wont work as the load event has already fired – Patrick Evans Oct 02 '16 at 03:31

1 Answers1

0

The if (navigator.geolocation) method doesn't work here as navigator.geolocation is an empty object, regardless of whether a position can be obtained. You can console.log(navigator.geolocation) to verify this.

Instead, use the error callback parameter of navigator.geolocation.watchPosition:

function getLocation() {
     navigator.geolocation.watchPosition(showPosition, throwError);
}

function throwError(err) {
     switch (err.code) {
         case 1: x.innerHTML = "Permission denied."; break;
         case 2: x.innerHTML = "Position unavailable."; break;
         case 3: x.innerHTML = "Request timed out."; break;
         default: x.innerHTML = "Unknown error.";
     }
}

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition https://developer.mozilla.org/en-US/docs/Web/API/PositionError

Also, there are some significant browser quirks to be aware of.

If you are testing your site on your local filesystem, Chrome blocks geolocation requests: HTML 5 Geo Location Prompt in Chrome

And Firefox still won't handle the error callback correctly (scroll down to see workarounds): Is there a way to check if geolocation has been DECLINED with Javascript?

Community
  • 1
  • 1
Matt Davis
  • 361
  • 1
  • 4
  • 10