Distance between Postal Codes

Test our free Canada Postal Code Distance Calculator and download our free scripts that are perfectly compatible with our Postal Code databases.





Usage


Calculate the distance between two Canadian Postal codes to show your users the distance (road distance or as the crow flies) to the nearest store or dealer. It allows your website's visitors to find the nearest dealers to their home by entering their own Postal code.

PHP Script - Source Code PHP Script


  1. <?php  
  2. /*====================================================================== 
  3. ** Distance between two ZIP Codes in USA or Canada 
  4. ** 
  5. ** This PHP Script requires 5 GET parameters: zipcode1, country1 (us/ca), zipcode2, country2, unit (miles/km) 
  6. ** Plus the database tables us and ca containing the ZIP Code-Lon/Lat data 
  7. ** 
  8. ** Example call: tools_distance.php?zipcode1=90210&country1=us&zipcode2=60601&country2=us&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. /* Get coordinates for a given ZIP Code value */  
  33. /* ----------------------------- */  
  34. function getCoordsByZip($sCountry$sZipValue) {  
  35.     if (!($sZipName= getZipName($sCountry))) return false;  
  36.     $sql"SELECT `longitude`, `latitude` FROM `$sCountry` WHERE `$sZipName`='$sZipValue' LIMIT 1";  
  37.     if (!($h_res= mysql_query($sql)) || !mysql_num_rows($h_res)) return false;  
  38.     $b_ok= ($a_row= mysql_fetch_row($h_res)) && count($a_row) == 2;  
  39.     mysql_free_result($h_res);  
  40.     return $b_ok$a_row : false;  
  41. }  
  42.   
  43. /* ----------------------------- */  
  44. /* Start of Script */  
  45. /* Get parameters */  
  46. /* ----------------------------- */  
  47. define('F_KMPERMILE', 1.609344  );  
  48. define('F_PI', 3.141592654  );  
  49. define('F_RADIAN_MUL', 3958.754 );  
  50.   
  51. $b_ok=   
  52.     isset($_REQUEST['zipcode1']) && isset($_REQUEST['country1']) &&  
  53.     isset($_REQUEST['zipcode2']) && isset($_REQUEST['country2']);  
  54. if (!$b_ok)  
  55.     die("Error: parameters are missed");  
  56.   
  57. $sZipCode1 = $_REQUEST['zipcode1'];  
  58. $sCountry1 = $_REQUEST['country1'];  
  59. $sZipCode2 = $_REQUEST['zipcode2'];  
  60. $sCountry2 = $_REQUEST['country2'];  
  61. $sUnit = (isset($_REQUEST['unit']) && $_REQUEST['unit'] == "km")? "km" : "miles";  
  62.   
  63. /* ----------------------------- */  
  64. /* Get coordinates of first ZIP Code */  
  65. /* ----------------------------- */  
  66. if (!($a_coords1 = getCoordsByZip($sCountry1$sZipCode1)))  
  67.     die("Error: zipcode1 not found");  
  68. /* ----------------------------- */  
  69. /* Get coordinates of second ZIP Code */  
  70. /* ----------------------------- */  
  71. if (!($a_coords2 = getCoordsByZip($sCountry2$sZipCode2)))  
  72.     die("Error: zipcode2 not found");  
  73. list($sLongitude1$sLatitude1)= $a_coords1;  
  74. list($sLongitude2$sLatitude2)= $a_coords2;  
  75.   
  76. /* ----------------------------- */  
  77. /* As the Crow flies - Calculation in due consideration of Earth curvation */  
  78. /* ----------------------------- */  
  79. $fLatitudeRadians1 = (float)$sLatitude1 * F_PI / 180;  
  80. $fLongitudeRadians1 = (float)$sLongitude1 * F_PI / 180;  
  81. $fLatitudeRadians2 = (float)$sLatitude2 * F_PI / 180;  
  82. $fLongitudeRadians2 = (float)$sLongitude2 * F_PI / 180;  
  83. $fLongitudeRadiansDifference = abs($fLongitudeRadians1 - $fLongitudeRadians2);  
  84. $fX = sin($fLatitudeRadians1) * sin($fLatitudeRadians2) +  
  85.     cos($fLatitudeRadians1) * cos($fLatitudeRadians2) * cos($fLongitudeRadiansDifference);  
  86. $fRadiansDistance = atan(-$fX / sqrt(-$fX * $fX + 1)) + 2 * atan(1);  
  87. if ($sUnit == "km")  
  88.     $fDistance = round($fRadiansDistance * F_RADIAN_MUL* F_KMPERMILE, 0);  
  89. else  
  90.     $fDistance = round($fRadiansDistance * F_RADIAN_MUL, 0);  
  91.   
  92. /* ----------------------------- */  
  93. /* Google Map and Road distance Calculation */  
  94. /* ----------------------------- */  
  95. ?><!DOCTYPE html>  
  96. <html>  
  97.   <head>  
  98.     <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
  99.     <meta charset="utf-8">  
  100.     <title>Distance between 2 ZIP Codes</title>  
  101.   
  102.   
  103. <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>  
  104. <script>  
  105.   
  106. var directionDisplay;  
  107. var directionsService = new google.maps.DirectionsService();  
  108.   
  109. function initialize() {  
  110.     ///////////////////////////////////  
  111.     /// Draw map  
  112.     ///////////////////////////////////  
  113.     var mapOptions = {  
  114.         zoom: 9,  
  115.         mapTypeId: google.maps.MapTypeId.ROADMAP,  
  116.         disableDefaultUI: true  
  117.     }  
  118.     var map = new google.maps.Map(document.getElementById('map'), mapOptions);  
  119.     var latlngbounds = new google.maps.LatLngBounds();  
  120.   
  121.     ///////////////////////////////////  
  122.     /// Draw first marker  
  123.     ///////////////////////////////////  
  124.     var pos1 = new google.maps.LatLng(<?=$sLatitude1?>,<?=$sLongitude1?>);  
  125.     latlngbounds.extend(pos1);  
  126.     var marker1 = new google.maps.Marker({  
  127.         position: pos1,  
  128.         map: map  
  129.     });  
  130.   
  131.     ///////////////////////////////////  
  132.     /// Draw second marker  
  133.     ///////////////////////////////////  
  134.     var pos2 = new google.maps.LatLng(<?=$sLatitude2?>,<?=$sLongitude2?>);  
  135.     latlngbounds.extend(pos2);  
  136.     var marker2 = new google.maps.Marker({  
  137.         position: pos2,  
  138.         map: map  
  139.     });  
  140.   
  141.     ///////////////////////////////////  
  142.     /// Draw Beeline  
  143.     ///////////////////////////////////  
  144.     var linecoords = [pos1,pos2];  
  145.     var linepath = new google.maps.Polyline({path: linecoords,strokeColor: "#F81",strokeOpacity: 1.0,strokeWeight: 3});  
  146.     linepath.setMap(map);  
  147.   
  148.     ///////////////////////////////////  
  149.     /// Draw Road connection  
  150.     ///////////////////////////////////  
  151.     directionsDisplay = new google.maps.DirectionsRenderer();  
  152.     var directionRendererOptions ={suppressMarkers: true,preserveViewport: true,polylineOptions:{strokeColor: "#00F",strokeOpacity: 0.5,strokeWeight: 3}};   
  153.     directionsDisplay.setOptions(directionRendererOptions);   
  154.     directionsDisplay.setMap(map);  
  155.     var request = {origin:"<?=$sLatitude1?>,<?=$sLongitude1?>",destination:"<?=$sLatitude2?>,<?=$sLongitude2?>",travelMode: google.maps.DirectionsTravelMode.DRIVING};  
  156.     directionsService.route(request, function(response, status) {if (status == google.maps.DirectionsStatus.OK) {directionsDisplay.setDirections(response);}});  
  157.     calculateDistances("<?=$sUnit?>");  
  158.   
  159.     map.fitBounds(latlngbounds);  
  160.     map.panToBounds(latlngbounds);  
  161. }  
  162.   
  163. ///////////////////////////////////  
  164. /// Calculate Road Distance  
  165. ///////////////////////////////////  
  166. function calculateDistances(unit) {  
  167. var service = new google.maps.DistanceMatrixService();  
  168. if(unit=="km"){  
  169. service.getDistanceMatrix(  
  170.     {  
  171.         origins: [new google.maps.LatLng(<?=$sLatitude1?>,<?=$sLongitude1?>)],  
  172.         destinations: [new google.maps.LatLng(<?=$sLatitude2?>,<?=$sLongitude2?>)],  
  173.     travelMode: google.maps.TravelMode.DRIVING,  
  174.     unitSystem: google.maps.UnitSystem.METRIC,  
  175.     avoidHighways: false,  
  176.     avoidTolls: false  
  177.     }, callback);  
  178.     }  
  179. if(unit=="miles"){  
  180. service.getDistanceMatrix(  
  181.     {  
  182.         origins: [new google.maps.LatLng(<?=$sLatitude1?>,<?=$sLongitude1?>)],  
  183.         destinations: [new google.maps.LatLng(<?=$sLatitude2?>,<?=$sLongitude2?>)],  
  184.     travelMode: google.maps.TravelMode.DRIVING,  
  185.     unitSystem: google.maps.UnitSystem.IMPERIAL,  
  186.     avoidHighways: false,  
  187.     avoidTolls: false  
  188.     }, callback);  
  189.     }  
  190. }  
  191.   
  192. function callback(response, status) {  
  193. if (status != google.maps.DistanceMatrixStatus.OK) {  
  194.     alert('Error was: ' + status);  
  195. else {  
  196.     var origins = response.originAddresses;  
  197.     var destinations = response.destinationAddresses;  
  198.     var outputDiv = document.getElementById('outputDiv');  
  199.     outputDiv.innerHTML = '';  
  200.     var distance;  
  201.     for (var i = 0; i < origins.length; i++) {  
  202.     var results = response.rows[i].elements;  
  203.     for (var j = 0; j < results.length; j++) {  
  204.     distance = results[j].distance.text;  
  205.     distance = distance.replace("mi""");  
  206.     distance = distance.replace("km""");  
  207.     distance = distance.replace(",""");  
  208.         outputDiv.innerHTML += "Result:  
  209. Distance: " + distance + ' <?=$sUnit?> (Road)  
  210. ' + "Distance: <?=$fDistance." ".$sUnit?> (Beeline)";  
  211.     }  
  212.     }  
  213. }  
  214. }  
  215. </script>  
  216.   
  217. </head>  
  218.   <body onload="initialize()">  
  219.     <div id="map" style="width: 300px; height: 300px;"></div>  
  220.     <div id="outputDiv" style="width: 300px; height: 50px;" ></div>  
  221.   </body>  
  222. </html>  
Download PHP script with sample database

ASP Script - Source CodeASP Script


  1. <%  
  2. '======================================================================  
  3. ' Distance between two ZIP Codes in USA and Canada  
  4. '  
  5. ' This ASP Script requires 5 GET parameters: zipcode1 and country1 (us/ca) and zipcode2 and country2 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_distance_asp.asp?zipcode1=90210&country1=us&zipcode2=60601&country2=us&unit=miles  
  9. '   
  10. ' © 2012 http://www.zipcodesoft.com, All Rights Reserved  
  11. '======================================================================  
  12.   
  13. Dim strZIPCode1  
  14. Dim strZIPCode2  
  15. Dim strCountry1  
  16. Dim strCountry2  
  17. Dim strUnit  
  18. Dim strLongitude1  
  19. Dim strLongitude2  
  20. Dim strLatitude1  
  21. Dim strLatitude2  
  22. Dim strZIPName1  
  23. Dim strZIPName2  
  24. Dim dblLatitudeRadians1  
  25. Dim dblLatitudeRadians2  
  26. Dim dblLongitudeRadians1  
  27. Dim dblLongitudeRadians2  
  28. Dim dblLongitudeRadiansDifference  
  29. Dim dblRadiansDistance  
  30. Dim dblX  
  31. Dim dblDistance  
  32.   
  33. Const KMperMile = 1.609344  
  34. Const Pi = 3.141592654  
  35.   
  36. strZIPCode1 = Request("zipcode1")  
  37. strCountry1 = Request("country1")  
  38. strZIPCode2 = Request("zipcode2")  
  39. strCountry2 = Request("country2")  
  40. strUnit = Request("unit")  
  41.   
  42.   
  43. Set conn =  Server.CreateObject("ADODB.Connection")  
  44. conn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & server.mappath("/db/geo.mdb")  
  45. Set rs = Server.CreateObject("ADODB.Recordset")  
  46.   
  47. '======================================================================  
  48. ' Set the correct term: ZIP Code = USA or Postal Code = Canada  
  49. '======================================================================  
  50. If strCountry1="us" Then strZIPName1 = "ZIP Code"  
  51. If strCountry1="ca" Then strZIPName1 = "Postal Code"  
  52.   
  53. '======================================================================  
  54. ' Get coordinates of first ZIP Code  
  55. '======================================================================  
  56. If strCountry1="us" Then sql = "SELECT * FROM us WHERE zipcode='" & strZIPCode1 & "';"  
  57. If strCountry1="ca" Then sql = "SELECT * FROM ca WHERE postalcode='" & strZIPCode1 & "';"  
  58.   
  59. Set rs = conn.Execute(sql)  
  60. If Not rs.EOF Then  
  61.     strLongitude1 = rs.Fields("longitude")  
  62.     strLatitude1 = rs.Fields("latitude")  
  63. Else  
  64.     Response.Write(strZIPName1 & "1 Not found")  
  65. End If  
  66. rs.Close  
  67.   
  68. '======================================================================  
  69. ' Set the correct term: ZIP Code = USA or Postal Code = Canada  
  70. '======================================================================  
  71. If strCountry2="us" Then strZIPName2 = "ZIP Code"  
  72. If strCountry2="ca" Then strZIPName2 = "Postal Code"  
  73.   
  74. '======================================================================  
  75. ' Get coordinates of second ZIP Code  
  76. '======================================================================  
  77. If strCountry2="us" Then sql = "SELECT * FROM us WHERE zipcode='" & strZIPCode2 & "';"  
  78. If strCountry2="ca" Then sql = "SELECT * FROM ca WHERE postalcode='" & strZIPCode2 & "';"  
  79.   
  80. Set rs = conn.Execute(sql)  
  81. If Not rs.EOF Then  
  82.     strLongitude2 = rs.Fields("longitude")  
  83.     strLatitude2 = rs.Fields("latitude")  
  84. Else  
  85.     Response.Write(strZIPName2 & "2 Not found")  
  86. End If  
  87. rs.Close  
  88.   
  89. '======================================================================  
  90. ' As the Crow flies - Calculation in due consideration of Earth curvation  
  91. '======================================================================  
  92. dblLatitudeRadians1 = CDbl(strLatitude1) * Pi / 180  
  93. dblLongitudeRadians1 = CDbl(strLongitude1) * Pi / 180  
  94. dblLatitudeRadians2 = CDbl(strLatitude2) * Pi / 180  
  95. dblLongitudeRadians2 = CDbl(strLongitude2) * Pi / 180  
  96. dblLongitudeRadiansDifference = Abs(dblLongitudeRadians1 - dblLongitudeRadians2)  
  97. dblX = Sin(dblLatitudeRadians1) * Sin(dblLatitudeRadians2) + Cos(dblLatitudeRadians1) * Cos(dblLatitudeRadians2) * Cos(dblLongitudeRadiansDifference)  
  98. dblRadiansDistance = Atn(-dblX / Sqr(-dblX * dblX + 1)) + 2 * Atn(1)  
  99. If strUnit = "km" Then  
  100.     dblDistance = Round(dblRadiansDistance * 3958.754 * KMperMile,0)  
  101. Else  
  102.     dblDistance = Round(dblRadiansDistance * 3958.754,0)  
  103. End If  
  104.   
  105. '======================================================================  
  106. ' Google Map and Road distance Calculation  
  107. '======================================================================  
  108. %>  
  109. <!DOCTYPE html>  
  110. <html>  
  111.   <head>  
  112.     <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
  113.     <meta charset="utf-8">  
  114.     <title>Distance between 2 ZIP Codes</title>  
  115.   
  116.   
  117. <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>  
  118. <script>  
  119.   
  120. var directionDisplay;  
  121. var directionsService = new google.maps.DirectionsService();  
  122.   
  123. function initialize() {  
  124.     ///////////////////////////////////  
  125.     /// Draw map  
  126.     ///////////////////////////////////  
  127.     var mapOptions = {  
  128.         zoom: 9,  
  129.         mapTypeId: google.maps.MapTypeId.ROADMAP,  
  130.         disableDefaultUI: true  
  131.     }  
  132.     var map = new google.maps.Map(document.getElementById('map'), mapOptions);  
  133.     var latlngbounds = new google.maps.LatLngBounds();  
  134.   
  135.     ///////////////////////////////////  
  136.     /// Draw first marker  
  137.     ///////////////////////////////////  
  138.     var pos1 = new google.maps.LatLng(<%=strLatitude1%>,<%=strLongitude1%>);  
  139.     latlngbounds.extend(pos1);  
  140.     var marker1 = new google.maps.Marker({  
  141.         position: pos1,  
  142.         map: map  
  143.     });  
  144.   
  145.     ///////////////////////////////////  
  146.     /// Draw second marker  
  147.     ///////////////////////////////////  
  148.     var pos2 = new google.maps.LatLng(<%=strLatitude2%>,<%=strLongitude2%>);  
  149.     latlngbounds.extend(pos2);  
  150.     var marker2 = new google.maps.Marker({  
  151.         position: pos2,  
  152.         map: map  
  153.     });  
  154.   
  155.     ///////////////////////////////////  
  156.     /// Draw Beeline  
  157.     ///////////////////////////////////  
  158.     var linecoords = [pos1,pos2];  
  159.     var linepath = new google.maps.Polyline({path: linecoords,strokeColor: "#F81",strokeOpacity: 1.0,strokeWeight: 3});  
  160.     linepath.setMap(map);  
  161.   
  162.     ///////////////////////////////////  
  163.     /// Draw Road connection  
  164.     ///////////////////////////////////  
  165.     directionsDisplay = new google.maps.DirectionsRenderer();  
  166.     var directionRendererOptions ={suppressMarkers: true,preserveViewport: true,polylineOptions:{strokeColor: "#00F",strokeOpacity: 0.5,strokeWeight: 3}};   
  167.     directionsDisplay.setOptions(directionRendererOptions);   
  168.     directionsDisplay.setMap(map);  
  169.     var request = {origin:"<%=strLatitude1%>,<%=strLongitude1%>",destination:"<%=strLatitude2%>,<%=strLongitude2%>",travelMode: google.maps.DirectionsTravelMode.DRIVING};  
  170.     directionsService.route(request, function(response, status) {if (status == google.maps.DirectionsStatus.OK) {directionsDisplay.setDirections(response);}});  
  171.     calculateDistances("<%=strUnit%>");  
  172.   
  173.     map.fitBounds(latlngbounds);  
  174.     map.panToBounds(latlngbounds);  
  175. }  
  176.   
  177. ///////////////////////////////////  
  178. /// Calculate Road Distance  
  179. ///////////////////////////////////  
  180. function calculateDistances(unit) {  
  181. var service = new google.maps.DistanceMatrixService();  
  182. if(unit=="km"){  
  183. service.getDistanceMatrix(  
  184.     {  
  185.         origins: [new google.maps.LatLng(<%=strLatitude1%>,<%=strLongitude1%>)],  
  186.         destinations: [new google.maps.LatLng(<%=strLatitude2%>,<%=strLongitude2%>)],  
  187.     travelMode: google.maps.TravelMode.DRIVING,  
  188.     unitSystem: google.maps.UnitSystem.METRIC,  
  189.     avoidHighways: false,  
  190.     avoidTolls: false  
  191.     }, callback);  
  192.     }  
  193. if(unit=="miles"){  
  194. service.getDistanceMatrix(  
  195.     {  
  196.         origins: [new google.maps.LatLng(<%=strLatitude1%>,<%=strLongitude1%>)],  
  197.         destinations: [new google.maps.LatLng(<%=strLatitude2%>,<%=strLongitude2%>)],  
  198.     travelMode: google.maps.TravelMode.DRIVING,  
  199.     unitSystem: google.maps.UnitSystem.IMPERIAL,  
  200.     avoidHighways: false,  
  201.     avoidTolls: false  
  202.     }, callback);  
  203.     }  
  204. }  
  205.   
  206. function callback(response, status) {  
  207. if (status != google.maps.DistanceMatrixStatus.OK) {  
  208.     alert('Error was: ' + status);  
  209. else {  
  210.     var origins = response.originAddresses;  
  211.     var destinations = response.destinationAddresses;  
  212.     var outputDiv = document.getElementById('outputDiv');  
  213.     outputDiv.innerHTML = '';  
  214.     var distance;  
  215.     for (var i = 0; i < origins.length; i++) {  
  216.     var results = response.rows[i].elements;  
  217.     for (var j = 0; j < results.length; j++) {  
  218.     distance = results[j].distance.text;  
  219.     distance = distance.replace("mi""");  
  220.     distance = distance.replace("km""");  
  221.     distance = distance.replace(",""");  
  222.         outputDiv.innerHTML += "Result:  
  223. Distance: " + distance + ' <%=strUnit%> (Road)  
  224. ' + "Distance: <%=dblDistance & " " & strUnit%> (Beeline)";  
  225.     }  
  226.     }  
  227. }  
  228. }  
  229. </script>  
  230.   
  231. </head>  
  232.   <body onload="initialize()">  
  233.     <div id="map" style="width: 300px; height: 300px;"></div>  
  234.     <div id="outputDiv" style="width: 300px; height: 50px;" ></div>  
  235.   </body>  
  236. </html>  
  237.    
Download ASP script with sample database

C# Script - Source Code C# Script


  1. Tools_Distance.aspx:  
  2.   
  3. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Tools_Distance.aspx.cs" Inherits="ZIPCodeTools.Tools_Distance" %>  
  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.     <title>Distance between 2 ZIP Codes</title>  
  10.   
  11. <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>  
  12. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  13. <%--<script type="text/javascript">  
  14.     $(document).ready(function () {  
  15.         initialize();  
  16.     });  
  17. </script>--%>  
  18.   
  19. <asp:Literal ID="litHeaderCode" runat="server"></asp:Literal>  
  20.   
  21. </head>  
  22. <body onload="$(document).ready(function () { initialize(); });">  
  23.     <form id="form1" runat="server">  
  24.     <div>  
  25.         <asp:literal ID="litMessages" runat="server"></asp:literal>  
  26.         <div id="map" style="width: 300px; height: 300px;"></div>  
  27.         <div id="outputDiv" style="width: 300px; height: 50px;" ></div>  
  28.     </div>  
  29.     </form>  
  30. </body>  
  31.   
  32. </html>  
  33.   
  34.   
  35.   
  36. Tools_Distance.aspx.cs:  
  37.   
  38. using System;  
  39. using System.Collections.Generic;  
  40. using System.Linq;  
  41. using System.Web;  
  42. using System.Web.UI;  
  43. using System.Web.UI.WebControls;  
  44. using System.Data.SqlClient;  
  45. using System.Data;  
  46. using System.Text;  
  47.   
  48. namespace ZIPCodeTools  
  49. {  
  50.     public partial class Tools_Distance : System.Web.UI.Page  
  51.     {  
  52.         DataTools dt = new DataTools();  
  53.   
  54.         protected void Page_Load(object sender, EventArgs e)  
  55.         {  
  56.             string ErrorMessage = "";  
  57.   
  58.             if (Request.Params["zipcode1"] == null || Request.Params["zipcode1"].Length == 0)  
  59.             {  
  60.                 ErrorMessage += "<li>Parameter zipcode1 cannot be missing or blank</li>";  
  61.             }  
  62.   
  63.             if (Request.Params["country1"] == null || Request.Params["country1"].Length == 0)  
  64.             {  
  65.                 ErrorMessage += "<li>Parameter country1 cannot be missing or blank</li>";  
  66.             }  
  67.   
  68.             if (Request.Params["zipcode2"] == null || Request.Params["zipcode2"].Length == 0)  
  69.             {  
  70.                 ErrorMessage += "<li>Parameter zipcode2 cannot be missing or blank</li>";  
  71.             }  
  72.   
  73.             if (Request.Params["country2"] == null || Request.Params["country2"].Length == 0)  
  74.             {  
  75.                 ErrorMessage += "<li>Parameter country2 cannot be missing or blank</li>";  
  76.             }  
  77.   
  78.             if (Request.Params["unit"] == null || Request.Params["unit"].Length == 0)  
  79.             {  
  80.                 ErrorMessage += "<li>Parameter unit cannot be missing or blank</li>";  
  81.             }  
  82.   
  83.             if (ErrorMessage.Length > 0)  
  84.             {  
  85.                 litMessages.Text = String.Format("<ul>{0}</ul>", ErrorMessage);  
  86.             }  
  87.             else  
  88.                 Calculate();  
  89.         }  
  90.   
  91.         public void Calculate()  
  92.         {  
  93.   
  94.             try  
  95.             {  
  96.   
  97.                 string unit;  
  98.                 unit = Request["unit"].ToString();  
  99.   
  100.                 SqlCommand cmd = new SqlCommand();  
  101.                 cmd.CommandText = "SELECT * FROM us WHERE countrycode = @CountryCode AND zipcode = @Zipcode;";  
  102.                 cmd.Parameters.Add("@CountryCode", SqlDbType.VarChar, 2).Value = Request["country1"].ToString();  
  103.                 cmd.Parameters.Add("@ZipCode", SqlDbType.VarChar, 5).Value = Request["zipcode1"].ToString();  
  104.   
  105.                 DataRow drOrigin = dt.GetDataSet(cmd, DataTools.DataSources.zipcodesoft).Tables[0].Rows[0];  
  106.   
  107.                 cmd = new SqlCommand();  
  108.                 cmd.CommandText = "SELECT * FROM us WHERE countrycode = @CountryCode AND zipcode = @Zipcode;";  
  109.                 cmd.Parameters.Add("@CountryCode", SqlDbType.VarChar, 2).Value = Request["country2"].ToString();  
  110.                 cmd.Parameters.Add("@ZipCode", SqlDbType.VarChar, 5).Value = Request["zipcode2"].ToString();  
  111.   
  112.                 DataRow drDestination = dt.GetDataSet(cmd, DataTools.DataSources.zipcodesoft).Tables[0].Rows[0];  
  113.   
  114.   
  115.                 double sLatitudeRadians = double.Parse(drOrigin["latitude"].ToString()) * (Math.PI / 180.0);  
  116.                 double sLongitudeRadians = double.Parse(drOrigin["longitude"].ToString()) * (Math.PI / 180.0);  
  117.                 double eLatitudeRadians = double.Parse(drDestination["latitude"].ToString()) * (Math.PI / 180.0);  
  118.                 double eLongitudeRadians = double.Parse(drDestination["longitude"].ToString()) * (Math.PI / 180.0);  
  119.   
  120.                 string oLatitude = drOrigin["latitude"].ToString();  
  121.                 string oLongitude = drOrigin["longitude"].ToString();  
  122.                 string dLatitude = drDestination["latitude"].ToString();  
  123.                 string dLongitude = drDestination["longitude"].ToString();  
  124.   
  125.                 double sLongitude = eLongitudeRadians - sLongitudeRadians;  
  126.                 double sLatitude = eLatitudeRadians - sLatitudeRadians;  
  127.   
  128.                 double result1 = Math.Pow(Math.Sin(sLatitude / 2.0), 2.0) +  
  129.                               Math.Cos(sLatitudeRadians) * Math.Cos(eLatitudeRadians) *  
  130.                               Math.Pow(Math.Sin(sLongitude / 2.0), 2.0);  
  131.   
  132.                 // Using 3956 as the number of miles around the earth  
  133.                 double result2 = 3958.754 * 2.0 *  
  134.                               Math.Atan2(Math.Sqrt(result1), Math.Sqrt(1.0 - result1));  
  135.   
  136.                 if (unit.ToUpper() == "KM")  
  137.                     result2 = result2 * (double)1.609344;  
  138.   
  139.                 //Begin Creating Website Javascript Code  
  140.                 StringBuilder output = new StringBuilder();  
  141. //output.Append("<script type=\"text/javascript\">");  
  142. output.Append(Environment.NewLine);  
  143. output.Append("var directionDisplay;");  
  144. output.Append(Environment.NewLine);  
  145. output.Append("var directionsService = new google.maps.DirectionsService();");  
  146. output.Append(Environment.NewLine);  
  147. output.Append("function initialize() {");  
  148. output.Append(Environment.NewLine);  
  149. output.Append("    ///////////////////////////////////");  
  150. output.Append(Environment.NewLine);  
  151. output.Append("    /// Draw map");  
  152. output.Append(Environment.NewLine);  
  153. output.Append("    ///////////////////////////////////");  
  154. output.Append(Environment.NewLine);  
  155. output.Append("    var mapOptions = {");  
  156. output.Append("        zoom: 9,");  
  157. output.Append("        mapTypeId: google.maps.MapTypeId.ROADMAP,");  
  158. output.Append("     disableDefaultUI: true");  
  159. output.Append("    };");  
  160. output.Append("    var map = new google.maps.Map(document.getElementById('map'), mapOptions);");  
  161. output.Append(" var latlngbounds = new google.maps.LatLngBounds();");  
  162.   
  163. output.Append("    ///////////////////////////////////");  
  164. output.Append(Environment.NewLine);  
  165. output.Append("    /// Draw first marker");  
  166. output.Append(Environment.NewLine);  
  167. output.Append("    ///////////////////////////////////");  
  168. output.Append(Environment.NewLine);  
  169. output.AppendFormat("   var pos1 = new google.maps.LatLng({0},{1});", oLatitude, oLongitude);  
  170. output.Append(" latlngbounds.extend(pos1);");  
  171. output.Append("    var marker1 = new google.maps.Marker({");  
  172. output.Append("        position: pos1,");  
  173. output.Append("        map: map");  
  174. output.Append("    });");  
  175.   
  176. output.Append("    ///////////////////////////////////");  
  177. output.Append(Environment.NewLine);  
  178. output.Append("    /// Draw second marker");  
  179. output.Append(Environment.NewLine);  
  180. output.Append("    ///////////////////////////////////");  
  181. output.Append(Environment.NewLine);  
  182. output.AppendFormat("    var pos2 = new google.maps.LatLng({0},{1});", dLatitude, dLongitude);  
  183. output.Append("    latlngbounds.extend(pos2);");  
  184. output.Append("    var marker2 = new google.maps.Marker({");  
  185. output.Append("        position: pos2,");  
  186. output.Append("        map: map");  
  187. output.Append("    });");  
  188.   
  189. output.Append("    ///////////////////////////////////");  
  190. output.Append(Environment.NewLine);  
  191. output.Append("    /// Draw Beeline");  
  192. output.Append(Environment.NewLine);  
  193. output.Append("    ///////////////////////////////////");  
  194. output.Append(Environment.NewLine);  
  195. output.Append("     var linecoords = [pos1,pos2];");  
  196. output.Append(" var linepath = new google.maps.Polyline({path: linecoords,strokeColor: \"#F81\",strokeOpacity: 1.0,strokeWeight: 3});");  
  197. output.Append(" linepath.setMap(map);");  
  198.   
  199. output.Append("    ///////////////////////////////////");  
  200. output.Append(Environment.NewLine);  
  201. output.Append("    /// Draw Road connection");  
  202. output.Append(Environment.NewLine);  
  203. output.Append("    ///////////////////////////////////");  
  204. output.Append(Environment.NewLine);  
  205. output.Append("    directionsDisplay = new google.maps.DirectionsRenderer();");  
  206. output.Append(" var directionRendererOptions ={suppressMarkers: true,preserveViewport: true,polylineOptions:{strokeColor: \"#00F\",strokeOpacity: 0.5,strokeWeight: 3}}; ");  
  207. output.Append(" directionsDisplay.setOptions(directionRendererOptions); ");  
  208. output.Append(" directionsDisplay.setMap(map);");  
  209. output.Append(" var request = {origin:\"" + oLatitude +"," + oLongitude + "\",destination:\"" + dLatitude + "," + dLongitude + "\",travelMode: google.maps.DirectionsTravelMode.DRIVING};");  
  210. output.Append(" directionsService.route(request, function(response, status) {if (status == google.maps.DirectionsStatus.OK) {directionsDisplay.setDirections(response);}});");  
  211. output.AppendFormat("   calculateDistances(\"{0}\");", Request.Params["unit"].ToString());  
  212.   
  213. output.Append(" map.fitBounds(latlngbounds);");  
  214. output.Append(" map.panToBounds(latlngbounds);");  
  215. output.Append("}");  
  216.   
  217. output.Append("///////////////////////////////////");  
  218. output.Append(Environment.NewLine);  
  219. output.Append("/// Calculate Road Distance");  
  220. output.Append(Environment.NewLine);  
  221. output.Append("///////////////////////////////////");  
  222. output.Append(Environment.NewLine);  
  223. output.Append("function calculateDistances(unit) {");  
  224. output.Append("var service = new google.maps.DistanceMatrixService();");  
  225. output.Append("if(unit==\"km\"){");  
  226. output.Append("service.getDistanceMatrix(");  
  227. output.Append("    {");  
  228. output.AppendFormat("        origins: [new google.maps.LatLng({0},{1})],", oLatitude, oLongitude);  
  229. output.AppendFormat("        destinations: [new google.maps.LatLng({0},{1})],", dLatitude,dLongitude);  
  230. output.Append("    travelMode: google.maps.TravelMode.DRIVING,");  
  231. output.Append("    unitSystem: google.maps.UnitSystem.METRIC,");  
  232. output.Append("    avoidHighways: false,");  
  233. output.Append("    avoidTolls: false");  
  234. output.Append("    }, callback);");  
  235. output.Append("    }");  
  236. output.Append("if(unit==\"miles\"){");  
  237. output.Append("service.getDistanceMatrix(");  
  238. output.Append("    {");  
  239. output.AppendFormat("        origins: [new google.maps.LatLng({0},{1})],", oLatitude, oLongitude);  
  240. output.AppendFormat("        destinations: [new google.maps.LatLng({0},{1})],", dLatitude, dLongitude);  
  241. output.Append("    travelMode: google.maps.TravelMode.DRIVING,");  
  242. output.Append("    unitSystem: google.maps.UnitSystem.IMPERIAL,");  
  243. output.Append("    avoidHighways: false,");  
  244. output.Append("    avoidTolls: false");  
  245. output.Append("    }, callback);");  
  246. output.Append("    }");  
  247. output.Append("}");  
  248.   
  249. output.Append("function callback(response, status) {");  
  250. output.Append("if (status != google.maps.DistanceMatrixStatus.OK) {");  
  251. output.Append("    alert('Error was: ' + status);");  
  252. output.Append("} else {");  
  253. output.Append("    var origins = response.originAddresses;");  
  254. output.Append("    var destinations = response.destinationAddresses;");  
  255. output.Append("    var outputDiv = document.getElementById('outputDiv');");  
  256. output.Append("    outputDiv.innerHTML = '';");  
  257. output.Append("    var distance;");  
  258. output.Append("    for (var i = 0; i < origins.length; i++) {");  
  259. output.Append("    var results = response.rows[i].elements;");  
  260. output.Append("    for (var j = 0; j < results.length; j++) {");  
  261. output.Append("    distance = results[j].distance.text;");  
  262. output.Append("    distance = distance.replace(\"mi\", \"\");");  
  263. output.Append("    distance = distance.replace(\"km\", \"\");");  
  264. output.Append("    distance = distance.replace(\",\", \"\");");  
  265. output.AppendFormat("        outputDiv.innerHTML += \"Result:  
  266. Distance: \" + distance + ' {0} (Road)  
  267. ' + \"Distance: {1} {0} (Beeline)\";", Request.Params["unit"], Math.Round(result2, 1).ToString());  
  268. output.Append("    }");  
  269. output.Append("    }");  
  270. output.Append("}");  
  271. output.Append("}");  
  272. //output.Append("</script>");  
  273. Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptAPI", output.ToString(), true);  
  274. //litHeaderCode.Text = output.ToString();  
  275.   
  276.             }  
  277.             catch (Exception ex)  
  278.             {  
  279.             }  
  280.         }  
  281.       
  282.     }  
  283. }  
Download C# script with sample database

Coldfusion Script - Source Code Coldfusion Script


  1. <!---   
  2. '======================================================================  
  3. ' Distance between two ZIP Codes in USA and Canada  
  4. '  
  5. ' This CFM Script requires 5 GET parameters: zipcode1 and country1 (us/ca) and zipcode2 and country2 and unit (miles/km)  
  6. ' Plus the database tables us and ca containing the ZIP Code-Lon/Lat data  
  7. '  
  8. ' Example call: tools_distance.cfm?zipcode1=90210&country1=us&zipcode2=60601&country2=us&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 strZIPCode1 = "">  
  20. <cfset strZIPCode2 = "">  
  21. <cfset strCountry1 = "">  
  22. <cfset strCountry2 = "">  
  23. <cfset strUnit = "">  
  24. <cfset strLongitude1 = "">  
  25. <cfset strLongitude2 = "">  
  26. <cfset strLatitude1 = "">  
  27. <cfset strLatitude2 = "">  
  28. <cfset strZIPName1 = "">  
  29. <cfset strZIPName2 = "">  
  30. <cfset dblLatitudeRadians1 = "">  
  31. <cfset dblLatitudeRadians2 = "">  
  32. <cfset dblLongitudeRadians1 = "">  
  33. <cfset dblLongitudeRadians2 = "">  
  34. <cfset dblLongitudeRadiansDifference = "">  
  35. <cfset dblRadiansDistance = "">  
  36. <cfset dblX = "">  
  37. <cfset dblDistance = "">  
  38.   
  39. <cfset KMperMile = 1.609344>  
  40. <cfset Pi = 3.141592654>  
  41.   
  42. <cfset strZIPCode1 = URL.zipcode1>  
  43. <cfset strCountry1 = URL.country1>  
  44. <cfset strZIPCode2 = URL.zipcode2>  
  45. <cfset strCountry2 = URL.country2>  
  46. <cfset strUnit = URL.unit>  
  47.   
  48.   
  49. <!--- '======================================================================  
  50. ' Set the correct term: ZIP Code = USA or Postal Code = Canada  
  51. '====================================================================== --->  
  52. <cfif strCountry1 eq "us">  
  53.     <cfset strZIPName1 = "ZIP Code">  
  54. <cfelseif strCountry1 eq "ca">  
  55.     <cfset strZIPName1 = "Postal Code">  
  56. </cfif>  
  57.   
  58. <!--- '======================================================================  
  59. ' Get coordinates of first ZIP Code  
  60. '====================================================================== --->  
  61.   
  62. <cfif strCountry1 eq "us">  
  63.     <cfquery name="getZipcodes1"  datasource="#rs#">  
  64.         SELECT * FROM us WHERE zipcode='#strZIPCode1#'  
  65.     </cfquery>  
  66. <cfelseif strCountry1 eq "ca">  
  67.     <cfquery name="getZipcodes1"  datasource="#rs#">  
  68.         SELECT * FROM ca WHERE postalcode='#strZIPCode1#'  
  69.     </cfquery>  
  70. </cfif>  
  71.   
  72.   
  73.   
  74. <cfif getZipcodes1.recordcount gt 0>  
  75.     <cfset strLongitude1 = getZipcodes1.longitude>  
  76.     <cfset strLatitude1 = getZipcodes1.latitude>  
  77. <cfelse>  
  78.     <cfoutput>#strZIPName1# 1 Not found</cfoutput>  
  79. </cfif>  
  80.   
  81. <!--- '======================================================================  
  82. ' Set the correct term: ZIP Code = USA or Postal Code = Canada  
  83. '====================================================================== --->  
  84.   
  85. <cfif strCountry2 eq "us">  
  86.     <cfset strZIPName2 = "ZIP Code">  
  87. <cfelseif strCountry2 eq "ca">  
  88.     <cfset strZIPName2 = "Postal Code">  
  89. </cfif>  
  90.   
  91. <!--- '======================================================================  
  92. ' Get coordinates of second ZIP Code  
  93. '====================================================================== --->  
  94.   
  95. <cfif strCountry2 eq "us">  
  96.     <cfquery name="getZipcodes2"  datasource="#rs#">  
  97.         SELECT * FROM us WHERE zipcode='#strZIPCode2#'  
  98.     </cfquery>  
  99. <cfelseif strCountry2 eq "ca">  
  100.     <cfquery name="getZipcodes2"  datasource="#rs#">  
  101.         SELECT * FROM ca WHERE postalcode='#strZIPCode2#'  
  102.     </cfquery>  
  103. </cfif>  
  104.   
  105. <cfif getZipcodes2.recordcount gt 0>  
  106.     <cfset strLongitude2 = getZipcodes2.longitude>  
  107.     <cfset strLatitude2 = getZipcodes2.latitude>  
  108. <cfelse>  
  109.     <cfoutput>#strZIPName2# 2 Not found)</cfoutput>  
  110. </cfif>  
  111.   
  112. <!--- '======================================================================  
  113. ' As the Crow flies - Calculation in due consideration of Earth curvation  
  114. '====================================================================== --->  
  115.   
  116.   
  117. <cfset dblLatitudeRadians1 = strLatitude1 * Pi / 180>  
  118. <cfset dblLongitudeRadians1 = strLongitude1 * Pi / 180>  
  119. <cfset dblLatitudeRadians2 = strLatitude2 * Pi / 180>  
  120. <cfset dblLongitudeRadians2 = strLongitude2 * Pi / 180>  
  121. <cfset dblLongitudeRadiansDifference = Abs(dblLongitudeRadians1 - dblLongitudeRadians2)>  
  122. <cfset dblX = Sin(dblLatitudeRadians1) * Sin(dblLatitudeRadians2) + Cos(dblLatitudeRadians1) * Cos(dblLatitudeRadians2) * Cos(dblLongitudeRadiansDifference)>  
  123. <cfset dblRadiansDistance = Atn(-dblX / Sqr(-dblX * dblX + 1)) + 2 * Atn(1)>  
  124.   
  125. <cfif strUnit eq "km">  
  126.     <cfset dblDistance = Round(dblRadiansDistance * 3958.754 * KMperMile)>  
  127. <cfelse>  
  128.     <cfset dblDistance = Round(dblRadiansDistance * 3958.754)>  
  129. </cfif>  
  130.   
  131. <cfoutput>  
  132. <!--- '======================================================================  
  133. ' Google Map and Road distance Calculation  
  134. '====================================================================== --->  
  135.   
  136. <!DOCTYPE html>  
  137. <html>  
  138.   <head>  
  139.     <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
  140.     <meta charset="utf-8">  
  141.     <title>Distance between 2 ZIP Codes</title>  
  142.   
  143.   
  144. <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>  
  145. <script>  
  146.   
  147. var directionDisplay;  
  148. var directionsService = new google.maps.DirectionsService();  
  149.   
  150. function initialize() {  
  151.     ///////////////////////////////////  
  152.     /// Draw map  
  153.     ///////////////////////////////////  
  154.     var mapOptions = {  
  155.         zoom: 9,  
  156.         mapTypeId: google.maps.MapTypeId.ROADMAP,  
  157.         disableDefaultUI: true  
  158.     }  
  159.     var map = new google.maps.Map(document.getElementById('map'), mapOptions);  
  160.     var latlngbounds = new google.maps.LatLngBounds();  
  161.   
  162.     ///////////////////////////////////  
  163.     /// Draw first marker  
  164.     ///////////////////////////////////  
  165.     var pos1 = new google.maps.LatLng(#strLatitude1#,#strLongitude1#);  
  166.     latlngbounds.extend(pos1);  
  167.     var marker1 = new google.maps.Marker({  
  168.         position: pos1,  
  169.         map: map  
  170.     });  
  171.   
  172.     ///////////////////////////////////  
  173.     /// Draw second marker  
  174.     ///////////////////////////////////  
  175.     var pos2 = new google.maps.LatLng(#strLatitude2#,#strLongitude2#);  
  176.     latlngbounds.extend(pos2);  
  177.     var marker2 = new google.maps.Marker({  
  178.         position: pos2,  
  179.         map: map  
  180.     });  
  181.   
  182.     ///////////////////////////////////  
  183.     /// Draw Beeline  
  184.     ///////////////////////////////////  
  185.     var linecoords = [pos1,pos2];  
  186.     var linepath = new google.maps.Polyline({path: linecoords,strokeColor: "##F81",strokeOpacity: 1.0,strokeWeight: 3});  
  187.     linepath.setMap(map);  
  188.   
  189.     ///////////////////////////////////  
  190.     /// Draw Road connection  
  191.     ///////////////////////////////////  
  192.     directionsDisplay = new google.maps.DirectionsRenderer();  
  193.     var directionRendererOptions ={suppressMarkers: true,preserveViewport: true,polylineOptions:{strokeColor: "##00F",strokeOpacity: 0.5,strokeWeight: 3}};   
  194.     directionsDisplay.setOptions(directionRendererOptions);   
  195.     directionsDisplay.setMap(map);  
  196.     var request = {origin:"#strLatitude1#,#strLongitude1#",destination:"#strLatitude2#,#strLongitude2#",travelMode: google.maps.DirectionsTravelMode.DRIVING};  
  197.     directionsService.route(request, function(response, status) {if (status == google.maps.DirectionsStatus.OK) {directionsDisplay.setDirections(response);}});  
  198.     calculateDistances("#strUnit#");  
  199.   
  200.     map.fitBounds(latlngbounds);  
  201.     map.panToBounds(latlngbounds);  
  202. }  
  203.   
  204. ///////////////////////////////////  
  205. /// Calculate Road Distance  
  206. ///////////////////////////////////  
  207. function calculateDistances(unit) {  
  208. var service = new google.maps.DistanceMatrixService();  
  209. if(unit=="km"){  
  210. service.getDistanceMatrix(  
  211.     {  
  212.         origins: [new google.maps.LatLng(#strLatitude1#,#strLongitude1#)],  
  213.         destinations: [new google.maps.LatLng(#strLatitude2#,#strLongitude2#)],  
  214.     travelMode: google.maps.TravelMode.DRIVING,  
  215.     unitSystem: google.maps.UnitSystem.METRIC,  
  216.     avoidHighways: false,  
  217.     avoidTolls: false  
  218.     }, callback);  
  219.     }  
  220. if(unit=="miles"){  
  221. service.getDistanceMatrix(  
  222.     {  
  223.         origins: [new google.maps.LatLng(#strLatitude1#,#strLongitude1#)],  
  224.         destinations: [new google.maps.LatLng(#strLatitude2#,#strLongitude2#)],  
  225.     travelMode: google.maps.TravelMode.DRIVING,  
  226.     unitSystem: google.maps.UnitSystem.IMPERIAL,  
  227.     avoidHighways: false,  
  228.     avoidTolls: false  
  229.     }, callback);  
  230.     }  
  231. }  
  232.   
  233. function callback(response, status) {  
  234. if (status != google.maps.DistanceMatrixStatus.OK) {  
  235.     alert('Error was: ' + status);  
  236. else {  
  237.     var origins = response.originAddresses;  
  238.     var destinations = response.destinationAddresses;  
  239.     var outputDiv = document.getElementById('outputDiv');  
  240.     outputDiv.innerHTML = '';  
  241.     var distance;  
  242.     for (var i = 0; i < origins.length; i++) {  
  243.     var results = response.rows[i].elements;  
  244.     for (var j = 0; j < results.length; j++) {  
  245.     distance = results[j].distance.text;  
  246.     distance = distance.replace("mi""");  
  247.     distance = distance.replace("km""");  
  248.     distance = distance.replace(",""");  
  249.         outputDiv.innerHTML += "Result:  
  250. Distance: " + distance + ' #strUnit# (Road)  
  251. ' + "Distance: #dblDistance & " " & strUnit# (Beeline)";  
  252.     }  
  253.     }  
  254. }  
  255. }  
  256. </script>  
  257.   
  258. </head>  
  259.   <body onload="initialize()">  
  260.     <div id="map" style="width: 300px; height: 300px;"></div>  
  261.     <div id="outputDiv" style="width: 300px; height: 50px;" ></div>  
  262.   </body>  
  263. </html>  
  264. </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