Using Maps in your Windows Phone App

Exclusive offer: get 50% off this eBook here
Windows Phone 7.5: Building Location-aware Applications

Windows Phone 7.5: Building Location-aware Applications — Save 50%

Build your first Windows Phone application with Location and Maps with this book and ebook.

$11.99    $6.00
by Zeeshan Chawdhary | July 2012 | Enterprise Articles

Maps provide a great visual experience for location-based services. Maps are now a default feature on most smartphones as they provide a good graphical overview of information (usually geotagged data) around the user's location.

With custom pin markers and directions, maps also help users navigate to their destination easily. Most importantly maps give the user a feeling that "This place is around the next block, north from where I am standing," so decision-making happens quickly for the user.

In this article by Zeeshan Chawdhary, author of Windows Phone 7.5: Building Location-aware Applications we shall cover the following topics:

  • Understanding map geometry
  • Overview of Windows Bing Maps Silverlight Control
  • Using maps in your Windows Phone application – Hello Maps
  • Using pushpins with maps
  • Custom map pushpins
  • Handling pushpin events
  • Working with Bing Maps geocoding and reverse geocoding services
  • Overview of Launchers and Choosers
  • Using directions with Bing Maps directions task
  • Performing local searches with BingMapsTask

 

 

(For more resources on Windows Phone, see here.)

Understanding map geometry

Windows Phone 7.5 supports two methods of map display in your mobile app:

  • Bing Maps Silverlight Control for Windows Phone
  • Bing Maps task Launcher

 

Before we delve into the methods, actions, and tasks of the Windows Phone Bing Maps Silverlight Control or the Bing Maps task Launcher, it is a good idea to get acquainted with the background of map geometry and how it works for Bing Maps. If you have a background in Computer Science, then you would be aware of keywords such as projection, trajectory, coordinate systems, raster and scalable graphics. If you are not from a Computer Science background, then a basic understanding of the Bing Maps API can be found at http://msdn.microsoft.com/en-us/library/ff428643.aspx. This should be good to get you started with Bing Maps.

Bing Maps uses the Mercator projection model of converting the Earth's sphere into a corresponding flat surface, grid-based, parallel map. In such a projection the longitude lines are parallel, and hence the land mass further from the equator tends to be distorted. However, the Mercator projection works well for navigational purposes, and therefore, despite the drawbacks, it is still used today.

The Mercator projection offers two compelling advantages:

  • The map scale is constant around any position.
  • Mercator projection is a cylindrical projection. North and south are straight up and down, while west and east are always left and right respectively. (This helps in keeping track of your course in navigation.)

 

The following diagrams should give you a good idea about the Mercator projection:

 

Earth's surface as a sphere diagram courtesy Michael Pidwirny from http://www.eoearth.org/article/Maps and http://www.physicalgeography.net/fundamentals/2a.html.

Mercator projection of the Earth's surface diagram courtesy Michael Pidwirny from http://www.eoearth.org/article/Maps and http://www.physicalgeography.net/fundamentals/2a.html.

The world map is pre-rendered at many different levels of detail and cut into tiles for quick retrieval. When you zoom in or zoom out on your Bing Maps, it is nothing but loading different tiles at different levels. To read more about the Bing Maps Tile System please see the following MSDN link:

http://msdn.microsoft.com/en-us/library/bb259689.aspx

Overview of the Windows Phone Bing Maps Silverlight Control

The Bing Maps Silverlight Control for Windows Phone 7.5 is a port of the desktop version of the Silverlight Map Control, which provides full mapping capabilities on the Windows Phone 7.5 device. Before using the Bing Maps control you need to get an application key from Microsoft's Bing Maps portal at: https://www.bingmapsportal.com/.

The Microsoft.Phone.Controls.Maps namespace contains the classes of the Bing Maps Silverlight Control for Windows Phone. Let us quickly see an example of using maps in our WP7.5 app.

Using maps in your Windows Phone 7.5 app – Hello Maps

