Routenmatrix abrufen

Entwickler im Europäischen Wirtschaftsraum (EWR)

Eine Routenmatrix ist ein zweidimensionales Array mit Routeninformationen, wobei die Zeilen den Startorten und die Spalten den Zielorten entsprechen. Anhand einer Liste von Start- und Zielorten berechnet die Klasse „Route Matrix“ die Entfernung und Dauer einer Route, die an jedem Startort beginnt und an jedem Zielort endet. Mit der Klasse „Route Matrix“ können Sie die Entfernung und Dauer einer Route für mehrere Start- und Zielorte berechnen.

Vollständigen Quellcode des Beispiels ansehen

In diesem Beispiel wird gezeigt, wie Sie mit der Klasse „Route Matrix“ die Entfernungen und Dauern für Reisen zwischen mehreren Start- und Zielorten berechnen.

TypeScript

// Initialize and add the map.
let map: google.maps.Map;
const markers: google.maps.marker.AdvancedMarkerElement[] = [];
const center = { lat: 51.55, lng: -1.8 };

async function init(): Promise<void> {
    //  Request the needed libraries.
    const [
        { Map },
        { Place },
        { AdvancedMarkerElement, PinElement },
        { RouteMatrix },
        { LatLngBounds, UnitSystem },
    ] = await Promise.all([
        google.maps.importLibrary('maps'),
        google.maps.importLibrary('places'),
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('routes'),
        google.maps.importLibrary('core'),
    ]);

    const bounds = new LatLngBounds();

    map = new Map(document.getElementById('map')!, {
        zoom: 8,
        center,
        mapId: 'DEMO_MAP_ID',
    });

    // Build the request using Place instances.
    const origin1 = new Place({
        id: 'ChIJ83WZp86p2EcRbMrkYqGncBQ', // Greenwich, London, UK
    });
    const origin2 = new Place({
        id: 'ChIJCSkVvleJc0gR8HHaTGpajKc', // Southampton, UK
    });
    const destinationA = new Place({
        id: 'ChIJYdizgWaDcUgRH9eaSy6y5I4', // Bristol, UK
    });
    const destinationB = new Place({
        id: 'ChIJ9VPsNNQCbkgRDmeGZdsGNBQ', // Cardiff, UK
    });

    await Promise.all([
        origin1.fetchFields({ fields: ['location', 'displayName'] }),
        origin2.fetchFields({ fields: ['location', 'displayName'] }),
        destinationA.fetchFields({ fields: ['location', 'displayName'] }),
        destinationB.fetchFields({ fields: ['location', 'displayName'] }),
    ]);

    const destinations = [destinationA, destinationB];
    const origins = [origin1, origin2];
    const request: google.maps.routes.ComputeRouteMatrixRequest = {
        origins,
        destinations,
        travelMode: 'DRIVING',
        units: UnitSystem.METRIC,
        fields: ['distanceMeters', 'durationMillis', 'condition'],
    };

    // Show the request.
    document.getElementById('request')!.innerText = JSON.stringify(
        request,
        null,
        2
    );

    // Get the RouteMatrix response.
    const response = await RouteMatrix.computeRouteMatrix(request);

    // Show the response.
    document.getElementById('response')!.innerText = JSON.stringify(
        response,
        null,
        2
    );

    // Add markers for the origins.
    for (const origin of origins) {
        if (origin.location) {
            const pin = new PinElement({
                glyphText: 'O',
                glyphColor: 'white',
                background: '#137333',
                borderColor: 'white',
            });
            const marker = new AdvancedMarkerElement({
                map,
                position: origin.location,
                title: `Origin: ${origin.displayName}`,
            });
            marker.append(pin);
            markers.push(marker);
            bounds.extend(origin.location);
        }
    }

    // Add markers for the destinations.
    for (const destination of destinations) {
        if (destination.location) {
            const pin = new PinElement({
                glyphText: 'D',
                glyphColor: 'white',
                background: '#C5221F',
                borderColor: 'white',
            });

            const marker = new AdvancedMarkerElement({
                map,
                position: destination.location,
                content: pin,
                title: `Destination: ${destination.displayName ?? 'Unknown'}`,
            });

            markers.push(marker);
            bounds.extend(destination.location);
        }
    }

    // Fit the map to the bounds of all markers.
    map.fitBounds(bounds);
}

