How to sort array items by longitude latitude distance in javascripts?

廉价感情. 提交于 2019-11-28 19:02:14
Tharik Kanaka

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;
});

You could loop through the array, and nest another loop that finds the nearest one.

var finalArray = [];

while(entries){
  //for each item
  while(what's left){
    //find the nearest against the current item
    //push to final
  }
}

This assumes that the very first in the array is the point of reference, that what comes next would be the nearest to that point, and so on.

Anyone else looking to do this, if you have the longitude and latitude avaliable, you can just sort linearly on it to get a simple line diagram like below. this will give you a rise/run linear result.

var $array = [
[79.853239, 6.912283, 279],
[79.851187, 6.912220, 13],
[79.853346, 6.899757, 281],
[79.854786, 6.894039, 16],
[79.865699, 6.885697, 284],
[79.858904, 6.87104, 282]
]

function sortLngLat(a, b){
var x = a[0] / a[1];
var y = b[0] / b[1];
}
var sortedArray = $array.sort(sortLngLat);
console.log(sortedArray);

output should be like graph below and you can tweak your values with negatives and positives to get different angles and directions.

 ---------------
|       |  /    |
| -1/1  | / 1/1 |
|       |/      |
|--------------
|      /|       |
|-1/-1/ | 1/-1  |
|    /  |       |
 ---------------
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!