다음을 통해 공유


How to get and display routes and directions

Get driving or walking routes and directions by calling the methods of the MapRouteFinder class in the Windows.Services.Maps namespace. Display a route in a MapControl with a few lines of code.

Here's how the classes for routes and directions are related.

Important  

Your app has to be authenticated before it can use many features of the Map control and map services. For more info, see How to authenticate your Maps app.

 

Which API shall I use to get directions?

  • If the user simply wants directions, and your app doesn't have to use the results of the query, launch another app by using the ms-drive-to or ms-walk-to Uri scheme. For more info, see How to request driving or walking directions from another app.
  • If the user wants directions, but probably wants to browse the map also, and your app doesn't have to use the results of the query, launch the built-in Maps app by using the bingmaps: Uri scheme. For more info, see How to display maps and directions in the built-in Maps app.
  • If the user wants directions, and your app has to use the results of the query to provide additional info or services to the user, use the APIs described in this topic.

Before you call the methods of the MapRouteFinder class

At the top of your class file, add a using statement for the Windows.Services.Maps namespace for the MapRouteFinder class and the related classes. Typically you also have to have a using statement for the Windows.Devices.Geolocation namespace.

If you want to display a route on a map, the MapControl requires a using statement for the Windows.UI.Xaml.Controls.Maps namespace.

using Windows.Services.Maps;
using Windows.Devices.Geolocation;
using Windows.UI.Xaml.Documents;   // For multiple lines of text.
using Windows.UI.Xaml.Controls.Maps;
using Windows.UI;   // For colors.

Provide the token required to authenticate for Maps services by setting the ServiceToken property of the static MapService class. For more info, see How to authenticate your Maps app.

    MapService.ServiceToken = "abcdef-abcdefghijklmno";

Getting a route and directions

Get a driving or walking route and directions by calling the methods of the MapRouteFinder class - for example, GetDrivingRouteAsync or GetWalkingRouteAsync. The MapRouteFinderResult object contains a MapRoute object that you access through its Route property.

When you request a route, you can specify the following things:

  • You can provide a start point and end point only, or you can provide a series of waypoints to compute the route.
  • You can specify optimizations - for example, minimize the distance.
  • You can specify restrictions - for example, avoid highways.

The computed MapRoute has properties that provide the time to traverse the route, the length of the route, and the collection of MapRouteLeg objects that contain the legs of the route. Each MapRouteLeg object contains a collection of MapRouteManeuver objects. MapRouteManeuver object contains directions that you access through its InstructionText property.

This example assumes that the page contains a TextBlock control named tbOutputText to display the results. The example uses objects from the Windows.UI.Xaml.Documents namespace to format multiple lines of text for display in the TextBlock control.

        private async void GetRouteAndDirections()
        {
            // Start at Microsoft in Redmond, Washington.
            BasicGeoposition startLocation = new BasicGeoposition();
            startLocation.Latitude = 47.643;
            startLocation.Longitude = -122.131;
            Geopoint startPoint = new Geopoint(startLocation);

            // End at the city of Seattle, Washington.
            BasicGeoposition endLocation = new BasicGeoposition();
            endLocation.Latitude = 47.604;
            endLocation.Longitude = -122.329;
            Geopoint endPoint = new Geopoint(endLocation);

            // Get the route between the points.
            MapRouteFinderResult routeResult =
                await MapRouteFinder.GetDrivingRouteAsync(
                startPoint,
                endPoint,
                MapRouteOptimization.Time,
                MapRouteRestrictions.None);

            if (routeResult.Status == MapRouteFinderStatus.Success)
            {
                // Display summary info about the route.
                tbOutputText.Inlines.Add(new Run()
                {
                    Text = "Total estimated time (minutes) = "
                        + routeResult.Route.EstimatedDuration.TotalMinutes.ToString()
                });
                tbOutputText.Inlines.Add(new LineBreak());
                tbOutputText.Inlines.Add(new Run()
                {
                    Text = "Total length (kilometers) = "
                        + (routeResult.Route.LengthInMeters / 1000).ToString()
                });
                tbOutputText.Inlines.Add(new LineBreak());
                tbOutputText.Inlines.Add(new LineBreak());

                // Display the directions.
                tbOutputText.Inlines.Add(new Run()
                {
                    Text = "DIRECTIONS"
                });
                tbOutputText.Inlines.Add(new LineBreak());

                foreach (MapRouteLeg leg in routeResult.Route.Legs)
                {
                    foreach (MapRouteManeuver maneuver in leg.Maneuvers)
                    {
                        tbOutputText.Inlines.Add(new Run()
                        {
                            Text = maneuver.InstructionText
                        });
                        tbOutputText.Inlines.Add(new LineBreak());
                    }
                }
            }
            else
            {
                tbOutputText.Text =
                    "A problem occurred: " + routeResult.Status.ToString();
            }

        }

This code displays the following results:

Displaying a route on a map in the MapControl

To display a MapRoute on a MapControl, construct a MapRouteView with the MapRoute. Then add the MapRouteView to the Routes collection of the MapControl.

Note that you have to provide the authentication token in two separate properties in an app that uses both Map services and the Map control.

This example assumes that the page contains a MapControl named MapWithRoute to display the route.

        private async void ShowRouteOnMap()
        {
            // Get a route as shown previously.
            ...

            if (routeResult.Status == MapRouteFinderStatus.Success)
            {
                // Use the route to initialize a MapRouteView.
                MapRouteView viewOfRoute = new MapRouteView(routeResult.Route);
                viewOfRoute.RouteColor = Colors.Yellow;
                viewOfRoute.OutlineColor = Colors.Black;

                // Add the new MapRouteView to the Routes collection
                // of the MapControl.
                MapWithRoute.Routes.Add(viewOfRoute);

                // Fit the MapControl to the route.
                await MapWithRoute.TrySetViewBoundsAsync(
                    routeResult.Route.BoundingBox,
                    null,
                    Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None);
            }
        }
    }
}

This code displays the following results:

Testing a route in the Emulator

Use the Location tab on the Additional Tools page of the emulator to test how your app handles the simulated traversal of a route. For more info, see Test app features in Windows Phone Emulator.

How to get locations and addresses

How to display maps and directions in the built-in Maps app

How to display maps in the Map control

How to authenticate a Maps app