2

I am trying to get the current location coordinates using navigator.geolocation.getCurrentPosition inside a Lightning Web Component.

Expected :

I am getting the coordinates correctly in the position.coords.latitude and position.coords.longitude But I am not able to assign the value to any track variable. (strLatitude is a track variable)

Code Snippet:

navigator.geolocation.getCurrentPosition(
    function(position) {
        console.log(position.coords.latitude); **//This console shows value**
        this.strLatitude = position.coords.latitude;
        console.log(this.strLatitude); **//This console doesnt shows value**
    }, function(e){            
        console.log(e.message);        
    }, {            
        enableHighAccuracy: true        
    }
);

1 Answer 1

1

this is set incorrectly because it's a callback. Use arrow functions instead:

navigator.geolocation.getCurrentPosition(
  (position) => {
    console.log(position.coords.latitude);
    this.strLatitude = position.coords.latitude;
    console.log(this.strLatitude);
  },
  (e) => {
    this.strError = e.message;
  },
  {
    enableHighAccuracy: true,
  }
);

Or, you can bind to the component controller to make sure that this is what you expect it to be:

  connectedCallback() {
    navigator.geolocation.getCurrentPosition(
      function (position) {
        console.log(position.coords.latitude);
        this.strLatitude = position.coords.latitude;
        console.log(this.strLatitude);
      }.bind(this),
      function (e) {
        console.log(e.message);
      }.bind(this),
      {
        enableHighAccuracy: true,
      }
    );
  }
1
  • Thank you @sfdcfox. Its working. Learned something new as well. Commented Jun 19, 2020 at 13:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .