D0nK3Y_D0nK D0nK3Y_D0nK - 1 year ago 105
HTML Question

getCurrentPosition () wont display - javascript

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.


window.onload = Location;

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

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


function show(position) {
x.innerHTML = position.coords.latitude;

Answer Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download