Google Map Control vb.net

Unhnd_Exception 4 Tallied Votes 9K Views Share

I was so amazed at how easy it was to embed google maps into a vb app I decided to post a quick example to help anyone get started.

This is a simple example. Google's api has all kinds of things to help customize your map. You can find out anything you need to know from here: http://code.google.com/apis/maps/documentation/javascript/reference.html


You will need to:
Create a new windows forms app.
Add a class named GoogleControl and paste the GoogleControl code into it.
Add a new html doc to the project and name it GoogleMap.htm and set its Build action to CopyIfNewer
Copy the attached text file into the GoogleMap.htm doc.

Run the app and you should have google maps displaying.

codeorder commented: just because .i have no use for this thread "yet". -3
M.Waqas Aslam commented: thanks for this impressive thing :) +5
Begginnerdev commented: Thanks for sharing, Exception. +4
'Using the control
Public Class Form1

    Private GoogleControl1 As GoogleControl

    Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        GoogleControl1 = New GoogleControl

        GoogleControl1.Dock = DockStyle.Fill

        Me.Controls.Add(GoogleControl1)

    End Sub

End Class

'The Control

'The class needs to be marked as com visible so the
'script in the GoogleMap.htm can call some of the subs.
<System.Runtime.InteropServices.ComVisibleAttribute(True)> _
Public Class GoogleControl : Inherits UserControl

    Private WebBrowser1 As WebBrowser
    Private StatusStrip1 As StatusStrip
    Private StatusButtonDelete As ToolStripButton
    Private StatusLabelLatLng As ToolStripStatusLabel

    Private InitialZoom As Integer
    Private InitialLatitude As Double
    Private InitialLongitude As Double
    Private InitialMapType As GoogleMapType

    'I use this enum to store the current map
    'type into the application's settings.
    'So when the user closes the map on Satellite
    'mode it will be on Satellite mode the next 
    'time they open it.
    Public Enum GoogleMapType
        None
        RoadMap
        Terrain
        Hybrid
        Satellite
    End Enum

    Sub New()
        MyBase.New()

        WebBrowser1 = New WebBrowser
        StatusStrip1 = New StatusStrip
        StatusButtonDelete = New ToolStripButton
        StatusLabelLatLng = New ToolStripStatusLabel

        WebBrowser1.Dock = DockStyle.Fill
        WebBrowser1.AllowWebBrowserDrop = False
        WebBrowser1.IsWebBrowserContextMenuEnabled = False
        WebBrowser1.WebBrowserShortcutsEnabled = False
        WebBrowser1.ObjectForScripting = Me
        WebBrowser1.ScriptErrorsSuppressed = False
        AddHandler WebBrowser1.DocumentCompleted, AddressOf WebBrowser1_DocumentCompleted

        StatusStrip1.Dock = DockStyle.Bottom
        StatusStrip1.Items.Add(StatusButtonDelete)
        StatusStrip1.Items.Add(StatusLabelLatLng)

        StatusButtonDelete.Text = "Delete Markers"
        AddHandler StatusButtonDelete.Click, AddressOf StatusButtonDelete_Click

        Me.Controls.Add(WebBrowser1)
        Me.Controls.Add(StatusStrip1)

        'The default map settings.
        InitialZoom = 4
        InitialLatitude = 38
        InitialLongitude = -96.5
        InitialMapType = GoogleMapType.RoadMap
    End Sub

    Sub New(ByVal zoom As Integer, ByVal lat As Double, ByVal lng As Double, ByVal mapType As GoogleMapType)
        'This constructor could be used to start the map with different values
        'other than the default settings.
        Me.New()
        InitialZoom = zoom
        InitialLatitude = lat
        InitialLongitude = lng
        InitialMapType = mapType
    End Sub

    Private Sub GoogleControl_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Load the htm doc into the webrowser.
        'When it completes, intialize the map.
        WebBrowser1.DocumentText = My.Computer.FileSystem.ReadAllText("GoogleMap.htm")
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
        'Initialize the google map with the initial settings.
        'The Initialize script function takes four parameters.
        'zoom, lat, lng, maptype.  Call the script passing the
        'parameters in.
        WebBrowser1.Document.InvokeScript("Initialize", New Object() {InitialZoom, InitialLatitude, InitialLongitude, CInt(InitialMapType)})
    End Sub

    Public Sub Map_MouseMove(ByVal lat As Double, ByVal lng As Double)
        'Called from the GoogleMap.htm script when ever the mouse is moved.
        StatusLabelLatLng.Text = "lat/lng: " & CStr(Math.Round(lat, 4)) & " , " & CStr(Math.Round(lng, 4))
    End Sub

    Public Sub Map_Click(ByVal lat As Double, ByVal lng As Double)
        'Add a marker to the map.
        Dim MarkerName As String = InputBox("Enter a Marker Name", "New Marker")

        If Not String.IsNullOrEmpty(MarkerName) Then
            'The script function AddMarker takes three parameters
            'name,lat,lng.  Call the script passing the parameters in.
            WebBrowser1.Document.InvokeScript("AddMarker", New Object() {MarkerName, lat, lng})
        End If

    End Sub

    Public Sub Map_Idle()
        'Would be a good place to load your own custom markers
        'from data source
    End Sub

    Private Sub StatusButtonDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        'Call the DeleteMarkers script in the htm doc.
        WebBrowser1.Document.InvokeScript("DeleteMarkers")
    End Sub