We will now create a new application titled HelloMaps that shows the Windows Phone Bing Maps Silverlight Control in action:

  1. Launch Microsoft Visual Studio 2010 Express for Windows Phone.
  2. Create a new Project from the File | New Project menu option and Name it HelloMaps.
  3. Add the Map control to your app by selecting it from the Toolbox. Change the Application Title to Hello Maps and the Page Title to Bing Maps. Your project should now look like the following screenshot:

  4. If you run the app now it will show the following output, as depicted in the next screenshot:
    Invalid Credentials. Sign up for a developer account at: http://www.microsoft.com/maps/developers

  5. This is because we have not signed up for a map key from https://www.bingmapsportal.com/. Let's do so.
  6. Visit https://www.bingmapsportal.com/ and sign up or log in with your Windows Live ID. Create your application and store the map key in a safe place.

  7. Now that we have our key, (for safety reason we assume xxxxxxxxxxxxxx as the key) let us initialize our Map control with the same.
  8. Notice the XAML tag <my:Map> when you added the Map control to your application. Add the key we got from step 7 by using the CredentialsProvider attribute of the Bing Maps Silverlight Control. Also change the name of the map to myMap.

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <my:Map Height="595"
    CredentialsProvider="xxxxxxxxxxxxxx"
    HorizontalAlignment="Left" Margin="6,6,0,0" Name="myMap"
    VerticalAlignment="Top" Width="444" />
    </Grid>

  9. Running the app in the emulator now will not show the Invalid Credentials message we saw earlier.
  10. Now let us make our application more exciting. We will add an Application Bar to our Hello Maps application that will allow us to choose the map mode: Road Mode or Aerial Mode.
  11. In your MainPage.xaml uncomment the following lines that add a default application bar to your application:

    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
    <shell:ApplicationBarIconButton
    IconUri="/Images/appbar_button1.png" Text="Button 1"/>
    <shell:ApplicationBarIconButton
    IconUri="/Images/appbar_button2.png" Text="Button 2"/>
    <shell:ApplicationBar.MenuItems>
    <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
    <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
    </shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

  12. Modify it to look like the following:

    <phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
    <shell:ApplicationBar.MenuItems>
    <shell:ApplicationBarMenuItem Text="Aerial Mode"/>
    <shell:ApplicationBarMenuItem Text="Road Mode"/>
    </shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>

  13. With your code editor open, go to the Aerial Mode Application Bar Menu Item and before the Text property enter Click="". IntelliSense will prompt you <New Event Handler> as shown in the following screenshot. Select it.

  14. Do the same for the other Application Bar Menu Item. Your code should now be as follows:

    <shell:ApplicationBarMenuItem
    Click="ApplicationBarMenuItem_Click" Text="Aerial Mode"/>
    <shell:ApplicationBarMenuItem
    Click="ApplicationBarMenuItem_Click_1" Text="Road Mode"/>

  15. Open your MainPage.xaml.cs file and you will find the two click event functions created automatically: ApplicationBarMenuItem_Click and ApplicationBarMenuItem_Click_1.
  16. As the first menu item is for Aerial Mode, we set the map mode to Aerial Mode by using the following code in the ApplicationBarMenuItem_Click function:

    private void ApplicationBarMenuItem_Click(object sender,
    EventArgs e)
    {
    myMap.Mode = new AerialMode();
    }

  17. Note the myMap variable was assigned to the Map control in step 8.
  18. Similarly we do the same for the ApplicationBarMenuItem_Click_1 function, however here we set the mode to Road by using the following code:

    private void ApplicationBarMenuItem_Click_1(object sender,
    EventArgs e)
    {
    myMap.Mode = newRoadMode();
    }

  19. Run the application in the emulator and click on the three dots you see on the lower right-hand side of your application footer. This invokes the Application Bar and your app screen should like the following screenshot:

  20. Select the aerial mode menu item and see your map change to Aerial Mode in real-time. You can switch back to Road Mode by selecting the road mode menu item again.

 

Windows Phone 7.5: Building Location-aware Applications Build your first Windows Phone application with Location and Maps with this book and ebook.
Published: July 2012
eBook Price: $11.99
Book Price: $19.99
See more
Select your format and quantity:

 

