Hi there!
In my current project I had to integrate a Google Map into my WPF application. This isn’t the most straightforward thing since Google pretty much only offers two alternatives: either use their Javascript API on a Web Application, or use their Web Services for geocoding/reverse-geocoding, etc. (they can also return static images, but I needed an actual map that I could interact with within my application).
I ended up developing a WPF Control for the Google Map. This control is quite simple, as it is only composed of a Web Browser and an html file (for the moment at least). This method can easily integrate any Javascrit API with a .Net application, so I’m going to post a little tutorial on how to do so.
Step 1: HTML File
First thing to do is the html file. You can check out the Google Maps Javascript API Tutorial for more info (and check their Reference as well), I’ll just write the necessary stuff here.
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
...
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
In our html file we’ll have to reference the Javascript API, so we set the // <
The only thing this control has is a WebBrowser.
<UserControl x:Class="My.Controls.GoogleMapsControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Grid>
<WebBrowser Name="mapBrowser" Margin="25" />
</Grid>
</UserControl>
The code-behind for the GoogleMapsControl, has the browser navigate to the html file we created, and then invokes the javascript code through methods, like so:
using System;
using System.Windows.Controls;
namespace My.Controls
{
public partial class GoogleMapsControl : UserControl
{
public GoogleMapsControl()
{
InitializeComponent();
mapBrowser.Navigate(new Uri("file://127.0.0.1/c$/Path/to/file/map.html"));
}
public void Pan(double x, double y)
{
this.mapBrowser.InvokeScript("Pan", x, y);
}
}
}
Since the Web Browser will be executing javascript code, your browser may show a little warning asking permission to execute said code. Running the file through “file://127.0.0.1/c$/…” shouldn’t show the warning.
And that’s it, a quick and easy Google Maps control. This should work with any other Javascript API (Bing maps, for instance..). WinForms also includes a web browser control, so this will also work there (although invoking a script is done using WebBrowser.Document.InvokeScript() ).
Maybe I’ll publish the control soon, there are still a few more features to implement, but thats the gist of it!
See ya next time.