void init();

JavaScript

// Initialize and add the map.
let map;
const markers = [];
const center = { lat: 51.55, lng: -1.8 };

async function init() {
    //  Request the needed libraries.
    const [
        { Map },
        { Place },
        { AdvancedMarkerElement, PinElement },
        { RouteMatrix },
        { LatLngBounds, UnitSystem },
    ] = await Promise.all([
        google.maps.importLibrary('maps'),
        google.maps.importLibrary('places'),
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('routes'),
        google.maps.importLibrary('core'),
    ]);

    const bounds = new LatLngBounds();

    map = new Map(document.getElementById('map'), {
        zoom: 8,
        center,
        mapId: 'DEMO_MAP_ID',
    });

    // Build the request using Place instances.
    const origin1 = new Place({
        id: 'ChIJ83WZp86p2EcRbMrkYqGncBQ', // Greenwich, London, UK
    });
    const origin2 = new Place({
        id: 'ChIJCSkVvleJc0gR8HHaTGpajKc', // Southampton, UK
    });
    const destinationA = new Place({
        id: 'ChIJYdizgWaDcUgRH9eaSy6y5I4', // Bristol, UK
    });
    const destinationB = new Place({
        id: 'ChIJ9VPsNNQCbkgRDmeGZdsGNBQ', // Cardiff, UK
    });

    await Promise.all([
        origin1.fetchFields({ fields: ['location', 'displayName'] }),
        origin2.fetchFields({ fields: ['location', 'displayName'] }),
        destinationA.fetchFields({ fields: ['location', 'displayName'] }),
        destinationB.fetchFields({ fields: ['location', 'displayName'] }),
    ]);

    const destinations = [destinationA, destinationB];
    const origins = [origin1, origin2];
    const request = {
        origins,
        destinations,
        travelMode: 'DRIVING',
        units: UnitSystem.METRIC,
        fields: ['distanceMeters', 'durationMillis', 'condition'],
    };

    // Show the request.
    document.getElementById('request').innerText = JSON.stringify(
        request,
        null,
        2
    );

    // Get the RouteMatrix response.
    const response = await RouteMatrix.computeRouteMatrix(request);

    // Show the response.
    document.getElementById('response').innerText = JSON.stringify(
        response,
        null,
        2
    );

    // Add markers for the origins.
    for (const origin of origins) {
        if (origin.location) {
            const pin = new PinElement({
                glyphText: 'O',
                glyphColor: 'white',
                background: '#137333',
                borderColor: 'white',
            });
            const marker = new AdvancedMarkerElement({
                map,
                position: origin.location,
                title: `Origin: ${origin.displayName}`,
            });
            marker.append(pin);
            markers.push(marker);
            bounds.extend(origin.location);
        }
    }

    // Add markers for the destinations.
    for (const destination of destinations) {
        if (destination.location) {
            const pin = new PinElement({
                glyphText: 'D',
                glyphColor: 'white',
                background: '#C5221F',
                borderColor: 'white',
            });

            const marker = new AdvancedMarkerElement({
                map,
                position: destination.location,
                content: pin,
                title: `Destination: ${destination.displayName ?? 'Unknown'}`,
            });

            markers.push(marker);
            bounds.extend(destination.location);
        }
    }

    // Fit the map to the bounds of all markers.
    map.fitBounds(bounds);
}

void init();

CSS

/*
 * Always set the map height explicitly to define the size of the div element
 * that contains the map.
 */
/* Optional: Makes the sample page fill the window. */
html,
body {
    height: 100%;
    margin: 0;
    padding: 0;
}

#container {
    height: 100%;
    display: flex;
}

