【问题标题】:Sort array based on geolocation根据地理位置对数组进行排序
【发布时间】:2023-03-31 15:12:01
【问题描述】:
我想根据我的位置从最近(到我的位置)到最远对城市数组/对象进行排序
我有从数据库中获取的位置列表
我将如何使用 javascript 和 HTML5 地理位置解决这个问题?
我有这样的事情:
示例:
var locations= [{"name":"location1" "latitude" :"31.413165123"
"longitude":"40.34215241"},{"name":"location2" "latitude" :"31.413775453"
"longitude":"40.34675341"}]
我想按离我最近的位置对这些位置进行排序
【问题讨论】:
标签:
javascript
sorting
geolocation
【解决方案1】:
存储您的位置,创建一个计算两点之间距离的函数,然后使用sort 方法:
function dist({latitude: lat1, longitude: long1}, {latitude: lat2, longitude: long2}) {
// I'm not very good at geography so I don't know how to calculate exactly the distance given latitudes and longitudes.
// I hope you can figure it out
// the function must return a number representing the distance
}
navigator.geolocation.getCurrentPosition(({coords}) => {
coords.latitude = parseFloat(coords.latitude)
corrds.longitude = parseFloat(coords.longitude)
locations.sort((p1, p2) => dist(coords, {latitude: parseFloat(p1.latitude), longitude: parseFloat (p1.longitude)}) -
dist(coords, {latitude: parseFloat(p2.latitude), longitude: parseFloat(p2.longitude)}))
})
希望对你有帮助
【解决方案2】:
FIRST:提供的数组已损坏(我在字段之间添加了逗号)。
var locations = [{
"name": "location1",
"latitude": "31.413165123",
"longitude": "40.34215241"
}, {
"name": "location2",
"latitude": "31.413775453",
"longitude": "40.34675341"
}];
您需要利用自定义排序函数,该函数需要根据比较 2 个项目返回 1、-1 或 0。
var myLong = 42.0; // whatever your location is
var myLat = 3.16; // whatever your location is
locations.sort( function (a, b) {
// This is untested example logic to
// help point you in the right direction.
var diffA = (Number(a.latitude) - myLat) + (Number(a.longitude) - myLong);
var diffB = (Number(b.latitude) - myLat) + (Number(b.longitude) - myLong);
if(diffA > diffB){
return 1;
} else if(diffA < diffB){
return -1;
} else {
return 0; // same
}
} );