Tom
Tom

Reputation: 936

Geolocation supported but not working

I'm trying to use the geolocation provided by the browser.

This is my code

console.log("Before Geolocation");

        if(navigator.geolocation) {
        console.log("Geolocation Supported");
            navigator.geolocation.getCurrentPosition(function(position) {
                console.log("Within function");
                geoloc = position.coords.latitude + "," + position.coords.longitude;
                console.log(geoloc);                    
                }, 
            function(){ 
                console.log("error");
            },
            {
                timeout: 10000
            }
            );

        }
        else {
            console.log("geolocation not supported");
        }


        if (geoloc != '') {
            addition = geoloc;

        }

        else {

        addition = "DEFAULT LOCATION"; 

        }

        console.log(addition);

My problem is, when im running the code, the console output on chrome says:

Before Geolocation
Geolocation Supported
DEFAULT LOCATION

It seems like that the call:

navigator.geolocation.getCurrentPosition(function(position) {

does not seem to be executed, as neither the success nor the failure function is doing something. (Which could be checked in the console)

What could be the reasons for the function not firing but geolocation being supported?

Upvotes: 2

Views: 1699

Answers (1)

Will
Will

Reputation: 3251

The function is called, but it's asynchronous. That's why you have to supply a callback function.

var addition = "DEFAULT LOCATION";
var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

if (navigator.geolocation) {
  console.log('geolocation supported');
  navigator.geolocation.getCurrentPosition(success, error, options);
} else {
  console.log("geolocation not supported");
  console.log(addition);
}

function success(position) {
  addition = position.coords.latitude + "," + position.coords.longitude;
  console.log(addition);

  // I worked! Party on...
}

function error(err) {
  console.error(err.message);
}

Upvotes: 2

Related Questions