Implement Map In UWP App

Maps and map services have become a vital part of mobile apps to implement geolocation functionality. In this chapter, you will learn how to display maps and use map services such as finding a location, searching for places, and driving directions.

Map

UWP uses Microsoft Bing map control to provide a map and related services. Maps API in UWP is defined in the Windows.UI.Xaml.Controls.Maps namespace. You must import the Windows.UI.Xaml.Controls.Maps namespace in your app before you can use maps.

Windows.Services.Maps control

Generate a Bing Map Authentication Key

MapControl used in UWP apps is powered by Microsoft Bing. Before you can use Bing maps, you must acquire a map authentication key using the Bing maps developer center.

Follow these steps to acquire a map authentication key. These steps require a Web browser, Internet connection, and a valid Microsoft or Azure account.

Step 1

Open a browser and open the Bing maps dev center using URL https://www.bingmapsportal.com.

Step 2

Sign in using your Microsoft or Azure account.

Step 3

Once you are you logged in, you will be asked to create a new Bing maps account. The screen will ask you to provide an account name, company name, contact name, email, and phone number.

UWP

Fill out the details on the above screen and click Create button.

Step 4

Go to My account and select My Keys menu item.

UWP

On this page, it will load your existing keys. If this is your first time, you will be asked to create a new key.

Step 5

In "Create key" form, you will be asked to provide an application name, a URL, key type, and application type. See below.

UWP

Provide a valid application name. Application URL is optional. The Key type is Basic or Enterprise. The Bing map can be used in various kinds of applications including mobile apps, websites, and others. In the Application type drop-down, select Universal Windows App for using a Bing map in your UWP app.

Step 6

Click on Create button will create a key.

On the following screen, you will see a key and its details, the created date, expiration date, and key status. The key status should be Enabled.

UWP

On this screen, you may also update and copy a key.

Map Control

The MapControl class defined in the Windows.UI.Xaml.Controls.Maps namespace represents a map control in UWP. You must import the Windows.UI.Xaml.Controls.Maps namespace in your app before using a MapControl.

Display Map

There are two common methods to load and display a Map control in UWP apps. The first method, using XAML by either typing XAML by hand or drag-and-drop a Map control from the Toolbox. Alternatively, using C# language to create a Map control dynamically in your code.

Display Map Using XAML

The <MapControl /> XAML element represents a XAML Map control. One of the easiest ways to display a map is by simply drag-and-drop the MapControl from the Toolbox to a page of your UWP app.

This action adds the following namespace import syntax to the root Page element.

xmlns:Maps="using:Windows.UI.Xaml.Controls.Maps"

And the following code to the Grid element.

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
    <Maps:MapControl HorizontalAlignment="Left" Margin="84,401,0,0" VerticalAlignment="Top" />   
</Grid> 

We can customize the above code to make the map look good by adding a Style, Zoom and Tilt modes, and setting the map key that we generated in the previous step.

The code snippet in Listing 1 creates a map control in XAML and sets its properties,

<Page  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    xmlns:local="using:LocationSample"  
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
    xmlns:Maps="using:Windows.UI.Xaml.Controls.Maps"  
    x:Class="LocationSample.MainPage"  
    mc:Ignorable="d">  
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
  
        <Maps:MapControl Name="MyMap"  
           Style="Terrain"                          
           ZoomInteractionMode="GestureAndControl"  
           TiltInteractionMode="GestureAndControl"    
           MapServiceToken="COPY-YOUR-KEY">  
        </Maps:MapControl>  
    </Grid>  
</Page> 

Listing 1.

In Listing 1, property MyServiceToken is the map authentication key that we had generated earlier. Copy and paste your map authentication key there.

The output of Listing 1 generates Figure 5.

UWP
Figure 5.

Dynamically Load Map Using C#

In the previous step, we displayed a map using XAML. Alternatively, we can use C# code to create and display a map using the MapControl class.

Before you can use the MapControl class, you must import the Windows.UI.Xaml.Controls.Maps namespace using the following code:

using Windows.UI.Xaml.Controls.Maps; 

Also, give the Grid control a name.

<Grid Name="ParentPanel" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

Now, let’s create a MapControl, set its properties, and add it to the Grid panel as a child control.

