How to start a turn-by-turn navigation to a destination from your Windows Phone app

  • 1,340 views
Uploaded on

Introduction to new Geolocation, Maps namespaces and new Tasks for Maps (quick review) …

Introduction to new Geolocation, Maps namespaces and new Tasks for Maps (quick review)
How to start a turn-by-turn navigation to a destination from your Windows Phone app

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
  • Today Nokia does a very useful webinar on this topic, explaining also the new Here API:

    http://www.slideshare.net/nokia-developer/lumia-app-lab-16-s-here-application-launchers

    https://projects.developer.nokia.com/here_launchers
    Are you sure you want to
    Your message goes here
  • There is also an interesting video on UgiDotNet vimeo: https://vimeo.com/65235762?utm_campaign=Feed%3A+UgidotnetVideos+%28Elenco+dei+video+UGIdotNET%29&utm_medium=feed&utm_source=feedburner)
    Are you sure you want to
    Your message goes here
  • In the following you can find the link to a post in my blog, related to some part of this presentation: http://enzocontini.wordpress.com/2013/04/07/how-to-start-a-turn-by-turn-navigation-to-a-destination-from-your-windows-phone-app/
    Are you sure you want to
    Your message goes here
  • If you are interested in this presentation, please download it as a file because the online view has got some display problems after the automatic elaboration made by slideshare !!! :-(
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
1,340
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
31
Comments
4
Likes
3

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appHow to start a turn-by-turn navigation to adestination from your Windows Phone appEnzo ContiniEmail: enzo.contini@telecomitalia.itBlog: http://enzocontini.wordpress.comEnzo Contini TILAB 1
  • 2. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appAgenda► Introduction to new Geolocation, Maps namespaces and new Tasks for Maps(quick review)► How to start a turn-by-turn navigation to a destination from your WindowsPhone app► Demos► References (online examples and presentations)► Go back to introduction to see more in details (if there is time!)► Q&AEnzo Contini TILAB 2
  • 3. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appLocation sourcesEnzo Contini TILAB 313/04/2013WP8 Location Services+ Accuracy- Power- Speed- Indoors- Accuracy+ Power+ Speed- Wilderness+/- Accuracy+/- Power+/- Speed+/- Urban areasGPSCell TowersWiFi
  • 4. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appControlling the sources the geolocation service uses► You can’t decide if the source is GPS, WIFI or Cell Towers!► You only can set the DesiredAccuracy property of the Geolocator object:► PositionAccuracy.Default – to optimize for power► PositionAccuracy.High – if you want the most accurate data available, but atthe cost of increased battery usage, network bandwidth and possibly monetarycharges from wireless network operators. Often this causes the GPS to beactivated► You can also set the DesiredAccuracyInMeters property to indicate tothe Geolocation service the desired accuracy of any results► However, the Geolocation service determines the best location data toprovide to the application inside the user decided timeout (maximum timethe Geolocator object has to obtain a position that satisfies the accuracyrequirement).Enzo Contini TILAB 413/04/2013Geolocator.GetGeopositionAsync(maximumAge, timeout
  • 5. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appNew Windows.Devices.Geolocation namespace► Enables app developers to easily access the computers geographic location by using asingle APICapabilities: ID_CAP_LOCATION in WMAppManifest.xmlGeolocator class: current geographic location (Windows.Devices.Geolocation Geoposition)► User consent: you only have to get user consent if you plan to make location data availableto any other service or other person. In that case, the first use of the Geolocator object tocall GetGeopositionAsync must be made on the UI thread so that the consent prompt canbe shown to the user.► Convergent with Windows 8 location API with only minor differences. Most code should bereusable on both platforms.► When in Connected Standby (when the system is powered on but the display is off: this happens in response to the userpressing the physical Power button or when the user selects Sleep from the UI), Geolocator objects can always beinstantiated but the Geolocator object will not find any sensors to aggregate so calls to GetGeopositionAsync will timeout after 7 seconds, PositionChanged event listeners will never be called, and StatusChanged event listeners will becalled once with the NoData status.Enzo Contini TILAB 5
  • 6. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appSystem.Device.Location.GeoCoordinateWatcher.NET Location API from Windows Phone OS 7.1 is still supported:System.Device.Location.GeoCoordinateWatcher and related classesEnzo Contini TILAB 613/04/2013private void TrackLocation_Click(object sender, RoutedEventArgs e) {if (!tracking) {geolocator = new Geolocator();geolocator.DesiredAccuracy = PositionAccuracy.High;geolocator.MovementThreshold = 100; // The units are meters.geolocator.PositionChanged += geolocator_PositionChanged;tracking = true;TrackLocationButton.Content = "stop tracking";} else {geolocator.PositionChanged -= geolocator_PositionChanged;geolocator = null;tracking = false;TrackLocationButton.Content = "track location";StatusTextBlock.Text = "stopped";}}void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args){Dispatcher.BeginInvoke(() => {LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.00");LongitudeTextBlock.Text = args.Position.Coordinate.Longitude.ToString("0.00");});}
  • 7. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appBE CAREFUL► Geolocator uses System.Device.Location.GeoCoordinate:► GeoCoordinateWatcher (as well as Maps API in general) usesWindows.Devices.Geolocation.GeocoordinateWindows.Devices.Geolocation.Geocoodinate != System.Device.Location.GeoCoordinateSystem.Device.Location.GeoCoordinate myCoord = newGeoCoordinate(Position.Coordinate.Latitude,Position.Coordinate.Longitude);Enzo Contini TILAB 713/04/2013WGS 84standardGeoposition geoposition;GeoCoordinate geoCoordinate =geoposition.Coordinate.ToGeoCoordinate();See also the Phone Toolkit Map extensions: GeocoordinateExtensionsclass that extends Geocoordinate class
  • 8. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appID_CAP_LOCATION capabilityEnzo Contini TILAB 813/04/2013If you forget, at runtime calls to location APIs throw an UnauthorizedAccessException
  • 9. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appGeolocator (summary)Enzo Contini TILAB 913/04/2013Windows.Devices.Geolocation.GeolocatorPositionChanged [Tracking] GetGeopositionAsync(maxAge, Timeout)[one shot]GeopositionGeocoordinate Coordinate CivicAddress = NULLAccuracyLatitudeLongitudePositionSourceSpeedTimeStampCellularGPSWIFIReportIntervalMovementThresholdDesiredAccuracyDesiredAccuracyInMeters
  • 10. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appGeoposition properties► The obtained Geoposition has the following 2 properties:► Geocoordinate Coordinate [Latitude /Longitude /Altitude , Accuracy , PositionSource ,Speed , Timestamp etc…]► CivicAddress CivicAddress [City , Country] always NULL in WP8. If you want the addressyou need to call ReverseGeocodeQuery maps service (from a GeoCoodinate).again … BE CAREFUL:Windows.Devices.Geolocation.Geocoodinate != System.Device.Location.GeoCoordinatetherefore ()GetReverseLocation(new GeoCoordinate(myCurrentGeoposition.Coordinate.Latitude,myCurrentGeoPosition.Coordinate.Longitude));See also the Phone Toolkit Map extensions: GeocoordinateExtensions class that extendsGeocoordinate classEnzo Contini TILAB 1013/04/2013Geoposition geoposition;GeoCoordinate geoCoordinate =geoposition.Coordinate.ToGeoCoordinate();WGS 84standard
  • 11. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appprivate async void OneShotLocation_Click(object sender, RoutedEventArgs e) {Geolocator geolocator = new Geolocator();geolocator.DesiredAccuracyInMeters = 50; //in meters//geolocator.DesiredAccuracy =Windows.Devices.Geolocation.PositionAccuracy.High,try {Geoposition geoposition = await geolocator.GetGeopositionAsync(maximumAge: TimeSpan.FromMinutes(5),timeout: TimeSpan.FromSeconds(10) );LatitudeTextBlock.Text =geoposition.Coordinate.Latitude.ToString("0.000");LongitudeTextBlock.Text =geoposition.Coordinate.Longitude.ToString("0.000");} catch (UnauthorizedAccessException) {// the app does not have the right capability or the location master switchis offStatusTextBlock.Text = "location is disabled in phone settings.";}}One shot phone’s current location (see *)Enzo Contini TILAB 1113/04/2013
  • 12. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appLocation TrackingEnzo Contini TILAB 1213/04/2013private void TrackLocation_Click(object sender, RoutedEventArgs e){ if (!tracking) {geolocator = new Geolocator();geolocator.DesiredAccuracy = PositionAccuracy.High;geolocator.MovementThreshold = 100; // The units are meters.geolocator.StatusChanged += geolocator_StatusChanged;geolocator.PositionChanged += geolocator_PositionChanged;tracking = true;} else {geolocator.PositionChanged -= geolocator_PositionChanged;geolocator.StatusChanged -= geolocator_StatusChanged;geolocator = null;tracking = false;}}void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args) {Dispatcher.BeginInvoke(() => {LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.000");LongitudeTextBlock.Text = args.Position.Coordinate.Longitude.ToString("0.000");});}
  • 13. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appEnable location tracking in the background (1)► Normally, when your user navigates away from your app, it is made dormantand all activity – including location tracking – is suspended► In Windows Phone 8, a location-tracking app can continue to run in thebackground after the user navigates away, as long as the app continues toactively track location► This feature enables scenarios such as an app that provides turn-by-turndirections or a run tracker► Continuously tracking the user’s location drains the user’s battery more andshould only be used for apps that require it.Enzo Contini TILAB 1313/04/2013
  • 14. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appEnable location tracking in the background (2)1. Edit WMAppManifest.xml using the XML Text EditorEnzo Contini TILAB 1413/04/2013
  • 15. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone app2. Register event handler for RunningInBackground event in App.xaml<Application.ApplicationLifetimeObjects><!--Required object that handles lifetime events for the application--><shell:PhoneApplicationServiceLaunching="Application_Launching" Closing="Application_Closing“Activated="Application_Activated" Deactivated="Application_Deactivated“RunningInBackground="Application_RunningInBackground"/></Application.ApplicationLifetimeObjects>Enable location tracking in the background (3)Enzo Contini TILAB 1513/04/2013
  • 16. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone app// Static variables global to application to support tracking public static Geolocator Geolocator{ get; set; }public static bool RunningInBackground { get; set; }// Code to execute when the application is activated (brought to foreground) private voidApplication_Activated(object sender, ActivatedEventArgs e) {RunningInBackground = false;}// Code to execute when the application is deactivated and is tracking locationprivate void Application_RunningInBackground(object sender, RunningInBackgroundEventArgs e) {RunningInBackground = true;// Suspend all unnecessary processing such as UI updates}Enable location tracking in the background (4)Enzo Contini TILAB 1613/04/20133. Implement RunningInBackground event handler in App.cs
  • 17. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appEnzo Contini TILAB 1713/04/2013void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args) {if (!App.RunningInBackground) {Dispatcher.BeginInvoke(() => {LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.000");LongitudeTextBlock.Text = args.Position.Coordinate.Longitude.ToString("0.000"); });} else {//DEMOMicrosoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();toast.Content = args.Position.Coordinate.Latitude.ToString("0.000");toast.Title = "Location: ";toast.NavigationUri = new Uri("/Page2.xaml", UriKind.Relative);toast.Show();}}Enable location tracking in the background (5)Do not update UI when running in the background.Then, for example, if running in background show toast or write in Start live tile.
  • 18. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appLocation on emulatorEnzo Contini TILAB 1813/04/2013► Windows Phone Emulator comes with Location simulator: useful especiallywhen you need tracking capabilities. You can also record data and then runagain the same sequence.NOTE - How to take a screenshot with Windows Phone 8
  • 19. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appNew Maps namespaces► Microsoft.Phone.Maps : contains core classes of the map controlCapabilities: ID_CAP_MAP in WMAppManifest.xml► Microsoft.Phone.Maps.Controls: contains the most commonly usedpublic classes of the map control for Windows Phone[Map, MapRoute, MapLayer, GeoCoordinateCollection, etc…]► Microsoft.Phone.Maps.Services : contains classes that providelocation services to map control► GeocodeQuery: from a text [address/building name] to potential geocoordinatesand other geolocation data (IList<MapLocation>)► ReverseGeocodeQuery: given a location, what do I find there? From a location (System.Device.Location.GeoCoordinate) to potential geolocation data (IList<MapLocation>) as address► RouteQuery : used to calculate the route between any two or more geographicallocations. The query result could be used to draw a route on the map and/or tocalculate the distance from source to destination.Enzo Contini TILAB 1913/04/2013
  • 20. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appID_CAP_MAP CapabilityEnzo Contini TILAB 2013/04/2013If you forget, always at runtime the page throw‘XAML Parse exception occurred -System.Windows.Markup.XamlParseException‘
  • 21. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appMap Control ()► In XAML► In code► By default, map displays at zoom level 1 (world view) and centered atLat/Long 0,0;► Center and ZoomLevel properties to change this, in XAML or in code.Enzo Contini TILAB 2113/04/2013<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"><maps:Map x:Name=“MyMap"/></Grid>private void CreateMap() {Map MyMap = new Map();ContentPanel.Children.Add(MyMap);}//Set the Map center by using Center propertyMyMap.Center = new GeoCoordinate(45.09854,17.33315);//Set the map zoom by using ZoomLevel propertyMyMap.ZoomLevel = 17;<maps:Map x:Name=“MyMap"Center="45.09874,17.32691"ZoomLevel="17"Heading="45"Pitch="25"CartographicMode="Road"ColorMode="Dark"PedestrianFeaturesEnabled="True"LandmarksEnabled="True" />
  • 22. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appMap Control: map views (1)► A new map view is defined any time the position of the map is changed asa result of panning, zooming, rotating or tilting► You can use one overload of the SetView method to define a map viewusing one or more of the following parameters:► Center: A GeoCoordiante object defining the center of the map after setting theview.► ZoomLevel: zoom level, between 1 and 20► Heading: specifies the directional heading that is pointing “up” on the map ingeometric degrees between 0 and 360► Pitch: specifies the degree to which the map is tilted as a value between 0 and180► BoundingRectangle: a LocationRectangle object that contains the Map control► AnimationKind: sets the kind of animation you want to see (None, Linear orParabolic) when the view changesEnzo Contini TILAB 2213/04/2013
  • 23. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appMap Control: map views (2)Use of the BoundingRectangle parameter to show a map that contains allthe interested GeoCoordinates:Enzo Contini TILAB 2313/04/2013
  • 24. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appMap Control: cartographic modes► CartographicMode property allows to set the cartographic mode of themapEnzo Contini TILAB 2413/04/2013Road (default) Aerial Hybrid Terrain
  • 25. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appMap Control: light and dark color modes► ColorMode property allows to display the map in a light or dark color modeEnzo Contini TILAB 2513/04/2013Light (default) Dark
  • 26. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone app► Display additional elements on your map such as 3D landmarks and pedestrianfeatures such as public stairs.► To display 3D landmarks (ZoomLevel>7; Pitch>25)LandmarksEnabled = true► To display pedestrian featuresPedestrianFeaturesEnabled = trueNOTE: landmarks are visible only when the ZoomLevel is 7 or higher, and the Pitchproperty is 25 or higherMap Control: pedestrian features and 3D landmarksEnzo Contini TILAB 2613/04/2013
  • 27. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appConvertViewportPointToGeoCoordinate Map methodEnzo Contini TILAB 2713/04/2013► ConvertViewportPointToGeoCoordinate method that returns the GeoCoordinatesfrom the specified viewport point of the map control.ConvertGeoCoordinateToViewportPoint: returns the viewport point from thespecified GeoCoordinates of the map control.GeoCoordinate geoCoordinate =Map.ConvertViewportPointToGeoCoordinate(e.GetPosition(this.Map));
  • 28. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appEnzo Contini TILAB 2813/04/2013► Unlike the Bing Maps API, WP8 Maps API does not have a specific PushPinobject. There’s nothing ready to be used in the SDK for common scenarioslike displaying a pushpin or the user’s location.► However, you can create your own pushPins by drawing UIElements onto aMapOverlay, then add the MapOverlay to a MapLayer which you add to theMap. ()► MapOverlay object, that has two main properties:► GeoCoordinate, with the coordinates where the element should be placed► Content, which is a generic object property so it accepts any XAML control► Very powerful: since the MapOverlay object has a generic Contentproperty, you can customize the overlay elements any way you wantPushpins (1)
  • 29. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appprivate void AddMapOverlay() {Grid MyGrid = CreatePushpin();//Creating a MapOverlay and adding the Grid to it.MapOverlay MyOverlay = new MapOverlay();MyOverlay.Content = MyGrid;//MyOverlay.Content = new Ellipse { Fill = newSolidColorBrush(Colors.Red), Width = 40, Height = 40 }MyOverlay.GeoCoordinate = new GeoCoordinate(7.60, -22.3);MyOverlay.PositionOrigin = new Point(0, 0.5);//Creating a MapLayer and adding the MapOverlay to itMapLayer MyLayer = new MapLayer();MyLayer.Add(MyOverlay);MyMap.Layers.Add(MyLayer);}Enzo Contini TILAB 2913/04/2013private Grid CreatePushpin() {//Creating a Grid element.Grid MyGrid = new Grid();MyGrid.RowDefinitions.Add(new RowDefinition());MyGrid.RowDefinitions.Add(new RowDefinition());MyGrid.Background = new SolidColorBrush(Colors.Transparent);//Creating a RectangleRectangle MyRectangle = new Rectangle();MyRectangle.Fill = new SolidColorBrush(Colors.Black);MyRectangle.Height = 20;MyRectangle.Width = 20;MyRectangle.SetValue(Grid.RowProperty, 0);MyRectangle.SetValue(Grid.ColumnProperty, 0);//Adding the Rectangle to the GridMyGrid.Children.Add(MyRectangle);}Pushpins (2)
  • 30. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appPhone Toolkit Map extensions (1) (see MapsSample in PhoneToolkitSample.WP8)UserLocationMarker and Pushpin controls► They are both overlay elements that are placed on the map over a specificposition and they offer a way to interact with them (so that, for example, theuser can tap on a pushpin and do something)► Pushpin has the same look & feel of the ones that were available in the oldBing Maps and can be used to highlights point of interests in the map► UserLocationMarker is used to identify the position of the user and it hasthe same look & feel of the one used in the native appEnzo Contini TILAB 3013/04/2013Pushpin UserLocationMarker
  • 31. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone app► Declare in the XAML the namespace:xmlns:maptk="clr-namespace:Microsoft.Phone.Maps.Toolkit;assembly=Microsoft.Phone.Controls.Toolkit“► In XAML:► Manage their position by code:Enzo Contini TILAB 3113/04/2013<maps:Map x:Name="myMap"><toolkit:MapExtensions.Children><toolkit:UserLocationMarker x:Name="UserLocationMarker" /><toolkit:Pushpin x:Name="MyPushpin" Content="My Position“Tap="MyPushpin_OnTap"/></toolkit:MapExtensions.Children></maps:Map>UserLocationMarker marker = (UserLocationMarker)this.FindName("UserLocationMarker");marker.GeoCoordinate = myMap.Center;Pushpin pushpin = (Pushpin)this.FindName("MyPushpin");pushpin.GeoCoordinate = new GeoCoordinate(32.71200, 7.32600);private void MyPushpin_OnTap(object sender, GestureEventArgs e) {Pushpin pushpin = sender as Pushpin;MessageBox.Show(pushpin.Content.ToString());}Phone Toolkit Map extensions (2) (see MapsSample in PhoneToolkitSample.WP8)UserLocationMarker and Pushpin controls
  • 32. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appPhone Toolkit Map extensions:GeocoordinateExtensions classEnzo Contini TILAB 3213/04/2013Geoposition geoposition;GeoCoordinate geoCoordinate =geoposition.Coordinate.ToGeoCoordinate();Windows.Devices.Geolocation.Geocoodinate !=System.Device.Location.GeoCoordinateWGS 84standard
  • 33. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appEnzo Contini TILAB 3313/04/2013GeocodeQuery & ReverseGeocodeQuery (summary)GeocodeQueryGeocodeQuery_QueryCompletedReverseGeocodeQuery_QueryCompletedIList<MapLocation>LocationRectangleBoundingBoxGeoCoordinateInformation LocationInformationSearchTerm [descriptive text]GeoCoordinate [current / new GeoCoordinate(0,0)]ReverseGeocodeQuerynew GeoCoordinate(Lat, Long)MapAddress AddressDescriptionNameAltitudeLatitudeLongitudeSpeedHorizontalAccuracyVerticalAccuracyStreetHouseNumberCity…
  • 34. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appTurning Query into a proper async operation ()Enzo Contini TILAB 3413/04/2013
  • 35. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appNew maps launchers: Tasks for MapsEnzo Contini TILAB 35
  • 36. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone app► MapsTask makes launching the built-in Maps application easy. It allows anapplication to launch the Maps application centered at the locationspecified with the Center property or, by default, at the user’s currentlocation.► If SearchTerm is set, locations matching the search term are tagged on themap.MapsTask (1)Enzo Contini TILAB 3613/04/2013private void LaunchMapsTask() {MapsTask mapsTask = new MapsTask();//NOTE: omit the Center property to use the users currentlocationmapsTask.Center = new GeoCoordinate(45.098541,7.697704);mapsTask.ZoomLevel = 17;mapsTask.SearchTerm ="ospedale"; //"ospedali";//"pizzeria";//!!!!!!!!!!mapsTask.Show();}
  • 37. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone app► Too few results and too often not consistent!!► If SearchTerm = “ospedale” it goes to the town “Ospedale”; then, if yousearch “ospedali”, it shows the hospitals near that previous found town andnot near the centered point set in MapTask: only if you go to current positionand then ask again for “ospedali”, it shows some of them … but again toofew!MapsTask (2)Enzo Contini TILAB 3713/04/2013«pizzeria» «ospedali»after previous search by code«ospedale» «ospedali»after asked for current position
  • 38. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appMapDownloaderTask / MapUpdaterTask (1)► These tasks launches the Maps settings application which allows the user toselect a region of map data to download / checks to see if there are updatesavailable for any previously downloaded map dataEnzo Contini TILAB 3813/04/2013
  • 39. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone app► If a map control is currently used by the phone, these tasks cannot work anda popup alert is shown.Enzo Contini TILAB 3913/04/2013MapDownloaderTask / MapUpdaterTask (2)MapDownloaderTask MapUpdaterTask
  • 40. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appPublish an app that uses the Map control: ApplicationIdand AuthenticationToken (1)► To run and debug an app that uses the Map control you don’t need to donothing than use it.► BUT, before you can publish an app that uses the Map control, you have toget an ApplicationId and AuthenticationToken from the Windows Phone DevCenter and add the values to your code, assign them to the respectiveproperties (see here):► after you have finished your app, begin the app submission process;► on the Submit app page, click Map services;► the Map services page opens;► on the page, click Get token;► the new ApplicationID and AuthenticationToken are displayed on the same page;► copy the values and paste them into your code as described in the followingprocedure;► rebuild your app with the new code and upload and updated copy to the Store.Enzo Contini TILAB 4013/04/2013
  • 41. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appPublish an app that uses the Map control: ApplicationIdand AuthenticationToken (2)Enzo Contini TILAB 4113/04/2013► In the xaml:► In the code:
  • 42. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appStart a turn-by-turn navigation to a destinationfrom your Windows Phone appSometime it is useful to insert in your WP8 app the capability to start a navigationto a destination that can be derived, for example, from the address of asomeone/some place or from the geocoordinate of a point in a map.There are several ways to do that and here I’ll try to describe the following ones:►Coding the navigation functions inside your app (RouteQuery class +GeocodeQuery class) .►Using the MapsDirectionsTask  class.►Launching a navigator app with a Launcher that uses a specific navigation Uri.Enzo Contini TILAB 4213/04/2013
  • 43. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appA) Coding the navigation functions inside yourapp (1)► This can be done mainly using ► the GeocodeQuery class (to find a possible list of Geocoordinate  from adescriptive search term like an address, a building name, or any other phraseindicating a place on Earth),► the RouteQuery class (to get all the route points to reach the destination[according to the required mode of travel and optimizations])► the SpeechSynthesizer class to have a text-to-speech reading of each Route turning point [the list of maneuvers associated with each route RouteLeg of everyRoute.Legs, that is the property  of the legs associated with the route].► All the three mentioned classes are async ones, in order not to stop the userinteraction with the UI; in particular, the first two comes from the newMicrosoft.Phone.Maps.Services.► A code example that implements this kind of solution can be found in theNokia Developer site: Map with directions in Windows Phone 8 project.Enzo Contini TILAB 4313/04/2013
  • 44. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appA) Coding the navigation functions inside yourapp (2)Enzo Contini TILAB 4413/04/2013You can see a blu circle for thestarting point, a red one for the endpoint and a green one for the actualRoute turning point with the maneuverwritten below (it is the text read by theSpeechSynthesizer).However if you run that example, you will notice that the user experience is notcomparable with that provided with commercial navigators and the synthesizedvoice, that can be acceptable for an input request, is not appropriate for givingdriving instructions.Most of the work needed to have a basic navigator is already done, even thoughtthe text-to-speech of each instruction should be based on the actual position ofthe user [using the Geolocator class and in particular itsGetGeopositionAsync(TimeSpan, TimeSpan) method and a listener to itsPositionChanged event].
  • 45. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appB) Using the MapsDirectionsTask class (1)► MapsDirectionsTask  class is very powerful and allows to launch the Mapsapplication, specifying a starting location and/or an ending location, forwhich driving directions are displayed and possibly launch an externalnavigator app.Very often the starting position is the user’s current position: in that case theStart property must not be set because user’s current position is its defaultvalue (therefore there is no need to use the Geolocator class and itsGetGeopositionAsync(TimeSpan, TimeSpan) method to find out user’scurrent position, because that Task already does everything for us).► A code example that implements this kind of solution can be foundamong the Nokia Developer examples: LaunchDirectionsTask project(inside a Zip archive).Enzo Contini TILAB 4513/04/2013
  • 46. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appEnzo Contini TILAB 4613/04/2013MapsDirectionsTask mapsDirectionsTask = new MapsDirectionsTask();mapsDirectionsTask.Start = new LabeledMapLocation(OriginTitle.Text, originMarker.GeoCoordinate);mapsDirectionsTask.End = new LabeledMapLocation(DestinationTitle.Text,destinationMarker.GeoCoordinate);mapsDirectionsTask.Show(); In the case that you have an originMarker MapOverlay as a start point and adestinationMarker one as a destination point: In the case you would like do go from your position to a specificgeoCoordinate, (the default value of the starting position is the phonescurrent position):MapsDirectionsTask mapsDirectionsTask = new MapsDirectionsTask();mapsDirectionsTask.End = new LabeledMapLocation("Home", new GeoCoordinate(45.098614934831858,7.6977774314582348));mapsDirectionsTask.Show(); If you have to go to a location that you want to find by name:MapsDirectionsTask mapsDirectionsTask = new MapsDirectionsTask();mapsDirectionsTask.End = new LabeledMapLocation("Space Needle", null);mapsDirectionsTask.Show();
  • 47. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appB) Using the MapsDirectionsTask class (2)Enzo Contini TILAB 4713/04/2013Request ofuser’s consentGetting directions Directions found(emulator)Set directionsfor pedestrian
  • 48. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appB) Using the MapsDirectionsTask class (3)Enzo Contini TILAB 4813/04/2013After click on the map Toolbar & menu (1) Toolbar & menu (2)If you click on “directions” toolbar button (“indicazioni stradali” in italian), you goback to the “Get direction” page, to allow a insert a new destination, and not to anavigation app.
  • 49. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appB) Using the MapsDirectionsTask class (4)Enzo Contini TILAB 4913/04/2013But if you use a real phone and not the emulator, you can see, in the “Directionfound“ page, a “by car“/”by foot” toolbar button (“In macchina“/”a piedi” in italian)[depending if it was chosen the car or the pedestrian view], that allows the user tolaunch, just from here, an external navigation app toward the chosen destination.
  • 50. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appB) Using the MapsDirectionsTask class (5)Enzo Contini TILAB 5013/04/2013When the external navigator program is closed, your app comes again inforeground.Note that, if is your app is registered to run in background (because most if not allthe navigator programs do the same and WP8 allows only one app to run inbackground), the background functions of your app stop until the navigatoris closed and your app is again in foreground: once again, when it will go inbackground (for example because you answer a phone call or you use the browserto search something) the background execution will be activated.
  • 51. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appBing Search vs. MapsDirectionsTask  (1)Navigation functions provided by the MapsDirectionsTask are in some way similar tothe ones provided by the embedded Bing search.When you go to the local results and click on the desired location, an Info pageappears where you can start an external navigator with “drive -use an app”(“percorri – usa un’app” in italian).However the procedures that can be used to start a navigation app are different.Enzo Contini TILAB 5113/04/2013
  • 52. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appBing Search vs. MapsDirectionsTask  (2)► In Bing Search “directions” ("indicazioni stradali" in italian) toolbar buttonstarts the navigation app, while  using MapsDirectionTask the toolbar buttonof the same name “directions” let the user go back to a previous page for anew input of start – end points, while the launch of a navigator app is doneby a different named toolbar button (“by car”) in that previous page.► In Bing Search, if there is not any app installed able to start a navigation (ex.case you can test using the emulator) clicking “directions” toolbar button letgo to the store, showing all the appropriate apps that satisfy that requestedprotocol, while in the MapsDirectionTask the “byCar” toolbar button is notshown in that case, disabling any way to start a navigator app.► I think that it is not nice to give a different user experience: if you agree youcan vote here.Enzo Contini TILAB 5213/04/2013
  • 53. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appBing Search vs. MapsDirectionsTask  (3)Enzo Contini TILAB 5313/04/2013after clicking ona pushpin (ita)after clicking ona pushpin (eng)ask for app in the store app in the storefor navigation
  • 54. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appC) Use a Launcher with a specific navigationURI (1)► Sometime you need to start a professional navigator as soon as possible andthe method described before can be useful only when probably it’s enoughfor the user to have the route shown as a layer on the map and onlysometimes he will need to ask for a turn-by-turn navigation.► So if you want to directly launch an other app that offer a navigation service,an app-to-app communication can be used: a navigator app can be launchedwith a Launcher that uses a specific navigation Uri.► If you knows the protocol name and the way possible parameters are passed, youcan directly call a specific store app. For example, Nokia Maps can be launchedas follows (at least now - NOKIA said that  the “explore-maps://v1.0/…” app2app customprotocol is NOT SUPPORTED for 3rd party apps):string launchNokiaMaps = "explore-maps://v1.0/?latlon=45.098541,7.697704&zoom=16";     await Windows.System.Launcher.LaunchUriAsync(new Uri(launchNokiaMaps));► Use the new “ms-*” app2app custom protocols and in particular the navigationprotocol and the ms-drive-to and ms-walk-to URI schemes (even thought they do notappear in the Reserved file and URI associations for Windows Phone 8 (???))Enzo Contini TILAB 5413/04/2013 
  • 55. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appC) Use a Launcher with a specific navigationURI (2)► A code example that implements this kind of solution can be foundamong the MSDN samples: Navigation URI scheme sample.► It shows how you can use the navigation protocol both to write an app thatrequests driving/walking directions, and to write an other app that providesdriving/walking directions.Enzo Contini TILAB 5513/04/2013
  • 56. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appEnzo Contini TILAB 5613/04/2013          // Test both navigation Uri schemes.           private const string DRIVING_PROTOCOL = "ms-drive-to";           private const string WALKING_PROTOCOL = "ms-walk-to";            // Use Seattle as the default destination.           private const string DESTINATION_LATITUDE = "45.098614934831858";           private const string DESTINATION_LONGITUDE = "7.6977774314582348";           private const string DESTINATION_NAME = "Casa, TO";           // Single event handler for both driving and walking directions.           private void GetDirections(object sender, EventArgs e) {               string uriProtocol = null;               string uri;                // Driving or walking directions?               string buttonClicked = ((Button)sender).Name;               switch(buttonClicked) {                   case "btnGetDrivingDirections":                       uriProtocol = DRIVING_PROTOCOL;                       break;                   case "btnGetWalkingDirections":                       uriProtocol = WALKING_PROTOCOL;                       break;                   default:                       uriProtocol = DRIVING_PROTOCOL;                       break;               }                // Assemble the Uri for the request.               uri = uriProtocol + ":?" +                   "destination.latitude=" + DESTINATION_LATITUDE + "&" +                   "destination.longitude=" + DESTINATION_LONGITUDE + "&" +                   "destination.name=" + DESTINATION_NAME;                // Display the Uri.               tbShowRequestUri.Text = AppResources.UriDisplayPrefix + ":n" + uri;                // Make the request.               RequestDirections(uri);           }  async void RequestDirections(string uri) {               try {                   // Make the request.                   var success = await Windows.System.Launcher.LaunchUriAsync(new Uri(uri));                   if(success) {                       // Request succeeded.                   } else {                       // Request failed.                       MessageBox.Show("Request failed");                   }               } catch(Exception ex) {                   MessageBox.Show("Exception: " + ex.Message);               }           }
  • 57. TTG - Torino Technologies Group - How to start a turn-by-turn navigation to a destination from your Windows Phone appReferences► Video:Building Apps for Windows Phone 8 Jump Start: (14) Maps and Location i8 (or in Microsoft Virtual Academy -Building Apps for Windows Phone 8 Jump Start)► Video:Windows Phone 8: Maps, Location, and Background Execution for Developers► Community Days 2013 - WP806 - Mappe su Windows Phone 8► Slides - Nokia - Mapping and Location ;Maps and location APIs for Windows Phone► Nokia Developer - Windows Phone 8 Maps Examples (Zip archive) ; **► Nokia Developer - Wiki Category: Nokia Maps - contains communityarticles related to Nokias Location Platform Here (also known as "Nokia Maps").► My Blog - How to start a turn by turn navigation to a destination fromyour Windows Phone app Enzo Contini TILAB 5713/04/2013