将坐标(地理位置)存储在数组中以计算距离 [英] Storing coordinates (geolocation) in array to calculate distance

查看:149
本文介绍了将坐标(地理位置)存储在数组中以计算距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和我的合作伙伴正在为我们的学校论文制作一个练习网络应用程序。我们正试图获得跑步者的位置,并在他使用geolocation API的watchposition()函数锻炼时跟踪他。在屏幕上,跑步者可以检查他目前的距离。

这是我们卡住的一点,我们只能计算开始点和结束点之间的距离,但当路线是圆形时,覆盖的总距离显示为零。

因此,我们有解决方案将多个坐标存储在一个数组中,并计算这些距离的总和,但我们并不是JavaScript中最熟练的人。我希望这有点意义,如果你想要更多的信息只是问。



更新:这是我到目前为止

 <脚本> 

函数startTracking(){

var startPos;
var coords = [];

//重用代码 - 版权可移动类型脚本 - 检索May 5,2010。
// http://www.movable-type.co.uk/scripts/latlong.html
//在Creative Commons License下http://creativecommons.org/licenses/by/3.0/

函数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; }
$ b $ if(navigator.geolocation){
watchID = navigator.geolocation.watchPosition(function(position){
currentLat = position.coords.latitude;
currentLon = position.coords.longitude;

coords.push([currentLat,currentLon]);

console.log(coords);

} ,函数(错误){
alert(发生错误,错误代码:+ error.code);
// error.code可以是:
// 0:未知错误
// 1:权限被拒绝
// 2:位置不可用(来自locaton提供者的错误响应)
// 3:超时
});
//结束错误}; // 万一 }; //结束startTracking

函数stopTracking(){

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

};
< / script>

现在我的问题是如何循环我的数组来计算所有给定的坐标之间的距离得到一个(或多或少)精确的距离?

解决方案

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

  var tracker =(function(){
var watchID;
var watchCallback;
var coords = [];
var distance = 0;

函数calculateDistance(fromPos,toPos){
var radius = 6371;
var toRad =函数(数字){
返回数字* 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)));
}

函数displayError(错误){
alert( 发生了错误。错误代码:+ error.code);
// error.code可以是:
// 0:未知错误
// 1:权限被拒绝
// 2:位置不可用(位置提供者的错误响应)
// 3:超时
}

函数appendPosition(position){
//计算距上一个位置的距离if可用
var lastPos = coords [coords.length-1];
if(lastPos){
distance + = calculateDistance(lastPos,position.coords);
}

//将新坐标添加到数组
coords.push(position.coords);

//调用自定义回调
if(watchCallback){
watchCallback(position,distance,watchID);
}
}

函数startWatcher(回调,选项){
if(导航器中的geolocation){
//观看位置更新
watchCallback =回拨;
//观看更新
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(函数(位置,距离){
console.log(位置,距离);
});

tracker.stop();


简要文档

$
$ b

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

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



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


JSFiddle Demo



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


Me and my partner are working on an exercise web application for our school thesis. We are trying to get a runner's position and track him during his workout with the watchposition() function of the geolocation api. On-screen the runner can check his current distance.

This is the point were we are stuck, we can only calculate the distance between the start and end point but when the course is a circle the total distance covered displays zero.

So we had the solution to store multiple coordinates in an array and calculate the sum of those distances but we aren't the most skilled persons in javascript. I hope this makes a little sense if you want more info just ask.

UPDATE: this is what i got so far

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

So now my question is how do i loop over my array to calculate the distance between all the given coordinates to get a (more or less) accurate distance?

解决方案

This should accomplish what you're looking to do. Feel free to use it in your code, or tear it apart and learn from it. Essentially it appends coordinates to an array and calculates the distance at the same time. You could just save the last coordinate instead of all of them if you just want the distance. This should get you started in the right direction for anything you want to do.

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


Example usage:

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

tracker.stop();


Brief documentation:

tracker.start accepts a callback as first parameter, optional geolocation options as the second.

tracker.update will force check the location, accepts optional geolocation options as first parameter.

tracker.stop will stop geolocation's watchPosition.

JSFiddle Demo:

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

这篇关于将坐标(地理位置)存储在数组中以计算距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