Anzeigen einer Wegbeschreibung von A nach B

In diesem Artikel erfahren Sie, wie Sie eine Route anfordern und die Route auf der Karte anzeigen.

Dafür gibt es zwei Möglichkeiten. Die erste Möglichkeit besteht darin, die API zum Abrufen von Wegbeschreibungen mithilfe des TypeScript REST SDK @azure-rest/maps-route abzufragen. Die zweite Möglichkeit besteht in der Verwendung der Fetch-API, um eine Suchanforderung an die API zum Abrufen von Wegbeschreibungen zu stellen. Beide Ansätze werden in diesem Artikel beschrieben.

Abfragen der Route über das REST SDK

import * as atlas from "azure-maps-control";
import MapsRoute, { toColonDelimitedLatLonString } from "@azure-rest/maps-route";
import "azure-maps-control/dist/atlas.min.css";

const onload = () => {
  // Initialize a map instance.
  const map = new atlas.Map("map", {
    view: "Auto",
    // Add authentication details for connecting to Azure Maps.
    authOptions: {
      // Use Azure Active Directory authentication.
      authType: "aad",
      clientId: "<Your Azure Maps Client Id>",
      aadAppId: "<Your Azure Active Directory Client Id>",
      aadTenant: "<Your Azure Active Directory Tenant Id>"
    }
  });

  map.events.add("load", async () => {
    // Use the access token from the map and create an object that implements the TokenCredential interface.
    const credential = {
      getToken: () => {
        return {
          token: map.authentication.getToken()
        };
      }
    };

    // Create a Route client.
    const client = MapsRoute(credential, "<Your Azure Maps Client Id>");

    // Create a data source and add it to the map.
    const dataSource = new atlas.source.DataSource();
    map.sources.add(dataSource);

    // Create the GeoJSON objects which represent the start and end points of the route.
    const startPoint = new atlas.data.Feature(new atlas.data.Point([-122.130137, 47.644702]), {
      title: "Redmond",
      icon: "pin-blue"
    });

    const endPoint = new atlas.data.Feature(new atlas.data.Point([-122.3352, 47.61397]), {
      title: "Seattle",
      icon: "pin-round-blue"
    });

    // Add the data to the data source.
    dataSource.add([startPoint, endPoint]);

    // Create a layer for rendering the route line under the road labels.
    map.layers.add(
      new atlas.layer.LineLayer(dataSource, null, {
        strokeColor: "#2272B9",
        strokeWidth: 5,
        lineJoin: "round",
        lineCap: "round"
      }),
      "labels"
    );

    // Create a layer for rendering the start and end points of the route as symbols.
    map.layers.add(
      new atlas.layer.SymbolLayer(dataSource, null, {
        iconOptions: {
          image: ["get", "icon"],
          allowOverlap: true,
          ignorePlacement: true
        },
        textOptions: {
          textField: ["get", "title"],
          offset: [0, 1.2]
        },
        filter: ["any", ["==", ["geometry-type"], "Point"], ["==", ["geometry-type"], "MultiPoint"]] //Only render Point or MultiPoints in this layer.
      })
    );

    // Get the coordinates of the start and end points.
    const coordinates = [
      [startPoint.geometry.coordinates[1], startPoint.geometry.coordinates[0]],
      [endPoint.geometry.coordinates[1], endPoint.geometry.coordinates[0]]
    ];

    // Get the route directions between the start and end points.
    const response = await client.path("/route/directions/{format}", "json").get({
      queryParameters: {
        query: toColonDelimitedLatLonString(coordinates)
      }
    });

    // Get the GeoJSON feature collection of the route.
    const data = getFeatures(response.body.routes);

    // Add the route data to the data source.
    dataSource.add(data);

    // Update the map view to center over the route.
    map.setCamera({
      bounds: data.bbox,
      padding: 40
    });
  });
};

/**
 * Helper function to convert a route response into a GeoJSON FeatureCollection.
 */
const getFeatures = (routes) => {
  const bounds = [];
  const features = routes.map((route, index) => {
    const multiLineCoords = route.legs.map((leg) => {
      return leg.points.map((coord) => {
        const position = [coord.longitude, coord.latitude];
        bounds.push(position);
        return position;
      });
    });

    // Include all properties on the route object except legs.
    // Legs is used to create the MultiLineString, so we only need the summaries.
    // The legSummaries property replaces the legs property with just summary data.
    const props = {
      ...route,
      legSummaries: route.legs.map((leg) => leg.summary),
      resultIndex: index
    };
    delete props.legs;

    return {
      type: "Feature",
      geometry: {
        type: "MultiLineString",
        coordinates: multiLineCoords
      },
      properties: props
    };
  });

  return {
    type: "FeatureCollection",
    features: features,
    bbox: new atlas.data.BoundingBox.fromLatLngs(bounds)
  };
};

