Reputation: 820
I'm basically trying to call a function which is outside of my AJAX inside the AJAX success response.
To explain this better, this is what I have.
These are two functions:
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(function(position) {
setMarkerPosition(userLocation, position);
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
});
}
function clearmyWatch() {
navigator.geolocation.clearWatch(positionTimer);
}
One of them keeps watching the users location and the other one 'should' stop it.
And this is how I'm calling the clearmyWatch();
function inside the AJAX:
$.ajax({
type:"post",
url:"TEST.PHP",
datatype:"html",
success:function(data)
{
clearmyWatch();
}
});
However, this doesn't work and the watchCurrentPosition();
constantly running and I also get an error in my console.
The error that I am getting is this:
ReferenceError: positionTimer is not defined
Could someone please advise on this issue?
Thanks in advance.
Upvotes: 2
Views: 4225
Reputation: 1563
positionTimer
is local to watchCurrentPosition
The better way to solve it without global variables is:
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(function(position) {
setMarkerPosition(userLocation, position);
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
});
clearmyWatch=()=>{
navigator.geolocation.clearWatch(positionTimer);
}
}
function clearmyWatch() {}
Explanation: clearmyWatch
is defined in a way that it does nothing.However calling watchCurrentPosition
sets clearmyWatch
as an inner function of watchCurrentPosition
that can get to positionTimer
. Actually by setting clearmyWatch
to an inner function of watchCurrentPosition
we create a closure (read about it of you don't know what it is, it's important).
Upvotes: 0
Reputation: 11512
You need to define positionTimer
at global level outside of function watchCurrentPosition()
like:
var positionTimer = null;
function watchCurrentPosition() {
positionTimer = navigator.geolocation.watchPosition(function(position) {
setMarkerPosition(userLocation, position);
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
});
}
function clearmyWatch() {
if(positionTimer)
navigator.geolocation.clearWatch(positionTimer);
}
Upvotes: 3