Useful Javascript function for checking distance between 2 points

Returns distance in kilometres. (i.e. return value of 0.01 = 10m)

class Utils {
    static getDistanceBetweenPoints(lat_1, lng_1, lat_2, lng_2) {
        return (6371 *
            Math.acos(
                Math.cos(Math.radians(lat_1)) *
                Math.cos(Math.radians(lat_2)) *
                Math.cos(Math.radians(lng_2) -
                    Math.radians(lng_1)) +
                Math.sin(Math.radians(lat_1)) *
                Math.sin(Math.radians(lat_2))))
    }
}

Math.radians = function (degrees) {
    return degrees * Math.PI / 180
};
1 Like

Hi Edwin,

Actually we encourage our users to tap on Turf Library (OS4Geo Consortium) for standardized spatial functions like distance finding. It is free and open source too. :slight_smile:

You can find this function @ https://turfjs.org/docs#distance

Apart from Turfjs, we also recommend a list of open-source projects that are pretty awesome. https://docs.onemap.sg/#helper-libraries

Hope you are proceeding well with your application!!

Regards,
Kai

1 Like

Ah! Wish I knew that sooner :slight_smile:

No problem at all Edwin!

We are here to learn from one another :smiley: