Last active
April 20, 2018 04:51
-
-
Save thu-san/be31f81f233653ce2b2e66f3cd03486c to your computer and use it in GitHub Desktop.
JavaScript (Pure) function to calculate the destination point by start point (latitude, longitude [numeric]), bearing (numeric degrees) and distance (km).
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
/*! | |
* JavaScript (Pure) function to calculate the destination point by start point (latitude, longitude [numeric]), bearing (numeric degrees) and distance (km). | |
* | |
* Optimized from https://stackoverflow.com/a/2637079/6160436 | |
*/ | |
(function(){ | |
function toRad(val) { | |
return val * Math.PI / 180; | |
}; | |
function toDeg(val) { | |
return val * 180 / Math.PI; | |
}; | |
/** | |
* calculate | |
* @param {Decimal} startLat - Starting latitude | |
* @param {Decimal} startLng - Starting longitude | |
* @param {Number} brng - Bearning: From 0=North | |
* @param {Number} dist - Distance in kilometers | |
* | |
* @return {Object} Return {lat: Decimal(), lng: Decimal()} | |
*/ | |
window.calcDestLatlng = function(startLat, startLng, brng, dist) { | |
dist = dist / 6371; | |
brng = toRad(brng); | |
startLat = toRad(startLat); | |
startLng = toRad(startLng); | |
var destLat = Math.asin(Math.sin(startLat) * Math.cos(dist) + | |
Math.cos(startLat) * Math.sin(dist) * Math.cos(brng)); | |
var destLng = startLng + Math.atan2(Math.sin(brng) * Math.sin(dist) * | |
Math.cos(startLat), | |
Math.cos(dist) - Math.sin(startLat) * | |
Math.sin(destLat)); | |
if (isNaN(destLat) || isNaN(destLng)) return null; | |
return { | |
lat: toDeg(destLat), | |
lng: toDeg(destLng) | |
}; | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment