我正在为移动网站开发地理定位工具,到目前为止我得到了这个:
来自here的地理位置验证 :
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} else {
console.log('Geolocation not enabled in your browser.');
}
Caspar 的回答中的 toRad() 函数 here :
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 次数学计算来检查哪个商店离用户更近(通过获取用户和每个商店之间的最小距离)。但我似乎无法找出为什么它不允许循环。
提前非常感谢。
最佳答案
您的循环条件是i<4
所以i
将是0, 1, 2, 3
,但只有数组索引 0, 1, 2
您无法超过数组的长度,因此请使用 i < aLocal.length
更改循环条件,直到达到数组的长度。
for(i = 0; i < aLocal.length; i++) {
关于javascript - 地理定位,使用 for 和 javascript 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13166261/