The products listed above, and their associated names, icons and logos, are the intellectual property of Microsoft Corporation.
Getting Started with Virtual Earth Silverlight Map Control

Getting Started with the Virtual Earth Silverlight Map Control

 The Virtual Earth Silverlight Map Control combines Virtual Earth mapping functionality with a rich graphical framework to support .NET development in the browser. It enables developers to embed and extend Virtual Earth functionality. The ability to combine data with geographical context is becoming increasingly more significant to companies and users.

The Virtual Earth Silverlight Map Control Interactive SDK contains samples demonstrating the functionality available to the control such as layering elements on the map, smoother tiling transitions, improved events and customizable behavior, and integration with Web Services to perform geocoding (latitude/longitude conversions).

This paper aims to familiarize developers with the key features of the Silverlight version of the Virtual Earth Map Control including the following:

·         Improved map rendering: Panning and zooming now uses blending to transition between tiles, which is a significant enhancement when compared to the AJAX map control.

·         Superior graphics framework: Support for WPF animations and transformations of graphics and images.

·         Utilize existing .NET skills: The Silverlight libraries are a subset of the .NET Framework 3.5. Visual Studio can be used to build the applications. Expression Blend can be used to build the user interface and graphical components.

·         Creating a consistent user experience in the browser: Available for users with Silverlight 2.0 installed. Supported browsers include Internet Explorer, Firefox and Safari.

Contents

Building a Virtual Earth Silverlight Map Control Sample

Getting Started

Adding a Pushpin to the Map

Adding Pushpin Animation

Displaying Latitude and Longitude Values on the Map

Adding a Map Sizing Slider

Summary

Building a Virtual Earth Silverlight Map Control Sample

Follow the steps through this section to learn how to create a new Virtual Earth Silverlight sample. Walk through getting started with the map control, adding a pushpin to the map, attaching a hover-over animation effect to the pushpin, and working with latitude and longitude information.

Getting Started

Begin by downloading the Virtual Earth Silverlight Map Control and running the installer from http://www.connect.microsoft.com. This will install the required assemblies and an Interactive SDK demonstrating the features available. This guide uses Visual Studio 2008 to build the application.

Create a new Silverlight project in Visual Studio 2008 and add a reference to Microsoft.VirtualEarth.MapControl.dll which can now be found in C:\Program Files\Microsoft Virtual Earth Silverlight Map Control\CTP\Libraries. This guide will modify the Page.xaml and Page.xaml.cs files to implement the control.

The next step is to add the Silverlight control to the map. Modify the UserControl element at the beginning of the Page.xaml file to match the following code snippet. This adds a reference to the Virtual Earth Silverlight Map Control namespace and changes the dimensions of the user control.

<UserControl x:Class="VirtualEarthDemo.Page"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   xmlns:VirtualEarth="clr-namespace:Microsoft.VirtualEarth.MapControl;assembly=Microsoft.VirtualEarth.MapControl"

Width="700" Height="400">

Next, the map code should be inserted within the Grid element. Rather than drawing graphics elements based on screen position, the MapLayer element allows graphics to be added with latitude and longitude values specified by the developer. The map then handles positioning the graphics elements onscreen.

<Grid x:Name="LayoutRoot" Background="White">

<Grid.ColumnDefinitions>

            <ColumnDefinition Width="500"></ColumnDefinition>

            <ColumnDefinition Width="200"></ColumnDefinition>

        </Grid.ColumnDefinitions>

 

        <Grid.RowDefinitions>

            <RowDefinition Height="180"></RowDefinition>

            <RowDefinition Height="40"></RowDefinition>

            <RowDefinition Height="180"></RowDefinition>

        </Grid.RowDefinitions>

<VirtualEarth:Map x:Name="MyMap" Grid.Column="0" Grid.Row="0" Grid.RowSpan="3" Height="400" Width="500" HorizontalAlignment="Left" VerticalAlignment="Top" MouseClick="MyMap_MouseClick">

<VirtualEarth:Map.Children>

      <VirtualEarth:MapLayer x:Name="PushpinLayer">

</VirtualEarth:MapLayer>

</VirtualEarth:Map.Children>

</VirtualEarth:Map>

</Grid>

Now open the Page.xaml.cs file. Add the following using statement to the top of the page.

using Microsoft.VirtualEarth.MapControl;

using System.Windows.Media.Imaging;

Add the following snippet within the Page class.

private void MyMap_MouseClick(object sender, MapMouseEventArgs e)

{

// will add code later

}

Press F5 to run your project, the following image should appear.

 

 

Now that you have created a working map with the Virtual Earth Silverlight Map Control, take a moment to experiment with the functions, such as panning and zooming.

Adding a Pushpin to the Map

Bring additional functionality to the map by facilitating the creation of interactive pushpins. You can build this option easily with the Virtual Earth Silverlight Map Control.

To add a basic pushpin, paste the following code into your project on the Page.xaml.cs file. Make sure you have a small image in your project that you can use in place of “house.png” used below as the image for the pushpin. Using XAML to render the pushpin on the map enables developers to build animations and effects into the pushpin above and beyond what is possible with JavaScript and CSS.

private void AddPushpin(double latitude, double longitude, double size)

{

// pushpin image

       Image i = new Image();

       i.Source = new BitmapImage(new Uri("house.png", UriKind.Relative));

       i.Width = size;

       i.Height = size;

       i.MouseEnter += new MouseEventHandler(i_MouseEnter);

       i.MouseLeave += new MouseEventHandler(i_MouseLeave);

 

// set Map position before adding to Map Control

      i.SetValue(MapLayer.MapPositionProperty, new Microsoft.VirtualEarth.MapControl.Location(latitude, longitude));

      i.SetValue(MapLayer.MapPositionMethodProperty, PositionMethod.Center);

 

       (MyMap.FindName("PushpinLayer") as MapLayer).AddChild(i);

}

 

private void i_MouseLeave(object sender, MouseEventArgs e)

{

// will add code later

}

 

private void i_MouseEnter(object sender, MouseEventArgs e)

{

// will add code later

}

Next, update the Page() constructor method to create the sample pushpin.

public Page()

{

InitializeComponent();

 

       // hard-coded latitude, longitude and image size

      AddPushpin(51.5, 0, 40);

}

Run the project to see the pushpin. It should be located on the map near London.

 

 

Adding Pushpin Animation

As Pushpins are now simply XAML elements you can use animation and transform effects to bring magic to an application. In this section, learn how to add animation to a sample so that the pushpin appears to grow when the mouse hovers over it.

First, update the AddPushpin method on the Page.xaml.cs file to include the following two highlighted lines.

private void AddPushpin(double latitude, double longitude, double size)

{

       ...

 

// attach event handlers

i.MouseEnter += new MouseEventHandler(i_MouseEnter);

i.MouseLeave += new MouseEventHandler(i_MouseLeave);

 

(MyMap.FindName("PushpinLayer") as MapLayer).AddChild(c);

}

 

Next, update the image handler events as shown here. When finished, the code should appear as follows.

private void i_MouseLeave(object sender, MouseEventArgs e)

{

Image i = (Image)sender;

 

// remove transform when mouse leaves image

i.RenderTransform = null;

}

 

private void i_MouseEnter(object sender, MouseEventArgs e)

{

Image i = (Image)sender;

 

// scaling will shrink (less than 1) or enlarge

// (greater than 1) source element

ScaleTransform st = new ScaleTransform();

st.ScaleX = 1.4;

st.ScaleY = 1.4;

 

// set center of scaling to center of image

st.CenterX = i.Height / 2;

st.CenterY = i.Height / 2;

 

i.RenderTransform = st;

}

 

Finally, press F5 to run the project. Move your mouse over your pushpin image to see the pushpin animation.

 

 

Displaying Latitude and Longitude Values on the Map

This section explains how to obtain latitude and longitude values from a map event and create your own pushpin.

Add the following code to the MapControl element (within the Grid) on the Page.xaml page to enable users to interact with the map and add their own pushpins by clicking on the map at the desired location. This form consists of Latitude, Longitude and Label inputs:

<StackPanel Orientation="Vertical" Grid.Column="1" Grid.Row="2" Width="200">

<TextBlock FontWeight="Bold">Add Location</TextBlock>

<StackPanel Orientation="Horizontal">

<TextBlock Width="75" HorizontalAlignment="Center" VerticalAlignment="Center">Latitude:</TextBlock>

<TextBox x:Name="txtLatitude" Width="125"></TextBox>

</StackPanel>

<StackPanel Orientation="Horizontal" >

<TextBlock Width="75" VerticalAlignment="Center">Longitude:</TextBlock>

<TextBox x:Name="txtLongitude" Width="125"></TextBox>

</StackPanel>

<StackPanel Orientation="Horizontal" >

<TextBlock Width="75" VerticalAlignment="Center">Label:</TextBlock>

<TextBox x:Name="txtLabel" Width="125"></TextBox>

</StackPanel>

 

<Button x:Name="btnAddNew" Content="Add" HorizontalAlignment="Left" Width="50" Click="btnAddNew_Click"></Button>

<!-- Placeholder for Slider -->

</StackPanel>

 

Since Silverlight elements are being used instead of ASP.NET or HTML elements (as is in the AJAX map control), databinding options are available to make the code simpler. Add the following XAML code, after the StackPanel code inserted previously. This XAML will display a list of locations and options to show or hide pushpins on the map.

<StackPanel Orientation="Vertical" Grid.Column="1" Grid.Row="0" Grid.RowSpan="3" Width="200">

<TextBlock FontWeight="Bold">Locations</TextBlock>

<ListBox x:Name="Locations" Height="150"></ListBox>

<StackPanel Orientation="Horizontal" Grid.Column="1" HorizontalAlignment="Right">

<Button x:Name="btnShow" Content="Show" Width="70" Click="btnShow_Click"></Button>

<Button x:Name="btnHide" Content="Hide" Width="70" Click="btnHide_Click"></Button>

</StackPanel>

</StackPanel>

 

The next snippet of code creates a list of location names with the related latitude and longitude values. This information is stored and used when rendering the pushpins on the map. Add this to the Page.xaml.cs file within the Page class.

private void SetupLocations()

{

Locations.Items.Clear();

      Locations.Items.Add(new ListBoxItem() { Content = "Adelaide", Tag = new Microsoft.VirtualEarth.MapControl.Location(-34.9, 138.6) });

      Locations.Items.Add(new ListBoxItem() { Content = "Sydney", Tag = new Microsoft.VirtualEarth.MapControl.Location(-33.85, 151.2) });

      Locations.Items.Add(new ListBoxItem() { Content = "Melbourne", Tag = new Microsoft.VirtualEarth.MapControl.Location(-37.73, 145.00) });

      Locations.Items.Add(new ListBoxItem() { Content = "Seattle", Tag = new Microsoft.VirtualEarth.MapControl.Location(47.54, -122.33) });

}

 

Modify the Page constructor to match this code snippet.

public Page()

{

InitializeComponent();

SetupLocations();

}

Add the following code to the MouseClick handler capture the click position on the MapControl and identify corresponding latitude and longitude values. These values are inserted into text boxes on the form.

private void MyMap_MouseClick(object sender, MapMouseEventArgs e)

{

Point clickLocation = e.ViewportPoint;

Location loc = MyMap.ViewportPointToLocation(clickLocation, MyMap.View);

txtLatitude.Text = loc.Latitude.ToString();

txtLongitude.Text = loc.Longitude.ToString();

if (string.IsNullOrEmpty(txtLabel.Text))

{

txtLabel.Text = "Mouse Click";

}

}

 

Add this code to insert a new location to the list, using values entered on the form.

private void btnAddNew_Click(object sender, RoutedEventArgs e)

