1.11M Members

Google Map Control vb.net

Unhnd_Exception
Deleted Member
 
4
 

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.

Attachments GoogleMap.txt (3.32KB)
'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
 
0
 

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'

 
0
 

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

 
1
 

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

 
1
 

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

 
0
 

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

 
0
 

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

 
0
 

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!

 
0
 

Nice job and thank you for sharing your knowledge.

 
0
 

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

 
0
 

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.

 
0
 

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

Unhnd_Exception
Deleted Member
 
0
 

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>
 
0
 

>

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?

 
0
 

Cool, nice work!

 
0
 

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?

 
0
 

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..

 
0
 

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

Attachments
 
0
 

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.

 
0
 

Thanks, this did the trick

Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

You
This is an OP Kudos discussion and contributors may be rewarded
Post:
Start New Discussion
View similar articles that have also been tagged: