using bing mapsaz12722.vo.msecnd.net/.../usingbingmaps.docx · web viewthis lab walks you through...

50
Hands-On Lab Using Bing Maps Lab version: 1.0.0 Last updated: 4/29/2022 Page | 1 ©2011 Microsoft Corporation. All rights reserved.

Upload: others

Post on 21-Jul-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Hands-On LabUsing Bing MapsLab version: 1.0.0

Last updated: 5/22/2023

Page | 1

©2011 Microsoft Corporation. All rights reserved.

Page 2: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

CONTENTSOverview.....................................................................................................................................................3

Exercise 1: Introduction to the Bing Map Control.......................................................................................5

Task 1 – Registering a Bing Maps Account...........................................................................................5

Task 2 – Working with the Bing Map Control......................................................................................8

Exercise 2: Handling and Customizing Pushpins........................................................................................21

Task 1 – Creating a Pushpins Layer....................................................................................................21

Exercise 3: Calculating a Route..................................................................................................................29

Task 1 – Adding a Route to the Map..................................................................................................29

Task 2 – Displaying Route Itineraries.................................................................................................35

Summary...................................................................................................................................................43

Page | 2

©2011 Microsoft Corporation. All rights reserved.

Page 3: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Overview

The Bing™ Maps Silverlight® Control for Windows® Phone combines the power of Silverlight and Bing Maps to provide an enhanced mapping experience. Developers can use the Bing Maps Silverlight Control to incorporate the latest location and local search features into their Windows Phone applications.

Using both Bing Maps Silverlight Control and the Bing Maps SOAP (strategy on a page) Services, you can create Windows Phone applications that include an enhanced mapping experience.

This lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone, and provides a quick reference for developing Windows Phone applications integrated with Bing Maps.

Objectives

Upon completion of the lab you will:

Be familiar with Bing Maps for Windows Phone Understand how to use Bing Map control with Data Binding Have used Bing Maps services to fetch mapping data Have created a simple map-based application, complete with pushpins and route layers

Prerequisites

The following is required to complete this hands-on lab:

Microsoft Visual Studio® 2010 Express for Windows Phone or Microsoft Visual Studio 2010 Windows Phone Developer Tools Active Internet Connection

Note: You can download all Windows Phone development tools in one package from http://go.microsoft.com/?linkid=9772716

Exercises

This hands-on lab comprises of the following exercises:

1. Introduction to the Bing Map Control2. Handling and Customizing Pushpins3. Calculating and Rendering a Route

Page | 3

©2011 Microsoft Corporation. All rights reserved.

Page 4: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Estimated time to complete this lab: 90 minutes.

Page | 4

©2011 Microsoft Corporation. All rights reserved.

Page 5: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Exercise 1: Introduction to the Bing Map Control

In this exercise you will:

Register a Bing Maps account to get a private key Learn about the Bing Silverlight map control for Windows Phone Add a map control to the page Attach the map control with Bing Maps private key Switch between aerial and road map modes Center and zoom the map to a geographic location

You will use the Microsoft Visual Studio 2010 Express for Windows Phone development environment, and will deploy to the Windows Phone Emulator for debugging. The solution we will be working with is based upon the Silverlight for Windows Phone Application template.

Note: The steps in this hands-on lab illustrate procedures using Microsoft Visual Studio 2010 Express for Windows Phone, but they are equally applicable to Microsoft Visual Studio 2010 with the Windows Phone Developer Tools. Instructions that refer generically to Visual Studio apply to both products.

Task 1 – Registering a Bing Maps Account

In this task you will create a Bing Maps account over the Internet. The Bing Maps Account Center allows you to create keys to use the Bing Maps Control, Bing Maps SOAP Services, Bing Maps REST (representational state transfer) Services and Bing Spatial Data Services. If you already have a key for using Bing, you may use it for the next tasks. Without a valid key, you won’t be able to see retrieve Bing Maps content from the web.

1. Open your web browser and go to the following address: http://www.bingmapsportal.com.

2. Click Create to create a new Bing Maps account using your Windows Live ID.

Figure 1Bing maps registration

Page | 5

©2011 Microsoft Corporation. All rights reserved.

Page 6: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

3. On the next page, fill in your details.

Figure 2Bing maps account details

4. Once you’ve agreed the terms and registered and/or signed in, you may choose to create a new key for your application. Click the “Create or view keys” link on the left.

Figure 3

Page | 6

©2011 Microsoft Corporation. All rights reserved.

Page 7: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Create or view keys

5. On the next page fill in your application details and click Createkey.

Figure 4Create a new key

Page | 7

©2011 Microsoft Corporation. All rights reserved.

Page 8: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

6. Now you have to sign in and you will able to see your private key.

7. Below, you’ll see your new private key. Save this key, you will use it later.

Figure 5Saving the private key

Note: In the next tasks you’ll be asked to use this private key. Keep it handy since you’ll have to use it for the rest of this lab.

Task 2 – Working with the Bing Map Control

In this task you’ll use the Bing Map Silverlight control for Windows Phone. The Bing Map Silverlight Control combines the power of Silverlight and Bing Maps to provide an enhanced mapping experience. Developers can use the Bing Maps Silverlight Control to incorporate the latest location and local search features into their applications.

You’ll use an existing starter solution for Microsoft Visual Studio 2010 Express for Windows Phone or Microsoft Visual Studio 2010. This solution contains a partial Windows Phone application, with startup code and UI behavior for completing this lab.

1. Open Microsoft Visual Studio 2010 Express for Windows Phone from Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft Visual Studio 2010 Express for Windows Phone.

2. Open the project located at the Source\Ex1-TheBingMapControl\Begin folder of this lab, select Begin.sln and click Open.

