Reverse GEO lookup in C#

Nov 19, 2008

Google’s maps API now supports reversed GEO lookup which allows you to find an address based on geo coordinates.  All you need is a latitude, a longitude and this handy method:

private const string endPoint = "http://maps.google.com/maps/geo?q={0},{1}&output=xml&sensor=true&key=YOURKEY";

 

private static string GetAddress(double latitude, double longitude)

{

  string lat = latitude.ToString(CultureInfo.InvariantCulture);

  string lon = longitude.ToString(CultureInfo.InvariantCulture);

  string url = string.Format(endPoint, lat, lon);

 

  using (WebClient client = new WebClient())

  {

    string xml = client.DownloadString(url);

    XmlDocument doc = new XmlDocument();

    doc.LoadXml(xml);

 

    XmlNode node = doc.ChildNodes[1].FirstChild.ChildNodes[2].ChildNodes[0];

    return node.InnerText;

  }

}

It returns the address as a string.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (2) -

Yoann. B
Yoann. B France
11/28/2008 2:55:07 PM #

Hi,

Thanks for that article.

I also wrote an article about this subject : blog.sb2.fr/.../...ionGeoTargeting-for-ASPNET.aspx

Andrés Zacchino
Andrés Zacchino Argentina
12/17/2008 6:32:23 PM #

Great, Gracias

una cosa nomas. error code.

private static string GetAddress(double latitude, double longitude)
{
string lat = latitude.ToString(CultureInfo.InvariantCulture);
string lon = longitude.ToString(CultureInfo.InvariantCulture);
string url = string.Format(endPoint, lat, lon);

using (WebClient client = new WebClient())
{
    string xml = client.DownloadString(url);
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    XmlNode nodeStatus = doc.ChildNodes[1].FirstChild.ChildNodes[1].ChildNodes[0];
    if (nodeStatus.InnerText == "200") // if status code is OK
    {
       XmlNode node = doc.ChildNodes[1].FirstChild.ChildNodes[2].ChildNodes[0];
       return node.InnerText; // Primera Direccion que resulve
    }
    else
        return "Not Found";
}
}

Pingbacks and trackbacks (3)+

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.