#sidebar {
    flex-basis: 15rem;
    flex-grow: 1;
    padding: 1rem;
    max-width: 30rem;
    height: 100%;
    box-sizing: border-box;
    overflow: auto;
}

#map {
    flex-basis: 0;
    flex-grow: 4;
    height: 100%;
}

#sidebar {
    flex-direction: column;
}

HTML

<html>
    <head>
        <title>Route matrix</title>

        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script type="module" src="./index.js"></script>
        <script>
            // prettier-ignore
            (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
                key: "GOOGLE_MAPS_API_KEY"
            });
        </script>
    </head>
    <body>
        <div id="container">
            <div id="map"></div>
            <div id="sidebar">
                <h3 style="flex-grow: 0">Request</h3>
                <pre style="flex-grow: 1" id="request"></pre>
                <h3 style="flex-grow: 0">Response</h3>
                <pre style="flex-grow: 1" id="response"></pre>
            </div>
        </div>
    </body>
</html>

Anfragelimits

Die computeRouteMatrix Methode erzwingt die folgenden Anfrage Limits für Wegpunkte mit Adress- oder Ortsinstanzen und für Elemente. Elemente sind die Routen zwischen den einzelnen Start- und Zielorten in einer Routenmatrix. Die Anzahl der Elemente entspricht also der Anzahl der Startorte multipliziert mit der Anzahl der Zielorte. Wenn Sie beispielsweise 10 Startorte und 10 Zielorte haben, gibt es 100 Elemente:

  • Die Anzahl der Elemente darf für Routen, die keine TRANSIT Routen sind, 625 nicht überschreiten.
  • Wenn Sie eine TRANSIT Route angeben, darf die Anzahl der Elemente 100 nicht überschreiten.
  • Wenn Sie TRAFFIC_AWARE_OPTIMAL angeben, darf die Anzahl der Elemente 100 nicht überschreiten.
  • Wenn Sie Start- oder Zielorte mit Adressen oder Ortsinstanzen angeben, können Sie auf diese Weise insgesamt bis zu 50 angeben.

Weitere Informationen finden Sie unter Route mit öffentlichen Verkehrsmitteln abrufen.

Beispiel für eine Routenmatrixanfrage

Das folgende Beispiel zeigt eine ComputeRouteMatrixRequest. Dieses Beispiel tut Folgendes:

  • Es wird gezeigt, wie ein Array mit zwei Start- und zwei Zielwegpunkten angegeben wird. Die Methode berechnet eine Route von jedem Startort zu jedem Zielort. Die Antwort enthält also vier Routen.
    Im Array befindet sich das erste Element an Index 0, das zweite an Index 1 usw.
  • Gibt die zurückzugebenden Felder an. In diesem Beispiel ist die Anfrage so konfiguriert, dass für jede Route durationMillis, distanceMeters und condition zurückgegeben werden.

TypeScript

const destinations = [destinationA, destinationB];
const origins = [origin1, origin2];
const request: google.maps.routes.ComputeRouteMatrixRequest = {
    origins,
    destinations,
    travelMode: 'DRIVING',
    units: UnitSystem.METRIC,
    fields: ['distanceMeters', 'durationMillis', 'condition'],
};

JavaScript

const destinations = [destinationA, destinationB];
const origins = [origin1, origin2];
const request = {
    origins,
    destinations,
    travelMode: 'DRIVING',
    units: UnitSystem.METRIC,
    fields: ['distanceMeters', 'durationMillis', 'condition'],
};

Die Antwort enthält die vier möglichen Routen für die Kombination aller Start- und Zielwegpunkte, wie im folgenden Beispiel gezeigt:

"matrix": {
  "rows": [
    {
      "items": [
        {
          "condition": "ROUTE_EXISTS",
          "distanceMeters": 202587,
          "durationMillis": 10040000
        },
        {
          "condition": "ROUTE_EXISTS",
          "distanceMeters": 252734,
          "durationMillis": 12240000
        }
      ]
    },
    {
      "items": [
        {
          "condition": "ROUTE_EXISTS",
          "distanceMeters": 166135,
          "durationMillis": 6596000
        },
        {
          "condition": "ROUTE_EXISTS",
          "distanceMeters": 216282,
          "durationMillis": 8797000
        }
      ]
    }
  ]
}
    

Identifizieren Sie jede Route im Ergebnis, indem Sie mit dem Start- und Zielindex das entsprechende RouteMatrixItem im 2D-Array suchen. Das RouteMatrixItem das die Route beschreibt, die vom Startort an Index 1 und Zielort 0 in der Anfrage berechnet wurde, befindet sich beispielsweise im zweiten Element des RouteMatrix.rows Arrays und im ersten Element des RouteMatrixRow.items Arrays.

Das folgende Code-Snippet zeigt, wie Sie das RouteMatrixItem identifizieren, um die Route für einen bestimmten Start- und Zielort zu finden:

// Find the route for origin 'x' and destination 'y'.
const {matrix} = await RouteMatrix.computeRouteMatrix(request);
const myRouteMatrixItem = matrix.rows[x].items[y];
    

Zurückzugebende Felder auswählen

Wenn Sie eine Routenmatrix anfordern, müssen Sie mit einer Feldmaske angeben, welche Informationen in der Antwort zurückgegeben werden sollen.

Mit einer Feldmaske lässt sich auch verhindern, dass unnötige Daten angefordert werden, was wiederum die Antwortlatenz verbessert und vermeidet, dass Informationen zurückgegeben werden, die Ihr System nicht benötigt.

Geben Sie die Liste der benötigten Felder an, indem Sie das ComputeRoutesMatrixRequest.fields Attribut festlegen, wie im folgenden Snippet gezeigt:

fields: ['durationMillis', 'distanceMeters', 'condition'],
    

Zu verwendende Feldmasken festlegen

So können Sie festlegen, welche Felder Sie verwenden möchten, und die Feldmasken dafür erstellen:

  1. Fordern Sie alle Felder an , indem Sie die Feldmaske ['*'] verwenden.
  2. Sehen Sie sich die Hierarchie der Felder in der RouteMatrixItem Klasse für die gewünschten Felder an.
  3. Erstellen Sie Ihre Feldmasken anhand der Hierarchie der Felder aus dem vorherigen Schritt im folgenden Format:

    topLevelField[.secondLevelField][.thirdLevelField][...]

Beispiel für dieses RouteMatrixItem:

  "travelAdvisory": {
    "fuelConsumptionMicroliters": 0,
    "tollInfo": {
      "estimatedPrices": [
        {
          "currencyCode": "USD",
          "units": 4,
          "nanos": 400000000
        }
      ]
    }
  },
    

Wenn Sie nur das Feld tollInfo für das RouteMatrixItem, zurückgeben möchten, sieht Ihre Feldmaske so aus:

fields: ['travelAdvisory.tollInfo']

Wenn Sie stattdessen den geschätzten Kraftstoffverbrauch anfordern möchten, sieht Ihre Feldmaske so aus:

fields: ['travelAdvisory.fuelConsumptionMicroliters']

Wenn Sie beides anfordern möchten, sieht Ihre Feldmaske so aus:

fields: ['travelAdvisory.fuelConsumptionMicroliters', 'travelAdvisory.tollInfo']

Und wenn Sie alle Reisehinweise anfordern möchten, sieht Ihre Feldmaske so aus:

fields: ['travelAdvisory']

Routenmatrix mit öffentlichen Verkehrsmitteln anfordern

Rufen Sie eine Routenmatrix mit öffentlichen Verkehrsmitteln ab, die die in der Region verfügbaren Optionen für öffentliche Verkehrsmittel verwendet. Zu den Optionen für öffentliche Verkehrsmittel gehören unter anderem Busse, U-Bahnen und Züge. So fordern Sie eine Routenmatrix mit öffentlichen Verkehrsmitteln an:

  • Legen Sie travelMode auf TRANSIT fest.
  • Fordern Sie das Feld travelAdvisory an.

Weitere Informationen zu Routen mit öffentlichen Verkehrsmitteln