Introduction
Hello everyone. I hope you're doing great with Windows Phone 8.1. I really love the new features of Windows Phone 8.1. Today I'll talk about Windows Phone Map Control and obviously it's Bing Map. In a new update of Windows Phone, there are significant APIs changed from the previous Windows Phone 8.0. Many great features were addedm like Geofencing. So let's get cracking with the entirely new Windows Phone 8.1 Map Control.
Creating a New Project and Add a Map Control
Create a new project and provide it a name (simply “Map” or whatever you want). Now, we'll add our Map Control from the “Toolbox”. Drag the “MapContol” tool from the “Toolbox” and place it in the main Grid.
Figure 1
Making Grids
We'll now modify our main Grid to re-size the “MapControl” and to show some other stuffs. First of all, we'll make some rows for other controls.
- <Grid HorizontalAlignment="Stretch"
- Margin="8,8,8,8" VerticalAlignment="Stretch">
- <Grid.RowDefinitions>
- <RowDefinition Height="10"/>
- <RowDefinition Height="50"/>
- <RowDefinition Height="*"/>
- <RowDefinition Height="40"/>
- </Grid.RowDefinitions>
- ...
- </Grid>
Here, in line numbers 4, 5, 6 and 7 we've declared four “RowDefinitions”. The first one is 10px in height, the second 50px, the third one is “*” that will cover the rest of the grid space and the last one is 40px.
Adding Controls
Here are the controls we've used in our “MainPage.xaml”.
- <Canvas>
- <ProgressBar x:Name="progressBar" Grid.Row="0"
- IsIndeterminate="True"
- Maximum="100" Value="30"
- Height="10"
- Width="400"/>
- </Canvas>
- <TextBlock TextWrapping="NoWrap" Grid.Row="1"
- Text="Map control"
- FontSize="36"
- Margin="8,0,0,16" />
- <Maps:MapControl x:Name="MyMap" Grid.Row="2"
- HorizontalAlignment="Left"
- VerticalAlignment="Top"
- Height="500"
- Width="385"
- MapTapped="MyMap_MapTapped" />
- <Slider x:Name="mySlider" Grid.Row="3"
- Maximum="20"
- Minimum="10"
- ValueChanged="Slider_ValueChanged" />
We've used a “ProgressBar” control, to indicate when the Map is loading, a “TextBlock” to show the title, a “MapControl” to show the Bing Map and a “Slider” to zoom in and zoom out.
Adding AppBar
We've also used a “BottomAppBar” to locate your current position.
- <Page.BottomAppBar>
- <CommandBar ClosedDisplayMode="Minimal" Opacity="0.5">
- <AppBarButton Label="locate me" Icon="Target" Click="LocateMe_Click" />
- </CommandBar>
- </Page.BottomAppBar>
I'm not going into the details of adding controls and how they work, if you don't know please feel free to have a look at my previous articles.
So, finally our design will look like this.

