1π
The word this
refers to the scope of the function. When you nest another function inside, the word this
now refers to the new/ smaller scope so this.lat
is no longer defined. So we capture the out this
in vm
and use it inside functions.
methods: {
initGeolocation: function() {
var vm = this;
if( navigator.geolocation)
{
// Call getCurrentPosition with success and failure callbacks
navigator.geolocation.getCurrentPosition( success, fail );
}
else
{
return;
}
function success(position)
{
vm.lat = position.coords.latitude; //should work now!!
}
function fail()
{
console.log('fail')
}
}
},
mounted() {
this.initGeolocation();
},
0π
In your mounted
you assign this.lat
with the return of your initGeolocation()
method. However this method does not return any data if it succeeds. Instead you write your result into this.lat
which then will be overridden again by the void result of your method. So make sure your method initGeolocation
either returns your geolocation data or you change your mounted method to call the method without assigning the return value to this.lat
.
Also it seems like you just added the initGeolocation
method to your component. Look into the methods
property of vue components where this would belong.
So try this instead:
mounted() {
this.initGeolocation();
console.log(this.initGeolocation());
},
methods: {
initGeolocation: function() {
if( navigator.geolocation)
{
// Call getCurrentPosition with success and failure callbacks
navigator.geolocation.getCurrentPosition( success, fail );
}
else
{
return;
}
function success(position)
{
this.lat = position.coords.latitude; //does not work
}
function fail()
{
console.log('fail')
}
}
}