Here is a function that I wrote to get the Latitude and Longitude for a given address using the Google API. It's quite simple.
You build the URL along with the query string parameters, make a
request to Google's API, when the response comes back you process the
results.
using System.Net;
private void GetLatAndLongGoogle(string address, string city, string state,
string zip, ref string inLat, ref string inLong)
{
/*
* Pass in the paramters: address, city, state, zip
*
* The Longitude and Latitude will be passed back out through: inLat, inLong
* (don't forget to pass these last two as "ref")
*/
/* appID is the API Key you get from Google */
string appID = "YOUrKraZYKey1w";
/* Here we build the URL with the query string parameters*/
url.Append("output=csv&key=");
url.Append(appID);
url.Append("&q=");
url.Append(CleanForURL(address));
url.Append(",");
url.Append(CleanForURL(city));
url.Append(",");
url.Append(CleanForURL(state));
url.Append(",");
url.Append(CleanForURL(zip));
/*Create HttpWebRequest object*/
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url.ToString());
myReq.Credentials = CredentialCache.DefaultCredentials;
try
{
HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
string httpString = readStream.ReadToEnd();
if (httpString.StartsWith(@"200,"))
{
string[] AddressArray = httpString.Split(',');
inLat = AddressArray[2];
inLong = AddressArray[3];
}
else
{
inLat = "0.0";
inLong = "0.0";
}
}
catch (Exception e)
{
inLat = "0.0";
inLong = "0.0";
}
}
private string CleanForURL(string inStr)
{
inStr = inStr.Replace(@"&", "");
inStr = inStr.Replace(@"/", "");
inStr = inStr.Replace(@"\", "");
inStr = inStr.Replace(@"?", "");
return inStr;
}
Here is a sample of how you would call the function:
int myAddressKey = 1234;
string myAddress = "401 Main St";
string myCity = "Huntington Beach";
string myState = "CA";
string myZip = "92648";
string myLatitude = "";
string myLongitude = "";
GetLatAndLongGoogle(myAddress, myCity, myState, myZip,
ref myLatitude, ref myLongitude);
MyProcedureThatUpdatesDBWithLatAndLong(myAddressKey, myLatitude, myLongitude);