Figure 2
Code Behind
It is now time to do the code behind in C#. Let's open “MainPage.xaml.cs” and find the “OnNavigatedTo” method. Modify it as in the following.
- public sealed partial class MainPage : Page
- {
- Geolocator geolocator;
- protected async override void OnNavigatedTo(NavigationEventArgs e)
- {
- // Map Token for testing purpose,
- // otherwise you'll get an alart message in Map Control
- MyMap.MapServiceToken = "abcdef-abcdefghijklmno";
- geolocator = new Geolocator();
- geolocator.DesiredAccuracyInMeters = 50;
- try
- {
- // Getting Current Location
- Geoposition geoposition = await geolocator.GetGeopositionAsync(
- maximumAge: TimeSpan.FromMinutes(5),
- timeout: TimeSpan.FromSeconds(10));
- MapIcon mapIcon = new MapIcon();
- // Locate your MapIcon
- mapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/my-position.png"));
- // Show above the MapIcon
- mapIcon.Title = "Current Location";
- // Setting up MapIcon location
- mapIcon.Location = new Geopoint(new BasicGeoposition()
- {
- //Latitude = geoposition.Coordinate.Latitude, [Don't use]
- //Longitude = geoposition.Coordinate.Longitude [Don't use]
- Latitude = geoposition.Coordinate.Point.Position.Latitude,
- Longitude = geoposition.Coordinate.Point.Position.Longitude
- });
- // Positon of the MapIcon
- mapIcon.NormalizedAnchorPoint = new Point(0.5, 0.5);
- MyMap.MapElements.Add(mapIcon);
- // Showing in the Map
- await MyMap.TrySetViewAsync(mapIcon.Location, 18D, 0, 0, MapAnimationKind.Bow);
- // Disable the ProgreesBar
- progressBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
- // Set the Zoom Level of the Slider Control
- mySlider.Value = MyMap.ZoomLevel;
- }
- catch (UnauthorizedAccessException)
- {
- MessageBox("Location service is turned off!");
- }
- base.OnNavigatedTo(e);
- }
- ...
- }
Our main work is done, now we are ready to write the other methods for it to work perfectly.
- // Slider Control
- private void Slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
- {
- if (MyMap != null)
- MyMap.ZoomLevel = e.NewValue;
- }
- // Locate Me Bottom App Bar
- private async void LocateMe_Click(object sender, RoutedEventArgs e)
- {
- progressBar.Visibility = Windows.UI.Xaml.Visibility.Visible;
- geolocator = new Geolocator();
- geolocator.DesiredAccuracyInMeters = 50;
- try
- {
- Geoposition geoposition = await geolocator.GetGeopositionAsync(
- maximumAge: TimeSpan.FromMinutes(5),
- timeout: TimeSpan.FromSeconds(10));
- await MyMap.TrySetViewAsync(geoposition.Coordinate.Point, 18D);
- mySlider.Value = MyMap.ZoomLevel;
- progressBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
- }
- catch (UnauthorizedAccessException)
- {
- MessageBox("Location service is turned off!");
- }
- }
- // Custom Message Dialog Box
- private async void MessageBox(string message)
- {
- var dialog = new MessageDialog(message.ToString());
- await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => await dialog.ShowAsync());
- }
Adding Tap Event
One more thing I'd like to add is Map Tapped functionality. We'll add another method that will provide us a cool feature when we tap somewhere and in the Map Icon. It'll show the location details in the Message Dialog Box.
To add this method, go to “MainPage.xaml”, select “MapControl” in the main grid. If you don't see the “Properties” tab, then hit F4 and you'll find it on the left side of Visual Studio.
Now double-click on the “MapTapped” section and it'll automatically generate the method stub for you.

Figure 3
Now complete the “MyMap_MapTapped” method in the “MainPage.xaml.cs”
- private async void MyMap_MapTapped(MapControl sender, MapInputEventArgs args)
- {
- Geopoint pointToReverseGeocode = new Geopoint(args.Location.Position);
- // Reverse geocode the specified geographic location.
- MapLocationFinderResult result =
- await MapLocationFinder.FindLocationsAtAsync(pointToReverseGeocode);
- var resultText = new StringBuilder();
- if (result.Status == MapLocationFinderStatus.Success)
- {
- resultText.AppendLine(result.Locations[0].Address.District + ", " + result.Locations[0].Address.Town + ", " + result.Locations[0].Address.Country);
- }
- MessageBox(resultText.ToString());
- }
Adding Location Capability
Our work is now done, but if you run the application in your device or emulator, you'll definitely get an error. Because we've given permission to track our current position to our application. To do this, go to “Package.appxmanifest” and find the “Capabilities” section and tick the “Location” service and save it.

Figure 4
Running the Application
Now if you run the application it'll look exactly like this.

