Skip to content

Instantly share code, notes, and snippets.

@khriztianmoreno
Created September 4, 2017 15:33
Show Gist options
  • Save khriztianmoreno/d89c44d6aa35907b46e1bcd3e1f5eec7 to your computer and use it in GitHub Desktop.
Save khriztianmoreno/d89c44d6aa35907b46e1bcd3e1f5eec7 to your computer and use it in GitHub Desktop.
Midpoint between two geographical points
//-- Define middle point function
const middlePoint = (lat1, lng1, lat2, lng2) => {
//-- Define radius function
if (typeof (Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
}
//-- Define degrees function
if (typeof (Number.prototype.toDeg) === "undefined") {
Number.prototype.toDeg = function () {
return this * (180 / Math.PI);
}
}
//-- Longitude difference
const dLng = (lng2 - lng1).toRad();
//-- Convert to radians
lat1 = lat1.toRad();
lat2 = lat2.toRad();
lng1 = lng1.toRad();
const bX = Math.cos(lat2) * Math.cos(dLng);
const bY = Math.cos(lat2) * Math.sin(dLng);
const lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt((Math.cos(lat1) + bX) * (Math.cos(lat1) + bX) + bY * bY));
const lng3 = lng1 + Math.atan2(bY, Math.cos(lat1) + bX);
//-- Return result
return [lat3.toDeg(), lng3.toDeg()];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment