0

I try to get my current browser location and set it in variables. If browser doesn't have activated geolocation set a default latitude and longitude.

if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(location) {
            this.latitude = location.coords.latitude;
            this.longitude = location.coords.longitude;
          });
        }else{
          this.latitude = 43.318820;
          this.longitude = -3.004561
        }
        console.log(this.latitude); //Undefinied
        console.log(this.longitude);//Undefinied

The problem: Variables return undefinied in every cases. So, ¿What´s wrong in this code?

EDIT

     if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(location => {
            this.latitude = location.coords.latitude;
            this.longitude = location.coords.longitude;
          });
        }else{
          this.latitude = 43.318820;
          this.longitude = -3.004561
        }
  console.log(this.latitude);
    console.log(this.longitude);
El Hombre Sin Nombre
  • 2,906
  • 18
  • 49
  • 92
  • 1) It's an asynchronous function. You can `console.log` inside the callback 2) You need to use an arrow function to use the correct `this` inside the callback: `getCurrentPosition(location => { })` – adiga May 20 '21 at 08:48
  • I edit question with the callback, but doesn´t work as expected. – El Hombre Sin Nombre May 20 '21 at 08:57
  • 1
    The `console.log` lines are executed before the callback is called. You can use `console.log(this.latitude)` inside the callback. The callback doesn't run synchronously with the code. You can add debugger in dev tools and verify this. – adiga May 20 '21 at 09:02

0 Answers0