I am facing this problem in javascript : I have lot of random map coordinates(latitude,longitude) stored in an array like
var coordinates = [
[64,22],[55,33],[28,35],[...,...]
]
I also have a method that calculates distance between two of those points
like
var getDistance =function(point1,point2)
{
return L.dist(point1,point2);//leaflet method
}
then here is my problem :
how to sort my array to have the distance sorted by closest from first coordinate then closest to second, then closest to third, then closest to fourth... ? anyone have a solution for this... im lost :(
edit 1 :
I tried to resolve the problem with a nested for loop ... but the results seems to be wrong.
var cloestIndex = 1;
var closestDistance = 99999999;
for (var i = 0; i < coords.length; i++) {
for (var j = i + 1; j < coords.length; j++) {
if ((Map().distance(coords[i], coords[j]) < closestDistance) &&
(Map().distance(coords[i], coords[j]) != 0){
closestDistance = (Map().distance(coords[i], coords[j]));
closestIndex = j;
}
}
console.log("CD", closestDistance + "(" + closestIndex + ")");
finalArray.push(coords[closestIndex]);
coords.splice(closestIndex, 0);
cloestDistance = 9999999;
}