If you tap on the “MapIcon” it'll show the location details on the Message Dialog Box.
Using Polygon for Pushpin
Another thing is, if don't want to use an external image as a “MapIcon” then you can use a custom “Pushpin” like a “Polygon” control. Then you only need to modify the “OnNavigatedTo” method like this:
- protected async override void OnNavigatedTo(NavigationEventArgs e)
- {
- // Map Token for testing purpose,
- // otherwise you'll get an alart message in Map Control
- MyMap.MapServiceToken = "abcdef-abcdefghijklmno";
- geolocator = new Geolocator();
- geolocator.DesiredAccuracyInMeters = 50;
- try
- {
- // Getting Current Location
- Geoposition geoposition = await geolocator.GetGeopositionAsync(
- maximumAge: TimeSpan.FromMinutes(5),
- timeout: TimeSpan.FromSeconds(10));
- // Create a New Pushpin
- var pushpin = CreatePushPin();
- MyMap.Children.Add(pushpin);
- // Setting up Pushpin location
- var location = new Geopoint(new BasicGeoposition()
- {
- Latitude = geoposition.Coordinate.Latitude,
- Longitude = geoposition.Coordinate.Longitude
- });
- MapControl.SetLocation(pushpin, location);
- // Position of the Pushpin
- MapControl.SetNormalizedAnchorPoint(pushpin, new Point(0.0, 1.0));
- // Showing in the Map
- await MyMap.TrySetViewAsync(location, 18D, 0, 0, MapAnimationKind.Bow);
- // Disable the ProgressBar
- progressBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
- // Set the Zoom Level of the Slider Control
- mySlider.Value = MyMap.ZoomLevel;
- }
- catch (UnauthorizedAccessException)
- {
- MessageBox("Location service is turned off!");
- }
- base.OnNavigatedTo(e);
- }
And the “CreatePushPin” method is given below.
- private DependencyObject CreatePushPin()
- {
- // Creating a Polygon Marker
- Polygon polygon = new Polygon();
- polygon.Points.Add(new Point(0, 0));
- polygon.Points.Add(new Point(0, 50));
- polygon.Points.Add(new Point(25, 0));
- polygon.Fill = new SolidColorBrush(Colors.Red);
- // Return the Polygon Marker
- return polygon;
- }
Running the Application
Now, if you run the application, the marker will look like this.

Figure 6
Map Overlaying
It’s really cool and awesome using a custom Pushpin in Windows Phone 8.1. One more thing I’d like to add is overlaying tiled images on a map. If you want to overlay third-party or custom tiled images on the map and make it customized, then you simply need to use the following lines of code in the “OnNavigatedTo” method at the top.
- protected async override void OnNavigatedTo(NavigationEventArgs e)
- {
- var httpsource = new HttpMapTileDataSource("http://a.tile.openstreetmap.org/{zoomlevel}/{x}/{y}.png");
- var ts = new MapTileSource(httpsource);
- MyMap.TileSources.Add(ts);
- ...
- base.OnNavigatedTo(e);
- }
And if your run the application, it will provide you a much more graphical view than before with some details.

Figure 7
Summary
And that’s it! I hope you understand how to use the “MapControl” in Windows Phone 8.1. Have fun with the Map Control and make some cool applications with it. Read more about Maps and directions (XAML) at: http://bit.ly/X7S7ei
I will be here with a new topic soon. Until then good bye. Have a nice day.
Happy Coding!
Read the original article at: bit.ly/1D6O93Q

Amine DammakPosted Aug 17, 2015, 12:45 AM
i want my "mapicon" to change position every time I tap on the "mapcontrol" and show the current latitude and longitude of the "mapicon" .. how to do this? Thanks a lot
Trishun RamgoolamPosted Jun 17, 2015, 10:56 AM
Hi, I want to find some restaurants using the map, definitely I`ll use the pushpins, but I dont have an Idea how to do the work,.. btw It is a great explanation, but wants beyond that Thanks
Javier GonzalezPosted Mar 18, 2015, 9:06 PM
Hi!!! It's a great example!!! Thanks so much for this article. I have a question. How I use this if I'm in the second page of my app? In the same way? Thanks a lot
Marius KazlauskasPosted Nov 18, 2014, 9:22 AM
I added some additional code in your app to calculate a route from point A to point B like in http://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631250.aspx , but routeResult.Status is "InvalidCredentials". How do you think, may the cause of this be the bad MyMap.MapServiceToken?
Marius KazlauskasPosted Nov 18, 2014, 8:07 AM
Great article. Thanks. Do you know what type of license is necessary for the development commercial applications with these maps? Is it enough to get Company Account in Windows Dev Center? Or maybe it is needed to buy Bing Maps licence? We are developing a commercial windows phone 8.1 app just for one company and don't publish to Windows Store. Is it working in Windows universal apps? Thanks for You answers!