ルート マトリックスを取得する

欧州経済領域(EEA)のデベロッパー

ルート マトリックスは、ルート情報の 2 次元配列です。行は出発地に対応し、列は目的地に対応します。ルート マトリックス クラスは、出発地と目的地のリストを受け取り、各出発地から各目的地に至るルートの距離と所要時間を計算します。Route Matrix クラスを使用して、複数の出発地と目的地のルートの距離と所要時間を計算します。

サンプル ソースコードの全文を見る

この例では、Route Matrix クラスを使用して、複数の出発地と目的地の間の移動距離と所要時間を計算する方法を示します。

TypeScript

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

async function initMap(): Promise<void> {
  //  Request the needed libraries.
  //@ts-ignore
  const [{Map}, {Place}, {AdvancedMarkerElement, PinElement}, {RouteMatrix}] = await Promise.all([
    google.maps.importLibrary('maps') as Promise<google.maps.MapsLibrary>,
    google.maps.importLibrary('places') as Promise<google.maps.PlacesLibrary>,
    google.maps.importLibrary('marker') as Promise<google.maps.MarkerLibrary>,
    google.maps.importLibrary('routes') as Promise<google.maps.RoutesLibrary>
  ]);

  const bounds = new google.maps.LatLngBounds();

  map = new Map(document.getElementById('map') as HTMLElement, {
    zoom: 8,
    center: 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 request = {
    origins: [origin1, origin2], 
    destinations: [destinationA, destinationB],
    travelMode: 'DRIVING',
    units: google.maps.UnitSystem.METRIC,
    fields: ['distanceMeters', 'durationMillis', 'condition'],
  };

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

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

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

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

  // Add markers for the destinations.
  for (let i = 0; i < request.destinations.length; i++) {
    const destination = request.destinations[i];
    if (destination.location) {
      const pin = new PinElement({
        //@ts-ignore
        glyphText: "D",
        glyphColor: "white",
        background: "#C5221F",
        borderColor: "white",
      });

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

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

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

initMap();

JavaScript

// Initialize and add the map.
let map;
let markers = [];
let center = { lat: 51.55, lng: -1.8 };
async function initMap() {
    //  Request the needed libraries.
    //@ts-ignore
    const [{ Map }, { Place }, { AdvancedMarkerElement, PinElement }, { RouteMatrix }] = await Promise.all([
        google.maps.importLibrary('maps'),
        google.maps.importLibrary('places'),
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('routes')
    ]);
    const bounds = new google.maps.LatLngBounds();
    map = new Map(document.getElementById('map'), {
        zoom: 8,
        center: 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 request = {
        origins: [origin1, origin2],
        destinations: [destinationA, destinationB],
        travelMode: 'DRIVING',
        units: google.maps.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 request.origins) {
        if (origin.location) {
            const pin = new PinElement({
                //@ts-ignore
                glyphText: "O",
                glyphColor: "white",
                background: "#137333",
                borderColor: "white",
            });
            const marker = new AdvancedMarkerElement({
                map,
                position: origin.location,
                content: pin.element,
                title: `Origin: ${origin.displayName}`,
            });
            markers.push(marker);
            bounds.extend(origin.location);
        }
    }
    // Add markers for the destinations.
    for (let i = 0; i < request.destinations.length; i++) {
        const destination = request.destinations[i];
        if (destination.location) {
            const pin = new PinElement({
                //@ts-ignore
                glyphText: "D",
                glyphColor: "white",
                background: "#C5221F",
                borderColor: "white",
            });
            const marker = new AdvancedMarkerElement({
                map,
                position: destination.location,
                content: pin.element,
                title: `Destination: ${destination.displayName}`,
            });
            markers.push(marker);
            bounds.extend(destination.location);
        }
    }
    // Fit the map to the bounds of all markers.
    map.fitBounds(bounds);
}
initMap();

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>
  </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>
    <!-- prettier-ignore -->
    <script>(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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "beta"});</script>
  </body>
</html>

サンプルを試す

リクエストに関する上限

computeRouteMatrix メソッドでは、住所または Place インスタンスを使用するウェイポイントとアイテムに対して、以下のリクエスト制限が適用されます。アイテムは、ルート マトリックス内の各出発地と目的地間のルートであるため、アイテム数は出発地の数×目的地の数になります。たとえば、出発地が 10 個、目的地が 10 個ある場合、アイテムは 100 個になります。

  • アイテムの数は、TRANSIT ルート以外のルートの場合、625 個以下にする必要があります。
  • TRANSIT ルートを指定する場合、アイテム数は 100 個以下にする必要があります。
  • TRAFFIC_AWARE_OPTIMAL を指定した場合、アイテム数は 100 個以下にする必要があります。
  • 住所または Place インスタンスで出発地または目的地を指定する場合、合計 50 件まで指定できます。

詳細については、公共交通機関のルートを取得するをご覧ください。

ルート マトリックス リクエストの例

次の例は、ComputeRouteMatrixRequest を示しています。この例では、次の操作を行います。

  • 出発地と目的地の 2 つの経由地を指定する様子を示しています。このメソッドは、各出発地から各目的地までのルートを計算するため、レスポンスには 4 つのルートが含まれます。
    配列では、最初の要素はインデックス 0、2 番目の要素はインデックス 1 です。以降も同様です。
  • 返すフィールドを指定します。この例では、各ルートの durationMillisdistanceMeterscondition を返すようにリクエストが構成されています。

TypeScript

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

JavaScript

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

レスポンスには、次の例に示すように、すべての出発地と目的地のウェイポイントの組み合わせによる 4 つのルートが含まれます。

"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
        }
      ]
    }
  ]
}
    

結果の各ルートを識別するには、出発地と目的地のインデックスを使用して、2 次元配列内の対応する RouteMatrixItem を見つけます。たとえば、リクエストのインデックス 1 の出発地とインデックス 0 の目的地から計算されたルートを記述する RouteMatrixItem は、RouteMatrix.rows 配列の 2 番目の要素と RouteMatrixRow.items 配列の 1 番目の要素にあります。

次のコード スニペットは、特定の出発地と目的地のルートを見つけるために RouteMatrixItem を特定する方法を示しています。

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

返すフィールドを選択する

ルート マトリックスをリクエストする場合は、フィールド マスクを使用して、レスポンスで返す情報を指定する必要があります。

フィールド マスクを使用すると、不要なデータをリクエストしないようにすることもできます。これにより、レスポンス レイテンシが短縮され、システムで不要な情報が返されるのを防ぐことができます。

次のスニペットに示すように、 ComputeRoutesMatrixRequest.fields プロパティを設定して、必要なフィールドのリストを指定します。

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

使用するフィールド マスクを決定する

使用するフィールドを特定し、それらのフィールドのフィールド マスクを作成する方法は次のとおりです。

  1. フィールド マスク ['*'] を使用してすべてのフィールドをリクエストします。
  2. 必要なフィールドの RouteMatrixItem クラスでフィールドの階層を確認します
  3. 前の手順で示したフィールドの階層を使用して、次の形式でフィールド マスクを作成します

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

たとえば、次の RouteMatrixItem の場合:

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

RouteMatrixItemtollInfo フィールドのみを返す場合は、フィールド マスクは次のようになります。

fields: ['travelAdvisory.tollInfo']

代わりに推定燃料消費量をリクエストする場合は、フィールド マスクは次のようになります。

fields: ['travelAdvisory.fuelConsumptionMicroliters']

両方をリクエストする場合は、フィールド マスクは次のようになります。

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

旅行に関する注意情報の完全なセットをリクエストする場合は、フィールド マスクは次のようになります。

fields: ['travelAdvisory']

公共交通機関のルート マトリックスをリクエストする

地域で利用可能な公共交通機関のオプションを使用する公共交通機関のルート マトリックスを取得します。公共交通機関のオプションには、バス、地下鉄、電車などが含まれます。公共交通機関のルート マトリックスをリクエストするには:

  • travelModeTRANSIT に設定します。
  • travelAdvisory フィールドをリクエストします。

詳しくは、公共交通機関の経路をご覧ください。