I needed to write a function to get a set of co-ordinates from an address, supplied as a string.
Using the Google API, I came up with this:
First, I created a struct, to represent the lat and lon co-ordinates:
public struct Coordinate
{
private double _latitude;
private double _longitude;
public Coordinate(double latitude, double longitude)
{
_latitude = latitude;
_longitude = longitude;
}
public double Latitude { get { return _latitude; } set { _latitude = value; } }
public double Longitude { get { return _longitude; } set { _longitude = value; } }
}
This is a simple representation of a set of latitude and longitude co-ordinates.
The main method, which returns the above Coordinate struct is:
public static Coordinate GetCoordinates(string address)
{
using (var client = new WebClient())
{
Uri uri = YOUR_URI_HERE;
/* The first number is the status code,
* the second is the accuracy,
* the third is the latitude,
* the fourth one is the longitude.
*/
string[] geocodeInfo = client.DownloadString(uri)
.Split(',');
return new Coordinate(
Convert.ToDouble(geocodeInfo[2]),
Convert.ToDouble(geocodeInfo[3]));
}
}
On line 5, you need to specify your Google API URL, in the format of:
http://maps.google.com/maps/geo?q=ADDRESS GOES HERE&output=csv&key=YOUR KEY HERE
And that’s it!
Obviously, there are usage restrictions when using the Google API for this, as outlined on the documentation pages