Adding a Map to your WP7 App

by CameronM 1. November 2011 06:08

My recent TrafficMATE Windows Phone 7 app heavily utilised the Bing Maps control for WP7. It was used to plot route in combination with the Bing Maps Route Service API, as well as to show the location of traffic cameras.

The easiest way to get started with the Maps control for Windows Phone is to take a look at the tutorials found in the Labs provided by Microsoft. If you just want to throw up a map to display a single geographic point, then here’s how to start.

Add the control to your xaml

The Map control resides in the Microsoft.Phone.Controls.Maps library, so you will want to add a reference to this library into your project. You will also want to create a namespace reference in the XAML page where you want to use the map control.

xmlns:msmap="clr-namespace:Microsoft.Phone.Controls.Maps;assembly=Microsoft.Phone.Controls.Maps"

You can then add the map control to your xaml.

<msmap:Map x:Name="routeMap"

           CredentialsProvider="{Binding CredentialsProvider}">

</msmap:Map>

 

Set your Bing Maps API key

To use the map you’ll need to get a key, which is free from Microsoft. Without a key, you will be stuck with the message Invalid Credentials Sign up for a developer account.

The API key is a single string, much like you may be familiar with if you have used the Google Maps API. The Map control makes it a little harder though and expects an object of the CredentialsProvider class. It’s easy enough to create a property in your .cs file that exposes a property of type CredentialsProvider and then bind that property to the map property.

private readonly CredentialsProvider _credentialsProvider = new ApplicationIdCredentialsProvider("Your Key");

 

public CredentialsProvider CredentialsProvider

{

    get { return _credentialsProvider; }

}

Adding a pushpin to the map

The first thing you will want to do with your newly acquired map is to zoom to a certain location and display a pushpin.  Thankfully there are a few ways to do this. The first is to programmatically add a pushpin to the map in your .cs file and zoom in.

The bare-bones approach to add a pushpin directly to the Map in your code is shown below.
Pushpin p = new Pushpin();
p.Location = new System.Device.Location.GeoCoordinate(51.42153, -0.20786);
 
//add the pushpin to the map
routeMap.Children.Add(p);

Compile and run the app and you will get a single pushpin, as shown below.

Just as you can add the pushpin in code-behind, you can also programmatically zoom the map to the chosen location, by setting the map’s Center and ZoomLevel properties. Set the zoom to an appropriate number between 1 and 19, where 19 is very close.

//set the center of the map and the zoom level

routeMap.Center = new System.Device.Location.GeoCoordinate(51.42153, -0.20786);

routeMap.ZoomLevel = 19;

Tags: , ,

Windows Phone 7 | WP7