Postal Codes in a Radius

Test our free Canadian Postal Code Radius Tool and download our free scripts that are perfectly compatible with our Postal Code databases.






Result:
K1P 1J1 Ottawa, ON (0 km)
K2P 1L4 Ottawa, ON (0.1 km)
K2P 2C4 Ottawa, ON (0.1 km)
K1P 5J3 Ottawa, ON (0.1 km)
K2P 3C3 Ottawa, ON (0.1 km)
K1P 5J4 Ottawa, ON (0.1 km)
K2P 2P8 Ottawa, ON (0.1 km)
K1A 1J4 Ottawa, ON (0.1 km)
K2P 2L7 Ottawa, ON (0.1 km)
K1P 1C3 Ottawa, ON (0.1 km)
K2P 2P7 Ottawa, ON (0.1 km)
K1P 5K8 Ottawa, ON (0.2 km)
K2P 2L2 Ottawa, ON (0.2 km)
K2P 2K3 Ottawa, ON (0.2 km)
K2P 2G5 Ottawa, ON (0.2 km)
K1P 1H7 Ottawa, ON (0.2 km)
K1P 1C7 Ottawa, ON (0.2 km)
K1P 5J2 Ottawa, ON (0.2 km)
K2P 0B1 Ottawa, ON (0.2 km)
K1P 5V5 Ottawa, ON (0.2 km)
K2P 1L5 Ottawa, ON (0.2 km)
K1A 0P4 Ottawa, ON (0.2 km)
K2P 1L7 Ottawa, ON (0.2 km)
K1P 5H1 Ottawa, ON (0.2 km)
K2P 1J2 Ottawa, ON (0.2 km)
K2P 0C4 Ottawa, ON (0.2 km)
K1R 1A4 Ottawa, ON (0.2 km)
K2P 0C2 Ottawa, ON (0.2 km)
K1P 5K7 Ottawa, ON (0.2 km)
K2P 0C3 Ottawa, ON (0.2 km)
K2P 1L6 Ottawa, ON (0.2 km)
K1P 1E3 Ottawa, ON (0.2 km)
K2P 1N8 Ottawa, ON (0.2 km)
K2P 0C1 Ottawa, ON (0.2 km)
K2P 1N9 Ottawa, ON (0.2 km)
K1A 1E3 Ottawa, ON (0.3 km)
K1P 1B7 Ottawa, ON (0.3 km)
K1P 6L7 Ottawa, ON (0.3 km)
K2P 0E9 Ottawa, ON (0.3 km)
K2P 1P2 Ottawa, ON (0.3 km)
K1P 5E7 Ottawa, ON (0.3 km)
K1P 5M1 Ottawa, ON (0.3 km)
K2P 0B9 Ottawa, ON (0.3 km)
K2P 0E8 Ottawa, ON (0.3 km)
K2P 0A1 Ottawa, ON (0.3 km)
K2P 1P3 Ottawa, ON (0.3 km)
K1P 5L9 Ottawa, ON (0.3 km)
K2P 1P1 Ottawa, ON (0.3 km)
K1N 9J2 Ottawa, ON (0.3 km)
K2P 1L9 Ottawa, ON (0.3 km)
K1P 6R2 Ottawa, ON (0.3 km)
K1A 1M8 Ottawa, ON (0.3 km)
K2P 0G1 Ottawa, ON (0.3 km)
K1P 6M7 Ottawa, ON (0.3 km)
K1A 0K5 Ottawa, ON (0.3 km)
K1A 0K7 Ottawa, ON (0.3 km)
K2P 0G2 Ottawa, ON (0.3 km)
K1A 0K2 Ottawa, ON (0.3 km)
K2P 2L5 Ottawa, ON (0.3 km)
K1A 0Z4 Ottawa, ON (0.3 km)
K2P 2H9 Ottawa, ON (0.3 km)
K2P 1P5 Ottawa, ON (0.3 km)
K1P 5M2 Ottawa, ON (0.3 km)
K2P 2E9 Ottawa, ON (0.3 km)
K1P 6A4 Ottawa, ON (0.3 km)
K1S 5R1 Ottawa, ON (0.3 km)
K1P 1C6 Ottawa, ON (0.3 km)
K2P 0G4 Ottawa, ON (0.3 km)
K2P 0E6 Ottawa, ON (0.3 km)
K1P 6K7 Ottawa, ON (0.3 km)
K2P 0C6 Ottawa, ON (0.3 km)
K2P 0E7 Ottawa, ON (0.3 km)
K2P 1L8 Ottawa, ON (0.3 km)
K1P 6M8 Ottawa, ON (0.3 km)
K1P 5Y7 Ottawa, ON (0.3 km)
K1P 5L7 Ottawa, ON (0.3 km)
K2P 2L1 Ottawa, ON (0.3 km)
K1P 5C4 Ottawa, ON (0.3 km)
K2P 0C8 Ottawa, ON (0.3 km)
K2P 2H1 Ottawa, ON (0.3 km)
K2P 2E3 Ottawa, ON (0.3 km)
K1P 5G3 Ottawa, ON (0.3 km)
K1P 6E2 Ottawa, ON (0.3 km)
K2P 1J3 Ottawa, ON (0.3 km)
K1P 5J6 Ottawa, ON (0.3 km)
K2P 2E1 Ottawa, ON (0.3 km)
K2P 1P7 Ottawa, ON (0.3 km)
K2P 0A7 Ottawa, ON (0.3 km)
K2P 0C5 Ottawa, ON (0.3 km)
K1P 5G4 Ottawa, ON (0.3 km)
K1P 5E9 Ottawa, ON (0.3 km)
K1P 1E7 Ottawa, ON (0.4 km)
K2P 0H8 Ottawa, ON (0.4 km)
K1P 5L6 Ottawa, ON (0.4 km)
K1P 1C9 Ottawa, ON (0.4 km)
K1R 7V9 Ottawa, ON (0.4 km)
K1P 5W1 Ottawa, ON (0.4 km)
K1P 5Z9 Ottawa, ON (0.4 km)
K2P 2P2 Ottawa, ON (0.4 km)
K1P 5H2 Ottawa, ON (0.4 km)
The result list on this website is limited to 100 entries... Of course this restrictions do not apply once your are hosting your own radius search.

Usage


A typical task for a Postal code radius search is for a "Store Locator" on a store's website. It allows website visitors to find the nearest stores to their home by entering their own Postal code.

It can be also very useful in social network or dating sites (show members in my area), in real estate listings or in any other classified ads directory.

Having our database of localities with their latitudes and longitudes enables you to locate the closest addresses to a set point (or within a maximum distance).