{

if (!string.IsNullOrEmpty(txtLatitude.Text) && !string.IsNullOrEmpty(txtLongitude.Text))

{

 

// ensure inputs are valid numbers

double latitude, longitude;

bool latValid = Double.TryParse(txtLatitude.Text, out latitude);

bool longValid = Double.TryParse(txtLongitude.Text, out longitude);

 

if (latValid && longValid)

{

// add new item to listbox

              ListBoxItem item = new ListBoxItem();

item.Content = txtLabel.Text;

item.Tag = new Location(latitude, longitude);

Locations.Items.Add(item);

}

 

// clear current values

txtLabel.Text = string.Empty;

txtLatitude.Text = string.Empty;

txtLongitude.Text = string.Empty;

}

}

 

The next section of code is used to display pushpins to the map for each location. The last line of the method will move the map to center on the final pushpin. In this case it will focus on the last location, or, if none are in the ListBox, the intersection of the Equator and the Prime Meridian.

private void btnShow_Click(object sender, RoutedEventArgs e)

{

Location location = new Location(0, 0);

foreach (ListBoxItem item in Locations.Items)

{

location = (Location)item.Tag;

AddPushpin(location.Latitude, location.Longitude, 40);

}

 

       // move map to last location

MyMap.View = new MapViewSpecification(location, 3);

}

 

Finally, this code is used to clear all pushpins from the map. The ListBox items are not modified.

private void btnHide_Click(object sender, RoutedEventArgs e)

{

PushpinLayer.Children.Clear();

}

 

Press F5 to build the project, and something similar to the following image will should appear. Click the different city names and see what happens as you take note of the speed and quality of the transformations.

 

 

Adding a Map Sizing Slider

At times it is convenient or desirable for the user to be able to resize a map on the page – or to resize the map based on space available in the browser window. The simple code provided in this section will show how to add a size slider to the sample. Find the placeholder for the Slider on the Page.xaml file and add the following XAML statements next to it.

<!-- Placeholder for Slider -->

 

<TextBlock TextWrapping="Wrap" FontWeight="Bold" >Resize Map</TextBlock>

<Slider x:Name="MapSize" Width="180" Minimum="0" Maximum="500" ValueChanged="Slider_ValueChanged"></Slider>

 

In the Page.xaml.cs, you will need to set an initial size for the slider and map. Do this by adding the following code in the Page() constructor.

public Page()

{

...

// set initial slider value

       MapSize.Value = 400;

// set map size

       ResizeMap(MapSize.Value);

}

Next add the following code to the Page class to resize the map control.

private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)

{

ResizeMap(e.NewValue);

}

 

private void ResizeMap(double newSize)

{

MyMap.Width = newSize;

       // not square map – this is the ratio of height:width

       MyMap.Height = newSize * 0.8;

}

Press F5 to build the project and use the slider to resize the map. Take note of how the map adjusts as the available space expands and shrinks.

 

Summary

As worldwide communication and travel increase, geography is becoming more and more relevant. Not only do people need to know the locations of friends and family and where to purchase products, but they are also seeking a geographical perspective on what they see in the media and advertising. They want to know where to find your corporate office and sales territories, as well as distribution centers. For businesses, the ability to combine a geographical context with business can provide valuable insight into performance metrics and decision-making processes. Virtual Earth maps aren’t just for real estate and location search sites anymore, they are rapidly becoming an element seen on most websites. How can you make yours stand out?

The combination of Silverlight and Virtual Earth brings opportunities to expose innovative ideas that readily capture and keep an audience’s attention. The Virtual Earth Silverlight Map Control gives developers the freedom to create enhanced versions of Virtual Earth applications. Silverlight makes Virtual Earth zooming and panning appear almost seamless, and allows the simple integration of animation to enhance the experience of a web page and draw attention to key points as demonstrated by the dynamic pushpins and map sizing options displayed in the above sample.

As the examples in this paper show, the Virtual Earth Silverlight Map Control is easily accessed and applied. Take advantage of the freedom that Silverlight enables for web development while you use your creativity and imagination to build the types of applications that meet your development needs and push Virtual Earth to its limits.

Copyright 2009. Sponsored by nsquared.   |  Terms Of Use  |  Privacy Statement
Content on this site is generated from the developer community and shared freely for your enjoyment and benefit. This site is run independently of Microsoft and does not express Microsoft's views in any way.