【发布时间】:2013-02-26 19:35:00
【问题描述】:
好的,所以我有一些东西可以抓取用户的地理位置,因为这个用户可能正在移动,它被设置为定时 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 编码的长期中断,所以我的语法和方法有点生疏。 提前致谢
编辑:
我在代码中添加了一些警报,并在第一次运行时发生以下情况: 它的第一次运行如此 alert(before if) = undefined for 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;
}
【问题讨论】:
-
然后呢?有什么问题?它有效吗?有错误吗?问题在哪里?
-
抱歉,在别处走神了。代码不起作用,地图现在根本无法加载。
-
不,没有。我只是在语句中以不同的时间间隔添加了一些 alert(),但没有一个被触发。