CFLib.org – Common Function Library Project

getHaversineDistance(lat1, lon1, lat2, lon2[, units])

Last updated January 8, 2013

author

Henry Ho

Version: 0 | Requires: CF9 | Library: MathLib

Description:
Calculates distance between Latitude/Longitude points using haversine formula : http://www.movable-type.co.uk/scripts/latlong.html

Return Values:
Returns numeric distance between the two points. Units varies, default is miles.

Example:

#getDistance(1, 1, 2, 2)#

Parameters:

Name Description Required
lat1 latitude of first point Yes
lon1 longitude of first point Yes
lat2 latitude of second point Yes
lon2 longitude of second point Yes
units Units for return value. Default is miles. No

Full UDF Source:

/**
 * Calculates distance between Latitude/Longitude points using haversine formula.
 * 
 * @param lat1 	 latitude of first point (Required)
 * @param lon1 	 longitude of first point (Required)
 * @param lat2 	 latitude of second point (Required)
 * @param lon2 	 longitude of second point (Required)
 * @param units 	 Units for return value. Default is miles. (Optional)
 * @return Returns numeric distance between the two points. Units varies, default is miles. 
 * @author Henry Ho (henryho167@gmail.com) 
 * @version 0, January 8, 2013 
 */
function getDistance(lat1, lon1, lat2, lon2, units = 'miles')
{
	// earth's radius. Default is miles.
	var radius = 3959;
	if (arguments.units EQ 'kilometers' )
		radius = 6371;
	else if (arguments.units EQ 'feet')
		radius = 20903520;
	
	var toRad = pi() / 180;
	var dLat = (lat2-lat1) * toRad;
	var dLon = (lon2-lon1) * toRad; 
	var a = sin(dLat/2)^2 + cos(lat1 * toRad) * cos(lat2 * toRad) * sin(dLon/2)^2; 
	var c = 2 * createObject("java","java.lang.Math").atan2(sqr(a), sqr(1-a));
	
	return radius * c;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson