Zip Code Radius Search
9/23/2004 11:10:57 AM
This code will show you how you can search within a specific radius of an area using a zip code.
This code snip provides a way of implementing a radius search within your application. One of the first things you need to do is obtain a database of zipcodes with latitude and longitude coordinates. You can do a search on Google and find databases containing the information for under $100.
Dim HighLatitude Dim LowLatitude Dim LowLongitude Dim HighLongitude
Function GetDistance(Lat1, Long1, Lat2, Long2, Unit) Dim x x = (sin(DegToRads(Lat1)) * sin(DegToRads(Lat2)) + cos(DegToRads(Lat1)) * _ cos(DegToRads(Lat2)) * cos(abs((DegToRads(long2))-(DegToRads(long1))))) ' Get Acos(x) x = atn((sqr(1-x^2))/x) ' Get distance in kilometers GetDistance = 1.852 * 60.0 * ((x/pi)*180) ' Convert units if necessary Select Case ucase(Unit) Case "M" GetDistance = GetDistance / 1.609344 Case "N" GetDistance = GetDistance / 1.852 End Select End Function '_________________________________ Sub SetRadius(iRadius, iZip) ' THIS VARIABLE SETS THE RADIUS IN MILES
Dim rs, SQLQ, iStartlat, iStartlong, LatRange, LongRange SQLQ = "SELECT LATITUDE, LONGITUDE FROM ZIPCODES WHERE ZIPCODE = '" & iZip & "'" Set rs = DBConn.Execute(SQLQ) If Not rs.EOF Then iStartlat = rs(0) iStartlong = rs(1) End If rs.Close Set rs = Nothing LatRange = iRadius / ((6076 / 5280) * 60) LongRange = iRadius / (((cos(cdbl(iStartLat * 3.141592653589 / 180)) * 6076.) / 5280.) * 60) LowLatitude = iStartlat - LatRange HighLatitude = iStartlat + LatRange LowLongitude = iStartlong - LongRange HighLongitude = iStartlong + LongRange End Sub '_________________________________________________________ 'condition for building SQL String:
If Request("radius") <> "0" Then Call SetRadius(CLng(Request("radius")), Request("zipcode")) SQLQ = SQLQ & JoinWord & " Company_Postal_Code IN(SELECT ZIPCODE " & _ "FROM ZIPCODES WHERE LATITUDE <= " & HighLatitude & " AND LATITUDE >= " & LowLatitude & _ " AND LONGITUDE >= " & LowLongitude & _ " AND LONGITUDE <= " & HighLongitude & ")" JoinWord = " AND " End If
|