3. Examine the project you’ve just opened. This is a standard Windows Phone application consists of single page: MainPage:

MainPage.xaml – defines the Bing maps lab UI using XAML; you’ll place UI controls into this file during the lab

MainPage.cs – this is a partial class that contains startup code for implementing the Bing maps lab; do not change this file during the lab

MainPage.xaml.cs – contains the map lab logic; you’ll place map application logic in this file during the lab

Page | 8

©2011 Microsoft Corporation. All rights reserved.

Page 9: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

o Resources such as icons and styles are located in the Resources folder

o Helper classes are placed in the Helpers folder

4. During the following steps you will use the Bing map control and learn how to use it. To begin, add a reference to the Microsoft.Phone.Controls.Maps assembly.

5. Open the MainPage.xaml in design mode and drag the Map control, located on the toolbox, to the center of the page. This will both add an XAML namespace and create an instance of the Bing map control for Windows Phone.

6. Open MainPage.xaml with the XAML editor, you should find something like this:

XAML

<!-- Map View --><Border x:Name="MapView" Background="Black" Height="768" Width="480"> <my:Map Name="map1" Height=”50” Width=”50” /></Border>

7. Change the map name to Map and remove both Height and Width properties so the map will stretch across the entire screen.

XAML

<my:Map x:Name="Map" />

8. Press F5 to examine the map.

Page | 9

©2011 Microsoft Corporation. All rights reserved.

Page 10: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Figure 6Bing map control

Note: The first time you zoom in by double clicking the map, the following message appears: “Invalid Credentials. Sign up for a developer account.” To remove this message, you should use the Bing Maps private key created earlier with the map.

9. Stop debugging and open the App.xaml.cs file and add a new internal constant string field called “Id” to the App class. This field will hold the Bing Maps private key you’ve created. You will reference this key during the lab to create credentials for both the Bing map control and Bing services.

C#

internal const string Id = "your Bing maps private key";

10. Open the MainPage.xaml.cs file and add the following using statements above the class declaration.

C#

Page | 10

©2011 Microsoft Corporation. All rights reserved.

Page 11: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

using System;using System.Device.Location;using Microsoft.Phone.Controls.Maps;

11. Now that we have the private key, we want to bind the map control with that key. To do so:

Locate the “Fields” region inside the MainPage class Create a new private read-only field of type

Microsoft.Phone.Controls.Maps.CredentialsProvider Initialize it with a new instance using the private key you’ve just added to the App class

C#

private readonly CredentialsProvider _credentialsProvider = new ApplicationIdCredentialsProvider(App.Id);

Note: If the using statement for the Microsoft.Phone.Controls.Maps were not added, you should resolve this issue by either using a full qualified class name or adding the required using statement. Several code snippets in this lab assume you are aware of how to resolve this kind of inconveniences.

12. Locate the “Properties” region inside the MainPage class and expose the field you’ve just created as a public property called CredentialsProvider so you can bind it with the map control.

C#

public CredentialsProvider CredentialsProvider{ get { return _credentialsProvider; }}

13. Open the MainPage.xaml file in XAML editor, and bind the Map.CredentialsProvider property with the public property you’ve just created.

XAML

<my:Map Name="Map" CredentialsProvider="{Binding CredentialsProvider}" /><phone:PhoneApplicationPage x:Class="UsingBingMaps.MainPage" ...>     <Canvas x:Name="LayoutRoot">         <!-- Map View -->        <Border x:Name="MapView"                Background="Black"

    Height="768" Width="480">Page | 11

©2011 Microsoft Corporation. All rights reserved.

Page 12: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

                        <!-- TODO : Add map control -->            <my:Map Name="Map"                    CredentialsProvider="{Binding CredentialsProvider}"  />           </Border>        ...    </Canvas>    ...</phone:PhoneApplicationPage>

Note: The MainPage.DataContext is set with the MainPage instance itself in the MainPage.cs file, so the implicit binding source is the MainPage instance itself.

14. Set the Map.Mode property to AerialMode with labels. This will change the map mode to be displayed in aerial view rather than road view, which is the default.

XAML

<my:Map Name="Map" CredentialsProvider="{Binding CredentialsProvider}"> <my:Map.Mode> <my:AerialMode ShouldDisplayLabels="True" /> </my:Map.Mode>

</my:Map>

15. We’ve added a button to the application bar for changing the map mode. This button’s click event is handled by calling the ChangeMapMode method located in the “Tasks” region. In the MainPage.xaml.cs, locate the “Tasks” region inside the MainPage class. You’ll find the ChangeMapMode method over there. Place code for switching from Road to Aerial mode and vice versa, by setting the Map.Mode property with a new instance of type Microsoft.Phone.Controls.Maps.AerialMode or Microsoft.Phone.Controls.Maps.RoadMode.

C#

private void ChangeMapMode(){ if (Map.Mode is AerialMode) { Map.Mode = new RoadMode(); } else { Map.Mode = new AerialMode(true);

Page | 12

©2011 Microsoft Corporation. All rights reserved.

Page 13: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

}}

16. Press F5 to test the results. For switching views, click on the “eye” button on the application bar. This invokes the ChangeMapMode method.

Figure 7Aerial map mode

Note: The Silverlight Map control for Windows Phone is designed to support the data binding model. Changing properties of the Map control using data binding is a good way for handling data objects within data templates and is a best practice for decoupling the Map control from the logic behind, especially when using the MVVM (model view viewmodel) pattern. For the simplicity of this lab, we are not using a data template for the map view itself; hence the logic is located directly in the MainPage code behind. From now on, we will leverage the map control data binding capabilities, although properties of the map control can be altered directly from code behind.

Page | 13

©2011 Microsoft Corporation. All rights reserved.

