Geolocation, loop with for and javascript

孤街醉人 提交于 2019-12-13 21:46:46

问题


I'm working on a Geolocation tool for a mobile website and so far i got this:

The Geolocation verification from here:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} else {
    console.log('Geolocation not enabled in your browser.');
}

The toRad() function from Caspar's answer here:

if (typeof(Number.prototype.toRad) === "undefined") {
    Number.prototype.toRad = function() {
        return this * Math.PI / 180;
    }
}

and the successFunction() from the first link, Movable Type Scripts and some others modifications:

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>';

    //}
}

This works just fine on my desktop and my iphone. The problem comes when i comment the i=0; line and uncomment the for() statement right after (as well as the closing bracket). Chrome's console returns me an error:

Uncaught TypeError: Cannot read property 'lat' of undefined

For this line:

lat2 = aLocal[i].lat;

The reason for the loop is that i want to do the math x times to check which shop is closer to the user (by getting the smallest distance between user and each shop). But i can't seem to find out why it won't allow the loop.

Thanks a lot in advance.


回答1:


aLocal has three elements. Your loop goes from 0 to 3 so that are 4 elements.

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



回答2:


Your loop condition is i<4 so i will be 0, 1, 2, 3, but you only have array indices 0, 1, 2

You can't go past the length of the array, so change the loop condition to go until the length of the array using i < aLocal.length

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


来源:https://stackoverflow.com/questions/13166261/geolocation-loop-with-for-and-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!