Implement Map In UWP App

Maps and map services have become a vital part of mobile apps to implement geolocation functionality.

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.

Key

RktIDIVG3WY7h2XkKR9a~yj7V_AYSmXC3PpEvbTqHzw~AgW3HdGywt3XN9RFsUZslEsyk1wfVMHDCtb7sPpteHs8agkNRAxtGJVEpYgMd5NN

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.

  1. <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
  2.     <Maps:MapControl HorizontalAlignment="Left" Margin="84,401,0,0" VerticalAlignment="Top" />   
  3. </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,

  1. <Page  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     xmlns:local="using:LocationSample"  
  5.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  6.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  7.     xmlns:Maps="using:Windows.UI.Xaml.Controls.Maps"  
  8.     x:Class="LocationSample.MainPage"  
  9.     mc:Ignorable="d">  
  10.     <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
  11.   
  12.         <Maps:MapControl Name="MyMap"  
  13.            Style="Terrain"                          
  14.            ZoomInteractionMode="GestureAndControl"  
  15.            TiltInteractionMode="GestureAndControl"    
  16.            MapServiceToken="COPY-YOUR-KEY">  
  17.         </Maps:MapControl>  
  18.     </Grid>  
  19. </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:

  1. using Windows.UI.Xaml.Controls.Maps;  

Also, give the Grid control a name.

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

  1. public void CreateDynamicMapControl() {  
  2.     MapControl MyMap = new MapControl();  
  3.     MyMap.Style = MapStyle.Terrain;  
  4.     MyMap.ZoomInteractionMode = MapInteractionMode.GestureAndControl;  
  5.     MyMap.TiltInteractionMode = MapInteractionMode.GestureAndControl;  
  6.     MyMap.MapServiceToken = "COPY-YOUR-KEY";  
  7.     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:

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

  1. // Make sure the Location service is on             
  2. if (await Geolocator.RequestAccessAsync() == GeolocationAccessStatus.Allowed) {  
  3.     // Get the current location.  
  4.     Geolocator geolocator = new Geolocator();  
  5.     Geoposition pos = await geolocator.GetGeopositionAsync();  
  6.     Geopoint myLocation = pos.Coordinate.Point;  
  7.     // Set the map location.  
  8.     MyMap.Center = myLocation;  
  9.     MyMap.ZoomLevel = 12;  
  10.     MyMap.LandmarksVisible = true;  
  11. }  

 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.

  1. // Create GeoPosition for Philadelphia  
  2. BasicGeoposition userGeoPosition = new BasicGeoposition() {  
  3.     Latitude = 39.952584, Longitude = -75.165222  
  4. };  
  5. Geopoint userLocation = new Geopoint(userGeoPosition);  
  6. // Set Map's Center property  
  7. MyMap.Center = userLocation;  
  8. MyMap.ZoomLevel = 12;  
  9. 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.

  1. // Set map style  
  2. 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.

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

  1. // Set map style  
  2. 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