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:
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
- /*======================================================================
- ** ZIP Codes in a Radius in USA and Canada
- **
- ** This PHP Script requires 4 GET parameters: zipcode, country (us/ca), radius, unit (miles/km)
- ** Plus the database tables us and ca containing the ZIP Code-Lon/Lat data.
- **
- ** Example call: tools_radius.php?zipcode=90210&country=us&radius=10&unit=miles
- **
- ** © 2012 https://www.zipcodesoft.com, All Rights Reserved
- **======================================================================
- */
- /* ----------------------------- */
- /* Connecting to MySQL server: */
- /* ----------------------------- */
- @mysql_connect($CFG_DB['db_host'], $CFG_DB['db_user'], $CFG_DB['db_pass'])
- or die("Error: mysql_connect() failed");
- /* ----------------------------- */
- /* Selecting client character set: */
- /* ----------------------------- */
- mysql_set_charset('utf8');
- /* ----------------------------- */
- /* Selecting database: */
- /* ----------------------------- */
- @mysql_select_db($CFG_DB['db_base'])
- or die("Error: mysql_select_db() failed");
- function getCountryIndex($sCountry) {
- static $aIndexes= array("us" => 1, "ca" => 2);
- return isset($aIndexes[$sCountry])? $aIndexes[$sCountry] : false;
- }
- function getZipName($sCountry) {
- if (!($nIndex= getCountryIndex($sCountry))) return false;
- static $aVals= array(1=> 'zipcode', 2=> 'postalcode');
- return $aVals[$nIndex];
- }
- /* ----------------------------- */
- /* Get info for a given ZIP Code value */
- /* ----------------------------- */
- function getInfoByZip($sCountry, $sZipValue) {
- if (!($sZipName= getZipName($sCountry))) return false;
- $sql= "SELECT * FROM `$sCountry` WHERE `$sZipName`='$sZipValue' LIMIT 1";
- if (!($h_res= mysql_query($sql)) || !mysql_num_rows($h_res)) return false;
- $b_ok= ($a_row= mysql_fetch_assoc($h_res)) && count($a_row);
- mysql_free_result($h_res);
- return $b_ok? $a_row : false;
- }
- /* ----------------------------- */
- /* Get coordinates for a given ZIP Code value */
- /* ----------------------------- */
- function getCoordsByZip($sCountry, $sZipValue) {
- if (!($sZipName= getZipName($sCountry))) return false;
- $sql= "SELECT `longitude`, `latitude` FROM `$sCountry` WHERE `$sZipName`='$sZipValue' LIMIT 1";
- if (!($h_res= mysql_query($sql)) || !mysql_num_rows($h_res)) return false;
- $b_ok= ($a_row= mysql_fetch_row($h_res)) && count($a_row) == 2;
- mysql_free_result($h_res);
- return $b_ok? $a_row : false;
- }
- /* ----------------------------- */
- /* Get all ZIP Codes within a given Radius from a given ZIP Code */
- /* ----------------------------- */
- function getZipsByRadius($sRadius, $sCountry, $sZipValue, $sLatitude, $sLongitude) {
- if (!($nIndex= getCountryIndex($sCountry))) return false;
- $fRadius = (float)$sRadius;
- $fLatitude = (float)$sLatitude;
- $fLongitude = (float)$sLongitude;
- $sXprDistance = "SQRT(POWER(($fLatitude-latitude)*110.7,2)+POWER(($fLongitude-longitude)*75.6,2))";
- static $aVals= array(1=> ", statecode AS areacode", 2=> ", provincecode AS areacode");
- $sXtraFields= $aVals[$nIndex];
- $sql = "SELECT `city`, `longitude`, `latitude`, `zipcode`, $sXprDistance AS distance $sXtraFields FROM `$sCountry` WHERE $sXprDistance <= '$fRadius' ORDER BY distance ASC";
- if (!($h_res= mysql_query($sql)) || !mysql_num_rows($h_res)) return false;
- $a_ret= array();
- while ($a_row= mysql_fetch_assoc($h_res)) {
- if (count($a_row)) $a_ret[]= $a_row;
- }
- mysql_free_result($h_res);
- return count($a_ret)? $a_ret : false;
- }
- define('F_KMPERMILE', 1.609344 );
- function sqr($x) {
- return $x * $x;
- }
- /* ----------------------------- */
- /* Start of Script */
- /* Get parameters */
- /* ----------------------------- */
- $b_ok= isset($_REQUEST['zipcode']) && isset($_REQUEST['country']) && isset($_REQUEST['radius']);
- if (!$b_ok)
- die("Error: parameters are missed");
- $sZipCode = $_REQUEST['zipcode'];
- $sCountry = $_REQUEST['country'];
- $sRadius = $_REQUEST['radius'];
- $fRadius = (float)$sRadius;
- $sUnit = (isset($_REQUEST['unit']) && $_REQUEST['unit'] == "km")? "km" : "miles";
- /* Radius is converted into kilometer as getZipsByRadius is expecting radius in km */
- if ($bUnitMiles = $sUnit=="miles") $fRadius = $fRadius * F_KMPERMILE;
- /* ----------------------------- */
- /* Get Info for ZIP Code */
- /* ----------------------------- */
- if (!($a_info = getInfoByZip($sCountry, $sZipCode)))
- die("Error: zipcode not found");
- $sCity = $a_info["city"];
- $sLongitude = $a_info["longitude"];
- $sLatitude = $a_info["latitude"];
- $fLatitude = (float)$sLatitude;
- $fLongitude = (float)$sLongitude;
- if ($sCountry == "us") {
- $sAreacode = $a_info["statecode"];
- }
- else {
- $sAreacode = $a_info["provincecode"];
- }
- $sMaptxt = "$sRadius $sUnit around $sZIPName
- $sZIPCode $sCity";
- /* Get Info for ZIP Code */
- if (!($a_result = getZipsByRadius($fRadius, $sCountry, $sZipCode, $sLatitude, $sLongitude)))
- die("Error: zipcode not found");
- /* ----------------------------- */
- /* Creating result list */
- /* ----------------------------- */
- $sResultlist = ''; $sCondition = '';
- foreach ($a_result as $i=> $a_row) {
- $sZipCode= $a_row["zipcode"];
- $sCity= $a_row["city"];
- $sAreacode= $a_row["areacode"];
- if ($i==0) {
- $sDistance = " (0 $sUnit)";
- $sResultlist = "$sZipCode $sCity, $sAreacode$sDistance
- ";
- $sCondition .= "'$sZipCode'";
- continue;
- }
- if (strpos($sCondition, "'$sZipCode'")!==false) continue;
- $sCondition .= ", '$sZipCode'";
- $fLatDiff = $fLatitude - (float)$a_row["latitude"];
- $fLonDiff = $fLongitude - (float)$a_row["longitude"];
- if ($bUnitMiles)
- $sDistance = " (". Round(sqrt(sqr($fLatDiff*110.7)+sqr($fLonDiff*75.6))/F_KMPERMILE,1). " ". $sUnit. ")";
- else
- $sDistance = " (". Round(sqrt(sqr($fLatDiff*110.7)+sqr($fLonDiff*75.6)),1). " ". $sUnit. ")";
- $sResultlist .= "$sZipCode $sCity, $sAreacode$sDistance
- ";
- }
- $sCondition = " zipcode IN ($sCondition)";
- /* ----------------------------- */
- /* $sCondition contains the SQL-WHERE statement that could now be used to extract all the 'in-radius' datasets out of another table */
- /* for example: SELECT * FROM mydealers WHERE $sCondition */
- /* ----------------------------- */
- /* ----------------------------- */
- /* Create Google Map and draw Radius Circle */
- /* ----------------------------- */
- ?><!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
- <meta charset="utf-8">
- <title>ZIP Codes in a Radius</title>
- <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
- <script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.5/src/infobox.js"></script>
- <script>
- function init() {
- /////////////////////////////////////////
- /// Draw Map
- /////////////////////////////////////////
- var mapCenter = new google.maps.LatLng(<?=$fLatitude?>,<?=$fLongitude?>);
- var mapOptions = {
- zoom: 9,
- center: mapCenter,
- mapTypeId: google.maps.MapTypeId.ROADMAP,
- disableDefaultUI: true
- }
- var map = new google.maps.Map(document.getElementById("map"), mapOptions);
- /////////////////////////////////////////
- /// Draw Marker
- /////////////////////////////////////////
- var marker1 = new google.maps.Marker({
- position: mapCenter,
- map: map,
- zIndex: 2
- });
- /////////////////////////////////////////
- /// Draw Circle
- /////////////////////////////////////////
- var circle = new google.maps.Circle({
- map: map,
- radius: <?=$fRadius*1000?>, //Radius in Millimeter
- center: mapCenter,
- strokeColor: "#0000FF",
- strokeOpacity: 0.4,
- strokeWeight: 2,
- zIndex: 1,
- fillColor: "#FFCC00",
- fillOpacity: 0.25,
- });
- /////////////////////////////////////////
- /// Draw Label
- /////////////////////////////////////////
- var labelText = document.createElement("div");
- 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;";
- labelText.innerHTML = "<?=$sMaptxt?>";
- var myOptions = {
- content: labelText,
- disableAutoPan: true,
- pixelOffset: new google.maps.Size(90, -170),
- position: mapCenter,
- closeBoxURL: "",
- isHidden: false,
- pane: "mapPane",
- zIndex: 3,
- enableEventPropagation: true
- };
- var ibLabel = new InfoBox(myOptions);
- ibLabel.open(map);
- /////////////////////////////////////////
- /// Zoom to fit
- /////////////////////////////////////////
- map.fitBounds(circle.getBounds());
- }
- </script>
- </head>
- <body onload="init()">
- <div id="map" style="width: 560px; height: 350px;"></div>
- <?=$sResultlist?>
- </body>
- </html>
ASP Script - Source Code
- <%
- '======================================================================
- ' ZIP Codes in a Radius in USA and Canada
- '
- ' This ASP Script requires 3 GET parameters: zipcode and country (us/ca) and unit (miles/km)
- ' Plus the database tables us and ca containing the ZIP Code-Lon/Lat data provided by ZIPCodeSoft.
- '
- ' Example call: tools_radius_asp.asp?zipcode=90210&country=us&radius=10&unit=miles
- '
- ' © 2012 http://www.zipcodesoft.com, All Rights Reserved
- '======================================================================
- Dim strZIPCode
- Dim strCountry
- Dim dblRadius
- Dim strUnit
- Dim dblLongitude
- Dim dblLatitude
- Dim strZIPName
- Dim strCity
- Dim strMaptxt
- Dim strAreacode
- Dim strDistance
- Dim strResultlist
- Dim strCondition
- Const KMperMile = 1.609344
- Const Pi = 3.141592654
- strZIPCode = Request("zipcode")
- strCountry = Request("country")
- strRadius = Request("radius")
- dblRadius = CDbl(strRadius)
- strUnit = Request("unit")
- If strUnit = "miles" Then dblRadius = dblRadius * KMperMile
- '======================================================================
- ' Set the correct term: ZIP Code = USA or Postal Code = Canada
- '======================================================================
- If strCountry="us" Then strZIPName = " ZIP Code"
- If strCountry="ca" Then strZIPName = " Postal Code"
- '======================================================================
- ' Get coordinates of center ZIP Code
- '======================================================================
- Set conn = Server.CreateObject("ADODB.Connection")
- conn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & server.mappath("/db/geo.mdb")
- Set rs = Server.CreateObject("ADODB.Recordset")
- If strCountry="us" Then sql = "SELECT * FROM us WHERE zipcode='" & strZIPCode & "';"
- If strCountry="ca" Then sql = "SELECT * FROM ca WHERE postalcode='" & strZIPCode & "';"
- Set rs = conn.Execute(sql)
- If Not rs.EOF Then
- dblLongitude = rs.Fields("longitude")
- dblLatitude = rs.Fields("latitude")
- strCity = rs.Fields("city")
- strMaptxt = strRadius & " " & strUnit & " around " & strZIPName & "
- " & strZIPCode & " " & strCity
- If strCountry="us" Then strAreacode = rs.Fields("statecode")
- If strCountry="ca" Then strAreacode = rs.Fields("provincecode")
- Else
- Response.Write(strZIPName & " Not found")
- End If
- rs.Close
- '======================================================================
- ' Calculate all ZIP Codes in within the given Radius
- '======================================================================
- dblDistanceCalc = "SQR(((" & dblLatitude & "-latitude)*110.7*(" & dblLatitude & "-latitude)*110.7)+((" & dblLongitude & "-longitude)*75.6*(" & dblLongitude & "-longitude)*75.6))"
- ' Use this line instead if using SQL Server instead of MS Access
- 'dblDistanceCalc = "SQRT(POWER((" & dblLatitude & "-latitude)*110.7,2)+POWER((" & dblLongitude & "-longitude)*75.6,2))"
- 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;"
- 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;"
- Set rs = Conn.Execute(sql)
- Dim intCounter
- Dim dblLatDiff
- Dim dblLonDiff
- intCounter = 1
- While Not rs.EOF
- If intCounter=1 Then
- strDistance = " (0 " & strUnit & ")"
- strResultlist = rs.Fields("zipcode") & " " & rs.Fields("city") & ", " & rs.Fields("areacode") & strDistance & "
- "
- strCondition = " zipcode IN ('" & rs.Fields("zipcode") & "'"
- Else
- If Instr(strCondition,"'" & rs.Fields("zipcode") & "'")=0 Then
- strCondition = strCondition & ", '" & rs.Fields("zipcode") & "'"
- dblLatDiff = CDbl(dblLatitude)-CDbl(rs.Fields("latitude"))
- dblLonDiff = CDbl(dblLongitude)-CDbl(rs.Fields("longitude"))
- If strUnit="miles" Then strDistance = " (" & Round(sqr(pow(dblLatDiff*110.7)+pow(dblLonDiff*75.6))/KMperMile,1) & " " & strUnit & ")"
- If strUnit="km" Then strDistance = " (" & Round(sqr(pow(dblLatDiff*110.7)+pow(dblLonDiff*75.6)),1) & " " & strUnit & ")"
- strResultlist = strResultlist & rs.Fields("zipcode") & " " & rs.Fields("city") & ", " & rs.Fields("areacode") & strDistance & "
- "
- End If
- End If
- intCounter=2
- rs.MoveNext
- Wend
- strCondition = strCondition & ")"
- 'strCondition contains the SQL-WHERE statement that could now be used to extract all the 'in-radius' datasets out of another table
- rs.Close
- Set rs = Nothing
- Set conn = Nothing
- Function iif(condition,isTrue,isFalse)
- If (condition) Then
- iif = isTrue
- Else
- iif = isFalse
- End If
- End Function
- Function pow(i)
- pow = i*i
- End Function
- '======================================================================
- ' Google Map and draw Radius ircle
- '======================================================================
- %>
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
- <meta charset="utf-8">
- <title>ZIP Codes in a Radius</title>
- <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
- <script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.5/src/infobox.js"></script>
- <script>
- function init() {
- /////////////////////////////////////////
- /// Draw Map
- /////////////////////////////////////////
- var mapCenter = new google.maps.LatLng(<%=dblLatitude%>,<%=dblLongitude%>);
- var mapOptions = {
- zoom: 9,
- center: mapCenter,
- mapTypeId: google.maps.MapTypeId.ROADMAP,
- disableDefaultUI: true
- }
- var map = new google.maps.Map(document.getElementById("map"), mapOptions);
- /////////////////////////////////////////
- /// Draw Marker
- /////////////////////////////////////////
- var marker1 = new google.maps.Marker({
- position: mapCenter,
- map: map,
- zIndex: 2
- });
- /////////////////////////////////////////
- /// Draw Circle
- /////////////////////////////////////////
- var circle = new google.maps.Circle({
- map: map,
- radius: <%=dblRadius*1000%>, //Radius in Millimeter
- center: mapCenter,
- strokeColor: "#0000FF",
- strokeOpacity: 0.4,
- strokeWeight: 2,
- zIndex: 1,
- fillColor: "#FFCC00",
- fillOpacity: 0.25,
- zIndex: 1
- });
- /////////////////////////////////////////
- /// Draw Label
- /////////////////////////////////////////
- var labelText = document.createElement("div");
- 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;";
- labelText.innerHTML = "<%=strMaptxt%>";
- var myOptions = {
- content: labelText,
- disableAutoPan: true,
- zIndex: null,
- pixelOffset: new google.maps.Size(90, -170),
- position: mapCenter,
- closeBoxURL: "",
- isHidden: false,
- pane: "mapPane",
- zIndex: 3,
- enableEventPropagation: true
- };
- var ibLabel = new InfoBox(myOptions);
- ibLabel.open(map);
- /////////////////////////////////////////
- /// Zoom to fit
- /////////////////////////////////////////
- map.fitBounds(circle.getBounds());
- }
- </script>
- </head>
- <body onload="init()">
- <div id="map" style="width: 560px; height: 350px;"></div>
- <%=strResultlist%>
- </body>
- </html>
C# Script - Source Code 
- Tools_Radius.aspx:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Tools_Radius.aspx.cs" Inherits="ZIPCodeTools.Tools_Radius" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
- <meta charset="utf-8" />
- <title>ZIP Codes in a Radius</title>
- <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
- <script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.5/src/infobox.js"></script>
- <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
- <asp:Literal ID="litHeaderCode" runat="server"></asp:Literal>
- </head>
- <body onload="$(document).ready(function () { initialize(); });">
- <form id="form1" runat="server">
- <div>
- <asp:literal ID="litMessages" runat="server"></asp:literal>
- <div id="map" style="width: 560px; height: 350px;"></div>
- <div id="outputDiv" style="width: 300px; height: 50px;" ></div>
- <asp:Literal ID="lit_results" runat="server" />
- </div>
- </form>
- </body>
- </html>
- Tools_Radius.aspx.cs:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data.SqlClient;
- using System.Data;
- using System.Text;
- namespace ZIPCodeTools
- {
- public partial class Tools_Radius : System.Web.UI.Page
- {
- DataTools dt = new DataTools();
- protected void Page_Load(object sender, EventArgs e)
- {
- string ErrorMessage = "";
- if (Request.Params["zipcode"] == null || Request.Params["zipcode"].Length == 0)
- {
- ErrorMessage += "<li>Parameter zipcode cannot be missing or blank</li>";
- }
- if (Request.Params["country"] == null || Request.Params["country"].Length == 0)
- {
- ErrorMessage += "<li>Parameter country cannot be missing or blank</li>";
- }
- if (Request.Params["radius"] == null || Request.Params["radius"].Length == 0)
- {
- ErrorMessage += "<li>Parameter radius cannot be missing or blank</li>";
- }
- if (Request.Params["unit"] == null || Request.Params["unit"].Length == 0)
- {
- ErrorMessage += "<li>Parameter unit cannot be missing or blank</li>";
- }
- if (ErrorMessage.Length > 0)
- {
- litMessages.Text = String.Format("<ul>{0}</ul>", ErrorMessage);
- }
- else
- Calculate();
- }
- public void Calculate()
- {
- try
- {
- double dblLongitude = 0d;
- double dblLatitude = 0d;
- string strCity = string.Empty;
- string strMaptxt = string.Empty;
- string strAreacode = string.Empty;
- string strCountry = string.Empty;
- string strDistance = string.Empty;
- string strResultlist = string.Empty;
- string strCondition = string.Empty;
- const double KMperMile = 1.609344;
- const double Pi = 3.141592654;
- string unit;
- unit = Request["unit"].ToString();
- double dblRadius = 0d;
- double.TryParse(Request["radius"].ToString(), out dblRadius);
- if (unit.Equals("miles"))
- dblRadius = dblRadius * KMperMile;
- strCountry = Request["country"].ToString().ToLower();
- string strZIPName = string.Empty;
- string strZIPCode = Request["zipcode"].ToString();
- if ( strCountry.Equals("us") )
- strZIPName = " ZIP Code";
- else if ( strCountry.Equals("ca") )
- strZIPName = " Postal Code";
- SqlCommand cmd = new SqlCommand();
- if ( strCountry.Equals("us") )
- cmd.CommandText = "SELECT * FROM us WHERE zipcode = @Zipcode";
- else if ( strCountry.Equals("ca") )
- cmd.CommandText = "SELECT * FROM ca WHERE postalcode = @Zipcode";
- cmd.Parameters.Add("@ZipCode", SqlDbType.VarChar, 5).Value = Request["zipcode"].ToString();
- DataSet ds = dt.GetDataSet(cmd, DataTools.DataSources.zipcodesoft);
- if ( ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0 )
- {
- DataRow dr = ds.Tables[0].Rows[0];
- double.TryParse(dr["longitude"].ToString(), out dblLongitude);
- double.TryParse(dr["latitude"].ToString(), out dblLatitude);
- strCity = dr["city"].ToString();
- strMaptxt = Request["radius"].ToString() + " " + unit + " around " + strZIPName + "
- " + strZIPCode + " " + strCity;
- if ( strCountry.Equals("us"))
- strAreacode = dr["statecode"].ToString();
- else if (strCountry.Equals("ca") )
- strAreacode = dr["provincecode"].ToString();
- }
- //======================================================================
- // Calculate all ZIP Codes in within the given Radius
- //======================================================================
- cmd = new SqlCommand();
- string dblDistanceCalc = "SQRT(POWER((" + dblLatitude + "-latitude)*110.7,2)+POWER((" + dblLongitude + "-longitude)*75.6,2))";
- string sql = string.Empty;
- if ( strCountry.Equals("us"))
- sql = "SELECT city, statecode AS areacode, longitude, latitude, zipcode, " + dblDistanceCalc + " AS distance FROM us WHERE " + dblDistanceCalc + " <= " + dblRadius + " ORDER BY " + dblDistanceCalc + " ASC";
- else if (strCountry.Equals("ca"))
- sql = "SELECT city, provincecode AS areacode, longitude, latitude, postalcode AS zipcode, " + dblDistanceCalc + " AS distance FROM ca WHERE " + dblDistanceCalc + " <= " + dblRadius + " ORDER BY " + dblDistanceCalc + " ASC";
- cmd.CommandText = sql;
- ds = dt.GetDataSet(cmd, DataTools.DataSources.zipcodesoft);
- int intCounter = 1;
- double dblLatDiff = 0d;
- double dblLonDiff = 0d;
- if ( ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0 )
- {
- foreach ( DataRow dr in ds.Tables[0].Rows )
- {
- if ( intCounter == 1 )
- {
- strDistance = " (0 " + unit + ")" ;
- strResultlist = dr["zipcode"].ToString() + " " + dr["city"].ToString() + ", " + dr["areacode"].ToString() + strDistance + "
- ";
- strCondition = " zipcode IN ('" + dr["zipcode"] + "'";
- }
- else
- {
- if ( !strCondition.Contains(dr["zipcode"].ToString() ))
- {
- double latitude = 0d;
- double longitude = 0d;
- double.TryParse(dr["latitude"].ToString(), out latitude);
- double.TryParse(dr["longitude"].ToString(), out longitude);
- strCondition = strCondition + ", '" + dr["zipcode"] + "'";
- dblLatDiff = dblLatitude - latitude;
- dblLonDiff = dblLongitude - longitude;
- if (unit.Equals("miles"))
- strDistance = " (" + Math.Round(Math.Sqrt(Math.Pow(dblLatDiff * 110.7, 2d) + Math.Pow(dblLonDiff * 75.6, 2d)) / KMperMile, 1, MidpointRounding.AwayFromZero) + " " + unit + ")";
- else if (unit.Equals("km"))
- strDistance = " (" + Math.Round(Math.Sqrt(Math.Pow(dblLatDiff * 110.7, 2d) + Math.Pow(dblLonDiff * 75.6, 2d)), 1, MidpointRounding.AwayFromZero) + " " + unit + ")";
- strResultlist = strResultlist + dr["zipcode"].ToString() + " " + dr["city"].ToString() + ", " + dr["areacode"] + strDistance + "
- ";
- }
- }
- intCounter = 2;
- }
- }
- lit_results.Text = strResultlist;
- //Begin Creating Website Javascript Code
- StringBuilder output = new StringBuilder();
- output.Append("function initialize() {");
- output.Append(Environment.NewLine);
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append(" /// Draw map");
- output.Append(Environment.NewLine);
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append("var mapCenter = new google.maps.LatLng(").Append(dblLatitude).Append(",").Append(dblLongitude).Append(");");
- output.Append(Environment.NewLine);
- output.Append(" var mapOptions = {");
- output.Append(" zoom: 9,");
- output.Append(" center: mapCenter,");
- output.Append(" mapTypeId: google.maps.MapTypeId.ROADMAP,");
- output.Append(" disableDefaultUI: true");
- output.Append(" };");
- output.Append(" var map = new google.maps.Map(document.getElementById('map'), mapOptions);");
- output.Append(Environment.NewLine);
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append(" /// Draw marker");
- output.Append(Environment.NewLine);
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append(" var marker1 = new google.maps.Marker({");
- output.Append(" position: mapCenter,");
- output.Append(" map: map,");
- output.Append(" zIndex: 2");
- output.Append(" });");
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append(" /// Draw Circle");
- output.Append(Environment.NewLine);
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine).
- Append("var circle = new google.maps.Circle({").
- Append(Environment.NewLine).
- Append("map: map,").
- Append(Environment.NewLine).
- Append("radius: ").Append(dblRadius*1000).Append(",").
- Append(Environment.NewLine).
- Append("center: mapCenter,").
- Append(Environment.NewLine).
- Append("strokeColor: \"#0000FF\",").
- Append(Environment.NewLine).
- Append("strokeOpacity: 0.4,").
- Append(Environment.NewLine).
- Append("strokeWeight: 2,").
- Append(Environment.NewLine).
- Append("zIndex: 1,").
- Append(Environment.NewLine).
- Append("fillColor: \"#FFCC00\",").
- Append(Environment.NewLine).
- Append("fillOpacity: 0.25, ").
- Append(Environment.NewLine).
- Append("});").
- Append(Environment.NewLine).
- Append("/////////////////////////////////////////").
- Append(Environment.NewLine).
- Append("/// Draw Label").
- Append(Environment.NewLine).
- Append("/////////////////////////////////////////").
- Append(Environment.NewLine).
- Append("var labelText = document.createElement(\"div\");").
- Append(Environment.NewLine).
- 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;\";").
- Append(Environment.NewLine).
- Append("labelText.innerHTML = \"").Append(strMaptxt).Append("\";").
- Append(Environment.NewLine).
- Append("var myOptions = {").
- Append(Environment.NewLine).
- Append("content: labelText,").Append(Environment.NewLine).
- Append("disableAutoPan: true,").Append(Environment.NewLine).
- Append("pixelOffset: new google.maps.Size(90, -170),").Append(Environment.NewLine).
- Append("position: mapCenter,").Append(Environment.NewLine).
- Append("closeBoxURL: \"\",").Append(Environment.NewLine).
- Append("isHidden: false,").Append(Environment.NewLine).
- Append("pane: \"mapPane\",").Append(Environment.NewLine).
- Append("zIndex: 3,").Append(Environment.NewLine).
- Append("enableEventPropagation: true").Append(Environment.NewLine).
- Append("};").Append(Environment.NewLine).
- Append("var ibLabel = new InfoBox(myOptions);").Append(Environment.NewLine).
- Append("ibLabel.open(map);").Append(Environment.NewLine).
- Append("/////////////////////////////////////////").Append(Environment.NewLine).
- Append("/// Zoom to fit").Append(Environment.NewLine).
- Append("/////////////////////////////////////////").Append(Environment.NewLine).
- Append("map.fitBounds(circle.getBounds());").Append(Environment.NewLine).
- Append("}");
- //output.Append("</script>");
- Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptAPI", output.ToString(), true);
- //litHeaderCode.Text = output.ToString();
- }
- catch (Exception ex)
- {
- }
- }
- }
- }
Coldfusion Script - Source Code 
- <!---
- '======================================================================
- ' ZIP Codes in a Radius in USA and Canada
- '
- ' This CFM Script requires 3 GET parameters: zipcode and country (us/ca) and unit (miles/km)
- ' Plus the database tables us and ca containing the ZIP Code-Lon/Lat data.
- '
- ' Example call: tools_radius.cfm?zipcode=90210&country=us&radius=10&unit=miles
- '
- ' © 2012 www.zipcodesoft.com, All Rights Reserved
- '======================================================================
- --->
- <cfsetting showdebugoutput="false">
- <!--- This is data source name defined in coldfusion administrator --->
- <cfset rs = "geodb">
- <cfset strZIPCode = "">
- <cfset strCountry = "">
- <cfset dblRadius = "">
- <cfset strUnit = "">
- <cfset dblLongitude = "">
- <cfset dblLatitude = "">
- <cfset strZIPName = "">
- <cfset strCity = "">
- <cfset strMaptxt = "">
- <cfset strAreacode = "">
- <cfset strDistance = "">
- <cfset strResultlist = "">
- <cfset strCondition = "">
- <cfset KMperMile = 1.609344>
- <cfset Pi = 3.141592654>
- <cfset strZIPCode = URL.zipcode>
- <cfset strCountry = URL.country>
- <cfset strRadius = URL.radius>
- <cfset dblRadius = strRadius>
- <cfset strUnit = URL.unit>
- <cfif strUnit eq "miles">
- <cfset dblRadius = dblRadius * KMperMile>
- </cfif>
- <!--- '======================================================================
- ' Set the correct term: ZIP Code = USA or Postal Code = Canada
- '====================================================================== --->
- <cfif strCountry eq "us">
- <cfset strZIPName = "ZIP Code">
- <cfelseif strCountry eq "ca">
- <cfset strZIPName = "Postal Code">
- </cfif>
- <cfif strCountry eq "us">
- <cfquery name="getZipcodes" datasource="#rs#">
- SELECT * FROM us WHERE zipcode='#strZIPCode#'
- </cfquery>
- <cfelseif strCountry eq "ca">
- <cfquery name="getZipcodes" datasource="#rs#">
- SELECT * FROM ca WHERE postalcode='#strZIPCode#'
- </cfquery>
- </cfif>
- <cfif getZipcodes.recordcount gt 0>
- <cfset dblLongitude = getZipcodes.longitude>
- <cfset dblLatitude = getZipcodes.latitude>
- <cfset strCity = getZipcodes.city>
- <cfset strMaptxt = strRadius & " " & strUnit & " around " & strZIPName & "
- " & strZIPCode & " " & strCity>
- <cfif strCountry eq "us">
- <cfset strAreaCode = getZipcodes.statecode>
- </cfif>
- <cfif strCountry eq "ca">
- <cfset strAreaCode = getZipcodes.provincecode>
- </cfif>
- <cfelse>
- <cfoutput>#strZIPName# Not found</cfoutput>
- </cfif>
- <!--- '======================================================================
- ' Calculate all ZIP Codes in within the given Radius
- '====================================================================== --->
- <cfset dblDistanceCalc = "SQRT(((" & dblLatitude & "-latitude)*110.7*(" & dblLatitude & "-latitude)*110.7)+((" & dblLongitude & "-longitude)*75.6*(" & dblLongitude & "-longitude)*75.6))">
- <!--- <cfoutput>#dblDistanceCalc#</cfoutput><cfabort> --->
- <cfif strCountry eq "us">
- <cfquery name="getAllData" datasource="#rs#">
- SELECT city, statecode AS areacode, longitude, latitude, zipcode, #dblDistanceCalc# AS distance
- FROM us
- WHERE #dblDistanceCalc# <= #dblRadius#
- ORDER BY #dblDistanceCalc# ASC
- </cfquery>
- <cfelseif strCountry eq "ca">
- <cfquery name="getAllData" datasource="#rs#">
- SELECT city, provincecode AS areacode, longitude, latitude, postalcode AS zipcode, #dblDistanceCalc# AS distance
- FROM ca
- WHERE #dblDistanceCalc# <= #dblRadius#
- ORDER BY #dblDistanceCalc# ASC
- </cfquery>
- </cfif>
- <cffunction name = "pow" returntype="numeric">
- <cfargument name="num" type="numeric" required="true">
- <cfreturn arguments.num * arguments.num>
- </cffunction>
- <cffunction name="roundToX" returntype="numeric">
- <cfargument name="num" type="numeric" required="yes">
- <cfset RoundedNumber = num * 10>
- <cfset RoundedNumber = Round(RoundedNumber )>
- <cfset RoundedNumber = RoundedNumber / 10>
- <cfreturn RoundedNumber>
- </cffunction>
- <cfset intCounter = 1>
- <cfset dblLatDiff = "">
- <cfset dblLonDiff = "">
- <cfloop query="getAllData">
- <cfif intCounter eq 1>
- <cfset strDistance = " (0 " & strUnit & ")">
- <cfset strResultlist = getAllData.zipcode & " " & getAllData.city & ", " & getAllData.areacode & strDistance & "
- ">
- <cfset strCondition = " zipcode IN ('" & getAllData.zipcode & "'">
- <cfelse>
- <cfif FindNoCase(getAllData.zipcode, strCondition) eq 0>
- <cfset strCondition = strCondition & ", '" & getAllData.zipcode & "'">
- <cfset dblLatDiff = dblLatitude - getAllData.latitude>
- <cfset dblLonDiff = dblLongitude - getAllData.longitude>
- <cfif strUnit eq "miles">
- <cfset strDistance = " (" & roundToX(sqr(pow(dblLatDiff*110.7)+pow(dblLonDiff*75.6))/KMperMile) & " " & strUnit & ")">
- </cfif>
- <cfif strUnit eq "km">
- <cfset strDistance = " (" & roundToX(sqr(pow(dblLatDiff*110.7)+pow(dblLonDiff*75.6))) & " " & strUnit & ")">
- </cfif>
- <cfset strResultlist = strResultlist & getAllData.zipcode & " " & getAllData.city & ", " & getAllData.areacode & strDistance & "
- ">
- </cfif>
- </cfif>
- <cfset intCounter=2>
- </cfloop>
- <cfset strCondition = strCondition & ")">
- <!--- 'strCondition contains the SQL-WHERE statement that could now be used to extract all the 'in-radius' datasets out of another table --->
- <!--- '======================================================================
- ' Google Map and draw Radius Circle
- '====================================================================== --->
- <cfoutput>
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
- <meta charset="utf-8">
- <title>ZIP Codes in a Radius</title>
- <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
- <script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.5/src/infobox.js"></script>
- <script>
- function init() {
- /////////////////////////////////////////
- /// Draw Map
- /////////////////////////////////////////
- var mapCenter = new google.maps.LatLng(#dblLatitude#,#dblLongitude#);
- var mapOptions = {
- zoom: 9,
- center: mapCenter,
- mapTypeId: google.maps.MapTypeId.ROADMAP,
- disableDefaultUI: true
- }
- var map = new google.maps.Map(document.getElementById("map"), mapOptions);
- /////////////////////////////////////////
- /// Draw Marker
- /////////////////////////////////////////
- var marker1 = new google.maps.Marker({
- position: mapCenter,
- map: map,
- zIndex: 2
- });
- /////////////////////////////////////////
- /// Draw Circle
- /////////////////////////////////////////
- var circle = new google.maps.Circle({
- map: map,
- radius: #dblRadius*1000#, //Radius in Millimeter
- center: mapCenter,
- strokeColor: "##0000FF",
- strokeOpacity: 0.4,
- strokeWeight: 2,
- zIndex: 1,
- fillColor: "##FFCC00",
- fillOpacity: 0.25,
- });
- /////////////////////////////////////////
- /// Draw Label
- /////////////////////////////////////////
- var labelText = document.createElement("div");
- 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;";
- labelText.innerHTML = "#strMaptxt#";
- var myOptions = {
- content: labelText,
- disableAutoPan: true,
- pixelOffset: new google.maps.Size(90, -170),
- position: mapCenter,
- closeBoxURL: "",
- isHidden: false,
- pane: "mapPane",
- zIndex: 3,
- enableEventPropagation: true
- };
- var ibLabel = new InfoBox(myOptions);
- ibLabel.open(map);
- /////////////////////////////////////////
- /// Zoom to fit
- /////////////////////////////////////////
- map.fitBounds(circle.getBounds());
- }
- </script>
- </head>
- <body onload="init()">
- <div id="map" style="width: 560px; height: 350px;"></div>
- #strResultlist#
- </body>
- </html>
- </cfoutput>