How to call Google Geocoding service from C# code

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.


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;

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);

}

Tags:

C#

Google Api