在地圖上顯示路線和路線指引Display routes and directions on a map

注意

隨 mapcontrol 和地圖服務會 Requite 稱為 MapServiceToken的地圖服務驗證金鑰。MapControl and map services requite a maps authentication key called a MapServiceToken. 如需有關取得及設定地圖驗證金鑰的詳細資訊,請參閱要求地圖驗證金鑰For more info about getting and setting a maps authentication key, see Request a maps authentication key.

要求路線和路線指引,並在應用程式中加以顯示。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. 如果地圖功能不是您 app 的核心功能,請考慮改為啟動 Windows 地圖 app。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 地圖 app 啟動到特定的地圖和轉向建議路線。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 waypoints adds additional route legs, each with their own Itinerary. 若要指定停止導航點,可使用任何的 GetDrivingRouteFromWaypointsAsync 多載。To specify stop waypoints, use any of the GetDrivingRouteFromWaypointsAsync overloads.

    透過導航點定義停止導航點之間的中繼位置。Via waypoint defines intermediate locations between stop waypoints. 它們不會新增路線區段。They do not add route legs. 它們只是路線必須經過的導航點。They are merely waypoints that a route must pass through. 若要指定經由導航點,可使用任何的 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 物件包含您可以透過其 Route 屬性存取的 MapRoute 物件。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.

顯示路線的地圖控制項。

以下是此範例的版本,其使用兩個停止個導航點之間的經由導航點: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);
  }
}