【问题标题】:Storing coordinates (geolocation) in array to calculate distance在数组中存储坐标(地理位置)以计算距离
【发布时间】:2014-05-03 17:42:51
【问题描述】:

我和我的搭档正在为我们的学校论文开发一个练习网络应用程序。我们正在尝试使用 geolocation api 的 watchposition() 函数获取跑步者的位置并在他的锻炼过程中跟踪他。跑步者可以在屏幕上查看他当前的距离。

这是我们被卡住的地方,我们只能计算起点和终点之间的距离,但是当路线是圆形时,所覆盖的总距离显示为零。

所以我们有解决方案将多个坐标存储在一个数组中并计算这些距离的总和,但我们并不是最熟练的 javascript 人员。如果您想了解更多信息,我希望这有点意义。

更新:这是我目前得到的

    <script>

        function startTracking() {

            var startPos;   
            var coords = [];

            // Reused code - copyright Moveable Type Scripts - retrieved May 4,2010.
            // http://www.movable-type.co.uk/scripts/latlong.html
            // Under Creative Commons License http://creativecommons.org/licenses/by/3.0/

            function calculateDistance(lat1, lon1, lat2, lon2) {
                var R = 6371000; // m
                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.toFixed(2);    }

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

            if (navigator.geolocation) {
                watchID = navigator.geolocation.watchPosition(function(position) {
                    currentLat = position.coords.latitude;
                    currentLon = position.coords.longitude;

                    coords.push([currentLat, currentLon]);

                    console.log(coords);

                }, function(error) {
                    alert("Error occurred. Error code: " + error.code);
                    // error.code can be:
                    //   0: unknown error
                    //   1: permission denied
                    //   2: position unavailable (error response from locaton provider)
                    //   3: timed out
                });
                // end error    };      // end if  }; // end startTracking

        function stopTracking() {

            if (navigator.geolocation) {
               navigator.geolocation.clearWatch(watchID);   }

            };  
</script>

所以现在我的问题是如何遍历我的数组来计算所有给定坐标之间的距离以获得(或多或少)准确的距离?

【问题讨论】:

    标签: javascript html geolocation


    【解决方案1】:

    这应该可以完成您想要做的事情。随意在您的代码中使用它,或者将其拆开并从中学习。本质上,它将坐标附加到数组并同时计算距离。如果您只想要距离,您可以只保存最后一个坐标而不是所有坐标。这应该会让您朝着正确的方向开始您想做的任何事情。

    var tracker = (function() {
        var watchID;
        var watchCallback;
        var coords = [];
        var distance = 0;
    
        function calculateDistance(fromPos, toPos) {
            var radius = 6371;
            var toRad = function(number) {
                return number * Math.PI / 180;
            };
    
            var latDistance = toRad(toPos.latitude - fromPos.latitude);
            var lonDistance = toRad(toPos.longitude - fromPos.longitude);
            var a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + 
                    Math.cos(toRad(fromPos.latitude)) * Math.cos(toRad(toPos.latitude)) * 
                    Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
    
            return radius * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))); 
        }
    
        function displayError(error) {
            alert("Error occurred. Error code: " + error.code);
            // error.code can be:
            //   0: unknown error
            //   1: permission denied
            //   2: position unavailable (error response from locaton provider)
            //   3: timed out
        }
    
        function appendPosition(position) {
            // Calculate distance from last position if available
            var lastPos = coords[coords.length-1];
            if(lastPos) {
                distance += calculateDistance(lastPos, position.coords);
            }
    
            // Add new coordinates to array
            coords.push(position.coords);
    
            // Call custom callback
            if(watchCallback) {
                watchCallback(position, distance, watchID);
            }
        }
    
        function startWatcher(callback, options) {
            if ("geolocation" in navigator) {
                // Watch position updates
                watchCallback = callback;
                // Watch for updates
                watchID = navigator.geolocation.watchPosition(appendPosition, displayError, options);
                var registerWatchPosition = function(position) {
                    appendPosition(position);
                };
            } else {
                alert('Geolocation is not supported!');
            }
        }
    
        function forceUpdate(options) {
            navigator.geolocation.getCurrentPosition(appendPosition, displayError, options);
        }
    
        function stopWatcher() {
            navigator.geolocation.clearWatch(watchID);
        }
    
        return {
            start: startWatcher,
            stop: stopWatcher,
            update: forceUpdate
        };
    })();
    


    使用示例

    tracker.start(function(position, distance) {
        console.log(position, distance);
    });
    
    tracker.stop();
    


    简要文档

    tracker.start 接受回调作为第一个参数,可选的地理位置选项作为第二个参数。

    tracker.update 将强制检查位置,接受可选的地理位置选项作为第一个参数。

    tracker.stop 将停止地理定位的 watchPosition。

    JSFiddle 演示

    http://jsfiddle.net/Cavitt/Gcz6H/1/

    【讨论】:

    • 嘿,我想感谢您的评论,这对我很有帮助,我用一些代码编辑了我的原始问题。
    • @StimCoder -- 更新了我的答案以回答您编辑的问题。
    • 这是一个了不起的人,我无法告诉你我们自己寻找解决方案有多久了。你先生是救命稻草!
    • 只是一个小问题,我可以在哪里为地理位置选项添加 enableHighAccuracy?
    【解决方案2】:

    我也想知道在哪里添加 enableHighAccuray 选项。我尝试了以下方法:

            function startWatcher(callback, options) {
            if ("geolocation" in navigator) {
                // Watch position updates
                watchCallback = callback;
                // Watch for updates
                watchID = navigator.geolocation.watchPosition(appendPosition, displayError, {
        enableHighAccuracy:true
     });
                var registerWatchPosition = function(position) {
                    appendPosition(position);
                };
            } else {
                alert('Geolocation is not supported!');
            }
        }
    

    但没有按预期工作......

    谢谢!

    【讨论】:

    • 嗨,DonHS,欢迎来到 StackOverflow!我建议您发布一个新问题,而不是在答案中提出问题。在其中参考这个问题可能会有所帮助?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多