基于地理位置对数组进行排序

时间:2018-04-04 16:52:15

标签: javascript sorting geolocation

我想根据我的位置从最近的(到我的位置)到最远的

对城市的数组/对象进行排序

我有从数据库获得的位置列表 我如何使用javascript和HTML5地理定位来解决这个问题?

我有这样的事情: 例如:

var locations= [{"name":"location1" "latitude" :"31.413165123" 
"longitude":"40.34215241"},{"name":"location2" "latitude" :"31.413775453" 
"longitude":"40.34675341"}]

我希望按离我的位置最近的方式对这些位置进行排序

2 个答案:

答案 0 :(得分:0)

存储您的位置,创建一个计算两点之间距离的函数,然后使用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)}))
})

希望它可以帮到你

答案 1 :(得分:0)

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
    }

} );