Page 14: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

17. To remove the Bing logo and Copyright from the bottom, you can set both Map.CopyrightVisibility and Map.LogoVisibility to Visibility.Collapsed.

XAML

<my:Map Name="Map" CredentialsProvider="{Binding CredentialsProvider}" CopyrightVisibility="Collapsed" LogoVisibility="Collapsed">

<my:Map.Mode> <my:AerialMode ShouldDisplayLabels="True" /> </my:Map.Mode>

</my:Map>

You may notice that you can zoom in by double-clicking on the map. This option is implemented internally by the map control. You have an option to display the built-in zoom bar, by setting the Map.ZoomBarVisibility to Visible, but you can’t change the buttons style or location. Next you will add custom zoom buttons so you can freely zoom in and out.

18. In MainPage.xaml.cs, find the automatic property called Zoom, and change it to get or set the value of the _zoom field. In the setter, consider the zoom level constraints you’ve added and notify on property changed.

C#

public double Zoom{ get { return _zoom; } set { var coercedZoom = Math.Max(MinZoomLevel, Math.Min(MaxZoomLevel, value)); if (_zoom != coercedZoom) { _zoom = value; NotifyPropertyChanged("Zoom"); } }}

19. Open the MainPage.xaml in XAML editor and bind the Map.ZoomLevel property with the Zoom property you’ve just changed. The binding mode must be two-way.

XAML

<my:Map Name="Map"

Page | 14

©2011 Microsoft Corporation. All rights reserved.

Page 15: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

LogoVisibility="Collapsed" CopyrightVisibility="Collapsed" CredentialsProvider="{Binding CredentialsProvider}" ZoomLevel="{Binding Zoom, Mode=TwoWay}"> <my:Map.Mode> <my:AerialMode ShouldDisplayLabels="True" /> </my:Map.Mode>

</my:Map>

20. Drop two buttons vertically from the toolbox into the middle left side of the map control, one for zoom-in and the other for zoom-out.

XAML

<my:Map Name="Map" LogoVisibility="Collapsed" CopyrightVisibility="Collapsed" CredentialsProvider="{Binding CredentialsProvider}" ZoomLevel="{Binding Zoom, Mode=TwoWay}"> <my:Map.Mode> <my:AerialMode ShouldDisplayLabels="True" /> </my:Map.Mode>

<Button x:Name="ButtonZoomIn" HorizontalAlignment="Left" VerticalAlignment="Top" Height="56" Width="56" Margin="8,180,0,0" /> <Button x:Name="ButtonZoomOut" HorizontalAlignment="Left" VerticalAlignment="Top" Height="56" Width="56" Margin="8,260,0,0" />

</my:Map>

21. Register the respective button Click event with the ButtonZoomIn_Click and ButtonZoomOut_Click event handlers. These event handlers are already provided in the MainPage.xaml.cs file. When invoked, the ButtonZoomIn_Click event handler increases the Zoom property by one and the ButtonZoomOut_Click event handler decreases the Zoom property by one.

XAML

<Button x:Name="ButtonZoomIn" HorizontalAlignment="Left" VerticalAlignment="Top" Height="56" Width="56" Margin="8,180,0,0"

Page | 15

©2011 Microsoft Corporation. All rights reserved.

Page 16: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Click="ButtonZoomIn_Click" /> <Button x:Name="ButtonZoomOut" HorizontalAlignment="Left" VerticalAlignment="Top" Height="56" Width="56" Margin="8,260,0,0" Click="ButtonZoomOut_Click" />

22. To change the look and feel of the zoom-in and zoom-out buttons, open the MainPage.xaml in XAML mode and set each Button.Style property with the appropriate ButtonZoomInStyle or ButtonZoomOutStyle style. These styles were provided with the starter solution and are located in the DefaultStyle.xaml resource file.

XAML

<Button x:Name="ButtonZoomIn" Style="{StaticResource ButtonZoomInStyle}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="56" Width="56" Margin="8,180,0,0" Click="ButtonZoomIn_Click" /> <Button x:Name="ButtonZoomOut" Style="{StaticResource ButtonZoomOutStyle}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="56" Width="56" Margin="8,260,0,0" Click="ButtonZoomOut_Click" />

Page | 16

©2011 Microsoft Corporation. All rights reserved.

Page 17: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

23. To test the results, press F5 and click the zoom-in and zoom-out buttons.

Figure 8Zoom out

Page | 17

©2011 Microsoft Corporation. All rights reserved.

Page 18: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Figure 9Zoom in

In the next step you’ll center the map to your geographic location. Since this lab works with the emulator, you don’t have a real GPS device. So you’ll have to pre-define your geographic location using latitude and longitude coordinates.

Note: You can determine your geographic location by browsing to http://www.bing.com/maps, set your location, and then copy the Latitude and Longitude coordinates from the address bar.

24. In the MainPage.xaml.cs, add a new static, read-only field of type System.Device.Location.GeoCoordinate, called DefaultLocation, and set it with a new instance using your latitude and longitude coordinates. This will be your current location.

Page | 18

©2011 Microsoft Corporation. All rights reserved.

Page 19: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

C#

private static readonly GeoCoordinate DefaultLocation = new GeoCoordinate(47.639631, -122.127713);

25. In the MainPage.xaml.cs, create a property called Center that exposes the _center field. In the setter, call the notification change method.

C#

public GeoCoordinate Center{ get { return _center; } set { if (_center != value) { _center = value; NotifyPropertyChanged("Center"); } }}

26. In the MainPage.xaml, bind the Map.Center property with the Center property you’ve created. The binding mode must be two-way.

XAML

<my:Map Name="Map" CredentialsProvider="{Binding CredentialsProvider}" ZoomLevel="{Binding Zoom, Mode=TwoWay}" Center="{Binding Center, Mode=TwoWay}"> ...

</my:Map>

27. In the MainPage.xaml.cs, find the CenterLocation method. The first application’s bar left button event handler calls this method. Change both Center and Zoom to defaults.

C#

private void CenterLocation(){ Center = DefaultLocation;

Zoom = DefaultZoomLevel;}

Page | 19

©2011 Microsoft Corporation. All rights reserved.

Page 20: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

28. To test the application, press F5 and click the application bar’s target icon on the left.This should zoom and center the map to the location provided by the DefaultLocation field.

Figure 10Center and zoom map to default location

This concludes the exercise.

Note: The complete solution for this exercise is provided at the following location: Source\Ex1-TheBingMapControl\End.

Page | 20

©2011 Microsoft Corporation. All rights reserved.

Page 21: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Exercise 2: Handling and Customizing Pushpins

In this exercise you will:

Learn how to use map layers with data binding Create a pushpin layer Add a pushpin for indicating current location Handle pushpin clicks Add pushpins from a catalog to the map Customize the pushpin look and feel

Task 1 – Creating a Pushpins Layer

In this task you will learn how to create a map layer and how to populate it with pushpin data using data binding. A map layer is represented by a custom panel of type Microsoft.Phone.Controls.Maps.MapLayer. Using the MapLayer panel you can have any kind of UIElement on top of the map. The MapLayer panel knows how to lay out elements on the map using geo coordinates. A map control can have zero or more layers.

Although we can add and remove visual items directly to the MapLayer panel from code behind, we will populate map layers using the data binding mechanism. Instead of using MapLayer directly, we will use another control of type Microsoft.Phone.Controls.Maps.MapItemsControl. This custom ItemsControl uses the MapLayer panel to layout items by default.

In this task you will create also a pushpin catalog and display it using a popup window. To build a catalog, you will bind a list box to a collection of predefined pushpin models. Selecting a pushpin from the catalog will clone it and add that pushpin to the touched area. You will use the Map control APIs to translate a view point to geographic location.

1. Open the starter solution located in the Source\Ex2-HandlingPushpins\Begin folder.

Note: You should set the Bing Maps application Id in the App class with your private key created in the previous exercise.

2. Open the file named MainPage.xaml.cs.

3. To populate the pushpins layer with pushpins, add a new private read-only field called _pushpins of type ObservableCollection<PushpinModel>, and initialize it with one PushpinModel instance using the default location.

C#

Page | 21

©2011 Microsoft Corporation. All rights reserved.

Page 22: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

private readonly ObservableCollection<PushpinModel> _pushpins = new ObservableCollection<PushpinModel>{ new PushpinModel { Location = DefaultLocation }};

4. Expose the _pushpins field with public property so you can bind it with the pushpins layer.

C#

public ObservableCollection<PushpinModel> Pushpins{ get { return _pushpins; }}

5. Inside the DefaultStyle.xaml resource dictionary, create a new style for the pushpin as follows:

XAML

<Style x:Key="PushpinStyle" TargetType="m:Pushpin"> <Setter Property="BorderBrush" Value="#FFF4F4F5" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Canvas Height="0" RenderTransformOrigin="0.5,0.5" Width="0"> <Canvas RenderTransformOrigin="0.5,0.5" Height="1" Width="1"> <Path Data="M22.5,1 C34.374123,1 44,10.625878 44,22.5 C44,31.034525 39.027256,38.407604 31.821138,41.879868 L31.359026,42.095631 L22.702744,60.864998 L13.900847,42.209641 L13.651964,42.100761 C6.1912994,38.727623 0.99999976,31.220058 1,22.5 C0.99999976,10.625878 10.625878,1 22.5,1 z" Fill="{TemplateBinding BorderBrush}" Height="61.865" Stretch="Fill" Stroke="Black" StrokeThickness="2" StrokeLineJoin="Miter" UseLayoutRounding="False" Width="45" RenderTransformOrigin="0.5,0.5"

Page | 22

©2011 Microsoft Corporation. All rights reserved.

Page 23: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Canvas.Left="-2.703" Canvas.Top="-7.187" > <Path.RenderTransform> <CompositeTransform TranslateX="-20" TranslateY="-55"/> </Path.RenderTransform> </Path> <Path Data="M35,17.5 C35,27.164984 27.164984,35 17.5,35 C7.8350167,35 0,27.164984 0,17.5 C0,7.8350167 7.8350167,0 17.5,0 C27.164984,0 35,7.8350167 35,17.5 z" Fill="{TemplateBinding Background}" HorizontalAlignment="Left" Height="35" Stretch="Fill" StrokeThickness="2" VerticalAlignment="Top" RenderTransformOrigin="0.5,0.5" Width="35" UseLayoutRounding="False" Canvas.Top="-7.4" Canvas.Left="-2.888" > <Path.RenderTransform> <CompositeTransform TranslateX="-15" TranslateY="-50"/> </Path.RenderTransform> </Path> </Canvas> <ContentPresenter Width="35" Height="35" RenderTransformOrigin="0.5,0.5" Canvas.Top="-3.5"> <ContentPresenter.RenderTransform> <CompositeTransform TranslateX="-18" TranslateY="-54"/> </ContentPresenter.RenderTransform> </ContentPresenter> </Canvas> </ControlTemplate> </Setter.Value> </Setter></Style>

Note: If you design your own pushpin control template, you should know that the default relative point of a pushpin when scaling the map (zoom) is the bottom left corner, not the center or top left. You can easily create your own control template using Microsoft Expression Blend for Windows Phone, which is part of the Windows Phone development tools.

Page | 23

©2011 Microsoft Corporation. All rights reserved.

Page 24: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

6. Add new public property of type Uri, named Icon to the PushpinModel class. You will use it to bind the image of the pushpin.

C#

public class PushpinModel{ public GeoCoordinate Location { get; set; }

public Uri Icon { get; set; } ...}

7. Open the MainPage.xaml file. Set the content of the pushpin to an Image element and bind the Image.Source property to the PushpinModel.Icon property.

XAML

<my:MapItemsControl ItemsSource="{Binding Pushpins}"> <my:MapItemsControl.ItemTemplate> <DataTemplate> <my:Pushpin Style="{StaticResource PushpinStyle}" Location="{Binding Location}" Background="{Binding TypeName, Converter={StaticResource PushpinTypeBrushConverter}}"> <Image Source="{Binding Icon}" /> </my:Pushpin>...

8. In the MainPage.xaml.cs, set the PushpinData.Icon property of pushpin instance you’ve created before with a relative Uri to the PushpinLocation.png icon file located in the Pushpins project folder.

C#

private readonly ObservableCollection<PushpinModel> _pushpins = new ObservableCollection<PushpinModel>{ new PushpinModel { Location = DefaultLocation, Icon = new Uri("/Resources/Icons/Pushpins/PushpinLocation.png", UriKind.Relative) }};

Page | 24

©2011 Microsoft Corporation. All rights reserved.

Page 25: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

9. Open the file name PushpinCatalog.cs under Models folder and add the following highlighted code. This file defines a class which contains one pushpin instance per pushpin type.

C#

public class PushpinCatalog{ ... public PushpinCatalog() { InitializePuspins(); }

private void InitializePuspins() { string[] pushpinIcons = { "PushpinBicycle.png", "PushpinCar.png", "PushpinDrink.png", "PushpinFuel.png", "PushpinHouse.png", "PushpinRestaurant.png", "PushpinShop.png" };

var pushpins = from icon in pushpinIcons select new PushpinModel { Icon = new Uri("/Resources/Icons/Pushpins/" + icon, UriKind.Relative), TypeName = System.IO.Path.GetFileNameWithoutExtension(icon) };

_items = pushpins.ToList(); }}

10. Open MainPage.xaml.cs file. To center the popup at the exact touch location, find the CenterPushpinsPopup method located in the MainPage.xaml.cs file, and add logic to calculate the popup’s Canvas.Top value based on the size of the list box and the touch point.

C#

private void CenterPushpinsPopup(Point touchPoint){

Page | 25

©2011 Microsoft Corporation. All rights reserved.

Page 26: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Canvas.SetTop(PushpinPopup, touchPoint.Y - ListBoxPushpinCatalog.Height / 2);}

11. Now that the catalog is ready, let’s add logic to pick a pushpin and place it at the exact location. Register the ListBox.SelectionChanged event with the ListBoxPushpinCatalog_SelectionChanged event handler provided with the starter solution.

12. Add a new method named Clone to the PushpinModel class. This method should return a clone of the PushpinModel instance with a different geo location provided as parameter of type GeoCoordinate.

C#

public PushpinModel Clone(GeoCoordinate location){ return new PushpinModel { Location = location, TypeName = TypeName, Icon = Icon };}

13. In the MainPage.xaml.cs, find the CreateNewPushpin method. This method is called by the ListBoxPushpinCatalog_SelectionChanged located in the MainPage.cs. It has two parameters: the selected pushpin model and the exact touch point in view coordinates.Translate the touch point to geo coordinates using the Map.TryViewportPointToLocation method.

C#

private void CreateNewPushpin(object selectedItem, Point point){ GeoCoordinate location; Map.TryViewportPointToLocation(point, out location);}

14. Now that you’ve got the exact geo coordinate for the pushpin, clone the selected pushpin with the new coordinate, and add the clone to the Pushpins collection. This will generate a new pushpin on the correct geo location on the map.

C#

private void CreateNewPushpin(object selectedItem, Point point){

Page | 26

©2011 Microsoft Corporation. All rights reserved.

Page 27: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

GeoCoordinate location; Map.TryViewportPointToLocation(point, out location); var pushpinPrototype = selectedItem as PushpinModel; var pushpin = pushpinPrototype.Clone(location); Pushpins.Add(pushpin);}

15. Open the file DefaultStyles.xaml under Resources\Styles and add the following code as a resource to resource dictionary.

XAML

<ResourceDictionary ... xmlns:converters="clr-namespace:UsingBingMaps.Converters">

<converters:PushpinTypeBrushConverter x:Key="PushpinTypeBrushConverter" /></ResourceDictionary>

16. To center the map on a pushpin while touching it, register the Pushpin.MouseLeftButtonUp event in the MainPage.xaml file. Since the Pushpin is defined by a DataTemplate located directly inside MainPage.xaml, you can simply register the event handler over there. Otherwise you can use an Attached Behavior to activate a command. In the pushpin DataTemplate, register to the Pushpin.MouseLeftButtonUp event.

17. Open the file name MainPage.xaml.cs and the following code. It handles the event by setting the MainPage.Center property with the pushpin’s Location property. You can extract the pushpin object from the event handler sender argument.

C#

private void Pushpin_MouseLeftButtonUp(object sender, MouseButtonEventArgs e){ var pushpin = sender as Pushpin; Center = pushpin.Location;}

Page | 27

©2011 Microsoft Corporation. All rights reserved.

Page 28: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

18. To test the results, press F5, go to the default location, click and hold a position on the map then select a pushpin from the list. The pushpin you’ve selected should be added to the map. Repeat this behavior for adding more pushpins. Click on any pushpin to center the map on it.

Figure 11Pushpin selection

This concludes the exercise.

Note: The complete solution for this exercise is provided at the following location: Source\Ex2-HandlingPushpins\End.

Page | 28

©2011 Microsoft Corporation. All rights reserved.

Page 29: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Exercise 3: Calculating a Route

In this exercise we will:

Create a map route layer Use Bing services to calculate to and from routes Display calculated route itineraries

We will use the Microsoft Visual Studio 2010 Express for Windows Phone development environment, and will deploy to the Windows Phone Emulator for debugging. The solution we will be working with is based upon the previous exercise.

Task 1 – Adding a Route to the Map

In this task you’ll work with Bing Maps SOAP services to calculate a route from point A to point B, and then you’ll create a route layer for rendering the calculated route. As part of the route rendering, you’ll also render route itineraries provided by the Bing Maps services.

In this task you’ll use the following services:

Geocode Service – to match addresses, places, and geographic entities to latitude and longitude coordinates on the map, as well as return location information for a specified latitude and longitude coordinate

Route Service – to generate routes and driving directions based on locations or waypoints, for example, directions that include traffic warnings and route hints between multiple locations, and directions from all major roads to a destination (1-click directions, also referred to as a "party map")

Search Service – to parse a search query that contains a location or keyword (or both) and return search result

1. Open the starter solution located in the Source\Ex3-RouteCalculation\Begin folder.

Note: You should set the Bing Maps application Id in the App class with your private key created in the previous exercise.

2. Add a reference to the Bing Maps Geocode service, right click on the project references, and select “Add Service Reference…”. Paste the following service address into the opened dialog, and click Go: http://dev.virtualearth.net/webservices/v1/geocodeservice/geocodeservice.svc

3. In the “Namespace” field, make sure that you enter Bing.Geocode and then click OK.

Note: If you have problems generating the data from the service, please make sure that you are currently connected to the Internet. Try to paste the service address into the web browser;

Page | 29

©2011 Microsoft Corporation. All rights reserved.

Page 30: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

you should get a service test page. If you have a connection, try to run Visual Studio 2010 again as Administrator (right click on Visual Studio 2010 icon on start menu, select “Run as administrator”), then try again.

4. Add reference to the Bing Maps Route service, right-click the project references, and select “Add Service Reference…”. Paste the following service address into the opened dialog, and click Go: http://dev.virtualearth.net/webservices/v1/routeservice/routeservice.svc . In the “Namespace” field, make sure that you enter Bing.Route and then click OK.

5. Add a reference to the Bing Maps Search service, right-click the project references, and select “Add Service Reference…”. Paste the following service address into the opened dialog, and click Go: http://dev.virtualearth.net/webservices/v1/searchservice/searchservice.svc . In the “Namespace” field, make sure that you enter Bing.Search and then click OK.

6. Open the ServiceReferences.ClientConfig configuration file that was automatically created as a project item and delete all CustomBinding related entries. In this lab we will use only the basic http bindings. You should have a file that looks like this:

XAML

<configuration> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IGeocodeService" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"> <security mode="None" /> </binding> <binding name="BasicHttpBinding_IRouteService" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"> <security mode="None" /> </binding> <binding name="BasicHttpBinding_ISearchService" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"> <security mode="None" /> </binding> </basicHttpBinding> </bindings> <client> <endpoint address="http://dev.virtualearth.net/webservices/v1/geocodeservice/GeocodeService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IGeocodeService"

Page | 30

©2011 Microsoft Corporation. All rights reserved.

Page 31: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

contract="Bing.Geocode.IGeocodeService" name="BasicHttpBinding_IGeocodeService" /> <endpoint address="http://dev.virtualearth.net/webservices/v1/routeservice/routeservice.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IRouteService" contract="Bing.Route.IRouteService" name="BasicHttpBinding_IRouteService" /> <endpoint address="http://dev.virtualearth.net/webservices/v1/searchservice/searchservice.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISearchService" contract="Bing.Search.ISearchService" name="BasicHttpBinding_ISearchService" /> </client> </system.serviceModel></configuration>

Note: You’ve now added three Bing Maps services. Next you’ll add a helper class that uses these services to wrap part of the asynchronous calls for calculating a route.

7. Pay attention to the files under Helpers project: RouteCalculator.cs, RoutingState.cs, RouteCalculationError.cs. These files will help you calculate a route using the Bing Maps Services you’ve added. The RouteCalculator class exposes one public method called CalculateAsync and one public event called Error. To calculate a route all you have to do is to initialize a new instance of the RouteCalculator type with the following parameter: Map credentials, To string, From string, UI dispatcher, and a delegate that will be called on the UI thread when calculation is done. If an error occurs, the Error event is raised on the UI thread. This is why you must pass the UI dispatcher.

8. In the RouteModel.cs file under Models folder, create a constructor with one collection parameter of type Microsoft.Phone.Controls.Maps.Platform.Location. Use it to initialize the internal collection. Location has an implicit cast to the GeoCoordinate type.

C#

public class RouteModel{ private readonly LocationCollection _locations;

public ICollection<GeoCoordinate> Locations { get { return _locations; } }

Page | 31

©2011 Microsoft Corporation. All rights reserved.

Page 32: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

public RouteModel(ICollection<Location> locations) { _locations = new LocationCollection(); foreach (Location location in locations) { _locations.Add(location); } }}

9. In the MainPage.xaml.cs, add a new ObservableCollection<RouteModel> and expose it with a public property called Routes. This collection holds the calculated route and will be bound with the route layer.

C#

private readonly ObservableCollection<RouteModel> _routes = new ObservableCollection<RouteModel>();

public ObservableCollection<RouteModel> Routes{ get { return _routes; }}