The code snippet in Listing 2 creates a map control dynamically using the MapControl class.

public void CreateDynamicMapControl() {  
    MapControl MyMap = new MapControl();  
    MyMap.Style = MapStyle.Terrain;  
    MyMap.ZoomInteractionMode = MapInteractionMode.GestureAndControl;  
    MyMap.TiltInteractionMode = MapInteractionMode.GestureAndControl;  
    MyMap.MapServiceToken = "COPY-YOUR-KEY";  
    ParentPanel.Children.Add(MyMap);  
}

Listing 2.

Now, Build and Run your project.

Get and Set Current Location

To get a user’s current location, the Location capability should be enabled in the App. To enable the Location capability, in Solution Explorer, double-click package.appxmanifest and select the Capabilities tab and check Location check box.

UWP

Device location functionality is defined in the Windows.Devices.Geolocation namespace. Declare the following statement to import the namespace:

using Windows.Devices.Geolocation; 

The Geolocator.GetGeopositionAsync() method gets the geoposition of a user. The Center property of MapControl is used to set the current location in the map. The code snippet in Listing 3 gets and set the location in the map followed by map’s zoom level and landmark visibility.

// Make sure the Location service is on             
if (await Geolocator.RequestAccessAsync() == GeolocationAccessStatus.Allowed) {  
    // Get the current location.  
    Geolocator geolocator = new Geolocator();  
    Geoposition pos = await geolocator.GetGeopositionAsync();  
    Geopoint myLocation = pos.Coordinate.Point;  
    // Set the map location.  
    MyMap.Center = myLocation;  
    MyMap.ZoomLevel = 12;  
    MyMap.LandmarksVisible = true;  
}

Listing 3.

To set and display a location in the map, the Center property of MapControl is used. The code snippet in Listing 4 creates a Geopoint for Philadelphia city location and sets it’s the center of the map.

// Create GeoPosition for Philadelphia  
BasicGeoposition userGeoPosition = new BasicGeoposition() {  
    Latitude = 39.952584, Longitude = -75.165222  
};  
Geopoint userLocation = new Geopoint(userGeoPosition);  
// Set Map's Center property  
MyMap.Center = userLocation;  
MyMap.ZoomLevel = 12;  
MyMap.LandmarksVisible = true; 

Listing 4.

Map Style

The MapStyle property sets the style of a map.

  • None - A style is not specified.
  • Road - A roadmap.
  • Aerial - An aerial map.
  • AerialWithRoads - A hybrid map that combines an aerial map with roads.
  • Terrain - A terrain map.
  • Aerial3D - An aerial 3D map.
  • Aerial3DWithRoads - A hybrid map that combines an aerial 3D map with roads.

The following code snippet sets map style to Aerial3DWithRoad.

// Set map style  
MyMap.Style = MapStyle.Aerial3DWithRoads;  

Map Zoom Level

The ZoomLevel property represents the zoom level of a map. Value of ZoomLevel is between 1 and 20 for 2D and 3D views where zoom level 1 means full earth view and zoom level 20 means the closest view of a location. For the Streetside range, the value is between 24 to 26.

The following code snippet sets map zoom level to 12, which is close to the street view in a map.

MyMap.ZoomLevel = 12;

Map Direction

The MapStyle property sets the style of a map.

  • None - A style is not specified.
  • Road - A road map.
  • Aerial - An aerial map.
  • AerialWithRoads - A hybrid map that combines an aerial map with roads.
  • Terrain - A terrain map.
  • Aerial3D - An aerial 3D map.
  • Aerial3DWithRoads - A hybrid map that combines an aerial 3D map with roads.

The following code snippet sets map style to Aerial3DWithRoad.

// Set map style  
MyMap.Style = MapStyle.Aerial3DWithRoads;

Map Icon, May Polygon, and Map Polyline

We can customize the graphical representation of a location on the map in forms of pushpins, images, and shapes. There are four ways to customize the location representation by adding MapIcon, MapPolygon, and MapPolyline objects to the MapElements. A may location representation may also be customized using custom XAML by adding Children of the MapControl.

Summary

In this article, we learned the basics of the map control and how to use it in a UWP app.

References

  • https://msdn.microsoft.com/en-us/windows/uwp/maps-and-location/controls-map


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.