document.body.onload = onload;

Im obigen Codebeispiel erstellt der erste Block ein Kartenobjekt und legt als Authentifizierungsmechanismus die Verwendung von Microsoft Entra ID fest. Eine Anleitung finden Sie unter Erstellen einer Karte.

Der zweite Codeblock erstellt ein Objekt, das die TokenCredential-Schnittstelle implementiert, um HTTP-Anforderungen an Azure Maps mit dem Zugriffstoken zu authentifizieren. Anschließend wird das Anmeldeinformationsobjekt an MapsRoute übergeben und eine Instanz des Clients erstellt.

Mit dem dritten Codeblock wird ein DataSource-Objekt erstellt und der Karte hinzugefügt.

Mit dem vierten Codeblock werden points-Objekte als Start- und Endpunkte erstellt und dem dataSource-Objekt hinzugefügt.

Eine Linie ist ein Feature-Objekt für LineString. Ein LineLayer-Objekt rendert Linienobjekte, die von DataSource umschlossen sind, als Linien in der Karte. Mit dem letzten Codeblock wird eine Linienebene erstellt und der Karte hinzugefügt. Die Eigenschaften einer Linienebene finden Sie unter LinestringLayerOptions.

Eine Symbolebene verwendet Text oder Symbole zum Rendern punktbasierter Daten, die in DataSource umschlossen sind. Die Texte oder Symbole werden als Symbole auf der Karte gerendert. Mit dem fünften Codeblock wird eine Symbolebene erstellt und der Karte hinzugefügt.

Mit dem sechsten Codeblock wird der Azure Maps-Routingdienst abgefragt, der Teil des MapsRoute-Clients ist. Eine GET-Anforderung wird genutzt, um eine Route zwischen den Start- und Endpunkten zu erhalten. Anschließend wird mit der Hilfsfunktion getFeatures() eine GeoJSON-Merkmalsauswahl extrahiert und der Datenquelle hinzugefügt. Anschließend wird die Antwort als Route in der Karte gerendert. Weitere Informationen zum Hinzufügen einer Linie zur Karte finden Sie unter Hinzufügen einer Linie zur Karte.

Mit dem letzten Codeblock werden die Grenzen der Karte mithilfe der setCamera-Eigenschaft der Karte festgelegt.

Die Routenabfrage, die Datenquelle, das Symbol, die Linienebenen und die Kameragrenzen werden innerhalb des Ereignislisteners erstellt. Diese Codestruktur stellt sicher, dass die Ergebnisse erst nach dem vollständigen Laden der Karte angezeigt werden.

Abfragen der Route über die Fetch-API

import * as atlas from "azure-maps-control";
import "azure-maps-control/dist/atlas.min.css";

