Blue Theme Orange Theme Green Theme Red Theme
 
ASP.NET Web Hosting – Click Here
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Windows Controls » Add a Google Map to a VB Desktop Application

Add a Google Map to a VB Desktop Application

This project demonstrates a quick and easy way to add mapping to a windows desktop application (with an available internet connection) using Google Maps as the basis and source for the map.

Author Rank:
Technologies: .NET 1.0/1.1, Common Controls, Controls, Windows Forms,Visual Basic .NET
Total downloads : 2032
Total page views :  54786
Rating :
 5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
VBQuickMapPack.zip
 
ArticleAd
Become a Sponsor


Related EbooksTop Videos

Introduction

This project demonstrates a quick and easy way to add mapping to a windows desktop application (with an available internet connection) using Google Maps as the basis and source for the map. The demonstration application will map a point by either its physical address or its latitude and longitude.  Building the application does not require any sort of agreement or licensing with Google; there is no required API to invoke and using this approach it really won't take more than a few minutes to put a map into your Visual Basic 2005 built desktop application.



Figure 1:  Mapping an Address (
New York).
 

Since the application is based entirely on Google Maps, as an added bonus, the Google Maps site provides all of the view manipulation controls necessary to navigate the map; so with no additional effort you pick up panning and zooming, traffic maps, street maps, raster imagery, and hybrid maps combining street maps with raster.  You even get an overview map, the ability to print the map, email it, or link to it at no extra charge. 

One could also remove the interface and feed specific addresses or coordinates directly to equivalent code and access specific maps directly through a web browser control.



Figure 2:  Mapping a Latitude/Longitude Coordinate Pair (Paris).
 

Getting Started

The solution contains a single project for a C# windows desktop application. The project is called "VB_QuickMap" and this project contains one form. The form contains all of the controls and code necessary to request and display a map from the Google Maps site.



Figure 3:  Solution Explorer with Project Visible.
 

Form 1 contains a split panel control oriented horizontally; the top pane contains the controls used to enter the search terms.  There are two sets of controls in this panel; the first set will collect an address in the form of the street, city, state, and zip code (5 digits). The second set of controls will collect a latitude and longitude. Both sets of controls have buttons; the click event handlers for these buttons are used to construct a query string used to retrieve the map based on either the address or coordinates supplied by the user. 

The bottom pane of the control contains a panel with a web browser control docked into it. The query string is appended to the basic URL used to query Google Maps; the combined string is set as the navigation URL property for the web browser control. 

Code:  Form 1

The form 1 class starts out with the default class declaration. An import statement was added to pull in the System.Text library; this is required to support the use of string builders within the application.

Imports System.Text

 

Public Class Form1

Following the class declaration, the next bit of code in the class is used to handle the button click event that requests a map of a physical address from Google Maps; that code is as follows: 

''' <summary>

''' Map a physical address

''' </summary>

''' <param name="sender"></param>

''' <param name="e"></param>

''' <remarks></remarks>

Private Sub btnMapIt_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnMapIt.Click

 

    Try

        Dim street As String = String.Empty

        Dim city As String = String.Empty

        Dim state As String = String.Empty

        Dim zip As String = String.Empty

        Dim queryAddress As New StringBuilder()

        queryAddress.Append("http://maps.google.com/maps?q=")

 

        ' build street part of query string

        If txtStreet.Text <> String.Empty Then

            street = txtStreet.Text.Replace(" ", "+")

            queryAddress.Append(street + "," & "+")

        End If

 

        ' build city part of query string

        If txtCity.Text <> String.Empty Then

            city = txtCity.Text.Replace(" ", "+")

            queryAddress.Append(city + "," & "+")

        End If

 

        ' build state part of query string

        If txtState.Text <> String.Empty Then

            state = txtState.Text.Replace(" ", "+")

            queryAddress.Append(state + "," & "+")

        End If

 

        ' build zip code part of query string

        If txtZipCode.Text <> String.Empty Then

            zip = txtZipCode.Text.ToString()

            queryAddress.Append(zip)

        End If

 

        ' pass the url with the query string to web browser control

        webBrowser1.Navigate(queryAddress.ToString())

 

    Catch ex As Exception

 

        MessageBox.Show(ex.Message.ToString(), "Unable to Retrieve Map")

 

    End Try

 

End Sub 

A quick examination of this code reveals that the contents of the text boxes used to define the physical address are captured from the form and used to populate variables local to the event handler. A string builder is used to build the URL and query string. 

Once the string builder is initialized, the first part of the URL is appended to it. As each additional section of the address is conditioned for use in the query string, it too is appended to the query string. Once the string is defined, it is passed to the web browser control as its navigate URL. At that point, the web browser will display the address if it can be found or will summon Goggle Maps with optional selections used to narrow down to a single address.

The next bit of code in the application performs a similar function with Latitudes and Longitudes; the click event handler for the button is used to evoke the map based upon the user supplied lat/long values. That code is as follows: 

''' <summary>

''' Map a location by latitude and longitude

''' </summary>

''' <param name="sender"></param>

''' <param name="e"></param>

''' <remarks></remarks>

