Distance between ZIP Codes
Test our free ZIP Code Distance Calculator and download our free scripts that are perfectly compatible with our ZIP Code databases.
Usage
Calculate the distance between two ZIP 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 ZIP code.
PHP Script - Source Code 
- <?php
- /*======================================================================
- ** Distance between two ZIP Codes in USA or Canada
- **
- ** This PHP Script requires 5 GET parameters: zipcode1, country1 (us/ca), zipcode2, country2, unit (miles/km)
- ** Plus the database tables us and ca containing the ZIP Code-Lon/Lat data
- **
- ** Example call: tools_distance.php?zipcode1=90210&country1=us&zipcode2=60601&country2=us&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");
- /* ----------------------------- */
- /* 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;
- }
- /* ----------------------------- */
- /* Start of Script */
- /* Get parameters */
- /* ----------------------------- */
- define('F_KMPERMILE', 1.609344 );
- define('F_PI', 3.141592654 );
- define('F_RADIAN_MUL', 3958.754 );
- $b_ok=
- isset($_REQUEST['zipcode1']) && isset($_REQUEST['country1']) &&
- isset($_REQUEST['zipcode2']) && isset($_REQUEST['country2']);
- if (!$b_ok)
- die("Error: parameters are missed");
- $sZipCode1 = $_REQUEST['zipcode1'];
- $sCountry1 = $_REQUEST['country1'];
- $sZipCode2 = $_REQUEST['zipcode2'];
- $sCountry2 = $_REQUEST['country2'];
- $sUnit = (isset($_REQUEST['unit']) && $_REQUEST['unit'] == "km")? "km" : "miles";
- /* ----------------------------- */
- /* Get coordinates of first ZIP Code */
- /* ----------------------------- */
- if (!($a_coords1 = getCoordsByZip($sCountry1, $sZipCode1)))
- die("Error: zipcode1 not found");
- /* ----------------------------- */
- /* Get coordinates of second ZIP Code */
- /* ----------------------------- */
- if (!($a_coords2 = getCoordsByZip($sCountry2, $sZipCode2)))
- die("Error: zipcode2 not found");
- list($sLongitude1, $sLatitude1)= $a_coords1;
- list($sLongitude2, $sLatitude2)= $a_coords2;
- /* ----------------------------- */
- /* As the Crow flies - Calculation in due consideration of Earth curvation */
- /* ----------------------------- */
- $fLatitudeRadians1 = (float)$sLatitude1 * F_PI / 180;
- $fLongitudeRadians1 = (float)$sLongitude1 * F_PI / 180;
- $fLatitudeRadians2 = (float)$sLatitude2 * F_PI / 180;
- $fLongitudeRadians2 = (float)$sLongitude2 * F_PI / 180;
- $fLongitudeRadiansDifference = abs($fLongitudeRadians1 - $fLongitudeRadians2);
- $fX = sin($fLatitudeRadians1) * sin($fLatitudeRadians2) +
- cos($fLatitudeRadians1) * cos($fLatitudeRadians2) * cos($fLongitudeRadiansDifference);
- $fRadiansDistance = atan(-$fX / sqrt(-$fX * $fX + 1)) + 2 * atan(1);
- if ($sUnit == "km")
- $fDistance = round($fRadiansDistance * F_RADIAN_MUL* F_KMPERMILE, 0);
- else
- $fDistance = round($fRadiansDistance * F_RADIAN_MUL, 0);
- /* ----------------------------- */
- /* Google Map and Road distance Calculation */
- /* ----------------------------- */
- ?><!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
- <meta charset="utf-8">
- <title>Distance between 2 ZIP Codes</title>
- <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
- <script>
- var directionDisplay;
- var directionsService = new google.maps.DirectionsService();
- function initialize() {
- ///////////////////////////////////
- /// Draw map
- ///////////////////////////////////
- var mapOptions = {
- zoom: 9,
- mapTypeId: google.maps.MapTypeId.ROADMAP,
- disableDefaultUI: true
- }
- var map = new google.maps.Map(document.getElementById('map'), mapOptions);
- var latlngbounds = new google.maps.LatLngBounds();
- ///////////////////////////////////
- /// Draw first marker
- ///////////////////////////////////
- var pos1 = new google.maps.LatLng(<?=$sLatitude1?>,<?=$sLongitude1?>);
- latlngbounds.extend(pos1);
- var marker1 = new google.maps.Marker({
- position: pos1,
- map: map
- });
- ///////////////////////////////////
- /// Draw second marker
- ///////////////////////////////////
- var pos2 = new google.maps.LatLng(<?=$sLatitude2?>,<?=$sLongitude2?>);
- latlngbounds.extend(pos2);
- var marker2 = new google.maps.Marker({
- position: pos2,
- map: map
- });
- ///////////////////////////////////
- /// Draw Beeline
- ///////////////////////////////////
- var linecoords = [pos1,pos2];
- var linepath = new google.maps.Polyline({path: linecoords,strokeColor: "#F81",strokeOpacity: 1.0,strokeWeight: 3});
- linepath.setMap(map);
- ///////////////////////////////////
- /// Draw Road connection
- ///////////////////////////////////
- directionsDisplay = new google.maps.DirectionsRenderer();
- var directionRendererOptions ={suppressMarkers: true,preserveViewport: true,polylineOptions:{strokeColor: "#00F",strokeOpacity: 0.5,strokeWeight: 3}};
- directionsDisplay.setOptions(directionRendererOptions);
- directionsDisplay.setMap(map);
- var request = {origin:"<?=$sLatitude1?>,<?=$sLongitude1?>",destination:"<?=$sLatitude2?>,<?=$sLongitude2?>",travelMode: google.maps.DirectionsTravelMode.DRIVING};
- directionsService.route(request, function(response, status) {if (status == google.maps.DirectionsStatus.OK) {directionsDisplay.setDirections(response);}});
- calculateDistances("<?=$sUnit?>");
- map.fitBounds(latlngbounds);
- map.panToBounds(latlngbounds);
- }
- ///////////////////////////////////
- /// Calculate Road Distance
- ///////////////////////////////////
- function calculateDistances(unit) {
- var service = new google.maps.DistanceMatrixService();
- if(unit=="km"){
- service.getDistanceMatrix(
- {
- origins: [new google.maps.LatLng(<?=$sLatitude1?>,<?=$sLongitude1?>)],
- destinations: [new google.maps.LatLng(<?=$sLatitude2?>,<?=$sLongitude2?>)],
- travelMode: google.maps.TravelMode.DRIVING,
- unitSystem: google.maps.UnitSystem.METRIC,
- avoidHighways: false,
- avoidTolls: false
- }, callback);
- }
- if(unit=="miles"){
- service.getDistanceMatrix(
- {
- origins: [new google.maps.LatLng(<?=$sLatitude1?>,<?=$sLongitude1?>)],
- destinations: [new google.maps.LatLng(<?=$sLatitude2?>,<?=$sLongitude2?>)],
- travelMode: google.maps.TravelMode.DRIVING,
- unitSystem: google.maps.UnitSystem.IMPERIAL,
- avoidHighways: false,
- avoidTolls: false
- }, callback);
- }
- }
- function callback(response, status) {
- if (status != google.maps.DistanceMatrixStatus.OK) {
- alert('Error was: ' + status);
- } else {
- var origins = response.originAddresses;
- var destinations = response.destinationAddresses;
- var outputDiv = document.getElementById('outputDiv');
- outputDiv.innerHTML = '';
- var distance;
- for (var i = 0; i < origins.length; i++) {
- var results = response.rows[i].elements;
- for (var j = 0; j < results.length; j++) {
- distance = results[j].distance.text;
- distance = distance.replace("mi", "");
- distance = distance.replace("km", "");
- distance = distance.replace(",", "");
- outputDiv.innerHTML += "Result:
- Distance: " + distance + ' <?=$sUnit?> (Road)
- ' + "Distance: <?=$fDistance." ".$sUnit?> (Beeline)";
- }
- }
- }
- }
- </script>
- </head>
- <body onload="initialize()">
- <div id="map" style="width: 300px; height: 300px;"></div>
- <div id="outputDiv" style="width: 300px; height: 50px;" ></div>
- </body>
- </html>
ASP Script - Source Code
- <%
- '======================================================================
- ' Distance between two ZIP Codes in USA and Canada
- '
- ' This ASP Script requires 5 GET parameters: zipcode1 and country1 (us/ca) and zipcode2 and country2 and unit (miles/km)
- ' Plus the database tables us and ca containing the ZIP Code-Lon/Lat data provided by ZIPCodeSoft.
- '
- ' Example call: tools_distance_asp.asp?zipcode1=90210&country1=us&zipcode2=60601&country2=us&unit=miles
- '
- ' © 2012 http://www.zipcodesoft.com, All Rights Reserved
- '======================================================================
- Dim strZIPCode1
- Dim strZIPCode2
- Dim strCountry1
- Dim strCountry2
- Dim strUnit
- Dim strLongitude1
- Dim strLongitude2
- Dim strLatitude1
- Dim strLatitude2
- Dim strZIPName1
- Dim strZIPName2
- Dim dblLatitudeRadians1
- Dim dblLatitudeRadians2
- Dim dblLongitudeRadians1
- Dim dblLongitudeRadians2
- Dim dblLongitudeRadiansDifference
- Dim dblRadiansDistance
- Dim dblX
- Dim dblDistance
- Const KMperMile = 1.609344
- Const Pi = 3.141592654
- strZIPCode1 = Request("zipcode1")
- strCountry1 = Request("country1")
- strZIPCode2 = Request("zipcode2")
- strCountry2 = Request("country2")
- strUnit = Request("unit")
- 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")
- '======================================================================
- ' Set the correct term: ZIP Code = USA or Postal Code = Canada
- '======================================================================
- If strCountry1="us" Then strZIPName1 = "ZIP Code"
- If strCountry1="ca" Then strZIPName1 = "Postal Code"
- '======================================================================
- ' Get coordinates of first ZIP Code
- '======================================================================
- If strCountry1="us" Then sql = "SELECT * FROM us WHERE zipcode='" & strZIPCode1 & "';"
- If strCountry1="ca" Then sql = "SELECT * FROM ca WHERE postalcode='" & strZIPCode1 & "';"
- Set rs = conn.Execute(sql)
- If Not rs.EOF Then
- strLongitude1 = rs.Fields("longitude")
- strLatitude1 = rs.Fields("latitude")
- Else
- Response.Write(strZIPName1 & "1 Not found")
- End If
- rs.Close
- '======================================================================
- ' Set the correct term: ZIP Code = USA or Postal Code = Canada
- '======================================================================
- If strCountry2="us" Then strZIPName2 = "ZIP Code"
- If strCountry2="ca" Then strZIPName2 = "Postal Code"
- '======================================================================
- ' Get coordinates of second ZIP Code
- '======================================================================
- If strCountry2="us" Then sql = "SELECT * FROM us WHERE zipcode='" & strZIPCode2 & "';"
- If strCountry2="ca" Then sql = "SELECT * FROM ca WHERE postalcode='" & strZIPCode2 & "';"
- Set rs = conn.Execute(sql)
- If Not rs.EOF Then
- strLongitude2 = rs.Fields("longitude")
- strLatitude2 = rs.Fields("latitude")
- Else
- Response.Write(strZIPName2 & "2 Not found")
- End If
- rs.Close
- '======================================================================
- ' As the Crow flies - Calculation in due consideration of Earth curvation
- '======================================================================
- dblLatitudeRadians1 = CDbl(strLatitude1) * Pi / 180
- dblLongitudeRadians1 = CDbl(strLongitude1) * Pi / 180
- dblLatitudeRadians2 = CDbl(strLatitude2) * Pi / 180
- dblLongitudeRadians2 = CDbl(strLongitude2) * Pi / 180
- dblLongitudeRadiansDifference = Abs(dblLongitudeRadians1 - dblLongitudeRadians2)
- dblX = Sin(dblLatitudeRadians1) * Sin(dblLatitudeRadians2) + Cos(dblLatitudeRadians1) * Cos(dblLatitudeRadians2) * Cos(dblLongitudeRadiansDifference)
- dblRadiansDistance = Atn(-dblX / Sqr(-dblX * dblX + 1)) + 2 * Atn(1)
- If strUnit = "km" Then
- dblDistance = Round(dblRadiansDistance * 3958.754 * KMperMile,0)
- Else
- dblDistance = Round(dblRadiansDistance * 3958.754,0)
- End If
- '======================================================================
- ' Google Map and Road distance Calculation
- '======================================================================
- %>
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
- <meta charset="utf-8">
- <title>Distance between 2 ZIP Codes</title>
- <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
- <script>
- var directionDisplay;
- var directionsService = new google.maps.DirectionsService();
- function initialize() {
- ///////////////////////////////////
- /// Draw map
- ///////////////////////////////////
- var mapOptions = {
- zoom: 9,
- mapTypeId: google.maps.MapTypeId.ROADMAP,
- disableDefaultUI: true
- }
- var map = new google.maps.Map(document.getElementById('map'), mapOptions);
- var latlngbounds = new google.maps.LatLngBounds();
- ///////////////////////////////////
- /// Draw first marker
- ///////////////////////////////////
- var pos1 = new google.maps.LatLng(<%=strLatitude1%>,<%=strLongitude1%>);
- latlngbounds.extend(pos1);
- var marker1 = new google.maps.Marker({
- position: pos1,
- map: map
- });
- ///////////////////////////////////
- /// Draw second marker
- ///////////////////////////////////
- var pos2 = new google.maps.LatLng(<%=strLatitude2%>,<%=strLongitude2%>);
- latlngbounds.extend(pos2);
- var marker2 = new google.maps.Marker({
- position: pos2,
- map: map
- });
- ///////////////////////////////////
- /// Draw Beeline
- ///////////////////////////////////
- var linecoords = [pos1,pos2];
- var linepath = new google.maps.Polyline({path: linecoords,strokeColor: "#F81",strokeOpacity: 1.0,strokeWeight: 3});
- linepath.setMap(map);
- ///////////////////////////////////
- /// Draw Road connection
- ///////////////////////////////////
- directionsDisplay = new google.maps.DirectionsRenderer();
- var directionRendererOptions ={suppressMarkers: true,preserveViewport: true,polylineOptions:{strokeColor: "#00F",strokeOpacity: 0.5,strokeWeight: 3}};
- directionsDisplay.setOptions(directionRendererOptions);
- directionsDisplay.setMap(map);
- var request = {origin:"<%=strLatitude1%>,<%=strLongitude1%>",destination:"<%=strLatitude2%>,<%=strLongitude2%>",travelMode: google.maps.DirectionsTravelMode.DRIVING};
- directionsService.route(request, function(response, status) {if (status == google.maps.DirectionsStatus.OK) {directionsDisplay.setDirections(response);}});
- calculateDistances("<%=strUnit%>");
- map.fitBounds(latlngbounds);
- map.panToBounds(latlngbounds);
- }
- ///////////////////////////////////
- /// Calculate Road Distance
- ///////////////////////////////////
- function calculateDistances(unit) {
- var service = new google.maps.DistanceMatrixService();
- if(unit=="km"){
- service.getDistanceMatrix(
- {
- origins: [new google.maps.LatLng(<%=strLatitude1%>,<%=strLongitude1%>)],
- destinations: [new google.maps.LatLng(<%=strLatitude2%>,<%=strLongitude2%>)],
- travelMode: google.maps.TravelMode.DRIVING,
- unitSystem: google.maps.UnitSystem.METRIC,
- avoidHighways: false,
- avoidTolls: false
- }, callback);
- }
- if(unit=="miles"){
- service.getDistanceMatrix(
- {
- origins: [new google.maps.LatLng(<%=strLatitude1%>,<%=strLongitude1%>)],
- destinations: [new google.maps.LatLng(<%=strLatitude2%>,<%=strLongitude2%>)],
- travelMode: google.maps.TravelMode.DRIVING,
- unitSystem: google.maps.UnitSystem.IMPERIAL,
- avoidHighways: false,
- avoidTolls: false
- }, callback);
- }
- }
- function callback(response, status) {
- if (status != google.maps.DistanceMatrixStatus.OK) {
- alert('Error was: ' + status);
- } else {
- var origins = response.originAddresses;
- var destinations = response.destinationAddresses;
- var outputDiv = document.getElementById('outputDiv');
- outputDiv.innerHTML = '';
- var distance;
- for (var i = 0; i < origins.length; i++) {
- var results = response.rows[i].elements;
- for (var j = 0; j < results.length; j++) {
- distance = results[j].distance.text;
- distance = distance.replace("mi", "");
- distance = distance.replace("km", "");
- distance = distance.replace(",", "");
- outputDiv.innerHTML += "Result:
- Distance: " + distance + ' <%=strUnit%> (Road)
- ' + "Distance: <%=dblDistance & " " & strUnit%> (Beeline)";
- }
- }
- }
- }
- </script>
- </head>
- <body onload="initialize()">
- <div id="map" style="width: 300px; height: 300px;"></div>
- <div id="outputDiv" style="width: 300px; height: 50px;" ></div>
- </body>
- </html>
C# Script - Source Code 
- Tools_Distance.aspx:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Tools_Distance.aspx.cs" Inherits="ZIPCodeTools.Tools_Distance" %>
- <!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">
- <title>Distance between 2 ZIP Codes</title>
- <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
- <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
- <%--<script type="text/javascript">
- $(document).ready(function () {
- initialize();
- });
- </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: 300px; height: 300px;"></div>
- <div id="outputDiv" style="width: 300px; height: 50px;" ></div>
- </div>
- </form>
- </body>
- </html>
- Tools_Distance.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_Distance : System.Web.UI.Page
- {
- DataTools dt = new DataTools();
- protected void Page_Load(object sender, EventArgs e)
- {
- string ErrorMessage = "";
- if (Request.Params["zipcode1"] == null || Request.Params["zipcode1"].Length == 0)
- {
- ErrorMessage += "<li>Parameter zipcode1 cannot be missing or blank</li>";
- }
- if (Request.Params["country1"] == null || Request.Params["country1"].Length == 0)
- {
- ErrorMessage += "<li>Parameter country1 cannot be missing or blank</li>";
- }
- if (Request.Params["zipcode2"] == null || Request.Params["zipcode2"].Length == 0)
- {
- ErrorMessage += "<li>Parameter zipcode2 cannot be missing or blank</li>";
- }
- if (Request.Params["country2"] == null || Request.Params["country2"].Length == 0)
- {
- ErrorMessage += "<li>Parameter country2 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
- {
- string unit;
- unit = Request["unit"].ToString();
- SqlCommand cmd = new SqlCommand();
- cmd.CommandText = "SELECT * FROM us WHERE countrycode = @CountryCode AND zipcode = @Zipcode;";
- cmd.Parameters.Add("@CountryCode", SqlDbType.VarChar, 2).Value = Request["country1"].ToString();
- cmd.Parameters.Add("@ZipCode", SqlDbType.VarChar, 5).Value = Request["zipcode1"].ToString();
- DataRow drOrigin = dt.GetDataSet(cmd, DataTools.DataSources.zipcodesoft).Tables[0].Rows[0];
- cmd = new SqlCommand();
- cmd.CommandText = "SELECT * FROM us WHERE countrycode = @CountryCode AND zipcode = @Zipcode;";
- cmd.Parameters.Add("@CountryCode", SqlDbType.VarChar, 2).Value = Request["country2"].ToString();
- cmd.Parameters.Add("@ZipCode", SqlDbType.VarChar, 5).Value = Request["zipcode2"].ToString();
- DataRow drDestination = dt.GetDataSet(cmd, DataTools.DataSources.zipcodesoft).Tables[0].Rows[0];
- double sLatitudeRadians = double.Parse(drOrigin["latitude"].ToString()) * (Math.PI / 180.0);
- double sLongitudeRadians = double.Parse(drOrigin["longitude"].ToString()) * (Math.PI / 180.0);
- double eLatitudeRadians = double.Parse(drDestination["latitude"].ToString()) * (Math.PI / 180.0);
- double eLongitudeRadians = double.Parse(drDestination["longitude"].ToString()) * (Math.PI / 180.0);
- string oLatitude = drOrigin["latitude"].ToString();
- string oLongitude = drOrigin["longitude"].ToString();
- string dLatitude = drDestination["latitude"].ToString();
- string dLongitude = drDestination["longitude"].ToString();
- double sLongitude = eLongitudeRadians - sLongitudeRadians;
- double sLatitude = eLatitudeRadians - sLatitudeRadians;
- double result1 = Math.Pow(Math.Sin(sLatitude / 2.0), 2.0) +
- Math.Cos(sLatitudeRadians) * Math.Cos(eLatitudeRadians) *
- Math.Pow(Math.Sin(sLongitude / 2.0), 2.0);
- // Using 3956 as the number of miles around the earth
- double result2 = 3958.754 * 2.0 *
- Math.Atan2(Math.Sqrt(result1), Math.Sqrt(1.0 - result1));
- if (unit.ToUpper() == "KM")
- result2 = result2 * (double)1.609344;
- //Begin Creating Website Javascript Code
- StringBuilder output = new StringBuilder();
- //output.Append("<script type=\"text/javascript\">");
- output.Append(Environment.NewLine);
- output.Append("var directionDisplay;");
- output.Append(Environment.NewLine);
- output.Append("var directionsService = new google.maps.DirectionsService();");
- output.Append(Environment.NewLine);
- 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 mapOptions = {");
- output.Append(" zoom: 9,");
- 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(" var latlngbounds = new google.maps.LatLngBounds();");
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append(" /// Draw first marker");
- output.Append(Environment.NewLine);
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.AppendFormat(" var pos1 = new google.maps.LatLng({0},{1});", oLatitude, oLongitude);
- output.Append(" latlngbounds.extend(pos1);");
- output.Append(" var marker1 = new google.maps.Marker({");
- output.Append(" position: pos1,");
- output.Append(" map: map");
- output.Append(" });");
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append(" /// Draw second marker");
- output.Append(Environment.NewLine);
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.AppendFormat(" var pos2 = new google.maps.LatLng({0},{1});", dLatitude, dLongitude);
- output.Append(" latlngbounds.extend(pos2);");
- output.Append(" var marker2 = new google.maps.Marker({");
- output.Append(" position: pos2,");
- output.Append(" map: map");
- output.Append(" });");
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append(" /// Draw Beeline");
- output.Append(Environment.NewLine);
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append(" var linecoords = [pos1,pos2];");
- output.Append(" var linepath = new google.maps.Polyline({path: linecoords,strokeColor: \"#F81\",strokeOpacity: 1.0,strokeWeight: 3});");
- output.Append(" linepath.setMap(map);");
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append(" /// Draw Road connection");
- output.Append(Environment.NewLine);
- output.Append(" ///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append(" directionsDisplay = new google.maps.DirectionsRenderer();");
- output.Append(" var directionRendererOptions ={suppressMarkers: true,preserveViewport: true,polylineOptions:{strokeColor: \"#00F\",strokeOpacity: 0.5,strokeWeight: 3}}; ");
- output.Append(" directionsDisplay.setOptions(directionRendererOptions); ");
- output.Append(" directionsDisplay.setMap(map);");
- output.Append(" var request = {origin:\"" + oLatitude +"," + oLongitude + "\",destination:\"" + dLatitude + "," + dLongitude + "\",travelMode: google.maps.DirectionsTravelMode.DRIVING};");
- output.Append(" directionsService.route(request, function(response, status) {if (status == google.maps.DirectionsStatus.OK) {directionsDisplay.setDirections(response);}});");
- output.AppendFormat(" calculateDistances(\"{0}\");", Request.Params["unit"].ToString());
- output.Append(" map.fitBounds(latlngbounds);");
- output.Append(" map.panToBounds(latlngbounds);");
- output.Append("}");
- output.Append("///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append("/// Calculate Road Distance");
- output.Append(Environment.NewLine);
- output.Append("///////////////////////////////////");
- output.Append(Environment.NewLine);
- output.Append("function calculateDistances(unit) {");
- output.Append("var service = new google.maps.DistanceMatrixService();");
- output.Append("if(unit==\"km\"){");
- output.Append("service.getDistanceMatrix(");
- output.Append(" {");
- output.AppendFormat(" origins: [new google.maps.LatLng({0},{1})],", oLatitude, oLongitude);
- output.AppendFormat(" destinations: [new google.maps.LatLng({0},{1})],", dLatitude,dLongitude);
- output.Append(" travelMode: google.maps.TravelMode.DRIVING,");
- output.Append(" unitSystem: google.maps.UnitSystem.METRIC,");
- output.Append(" avoidHighways: false,");
- output.Append(" avoidTolls: false");
- output.Append(" }, callback);");
- output.Append(" }");
- output.Append("if(unit==\"miles\"){");
- output.Append("service.getDistanceMatrix(");
- output.Append(" {");
- output.AppendFormat(" origins: [new google.maps.LatLng({0},{1})],", oLatitude, oLongitude);
- output.AppendFormat(" destinations: [new google.maps.LatLng({0},{1})],", dLatitude, dLongitude);
- output.Append(" travelMode: google.maps.TravelMode.DRIVING,");
- output.Append(" unitSystem: google.maps.UnitSystem.IMPERIAL,");
- output.Append(" avoidHighways: false,");
- output.Append(" avoidTolls: false");
- output.Append(" }, callback);");
- output.Append(" }");
- output.Append("}");
- output.Append("function callback(response, status) {");
- output.Append("if (status != google.maps.DistanceMatrixStatus.OK) {");
- output.Append(" alert('Error was: ' + status);");
- output.Append("} else {");
- output.Append(" var origins = response.originAddresses;");
- output.Append(" var destinations = response.destinationAddresses;");
- output.Append(" var outputDiv = document.getElementById('outputDiv');");
- output.Append(" outputDiv.innerHTML = '';");
- output.Append(" var distance;");
- output.Append(" for (var i = 0; i < origins.length; i++) {");
- output.Append(" var results = response.rows[i].elements;");
- output.Append(" for (var j = 0; j < results.length; j++) {");
- output.Append(" distance = results[j].distance.text;");
- output.Append(" distance = distance.replace(\"mi\", \"\");");
- output.Append(" distance = distance.replace(\"km\", \"\");");
- output.Append(" distance = distance.replace(\",\", \"\");");
- output.AppendFormat(" outputDiv.innerHTML += \"Result:
- Distance: \" + distance + ' {0} (Road)
- ' + \"Distance: {1} {0} (Beeline)\";", Request.Params["unit"], Math.Round(result2, 1).ToString());
- output.Append(" }");
- output.Append(" }");
- output.Append("}");
- output.Append("}");
- //output.Append("</script>");
- Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptAPI", output.ToString(), true);
- //litHeaderCode.Text = output.ToString();
- }
- catch (Exception ex)
- {
- }
- }
- }
- }
Coldfusion Script - Source Code 
- <!---
- '======================================================================
- ' Distance between two ZIP Codes in USA and Canada
- '
- ' This CFM Script requires 5 GET parameters: zipcode1 and country1 (us/ca) and zipcode2 and country2 and unit (miles/km)
- ' Plus the database tables us and ca containing the ZIP Code-Lon/Lat data
- '
- ' Example call: tools_distance.cfm?zipcode1=90210&country1=us&zipcode2=60601&country2=us&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 strZIPCode1 = "">
- <cfset strZIPCode2 = "">
- <cfset strCountry1 = "">
- <cfset strCountry2 = "">
- <cfset strUnit = "">
- <cfset strLongitude1 = "">
- <cfset strLongitude2 = "">
- <cfset strLatitude1 = "">
- <cfset strLatitude2 = "">
- <cfset strZIPName1 = "">
- <cfset strZIPName2 = "">
- <cfset dblLatitudeRadians1 = "">
- <cfset dblLatitudeRadians2 = "">
- <cfset dblLongitudeRadians1 = "">
- <cfset dblLongitudeRadians2 = "">
- <cfset dblLongitudeRadiansDifference = "">
- <cfset dblRadiansDistance = "">
- <cfset dblX = "">
- <cfset dblDistance = "">
- <cfset KMperMile = 1.609344>
- <cfset Pi = 3.141592654>
- <cfset strZIPCode1 = URL.zipcode1>
- <cfset strCountry1 = URL.country1>
- <cfset strZIPCode2 = URL.zipcode2>
- <cfset strCountry2 = URL.country2>
- <cfset strUnit = URL.unit>
- <!--- '======================================================================
- ' Set the correct term: ZIP Code = USA or Postal Code = Canada
- '====================================================================== --->
- <cfif strCountry1 eq "us">
- <cfset strZIPName1 = "ZIP Code">
- <cfelseif strCountry1 eq "ca">
- <cfset strZIPName1 = "Postal Code">
- </cfif>
- <!--- '======================================================================
- ' Get coordinates of first ZIP Code
- '====================================================================== --->
- <cfif strCountry1 eq "us">
- <cfquery name="getZipcodes1" datasource="#rs#">
- SELECT * FROM us WHERE zipcode='#strZIPCode1#'
- </cfquery>
- <cfelseif strCountry1 eq "ca">
- <cfquery name="getZipcodes1" datasource="#rs#">
- SELECT * FROM ca WHERE postalcode='#strZIPCode1#'
- </cfquery>
- </cfif>
- <cfif getZipcodes1.recordcount gt 0>
- <cfset strLongitude1 = getZipcodes1.longitude>
- <cfset strLatitude1 = getZipcodes1.latitude>
- <cfelse>
- <cfoutput>#strZIPName1# 1 Not found</cfoutput>
- </cfif>
- <!--- '======================================================================
- ' Set the correct term: ZIP Code = USA or Postal Code = Canada
- '====================================================================== --->
- <cfif strCountry2 eq "us">
- <cfset strZIPName2 = "ZIP Code">
- <cfelseif strCountry2 eq "ca">
- <cfset strZIPName2 = "Postal Code">
- </cfif>
- <!--- '======================================================================
- ' Get coordinates of second ZIP Code
- '====================================================================== --->
- <cfif strCountry2 eq "us">
- <cfquery name="getZipcodes2" datasource="#rs#">
- SELECT * FROM us WHERE zipcode='#strZIPCode2#'
- </cfquery>
- <cfelseif strCountry2 eq "ca">
- <cfquery name="getZipcodes2" datasource="#rs#">
- SELECT * FROM ca WHERE postalcode='#strZIPCode2#'
- </cfquery>
- </cfif>
- <cfif getZipcodes2.recordcount gt 0>
- <cfset strLongitude2 = getZipcodes2.longitude>
- <cfset strLatitude2 = getZipcodes2.latitude>
- <cfelse>
- <cfoutput>#strZIPName2# 2 Not found)</cfoutput>
- </cfif>
- <!--- '======================================================================
- ' As the Crow flies - Calculation in due consideration of Earth curvation
- '====================================================================== --->
- <cfset dblLatitudeRadians1 = strLatitude1 * Pi / 180>
- <cfset dblLongitudeRadians1 = strLongitude1 * Pi / 180>
- <cfset dblLatitudeRadians2 = strLatitude2 * Pi / 180>
- <cfset dblLongitudeRadians2 = strLongitude2 * Pi / 180>
- <cfset dblLongitudeRadiansDifference = Abs(dblLongitudeRadians1 - dblLongitudeRadians2)>
- <cfset dblX = Sin(dblLatitudeRadians1) * Sin(dblLatitudeRadians2) + Cos(dblLatitudeRadians1) * Cos(dblLatitudeRadians2) * Cos(dblLongitudeRadiansDifference)>
- <cfset dblRadiansDistance = Atn(-dblX / Sqr(-dblX * dblX + 1)) + 2 * Atn(1)>
- <cfif strUnit eq "km">
- <cfset dblDistance = Round(dblRadiansDistance * 3958.754 * KMperMile)>
- <cfelse>
- <cfset dblDistance = Round(dblRadiansDistance * 3958.754)>
- </cfif>
- <cfoutput>
- <!--- '======================================================================
- ' Google Map and Road distance Calculation
- '====================================================================== --->
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
- <meta charset="utf-8">
- <title>Distance between 2 ZIP Codes</title>
- <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
- <script>
- var directionDisplay;
- var directionsService = new google.maps.DirectionsService();
- function initialize() {
- ///////////////////////////////////
- /// Draw map
- ///////////////////////////////////
- var mapOptions = {
- zoom: 9,
- mapTypeId: google.maps.MapTypeId.ROADMAP,
- disableDefaultUI: true
- }
- var map = new google.maps.Map(document.getElementById('map'), mapOptions);
- var latlngbounds = new google.maps.LatLngBounds();
- ///////////////////////////////////
- /// Draw first marker
- ///////////////////////////////////
- var pos1 = new google.maps.LatLng(#strLatitude1#,#strLongitude1#);
- latlngbounds.extend(pos1);
- var marker1 = new google.maps.Marker({
- position: pos1,
- map: map
- });
- ///////////////////////////////////
- /// Draw second marker
- ///////////////////////////////////
- var pos2 = new google.maps.LatLng(#strLatitude2#,#strLongitude2#);
- latlngbounds.extend(pos2);
- var marker2 = new google.maps.Marker({
- position: pos2,
- map: map
- });
- ///////////////////////////////////
- /// Draw Beeline
- ///////////////////////////////////
- var linecoords = [pos1,pos2];
- var linepath = new google.maps.Polyline({path: linecoords,strokeColor: "##F81",strokeOpacity: 1.0,strokeWeight: 3});
- linepath.setMap(map);
- ///////////////////////////////////
- /// Draw Road connection
- ///////////////////////////////////
- directionsDisplay = new google.maps.DirectionsRenderer();
- var directionRendererOptions ={suppressMarkers: true,preserveViewport: true,polylineOptions:{strokeColor: "##00F",strokeOpacity: 0.5,strokeWeight: 3}};
- directionsDisplay.setOptions(directionRendererOptions);
- directionsDisplay.setMap(map);
- var request = {origin:"#strLatitude1#,#strLongitude1#",destination:"#strLatitude2#,#strLongitude2#",travelMode: google.maps.DirectionsTravelMode.DRIVING};
- directionsService.route(request, function(response, status) {if (status == google.maps.DirectionsStatus.OK) {directionsDisplay.setDirections(response);}});
- calculateDistances("#strUnit#");
- map.fitBounds(latlngbounds);
- map.panToBounds(latlngbounds);
- }
- ///////////////////////////////////
- /// Calculate Road Distance
- ///////////////////////////////////
- function calculateDistances(unit) {
- var service = new google.maps.DistanceMatrixService();
- if(unit=="km"){
- service.getDistanceMatrix(
- {
- origins: [new google.maps.LatLng(#strLatitude1#,#strLongitude1#)],
- destinations: [new google.maps.LatLng(#strLatitude2#,#strLongitude2#)],
- travelMode: google.maps.TravelMode.DRIVING,
- unitSystem: google.maps.UnitSystem.METRIC,
- avoidHighways: false,
- avoidTolls: false
- }, callback);
- }
- if(unit=="miles"){
- service.getDistanceMatrix(
- {
- origins: [new google.maps.LatLng(#strLatitude1#,#strLongitude1#)],
- destinations: [new google.maps.LatLng(#strLatitude2#,#strLongitude2#)],
- travelMode: google.maps.TravelMode.DRIVING,
- unitSystem: google.maps.UnitSystem.IMPERIAL,
- avoidHighways: false,
- avoidTolls: false
- }, callback);
- }
- }
- function callback(response, status) {
- if (status != google.maps.DistanceMatrixStatus.OK) {
- alert('Error was: ' + status);
- } else {
- var origins = response.originAddresses;
- var destinations = response.destinationAddresses;
- var outputDiv = document.getElementById('outputDiv');
- outputDiv.innerHTML = '';
- var distance;
- for (var i = 0; i < origins.length; i++) {
- var results = response.rows[i].elements;
- for (var j = 0; j < results.length; j++) {
- distance = results[j].distance.text;
- distance = distance.replace("mi", "");
- distance = distance.replace("km", "");
- distance = distance.replace(",", "");
- outputDiv.innerHTML += "Result:
- Distance: " + distance + ' #strUnit# (Road)
- ' + "Distance: #dblDistance & " " & strUnit# (Beeline)";
- }
- }
- }
- }
- </script>
- </head>
- <body onload="initialize()">
- <div id="map" style="width: 300px; height: 300px;"></div>
- <div id="outputDiv" style="width: 300px; height: 50px;" ></div>
- </body>
- </html>
- </cfoutput>