10. To calculate a route asynchronously, create an instance of RouteCalculator inside CalculateRoute method. So far you should have all the required parameters as properties of the MainPage class, except for the last one which will be an empty lambda expression with a single ‘result’ parameter.

C#

try{ var routeCalculator = new RouteCalculator( CredentialsProvider, To, From, Dispatcher, result => {

});}…

Page | 32

©2011 Microsoft Corporation. All rights reserved.

Page 33: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

11. Register the RouteCalculator.Error event by displaying an error message to the user and then call the RouteCalculator.CalculateAsync method to start the route calculation.

C#

try{ var routeCalculator = new RouteCalculator( CredentialsProvider, To, From, Dispatcher, result => {

});

// Display an error message in case of fault. routeCalculator.Error += r => MessageBox.Show(r.Reason);

// Start the route calculation asynchronously. routeCalculator.CalculateAsync();}…

12. When the route calculation is finished, the lambda expression should be invoked. Inside the lambda expression, clear the Route collection. For the simplicity, you’ll have only one route at a time.

C#

result =>{ Routes.Clear();};

13. Below, create a new RouteModel instance based on route calculator parameter (result.Result.RoutePath.Points), and add the new route to the route collection.

C#

var routeModel = new RouteModel(result.Result.RoutePath.Points);Routes.Add(routeModel);

14. Then, center the map on the new route, by calling Map.SetView, and passing it a LocationRect instance which can be calculated using the LocationRect.CreateLocationRect static helper method.

Page | 33

©2011 Microsoft Corporation. All rights reserved.

Page 34: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

C#

var viewRect = LocationRect.CreateLocationRect(routeModel.Locations);Map.SetView(viewRect);

15. To create a route layer, add another MapItemsControl to the map control just before the pushpins layer, and bind it to the Routes property.

XAML

<my:MapItemsControl ItemsSource="{Binding Routes}"><my:MapItemsControl.ItemTemplate>

<DataTemplate></DataTemplate>

</my:MapItemsControl.ItemTemplate></my:MapItemsControl>

16. To draw the route as a single line on the map, set the MapItemsControl.ItemTemplate with a data template that contains a single MapPolyline instance.

XAML

<my:MapItemsControl.ItemTemplate> <DataTemplate> <my:MapPolyline Stroke="#FF2C76B7" Opacity="0.85" StrokeThickness="6" /> </DataTemplate></my:MapItemsControl.ItemTemplate>

17. Bind the MapPolyline instance with the RouteModel.Locations property.

XAML

<my:MapPolyline Stroke="#FF2C76B7" Opacity="0.85" StrokeThickness="6" Locations="{Binding Locations}" />

18. To test the application:

◦ Press F5 and then click on route icon on the application bar (the upward-facing arrow).The route view should slide down from the top.

◦ Write a valid address in the From and To fields. For example: “Microsoft Building 1, WA,” “Microsoft Building 9, WA.”

Page | 34

©2011 Microsoft Corporation. All rights reserved.

Page 35: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

◦ Click the search icon. This should calculate the route and you should see it on the map. If an error occurs, you should see an error message.

Figure 12Calculating a route

Task 2 – Displaying Route Itineraries

The Bing route service supplies additional data with the route data, namely, the route itineraries data. By using the itineraries data you can display the exact directions of how to walk or drive from point A to point B on the route. In this task you’ll create a directions list based on these itineraries.

1. In the MainPage.xaml.cs, add a new collection of type ItineraryItem, and expose it as public property called Itineraries. This type was auto generated as part of the Bing Route service data contracts. You’ll use this class to encapsulate the itineraries collection provided with the route.

C#

Page | 35

©2011 Microsoft Corporation. All rights reserved.

Page 36: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

private readonly ObservableCollection<ItineraryItem> _itineraries = new ObservableCollection<ItineraryItem>();

public ObservableCollection<ItineraryItem> Itineraries{ get { return _itineraries; }}

2. Find the CalculateRoute method and clear both the Routes collection and the Itineraries collection. Since you’re displaying only one route at a time you’ll provide the itineraries of that active route.

C#

result =>{ Routes.Clear();

Itineraries.Clear();

...}

3. After adding the new route to the collection of routes, add all the itineraries provided by result.Result.Legs[0] right.

C#

var routeModel = new RouteModel(result.Result.RoutePath.Points);Routes.Add(routeModel);

foreach (var itineraryItem in result.Result.Legs[0].Itinerary){ Itineraries.Add(itineraryItem);}

4. In the MainPage.xaml, use the MapItemsControl to add a new layer for the itineraries, right below the routed layer, and bind it with the Itineraries collection.

XAML

<my:MapItemsControl ItemsSource="{Binding Itineraries}">

</my:MapItemsControl>

Page | 36

©2011 Microsoft Corporation. All rights reserved.

Page 37: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

5. To display each Itinerary as a custom pushpin, set the MapItemsControl.ItemTemplate with a new data template that contains a single pushpin.

XAML

<my:MapItemsControl ItemsSource="{Binding Itineraries}"> <my:MapItemsControl.ItemTemplate> <DataTemplate> <my:Pushpin /> </DataTemplate> </my:MapItemsControl.ItemTemplate></my:MapItemsControl>

6. Bind the pushpin with the ItineraryItem.Location property.

XAML

<my:Pushpin Location="{Binding Location}" />

7. Create an instance of the value converter inside the DefaultStyles.xaml resource dictionary located in the Resources\Styles folder.

XAML

<ResourceDictionary ... xmlns:converters="clr-namespace:UsingBingMaps.Converters" mc:Ignorable="d">

<converters:LocationGeoCoordinateConverter x:Key="LocationGeoCoordinateConverter" />...</ResourceDictionary>

8. Use the converter inside the binding extension.

XAML

<my:Pushpin Location="{Binding Location, Converter={StaticResource LocationGeoCoordinateConverter}}" />

9. Create a style for displaying the itinerary pushpin as a rounded shape and place it inside the DefaultStyle.xaml resource dictionary located in the Resources\Styles folder.

XAML

<Style x:Key="MapPoint" TargetType="Ellipse">

Page | 37

©2011 Microsoft Corporation. All rights reserved.

Page 38: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

<Setter Property="Width" Value="18"/> <Setter Property="Height" Value="18"/> <Setter Property="Fill" Value="#FF003664"/> <Setter Property="Stroke" Value="AliceBlue"/></Style>

<Style x:Key="ItineraryPushpinStyle" TargetType="m:Pushpin"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="m:Pushpin"> <Grid Height="20" Width="20"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="VisualStateGroup"> <VisualStateGroup.Transitions> <VisualTransition GeneratedDuration="0:0:0.1"> <VisualTransition.GeneratedEasingFunction> <PowerEase EasingMode="EaseIn"/> </VisualTransition.GeneratedEasingFunction> </VisualTransition> <VisualTransition GeneratedDuration="0:0:0.1" To="Selected"> <VisualTransition.GeneratedEasingFunction> <PowerEase EasingMode="EaseIn"/> </VisualTransition.GeneratedEasingFunction> </VisualTransition> </VisualStateGroup.Transitions> <VisualState x:Name="UnSelected"/> <VisualState x:Name="Selected"> <Storyboard> <ColorAnimation Duration="0" To="White" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="ellipse" d:IsOptimized="True"/> <DoubleAnimation Duration="0" To="1.3" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleX)" Storyboard.TargetName="ellipse" d:IsOptimized="True"/> <DoubleAnimation Duration="0" To="1.3" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleY)" Storyboard.TargetName="ellipse" d:IsOptimized="True"/>

