Learn to Geocode Address with C# and Google API

There comes a time when it is important for a business to Geo Code address / customers.. and nothing is better than using Google API to accomplish this task.

Sample problem: Create a small application using C# that uses Google API to geo code a given address / location. The C# application should show user latitude, longitude and the accuracy of the lat / long.

Solution: We can use Google’s API to geo code a given address, Google API will give us back three items we need. Lat, Long and the accuracy. The API will give us back 8 for very good match and down to 2 for poor or bad match.

Implementation: I assume you know how to program in C#, therefore I’m only going to list CodeBehind version of the application.

//include below system.Net class if its not already included

using System.Net;

//you might need a google api key if you don’t already have one

//https://developers.google.com/maps/location-based-apps

//API key for https://YourDomain.com

string strKey = “ABQIAAAA………………PUT YOUR KEY HERE

//Address

string strAddress = “1 Main St, New York, NY 10001”;

//Create a path string with address and api key

string sPath = “https://maps.google.com/maps/geo?q=” + strAddress + “&output=csv&key=” + strKey;

//Using WebClient class to download the CSV

//WebClient is part of System.Net class

WebClient client = new WebClient();

//Downloading CSV with Latitute and Longitute

//.DownloadString method download CSV file from browser

string[] eResult = client.DownloadString(sPath).ToString().Split(‘,’);

//As you can see, I’m spliting the string into array

//I’m not using element 0 as it keeps status code if address if found, //but you can if you want too.

//Once the result / response is in string array eResult, we can access //it by calling its GetValue method and pass the 0 based index.

lbl1.Text = eResult.GetValue(1).ToString();

lbl2.Text = eResult.GetValue(2).ToString();

lbl3.Text = eResult.GetValue(3).ToString();

That’s all, its simple as that!!