在地图上显示路线和方向Display routes and directions on a map

请求路线和方向并在应用中显示它们。Request routes and directions, and display them in your app.

备注

若要了解有关在应用中使用地图的详细信息,请下载通用 Windows 平台 (UWP) 地图示例To learn more about using maps in your app, download the Universal Windows Platform (UWP) map sample. 如果映射不是你的应用的核心功能,请考虑改为启动 Windows 地图应用。If mapping isn't a core feature of your app, consider launching the Windows Maps app instead. 你可以使用 bingmaps:ms-drive-to:ms-walk-to: URI 方案来将 Windows 地图应用启动为特定的地图和路线规划。You can use the bingmaps:, ms-drive-to:, and ms-walk-to: URI schemes to launch the Windows Maps app to specific maps and turn-by-turn directions. 有关详细信息,请参阅启动 Windows 地图应用For more info, see Launch the Windows Maps app.

 

MapRouteFinder 结果简介An intro to MapRouteFinder results

下面介绍了路线的类如何与方向的类相关联:Here's how the classes for routes and directions are related:

通过调用 MapRouteFinder 类的方法,获取驾车或步行路线和方向。Get a driving or walking route and directions by calling the methods of the MapRouteFinder class. 例如,GetDrivingRouteAsyncGetWalkingRouteAsyncFor example, GetDrivingRouteAsync or GetWalkingRouteAsync.

在请求路线时,你可以指定以下操作: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.

    Stop 路点添加额外的路线行程,每一个都有自己的路线。Stop waypoints adds additional route legs, each with their own Itinerary. 若要指定 stop 路点,请使用任一 GetDrivingRouteFromWaypointsAsync 重载。To specify stop waypoints, use any of the GetDrivingRouteFromWaypointsAsync overloads.

    Via 路点定义 stop 路点之间的中间位置。Via waypoint defines intermediate locations between stop waypoints. 它们不添加路线行程。They do not add route legs. 它们只是路线必须通过的路点。They are merely waypoints that a route must pass through. 若要指定 via 路点,请使用任一 GetDrivingRouteFromEnhancedWaypointsAsync 重载。To specify via waypoints, use any of the GetDrivingRouteFromEnhancedWaypointsAsync overloads.

  • 你可以指定优化项(例如:最小化距离)。You can specify optimizations (For example: minimize the distance).

  • 你可以指定限制项(例如:避开高速公路)。You can specify restrictions (For example: avoid highways).

显示路线Display directions

MapRouteFinderResult 对象包含一个 MapRoute 对象,你可以通过其 Route 属性访问该对象。The MapRouteFinderResult object contains a MapRoute object that you can access through its Route property.

计算的 MapRoute 具有多个属性,可提供遍历该路线所需的时间、路线的长度以及包含路线段的 MapRouteLeg 对象的集合。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. 每个 MapRouteLeg 对象都包含 MapRouteManeuver 对象的集合。Each MapRouteLeg object contains a collection of MapRouteManeuver objects. MapRouteManeuver 对象包含可以通过其 InstructionText 属性进行访问的路线。The MapRouteManeuver object contains directions that you can access through its InstructionText property.

重要

必须先指定地图验证密钥,才能使用地图服务。You must specify a maps authentication key before you can use map services. 有关详细信息,请参阅请求地图身份验证密钥For more info, see Request a maps authentication key.

 

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Services.Maps;
using Windows.Devices.Geolocation;
...
private async void button_Click(object sender, RoutedEventArgs e)
{
   // Start at Microsoft in Redmond, Washington.
   BasicGeoposition startLocation = new BasicGeoposition() {Latitude=47.643,Longitude=-122.131};

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

   // Get the route between the points.
   MapRouteFinderResult routeResult =
         await MapRouteFinder.GetDrivingRouteAsync(
         new Geopoint(startLocation),
         new Geopoint(endLocation),
         MapRouteOptimization.Time,
         MapRouteRestrictions.None);

   if (routeResult.Status == MapRouteFinderStatus.Success)
   {
      System.Text.StringBuilder routeInfo = new System.Text.StringBuilder();

      // Display summary info about the route.
      routeInfo.Append("Total estimated time (minutes) = ");
      routeInfo.Append(routeResult.Route.EstimatedDuration.TotalMinutes.ToString());
      routeInfo.Append("\nTotal length (kilometers) = ");
      routeInfo.Append((routeResult.Route.LengthInMeters / 1000).ToString());

      // Display the directions.
      routeInfo.Append("\n\nDIRECTIONS\n");

      foreach (MapRouteLeg leg in routeResult.Route.Legs)
      {
         foreach (MapRouteManeuver maneuver in leg.Maneuvers)
         {
            routeInfo.AppendLine(maneuver.InstructionText);
         }
      }

      // Load the text box.
      tbOutputText.Text = routeInfo.ToString();
   }
   else
   {
      tbOutputText.Text =
            "A problem occurred: " + routeResult.Status.ToString();
   }
}

此示例向 tbOutputText 文本框显示以下结果。This example displays the following results to the tbOutputText text box.

Total estimated time (minutes) = 18.4833333333333
Total length (kilometers) = 21.847

DIRECTIONS
Head north on 157th Ave NE.
Turn left onto 159th Ave NE.
Turn left onto NE 40th St.
Turn left onto WA-520 W.
Enter the freeway WA-520 from the right.
Keep left onto I-5 S/Portland.
Keep right and leave the freeway at exit 165A towards James St..
Turn right onto James St.
You have reached your destination.

显示路线Display routes

若要在 MapControl 上显示 MapRoute,请使用 MapRoute 构建一个 MapRouteViewTo display a MapRoute on a MapControl, construct a MapRouteView with the MapRoute. 然后,将 MapRouteView 添加到 MapControlRoutes 集合。Then, add the MapRouteView to the Routes collection of the MapControl.

重要

必须先指定地图身份验证密钥,然后才能使用地图服务或地图控件。You must specify a maps authentication key before you can use map services or the map control. 有关详细信息,请参阅请求地图身份验证密钥For more info, see Request a maps authentication key.

 

using System;
using Windows.Devices.Geolocation;
using Windows.Services.Maps;
using Windows.UI;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Maps;
...
private async void ShowRouteOnMap()
{
   // Start at Microsoft in Redmond, Washington.
   BasicGeoposition startLocation = new BasicGeoposition() { Latitude = 47.643, Longitude = -122.131 };

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


   // Get the route between the points.
   MapRouteFinderResult routeResult =
         await MapRouteFinder.GetDrivingRouteAsync(
         new Geopoint(startLocation),
         new Geopoint(endLocation),
         MapRouteOptimization.Time,
         MapRouteRestrictions.None);

   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);
   }
}

此示例在名为 MapWithRouteMapControl 上显示以下内容。This example displays the following on a MapControl named MapWithRoute.

显示路线的地图控件。

下面是使用两个 stop 路点之间的 via 路点的示例版本:Here's a version of this example that uses a via waypoint in between two stop waypoints:

using System;
using Windows.Devices.Geolocation;
using Windows.Services.Maps;
using Windows.UI;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Maps;
...
private async void ShowRouteOnMap()
{
  Geolocator locator = new Geolocator();
  locator.DesiredAccuracyInMeters = 1;
  locator.PositionChanged += Locator_PositionChanged;

  BasicGeoposition point1 = new BasicGeoposition() { Latitude = 47.649693, Longitude = -122.144908 };
  BasicGeoposition point2 = new BasicGeoposition() { Latitude = 47.6205, Longitude = -122.3493 };
  BasicGeoposition point3 = new BasicGeoposition() { Latitude = 48.649693, Longitude = -122.144908 };

  // Get Driving Route from point A  to point B thru point C
  var path = new List<EnhancedWaypoint>();

  path.Add(new EnhancedWaypoint(new Geopoint(point1), WaypointKind.Stop));
  path.Add(new EnhancedWaypoint(new Geopoint(point2), WaypointKind.Via));
  path.Add(new EnhancedWaypoint(new Geopoint(point3), WaypointKind.Stop));

  MapRouteFinderResult routeResult =  await MapRouteFinder.GetDrivingRouteFromEnhancedWaypointsAsync(path);

  if (routeResult.Status == MapRouteFinderStatus.Success)
  {
      MapRouteView viewOfRoute = new MapRouteView(routeResult.Route);
      viewOfRoute.RouteColor = Colors.Yellow;
      viewOfRoute.OutlineColor = Colors.Black;

      myMap.Routes.Add(viewOfRoute);

      await myMap.TrySetViewBoundsAsync(
            routeResult.Route.BoundingBox,
            null,
            Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None);
  }
}