好的,所以我有一些东西可以抓住用户的地理位置,因为这个用户可能正在移动它被设置为定时 setTimeout 以每 3 秒重新运行一次地理定位功能,如果他们移动将显示他们的进度,但是我想要它如果它们没有移动,例如它们的纬度和经度相同,则不要更新,因为也没有理由。
我的想法如下:
function startGeolocation() {
var options;
navigator.geolocation.getCurrentPosition(geoSuccess, geoFail, options);
}
//get various coordinates
function geoSuccess(position) {
var gpsPosition = position;
var coordinates = gpsPosition.coords;
//if its the first run through and myLat is empty, then continue as normal.
if (!myLat){
myLat = coordinates.latitude;
myLong = coordinates.longitude;
//if its the second run through and the myLat is the same as it was before, do nothing.
}else if ((myLat == myLatSame) && (myLong == myLongSame)){
}
//else if they are different, e.g user has moved, then update.
else{
myLat = coordinates.latitude;
myLong = coordinates.longitude;
setTimeout(geoSuccess, 3000);
}
myLatSame = myLat;
myLongSame = myLong;
}
它似乎不起作用,并且页面完全停止加载地图。
但是,如果我回到非常基本的代码,
function startGeolocation() {
var options;
navigator.geolocation.getCurrentPosition(geoSuccess, geoFail, options);
setTimeout(startGeolocation, 3000);
}
function geoSuccess(position) {
var gpsPosition = position;
var coordinates = gpsPosition.coords;
myLat = coordinates.latitude;
myLong = coordinates.longitude;
这工作正常,每 3 秒更新一次。
我已经从长时间的 javascript 编码中断中回来了,所以我的语法和方法有点生疏。提前致谢
编辑:
我在代码中添加了一些警报,并在第一次运行时发生以下情况:它第一次运行所以警报(之前 if)=未定义 myLat 和 myLong。!myLat 是真的,因为它什么都没有,所以 myLat 和 myLong 充满坐标并在警报中发出警报(如果),以下警报(myLatSame + myLongSame)返回为“NaN”
else if 没有被触发,因为它们不一样,但是 else alert(else) 语句也没有被触发并且没有被看到。
//get various coordinates
function geoSuccess(position) {
var gpsPosition = position;
var coordinates = gpsPosition.coords;
alert("before if \n" + myLat + "\n" + myLong);
//if its the first run through and myLat is empty, then continue as normal.
if (!myLat){
myLat = coordinates.latitude;
myLong = coordinates.longitude;
alert("in if \n" + myLat + "\n" + myLong);
alert(myLatSame + myLongSame);
//if its the second run through and the myLat is the same as it was before, do nothing.
}else if ((myLat == myLatSame) && (myLong == myLongSame)){
alert("in else if \n" + myLat + "\n" + myLong);
}
//else if they are different, e.g user has moved, then update.
{
myLat = coordinates.latitude;
myLong = coordinates.longitude;
alert("else \n" + myLat + "\n" + myLong);
setTimeout(geoSuccess, 3000);
}
myLatSame = myLat;
myLongSame = myLong;
}