Microsoft Most Valuable Professional

Chris Pietschmann

An MVP From Wisconsin



Scrape Geocodes from Google Maps w/ C#

I need to geocode some addresses once in a while and I notice if you view the source of the Google Maps page, the geocodes are right there. So instead of looking at the source of the page manually, I just created a little app that scrapes them from the page for me and places them into textboxes.

Below is a small code snippet I wrote that does just that. It's not perfect but it is simple and it just plain works.

string lat = "";
string lng = "";
string address = "1 Microsoft Way, Redmond WA";

try
{
System.Net.
WebClient client = new System.Net.WebClient();
string page = client.DownloadString("http://maps.google.com/maps?q=" + address);
int begin = page.IndexOf("markers: [");
string str = page.Substring(begin);
int end = str.IndexOf(",image:");
str = str.Substring(0, end);

//Parse out Latitude
lat = str.Substring(str.IndexOf(",lat: ") + 6);
lat = lat.Substring(0, lat.IndexOf(
",lng: "));
//Parse out Longitude
lng = str.Substring(str.IndexOf(",lng: ") + 6);
}
catch (Exception ex)
{
MessageBox.Show("An Error Occured Loading Geocode!\nCheck that a valid address has been entered.", "An Error Occured Loading Geocode!");
}
MessageBox.Show("Latitude:\n" + lat + "\n\nLongitude:\n" + lng);

 

I know I should have used Regular Expressions, but I don't know them very well and this was just quicker/easier to do. It took all of like 5 minutes.

Currently rated 3.0 by 2 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Tuesday, June 13, 2006 9:00 AM
Permalink | Comments (3) | Post RSSRSS comment feed

Related posts

Comments

vadim

Friday, June 30, 2006 8:50 PM

vadim

Dim expr As String = "^([\s\S]+)(lat: ([-]|[.]|[-.]|[0-9])[0-9]*[.][0-9]+,lng: ([-]|[.]|[-.]|[0-9])[0-9]*[.][0-9]+)([\s\S]+)$"

If System.Text.RegularExpressions.Regex.IsMatch(page, expr) Then
Dim latlon() As String = System.Text.RegularExpressions.Regex.Split(page, expr)
MessageBox.Show(latlon(2))
End If

Bart

Wednesday, July 12, 2006 1:51 PM

Bart

You maybe didn't notice, but as from June 11th '06, the geocoding feature is included in the Google Maps API.

Pierpaolo

Friday, October 13, 2006 10:54 AM

Pierpaolo

Hi. Could you help me writing a similar code but aimed at getting the distance between two addresses obtained using maps.google.com "Get Directions" feature? Thank you.

Comments are closed

About the author

I'm Chris Pietschmann, go to the About Me page to learn more about me.

Search

Sponsors

Web.Maps.VE - ASP.NET AJAX Virtual Earth Mapping Server Control

Recent comments

Disclaimer


This work is licensed under a Creative Commons Attribution 3.0 United States License, unless explicitly stated otherwise within the posted content.
© Copyright 2004 - 2008 Chris Pietschmann