You are on page 1of 2

using System; using System.Net; using System.Xml.XPath; namespace GeoCode { public class GeoCode { private string url = "http://maps.googleapis.com/maps/api/geocode/xml?

ad dress={0}&sensor=false"; private string _address = string.Empty; public GeoCode(string address) { url = string.Format(url, address); } public GeoCoord GetGeoCoordinate() { WebResponse response = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "Get"; response = request.GetResponse(); if (response != null) { XPathDocument document = new XPathDocument(response.GetRespo nseStream()); XPathNavigator navigator = document.CreateNavigator(); // get response status XPathNodeIterator statusIterator = navigator.Select("/Geocod eResponse/status"); statusIterator.MoveNext(); if (statusIterator.Current.Value != "OK") throw new Exceptio n("Status Found : " + statusIterator.Current.Value); else { XPathNodeIterator locationIterator = navigator.Select("/ GeocodeResponse/result/geometry/location"); locationIterator.MoveNext(); XPathNodeIterator latIterator = locationIterator.Current .Select("lat"); latIterator.MoveNext(); string latitude = latIterator.Current.Value; XPathNodeIterator longIterator = locationIterator.Curren t.Select("lng"); longIterator.MoveNext(); string longitude = longIterator.Current.Value; XPathNodeIterator formatedAddressIterator = navigator.Se lect("/GeocodeResponse/result/formatted_address"); formatedAddressIterator.MoveNext(); GeoCoord coord = new GeoCoord { Latitude = Convert.ToDou ble(latitude), Longitude = Convert.ToDouble(longitude), FormatedAddress = format edAddressIterator.Current.Value }; return coord; } }

else return null; } catch (Exception ex) { throw ex; } finally { if (response != null) response.Close(); response = null; } } } } namespace GeoCode { public class GeoCoord { public double Latitude; public double Longitude; public string FormatedAddress; } }

You might also like