Add Maps to your WinUI / Windows App SDK Application using MapControl

The latest 1.5 experimental and preview version of the Windows App SDK contains the much anticipated MapControl. To get started, all you need to do is the following:

  • Update to either the experiemental or preview version of the Windows App SDK
  • Register for a token/key using these instructions
  • Add the MapControl to your application and set the MapServicesToken either in XAML or code behind.
<Window
    x:Class="App2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <MapControl x:Name="mapControl" Width="800"  Height="600"  InteractiveControlsVisible="True"
                   MapServiceToken="{your map service token}"  />
    </Grid>
</Window>

Unfortunately, this doesn’t work out of the box (see GitHub issue), with only a Blue background showing. This experience may vary as one of the contributors on the GitHub issue has indicated that the MapControl is working for them.

If you read through the GitHub issue, you’ll notice that dotMorten has contributed a workaround to get the maps to render:

public MainWindow()
{
    this.InitializeComponent();
    mapControl.Loaded += MapControl_Loaded;
}

private void MapControl_Loaded(object sender, RoutedEventArgs e)
{
    var webView = VisualTreeHelper.GetChild(mapControl, 0) as WebView2;
    webView.NavigationCompleted += WebView_NavigationCompleted;
}

private async void WebView_NavigationCompleted(WebView2 sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs args)
{
    sender.NavigationCompleted -= WebView_NavigationCompleted;
    var result = await sender.ExecuteScriptAsync($"initializeMap(0,0,\"{mapControl.MapServiceToken}\");");
}

With this workaround in place, maps should start appearing. I particularly like the terrain option that’s selectable from the interactive controls in the top right corner.

Not withstanding the issue with the maps not actually showing, it’s great to have a functioning MapControl. Having said this, it’s early days and most of the features available in the UWP MapControl are missing. For example the MapIcon doesn’t yet support things like setting the ZIndex or the Title; MapElement exists but there’s no subclasses, such as MapPolygon, making it kinda useless.

Hopefully by the time v1.5 of the Windows App SDK ships, the MapControl will be in a more stable and more complete state.

1 thought on “Add Maps to your WinUI / Windows App SDK Application using MapControl”

Leave a comment