I am looking for a JavaScript function who returns the nearest neighbor of a number. e.g: I am having a coordinate 12,323432/12,234223 and i want to know the nearest coordinate of a set of 20 other coordinates in a database. How to handle that?
Advertisement
Answer
The following 3 functions find the nearest coordinate from a javascript array using the Haversine formula.
JavaScript
x
26
26
1
function toRad(Value) {
2
/** Converts numeric degrees to radians */
3
return Value * Math.PI / 180;
4
}
5
6
function haversine(lat1,lat2,lng1,lng2){
7
rad = 6372.8; // for km Use 3961 for miles
8
deltaLat = toRad(lat2-lat1);
9
deltaLng = toRad(lng2-lng1);
10
lat1 = toRad(lat1);
11
lat2 = toRad(lat2);
12
a = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) + Math.sin(deltaLng/2) * Math.sin(deltaLng/2) * Math.cos(lat1) * Math.cos(lat2);
13
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
14
return rad * c;
15
}
16
function calculate(){
17
var result = haversine(lat1,coordArray [0][0],lng1,coordArray [0][1]);
18
for (var i=1;i<coordArray.length;i++){
19
var ans = haversine(lat1,coordArray [i][0],lng1,coordArray [i][1]);
20
if (ans < result){//nearest
21
result = ans;
22
}
23
}
24
document.write("Result " +result);
25
}
26