gpt4 book ai didi

javascript - 在坐标数组中找到最接近给定的点

转载 作者:行者123 更新时间:2023-12-02 02:44:33 24 4
gpt4 key购买 nike

我有一个有 2 个属性的对象 - 纬度和经度。我想通过考虑这两个属性来从对象数组中获取最接近的匹配。

obj = {latitude: 55.87, longitude: 4.20}

[
{
"latitude": 55.85,
"longitude": 4.22
},
{
"latitude": 55.89,
"longitude": 4.16
},
{
"latitude": 55.88,
"longitude": -4.24
}
]

我需要获取最接近匹配的数组索引。

最佳答案

有一个Haversine formula计算您的点与数组中每个点之间的球面距离,例如使用Array.prototype.reduce() :

const haversine = ({longitude: lonA, latitude: latA}, {longitude: lonB, latitude: latB}) => {
const {PI, sin, cos, atan2} = Math,
r = PI/180,
R = 6371,
deltaLat = (latB - latA)*r,
deltaLon = (lonB - lonA)*r,
a = sin(deltaLat / 2)**2 + cos(cos(latB*r)*latA*r) * sin(deltaLon /2)**2,
c = 2 * atan2(a**0.5, (1 - a)**0.5),
d = R * c
return d
},

obj = {latitude: 55.87, longitude: 4.20},

arr = [{"latitude":55.85,"longitude":4.22},{"latitude":55.89,"longitude":4.16},{"latitude":55.88,"longitude":-4.24}],

{closest} = arr.reduce((r,o) => {
const distance = haversine(o, obj)
distance < r.minDistance || !r.closest &&
(r.closest = o, r.minDistance = distance)
return r
}, {closest: null, minDistance: null})

console.log(closest)
.as-console-wrapper{min-height:100%;}

关于javascript - 在坐标数组中找到最接近给定的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63013252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com