Skip to content

Instantly share code, notes, and snippets.

@stefanolaru
Created May 8, 2020 05:57
Show Gist options
  • Save stefanolaru/70a936f7f5ccd45942bc3efb8cd9de27 to your computer and use it in GitHub Desktop.
Save stefanolaru/70a936f7f5ccd45942bc3efb8cd9de27 to your computer and use it in GitHub Desktop.
calculate distance between 2 map points
'use strict';
const toRadians = degrees => (Math.PI / 180) * degrees;
const toDegrees = radians => (180 * radians) / Math.PI;
const earthRadius = 6371e3; // metres
module.exports.getDistance = (ne_lat, sw_lat, ne_lng, sw_lng) => {
var lat1 = toRadians(ne_lat);
var lat2 = toRadians(sw_lat);
var lat_diff = toRadians(sw_lat - ne_lat);
var lng_diff = toRadians(sw_lng - ne_lng);
var a =
Math.sin(lat_diff / 2) * Math.sin(lat_diff / 2) +
Math.cos(lat1) *
Math.cos(lat2) *
Math.sin(lng_diff / 2) *
Math.sin(lng_diff / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
// return distance between points in meters
return earthRadius * c;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment