如何在javascripts中按经度纬度距离对数组项进行排序? [英] How to sort array items by longitude latitude distance in javascripts?

查看:169
本文介绍了如何在javascripts中按经度纬度距离对数组项进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注6个位置的JSON数组。有没有什么方法可以根据经度和纬度对这些数据进行排序?

I am having following JSON array of 6 locations. Is there any way sort these based on longitude and latitude where nearby locations come next in the array?

[
{"id" : 279, "longitude":79.853239,"latitude":6.912283},
{"id" : 284, "longitude":79.865699,"latitude":6.885697},
{"id" : 13,  "longitude":79.851187,"latitude":6.912220},
{"id" : 282, "longitude":79.858904,"latitude":6.871041},
{"id" : 281, "longitude":79.853346,"latitude":6.899757},
{"id" : 16,  "longitude":79.854786,"latitude":6.894039}
]

排序可以从第一项开始,结果应该是这样的

Sorting can be started from first item and result should be something like this

[
{"id" : 279, "longitute":79.853239,"latitude":6.912283},
{"id" : 13,  "longitute":79.851187,"latitude":6.912220},
{"id" : 281, "longitute":79.853346,"latitude":6.899757},
{"id" : 16,  "longitute":79.854786,"latitude":6.894039},
{"id" : 284, "longitute":79.865699,"latitude":6.885697},
{"id" : 282, "longitute":79.858904,"latitude":6.871041}
]


推荐答案

Pro通过添加另一个名为distance的属性解决了blem。使用以下函数计算两点之间的距离

Problem resolved by adding another attribute called distance. Used following function to calculate distance between two points

function calculateDistance(lat1, lon1, lat2, lon2, unit) {
  var radlat1 = Math.PI * lat1/180
  var radlat2 = Math.PI * lat2/180
  var radlon1 = Math.PI * lon1/180
  var radlon2 = Math.PI * lon2/180
  var theta = lon1-lon2
  var radtheta = Math.PI * theta/180
  var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
  dist = Math.acos(dist)
  dist = dist * 180/Math.PI
  dist = dist * 60 * 1.1515
  if (unit=="K") { dist = dist * 1.609344 }
  if (unit=="N") { dist = dist * 0.8684 }
  return dist
}

然后使用上述函数计算数组中每个项目的距离。然后按距离排序数组。

Then calculated distance for each item in the array by using above function. Then sorted array by distance.

for ( i = 0; i < uniqueNodes.length; i++) {
  uniqueNodes[i]["distance"] = calculateDistance(uniqueNodes[0]["latitude"],uniqueNodes[0]["longitute"],uniqueNodes[i]["latitude"],uniqueNodes[i]["longitute"],"K");
}

uniqueNodes.sort(function(a, b) { 
  return a.distance - b.distance;
});

这篇关于如何在javascripts中按经度纬度距离对数组项进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