Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » VB.NET » 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:
Total page views :  104401
Total downloads :  4325
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
VBQuickMapPack.zip
 
Become a Sponsor

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
 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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
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.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
I was looking for it by Mahesh On March 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 it by Scott On September 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 it by mbmiller On April 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 VB6 by lichi On September 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 VB6 by Scott On September 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 VB6 by jose On November 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 in by jose On November 19, 2007
I don't know...
Reply | Email | Delete | Modify | 
A Great Article by Soumik On March 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.NET by Tamim On March 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.NET by Scott On March 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 api by map On December 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 api by Scott On December 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 this by Lin On February 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..? by rajesh On June 19, 2009
Can u please tell me how to crop only the map and zooming out to a particulat level..?
Reply | Email | Delete | Modify | 
New script knowledge by dodo On September 15, 2009
very good man... you're great
Reply | Email | Delete | Modify | 
Nice and Simple !! by kas On October 20, 2009
gr8 work there...I am actually building a software for one of my clients and was looking to automate their bus-routes via GMaps. This application provides me the starting point that I was looking for. I will also have to let the make a route on GMaps...and track the Longs & Lats to my application. These will then be used to recreate the selection. As I studied, I came to know that since there are different frames in the page, i will have to look in a particular frame to get what I want...I will keep u guyz posted.
Once again...thanks so much !!
Reply | Email | Delete | Modify | 
thank you by Marco On December 9, 2009
Thank you very much! Very interesting! Exactly what I need!
Pileggi
Reply | Email | Delete | Modify | 
Can this be done in linux? by daniel On December 27, 2009
Does anyone know of an equal for this for linux?
Reply | Email | Delete | Modify | 
Please advise me for any documentation by andhika On April 16, 2010

Hi, I wonder can we create application on windows mobile to receive and send location to webserver so from your application the location is based on the webserver data location that just receive from windows mobile phone.

I once learn VB6 thats a long ago but I havent try VB.net
I've been wondering to create cellphone tracker using free maps from google. I would like this to be my project for my last semester. Please advise me for any documentation  I should need


Thanks,
Andhika

Reply | Email | Delete | Modify | 
lv by watches On July 11, 2010
Here I will introduce a classic louis vuitton bag — Duomo. This city bag in Damier canvas takes Louis vuitton bags name from the historic shopping district in Florence, Italy. The lv , one of the architectural and artistic wonders of the world, is one of the largest cathedrals in the world, with old architectural structures still well-preserved and intact. You can imagine the rich history and culture behind this louis vuitton .
Reply | Email | Delete | Modify | 
Googlemaps Vb.net winform control by Henry Alberto On July 26, 2010
Well there's another way to integrate the google maps into your aplication, already exist controls for ASP.NET but in winforms is another story, for that reason i decided to develop a control that let me use the google maps into a winform in .net, you can find it here:

http://pegazux.blogspot.com/2010/07/pegazuxcontrolsgooglemaps.html

I hope it'll be usefull.
Reply | Email | Delete | Modify | 
Need Help by Emad On August 2, 2010
Great Article, I'm looking for the same but to use on my aviation application we are constructing in VB, our application gives the Origin and Destination Country with LAT and LON, what i'm looking for is a script to draw a line between those countries over a map with the possibilities to insert an object over the line such as aircraft to simulate the flight. is that possible? can someone help?
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.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.