Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thu-san/be31f81f233653ce2b2e66f3cd03486c to your computer and use it in GitHub Desktop.
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).
/*!
* 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