To help you implement a postal code radius or distance search, we offer free access to example codes in many scripting and programming languages like ASP (VBScript), ASP.NET (C#), PHP, Coldfusion and more...

PHP Script - Source Code PHP Script


  1. <?php  
  2. /*====================================================================== 
  3. ** ZIP Codes in a Radius in USA and Canada 
  4. ** 
  5. ** This PHP Script requires 4 GET parameters: zipcode, country (us/ca), radius, unit (miles/km) 
  6. ** Plus the database tables us and ca containing the ZIP Code-Lon/Lat data. 
  7. ** 
  8. ** Example call: tools_radius.php?zipcode=90210&country=us&radius=10&unit=miles 
  9. **  
  10. **  © 2012 https://www.zipcodesoft.com, All Rights Reserved 
  11. **====================================================================== 
  12. */  
  13.   
  14. /* ----------------------------- */  
  15. /* Connecting to MySQL server: */  
  16. /* ----------------------------- */  
  17. @mysql_connect($CFG_DB['db_host'], $CFG_DB['db_user'], $CFG_DB['db_pass'])  
  18.     or die("Error: mysql_connect() failed");  
  19.   
  20. /* ----------------------------- */  
  21. /* Selecting client character set: */  
  22. /* ----------------------------- */  
  23. mysql_set_charset('utf8');  
  24.   
  25. /* ----------------------------- */  
  26. /* Selecting database: */  
  27. /* ----------------------------- */  
  28. @mysql_select_db($CFG_DB['db_base'])  
  29.     or die("Error: mysql_select_db() failed");  
  30.   
  31.   
  32. function getCountryIndex($sCountry) {  
  33.     static $aIndexesarray("us" => 1, "ca" => 2);  
  34.     return isset($aIndexes[$sCountry])? $aIndexes[$sCountry] : false;  
  35. }  
  36.   
  37. function getZipName($sCountry) {  
  38.     if (!($nIndex= getCountryIndex($sCountry))) return false;  
  39.     static $aValsarray(1=> 'zipcode', 2=> 'postalcode');  
  40.     return $aVals[$nIndex];  
  41. }  
  42.   
  43. /* ----------------------------- */  
  44. /* Get info for a given ZIP Code value */  
  45. /* ----------------------------- */  
  46. function getInfoByZip($sCountry$sZipValue) {  
  47.     if (!($sZipName= getZipName($sCountry))) return false;  
  48.     $sql"SELECT * FROM `$sCountry` WHERE `$sZipName`='$sZipValue' LIMIT 1";  
  49.     if (!($h_res= mysql_query($sql)) || !mysql_num_rows($h_res)) return false;  
  50.     $b_ok= ($a_row= mysql_fetch_assoc($h_res)) && count($a_row);  
  51.     mysql_free_result($h_res);  
  52.     return $b_ok$a_row : false;  
  53. }  
  54.   
  55. /* ----------------------------- */  
  56. /* Get coordinates for a given ZIP Code value */  
  57. /* ----------------------------- */  
  58. function getCoordsByZip($sCountry$sZipValue) {  
  59.     if (!($sZipName= getZipName($sCountry))) return false;  
  60.     $sql"SELECT `longitude`, `latitude` FROM `$sCountry` WHERE `$sZipName`='$sZipValue' LIMIT 1";  
  61.     if (!($h_res= mysql_query($sql)) || !mysql_num_rows($h_res)) return false;  
  62.     $b_ok= ($a_row= mysql_fetch_row($h_res)) && count($a_row) == 2;  
  63.     mysql_free_result($h_res);  
  64.     return $b_ok$a_row : false;  
  65. }  
  66.   
  67. /* ----------------------------- */  
  68. /* Get all ZIP Codes within a given Radius from a given ZIP Code */  
  69. /* ----------------------------- */  
  70. function getZipsByRadius($sRadius$sCountry$sZipValue$sLatitude$sLongitude) {  
  71.     if (!($nIndex= getCountryIndex($sCountry))) return false;  
  72.     $fRadius = (float)$sRadius;  
  73.     $fLatitude = (float)$sLatitude;  
  74.     $fLongitude = (float)$sLongitude;  
  75.     $sXprDistance =  "SQRT(POWER(($fLatitude-latitude)*110.7,2)+POWER(($fLongitude-longitude)*75.6,2))";  
  76.     static $aValsarray(1=> ", statecode AS areacode", 2=> ", provincecode AS areacode");  
  77.     $sXtraFields$aVals[$nIndex];  
  78.     $sql = "SELECT `city`, `longitude`, `latitude`, `zipcode`, $sXprDistance AS distance $sXtraFields FROM `$sCountry` WHERE $sXprDistance <= '$fRadius' ORDER BY distance ASC";  
  79.     if (!($h_res= mysql_query($sql)) || !mysql_num_rows($h_res)) return false;  
  80.     $a_retarray();  
  81.     while ($a_row= mysql_fetch_assoc($h_res)) {  
  82.         if (count($a_row)) $a_ret[]= $a_row;  
  83.     }  
  84.     mysql_free_result($h_res);  
  85.     return count($a_ret)? $a_ret : false;  
  86. }  
  87.   
  88. define('F_KMPERMILE', 1.609344  );  
  89.   
  90. function sqr($x) {  
  91.     return $x * $x;  
  92. }  
  93.   
  94. /* ----------------------------- */  
  95. /* Start of Script */  
  96. /* Get parameters */  
  97. /* ----------------------------- */  
  98. $b_ok= isset($_REQUEST['zipcode']) && isset($_REQUEST['country']) && isset($_REQUEST['radius']);  
  99. if (!$b_ok)  
  100.     die("Error: parameters are missed");  
  101.   
  102. $sZipCode = $_REQUEST['zipcode'];  
  103. $sCountry = $_REQUEST['country'];  
  104. $sRadius = $_REQUEST['radius'];  
  105. $fRadius = (float)$sRadius;  
  106. $sUnit = (isset($_REQUEST['unit']) && $_REQUEST['unit'] == "km")? "km" : "miles";  
  107. /* Radius is converted into kilometer as getZipsByRadius is expecting radius in km   */  
  108. if ($bUnitMiles = $sUnit=="miles"$fRadius = $fRadius * F_KMPERMILE;  
  109.   
  110. /* ----------------------------- */  
  111. /* Get Info for ZIP Code */  
  112. /* ----------------------------- */  
  113. if (!($a_info = getInfoByZip($sCountry$sZipCode)))  
  114.     die("Error: zipcode not found");  
  115.   
  116. $sCity = $a_info["city"];  
  117. $sLongitude = $a_info["longitude"];  
  118. $sLatitude = $a_info["latitude"];  
  119. $fLatitude = (float)$sLatitude;  
  120. $fLongitude = (float)$sLongitude;  
  121. if ($sCountry == "us") {  
  122.     $sAreacode = $a_info["statecode"];  
  123. }  
  124. else {  
  125.     $sAreacode = $a_info["provincecode"];  
  126. }  
  127. $sMaptxt = "$sRadius $sUnit around $sZIPName  
  128. $sZIPCode $sCity";  
  129.   
  130. /* Get Info for ZIP Code */  
  131. if (!($a_result = getZipsByRadius($fRadius$sCountry$sZipCode$sLatitude$sLongitude)))  
  132.     die("Error: zipcode not found");  
  133.   
  134. /* ----------------------------- */  
  135. /* Creating result list */  
  136. /* ----------------------------- */  
  137. $sResultlist = ''$sCondition = '';  
  138. foreach ($a_result as $i=> $a_row) {  
  139.     $sZipCode$a_row["zipcode"];  
  140.     $sCity$a_row["city"];  
  141.     $sAreacode$a_row["areacode"];  
  142.     if ($i==0) {  
  143.         $sDistance = " (0  $sUnit)";  
  144.         $sResultlist = "$sZipCode $sCity$sAreacode$sDistance  
  145. ";  
  146.         $sCondition .= "'$sZipCode'";  
  147.         continue;  
  148.     }  
  149.     if (strpos($sCondition"'$sZipCode'")!==false) continue;  
  150.     $sCondition .= ", '$sZipCode'";  
  151.     $fLatDiff = $fLatitude - (float)$a_row["latitude"];  
  152.     $fLonDiff = $fLongitude - (float)$a_row["longitude"];  
  153.     if ($bUnitMiles)  
  154.         $sDistance = " ("Round(sqrt(sqr($fLatDiff*110.7)+sqr($fLonDiff*75.6))/F_KMPERMILE,1). "  "$sUnit")";  
  155.     else  
  156.         $sDistance = " ("Round(sqrt(sqr($fLatDiff*110.7)+sqr($fLonDiff*75.6)),1). "  "$sUnit")";  
  157.     $sResultlist .= "$sZipCode $sCity$sAreacode$sDistance  
  158. ";  
  159. }  
  160. $sCondition = " zipcode IN ($sCondition)";  
  161. /* ----------------------------- */  
  162. /* $sCondition contains the SQL-WHERE statement that could now be used to extract all the 'in-radius' datasets out of another table */  
  163. /* for example: SELECT * FROM mydealers WHERE $sCondition */  
  164. /* ----------------------------- */  
  165.   
  166.   
  167. /* ----------------------------- */  
  168. /* Create Google Map and draw Radius Circle */  
  169. /* ----------------------------- */  
  170. ?><!DOCTYPE html>  
  171. <html>  
  172.   <head>  
  173.     <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
  174.     <meta charset="utf-8">  
  175.     <title>ZIP Codes in a Radius</title>  
  176.   
  177. <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>  
  178. <script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.5/src/infobox.js"></script>  
  179. <script>  
  180.   
  181. function init() {  
  182. /////////////////////////////////////////  
  183. /// Draw Map  
  184. /////////////////////////////////////////  
  185.     var mapCenter = new google.maps.LatLng(<?=$fLatitude?>,<?=$fLongitude?>);  
  186.     var mapOptions = {  
  187.         zoom: 9,  
  188.         center: mapCenter,  
  189.         mapTypeId: google.maps.MapTypeId.ROADMAP,  
  190.         disableDefaultUI: true  
  191.     }  
  192.     var map = new google.maps.Map(document.getElementById("map"), mapOptions);  
  193.   
  194. /////////////////////////////////////////  
  195. /// Draw Marker  
  196. /////////////////////////////////////////  
  197.     var marker1 = new google.maps.Marker({  
  198.         position: mapCenter,  
  199.         map: map,  
  200.         zIndex: 2  
  201.     });  
  202.   
  203. /////////////////////////////////////////  
  204. /// Draw Circle  
  205. /////////////////////////////////////////  
  206.     var circle = new google.maps.Circle({  
  207.         map: map,  
  208.         radius: <?=$fRadius*1000?>, //Radius in Millimeter  
  209.         center: mapCenter,  
  210.         strokeColor: "#0000FF",  
  211.         strokeOpacity: 0.4,  
  212.         strokeWeight: 2,  
  213.         zIndex: 1,  
  214.         fillColor: "#FFCC00",  
  215.         fillOpacity: 0.25,   
  216.     });  
  217.   
  218. /////////////////////////////////////////  
  219. /// Draw Label  
  220. /////////////////////////////////////////  
  221.     var labelText = document.createElement("div");  
  222.         labelText.style.cssText = "text-align: center; width: 180px; border: 1px solid #333; background: white; font-family:Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: bold;";  
  223.         labelText.innerHTML = "<?=$sMaptxt?>";  
  224.   
  225.     var myOptions = {  
  226.             content: labelText,  
  227.             disableAutoPan: true,  
  228.             pixelOffset: new google.maps.Size(90, -170),  
  229.             position: mapCenter,  
  230.             closeBoxURL: "",  
  231.             isHidden: false,  
  232.             pane: "mapPane",  
  233.             zIndex: 3,  
  234.             enableEventPropagation: true  
  235.     };  
  236.     var ibLabel = new InfoBox(myOptions);  
  237.     ibLabel.open(map);  
  238.   
  239. /////////////////////////////////////////  
  240. /// Zoom to fit  
  241. /////////////////////////////////////////  
  242.     map.fitBounds(circle.getBounds());  
  243. }  
  244. </script>  
  245.   
  246. </head>  
  247.   <body onload="init()">  
  248.     <div id="map" style="width: 560px; height: 350px;"></div>  
  249.     <?=$sResultlist?>  
  250.   </body>  
  251. </html>  
Download PHP script with sample database

ASP Script - Source CodeASP Script


  1. <%  
  2. '======================================================================  
  3. ' ZIP Codes in a Radius in USA and Canada  
  4. '  
  5. ' This ASP Script requires 3 GET parameters: zipcode and country (us/ca) and unit (miles/km)  
  6. ' Plus the database tables us and ca containing the ZIP Code-Lon/Lat data provided by ZIPCodeSoft.  
  7. '  
  8. ' Example call: tools_radius_asp.asp?zipcode=90210&country=us&radius=10&unit=miles  
  9. '   
  10. ' © 2012 http://www.zipcodesoft.com, All Rights Reserved  
  11. '======================================================================  
  12.   
  13. Dim strZIPCode  
  14. Dim strCountry  
  15. Dim dblRadius  
  16. Dim strUnit  
  17. Dim dblLongitude  
  18. Dim dblLatitude  
  19. Dim strZIPName  
  20. Dim strCity  
  21. Dim strMaptxt  
  22. Dim strAreacode  
  23. Dim strDistance  
  24. Dim strResultlist  
  25. Dim strCondition   
  26.   
  27. Const KMperMile = 1.609344  
  28. Const Pi = 3.141592654  
  29.   
  30. strZIPCode = Request("zipcode")  
  31. strCountry = Request("country")  
  32. strRadius = Request("radius")  
  33. dblRadius = CDbl(strRadius)  
  34. strUnit = Request("unit")  
  35. If strUnit = "miles" Then dblRadius = dblRadius * KMperMile  
  36.   
  37. '======================================================================  
  38. ' Set the correct term: ZIP Code = USA or Postal Code = Canada  
  39. '======================================================================  
  40. If strCountry="us" Then strZIPName = " ZIP Code"  
  41. If strCountry="ca" Then strZIPName = " Postal Code"  
  42.   
  43. '======================================================================  
  44. ' Get coordinates of center ZIP Code  
  45. '======================================================================  
  46. Set conn =  Server.CreateObject("ADODB.Connection")  
  47. conn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & server.mappath("/db/geo.mdb")  
  48. Set rs = Server.CreateObject("ADODB.Recordset")  
  49.   
  50. If strCountry="us" Then sql = "SELECT * FROM us WHERE zipcode='" & strZIPCode & "';"  
  51. If strCountry="ca" Then sql = "SELECT * FROM ca WHERE postalcode='" & strZIPCode & "';"  
  52.   
  53. Set rs = conn.Execute(sql)  
  54. If Not rs.EOF Then  
  55.     dblLongitude = rs.Fields("longitude")  
  56.     dblLatitude = rs.Fields("latitude")  
  57.     strCity = rs.Fields("city")  
  58.     strMaptxt = strRadius & " " & strUnit & " around " & strZIPName & "  
  59. " & strZIPCode & " " & strCity  
  60.     If strCountry="us" Then strAreacode = rs.Fields("statecode")  
  61.     If strCountry="ca" Then strAreacode = rs.Fields("provincecode")  
  62. Else  
  63.     Response.Write(strZIPName & " Not found")  
  64. End If  
  65. rs.Close  
  66.   
  67. '======================================================================  
  68. ' Calculate all ZIP Codes in within the given Radius  
  69. '======================================================================  
  70.   
  71. dblDistanceCalc =  "SQR(((" & dblLatitude & "-latitude)*110.7*(" & dblLatitude & "-latitude)*110.7)+((" & dblLongitude & "-longitude)*75.6*(" & dblLongitude & "-longitude)*75.6))"  
  72. ' Use this line instead if using SQL Server instead of MS Access  
  73. 'dblDistanceCalc =  "SQRT(POWER((" & dblLatitude & "-latitude)*110.7,2)+POWER((" & dblLongitude & "-longitude)*75.6,2))"  
  74.   
  75. If strCountry="us" Then sql = "SELECT city, statecode AS areacode, longitude, latitude, zipcode, " & dblDistanceCalc & " AS distance FROM us WHERE " & dblDistanceCalc & " <= " & dblRadius & " ORDER BY " & dblDistanceCalc & " ASC;"  
  76. If strCountry="ca" Then sql = "SELECT city, provincecode AS areacode, longitude, latitude, postalcode AS zipcode, " & dblDistanceCalc & " AS distance FROM ca WHERE " & dblDistanceCalc & " <= " & dblRadius & " ORDER BY " & dblDistanceCalc & " ASC;"  
  77.   
  78. Set rs = Conn.Execute(sql)  
  79.   
  80. Dim intCounter  
  81. Dim dblLatDiff  
  82. Dim dblLonDiff  
  83. intCounter = 1  
  84. While Not rs.EOF  
  85.     If intCounter=1 Then   
  86.         strDistance = " (0  " & strUnit & ")"   
  87.         strResultlist = rs.Fields("zipcode") & " "  & rs.Fields("city") & ", " & rs.Fields("areacode") & strDistance & "  
  88. "  
  89.         strCondition = " zipcode IN ('" & rs.Fields("zipcode") & "'"          
  90.     Else        
  91.         If Instr(strCondition,"'" & rs.Fields("zipcode") & "'")=0 Then  
  92.             strCondition = strCondition & ", '" & rs.Fields("zipcode") & "'"  
  93.             dblLatDiff = CDbl(dblLatitude)-CDbl(rs.Fields("latitude"))  
  94.             dblLonDiff = CDbl(dblLongitude)-CDbl(rs.Fields("longitude"))  
  95.             If strUnit="miles" Then strDistance = " (" & Round(sqr(pow(dblLatDiff*110.7)+pow(dblLonDiff*75.6))/KMperMile,1) & "  " & strUnit & ")"  
  96.             If strUnit="km" Then strDistance = " (" & Round(sqr(pow(dblLatDiff*110.7)+pow(dblLonDiff*75.6)),1) & "  " & strUnit & ")"  
  97.             strResultlist = strResultlist & rs.Fields("zipcode") & " "  & rs.Fields("city") & ", " & rs.Fields("areacode") & strDistance & "  
  98. "  
  99.         End If            
  100.     End If  
  101.     intCounter=2  
  102.     rs.MoveNext  
  103. Wend  
  104. strCondition = strCondition & ")"  
  105. 'strCondition contains the SQL-WHERE statement that could now be used to extract all the 'in-radius' datasets out of another table  
  106. rs.Close  
  107.   
  108. Set rs = Nothing  
  109. Set conn = Nothing  
  110.   
  111. Function iif(condition,isTrue,isFalse)  
  112.   
  113.     If (condition) Then  
  114.        iif = isTrue  
  115.     Else  
  116.        iif = isFalse  
  117.     End If  
  118.   
  119. End Function  
  120.   
  121. Function pow(i)  
  122.     pow = i*i  
  123. End Function   
  124.   
  125. '======================================================================  
  126. ' Google Map and draw Radius ircle  
  127. '======================================================================  
  128. %>  
  129. <!DOCTYPE html>  
  130. <html>  
  131.   <head>  
  132.     <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
  133.     <meta charset="utf-8">  
  134.     <title>ZIP Codes in a Radius</title>  
  135.   
  136. <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>  
  137. <script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.5/src/infobox.js"></script>  
  138. <script>  
  139.   
  140. function init() {  
  141. /////////////////////////////////////////  
  142. /// Draw Map  
  143. /////////////////////////////////////////  
  144.     var mapCenter = new google.maps.LatLng(<%=dblLatitude%>,<%=dblLongitude%>);  
  145.     var mapOptions = {  
  146.         zoom: 9,  
  147.         center: mapCenter,  
  148.         mapTypeId: google.maps.MapTypeId.ROADMAP,  
  149.         disableDefaultUI: true  
  150.     }  
  151.     var map = new google.maps.Map(document.getElementById("map"), mapOptions);  
  152.   
  153. /////////////////////////////////////////  
  154. /// Draw Marker  
  155. /////////////////////////////////////////  
  156.     var marker1 = new google.maps.Marker({  
  157.         position: mapCenter,  
  158.         map: map,  
  159.         zIndex: 2  
  160.     });  
  161.   
  162. /////////////////////////////////////////  
  163. /// Draw Circle  
  164. /////////////////////////////////////////  
  165.     var circle = new google.maps.Circle({  
  166.         map: map,  
  167.         radius: <%=dblRadius*1000%>, //Radius in Millimeter  
  168.         center: mapCenter,  
  169.         strokeColor: "#0000FF",  
  170.         strokeOpacity: 0.4,  
  171.         strokeWeight: 2,  
  172.         zIndex: 1,  
  173.         fillColor: "#FFCC00",  
  174.         fillOpacity: 0.25,  
  175.         zIndex: 1     
  176.     });  
  177.   
  178. /////////////////////////////////////////  
  179. /// Draw Label  
  180. /////////////////////////////////////////  
  181.     var labelText = document.createElement("div");  
  182.         labelText.style.cssText = "text-align: center; width: 180px; border: 1px solid #333; background: white; font-family:Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: bold;";  
  183.         labelText.innerHTML = "<%=strMaptxt%>";  
  184.   
  185.     var myOptions = {  
  186.             content: labelText,  
  187.             disableAutoPan: true,  
  188.             zIndex: null,  
  189.             pixelOffset: new google.maps.Size(90, -170),  
  190.             position: mapCenter,  
  191.             closeBoxURL: "",  
  192.             isHidden: false,  
  193.             pane: "mapPane",  
  194.             zIndex: 3,  
  195.             enableEventPropagation: true  
  196.     };  
  197.     var ibLabel = new InfoBox(myOptions);  
  198.     ibLabel.open(map);  
  199.   
  200. /////////////////////////////////////////  
  201. /// Zoom to fit  
  202. /////////////////////////////////////////  
  203.     map.fitBounds(circle.getBounds());  
  204. }  
  205. </script>  
  206.   
  207. </head>  
  208.   <body onload="init()">  
  209.     <div id="map" style="width: 560px; height: 350px;"></div>  
  210.     <%=strResultlist%>  
  211.   </body>  
  212. </html>  
Download ASP script with sample database

C# Script - Source Code C# Script


  1. Tools_Radius.aspx:  
  2.   
  3. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Tools_Radius.aspx.cs" Inherits="ZIPCodeTools.Tools_Radius" %>  
  4.   
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  6.   
  7. <html xmlns="http://www.w3.org/1999/xhtml">  
  8. <head runat="server">  
  9.     <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />  
  10.     <meta charset="utf-8" />  
  11.     <title>ZIP Codes in a Radius</title>  
  12.   
  13.     <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>  
  14.     <script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.5/src/infobox.js"></script>  
  15.     <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>  
  16.   
  17.     <asp:Literal ID="litHeaderCode" runat="server"></asp:Literal>  
  18.   
  19. </head>  
  20. <body onload="$(document).ready(function () { initialize(); });">  
  21.     <form id="form1" runat="server">  
  22.     <div>  
  23.         <asp:literal ID="litMessages" runat="server"></asp:literal>  
  24.         <div id="map" style="width: 560px; height: 350px;"></div>  
  25.         <div id="outputDiv" style="width: 300px; height: 50px;" ></div>  
  26.         <asp:Literal ID="lit_results" runat="server" />  
  27.     </div>  
  28.     </form>  
  29. </body>  
  30.   
  31. </html>  
  32.   
  33.   
  34.   
  35. Tools_Radius.aspx.cs:  
  36.   
  37. using System;  
  38. using System.Collections.Generic;  
  39. using System.Linq;  
  40. using System.Web;  
  41. using System.Web.UI;  
  42. using System.Web.UI.WebControls;  
  43. using System.Data.SqlClient;  
  44. using System.Data;  
  45. using System.Text;  
  46.   
  47. namespace ZIPCodeTools  
  48. {  
  49.     public partial class Tools_Radius : System.Web.UI.Page  
  50.     {  
  51.         DataTools dt = new DataTools();  
  52.   
  53.         protected void Page_Load(object sender, EventArgs e)  
  54.         {  
  55.             string ErrorMessage = "";  
  56.   
  57.             if (Request.Params["zipcode"] == null || Request.Params["zipcode"].Length == 0)  
  58.             {  
  59.                 ErrorMessage += "<li>Parameter zipcode cannot be missing or blank</li>";  
  60.             }  
  61.   
  62.             if (Request.Params["country"] == null || Request.Params["country"].Length == 0)  
  63.             {  
  64.                 ErrorMessage += "<li>Parameter country cannot be missing or blank</li>";  
  65.             }  
  66.   
  67.             if (Request.Params["radius"] == null || Request.Params["radius"].Length == 0)  
  68.             {  
  69.                 ErrorMessage += "<li>Parameter radius cannot be missing or blank</li>";  
  70.             }  
  71.   
  72.             if (Request.Params["unit"] == null || Request.Params["unit"].Length == 0)  
  73.             {  
  74.                 ErrorMessage += "<li>Parameter unit cannot be missing or blank</li>";  
  75.             }  
  76.   
  77.             if (ErrorMessage.Length > 0)  
  78.             {  
  79.                 litMessages.Text = String.Format("<ul>{0}</ul>", ErrorMessage);  
  80.             }  
  81.             else  
  82.                 Calculate();  
  83.         }  
  84.   
  85.         public void Calculate()  
  86.         {  
  87.   
  88.             try  
  89.             {  
  90.                 double dblLongitude = 0d;  
  91.                 double dblLatitude = 0d;  
  92.                 string strCity = string.Empty;  
  93.                 string strMaptxt = string.Empty;  
  94.                 string strAreacode = string.Empty;  
  95.                 string strCountry = string.Empty;  
  96.                 string strDistance = string.Empty;  
  97.                 string strResultlist = string.Empty;  
  98.                 string strCondition = string.Empty;  
  99.                 const double KMperMile = 1.609344;  
  100.                 const double Pi = 3.141592654;  
  101.   
  102.                 string unit;  
  103.                 unit = Request["unit"].ToString();  
  104.                 double dblRadius = 0d;  
  105.                 double.TryParse(Request["radius"].ToString(), out dblRadius);  
  106.   
  107.                 if (unit.Equals("miles"))  
  108.                     dblRadius = dblRadius * KMperMile;  
  109.   
  110.                 strCountry = Request["country"].ToString().ToLower();  
  111.                 string strZIPName = string.Empty;  
  112.                   
  113.                 string strZIPCode = Request["zipcode"].ToString();  
  114.   
  115.                 if ( strCountry.Equals("us") )  
  116.                     strZIPName = " ZIP Code";  
  117.                 else if ( strCountry.Equals("ca") )  
  118.                     strZIPName = " Postal Code";                  
  119.   
  120.                 SqlCommand cmd = new SqlCommand();  
  121.                 if ( strCountry.Equals("us") )  
  122.                     cmd.CommandText = "SELECT * FROM us WHERE zipcode = @Zipcode";  
  123.                 else if ( strCountry.Equals("ca") )  
  124.                     cmd.CommandText = "SELECT * FROM ca WHERE postalcode = @Zipcode";  
  125.   
  126.                 cmd.Parameters.Add("@ZipCode", SqlDbType.VarChar, 5).Value = Request["zipcode"].ToString();  
  127.   
  128.                 DataSet ds = dt.GetDataSet(cmd, DataTools.DataSources.zipcodesoft);  
  129.                   
  130.                 if ( ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0 )  
  131.                 {  
  132.                     DataRow dr = ds.Tables[0].Rows[0];  
  133.                     double.TryParse(dr["longitude"].ToString(), out dblLongitude);  
  134.                     double.TryParse(dr["latitude"].ToString(), out dblLatitude);  
  135.                     strCity = dr["city"].ToString();  
  136.                     strMaptxt = Request["radius"].ToString() + " " + unit + " around " + strZIPName + "  
  137. " + strZIPCode + " " + strCity;  
  138.                       
  139.                     if ( strCountry.Equals("us"))   
  140.                         strAreacode = dr["statecode"].ToString();  
  141.                     else if (strCountry.Equals("ca") )   
  142.                         strAreacode = dr["provincecode"].ToString();  
  143.                 }  
  144.   
  145.                 //======================================================================  
  146.                 // Calculate all ZIP Codes in within the given Radius  
  147.                 //======================================================================  
  148.   
  149.                 cmd = new SqlCommand();  
  150.                 string dblDistanceCalc = "SQRT(POWER((" + dblLatitude + "-latitude)*110.7,2)+POWER((" + dblLongitude + "-longitude)*75.6,2))";  
  151.                 string sql = string.Empty;  
  152.   
  153.                 if ( strCountry.Equals("us"))  
  154.                     sql = "SELECT city, statecode AS areacode, longitude, latitude, zipcode, " + dblDistanceCalc + " AS distance FROM us WHERE " + dblDistanceCalc + " <= " + dblRadius + " ORDER BY " + dblDistanceCalc + " ASC";  
  155.                 else if (strCountry.Equals("ca"))  
  156.                     sql = "SELECT city, provincecode AS areacode, longitude, latitude, postalcode AS zipcode, " + dblDistanceCalc + " AS distance FROM ca WHERE " + dblDistanceCalc + " <= " + dblRadius + " ORDER BY " + dblDistanceCalc + " ASC";  
  157.   
  158.                 cmd.CommandText = sql;                  
  159.   
  160.                 ds = dt.GetDataSet(cmd, DataTools.DataSources.zipcodesoft);  
  161.                 int intCounter = 1;  
  162.                 double dblLatDiff = 0d;  
  163.                 double dblLonDiff = 0d;  
  164.   
  165.                 if ( ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0 )  
  166.                 {  
  167.                     foreach ( DataRow dr in ds.Tables[0].Rows )  
  168.                     {  
  169.                         if ( intCounter == 1 )   
  170.                         {  
  171.                             strDistance = " (0  " + unit + ")" ;  
  172.                             strResultlist = dr["zipcode"].ToString() + " "  + dr["city"].ToString() + ", " + dr["areacode"].ToString() + strDistance + "  
  173. ";  
  174.                             strCondition = " zipcode IN ('" + dr["zipcode"] + "'";  
  175.                         }  
  176.                         else  
  177.                         {  
  178.                             if ( !strCondition.Contains(dr["zipcode"].ToString() ))   
  179.                             {  
  180.                                 double latitude = 0d;  
  181.                                 double longitude = 0d;  
  182.   
  183.                                 double.TryParse(dr["latitude"].ToString(), out latitude);  
  184.                                 double.TryParse(dr["longitude"].ToString(), out longitude);  
  185.                                   
  186.                                 strCondition = strCondition + ", '" + dr["zipcode"] + "'";  
  187.                                 dblLatDiff = dblLatitude - latitude;  
  188.                                 dblLonDiff = dblLongitude - longitude;  
  189.                                 if (unit.Equals("miles"))  
  190.                                     strDistance = " (" + Math.Round(Math.Sqrt(Math.Pow(dblLatDiff * 110.7, 2d) + Math.Pow(dblLonDiff * 75.6, 2d)) / KMperMile, 1, MidpointRounding.AwayFromZero) + "  " + unit + ")";  
  191.                                 else if (unit.Equals("km"))  
  192.                                     strDistance = " (" + Math.Round(Math.Sqrt(Math.Pow(dblLatDiff * 110.7, 2d) + Math.Pow(dblLonDiff * 75.6, 2d)), 1, MidpointRounding.AwayFromZero) + "  " + unit + ")";  
  193.                                   
  194.                                 strResultlist = strResultlist + dr["zipcode"].ToString() + " "  + dr["city"].ToString() + ", " + dr["areacode"] + strDistance + "  
  195. ";  
  196.                             }  
  197.                         }      
  198.                         intCounter = 2;  
  199.                     }  
  200.                 }  
  201.   
  202.                 lit_results.Text = strResultlist;  
  203.   
  204.                 //Begin Creating Website Javascript Code  
  205.                 StringBuilder output = new StringBuilder();  
  206.   
  207.                 output.Append("function initialize() {");  
  208.                 output.Append(Environment.NewLine);  
  209.                 output.Append("    ///////////////////////////////////");  
  210.                 output.Append(Environment.NewLine);  
  211.                 output.Append("    /// Draw map");  
  212.                 output.Append(Environment.NewLine);  
  213.                 output.Append("    ///////////////////////////////////");  
  214.                 output.Append(Environment.NewLine);  
  215.                 output.Append("var mapCenter = new google.maps.LatLng(").Append(dblLatitude).Append(",").Append(dblLongitude).Append(");");  
  216.                 output.Append(Environment.NewLine);  
  217.                 output.Append("    var mapOptions = {");  
  218.                 output.Append("        zoom: 9,");  
  219.                 output.Append("        center: mapCenter,");  
  220.                 output.Append("        mapTypeId: google.maps.MapTypeId.ROADMAP,");  
  221.                 output.Append("     disableDefaultUI: true");  
  222.                 output.Append("    };");  
  223.                 output.Append("    var map = new google.maps.Map(document.getElementById('map'), mapOptions);");  
  224.                 output.Append(Environment.NewLine);  
  225.                 output.Append("    ///////////////////////////////////");  
  226.                 output.Append(Environment.NewLine);  
  227.                 output.Append("    /// Draw marker");  
  228.                 output.Append(Environment.NewLine);  
  229.                 output.Append("    ///////////////////////////////////");  
  230.                 output.Append(Environment.NewLine);  
  231.                 output.Append("    var marker1 = new google.maps.Marker({");  
  232.                 output.Append("        position: mapCenter,");  
  233.                 output.Append("        map: map,");  
  234.                 output.Append("        zIndex: 2");  
  235.                 output.Append("    });");  
  236.   
  237.                 output.Append("    ///////////////////////////////////");  
  238.                 output.Append(Environment.NewLine);  
  239.                 output.Append("    /// Draw Circle");  
  240.                 output.Append(Environment.NewLine);  
  241.                 output.Append("    ///////////////////////////////////");  
  242.                 output.Append(Environment.NewLine).  
  243.                     Append("var circle = new google.maps.Circle({").  
  244.                     Append(Environment.NewLine).  
  245.                     Append("map: map,").  
  246.                     Append(Environment.NewLine).  
  247.                     Append("radius: ").Append(dblRadius*1000).Append(",").  
  248.                     Append(Environment.NewLine).  
  249.                     Append("center: mapCenter,").  
  250.                     Append(Environment.NewLine).  
  251.                     Append("strokeColor: \"#0000FF\",").  
  252.                     Append(Environment.NewLine).  
  253.                     Append("strokeOpacity: 0.4,").  
  254.                     Append(Environment.NewLine).  
  255.                     Append("strokeWeight: 2,").  
  256.                     Append(Environment.NewLine).  
  257.                     Append("zIndex: 1,").  
  258.                     Append(Environment.NewLine).  
  259.                     Append("fillColor: \"#FFCC00\",").  
  260.                     Append(Environment.NewLine).  
  261.                     Append("fillOpacity: 0.25, ").  
  262.                     Append(Environment.NewLine).  
  263.                     Append("});").  
  264.                     Append(Environment.NewLine).  
  265.                     Append("/////////////////////////////////////////").  
  266.                     Append(Environment.NewLine).  
  267.                     Append("/// Draw Label").  
  268.                     Append(Environment.NewLine).  
  269.                     Append("/////////////////////////////////////////").  
  270.                     Append(Environment.NewLine).  
  271.                     Append("var labelText = document.createElement(\"div\");").  
  272.                     Append(Environment.NewLine).  
  273.                     Append("labelText.style.cssText = \"text-align: center; width: 180px; border: 1px solid #333; background: white; font-family:Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: bold;\";").  
  274.                     Append(Environment.NewLine).  
  275.                     Append("labelText.innerHTML = \"").Append(strMaptxt).Append("\";").  
  276.                     Append(Environment.NewLine).  
  277.                     Append("var myOptions = {").  
  278.                     Append(Environment.NewLine).  
  279.                     Append("content: labelText,").Append(Environment.NewLine).  
  280.                     Append("disableAutoPan: true,").Append(Environment.NewLine).  
  281.                     Append("pixelOffset: new google.maps.Size(90, -170),").Append(Environment.NewLine).  
  282.                     Append("position: mapCenter,").Append(Environment.NewLine).  
  283.                     Append("closeBoxURL: \"\",").Append(Environment.NewLine).  
  284.                     Append("isHidden: false,").Append(Environment.NewLine).  
  285.                     Append("pane: \"mapPane\",").Append(Environment.NewLine).  
  286.                     Append("zIndex: 3,").Append(Environment.NewLine).  
  287.                     Append("enableEventPropagation: true").Append(Environment.NewLine).  
  288.                     Append("};").Append(Environment.NewLine).  
  289.                     Append("var ibLabel = new InfoBox(myOptions);").Append(Environment.NewLine).  
  290.                     Append("ibLabel.open(map);").Append(Environment.NewLine).  
  291.                     Append("/////////////////////////////////////////").Append(Environment.NewLine).  
  292.                     Append("/// Zoom to fit").Append(Environment.NewLine).  
  293.                     Append("/////////////////////////////////////////").Append(Environment.NewLine).  
  294.                     Append("map.fitBounds(circle.getBounds());").Append(Environment.NewLine).                      
  295.                     Append("}");  
  296. //output.Append("</script>");  
  297. Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptAPI", output.ToString(), true);  
  298. //litHeaderCode.Text = output.ToString();  
  299.   
  300.             }  
  301.             catch (Exception ex)  
  302.             {  
  303.             }  
  304.         }  
  305.       
  306.     }  
  307. }  
Download C# script with sample database

Coldfusion Script - Source Code Coldfusion Script


  1. <!---   
  2. '======================================================================  
  3. ' ZIP Codes in a Radius in USA and Canada  
  4. '  
  5. ' This CFM Script requires 3 GET parameters: zipcode and country (us/ca) and unit (miles/km)  
  6. ' Plus the database tables us and ca containing the ZIP Code-Lon/Lat data.  
  7. '  
  8. ' Example call: tools_radius.cfm?zipcode=90210&country=us&radius=10&unit=miles  
  9. '   
  10. ' © 2012 www.zipcodesoft.com, All Rights Reserved  
  11. '======================================================================  
  12.  --->  
  13.   
  14. <cfsetting showdebugoutput="false">  
  15.   
  16. <!--- This is data source name defined in coldfusion administrator --->  
  17. <cfset rs = "geodb">  
  18.   
  19. <cfset strZIPCode = "">  
  20. <cfset strCountry = "">  
  21. <cfset dblRadius = "">  
  22. <cfset strUnit = "">  
  23. <cfset dblLongitude = "">  
  24. <cfset dblLatitude = "">  
  25. <cfset strZIPName = "">  
  26. <cfset strCity = "">  
  27. <cfset strMaptxt = "">  
  28. <cfset strAreacode = "">  
  29. <cfset strDistance = "">  
  30. <cfset strResultlist = "">  
  31. <cfset strCondition  = "">  
  32.   
  33. <cfset KMperMile = 1.609344>  
  34. <cfset Pi = 3.141592654>  
  35.   
  36. <cfset strZIPCode = URL.zipcode>  
  37. <cfset strCountry = URL.country>  
  38. <cfset strRadius = URL.radius>  
  39. <cfset dblRadius = strRadius>  
  40. <cfset strUnit = URL.unit>  
  41.   
  42. <cfif strUnit eq "miles">  
  43.     <cfset dblRadius = dblRadius * KMperMile>  
  44. </cfif>  
  45.   
  46. <!--- '======================================================================  
  47. ' Set the correct term: ZIP Code = USA or Postal Code = Canada  
  48. '====================================================================== --->  
  49.   
  50. <cfif strCountry eq "us">  
  51.     <cfset strZIPName = "ZIP Code">  
  52. <cfelseif strCountry eq "ca">  
  53.     <cfset strZIPName = "Postal Code">  
  54. </cfif>  
  55.   
  56. <cfif strCountry eq "us">  
  57.     <cfquery name="getZipcodes"  datasource="#rs#">  
  58.         SELECT * FROM us WHERE zipcode='#strZIPCode#'  
  59.     </cfquery>  
  60. <cfelseif strCountry eq "ca">  
  61.     <cfquery name="getZipcodes"  datasource="#rs#">  
  62.         SELECT * FROM ca WHERE postalcode='#strZIPCode#'  
  63.     </cfquery>  
  64. </cfif>  
  65.   
  66.   
  67. <cfif getZipcodes.recordcount gt 0>  
  68.   
  69.     <cfset dblLongitude = getZipcodes.longitude>  
  70.     <cfset dblLatitude = getZipcodes.latitude>  
  71.     <cfset strCity = getZipcodes.city>  
  72.     <cfset strMaptxt = strRadius & " " & strUnit & " around " & strZIPName & "  
  73. " & strZIPCode & " " & strCity>  
  74.   
  75.     <cfif strCountry eq "us">  
  76.         <cfset strAreaCode = getZipcodes.statecode>  
  77.     </cfif>  
  78.     <cfif strCountry eq "ca">  
  79.         <cfset strAreaCode = getZipcodes.provincecode>  
  80.     </cfif>  
  81. <cfelse>  
  82.     <cfoutput>#strZIPName# Not found</cfoutput>  
  83. </cfif>  
  84.   
  85.   
  86. <!--- '======================================================================  
  87. ' Calculate all ZIP Codes in within the given Radius  
  88. '====================================================================== --->  
  89.   
  90. <cfset dblDistanceCalc =  "SQRT(((" & dblLatitude & "-latitude)*110.7*(" & dblLatitude & "-latitude)*110.7)+((" & dblLongitude & "-longitude)*75.6*(" & dblLongitude & "-longitude)*75.6))">  
  91.   
  92. <!--- <cfoutput>#dblDistanceCalc#</cfoutput><cfabort> --->  
  93.   
  94.   
  95. <cfif strCountry eq "us">  
  96.     <cfquery name="getAllData"  datasource="#rs#">  
  97.         SELECT city, statecode AS areacode, longitude, latitude, zipcode, #dblDistanceCalc# AS distance   
  98.         FROM us   
  99.         WHERE #dblDistanceCalc# <= #dblRadius#  
  100.         ORDER BY #dblDistanceCalc# ASC  
  101.     </cfquery>  
  102. <cfelseif strCountry eq "ca">  
  103.     <cfquery name="getAllData"  datasource="#rs#">  
  104.         SELECT city, provincecode AS areacode, longitude, latitude, postalcode AS zipcode, #dblDistanceCalc# AS distance   
  105.         FROM ca   
  106.         WHERE #dblDistanceCalc# <= #dblRadius#   
  107.         ORDER BY #dblDistanceCalc# ASC  
  108.     </cfquery>  
  109. </cfif>  
  110.   
  111. <cffunction name = "pow" returntype="numeric">  
  112.     <cfargument name="num" type="numeric" required="true">  
  113.     <cfreturn arguments.num * arguments.num>  
  114. </cffunction>  
  115.   
  116. <cffunction name="roundToX" returntype="numeric">  
  117.    <cfargument name="num" type="numeric" required="yes">  
  118.   
  119.     <cfset RoundedNumber = num * 10>  
  120.     <cfset RoundedNumber = Round(RoundedNumber )>  
  121.     <cfset RoundedNumber = RoundedNumber / 10>  
  122.    <cfreturn RoundedNumber>  
  123. </cffunction>  
  124.   
  125. <cfset intCounter = 1>  
  126. <cfset dblLatDiff = "">  
  127. <cfset dblLonDiff = "">  
  128.   
  129. <cfloop query="getAllData">  
  130.     <cfif intCounter eq 1>  
  131.         <cfset strDistance = " (0  " & strUnit & ")">   
  132.         <cfset strResultlist = getAllData.zipcode & " "  & getAllData.city & ", " & getAllData.areacode & strDistance & "  
  133. ">  
  134.         <cfset strCondition = " zipcode IN ('" & getAllData.zipcode & "'">  
  135.     <cfelse>  
  136.         <cfif FindNoCase(getAllData.zipcode, strCondition) eq 0>  
  137.             <cfset strCondition = strCondition & ", '" & getAllData.zipcode & "'">  
  138.             <cfset dblLatDiff = dblLatitude - getAllData.latitude>  
  139.             <cfset dblLonDiff = dblLongitude - getAllData.longitude>  
  140.               
  141.             <cfif strUnit eq "miles">  
  142.                 <cfset strDistance = " (" & roundToX(sqr(pow(dblLatDiff*110.7)+pow(dblLonDiff*75.6))/KMperMile) & "  " & strUnit & ")">  
  143.             </cfif>  
  144.             <cfif strUnit eq "km">  
  145.                 <cfset strDistance = " (" & roundToX(sqr(pow(dblLatDiff*110.7)+pow(dblLonDiff*75.6))) & "  " & strUnit & ")">  
  146.             </cfif>  
  147.             <cfset strResultlist = strResultlist & getAllData.zipcode & " "  & getAllData.city & ", " & getAllData.areacode & strDistance & "  
  148. ">  
  149.         </cfif>  
  150.     </cfif>  
  151.     <cfset intCounter=2>  
  152. </cfloop>  
  153. <cfset strCondition = strCondition & ")">  
  154. <!--- 'strCondition contains the SQL-WHERE statement that could now be used to extract all the 'in-radius' datasets out of another table --->  
  155.   
  156.   
  157. <!--- '======================================================================  
  158. ' Google Map and draw Radius Circle  
  159. '====================================================================== --->  
  160.   
  161. <cfoutput>  
  162. <!DOCTYPE html>  
  163. <html>  
  164.   <head>  
  165.     <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
  166.     <meta charset="utf-8">  
  167.     <title>ZIP Codes in a Radius</title>  
  168.   
  169. <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>  
  170. <script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.5/src/infobox.js"></script>  
  171. <script>  
  172.   
  173. function init() {  
  174. /////////////////////////////////////////  
  175. /// Draw Map  
  176. /////////////////////////////////////////  
  177.     var mapCenter = new google.maps.LatLng(#dblLatitude#,#dblLongitude#);  
  178.     var mapOptions = {  
  179.         zoom: 9,  
  180.         center: mapCenter,  
  181.         mapTypeId: google.maps.MapTypeId.ROADMAP,  
  182.         disableDefaultUI: true  
  183.     }  
  184.     var map = new google.maps.Map(document.getElementById("map"), mapOptions);  
  185.   
  186. /////////////////////////////////////////  
  187. /// Draw Marker  
  188. /////////////////////////////////////////  
  189.     var marker1 = new google.maps.Marker({  
  190.         position: mapCenter,  
  191.         map: map,  
  192.         zIndex: 2  
  193.     });  
  194.   
  195. /////////////////////////////////////////  
  196. /// Draw Circle  
  197. /////////////////////////////////////////  
  198.     var circle = new google.maps.Circle({  
  199.         map: map,  
  200.         radius: #dblRadius*1000#, //Radius in Millimeter  
  201.         center: mapCenter,  
  202.         strokeColor: "##0000FF",  
  203.         strokeOpacity: 0.4,  
  204.         strokeWeight: 2,  
  205.         zIndex: 1,  
  206.         fillColor: "##FFCC00",  
  207.         fillOpacity: 0.25,   
  208.     });  
  209.   
  210. /////////////////////////////////////////  
  211. /// Draw Label  
  212. /////////////////////////////////////////  
  213.     var labelText = document.createElement("div");  
  214.         labelText.style.cssText = "text-align: center; width: 180px; border: 1px solid ##333; background: white; font-family:Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: bold;";  
  215.         labelText.innerHTML = "#strMaptxt#";  
  216.   
  217.     var myOptions = {  
  218.             content: labelText,  
  219.             disableAutoPan: true,  
  220.             pixelOffset: new google.maps.Size(90, -170),  
  221.             position: mapCenter,  
  222.             closeBoxURL: "",  
  223.             isHidden: false,  
  224.             pane: "mapPane",  
  225.             zIndex: 3,  
  226.             enableEventPropagation: true  
  227.     };  
  228.     var ibLabel = new InfoBox(myOptions);  
  229.     ibLabel.open(map);  
  230.   
  231. /////////////////////////////////////////  
  232. /// Zoom to fit  
  233. /////////////////////////////////////////  
  234.     map.fitBounds(circle.getBounds());  
  235. }  
  236. </script>  
  237.   
  238. </head>  
  239.   <body onload="init()">  
  240.     <div id="map" style="width: 560px; height: 350px;"></div>  
  241.     #strResultlist#  
  242.   </body>  
  243. </html>  
  244. </cfoutput>  
Download Coldfusion script with sample database

Source Code available
for free download in


PHP Script

ASP Script Source Code

C# Source Code

CF Source Code

All these scripts work perfectly with our databases


Postal Code Database Canada

ZIP Code Database USA

ZIP Code Database USA / Canada

comments powered by Disqus