We often have to list the stores closest to a zip code and show the distance between the two points as well.
The solution is performed within SQL itself (MSSQL in this case, but can probably be easily modified for other databases).
<cfset radius = 111.3195> <!--- km --->
<cfset radius = 69.17073> <!--- mi --->
<cfset distance = 100> <!--- distance from the point you are searching for --->
<!---
degrees - tweak according to your needs / it should be related to the distance you set above
this will help limit the records searched instead of having to perform the calculation for every record
--->
<cfset searchDegree = 4>
<cfset latitude = 0> <!--- pass in this value --->
<cfset longitude = 0> <!--- pass in this value --->
<cfquery name="closestStore" datasource="#application.dsn#">
Select #radius# * Degrees(
acos(
sin(radians(#latitude#))*sin(radians(store.latitude))
+
cos(radians(#latitude#)) * cos(radians(store.latitude)) * cos(radians(store.longitude)-radians(#longitude#))
)
) As distance,
store.name
From store
Where
(
store.latitude between
#latitude# - #searchDegree#
and
#latitude# + #searchDegree#
)
And
(
store.longitude between
#longitude# - #searchDegree#
and
#longitude# + #searchDegree#
)
And
(
#radius# * Degrees(
acos(
sin(radians(#latitude#))*sin(radians(store.latitude))
+
cos(radians(#latitude#)) * cos(radians(store.latitude)) * cos(radians(store.longitude)-radians(#longitude#))
)
)
) < #distance#
Order By distance, name
</cfquery>
+