End Class
Netcode 33 Veteran Poster

am trying it out, can't see anything like 'CopyifNewer' in the Build action. What's closest to it that stars with a ''C is 'Compile' and 'Content'

Netcode 33 Veteran Poster

Add a new html doc to the project and name it GoogleMap.htm and set its Build action to CopyIfNewer

Am sure you meant, 'Copy to output Directory' property of the html doc. Another thing, am done with setting up the project and codes as directed by you but when i run, it gives the following error:

Error: Project file must include the .NET Framework assembly 'WindowsBase, PresentationCore, PresentationFramework' in the reference list. WindowsApplication1

WIth this, does it mean i have to reference any of the .NET libraries. I really want to try this out so i need help here

Netcode 33 Veteran Poster

Added the three references from the .NET library as requested in the error message and i had a successful run but the form is blank. Cant see any map but i noticed the 'Delete markers' in the left-bottom corner

Netcode 33 Veteran Poster

okay now. I got it to work, it was an omission on my part, did not change the 'Copy to output Directory' property of the html doc to 'Copy if newer'.

To add to Unhnd Exception's post,
> you need to add the following references from the .NET library:
windows base
presentation core
presentation framework
> Correction to one of cwarn23's points: its the 'Copy to Directory' property of the html doc that should be changed to 'Copy if Newer' and not the 'Build Action' property

Every other thing works just perfectly.
Thanks Unhnd Exception

NetJunkie 29 Junior Poster

Sickest integration I have seen of an HTML/HTM file in VB yet! Nice post.

Member Avatar for Alankst
Alankst

Hi

I have just started looking for a map control for vb. There are several versions on the Internet. which one are you using? Does Goolgle provide the control itself?

Appreciate if you could show me where to download.

thanks

Alan

Member Avatar for Alankst
Alankst

Hi

Sorry I wasn't paying attention. After reading the code, I realised that you are making the control.

Thanks for sharing the project. Nice!

bluehangook629 0 Posting Whiz in Training

Nice job and thank you for sharing your knowledge.

striag 0 Newbie Poster

Great job, it works fine, but I would need a
Further, how can I read the height of the soil, but in particular the buildings? I mean something you know?
thanks
greetings
Gerardo

Member Avatar for wxman13
wxman13

In your post you have the following...

Copy the attached text file into the GoogleMap.htm doc

Where is the attached text file to copy into the GoogleMap.htm doc. I can't seem to find it.

bgood007 0 Newbie Poster

Same question as wxman13: I can't find the text file for GoogleMap.htm. Thanks.

Member Avatar for Unhnd_Exception
Unhnd_Exception

Attached GoogleMap.htm

Below are the contents of the no longer existing googlemap.htm attachment.

just add a html file to the project named GoogleMap.htm and set its build action to copy if newer and paste the following into the file:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
        html
        {
            height: 100%;
        }
        body
        {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        #map_canvas
        {
            height: 100%;
        }
    </style>

    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"> </script>

    <script type="text/javascript">  

        var map;
        var Markers = [];

        function Initialize(zoomLevel,lat,lng,type){  
            //Get the type of map to start.
            //Need to convert the GoogleMapType enum
            //to an actual Google Map Type
            var MapType;
            switch (type)
            {
                case 1:
                    MapType = google.maps.MapTypeId.ROADMAP;
                    break;
                case 2:
                    MapType = google.maps.MapTypeId.TERRAIN;
                    break;
                case 3:
                    MapType = google.maps.MapTypeId.HYBRID;
                    break;
                case 4:
                    MapType = google.maps.MapTypeId.SATELLITE;
                    break;
                default:
                   MapType = google.maps.MapTypeId.ROADMAP;
            };

            //Create an instance of the map with the lat, lng, zoom, and
            //type passed in
            var myLatlng = new google.maps.LatLng(lat,lng);   
            var myOptions = {zoom: zoomLevel,center: myLatlng,mapTypeId: MapType};
            var MarkerSize = new google.maps.Size(48,48);

            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);     
            google.maps.event.addListener(map, 'click', Map_Click);
            google.maps.event.addListener(map, 'mousemove', Map_MouseMove);
            google.maps.event.addListener(map, 'idle',Map_Idle);
            google.maps.event.addListener(map, 'mousedown',MouseDown);
        }  
        function MouseDown(e){
        window.external.Mouse_Down(); 
        }

        function Map_Click(e){
            window.external.Map_Click(e.latLng.lat(),e.latLng.lng()); 
        }

        function Map_MouseMove(e){
            window.external.Map_MouseMove(e.latLng.lat(),e.latLng.lng()); 
        }

        function Map_Idle(){
            window.external.Map_Idle();
        }


        function DeleteMarkers()
        {
            if (Markers){
                for (i in Markers){
                    Markers[i].setMap(null);
                    google.maps.event.clearInstanceListeners(Markers[i]);
                    Markers[i] = null;
                }
                Markers.length = 0;
            }
        }


        function AddMarker(name,lat,lng)
        {
            var MarkerLatLng = new google.maps.LatLng(lat, lng);     
            var MarkerOption = {map:map,position:MarkerLatLng,title:name};
            var Marker = new google.maps.Marker(MarkerOption);
            Markers.push(Marker);
            MarkerLatLng = null;
            MarkerOption = null;
        }

    </script>

