繁体   English   中英

在js循环中获取上一个和当前光标的差异

[英]get difference of previous and current cursor in js loop

我有一个数组,其中 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 ,我该怎么做最理想?

似乎有点简单,但我可能根本不明白这个问题,如果问题是如何通过与上一个条目的比较来循环数组,有几种方法可以做到,一种方法如下所示

 // 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 个点之间的直线,并且确实考虑到行星不是球体。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM