Get location (Latitude & Longitude) for given address in c# using google api

In my application I wanted to find Latitude & Longitude of address of a person.

To do this I have used google api.

Bellow is c# code:

 public static List<string> GetLatLng(string address)
        {
            var requestUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=true", Uri.EscapeDataString(address));

            var request = WebRequest.Create(requestUri);
            var response = request.GetResponse();
            var xdoc = XDocument.Load(response.GetResponseStream());
            var latLngArray = new List<string>();
            var xElement = xdoc.Element("GeocodeResponse");
            if (xElement != null)
            {
                var result = xElement.Element("result");
                if (result != null)
                {
                    var element = result.Element("geometry");
                    if (element != null)
                    {
                        var locationElement = element.Element("location");
                        if (locationElement != null)
                        {
                            var xElement1 = locationElement.Element("lat");
                            if (xElement1 != null)
                            {
                                var lat = xElement1.Value;
                                latLngArray.Add(lat);

                            }
                            var element1 = locationElement.Element("lng");
                            if (element1 != null)
                            {
                                var lng = element1.Value;
                                latLngArray.Add(lng);
                            }
                        }
                    }
                }
            }
            return latLngArray;
        }

Here What I did is just called google service & just extracted the latitude & longitude from the xml response which I got from service.

This free service has limitation of 2500 request per IP per day, so If your application is will request more than that then google api will block your IP temporarily & If you continue to do this then It may ban your IP also.

I your application will request more that 2500 request per day per IP then you may have to buy service from google.

admin

  • pullareddy

    good post it is woking well thanks……..