【发布时间】:2012-10-21 09:38:59
【问题描述】:
我正在为一个移动网站开发一个地理定位工具,到目前为止我得到了这个:
来自here的地理位置验证:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} else {
console.log('Geolocation not enabled in your browser.');
}
Caspar 的回答 here 中的 toRad() 函数:
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
和第一个链接中的 successFunction()、Movable Type Scripts 和其他一些修改:
function successFunction(position) {
var lat1 = position.coords.latitude;
var lon1 = position.coords.longitude;
function calcdist(nLoja,nLat,nLong) {
this.loja = nLoja;
this.lat = nLat;
this.long = nLong;
}
aLocal = new Array(3)
aLocal[0] = new calcdist("leblon",-22.982279,-43.217792);
aLocal[1] = new calcdist("ipanema",-22.98376,-43.212138);
aLocal[2] = new calcdist("barra",-22.999118,-43.357867);
var i = 0;
//for (var i = 0; i < 4; i++){
lat2 = aLocal[i].lat;
lon2 = aLocal[i].long;
var R = 6371;
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
var thediv = document.getElementById('locationinfo');
thediv.innerHTML = '<p>Distance user-' + aLocal[i].loja + ': ' + d + '</p>';
//}
}
这在我的桌面和我的 iPhone 上运行良好。当我评论i=0; 行并在之后(以及右括号)取消注释for() 语句时,问题就来了。 Chrome 的控制台返回错误:
Uncaught TypeError: Cannot read property 'lat' of undefined
对于这一行:
lat2 = aLocal[i].lat;
循环的原因是我想计算 x 次来检查哪个商店离用户更近(通过获取用户和每个商店之间的最小距离)。但我似乎无法找出为什么它不允许循环。
非常感谢。
【问题讨论】:
-
不确定它是否会修复错误,但您应该在声明变量时使用
var。 -
感谢@sachleen 我忘记的小修改和帮助。
标签: javascript arrays for-loop geolocation