javascript - 地理定位,使用 for 和 javascript 循环

标签 javascript arrays for-loop geolocation

我正在为移动网站开发地理定位工具,到目前为止我得到了这个:

来自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/

相关文章:

javascript - 在 await 之后调用 setState 时状态立即可用

javascript - 谁能告诉我为什么我的 div 是垂直排列而不是水平排列的?

c++ - 在 xcode C++ (lldb) 中查看动态数组的内容

arrays - 具有特定键的 Mongoose 更新数组中的对象

for-loop - kotlin,如何动态改变for循环的速度

javascript - Chrome 扩展/Bootstrap native 函数未定义? (Javascript)

javascript - 在什么情况下或条件下需要 jQuery.noConflict?

arrays - 如何在 Ecto 中做 'where model.field contains array'?

java - Java 中嵌套 for 内部的 for 更改为 to

for 循环中来自 LocalForage 的 JavaScript 链式 promise