Skip to content

JavaScript function nearest neighbor

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?

Answer

The following 3 functions find the nearest coordinate from a javascript array using the Haversine formula.

function toRad(Value) {
    /** Converts numeric degrees to radians */
    return Value * Math.PI / 180;
}

function haversine(lat1,lat2,lng1,lng2){
    rad = 6372.8; // for km Use 3961 for miles
    deltaLat = toRad(lat2-lat1);
    deltaLng = toRad(lng2-lng1);
    lat1 = toRad(lat1);
    lat2 = toRad(lat2);
    a = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) + Math.sin(deltaLng/2) * Math.sin(deltaLng/2) * Math.cos(lat1) * Math.cos(lat2); 
    c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    return  rad * c;
}
function calculate(){
    var result = haversine(lat1,coordArray [0][0],lng1,coordArray [0][1]);
        for (var i=1;i<coordArray.length;i++){ 
        var ans = haversine(lat1,coordArray [i][0],lng1,coordArray [i][1]);
        if (ans < result){//nearest 
            result = ans;
        }       
    }
    document.write("Result " +result);
}