</head>
<body>
    <div id="map_canvas" style="width: 100%; height: 100%">
    </div>
</body>
</html>
pcigreg 0 Newbie Poster

>

Got this going, and it is awesome, I want to throw a bunch of zip codes at it and have them map them (mark them) how would I go about doing that?

rprenen 0 Newbie Poster

Cool, nice work!

razree 0 Newbie Poster

Created new class, added GoogleControl code to it, created GoogleMap.htm and added the text, set the Copy to output dir to Copy if newer but all I'm getting are these errors:

'InitializeComponent' is not declared. It may be inaccessible due to its protection level.

'Controls' is not a member of 'WindowsApplication1.GoogleControl.Form1'

'Form1' is not a member of 'WindowsApplication1'

what am I missing?

razree 0 Newbie Poster

I'm getting another error:
"google" is undefined, line33, char 7, code 0(this is for googlemap.htm I think)

I've tripple checked that I had copeid exact text from the post..

Quazy 0 Newbie Poster

Hello, I get this error when I click the map, either left or right mouse button, any tip for how to solve this?
error14

My guess is that the error is in the .htm file.
I have double checked the contents in the project and .htm file, and code is according to posted here.
Thanks

clefranc 0 Newbie Poster

Quazy,
Just remove these lines of code in GoogleMap.htm:

62.            google.maps.event.addListener(map, 'mousedown',MouseDown);

64.        function MouseDown(e){
65.        window.external.Mouse_Down(); 
66.        }

or implement your own MouseDown sub in GoogleControl.vb.

You can also remove line 59 and use GoogleControl1.Map_Click(latitute, longitude) in Form1 to add a marker.

Quazy 0 Newbie Poster

Thanks, this did the trick

dokrobs 0 Newbie Poster

Thanks very much for this Exception - you said its simple but it takes someone who really knows what there do make it so - this is really impressive.

Hopefully someone can answer one question I have. In the Sub Map Idle() it says its a good place to add markers from a dataset. Obviously the map is already rendered at this point so the data from the dataset is not sent back over the net to google. As far as I can see that remains the case when the map refreshes - am I right ? - just want to be sure no data from the dataset is sent back over the net

srkv03 12 Newbie Poster

Thanks very much! It works like a treat.

Customoffice` 0 Newbie Poster

Great code, thanks.. but can anyone tell me how to add a kml file as a layer in this app please ??

artemix22 4 Newbie Poster

What i have to do?

its appear when i click the map.

artemix22 4 Newbie Poster

ignore my question above, it's work like a charm now :D, thx soooooooo much dude, you're the man, god bless you always!

micofelicio 0 Newbie Poster

Hello razzi! I'm getting a similar error as well.
Can anyone help me with this? I'm familiar with HTML and a bit of OOP but just started with javascript. >.< script_error

Archdeacon 0 Newbie Poster

If the creator of this template would like to leave a note here, I have made considerable modifications and would like to give credit if I distribute my version (free of charge, of course).

farooqulhassan 0 Newbie Poster

thanks for your help ..

Xeta 0 Newbie Poster

Thats cool, just learnt how to integrate html to windows app

bisma 0 Newbie Poster

thanks..i think i am getting somewhere in my assignment now...but i need more HELP
is it possible that i save the googlemap once taken from the internet and then my application works offline...and can go online only when i have to load new map..???.
actually, i have to make a simple application that displays a map and through an external file of latitudes and long, locations are marked and updated ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.