Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
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>
Posted

If you load the XML in the browser, you'll see the following error message:

The Geocoding API v2 has been turned down on September 9th, 2013. The Geocoding API v3 should be used now. Learn more at https://developers.google.com/maps/documentation/geocoding/[^]

If you follow the link, you'll see a page with details on upgrading to v3:
https://developers.google.com/maps/articles/geocodingupgrade[^]

If you read through that, you'll find that you need to use the new endpoint:
"https://maps.googleapis.com/maps/api/geocode/xml?address={0}"
 
Share this answer
 
You have to use Google Maps & Places API to get the distance between two places. Check the link below on how to:

http://www.aspsnippets.com/Articles/Google-Maps-V3-Calculate-Distance-Travel-Duration-draw-plot-Route-and-display-Directions-between-two-locations.aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



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