【问题标题】:Geolocation, loop with for and javascript地理位置,使用 for 和 javascript 循环
【发布时间】: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


【解决方案1】:

您的循环条件是i&lt;4,所以i 将是0, 1, 2, 3,但您只有数组索引0, 1, 2

你不能超过数组的长度,所以使用i &lt; aLocal.length改变循环条件直到数组的长度

for(i = 0; i < aLocal.length; i++) {

【讨论】:

    【解决方案2】:

    aLocal 具有三个元素。您的循环从 0 变为 3,因此是 4 个元素。

    for (var $i = 0; $i < aLocal.length; $i++) {
        //...
    }
    

    【讨论】:

    • 该死,简直不敢相信它是如此简单。我想我在这上面已经太久了。伟大的。现在第二个循环有一个距离错误,但我应该能够弄清楚。
    猜你喜欢
    • 1970-01-01
    • 2022-12-31
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多