Private Sub btnMapLatLong_Click(ByVal sender As System.Object, ByVal e As 

System.EventArgs) Handles btnMapLatLong.Click

 

    If txtLat.Text = String.Empty Or txtLong.Text = String.Empty Then

        MessageBox.Show("Supply a latitude and longitude value.""Missing Data")

    End If

 

    Try

        Dim lat As String = String.Empty

        Dim lon As String = String.Empty

        Dim queryAddress As New StringBuilder()

        queryAddress.Append("http://maps.google.com/maps?q=")

 

        ' build latitude part of query string

        If txtLat.Text <> String.Empty Then

            lat = txtLat.Text

            queryAddress.Append(lat + "%2C")

        End If

 

        ' build longitude part of query string

        If txtLong.Text <> String.Empty Then

            lon = txtLong.Text

            queryAddress.Append(lon)

        End If

 

        webBrowser1.Navigate(queryAddress.ToString())

 

    Catch ex As Exception

 

        MessageBox.Show(ex.Message.ToString(), "Error")

 

    End Try

 

End Sub 

That wraps up the class. The two button click event handlers do all of the work necessary to generate the query string and to pass that string to the navigate URL property for the web browser control. The approach shown works with latitude and longitude pairs as well as addresses; when dealing with addresses, the function will work even with incomplete addresses (e.g., no zip code, or no zip code and street address). 

Summary.

This article was intended to demonstrate a very simple approach to integrating maps into a desktop application (so long as the desktop application user has a viable internet connection). Since the application operates against a public website, there is no requirement for licensing the application or its users; of course there is also no guarantee that the URL and query string will not change at some point in the future.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
VBQuickMapPack.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
I was looking for itMahesh3/23/2007
Good article. I was looking for how to use google map in one of the Web apps. It would be nice instead of redirecting to Google site, if google Web Service can just give us the image.
Reply | Email | Delete | Modify | 
 
 
Re: I was looking for itScott9/11/2007
I think it is a safe bet to assume that Google will brand every image they return however through their Google maps API it might be easier to get closer to that mark.  Their API is available for free (http://www.google.com/apis/maps/) but there are some limitations; for example, with the free account they will support a maximum of 50,000 requests a day.  This is likely okay for a lot of sites but might not be so great for others.
Reply | Email | Delete | Modify | 
Re: I was looking for itmbmiller4/2/2007
Was wondering if it is possible to track latitude / longitude as the mouse cursor is moved?
Reply | Email | Delete | Modify | 
VB Qick Map in VB6lichi9/10/2007
Follwoing my previous question, I am a VB6 user not in VBNet or C# yet. Do you have VB6 coded project available? Thanks. Cliff Po info@microsimtech.com
Reply | Email | Delete | Modify | 
 
 
Re: VB Qick Map in VB6Scott9/11/2007
No, I don't have any VB6 code for it but it can be done using the same approach.  You could use the web browser control and assemble the querystring in the same manner.
Reply | Email | Delete | Modify | 
 
Re: VB Qick Map in VB6jose11/19/2007

Exists...

this page had: http://www.macoratti.net/

but it is a Brasilian page and not be in english. learn portuguese or use a translator...its easy

Reply | Email | Delete | Modify | 
Im injose11/19/2007
I don't know...
Reply | Email | Delete | Modify | 
A Great ArticleSoumik3/10/2008
HI thnx for such a article But i want to know how would u create bookmarks from database where i hv 1000 sites lat long more over i need to know how would u actually create line from one point to another in vb.net all the data are fetcheed from database plz reply Soumik Chandra soumikchandra@gmail.com
Reply | Email | Delete | Modify | 
GOOGLE MAP IN VB.NETTamim3/24/2008
Hi, I was hoping if you can help me with google map in vb,net, the code that you have provided is to show the address typed but i want the program to give direction to the user e.g from one post code to another postcode and then print the map. Thank you very much in advance!
Reply | Email | Delete | Modify | 
 
 
Re: GOOGLE MAP IN VB.NETScott3/25/2008
You can do that with the Google Maps API; I will try to post something about that but I would also encourage you to look at the Yahoo! Map API; the directions service is really pretty easy to use.  You can get a start with that here:  http://developer.yahoo.com/maps/simple/index.html
Reply | Email | Delete | Modify | 
desktop apimap12/8/2008
could you please tell me how to use google map apis in my desktop application? I want to add multiple lable images to my map and text...
Reply | Email | Delete | Modify | 
 
 
Re: desktop apiScott12/14/2008

http://code.google.com/apis/maps/index.html

You can sign up for it here; there is a reference available for the API on the same page.

Reply | Email | Delete | Modify | 
I just needed something simple like thisLin2/5/2009
Thank you so much for pointing me in this direction. I just needed something simple like this. If you contact Google, they will give you everything you need including a user id, password and the api to use their application but I do not need that for my desktop application at this time. This is perfect for my current needs. So thanks.
Reply | Email | Delete | Modify | 
how to zoom out..?rajesh6/19/2009
Can u please tell me how to crop only the map and zooming out to a particulat level..?
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved