Using Google Maps with Visual Basic 2010

Introduction

Getting lost is an unfortunate habit for me. My mind is always somewhere else, and before I know it, I have skipped a Stop sign… or two… My wife always wants to drive, because she always knows where to go and gets just as frustrated as I get when I am lost - but for other reasons… I am not blessed with a natural compass. I have to rely on maps, Google maps. This article will demonstrate how to use Google maps in your VB desktop application.

Google Documentation & Samples

I should say that I am somewhat disappointed with the lack of documentation. I am not saying that there isn't documentation for Google's libraries, I am saying that the way the documentation is structured is not as good as Microsoft's MSDN, or Facebook's documentation. That is a bit disappointing. Perhaps I am too spoilt with Microsoft's huge reference section, that nothing else can compare to it.

I struggled immensely to find the proper details of all of Google's classes and methods of those classes.

The samples I found to be a bit lacking. Whenever I explore new programming
territories, I always like to imagine myself being a beginner programmer. Perhaps it is the teacher in me; or perhaps it is the long road I had to walk, that causes this mindset. Anyway, from a beginner's perspective, I'd say that the samples provided about Google's inner workings by most places are way too advanced. Yes, there are some complicated things that need to be demonstrated, but being a "beginner" I honestly didn't know where to start, or where to add which class. That was tough to figure out. All samples floating around on the net are solely on C#, which I think is quite unfair, hence this VB.NET article :)

Luckily, I came across this codeplex sample, which was really worth my while! It was the most complete example I have found, and it works 100%. In our project, we will use some of this project's output files. I am not saying that we will just make a VB.NET version of this article, we will only utilize what is needed and make our own unique sample, with its help.

Our Project

The purpose of our project is to quickly find a location on a Google map. In this project we will not go too overboard with unnecessary methods that we might not need.

Open Visual Studio 2010, and start a new Windows Forms VB project. Name it
anything you like. My sample (that I am including), is named FindMeQuick. Add the following objects to the form, with their associated properties :

ControlPropertySetting
Form1 Name frmFMQ
  Size 880, 606
  Text Find Me Quick
  WindowState Maximized
Panel Name Panel1
  Dock Top
  Location 0, 0
Panel Name Panel2
  Dock Left
  Location 0, 60
Panel Name Panel3
  Dock Fill
Label Location 12, 5 ( Inside Panel1 )
  Text Address to Search
TextBox Name txtSearch
  Location 111, 3 ( Inside Panel 1 )
  Size 398, 20
TrackBar Name tbZoom
  LargeChange 2
  Location 515, 3 ( Inside Panel 1 )
  Maximum 20
  Size 264, 45
  Value 15
Button Name btnSearch
  Location 785, 3 ( Inside Panel 1 )
  Text Search
Listview Name lvAddressDetails
  Columns MainAddress

Latitude

Longitude
  Dock Fill
  Location Inside Panel 2
  View Details
ElementHost Name ehImageHost
  Dock Fill
  Location Inside Panel 3

Coding

First, download the codeplex project I mentioned earlier. Unzip the downloaded project - note that this project is based on the .NET Framework 3.5. Open the solution, and Run it or Build it. This will produce a library file called Google.Api.Maps.Service.dll inside the src\Google.Api.Maps.Service\bin\Debug folder. We should now set References to this project's output inside our project.

Setting References

Apart from setting a reference to Google.Api.Maps.Service.dll, we also need to set other References, because we will be working with WPF controls inside our Windows Forms application. Let us set the following references:

Reference Tab Item
Google.Api.Maps.Service.dll Browse [Download Location]\src\Google.Api.Maps.Service\bin\Debug
PresentationCore .NET PresentationCore
PresentationFramework .NET PresentationFramework
System.XAML .NET System.XAML
WindowsBase .NET WindowsBase

We have set the reference to the GoogleMaps project so that we can use its functionality from inside our program. The Windows Presentation Foundation references, we need in order to utilize WPF features and controls inside our Windows Forms application.

Namespaces

Add the following Imports statements:

Imports Google.Api.Maps.Service.Geocoding 'GeoCoding functionalities
Imports Google.Api.Maps.Service.StaticMaps 'Map methods
Imports System.Windows.Media.Imaging 'Added reference to PresentationCore for WPF image capabilities

The first two lines ensure that we are able to make use of the Google Library's methods. The third line imports the Imaging functions present inside System.Windows. These Imaging functions are much more powerful than the Imaging functions inside System.Drawing; and that is probably the biggest reason why I opted to make use of it as well.

Searching for an Address

When searching for an address location, or route on a Google Map, we have to
tap into the Google
Geocoding API
. The purpose of this API is to convert a written address into a geographic coordinate. A geographic coordinate is expressed in Latitude and Longitude. Add the
following for your Search button:

  Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
 
     Try
       Dim fmqRequest = New GeocodingRequest() 'Request geographical info
       fmqRequest.Address = txtSearch.Text 'Address that needs to be converted to geographic coordinates
       fmqRequest.Sensor = "false" 'No built in location sensor
 
       Dim fmqResponse = GeocodingService.GetResponse(fmqRequest) 'Get response from request
 
       If fmqResponse.Status = ServiceResponse.Ok Then 'Everything OK, add to Listview
 
         lvAddressDetails.Items.Add(fmqResponse.Results.Single().FormattedAddress.ToString) 'Main address
         lvAddressDetails.Items(0).SubItems.Add(fmqResponse.Results.Single().Geometry.Location.Latitude) 'Latitude
         lvAddressDetails.Items(0).SubItems.Add(fmqResponse.Results.Single().Geometry.Location.Longitude) 'Longitude
 
 
       End If
 
     Catch ex As System.InvalidOperationException
       MessageBox.Show("Please enter Town / Suburb / City with Street Address") 'Improper address
     End Try
   End Sub

In this sub, we created a GeocodingRequest object, and set its Address property to the typed in address. We then created a Response object to determine whether or not the supplied address was valid thus making the request valid. If the response was fine, we add the address details as well as the latitude position and longitude position in the ListView. ServiceResponse is an enum that we quickly have to add. This enum contains all possible response values from the GeocodingRequest object. We also needed to catch the InvalidOperation Exception, which usually occurs if an address hasn't been entered completely. We do not need to use:

Catch ex As Exception

Because that will be classified as Pokemon Exception Handling. It is actually common-practice among some programmers I know, and it is so wrong! It is actually quite unprofessional in my opinion. Cater for specific errors and plan for them accordingly without being lazy.

Let us add the enum now:

  Private Enum ServiceResponse
     Unknown 'Unknown response
     Ok ' Everything is fine
     InvalidRequest 'Address requested was improperly formatted
     ZeroResults 'No results to return, possibly a non-existant address
     OverQueryLimit 'Too many request on a given day
     RequestDenied 'Reques denied
   End Enum

Getting the Map

Now that we have found the coordinates to the entered address, we need to display the map according to our coordinates. The best place to add this functionality is inside the ListView's SelectedIndexChanged event. Let us add that now:

  Private Sub lvAddressDetails_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvAddressDetails.SelectedIndexChanged
 
     If lvAddressDetails.SelectedIndices Is Nothing Then 'Nothing selected
       Return
     End If
 
     Dim fmqLocation As New GeoPos 'Latitude and Longitude Values
     fmqLocation.Latitude = lvAddressDetails.SelectedItems(0).SubItems(1).Text 'Set Latitude property
     fmqLocation.Longitude = lvAddressDetails.SelectedItems(0).SubItems(2).Text 'Set Longitude property
 
     Dim fmqMap = New StaticMap() 'New map object
 
     fmqMap.Center = fmqLocation.Latitude.ToString() & "," _
       & Convert.ToString(fmqLocation.Longitude) 'Center-focus the map to your desired location
     fmqMap.Zoom = tbZoom.Value.ToString("0") 'Zoom percentage
     fmqMap.Size = "250x250" 'Size of map
     fmqMap.Markers = fmqMap.Center
     fmqMap.MapType = "Roadmap" 'Can be Roadmap, Satelite, Terrain, Hybrid
     fmqMap.Sensor = "false" 'No built in location sensor
 
     Dim mpMap As New BitmapImage() 'added reference to WindowsBase and System.XAML
     mpMap.BeginInit()
     mpMap.CacheOption = BitmapCacheOption.OnDemand 'Cahce only when needed
     mpMap.UriSource = fmqMap.ToUri() 'Source of map / image
 
     mpMap.EndInit()
 
     ehImageHost.Child = ehImage 'Set child control in element host
     ehImage.Source = mpMap 'Set Image source
 
   End Sub

A couple of things happen here, so I'll break it down into smaller pieces. First, we determine a selection in the ListView. Based on this selection, we obtain a Latitude position and Longitude position to be used for the map. This happens via the GeoPos class, which only exposes the Latitude and Longitude properties. Feel free to add it to your project now, or later. Here is the code for GeoPos :

Public Class GeoPos
 
   Private Lng As Decimal 'Longitude Value
   Private Lat As Decimal 'Latitude Value
 
   Public Property Latitude() As Decimal 'Gets / Sets Latitude
     Get
       Return Lat
     End Get
     Set(ByVal value As Decimal)
       Lat = value
     End Set
   End Property
 
   Public Property Longitude() As Decimal 'Gets / Sets Longitude
     Get
       Return Lng
     End Get
     Set(ByVal value As Decimal)
       Lng = value
     End Set
   End Property
 
 End Class

We then create a StaticMap object and configure its settings, indicating what type of map we want (which can be Roadmap, Satellite, Terrain or Hybrid), what size the map should be and where its focus area should be focused.

Lastly, we create a BitmapImage object to display our map properly inside our WPF ElementHost's child object. You will notice that you need to add a declaration for the ehImage object:

  Private ehImage As System.Windows.Controls.Image = New System.Windows.Controls.Image() 'Added Element Host from WPF section in toolbox

That's it! If you were to build and run your application now, you will see that it searches for your entered address and displays the map, based on your ListView selection.

Example

Figure 1 - Example

Conclusion

The purpose of this article was just to show how easy it can be to display Google maps in your application. You could use this project as a reference to learn from, or a framework to build upon further. I hope you have enjoyed this article, and that you won't get lost (as much as I do) anymore. Till next time, cheers!

About the Author:

Hannes du Preez is a Microsoft MVP for Visual Basic for the fifth year in a row. He is a trainer at a South African-based company providing IT training in the Vaal Triangle. You could reach him at hannes [at] ncc-cla [dot] com



Related Articles

Comments

  • achat cialis

    Posted by FloallAlkatly on 07/15/2013 08:27pm

    There are at best two characters in the histrionics named Eli Aureate, and Anton Ilyich. Eli Auric is a old bookseller while Anton IIyich is a retired professor on biology. The play is acheter viagra hsef3917 cialis effet secondaire

    Reply
  • propecia generic buy online

    Posted by CoxCupCoack on 07/11/2013 04:08am

    propecia online numbers. These viagra pharmacies bid monumental discounts on viagra.http://propecia4sale.net#propecia-experience which take wreaked havoc in the time of millions of males across the world. On the in unison present, while Viagra reputation has made Pfizer, its maker incredibly spondulicks rich, the [url=http://propecia4sale.net]propecia[/url] tablets. Uttered jelly users be experiencing reported a faster retaliation continually of as vulgar as 13 minutes from consumption. Generic Viagra during itself should not create an erection. Procreative stimulation

    Reply
  • Great App., but can't get the type to function.

    Posted by Tim Pittser on 07/10/2013 06:25am

    I really like this application very functional. I'm trying to get the map type to bring satellite map, but doesn't seem to work. Any thoughts? Sincerely, Tim

    Reply
  • viagra spam email

    Posted by Dwedgedowcado on 07/07/2013 06:02am

    wonder back whether Viagra can offer a compound in behalf of their own http://viagraukpharmacies.co.uk#bl8420 The best point take Generic Viagra is that it is highly shit and is also quite safe-deposit as it works with the unpretentious chemicals in the body to surrender the required erection in the

    Reply
  • tomar cialis

    Posted by Tyncseems on 07/06/2013 02:02am

    venta de cialis en espana vbbm2054 donde comprar cialis compra cialis generico yqwg9349 viagra vs cialis vs levitra cialis precio en farmacia bqlt9183 precio cialis farmacia cialis generico en farmacias ilsh3671 cialis en farmacias partner. Totally stating that an advertise and supportive brainpower is all that is required in such cases. [url=http://www.anthail.net/damnation/viewtopic.php?f=4&t=371829]precio de cialis 20 mg [/url] ubdh9498 [url=http://techfolks.com.br/viewtopic.php?pid=25486#p25486]viagra cialis levitra cual es mejor [/url] xmit9767

    Reply
  • slots4

    Posted by poker3 on 07/02/2013 03:31am

    мини игра казино скачать [url=http://vip.kazino-za-rubli.ru/file92.html]Игры Через Яндекс Деньги[/url] покер net [url=http://vip.kazino-za-rubli.ru/file240.html]Игры Свыводом Денег[/url] казино у адмирала минск [url=http://vip.kazino-za-rubli.ru/file330.html]Скачать Онлайн Покер На Деньги[/url] интернет казино при регистрации получаешь деньги qiwi com [url=http://vip.kazino-za-rubli.ru/file6.html]Игровые Аппараты На Реальные Деньги[/url] , в карточной игре две колоды

    Reply
  • clarisonic profit in pink blossom shape is truly bonny

    Posted by iouwanzi on 06/06/2013 12:07am

    [url=http://www.australiaclarisonic.com/]clarisonic brush[/url] Cette approche ependant, juste pour un grand nombre de périodes à l’heure actuelle, toute l’entreprise collabore utilisant Jesse Lachapelle en raison des activités de publicité. (Queuwaaa ? Vous voulez ne sont pas au courant Jesse Lachapelle ? Petite et moyenne taille des classes de rattrapage pour tout le monde, par la suite. Fichier de l’ordinateur à ce moment, jeune padawan ! ) #) Afin d’améliorer la prochaine petite à moyenne taille relatives à la société photo, Document peut communiquer mon propre vraiment profiter de votre travail sur ce mec. Disputent au sérieux, à ce stade sa exploite ont tendance à être levé un grand métaphores ésotérique et un incroyablement puissant, particulièrement précis. Document adore ces sortes d’images, juste où chaque profondeur est importante à tout moment chaque parcelle est toujours à rencontrer ainsi que de lire. Interprétaton de l’individu la Pieta particulier revisité façon dont Courtney Love et Kurt Cobain (tristement prémonitoires…)#) me fascine particulièrement. Document inspirer un pour obtenir un déplacement sur différentes photos peuvent être trouvés avec son site Web. [url=http://www.miaclarisonicaustralia.org/]clarisonic mia australia[/url] Cette approche ependant, juste pour un grand nombre de périodes à l’heure actuelle, toute l’entreprise collabore utilisant Jesse Lachapelle en raison des activités de publicité. (Queuwaaa ? Vous voulez ne sont pas au courant Jesse Lachapelle ? Petite et moyenne taille des classes de rattrapage pour tout le monde, par la suite. Fichier de l’ordinateur à ce moment, jeune padawan ! ) #) Afin d’améliorer la prochaine petite à moyenne taille relatives à la société photo, Document peut communiquer mon propre vraiment profiter de votre travail sur ce mec. Disputent au sérieux, à ce stade sa exploite ont tendance à être levé un grand métaphores ésotérique et un incroyablement puissant, particulièrement précis. Document adore ces sortes d’images, juste où chaque profondeur est importante à tout moment chaque parcelle est toujours à rencontrer ainsi que de lire. Interprétaton de l’individu la Pieta particulier revisité façon dont Courtney Love et Kurt Cobain (tristement prémonitoires…)#) me fascine particulièrement. Document inspirer un pour obtenir un déplacement sur différentes photos peuvent être trouvés avec son site Web. [url=http://www.miaclarisonicaustralia.org/]clarisonic mia online[/url] Elle devait examiner un individu ghd IV Styler avant vers le bas les avantages de l’utilisation de lisseur ghd pas cher dans Vous pouvez aussi le plus souvent de prêt-à-utiliser de l’huile durcit à intégrer les huiles végétales avec de l’huile de sésame, l’huile d’olive et de noix de coco.ghd lisseur est énorme à l’intérieur du Questionnaire, votre défrisants impliquant dela crème de la crème. L’idée n’est pas si énorme qu’aux États-Unis, qui à son tour, j’ai trouvé étrange, néanmoins je pense de la nation pour la raison que de toutes les quelques autres marques qui ont été si grands qui peut être à ce point moins décent.

    Reply
  • casinos in eastern new york

    Posted by Paxydaygiex on 06/03/2013 11:46pm

    3. Are a novitiate, and would like to practice your favorite games and get on speaking terms familiar with with their rules and finer aspects quite before prospering on for professional gambling, or more willingly than taking on the additional distractions online casino uk qyke4602 online casino no deposit

    Reply
  • casino games vegas

    Posted by GOOLOUSACEACK on 06/03/2013 01:30pm

    be dressed observed in numerous gaming jurisdictions around the outback, commonly casino ventures that take been operating "corpulent and happy" for a occasional years, consider themselves in a zero-growth period. Sometimes this is just to casino bonus fbkr960 online casino reviews

    Reply
  • shop in london buy viagra

    Posted by Boileammago on 06/02/2013 03:07pm

    with a scant cup to disk proportion where the blood vessels and nerves are closely bundled - wise provoking NAION. http://generic-viagra-trust-meds.net doing the rounds, making it all the more demanding by reason of a mere mortal to see the fine dividing line between Viagra myth and Viagra reality. What is false is a far not from what to manipulate haler when they are mental, if this is literally the case?? Are Americans the merely people in the world that can obtain a antiseptic pharmaceutical when they are in necessity of generic viagra online yxfj4974 buy viagra

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: March 27, 2014 Teams need to deliver quality software faster and need integrated agile planning, task tracking, source control, auto deploy with continuous builds and a configurable process to adapt to the way you work. Rational Team Concert and DevOps Services (JazzHub) have everything you need to build great software, integrated seamlessly together right out of the box or available immediately in the cloud. And with the Rational Team Concert Client, you can connect your …

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds