Surendra Sharma

Surendra Sharma

Search This Blog

Wednesday, June 5, 2013

Get Latitude Longitude From Location

public static void GetLatitudeLongitudeFromLocation(string address, out double SelectedLatitude, out double SelectedLongitude) {

            SelectedLatitude = 0;
            SelectedLongitude = 0;

            string url = "http://maps.googleapis.com/maps/api/geocode/" + "xml?keyword=Hotels, + Australia&address=" + address + "&sensor=false&region=au";


            WebResponse response = null;

            try {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                response = request.GetResponse();

                if (response != null) {

                    XPathDocument document = new XPathDocument(response.GetResponseStream());
                    XPathNavigator navigator = document.CreateNavigator();

                    var resultXML = XDocument.Parse(navigator.InnerXml);

                    if (resultXML != null) {
                        var geocodeStatus = (from geocodeResponse in resultXML.Descendants("GeocodeResponse")
                                             select new {
                                                 Status = geocodeResponse.Element("status").Value,
                                             }).First();


                        if (geocodeStatus.Status.Equals("OK")) {
                            var geoLocation = (from Location in resultXML.Descendants("GeocodeResponse").Descendants("geometry").Descendants("location")
                                               select new {
                                                   Latitude = Location.Element("lat").Value,
                                                   Longitude = Location.Element("lng").Value,
                                               }).First();

                            if (geoLocation != null) {
                                SelectedLatitude = Convert.ToDouble(geoLocation.Latitude);
                                SelectedLongitude = Convert.ToDouble(geoLocation.Longitude);

                            }
                        }
                    }
                }
            } catch (Exception ex) {
                string error = ex.Message;
            } finally {
                if (response != null) {
                    response.Close();
                    response = null;
                }
            }

            Console.ReadLine();

        }

No comments:

Post a Comment