遍历坐标数组并计算距离JavaScript

3

我有一个跟踪和记录跑步者位置的正在运行的应用程序,并将坐标保存到数组中,目前为止还不错。 我试图循环遍历这个数组,并计算总共行驶的距离。

代码:

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

我意识到的是,这个计算方式只在我沿着一条直线行走时才能正常工作,因为它总是从起点到当前点而不是逐一计算。如果跑步者回到零点,总距离将为0或接近于0,我需要改变它以便计算从坐标到坐标的距离并添加总距离。
我尝试了这个:
        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;

没有运气了。 请帮忙。

一种易于实现的解决方案:每个跑步者都可以拥有自己的数组,并在一段时间内推送一个坐标或者改变距离,然后将当前迭代和上一个迭代相加。与其绘制一条线,不如将这些点连接起来。根据您拥有的处理能力/存储空间的多少,您可以使其非常简单或者非常强大(甚至计算速度等)。 - Steven Lacks
1
如果你只使用两个点,你测量的是距离变化而不是总行程。@StevenLacks是正确的,你需要超过两个点。另外,你说你正在尝试循环遍历一个数组,但是也许我错过了,但我在你的代码中没有看到循环,你可以轻松地使用for循环并跟踪从点到点的行程距离来实现你想要的效果。 - Jess Patton
是的,使用我的解决方案,您还需要保持一个运行总数或再次循环以获得总距离。 - Steven Lacks
我来解释得更好一些。在这段代码中,我有超过2个点。在watchID = navigator.geolocation.watchPosition(function (position) { }函数中,startPos和position会随着用户移动而改变。因此,num变量应该是第一个坐标到第二个坐标之间的距离的总和,然后是第二个到第三个,以此类推。 - Aviran Bergic
1个回答

6
你需要遍历数组中的所有地理坐标,并找到每两个连续坐标之间的距离,将它们加起来得到总距离。

简化代码的相关部分如下:

假设coords保存了地理坐标数组,

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

这里有一个与Google Maps API相关的示例:http://jsfiddle.net/90kbnjqx/2/

抱歉,我更新了我的答案。我一时想到了欧几里得空间,而问题显然是关于地理距离的。 - neuro_sys

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接