Page | 38

©2011 Microsoft Corporation. All rights reserved.

Page 39: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

<ColorAnimation Duration="0" To="#FFF08609" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="ellipse_Center" d:IsOptimized="True"/> <DoubleAnimation Duration="0" To="1.5" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleX)" Storyboard.TargetName="ellipse_Center" d:IsOptimized="True"/> <DoubleAnimation Duration="0" To="1.5" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleY)" Storyboard.TargetName="ellipse_Center" d:IsOptimized="True"/> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Ellipse x:Name="ellipse" Style="{StaticResource MapPoint}" Width="20" Height="20" RenderTransformOrigin="0.5,0.5" Fill="White" Stroke="#FF2C76B7" StrokeThickness="3" > <Ellipse.RenderTransform> <CompositeTransform/> </Ellipse.RenderTransform> </Ellipse> <Ellipse x:Name="ellipse_Center" Style="{StaticResource MapPoint}" Width="8" Height="8" RenderTransformOrigin="0.5,0.5" Fill="Black" Stroke="{x:Null}" StrokeThickness="2" > <Ellipse.RenderTransform> <CompositeTransform/> </Ellipse.RenderTransform> </Ellipse> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>

10. Change the pushpin’s style to the new style you’ve just created.

XAML

<my:Pushpin Location="{Binding Location, Converter={StaticResource LocationGeoCoordinateConverter}}" Style="{StaticResource ItineraryPushpinStyle}" />

Page | 39

©2011 Microsoft Corporation. All rights reserved.

Page 40: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

11. In the DefaultStyles.xaml, add an instance of the converter you’ve created.

XAML

<ResourceDictionary ... xmlns:converters="clr-namespace:UsingBingMaps.Converters" ...>

<converters:ItineraryTextConverter x:Key="ItineraryTextConverter" /> ...</ResourceDictionary>

12. To test the results, press F5 and calculate a valid route.

Figure 13Route with Itineraries

Page | 40

©2011 Microsoft Corporation. All rights reserved.

Page 41: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

13. To display the itinerary view right after a route was found, in the MainPage.xaml.cs search the HasDirections property and return true if the Itinerary collection is not empty.

C#

public bool HasDirections{ get { return Itineraries.Count > 0; }}

14. In the CalculateRoute method, call the ShowDirectionsView inside the lambda body, right after setting the map view.

C#

// Set the map to center on the new route.var viewRect = LocationRect.CreateLocationRect(routeModel.Locations);Map.SetView(viewRect);

ShowDirectionsView();

15. To simplify testing, search for the InitializeDefaults, and set the following defaults:

C#

private void InitializeDefaults(){ Zoom = DefaultZoomLevel; Center = DefaultLocation; From = "Microsoft Building 1, WA"; To = "Microsoft Building 9, WA";}

Page | 41

©2011 Microsoft Corporation. All rights reserved.

Page 42: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

16. To test the final application, press F5 and search for a valid route. The directions view should pop up automatically.

Figure 14Bing Maps Final

This concludes the exercise and the lab.

Note: The complete solution for this exercise is provided at the following location: Source\Ex3-RouteCalculation\End.

Page | 42

©2011 Microsoft Corporation. All rights reserved.

Page 43: Using Bing Mapsaz12722.vo.msecnd.net/.../UsingBingMaps.docx · Web viewThis lab walks you through the steps required for using the Bing Maps Silverlight Control for Windows Phone,

Summary

During this lab you’ve learned about the Bing Silverlight Map Control for Windows Phone 7 platform. You’ve created a new account for accessing Bing Maps SOAP Services and created a private key for your Windows Phone Bing Maps application. You’ve learned about map layers, pushpins, and route calculations. You’ve created data models related to the map and bound them to different UI parts. You’ve designed styles and data templates for different parts of the map and data related to the map.

Page | 43

©2011 Microsoft Corporation. All rights reserved.