Sunday, July 21, 2013

Geocoding and Reverse Geocoding in C#

Step 1: Download and add the GMap.Net to your project

download a copy of GMap.Net library from:

http://greatmaps.codeplex.com/

add a reference to GMap.Net.Core to your project

Step 2: Get address or (lat, lon) from (lat, lon) or address

The following two methods allow you to retrieve address from (lat, lon) or (lat, lon) from a given address. The code also uses simple cache technique to store the retrieved results.

public static string FindAddress(double lat, double lng)
{
 int latE6 = (int)(lat * 1000000);
 int lngE6 = (int)(lng * 1000000);

 string foldername = "location_cache";
 if (!Directory.Exists(foldername))
 {
  Directory.CreateDirectory(foldername);
 }

 string filename = string.Format("{0}\\{1}_{2}.txt", foldername, latE6, lngE6);

 if (File.Exists(filename))
 {
  StreamReader reader = new StreamReader(filename);
  string data=reader.ReadToEnd();
  reader.Close();
  return data;
 }

 string address = "";
 GeoCoderStatusCode status;
 var pos = GMapProviders.GoogleMap.GetPlacemark(new PointLatLng(lat, lng), out status);
 if (status == GeoCoderStatusCode.G_GEO_SUCCESS && pos != null)
 {
  address = pos.Address;
  StreamWriter writer = new StreamWriter(filename);
  writer.WriteLine(address);
  writer.Close();
 }

 return address;
}

public static bool FindLatLngByAddress(string address, out double lat, out double lng)
{
 string address64 = EncodeTo64(address);

 string foldername = "address_cache";
 if (!Directory.Exists(foldername))
 {
  Directory.CreateDirectory(foldername);
 }

 string filename = string.Format("{0}\\{1}.txt", foldername, address64);

 if (File.Exists(filename))
 {
  StreamReader reader = new StreamReader(filename);
  string data = reader.ReadToEnd();
  reader.Close();
  string[] latlng=data.Split(new char[]{','});
  lat = double.Parse(latlng[0].Trim());
  lng = double.Parse(latlng[1].Trim());
  return true;
 }

 lat = 0;
 lng = 0;
 GeoCoderStatusCode status;
 PointLatLng? point=GMapProviders.GoogleMap.GetPoint(address, out status);
 if (status == GeoCoderStatusCode.G_GEO_SUCCESS && point != null)
 {
  lat = point.Value.Lat;
  lng = point.Value.Lng;

  StreamWriter writer = new StreamWriter(filename);
  writer.WriteLine(string.Format("{0},{1}", lat, lng));
  writer.Close();
  return true;
 }
 return false;
}

static public string EncodeTo64(string toEncode)
{
 byte[] toEncodeAsBytes
    = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
 string returnValue
    = System.Convert.ToBase64String(toEncodeAsBytes);
 return returnValue;
}

No comments:

Post a Comment