我有一個陣列,其中 x 元素給定lat-lng 值。我的目標是只要使用haversine公式的陣列的元素數(長度),就可以找到回圈中上一個位置和下一個位置之間的距離差。
示例我的陣列值;
var array = [
[51.06745252933975, -114.11267548799515],
[51.067506465746014, -114.09559518098831],
[51.0827140244322,-114.0949085354805],
[51.088267312195484,-114.10709649324417]];
我的數學沒有問題,我的目標是讓游標在回圈中作為前一個元素與下一個實際指標順序。
粗略的代碼配方;
回圈的第一個索引;array[0] lat-lng 和 array[1] lat-lng 計算距離
回圈的第二個索引;array[1] lat-lng 和 array[2] lat-lng 計算距離
我正在使用Javascript,我該怎么做最理想?
uj5u.com熱心網友回復:
似乎有點簡單,但我可能根本不明白這個問題,如果問題是如何通過與上一個條目的比較來回圈陣列,有幾種方法可以做到,一種方法如下所示
// https://stackoverflow.com/a/27943/28004
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2)
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
// end of pasted code
// your entry
const points = [
[51.06745252933975, -114.11267548799515],
[51.067506465746014, -114.09559518098831],
[51.0827140244322,-114.0949085354805],
[51.088267312195484,-114.10709649324417]
]
// looping through all points starting from the second element
for (let i = 1; i < points.length; i = 1) {
const lastPosition = points[i-1];
const newPosition = points[i];
console.log(
`from position ${i-1} to ${i} it's %s Km`,
getDistanceFromLatLonInKm(lastPosition[0], lastPosition[1], newPosition[0], newPosition[1]))
}
請記住,沒有驗證(只有 1 個條目會通過錯誤),并且 Haversine 公式僅計算 2 個點之間的直線,并且確實考慮到行星不是球體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495168.html
標籤:javascript html for循环 前锋
上一篇:在回圈中檢查陣列是升序還是降序
