我想根据我的位置从最近(到我的位置)到最远对城市数组/对象进行排序
我有从数据库获取的位置列表,我如何使用javascript和HTML5地理定位来解决这个问题?
我有类似这样的东西:示例:
var locations= [{"name":"location1" "latitude" :"31.413165123"
"longitude":"40.34215241"},{"name":"location2" "latitude" :"31.413775453"
"longitude":"40.34675341"}]我想根据离我最近的位置对这些位置进行排序
发布于 2018-04-05 01:18:34
存储您的位置,创建一个计算两点之间距离的函数,然后使用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)}))
})希望能对你有所帮助
发布于 2018-04-05 01:58:49
首先:提供的数组被破坏了(我在字段之间添加了逗号)。
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
}
} );https://stackoverflow.com/questions/49656424
复制相似问题