Display a Google map for an address in the system's default web browser in C#

When you enter an address, select a map type, and click Google, this example uses the following code to display a Google map showing the address in the system's default web browser.

// Display a Google map.
private void btnGoogle_Click(object sender, EventArgs e)
{
    // The basic map URL without the address information.
    const string url_base = 
        "http://maps.google.com/maps?f=q&hl=en&geocode=&" +
        "time=&date=&ttype=&q=@ADDR@&ie=UTF8&t=@TYPE@";

    // URL encode the street address.
    string addr = txtAddress.Text;
    addr = HttpUtility.UrlEncode(txtAddress.Text, System.Text.Encoding.UTF8);

    // Insert the encoded address into the base URL.
    string url = url_base.Replace("@ADDR@", addr);

    // Insert the proper type.
    switch (cboGoogle.Text)
    {
        case "Map":
            url = url.Replace("@TYPE@", "m");
            break;
        case "Satellite":
            url = url.Replace("@TYPE@", "h");
            break;
        case "Terrain":
            url = url.Replace("@TYPE@", "p");
            break;
    }

    // Display the URL in the default browser.
    Process.Start(url);
}

The code actually is fairly simple. First it uses the HttpUtility class's UrlEncode method to convert special characters in the address into URL encodings. It then inserts the encoded address in the proper spot in the Google URL. It uses a switch statement to insert the correct map type code for Map, Satellite, or Terrain in the URL and calls Process.Start to launch the final URL in the system's default web browser.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.