Click here to Skip to main content
15,892,298 members

Find Distance between two uk postcodes

Member 9018012 asked:

Open original thread
I have used the following code, but http://maps.google.com/maps/geo?q={0}&output=xml, always returns null. Is there any other way to do it?

using System;  
02.using System.Net;  
03.using System.Web;  
04.using System.Xml;  
05.  
06.namespace Codebrain  
07.{  
08.    public static class Distance  
09.    {  
10.        // Handy structure for Long/Lat information  
11.        public struct Coords  
12.        {  
13.            public double Longitude;  
14.            public double Latitude;  
15.        }  
16.  
17.        // Unit calculations  
18.        public enum Units  
19.        {  
20.            Miles,  
21.            Kilometres  
22.        }  
23.  
24.        // Will return a null if the Google API is unable to find either post code, or the country constraint fails  
25.        public static double? BetweenTwoPostCodes(string postcodeA, string postcodeB, string countryCodeWithin, Units units)  
26.        {  
27.            var ll1 = PostCodeToLongLat(postcodeA, countryCodeWithin);  
28.            if (!ll1.HasValue) return null;  
29.            var ll2 = PostCodeToLongLat(postcodeB, countryCodeWithin);  
30.            if (!ll2.HasValue) return null;  
31.            return ll1.Value.DistanceTo(ll2.Value, units);  
32.        }  
33.  
34.        // Overload for UK post codes  
35.        public static double? BetweenTwoUKPostCodes(string postcodeA, string postcodeB)  
36.        {  
37.            return BetweenTwoPostCodes(postcodeA, postcodeB, "GB", Units.Miles);  
38.        }  
39.  
40.        // Uses the Google API to resolve a post code (within the specified country)  
41.        public static Coords? PostCodeToLongLat(string postcode, string countryCodeWithin)  
42.        {  
43.            // Download the XML response from Google  
44.            var client = new WebClient();  
45.            var encodedPostCode = HttpUtility.UrlEncode(postcode);  
46.            var url = string.Format("http://maps.google.com/maps/geo?q={0}&output=xml", encodedPostCode);  
47.            var xml = client.DownloadString(url);  
48.            var doc = new XmlDocument();  
49.            doc.LoadXml(xml);  
50.  
51.            // Create a custom namespace manager  
52.            var nsmgr = new XmlNamespaceManager(doc.NameTable);  
53.            nsmgr.AddNamespace("ge", "http://earth.google.com/kml/2.0");  
54.            nsmgr.AddNamespace("oa", "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0");  
55.  
56.            // Any results?  
57.            var nodelist = doc.SelectNodes("//ge:kml/ge:Response/ge:Placemark", nsmgr);  
58.            if (nodelist == null || nodelist.Count == 0) return null;  
59.  
60.            // Results are already ordered by accuracy, so take the first one  
61.            var node = nodelist[0];  
62.  
63.            // Check the Country constraint  
64.            var countryname = node.SelectSingleNode("oa:AddressDetails/oa:Country/oa:CountryNameCode", nsmgr);  
65.            if (countryname.FirstChild.Value != countryCodeWithin)  
66.                return null;  
67.  
68.            // Get the raw Long/Lat coordinates (I wish there was a nicer way..  
69.            // perhaps averaging the LongLat enclosing box?)  
70.            var coords = node.SelectSingleNode("ge:Point/ge:coordinates", nsmgr).FirstChild.Value.Split(',');  
71.            double longitude;  
72.            double lattitude;  
73.            if (!Double.TryParse(coords[0], out longitude)) return null;  
74.            if (!Double.TryParse(coords[1], out lattitude)) return null;  
75.  
76.            return new Coords  
77.                       {  
78.                           Longitude = longitude,  
79.                           Latitude = lattitude  
80.                       };  
81.        }  
82.  
83.        public static double DistanceTo(this Coords from, Coords to, Units units)  
84.        {  
85.            // Haversine Formula...  
86.            var dLat1InRad = from.Latitude * (Math.PI / 180.0);  
87.            var dLong1InRad = from.Longitude * (Math.PI / 180.0);  
88.            var dLat2InRad = to.Latitude * (Math.PI / 180.0);  
89.            var dLong2InRad = to.Longitude * (Math.PI / 180.0);  
90.  
91.            var dLongitude = dLong2InRad - dLong1InRad;  
92.            var dLatitude = dLat2InRad - dLat1InRad;  
93.  
94.            // Intermediate result a.  
95.            var a = Math.Pow(Math.Sin(dLatitude / 2.0), 2.0) +  
96.                    Math.Cos(dLat1InRad) * Math.Cos(dLat2InRad) *  
97.                    Math.Pow(Math.Sin(dLongitude / 2.0), 2.0);  
98.  
99.            // Intermediate result c (great circle distance in Radians).  
100.            var c = 2.0 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1.0 - a));  
101.  
102.            // Unit of measurement  
103.            var radius = 6371;  
104.            if (units == Units.Miles) radius = 3959;  
105.  
106.            return radius * c;  
107.        }  
108.    }  
109.}  
/xml>
Tags: C#, ASP.NET

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900