gpt4 book ai didi

javascript - 从数组中获取最近的纬度和经度

转载 作者:行者123 更新时间:2023-12-02 06:57:07 25 4
gpt4 key购买 nike

我正在尝试编写一个以性能为导向的数组查找,它将返回相对于用户当前位置最近的经度和纬度。

一个问题是我的数组中有 5000 个位置,我需要遍历所有结果以尽可能快地返回最接近的结果,我也遇到了过滤器问题,因为目前它返回了错误的结果(我认为这是由于查找只寻找最接近当前的负面)

这是我的代码:

    if(has('geolocation')){

navigator.geolocation.getCurrentPosition((position) => {

// Example result from getCurrentPosition (this is my exact location)
//
// position.coords = {
// latitude: 51.4523,
// longitude: -0.9724
// }

// This is the nearest location
//
// location = {
// latitude: 51.457495699999996,
// longitude: -0.973083
// }

// This is the location my filter keeps returning
//
// location = {
// latitude: "50.6931",
// longitude: "-4.0094",
// name: "Yes Tor"
// }

let closest = this.locations.filter((location) => {
console.log(location, position.coords);
return location.latitude <= position.coords.latitude && location.longitude <= position.coords.longitude;
}).pop();


console.log(closest); //Is incorrect

});

}

我已经评论了我目前的结果,我的问题是是否有更快的方法来做到这一点,以及是否有一种方法可以使电流的负值和正值最接近。

如果有人需要这里是数组结构的例子(长度为5968)

            let this.locations = [
{
elevation: "936.0",
id: "350001",
latitude: "56.8716",
longitude: "-4.1969",
name: "A' Bhuidheanach Bheag",
region: "ta",
unitaryAuthArea: "Perth and Kinross"
},
{
elevation: "999.0",
id: "350024",
latitude: "57.6926",
longitude: "-5.1328",
name: "A'Chailleach (Fannaich Region)",
region: "he",
unitaryAuthArea: "Highland"
}
]

最佳答案

求两点之间的距离(Haversine 公式):

function distance(position1,position2){
var lat1=position1.latitude;
var lat2=position2.latitude;
var lon1=position1.longitude;
var lon2=position2.longitude;
var R = 6371000; // metres
var φ1 = lat1.toRadians();
var φ2 = lat2.toRadians();
var Δφ = (lat2-lat1).toRadians();
var Δλ = (lon2-lon1).toRadians();

var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

var d = R * c;
return d;
}

现在使用:

var closest=locations[0];
var closest_distance=distance(closest,position.coords);
for(var i=1;i<locations.length;i++){
if(distance(locations[i],position.coords)<closest_distance){
closest_distance=distance(locations[i],position.coords);
closest=locations[i];
}
}

这具有 O(n) 的复杂性。对于大多数情况下足够好的 5000 个位置。

关于javascript - 从数组中获取最近的纬度和经度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29118745/

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