Search code examples
javascriptgeolocationvue.js

set geolocation in data object after mounted vuejs


I'm relatively new to VueJS scene. Recently I'm trying to work on my side project which requires to get User's Geolocation Data as soon as the main component had mounted.

My code is here,

var app = new Vue({
  el: '#app', 
  data: {
    position: null
  },
  mounted: function() {
    if(navigator.geolocation){
       navigator.geolocation.getCurrentPosition(function(position){
        this.position = position.coords;
      })
    }

  }
});

I wanted to set position in data object to current geolocation after mounted but unfortunately it isn't working. Is there anything I'm missing?


Solution

  • It's context issue, this inside navigator is bounded to wrong context, so when you write this.position, this is not set to Vue object.

    To prevent that you can use arrow functions:

      mounted: function() {
        if(navigator.geolocation){
           navigator.geolocation.getCurrentPosition(position => {
            this.position = position.coords;
          })
        }
      }
    

    or declate the variable before navigator object that would hold correct context

      mounted: function() {
        if(navigator.geolocation) {
           var self = this;
           navigator.geolocation.getCurrentPosition(function(position){
            self.position = position.coords;
          })
        }
      }
    

    BTW just let you know - the position.coords would return Object that holds properties such as latitude, longitude etc, so If you want one of them you will need point that:

    self.position = position.coords.latitude;