How to call Google Geocoding service from C# code

vaibhav shah picture vaibhav shah · Apr 29, 2013 · Viewed 96k times · Source

I have one class library in C#. From there I have to call Google service & get latitude & longitude.

I know how to do it using AJAX on page, but I want to call Google Geocoding service directly from my C# class file.

Is there any way to do this or are there any other services which I can use for this.

Answer

Chris Johnson picture Chris Johnson · Apr 29, 2013

You could do something like this:

string address = "123 something st, somewhere";
string requestUri = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?key={1}&address={0}&sensor=false", Uri.EscapeDataString(address), YOUR_API_KEY);

WebRequest request = WebRequest.Create(requestUri);
WebResponse response = request.GetResponse();
XDocument xdoc = XDocument.Load(response.GetResponseStream());

XElement result = xdoc.Element("GeocodeResponse").Element("result");
XElement locationElement = result.Element("geometry").Element("location");
XElement lat = locationElement.Element("lat");
XElement lng = locationElement.Element("lng");

You will also want to validate the response status and catch any WebExceptions. Have a look at Google Geocoding API.