ルートは、出発地(起点)と目的地(終点)の間のナビゲーション可能な経路です。徒歩、自転車、さまざまな種類の車両など、さまざまな移動手段のルートを表示できます。また、距離、ルートの推定所要時間、予想される有料道路の料金、ルートをナビゲートするための詳細な手順などのルートの詳細をリクエストすることもできます。
サンプル ソースコードの全文を見る
次のコードサンプルは、2 つの地点間の運転ルートを取得する方法を示しています。
TypeScript
// Initialize and add the map. let map; let mapPolylines: google.maps.Polyline[] = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function initMap(): Promise<void> { // Request the needed libraries. const [{Map}, {Place}, {Route}] = await Promise.all([ google.maps.importLibrary('maps') as Promise<google.maps.MapsLibrary>, google.maps.importLibrary('places') as Promise<google.maps.PlacesLibrary>, //@ts-ignore google.maps.importLibrary('routes') as Promise<google.maps.Routes> ]); map = new Map(document.getElementById("map") as HTMLElement, { zoom: 12, center: 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'], }; // 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. }; // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = {lat: 37.422000, 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'], }; // 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'], }; // 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, fallbackInfo, geocodingResults} = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. 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.setMap(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. fitMapToPath(routes[0].path!); } // Helper function to fit the map to the path. async function fitMapToPath(path) { const { LatLngBounds } = await google.maps.importLibrary('core') as google.maps.CoreLibrary; const bounds = new LatLngBounds(); path.forEach((point) => { bounds.extend(point); }); map.fitBounds(bounds); } initMap();
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 initMap() { // Request the needed libraries. const [{ Map }, { Place }, { Route }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), //@ts-ignore google.maps.importLibrary('routes') ]); map = new Map(document.getElementById("map"), { zoom: 12, center: 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'], }; // 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. }; // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422000, 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'], }; // 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'], }; // 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, fallbackInfo, geocodingResults } = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. 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.setMap(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. 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); } initMap();
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>
</head>
<body>
<div id="map"></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>サンプルを試す
computeRoutes() メソッドを呼び出して、2 つの地点間のルートをリクエストします。次の例では、リクエストを定義してから computeRoutes() を呼び出してルートを取得しています。
// 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', }; // Call the computeRoutes() method to get routes. const {routes} = await Route.computeRoutes(request);
返すフィールドを選択する
ルートをリクエストする場合は、フィールド マスクを使用して、レスポンスで返す情報を指定する必要があります。フィールド マスクで ルートクラスのプロパティの名前を指定できます。
フィールド マスクを使用すると、不要なデータをリクエストしないようにすることもできます。これにより、レスポンス レイテンシが短縮され、システムで不要な情報が返されるのを防ぐことができます。
次のスニペットに示すように、ComputeRoutesRequest.fields プロパティを設定して、必要なフィールドのリストを指定します。
TypeScript
// Define a routes request. const request = { 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 = { 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.422000, 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'], };
JavaScript
// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422000, 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 Codes は、実際の住所がない人や場所の番地のようなものです。Plus Code は、番地と地名ではなく、緯度と経度の座標に基づいており、数字と文字で表示されます。
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 文字のプラスコード全体を使用して、ビジネス拠点の値を「849VCWC8+R9」として指定します。
- 複合コードは、明示的な場所と組み合わせた 6 文字以上のローカルコードで構成されます。たとえば、「450 Serra Mall, Stanford, CA 94305, USA」という住所のローカルコードは「CRHJ+C3」です。複合住所の場合は、ローカルコードと住所の市、州、郵便番号、国を「CRHJ+C3 Stanford, CA 94305, USA」の形式で組み合わせます。
次のスニペットは、プラスコードを使用してルートの出発地と目的地の経由地を指定してルートを計算する方法を示しています。
TypeScript
// 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'], };
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'], };