ルートとは、出発地(起点)と目的地(終点)の間のナビゲーション可能な経路です。徒歩、自転車、さまざまな種類の車両など、さまざまな移動手段のルートを取得できます。また、距離、ルートのナビゲーションの推定時間、予想される通行料金、ルートのナビゲーションの手順ガイドなど、ルートの詳細をリクエストすることもできます。
サンプル ソースコードの全文を見る
次のコードサンプルは、2 つの場所間の運転ルートを取得する方法を示しています。
TypeScript
// Initialize and add the map. let map: google.maps.Map; let mapPolylines: google.maps.Polyline[] = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function init(): Promise<void> { // Request the needed libraries. const [{ Map }, { Place }, { Route }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), google.maps.importLibrary('routes'), ]); map = new Map(document.getElementById('map')!, { zoom: 12, center, mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], }; console.log({ requestWithAddressStrings }); // Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds: google.maps.routes.ComputeRoutesRequest = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. }; console.log({ requestWithPlaceIds }); // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs: google.maps.routes.ComputeRoutesRequest = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], }; console.log({ requestWithLatLngs }); // Use Plus Codes in a directions request. const requestWithPlusCodes: google.maps.routes.ComputeRoutesRequest = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], }; console.log({ requestWithPlusCodes }); // Define a routes request. const request: google.maps.routes.ComputeRoutesRequest = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. }; // Call computeRoutes to get the directions. const { routes } = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. if (!routes) { console.warn('No routes found.'); return; } mapPolylines = routes[0].createPolylines(); // Add polylines to the map. mapPolylines.forEach((polyline) => { polyline.setMap(map); }); // Create markers to start and end points. const markers = await routes[0].createWaypointAdvancedMarkers(); // Add markers to the map markers.forEach((marker) => { marker.map = map; }); // Display the raw JSON for the result in the console. console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); // Fit the map to the path. void fitMapToPath(routes[0].path!); } // Helper function to fit the map to the path. async function fitMapToPath(path: google.maps.LatLngLiteral[]) { const { LatLngBounds } = await google.maps.importLibrary('core'); const bounds = new LatLngBounds(); path.forEach((point) => { bounds.extend(point); }); map.fitBounds(bounds); } void init();
JavaScript
// Initialize and add the map. let map; let mapPolylines = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function init() { // Request the needed libraries. const [{ Map }, { Place }, { Route }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), google.maps.importLibrary('routes'), ]); map = new Map(document.getElementById('map'), { zoom: 12, center, mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], }; console.log({ requestWithAddressStrings }); // Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. }; console.log({ requestWithPlaceIds }); // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], }; console.log({ requestWithLatLngs }); // Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], }; console.log({ requestWithPlusCodes }); // Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. }; // Call computeRoutes to get the directions. const { routes } = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. if (!routes) { console.warn('No routes found.'); return; } mapPolylines = routes[0].createPolylines(); // Add polylines to the map. mapPolylines.forEach((polyline) => { polyline.setMap(map); }); // Create markers to start and end points. const markers = await routes[0].createWaypointAdvancedMarkers(); // Add markers to the map markers.forEach((marker) => { marker.map = map; }); // Display the raw JSON for the result in the console. console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); // Fit the map to the path. void fitMapToPath(routes[0].path); } // Helper function to fit the map to the path. async function fitMapToPath(path) { const { LatLngBounds } = await google.maps.importLibrary('core'); const bounds = new LatLngBounds(); path.forEach((point) => { bounds.extend(point); }); map.fitBounds(bounds); } void init();
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ #map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Get directions</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="map"></div>
</body>
</html>computeRoutes() メソッドを呼び出して、2 つの場所間のルートをリクエストします。次の例では、リクエストを定義してから computeRoutes() を呼び出してルートを取得しています。computeRoutes() は Route クラスの静的メソッドであるため、Route.computeRoutes(request) を直接呼び出します。また、リクエストでは fields プロパティをレスポンス フィールド マスクに設定する必要があります。
// Import the Routes library. const { Route } = await google.maps.importLibrary('routes'); // Define a computeRoutes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', fields: ['path'], // Required: response field mask. }; // Call the computeRoutes() method to get routes. const {routes} = await Route.computeRoutes(request);
地図上にルートを描画するには、path フィールドでリクエストしたルートで createPolylines() を呼び出します。地図上にポリラインを表示するをご覧ください。
返されるフィールドを選択する
ルートをリクエストする際は、フィールド マスクを使用して、レスポンスで返す情報を指定する必要があります。フィールド マスクには、Route クラスのプロパティの名前を指定できます。
フィールド マスクを使用すると、不要なデータをリクエストしないようにすることもできます。これにより、レスポンスのレイテンシが短縮され、システムに不要な情報が返されるのを防ぐことができます。
次のスニペットに示すように、ComputeRoutesRequest.fields プロパティを設定して、必要なフィールドのリストを指定します。
TypeScript
// Define a routes request. const request: google.maps.routes.ComputeRoutesRequest = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. };
JavaScript
// Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. };
ルートの場所を指定する
ルートを計算するには、少なくともルートの出発地と目的地の場所、およびフィールド マスクを指定する必要があります。ルート上の中間ウェイポイントを指定することもできます。ウェイポイントを使用すると、ルート上に停車地や通過地点を追加するなど、さまざまなことができます。
ComputeRoutesRequest では、次のいずれかの方法でロケーションを指定できます。
リクエスト内のすべてのウェイポイントの場所を同じ方法で指定することも、異なる方法で指定することもできます。 たとえば、出発地のウェイポイントには緯度 / 経度座標を使用し、目的地のウェイポイントには Place オブジェクトを使用できます。
効率性と正確性を高めるため、緯度 / 経度の座標や住所文字列ではなく、Place オブジェクトを使用します。プレイス ID は一意に明示され、アクセス ポイントや交通変数などのルート設定にジオコーディングのメリットをもたらします。これらは、他の方法で位置情報を指定した場合に発生する可能性がある、次のような状況を回避するのに役立ちます。
- 緯度 / 経度座標を使用すると、その座標に最も近い道路に位置情報がスナップされることがあります。その道路は、目的地へのアクセス ポイントではない場合や、目的地に迅速かつ安全に到達できる道路ではない場合があります。
- 住所文字列は、ルートを計算する前に、Routes API によってジオコーディングされ、緯度と経度の座標に変換される必要があります。この変換はパフォーマンスに影響する可能性があります。
Place オブジェクトとして場所を指定する(推奨)
Place を使用して場所を指定するには、新しい Place インスタンスを作成します。次のスニペットは、origin と destination の新しい Place インスタンスを作成し、ComputeRoutesRequest で使用する方法を示しています。
TypeScript
// Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds: google.maps.routes.ComputeRoutesRequest = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. };
JavaScript
// Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. };
緯度と経度の座標
緯度/経度座標として場所を指定するには、新しい google.maps.LatLngLiteral、google.maps.LatLngAltitude、または google.maps.LatLngAltitudeLiteral インスタンスを作成します。次のスニペットは、origin と destination の新しい google.maps.LatLngLiteral インスタンスを作成し、computeRoutesRequest で使用する方法を示しています。
TypeScript
// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs: google.maps.routes.ComputeRoutesRequest = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], };
JavaScript
// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], };
アドレス文字列
住所文字列は、文字列で表されるリテラル住所です(「1600 Amphitheatre Parkway, Mountain View, CA」など)。ジオコーディングとは、住所文字列を緯度と経度の座標(緯度 37.423021、経度 -122.083739 など)に変換する処理のことです。
ウェイポイントの位置として住所文字列を渡すと、Routes ライブラリは内部で文字列をジオコーディングして緯度と経度の座標に変換します。
次のスニペットは、origin と destination のアドレス文字列を使用して ComputeRoutesRequest を作成する方法を示しています。
TypeScript
// Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], };
JavaScript
// Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], };
アドレスのリージョンを設定する
ウェイポイントの場所として不完全な住所文字列を渡すと、API は間違ったジオコーディングの緯度 / 経度座標を使用する可能性があります。たとえば、出発地として「Toledo」、目的地として「Madrid」を指定して、運転ルートをリクエストします。
// Define a request with an incomplete address string. const request = { origin: 'Toledo', destination: 'Madrid', };
この例では、「トレド」はスペインではなく、米国のオハイオ州の都市として解釈されます。そのため、リクエストは空の配列を返します。これは、ルートが存在しないことを意味します。
regionCode パラメータを含めることで、特定の地域に結果バイアスをかけて結果を返すように API を構成できます。このパラメータでは、地域コードを ccTLD(「トップレベル ドメイン」)の 2 文字の値として指定します。大半の ccTLD コードは ISO 3166-1 コードと同一ですが、いくつか注意が必要な例外もあります。たとえば、英国の ccTLD は「uk」(.co.uk)ですが、ISO 3166-1 コードは「gb」(厳密には「グレート ブリテンおよび北アイルランド連合王国」のエンティティ)です。
regionCode パラメータを含む「トレド」から「マドリード」へのルート リクエストでは、「トレド」がスペインの都市として解釈されるため、適切な結果が返されます。
const request = { origin: 'Toledo', destination: 'Madrid', region: 'es', // Specify the region code for Spain. };
Plus Code
多くの人は正確な住所を持っておらず、荷物の受け取りが困難な場合があります。また、住所がある場合でも、裏口や搬入口など、より具体的な場所での受け取りを希望する人もいます。
Plus Code は、実際の番地がない人や場所の住所のようなものです。Plus Codes は、番地や番号ではなく、緯度と経度の座標に基づいており、数字と文字で表示されます。
Google は、あらゆる人や場所が住所のメリットを享受できるように、Plus Codes を開発しました。Plus Code は、緯度 / 経度の座標から取得される、エンコードされた場所の参照情報です。8000 分の 1 x 8000 分の 1(14 メートル x 14 メートル)以下の領域を表します。Plus Codes は、番地がない場所、建物に番号が付いていない場所、通りに名前がない場所で、番地の代わりに使用できます。
Plus Code は、グローバル コードまたは複合コードの形式にする必要があります。
- グローバル コードは、4 文字の市外局番と 6 文字以上のローカルコードで構成されます。たとえば、「1600 Amphitheatre Parkway, Mountain View, CA」という住所の場合、グローバル コードは「849V」、ローカルコードは「CWC8+R9」です。次に、10 文字の Plus Code 全体を使用して、場所の値を「849VCWC8+R9」として指定します。
- 複合コードは、6 文字以上のローカルコードと明示的な場所を組み合わせたものです。たとえば、「450 Serra Mall, Stanford, CA 94305, USA」という住所のローカルコードは「CRHJ+C3」です。複合住所の場合は、ローカルコードと、住所の市区町村、都道府県、郵便番号、国を組み合わせて、「CRHJ+C3 Stanford, CA 94305, USA」のように指定します。
次のスニペットは、Plus Codes を使用してルートの出発地と目的地のウェイポイントを指定してルートを計算する方法を示しています。
TypeScript
// Use Plus Codes in a directions request. const requestWithPlusCodes: google.maps.routes.ComputeRoutesRequest = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], };
JavaScript
// Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], };