最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

loop over array of coordinates and calculate distance javascript - Stack Overflow

programmeradmin2浏览0评论

I have a running app that tracks and records the runners location and it saves the coordinates into array, so far so good. i'm trying to loop over the array and calculate the distance traveled in total.

the code:

        var startPos;
        var num;
        var distance;

        navigator.geolocation.getCurrentPosition(function (position) {
            startPos = position;
        });
        //
        watchID = navigator.geolocation.watchPosition(function (position) {

        pathArr.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        var latlng = new google.maps.LatLng(lat, lon);

        var num = calculateDistance(startPos.coords.latitude,startPos.coords.longitude,
        position.coords.latitude, position.coords.longitude);
        distance = num;
        },


        function (positionError) {
            $("#error").append("Error: " + positionError.message + "<br />");
        }, {
            enableHighAccuracy: true,
            timeout: 30 * 1000
        });


function calculateDistance(lat1, lon1, lat2, lon2) {
    var R = 6371; // km
    var dLat = (lat2 - lat1).toRad();
    var dLon = (lon2 - lon1).toRad();
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d;
}

what i had realized is that the calculation only works properly if i walk a straight line cause it always goes from start till current and not one by one and if the runner will circle back to point zero the total will be 0 or close to 0, i need to change it in order to calculate the distance from coord to coord and add the total.

i tried this :

        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        var latlng = new google.maps.LatLng(lat, lon);

            num += calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
            position.coords.latitude, position.coords.longitude);
            startPos = latlng;
            distance = num;

and no luck. please help

I have a running app that tracks and records the runners location and it saves the coordinates into array, so far so good. i'm trying to loop over the array and calculate the distance traveled in total.

the code:

        var startPos;
        var num;
        var distance;

        navigator.geolocation.getCurrentPosition(function (position) {
            startPos = position;
        });
        //
        watchID = navigator.geolocation.watchPosition(function (position) {

        pathArr.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        var latlng = new google.maps.LatLng(lat, lon);

        var num = calculateDistance(startPos.coords.latitude,startPos.coords.longitude,
        position.coords.latitude, position.coords.longitude);
        distance = num;
        },


        function (positionError) {
            $("#error").append("Error: " + positionError.message + "<br />");
        }, {
            enableHighAccuracy: true,
            timeout: 30 * 1000
        });


function calculateDistance(lat1, lon1, lat2, lon2) {
    var R = 6371; // km
    var dLat = (lat2 - lat1).toRad();
    var dLon = (lon2 - lon1).toRad();
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d;
}

what i had realized is that the calculation only works properly if i walk a straight line cause it always goes from start till current and not one by one and if the runner will circle back to point zero the total will be 0 or close to 0, i need to change it in order to calculate the distance from coord to coord and add the total.

i tried this :

        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        var latlng = new google.maps.LatLng(lat, lon);

            num += calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
            position.coords.latitude, position.coords.longitude);
            startPos = latlng;
            distance = num;

and no luck. please help

Share Improve this question asked Jun 30, 2015 at 16:28 Aviran BergicAviran Bergic 531 silver badge5 bronze badges 4
  • An easy to follow solution: Each runner could have their own array, and have it push a coordinate every so often or change in distance, then add up the current iteration + the last. Instead of drawing a line, it'd be more like connect the dots. Depending on how much processing power/storage you have, you could make this very simple or robust (even calculate speeds and such) – Steven Lacks Commented Jun 30, 2015 at 16:33
  • 1 if you only use two points you are measuring change in distance, not total distance travelled. @StevenLacks is right, you need more than two points. Also you said you are trying to loop over an array but, maybe I missed it, but I don't see a loop in your code, you can easily do what you want to just use a for loop and keep a track of distance traveled from point to point. – Jess Patton Commented Jun 30, 2015 at 16:37
  • Yes, with my solution, you'd also need to keep a running total or loop over it again to get a total distance. – Steven Lacks Commented Jun 30, 2015 at 16:38
  • ill explain better. i have a lot more than 2 points, inside watchID = navigator.geolocation.watchPosition(function (position) { num += calculateDistance(startPos.coords.latitude, startPos.coords.longitude, position.coords.latitude, position.coords.longitude); startPos = position; distance = num; the startPos and the position change every time the user moves , so the num variable should be the sum of the distance between the 1st coord to the second, then the second to the 3rd and so on. – Aviran Bergic Commented Jun 30, 2015 at 17:24
Add a ment  | 

1 Answer 1

Reset to default 6

You need to iterate over all geographic coordinates in your array, and find the distance between each successive two coordinates, and add them to a sum of distance to find the total distance.

The relevant part of the simplified code is like this:

Given that coords hold the array of geographical coordinates,

for (var i = 0; i < coords.length - 1; i++) {
    distanceTotal += google.maps.geometry.spherical.puteDistanceBetween(coords[i], coords[i+1]);
}

Here's an example with the Google Maps API: http://jsfiddle/90kbnjqx/2/

发布评论

评论列表(0)

  1. 暂无评论