(For more resources on Windows Phone, see here.)

Using pushpins with maps

We have seen how to change map modes, however just a simple map without any focus does not make much sense, does it? So we move further and modify the HelloMaps example by using the Windows Phone Location Service to add a pushpin to the map – signifying the user's detected location.

The Pushpin class is part of the Microsoft.Phone.Controls.Maps namespace, with location as one of the properties. So let's use this property in our code and render a simple pushpin:

  1. We start by creating a new project titled HelloMaps-Pushpin.
  2. From our HelloMaps example, reintegrate the same UI, maps, and text labels, and from our Hello Location example, import the TextBlock named statusText. Your UI should now look like the following screenshot:

  3. Open MainPage.xaml.cs and copy over the location variable and methods from the Hello Location example. Add a variable in the global scope called zoomLevel that controls your map's zoom level.

    GeoCoordinateWatcher locationManager;
    double zoomLevel = 10.00;

  4. Now in your MainPage()constructor copy over the location manager code from the Hello Location example, and for your map, set ZoomBarVisibility to Visible. This property is from the Map class that allows the zoom in/zoom out control to be visible on the map. The following is your constructor code:

    public MainPage()
    {
    InitializeComponent();
    locationManager = new
    GeoCoordinateWatcher(GeoPositionAccuracy.High);
    locationManager.StatusChanged += new
    EventHandler<GeoPositionStatusChangedEventArgs>
    (locationManager_getStatus);
    locationManager.PositionChanged += new
    EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>
    (locationManager_getPosition);
    myMap.ZoomBarVisibility = Visibility.Visible;
    locationManager.Start();
    }

  5. The StatusChanged event handler locationManager_getStatus remains similar to the Hello Location example, however the PositionChanged event handler undergoes a few changes by adding a new pushpin at the detected location.
  6. We begin the PositionChanged event handler function by creating a new pushpin named myPin. The Location property of the Pushpin class is then used to transfer the hardware's detected location to the pushpin by the following lines of code:

    void locationManager_getPosition(object sender,
    GeoPositionChangedEventArgs<GeoCoordinate> newLoc)
    {
    Pushpin myPin = new Pushpin();
    myPin.Location = new
    GeoCoordinate(newLoc.Position.Location.Latitude,
    newLoc.Position.Location.Longitude);

  7. Now we add this pushpin to the map by using the Children collection of the Map class as:

    myMap.Children.Add(myPin);

  8. Lastly, we change the map's current view to the detected location to focus the map at that geocoordinate and specify a zoom level.

    myMap.SetView(new GeoCoordinate(newLoc.Position.Location.
    Latitude,newLoc.Position.Location.Longitude), zoomLevel);

  9. Don't forget to import the following Location and Mapsnamespaces in your C# code:

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

     

  10. Running the application in the emulator produces the following result:

  11. Now open up the Location simulator and select a few locations around Paris. Do it one at a time and see the real-time pushpin magic!!

Custom map pushpins

We created our own maps application and added a pushpin. Great! But does it look great? To be honest – no, the black pushpin icon is not fancy. In fact the pushpins in the Location simulator are better! (We hope Microsoft guys are reading this line.) We can, however, use the following code to add some content to the pushpin, but it still does not give us the "wow" look:

myPin.Content = newLoc.Position.Location.Latitude.ToString() +
", " +newLoc.Position.Location.Longitude.ToString();

 

Thankfully the Windows Phone Bing Maps Silverlight Control provides the ability to use our own icons for the pushpin. There are two ways to use custom map pushpins:

  • Using an image as the pushpin
  • Using your own pushpin style (in XAML)

 

The guys at http://365psd.com/ have some excellent and free map pushpin icons. You can find a few at http://365psd.com/?s=map. We use the one from Dennis Covent: http://365psd.com/day/2-302/ as the custom icon for our pushpin.

Using an image as the pushpin

Let us use the icon mentioned previously as an image for our pushpins:

  1. Open the HelloMaps-Pushpin example and navigate to the MainPage.xaml.cs file.
  2. Declare an object of type MapLayer in the global namespace.

    MapLayer myMapLayer;

  3. In the MainPage() constructor initialize the myMapLayer object and add it to the map as:

    myMapLayer = new MapLayer();
    myMap.Children.Add(myMapLayer);

  4. In your locationManager_getPosition function add the following lines of code and comment out the rest:

    void locationManager_getPosition(object sender,
    GeoPositionChangedEventArgs<GeoCoordinate> newLoc)
    {
    // Custom PushPin
    Image pushpinImage = new Image();
    pushpinImage.Source = new
    System.Windows.Media.Imaging.BitmapImage
    (newUri("myPushPin.png", UriKind.Relative));
    pushpinImage.Opacity = 0.7;
    pushpinImage.Stretch = System.Windows.Media.Stretch.None;
    PositionOrigin position = PositionOrigin.Center;
    myMapLayer.AddChild(pushpinImage,
    new GeoCoordinate(newLoc.Position.Location.Latitude,
    newLoc.Position.Location.Longitude), position);
    // End of Custom PushPin
    myMap.SetView(new GeoCoordinate
    (newLoc.Position.Location.Latitude,
    newLoc.Position.Location.Longitude), zoomLevel);
    }

  5. Do not forget to add the myPushPin.png image to your project.
  6. It adds pushpinImage to the myMapLayer object at the location detected, and adds our pushpin icon in at the center of the view.
  7. Run the application now to see the custom pushpin icons in action as shown in the following screenshot:

  8.  

Using your own pushpin style

We saw how to use the image as a layer instead of a pushpin. Some developers would not want to work with a pushpin in this way. The Image and Pushpin classes are quite different in their own sense, each having their own properties, methods, constructors, and events. So using a layer is not always equal to a pushpin implementation. So using a layer is not always equal to a pushpin implementation.

In such cases we define a new XAML style in App.xaml, the main class that calls MainPage.xaml within the <Application.Resources> </Application.Resources> tags:

  1. Open your project HelloMaps-Pushpin. Navigate to the App.xaml file and add the following style markup within the <Application.Resources> </Application.Resources> tags:

    <Style TargetType="m:Pushpin" x:Key="myPushpinStyle">
    <Setter Property="Template">
    <Setter.Value>
    <ControlTemplate TargetType="m:Pushpin">
    <Grid x:Name="ContentGrid">
    <Image Source="myPushPin.png" Stretch="None"/>
    </Grid>
    </ControlTemplate>
    </Setter.Value>
    </Setter>
    </Style>

  2. Now in your MainPage.xaml.cs file uncomment the default pushpin code that we commented earlier.

    // Standard Pushpin
    myPin.Content = newLoc.Position.Location.Latitude.ToString()
    + ", " +newLoc.Position.Location.Longitude.ToString();
    myPin.Style =
    (Style)(Application.Current.Resources["myPushpinStyle"]);
    myPin.Location = newGeoCoordinate
    (newLoc.Position.Location.Latitude,
    newLoc.Position.Location.Longitude);
    myMap.Children.Add(myPin);
    // End of Standard Pushpin

  3. Here we are using the style we defined in App.xaml and assigning it to our pushpin object.
  4. Running the app will result in an almost similar icon display as shown earlier, the only difference being the Opacity parameter set previously, which we haven't put in our style.

 

Handling pushpin events

Handling pushpin events is fairly simple. For example, to handle a simple mouse left-click event we use the MouseButtonEventHandler event handler as:

myPin.MouseLeftButtonUp += new
MouseButtonEventHandler(myPin_MouseLeftButtonUp);

 

Here myPin_MouseLeftButtonUp is our function that will execute when the event triggers. We declare this as a simple function that shows a message box alert.

void myPin_MouseLeftButtonUp(object sender,
MouseButtonEventArgs e)
{
Pushpin localPushPin = new Pushpin();
localPushPin = (Pushpin) sender;
MessageBox.Show("You are Here : " +
localPushPin.Location.Latitude + "," +
localPushPin.Location.Longitude);
}

 

The following screenshot shows how it will look in the emulator:

 

Working with Bing Maps geocoding and reverse geocoding services

The Bing Maps REST Services API provides API end points for forward geocoding (or just simple geocoding) as well as reverse geocoding. Static Maps API, Routing and Traffic APIs are supported as well. Refer to the following MSDN documentation for a complete look at the APIs:

http://msdn.microsoft.com/en-us/library/ff701722.aspx

In our previous example, we showed an alert when a user clicked or touched on a pushpin. The content of the alert was geocodes, however to make the app more informational and useful, we could use the reverse geocoding API from Bing Maps, and convert the geocodes to meaningful addresses. Here's how:

  1. We use the Find a Location by Point API endpoint from the Bing Maps REST Service at:
    http://msdn.microsoft.com/en-us/library/ff701710.aspx
  2. Import the following XML namespaces in your project so that we can parse the API response:

    using System.Xml;
    using System.Xml.Linq;

  3. In your global class namespace, create a new variable of type WebClient, which will be used to send the API request.

    WebClient myWebClient;

  4. Next, in your MainPage() constructor, initialize the myWebClient variable as:

    myWebClient = new WebClient();

  5. In our myPin_MouseLeftButtonUp event function, define a functioncallback for the myWebClient object and name it myWebClient_DownloadStringCompleted.
  6. Now create a Uri object that contains the API link for the Bing Maps reverse geocoding API endpoint and initiate the API request. Your code should now look as follows:

    void myPin_MouseLeftButtonUp(object sender,
    MouseButtonEventArgs e)
    {
    Pushpin localPushPin = new Pushpin();
    localPushPin = (Pushpin) sender;
    myWebClient.DownloadStringCompleted +=
    new DownloadStringCompletedEventHandler
    (myWebClient_DownloadStringCompleted);
    Uri uri = new Uri
    ("http://dev.virtualearth.net/REST/v1/Locations/" +
    localPushPin.Location.Latitude + ","
    +localPushPin.Location.Longitude+
    "?o=xml&key=xxxxxxxxxxxxxx");
    myWebClient.DownloadStringAsync(uri);
    }

  7. Note that xxxxxxxxxxxxxx is your Bing Maps key that we obtained from the Bing Maps App Portal.
  8. As the web client requests get completed, our predefined callback function myWebClient_DownloadStringCompleted is fired, where we parse the XML response, find the right tag, and display an alert to the user.

    private void myWebClient_DownloadStringCompleted(object sender,
    DownloadStringCompletedEventArgs e)
    {
    XElement xml = XElement.Parse(e.Result);
    XNamespace xmlNameSpace =
    "http://schemas.microsoft.com/search/local/ws/rest/v1";
    MessageBox.Show("You are Here : " +
    xml.Descendants(xmlNameSpace + "Name").First().Value);
    }

  9. We use the Element.Parse() method to parse the XML response from the Bing Maps API. Note the use of the XNamespace object to search through the XML response. The following screenshot shows a sample response:

  10. We used the <Name> tag from the response to display the address to the user.
  11. Running the app in the emulator produces the following result:

Windows Phone 7.5: Building Location-aware Applications Build your first Windows Phone application with Location and Maps with this book and ebook.
Published: July 2012
eBook Price: $11.99
Book Price: $19.99
See more
Select your format and quantity:

 

(For more resources on Windows Phone, see here.)

Launchers and Choosers – An Overview

Launchers and Choosers are some other exceptional fundamental concepts in Windows Phone 7.5. They allow application developers to access the address book, web browsers, maps, messaging, and camera support without writing much code. The idea here is not to import tons of libraries and reuse the same functionality, but to pass control to the right application (system application) to get the job done and come back to the main application with the result.

Launchers are a set of API tasks that allow the user to navigate to other parts of the Windows Phone experience to accomplish a certain goal. However Launchers return no control back to the user or the calling program. Some examples of Launchers are e-mail, marketplace, SMS, web browser, media player, and the Bing Maps task. A complete list of available Launchers is shown in the following table:

Launcher name

Launcher description

BingMapsDirectionsTask

Used for displaying directions from a starting location or to an end location.

BingMapsTask

Launches the Bing Maps application, could be used to fire predefined searches from within our app.

ConnectionSettingsTask

Adjust the device's network connection settings.

EmailComposeTask

Send e-mail from your application.

MarketplaceDetailTask

Loads the Marketplace details page for a specified application.

MarketplaceHubTask

Launches the Marketplace with the specified hub name. For example, music will launch the Marketplace with applications that cater to the music category.

MarketplaceReviewTask

Loads the Marketplace with the current application's review page.

MarketplaceSearchTask

Loads the Marketplace and populates it with the search results for the specified search keyword.

MediaPlayerLauncher

Launches the Media player.

PhoneCallTask

Allows the user to make a phone call from our application.

SearchTask

Performs a web search.

ShareLinkTask

Enables the user to share a link on the social network(s).

ShareStatusTask

Enables the user to share his status on the social network(s).

SmsComposeTask

Send an SMS message from our application.

WebBrowserTask

Launches the web browser with the specified URL.

Choosers are similar to Launchers, with the exception that Choosers return some data back to the calling application. Some examples would be contact selection, photo selection, or the device camera, where the application expects a selection result to do further processing.

A list of Choosers available in Windows Phone 7.5 is shown in the following table:

Chooser name

Chooser description

AddressChooserTask

Launches the address book and allows the user to choose a contact.

CameraCaptureTask

Captures an image from the camera and returns the same to our application.

EmailAddressChooserTask

Launches the address book and allows the user to choose a contact. The contact's e-mail field is returned to the application.

GameInviteTask

Invite players to a multiplayer Xbox LIVE game.

PhoneNumberChooserTask

Launches the address book and allows the user to choose a contact. The contact's phone number is returned to the application.

PhotoChooserTask

Select an existing photo from the phone.

SaveContactTask

Saves a contact from your application using the Contacts application.

SaveEmailAddressTask

Saves an e-mail address from your application using the Contacts application.

SavePhoneNumberTask

Saves a phone number from your application using the Contacts application.

SaveRingtoneTask

Save an audio file as a ringtone.

To use Launchers or Choosers, your application must import the Microsoft.Phone.Tasks namespace. To read more about Launchers see the MSDN documentation at http://msdn.microsoft.com/en-us/library/ff769550%28v=vs.92%29.aspx, and for Choosers see the MSDN documentation at http://msdn.microsoft.com/en-us/library/ff769543%28v=vs.92%29.aspx.

Using directions with Bing Maps directions task

We got acquainted with Launchers in our previous topic. Let us now look at BingMapsDirectionsTask, and use it to provide driving directions from within our application:

  1. Create a copy of our HelloMaps-Pushpin project and rename it HelloMaps-Directions.
  2. Open your MainPage.xaml.cs file and import the Microsoft.Phone.Tasks namespace into your project.

    using Microsoft.Phone.Tasks;

  3. Assuming the maps center as Redmond, we want to show driving directions to the nearby Mercer Island as depicted in the following screenshot:

  4. We begin by defining a variable myDrivingDirection of type BingMapsDirectionsTask as:

    BingMapsDirectionsTask myDrivingDirection;

  5. In our MainPage() constructor, we define the start and end points of our route. The start being some location near Redmond and end being Mercer Island.

    // Show driving directions to Mercer Island
    // Use "null" as the starting location to use your current
    // location as the starting point.
    myDrivingDirection = new BingMapsDirectionsTask();
    myDrivingDirection.Start = new LabeledMapLocation
    ("My Location", newGeoCoordinate(47.6601, -122.13333));
    myDrivingDirection.End = new LabeledMapLocation
    ("Mercer Island", null);
    // End of driving directions

  6. We added a HyperlinkButton near the footer (as shown in the previous screenshot), that will be used to fire the start() method of the BingMapsDirectionsTask instance.

    private void hyperlinkButton1_Click(object sender,
    RoutedEventArgs e)
    {
    myDrivingDirection.Show();
    }

  7. Run the application now and click on the Show Directions hyperlink button. You should see the following output (tested on our Nokia Lumia 800):

Pretty simple, huh? It is that easy to incorporate directions in your apps – no more extensive SDKs, libraries, and tons of code to import within your app. In pure Windows folklore we would say "Plug and Play" directions.

Performing local searches with BingMapsTask

The BingMapsTask is similar to the BingMapsDirectionsTask Launcher, except for the difference that BingMapsTask launches the Bing Maps app from the Windows Phone, and can allow it to be pre-populated with a search keyword or mark locations on the map.

We can modify the previous example to use BingMapsTask and populate a search result for Pizza when the hyperlink button Search for Pizza is clicked or touched:

  1. Create a copy of our HelloMaps-Pushpin project and rename it HelloMaps-Search.
  2. Import the Microsoft.Phone.Tasks namespace.
  3. Declare an instance of BingMapsTask in your main class as:

    BingMapsTask myBingMapsTask;

  4. In the MainPage() constructor, we instantiate myBingMapsTask, center it to a position near Redmond, and finally define the search term as Pizza using the following lines of code:

    // Show Bing Maps and search for Pizza
    myBingMapsTask = new BingMapsTask();
    myBingMapsTask.Center = new GeoCoordinate
    (47.6601, -122.13333);
    myBingMapsTask.SearchTerm = "Pizza";
    // End of Bing Maps

  5. Add the Click() method of hyperlinkButton1 as:

    private void hyperlinkButton1_Click(object sender,
    RoutedEventArgs e)
    {
    myBingMapsTask.Show();
    }

  6. Running the app produces the following result:

Memory allocated for a BingMapsTask does not count towards the total memory usage of your application. So try to use BingMapsTask instead of the Bing Maps Silverlight Control in your memory constraint devices/applications.

Summary

In this article we learnt how to use Bing Maps and its various controls in our Windows Phone applications.Specifically we covered an overview of map geometry – analysis of how maps work – using the Bing Maps Silverlight control, working with pushpins and custom pushpins, handling pushpin events, working with the Bing Maps geocoding service, and using Bing Maps Launchers (BingMapsDirectionsTask and BingMapsTask) in our Windows Phone applications.


Further resources on this subject:


About the Author :


Zeeshan Chawdhary

Zeeshan Chawdhary has over 8 years of experience in the web, mobile, and location-based services space. With a career spanning from developing 3D mobile game development at IndiaGames to leading a location-based travel startup at iCityConcierge Ltd - as the chief technology officer, Zeeshan has been able to work on a lot of exciting technologies – with the focus on cutting edge travel technology.

Among the key achievements Zeeshan has pioneered is the right mix of using Open Source and Proprietary software to create a technology stack based on the client’s need. He has developed location-based solutions for Nokia (for millions of hits per year) on a scalable cloud platform using Rackspace Cloud.

He enjoys working with PHP, PostGIS, and PhoneGap. He has immense experience in making startups use location data effectively for their growth, from startups like Foursquare to hotel industry big-wigs like Marriott; from mobile giant Nokia to Airline king American Airlines, he has worked with them all.

Zeeshan Chawdhary currently serves as the CTO of iCityConcierge Ltd., where he is currently working on creating the best personalized travel experience for travellers. He can be reached on Google at imzeeshanc@gmail.com

Books From Packt


Windows Phone 7 XNA Cookbook
Windows Phone 7 XNA Cookbook

Microsoft XNA 4.0 Game Development Cookbook
Microsoft XNA 4.0 Game Development Cookbook

Microsoft Silverlight 5 Data and Services Cookbook
Microsoft Silverlight 5 Data and Services Cookbook

Microsoft SharePoint 2010 Developer’s Compendium: The Best of Packt for Extending SharePoint
Microsoft SharePoint 2010 Developer’s Compendium: The Best of Packt for Extending SharePoint

Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7
Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7

Windows Phone 7 Silverlight Cookbook
Windows Phone 7 Silverlight Cookbook

Windows Phone 7.5 Data Cookbook
Windows Phone 7.5 Data Cookbook

 Microsoft XNA 4.0 Game Development Cookbook
Microsoft XNA 4.0 Game Development Cookbook


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
k
P
h
m
5
z
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software