我正在为移动网站开发地理定位工具,到目前为止我得到了这个:
来自这里的地理位置验证:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} else {
console.log('Geolocation not enabled in your browser.');
}
来自 Caspar 的答案的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 次来检查哪个商店离用户更近(通过获取用户和每个商店之间的最小距离)。但我似乎无法找出为什么它不允许循环。
提前非常感谢。