user1911323
user1911323

Reputation: 11

Using Google Earth API in Winforms (.net 4.0)

Are there any samples for setting up Winforms (or WPF) that use the Google Earth API? I see a lot of deprecated stuff (FC.GEPlugins). I know that I need a webbrowser control, but I am not sure how to even assign this to the plugin.

Would love a simple application that shows how to pass a latitude/longitude to the plugin and put a marker on the location.

Thanks!

Upvotes: 1

Views: 5610

Answers (3)

Mohammad abumazen
Mohammad abumazen

Reputation: 1286

you can achieve that by building a KML file form your code and run it ,its quit simple.

Here an C# code example :

        StreamWriter _writer = new StreamWriter("C:\Map.KML");

        _writer.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://www.opengis.net/kml/2.2\">");
        _writer.WriteLine("<Document>");

        _writer.WriteLine("<Placemark>");
        _writer.WriteLine("<Style>");
        _writer.WriteLine("<IconStyle>");
        _writer.WriteLine("<color>ccaa00ee</color>");
        _writer.WriteLine("</IconStyle>");
        _writer.WriteLine("<LabelStyle>");
        _writer.WriteLine("<color>ccaa00ee</color>");
        _writer.WriteLine("</LabelStyle>");
        _writer.WriteLine("</Style>");
        _writer.WriteLine("<name>");
        _writer.WriteLine(your location name);
        _writer.WriteLine("</name>");
        _writer.WriteLine("<Point>");
        _writer.WriteLine("<coordinates>" + your longitude + "," + your latitude + "</coordinates>");
            _writer.WriteLine("</Point>");
            _writer.WriteLine("</Placemark>");
        }

        _writer.WriteLine("</Document>");
        _writer.WriteLine("</kml>");

        _writer.Close();

        System.Diagnostics.Process.Start("C:\Map.KML");

Upvotes: 1

Fraser
Fraser

Reputation: 17094

Why do you say deprecated? You can use the FC.GEPluginCtrls.GEWebBrowser in both winforms and WPF - it inherits from the standard webbrowser control and can be used wherever that can.

To load the plugin, add a marker and fly to the location you would simply do.

namespace ExampleFormTest
{
    using System;
    using System.Windows.Forms;
    using FC.GEPluginCtrls;

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            geWebBrowser1.LoadEmbededPlugin();

            // Handle the he PluginReady event 
            geWebBrowser1.PluginReady += (o, e) =>
            {
                // Here you can now use 'ge' exactly as you would
                // in the native javascript api. 
                dynamic ge = e.ApiObject;

                // create a placemark at (52, -2) look at it
                var placemark = KmlHelpers.CreatePlacemark(ge, 'myPm', 52, -2);
                GEHelpers.FlyToObject(ge, placemark);
            }; 
        }
    }
}

There is an example of setting up the controls here.

Upvotes: 0

James Stafford
James Stafford

Reputation: 1054

after I posted this I realized you asked for google earth not google maps - this is an example of google maps. hopefully it can help some

create a form

'Using the control
Public Class Mapping
Dim wide As Integer
Dim high As Integer
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() With {.Dock = DockStyle.Fill}
    Me.Controls.Add(GoogleControl1)
End Sub
End class

create a 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
Dim cnn As New MySqlConnection()
Dim cmd As New MySqlCommand
Dim adptr As New MySqlDataAdapter
Dim current As String
Dim filltab As New DataTable
Dim pop As Integer
Private WebBrowser1 As WebBrowser
Private StatusStrip1 As StatusStrip
Private StatusButtonDelete As ToolStripButton
Private StatusLabelLatLng As ToolStripStatusLabel
Private lastupdated As ToolStripStatusLabel
Private InitialZoom As Integer
Private timer2 As Timer
Private InitialLatitude As Double
Private InitialLongitude As Double
Private components As System.ComponentModel.IContainer
Private InitialMapType As GoogleMapType
Dim mapcontains As New System.Collections.Generic.HashSet(Of String)
'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
    lastupdated = New ToolStripStatusLabel
    WebBrowser1.Dock = DockStyle.Fill
    timer2 = New Timer() With {.Interval = 10000, .Enabled = True}
    WebBrowser1.AllowWebBrowserDrop = False
    WebBrowser1.IsWebBrowserContextMenuEnabled = False
    WebBrowser1.WebBrowserShortcutsEnabled = False
    WebBrowser1.ObjectForScripting = Me
    WebBrowser1.ScriptErrorsSuppressed = True
    AddHandler WebBrowser1.DocumentCompleted, AddressOf WebBrowser1_DocumentCompleted
    StatusStrip1.Dock = DockStyle.Bottom
    ' StatusStrip1.Items.Add(StatusButtonDelete)
    ' StatusStrip1.Items.Add(StatusLabelLatLng)
    StatusStrip1.Items.Add(lastupdated)
    StatusButtonDelete.Text = "Delete Markers"
    '       AddHandler StatusButtonDelete.Click, AddressOf StatusButtonDelete_Click
    AddHandler timer2.Tick, AddressOf Timer2_Tick
    Me.Controls.Add(WebBrowser1)
    Me.Controls.Add(StatusStrip1)
    'The default map settings.
    InitialZoom = 10
    InitialLatitude = 36.8438126
    InitialLongitude = -76.2862457
    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

Private Sub InitializeComponent()
    Me.SuspendLayout()
    '
    'GoogleControl
    '
    Me.Name = "GoogleControl"
    Me.ResumeLayout(False)

End Sub

End Class

then create a html file called GoogleMap.htm

<!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);

    }

    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>

congratulations you are in business - load the form and you should have a map looking at the center of the Hampton Roads, VA area. to change the location go to

InitialZoom = 10
InitialLatitude = 36.8438126
InitialLongitude = -76.2862457

the higher the zoom number the closer you will be to streetview initial lat and long must be in decimal

to add a marker you would use vb.net

                        WebBrowser1.Document.InvokeScript("AddMarker", New Object() {"Description entered here", lat, long})

you could easily add 2 textboxes and a button and run this script with the lat and long from the textboxes

good luck

Upvotes: 0

Related Questions