Compartilhar via


Exibir rotas e direções em um mapa

Importante

Desativação do serviço Bing Maps para empresas

O UWP MapControl e os serviços de mapa do namespace Windows.Services.Maps dependem do Bing Maps. O Bing Maps for Enterprise foi preterido e será desativado, momento em que o MapControl e os serviços não receberão mais dados.

Para obter mais informações, consulte a documentação da Central de Desenvolvedores do Bing Maps e do Bing Maps.

Observação

O MapControl e os serviços de mapa exigem uma chave de autenticação de mapas chamada MapServiceToken. Para saber mais sobre como obter e definir uma chave de autenticação de mapas, consulte Solicitar uma chave de autenticação de mapas.

Solicite rotas e trajetos e exiba-os no aplicativo.

Observação

Se o mapeamento não for um recurso principal do seu aplicativo, considere iniciar o aplicativo Windows Mapas. Você pode usar os bingmaps:esquemas de ms-drive-to:, e ms-walk-to: URI para iniciar o aplicativo Windows Mapas para mapas específicos e direções passo a passo. Para saber mais, consulte Iniciar o aplicativo Mapas do Windows.

Uma introdução aos resultados do MapRouteFinder

Veja como as classes de rotas e direções estão relacionadas:

Obtenha uma rota e direções de carro ou a pé chamando os métodos da classe MapRouteFinder. Por exemplo, GetDrivingRouteAsync ou GetWalkingRouteAsync.

Ao solicitar uma rota, você pode especificar o seguinte:

  • Você pode fornecer apenas um ponto inicial e um ponto final ou pode fornecer uma série de pontos de referência para calcular a rota.

    Os pontos de passagem de parada adicionam trechos de rota adicionais, cada um com seu próprio itinerário. Para especificar pontos de passagem de parada , use qualquer uma das sobrecargas GetDrivingRouteFromWaypointsAsync .

    Via waypoint define locais intermediários entre waypoints de parada . Eles não adicionam trechos de rota. Eles são apenas pontos de passagem pelos quais uma rota deve passar. Para especificar pontos de passagem, use qualquer uma das sobrecargas GetDrivingRouteFromEnhancedWaypointsAsync.

  • Você pode especificar otimizações (por exemplo: minimizar a distância).

  • Você pode especificar restrições (por exemplo: evitar rodovias).

Exibir direções

O objeto MapRouteFinderResult contém um objeto MapRoute que você pode acessar por meio de sua propriedade Route.

O MapRoute calculado tem propriedades que fornecem o tempo para percorrer a rota, o comprimento da rota e a coleção de objetos MapRouteLeg que contêm os trechos da rota. Cada objeto MapRouteLeg contém uma coleção de objetos MapRouteManeuver . O objeto MapRouteManeuver contém direções que você pode acessar por meio de sua propriedade InstructionText.

Importante

Você deve especificar uma chave de autenticação de mapas antes de poder utilizar os serviços de mapa. Para obter mais informações, consulte Solicitar uma chave de autenticação de mapas.

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

Este exemplo exibe os seguintes resultados na tbOutputText caixa de texto.

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.

Exibir rotas

Para exibir um MapRoute em um MapControl, construa um MapRouteView com o MapRoute. Em seguida, adicione o MapRouteView à coleção Routes do MapControl.

Importante

Você deve especificar uma chave de autenticação de mapas antes de poder usar os serviços de mapa ou o controle de mapa. Para obter mais informações, consulte Solicitar uma chave de autenticação de mapas.

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

Este exemplo exibe o seguinte em um MapControl chamado MapWithRoute.

Controle de mapa com rota exibida.

Aqui está uma versão deste exemplo que usa um waypoint via entre dois waypoints de parada :

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