const onload = () => {
  // Initialize a map instance.
  const map = new atlas.Map("map", {
    view: "Auto",
    // Add authentication details for connecting to Azure Maps.
    authOptions: {
      // Use Azure Active Directory authentication.
      authType: "aad",
      clientId: "<Your Azure Maps Client Id>",
      aadAppId: "<Your Azure Active Directory Client Id>",
      aadTenant: "<Your Azure Active Directory Tenant Id>"
    }
  });

  map.events.add("load", async () => {
    // Create a data source and add it to the map.
    const dataSource = new atlas.source.DataSource();
    map.sources.add(dataSource);

    // Create the GeoJSON objects which represent the start and end points of the route.
    const startPoint = new atlas.data.Feature(new atlas.data.Point([-122.130137, 47.644702]), {
      title: "Redmond",
      icon: "pin-blue"
    });

    const endPoint = new atlas.data.Feature(new atlas.data.Point([-122.3352, 47.61397]), {
      title: "Seattle",
      icon: "pin-round-blue"
    });

    // Add the data to the data source.
    dataSource.add([startPoint, endPoint]);

    // Create a layer for rendering the route line under the road labels.
    map.layers.add(
      new atlas.layer.LineLayer(dataSource, null, {
        strokeColor: "#2272B9",
        strokeWidth: 5,
        lineJoin: "round",
        lineCap: "round"
      }),
      "labels"
    );

    // Create a layer for rendering the start and end points of the route as symbols.
    map.layers.add(
      new atlas.layer.SymbolLayer(dataSource, null, {
        iconOptions: {
          image: ["get", "icon"],
          allowOverlap: true,
          ignorePlacement: true
        },
        textOptions: {
          textField: ["get", "title"],
          offset: [0, 1.2]
        },
        filter: ["any", ["==", ["geometry-type"], "Point"], ["==", ["geometry-type"], "MultiPoint"]] //Only render Point or MultiPoints in this layer.
      })
    );

    // Send a request to the route API
    let url = "https://atlas.microsoft.com/route/directions/json?";
    url += "&api-version=1.0";
    url +=
      "&query=" +
      startPoint.geometry.coordinates[1] +
      "," +
      startPoint.geometry.coordinates[0] +
      ":" +
      endPoint.geometry.coordinates[1] +
      "," +
      endPoint.geometry.coordinates[0];

    // Process request
    fetch(url, {
      headers: {
        Authorization: "Bearer " + map.authentication.getToken(),
        "x-ms-client-id": "<Your Azure Maps Client Id>"
      }
    })
      .then((response) => response.json())
      .then((response) => {
        const bounds = [];
        const route = response.routes[0];
        
        // Create an array to store the coordinates of each turn
        let routeCoordinates = [];
        route.legs.forEach((leg) => {
          const legCoordinates = leg.points.map((point) => {
            const position = [point.longitude, point.latitude];
            bounds.push(position);
            return position;
          });
          // Add each turn coordinate to the array
          routeCoordinates = routeCoordinates.concat(legCoordinates);
        });

        // Add route line to the dataSource
        dataSource.add(new atlas.data.Feature(new atlas.data.LineString(routeCoordinates)));

        // Update the map view to center over the route.
        map.setCamera({
          bounds: new atlas.data.BoundingBox.fromLatLngs(bounds),
          padding: 40
        });
      });
  });
};

document.body.onload = onload;

Im obigen Codebeispiel erstellt der erste Codeblock ein Kartenobjekt und legt als Authentifizierungsmechanismus die Verwendung von Microsoft Entra ID fest. Eine Anleitung finden Sie unter Erstellen einer Karte.

Mit dem zweiten Codeblock wird ein DataSource-Objekt erstellt und der Karte hinzugefügt.

Mit dem dritten Codeblock werden die Start- und Zielpunkte für die Route erstellt. Anschließend werden sie der Datenquelle hinzugefügt. Weitere Informationen finden Sie unter Hinzufügen eines Pins auf der Karte.

Ein LineLayer-Objekt rendert Linienobjekte, die von DataSource umschlossen sind, als Linien in der Karte. Mit dem letzten Codeblock wird eine Linienebene erstellt und der Karte hinzugefügt. Die Eigenschaften einer Linienebene finden Sie unter LineLayerOptions.

Eine Symbolebene verwendet Text oder Symbole zum Rendern punktbasierter Daten, die in DataSource als Symbole auf der Karte umschlossen sind. Mit dem fünften Codeblock wird eine Symbolebene erstellt und der Karte hinzugefügt. Die Eigenschaften einer Symbolebene finden Sie unter SymbolLayerOptions.

Der nächste Codeblock verwendet die Fetch-API für eine Suchanforderung an Wegbeschreibungen abrufen. Die Antwort wird dann analysiert. Bei einer erfolgreichen Antwort wird anhand der Breiten- und Längengradinformationen ein Array mit Linien erstellt, indem diese Punkte verbunden werden. Die Liniendaten werden dann der Datenquelle hinzugefügt, um die Route in der Karte zu rendern. Weitere Informationen finden Sie unter Hinzufügen einer Linie auf der Karte.

Mit dem letzten Codeblock werden die Grenzen der Karte mithilfe der setCamera-Eigenschaft der Karte festgelegt.

Die Routenabfrage, die Datenquelle, das Symbol, die Linienebenen und die Kameragrenzen werden innerhalb des Ereignislisteners erstellt. Auch hier möchten wir sicherstellen, dass die Ergebnisse nach dem vollständigen Laden der Karte angezeigt werden.

Die folgende Abbildung ist ein Screenshot, der die Ergebnisse der beiden Codebeispiele zeigt:

A screenshot of a map showing route directions between two points.

Nächste Schritte

Erfahren Sie mehr zu den in diesem Artikel verwendeten Klassen und Methoden:

Map

Die folgenden Artikel enthalten vollständige Codebeispiele: