経路とは、出発地(始点)から目的地(終点)までの移動可能なパスのことです。徒歩、自転車、さまざまな種類の車両など、さまざまな移動手段の 経路を取得できます。また、距離、経路の移動時間、予想される通行料金、経路の移動手順などの経路の詳細をリクエストすることもできます。
サンプル ソースコードの全文を見る
次のコードサンプルは、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() を呼び出してルートを取得する方法を示しています。
// 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);
返すフィールドを選択する
ルートをリクエストする場合は、フィールド マスクを使用して、レスポンスで返す情報を指定する必要があります。フィールド マスクで 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 インスタンスを作成します。次の
スニペットは、Placeの新しいインスタンスを作成し、origin
とdestinationでそれらを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, or
google.maps.LatLngAltitudeLiteral インスタンスを作成します。次のスニペットは、
新しいgoogle.maps.LatLngLiteralインスタンスをoriginとdestinationに作成し、
それらを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 ライブラリは内部で文字列をジオコーディングして緯度と経度の座標に変換します。
次のスニペットは、住所文字列を使用して ComputeRoutesRequest の origin と destination を作成する方法を示しています。
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', };
この例では、「Toledo」はスペインではなく、米国のオハイオ州の都市として解釈されます。 そのため、リクエストは空の配列を返します。つまり、ルートが存在しません。
regionCode パラメータを含めることで、特定の地域を優先する結果を返すように API を構成できます。このパラメータは、リージョン コードを ccTLD("トップレベル ドメイン") 2 文字の値として指定します。ほとんどの ccTLD コードは ISO 3166-1 コードと同一ですが、いくつか注意が必要な 例外もあります。たとえば、英国の ccTLD は「uk」(.co.uk)ですが、ISO 3166-1 コード は「gb」(厳密には「グレートブリテンおよび北アイルランド連合王国」のエンティティ用)です。
regionCode パラメータを含む「Toledo」から「Madrid」へのルート リクエストは、 「Toledo」がスペインの都市として解釈されるため、適切な結果を返します。
const request = { origin: 'Toledo', destination: 'Madrid', region: 'es', // Specify the region code for Spain. };
Plus Code
多くの人が正確な住所を持っていないため、配達物の受け取りが困難な場合があります。また、住所がある人は裏口や発送センターなど、より特定の 場所で配達物を受け取りたい場合があります。
Plus Codes は、実際の住所がない人や場所の番地のようなものです。 Plus Codes は、番地と番地ではなく、緯度と経度の座標に基づいており、数字と文字で表示されます。
Google は、すべての人や物に住所のメリットを提供するために Plus Codes を開発しました。Plus Code はエンコードされた 場所の参照情報です。緯度と経度の座標から取得され、8000 分の 1 x 8000 分の 1(14 メートル x 14 メートル)以下の領域を表します。Plus Codes は、番地がない場所や、建物に番号が付いていない場所、通りに名前がない場所で、番地の代わりに使用できます。
Plus Codes は、グローバル コードまたは複合コードとしてフォーマットする必要があります。
- グローバル コード は、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'], };