This is a useful script for calculating the distance between two points using their coordinates.

Very useful as part of a Lookup function.Â I can see many applications for this code.Â

**Note**: read the notes in the code carefully so you implement it correctly the first time.Â Original code location: here

The code below isn’t perfect by the way.Â Check out this pageÂ if you want to know more about the math and special cases for calculating distance.

What’s that you say? You need a coordinates database? This one is pretty good: http://download.geonames.org/export/zip/

Here is a site with an ASP function for pulling coordinates via a client browser’s IP address: http://forum.ipinfodb.com/viewtopic.php?f=7&t=269

<%

‘Â This routine calculates the distance between two points

‘ (given theÂ latitude/longitude of those points). It is being

‘used to calculateÂ distance between two ZIP Codes or Postal

‘Codes using ourÂ Â Â ZIPCodeWorld(TM) and PostalCodeWorld(TM)

‘ products.

‘Definitions

‘Â Â Â South latitudes are negative, east longitudes are

‘positiveÂ Â Â Â Â Â Â Â Â Â‘Â Passed to function

‘lat1, lon1 = Latitude and Longitude of point 1

‘(in decimal degrees)

‘lat2, lon2 = Latitude and Longitude of point 2

‘(in decimal degrees)

‘unit = the unit you desire for results

‘where ‘M’ is statute miles (default)

”K’ is kilometers

‘N’ is nautical miles

”United States ZIP Code/ Canadian Postal Code databases with

‘latitude & longitude are available at

‘http//www.zipcodeworld.com

‘For enquiries, please contact sales@zipcodeworld.comÂ Â‘Official Web site http//www.zipcodeworld.com

‘Hexa Software Development Center Â¸ All Rights Reserved 2003

const pi = 3.14159265358979323846

Function distance(lat1, lon1, lat2, lon2, unit)

Â Dim theta, dist

Â theta = lon1 – lon2

Â dist = sin(deg2rad(lat1)) * sin(deg2rad(lat2)) + cos(deg2rad(lat1)) * cos(deg2rad(lat2)) * cos(deg2rad(theta))

Â dist = acos(dist)

Â dist = rad2deg(dist)

Â distance = dist * 60 * 1.1515

Â Select Case ucase(unit)

Â Â Â Case “K”

Â Â Â Â Â distance = distance * 1.609344

Â Â Â Case “N”

Â Â Â Â Â distance = distance * 0.8684

Â End Select

End Function

‘

‘Â This function get the arccos function from arctan function

‘

Function acos(rad)

Â If Abs(rad) <> 1 Then

Â Â Â acos = pi/2 – Atn(rad / Sqr(1 – rad * rad))

Â ElseIf rad = -1 Then

Â Â Â acos = pi

Â End If

End function

‘

‘Â This function converts decimal degrees to radians

‘

Function deg2rad(Deg)

Â deg2rad = cdbl(Deg * pi / 180)

End Function‘

‘Â This function converts radians to decimal degrees

‘

Function rad2deg(Rad)

Â rad2deg = cdbl(Rad * 180 / pi)

End Function‘Demo

response.write distance(32.9697, -96.80322, 29.46786, -98.53506, “M”) & ” Miles<br>”

response.write distance(32.9697, -96.80322, 29.46786, -98.53506, “K”) & ” Kilometers<br>”

response.write distance(32.9697, -96.80322, 29.46786, -98.53506, “N”) & ” Nautical Miles<br>”%>