Forked from igorjs/calcDistanceBetweenTwoPoints.js
Created
September 11, 2023 16:17
-
-
Save Vuzereus/60711c5c5b226b208017d06b7d6da27d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function calcDistanceInMetresBetweenTwoPoints(Point1, Point2) { | |
const EARTH_RADIUS = 6371e3; // 6,371,000 metres | |
const latitude1 = (Point1.lat * Math.PI) / 180; | |
const latitude2 = (Point2.lat * Math.PI) / 180; | |
const deltaLatitude = ((Point2.lat - Point1.lat) * Math.PI) / 180; | |
const deltaLongitude = ((Point2.lon - Point1.lon) * Math.PI) / 180; | |
const angle = | |
Math.sin(deltaLatitude / 2) * Math.sin(deltaLatitude / 2) + | |
Math.cos(latitude1) * Math.cos(latitude2) * Math.sin(deltaLongitude / 2) * Math.sin(deltaLongitude / 2); | |
const theta = 2 * Math.atan2(Math.sqrt(angle), Math.sqrt(1 - angle)); | |
const distance = EARTH_RADIUS * theta; | |
return Math.round(distance * 100) / 100; // distance in metres, rounded up! | |
} | |
// Test | |
const PointA = { lat: -33.84887785692942, lon: 151.2106926524797 }; | |
const PointB = { lat: -33.85469551244261, lon: 151.22570778047384 }; | |
const result = calcDistanceInMetresBetweenTwoPoints(PointA, PointB); | |
console.log(result); // 1530.05 metres |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment