Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
lat/lon distance in GAS and VBA
// see http://www.movable-type.co.uk/scripts/latlong.html for maths
/**
* given lat, distance in km, and heading calculate new lat
* @param {number} mLat origin latitude
* @param {number} d distance in km
* @param {number} heading heading (degrees)
* @return {number} destination lat
*/
function getLatFromDistance(mLat, d , heading ) {
var lat = toRadians(mLat);
var newLat = Math.asin(Math.sin(lat) *
Math.cos(d / earthRadius()) +
Math.cos(lat) *
Math.sin(d / earthRadius()) *
Math.cos(heading));
return fromRadians(newLat);
}
/**
* given lat,lon, distance in km, and heading calculate new lon
* @param {number} mLat origin latitude
* @param {number} mLon origin longitude
* @param {number} d distance in km
* @param {number} heading heading (degrees)
* @return {number} destination lat
*/
function getLonFromDistance(mLat, mLon, d, heading) {
var lat = toRadians(mLat);
var lon = toRadians(mLon);
var newLat = toRadians(getLatFromDistance(mLat, d, heading));
var newLon = lon +
Math.atan2(
Math.sin(heading) * Math.sin(d / earthRadius()) * Math.cos(lat),
Math.cos(d / earthRadius()) - (Math.sin(lat) * Math.sin(newLat))
);
return fromRadians (newLon);
}
' see http://www.movable-type.co.uk/scripts/latlong.html for maths
' VBA version
Public Function getLatFromDistance(mLat As Double, d As Double, heading As Double) As Double
Dim lat As Double
' convert ro radians
lat = toRadians(mLat)
getLatFromDistance = _
fromRadians( _
Application.WorksheetFunction.Asin(sIn(lat) * _
Cos(d / earthRadius) + _
Cos(lat) * _
sIn(d / earthRadius) * _
Cos(heading)))
End Function
Public Function getLonFromDistance(mLat As Double, mLon As Double, d As Double, heading As Double) As Double
Dim lat As Double, lon As Double, newLat As Double
' convert ro radians
lat = toRadians(mLat)
lon = toRadians(mLon)
newLat = toRadians(getLatFromDistance(mLat, d, heading))
getLonFromDistance = _
fromRadians( _
(lon + Application.WorksheetFunction.Atan2(Cos(d / earthRadius) - _
sIn(lat) * _
sIn(newLat), _
sIn(heading) * _
sIn(d / earthRadius) * _
Cos(lat))))
End Function
@brucemcpherson

This comment has been minimized.

Copy link
Owner Author

commented Oct 2, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.