How to call Google Geocoding service from C# code

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.


Solution 1:

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.

Solution 2:

I don't have the reputation to comment, but just wanted to say that Chris Johnsons code works like a charm. The assemblies are:

using System.Net;
using System.Xml.Linq;

Solution 3:

You can also use the HttpClient class which is often used with Asp.Net Web Api or Asp.Net 5.0.

You have also a http state codes for free, asyn/await programming model and exception handling with HttpClient is easy as pie.

var address = "paris, france";
var requestUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", Uri.EscapeDataString(address));

using (var client = new HttpClient())
{
    var request = await client.GetAsync(requestUri);
    var content = await request.Content.ReadAsStringAsync();
    var xmlDocument = XDocument.Parse(content);

}