Created
April 13, 2021 19:57
-
-
Save teasmade/0be58f62556d0b53dc4e470b924a4ea6 to your computer and use it in GitHub Desktop.
Distance between 2 points test
This file contains hidden or 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
const quaiFM = [47.2076056402, -1.55753246791]; | |
const testMarker = [47.21, -1.552]; | |
const rdgReze = [47.19316, -1.549212]; | |
const plWalRou = [47.2277747611, -1.55214798607]; | |
// function to calculate distance - expects array of lat / long for each param | |
// this is no good due to the difference in conversion offset degrees / metres between lat and long! | |
calcDistance = function (origin, dest) { | |
const xOffset = origin[1] - dest[1]; | |
const yOffset = origin[0] - dest[0]; | |
const distance = Math.sqrt(xOffset * xOffset + yOffset * yOffset); | |
// distance hack - approx value for latitude of Nantes DOESNT WORK, leads to c. 1km error for 4km N / S journey across Nantes | |
console.log(distance * 82111); | |
}; | |
// better function to calculate distance, accurate lat / long offset | |
function getDistance(origin, destination) { | |
function toRadian(degree) { | |
return (degree * Math.PI) / 180; | |
} | |
// return distance in meters | |
const lon1 = toRadian(origin[1]); | |
const lat1 = toRadian(origin[0]); | |
const lon2 = toRadian(destination[1]); | |
const lat2 = toRadian(destination[0]); | |
const deltaLat = lat2 - lat1; | |
const deltaLon = lon2 - lon1; | |
const a = | |
Math.pow(Math.sin(deltaLat / 2), 2) + | |
Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(deltaLon / 2), 2); | |
const c = 2 * Math.asin(Math.sqrt(a)); | |
const EARTH_RADIUS = 6371; | |
return c * EARTH_RADIUS * 1000; | |
} | |
console.log(getDistance(rdgReze, plWalRou)); | |
console.log(getDistance(quaiFM, testMarker)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment