改用新的算繪方法
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
本指南說明如何遷移至 Route 類別的新算繪方法。
在 Directions 服務 (舊版) 中,算繪方法是 DirectionsRenderer
類別的一部分。Route 類別 (Beta 版) 提供兩種新的算繪方法:createPolylines
和 createWaypointAdvancedMarkers
。
舊版 DirectionsRenderer
在 Directions 服務 (舊版) 中,算繪方法是 DirectionsRenderer
類別的一部分。DirectionsRenderer
類別會負責顯示折線、任何相關聯的標記,以及步驟的文字顯示內容;這個類別具有下列方法:
setDirections()
:轉譯提供的路線回應。
setMap()
- 設定要顯示路線回應的地圖。
setPanel()
:在面板中以一系列文字步驟顯示路線。
下例說明如何使用 DirectionsRenderer
類別在地圖上轉譯路線。
function initMap() {
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom:7,
center: chicago
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Set the map on the directions renderer.
directionsRenderer.setMap(map);
// Set the panel to display the directions as a series of textual steps.
directionsRenderer.setPanel(document.getElementById('directionsPanel'));
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: 'DRIVING'
};
// Call the directions service to get the directions.
directionsService.route(request, function(response, status) {
if (status == 'OK') {
// Render the polyline and markers on the map.
directionsRenderer.setDirections(response);
}
});
}
Route
類別 (Beta 版)
Route 類別 (Beta 版) 提供下列新的算繪方法,可取代舊版 DirectionsRenderer
類別方法:
createPolylines
createWaypointAdvancedMarkers
Route
類別沒有與舊版 DirectionsRenderer
類別中的 setPanel()
方法對應的項目。如要顯示文字步驟,您必須手動建立 HTML 元素,並插入 DOM。以下範例說明如何使用 Route 類別在地圖上算繪路線,並手動建立 HTML 元素來顯示文字步驟。
let map;
let mapPolylines = [];
let markers = [];
let center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA
// Initialize and add the map.
async function initMap() {
// Request the needed libraries.
const { Map } = await google.maps.importLibrary('maps') as google.maps.MapsLibrary;
const { Route } = await google.maps.importLibrary('routes') as google.maps.Routes;
map = new Map(document.getElementById("map"), {
zoom: 12,
center,
mapTypeControl: false,
mapId: 'DEMO_MAP_ID',
});
// Define a simple directions request.
const request = {
origin: 'Mountain View, CA',
destination: 'San Francisco, CA',
travelMode: 'DRIVING',
fields: ['legs'],
};
// Call computeRoutes to get the directions.
const { routes } = 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));
fitMapToPath(routes[0].path);
// Add markers to start and end points.
const markers = await routes[0].createWaypointAdvancedMarkers({map});
// Render navigation instructions.
const directionsPanel = document.getElementById("directions-panel");
if (!routes || routes.length === 0) {
if (directionsPanel) {
directionsPanel.textContent = "No routes available.";
}
}
const route = routes[0];
if (!route.legs || route.legs.length === 0) {
if (directionsPanel) {
directionsPanel.textContent = "The route has no legs.";
}
return;
}
const fragment = document.createDocumentFragment();
route.legs.forEach((leg, index) => {
const legContainer = document.createElement("div");
legContainer.className = "directions-leg";
legContainer.setAttribute("aria-label", `Leg ${index + 1}`);
// Leg Title
const legTitleElement = document.createElement("h3");
legTitleElement.textContent = `Leg ${index + 1} of ${route.legs.length}`;
legContainer.appendChild(legTitleElement);
if (leg.steps && leg.steps.length > 0) {
// Add steps to an ordered list
const stepsList = document.createElement("ol");
stepsList.className = "directions-steps";
leg.steps.forEach((step, stepIndex) => {
const stepItem = document.createElement("li");
stepItem.className = "direction-step";
stepItem.setAttribute("aria-label", `Step ${stepIndex + 1}`);
// Maneuver
if (step.maneuver) {
const maneuverNode = document.createElement("p");
maneuverNode.textContent = step.maneuver;
maneuverNode.className = "maneuver";
stepItem.appendChild(maneuverNode);
}
// Distance and Duration
if (step.localizedValues) {
const distanceNode = document.createElement("p");
distanceNode.textContent = `${step.localizedValues.distance} (${step.localizedValues.staticDuration})`;
distanceNode.className = "distance";
stepItem.appendChild(distanceNode);
}
// Instructions
if (step.instructions) {
const instructionsNode = document.createElement("p");
instructionsNode.textContent = step.instructions;
instructionsNode.className = "instruction";
stepItem.appendChild(instructionsNode);
}
stepsList.appendChild(stepItem);
});
legContainer.appendChild(stepsList);
}
fragment.appendChild(legContainer);
directionsPanel?.appendChild(fragment);
});
}
// 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();
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-09-05 (世界標準時間)。
[null,null,["上次更新時間:2025-09-05 (世界標準時間)。"],[],[],null,["**European Economic Area (EEA) developers** If your billing address is in the European Economic Area, effective on 8 July 2025, the [Google Maps Platform EEA Terms of Service](https://cloud.google.com/terms/maps-platform/eea) will apply to your use of the Services. Functionality varies by region. [Learn more](/maps/comms/eea/faq).\n\nThis guide shows you how to migrate to the new rendering methods for the Route class.\nIn the Directions service (Legacy), the rendering methods were part of the\n`DirectionsRenderer` class. The Route class (Beta) provides two new rendering\nmethods: `createPolylines` and `createWaypointAdvancedMarkers`.\n\nLegacy `DirectionsRenderer`\n\nIn the Directions service (Legacy), the rendering methods were part of the\n`DirectionsRenderer` class. The `DirectionsRenderer` class handles\ndisplay of the polyline, any associated markers, as well as the textual display of steps; it\nhas the following methods:\n\n- `setDirections()` - Renders the provided directions response.\n- `setMap()` - Sets the map on which to render the directions response.\n- `setPanel()` - Displays the directions as a series of textual steps in a panel.\n\nThe following example shows how to use the `DirectionsRenderer` class to render\ndirections on a map. \n\n```javascript\nfunction initMap() {\n var directionsService = new google.maps.DirectionsService();\n var directionsRenderer = new google.maps.DirectionsRenderer();\n var chicago = new google.maps.LatLng(41.850033, -87.6500523);\n var mapOptions = {\n zoom:7,\n center: chicago\n }\n var map = new google.maps.Map(document.getElementById('map'), mapOptions);\n // Set the map on the directions renderer.\n directionsRenderer.setMap(map);\n // Set the panel to display the directions as a series of textual steps.\n directionsRenderer.setPanel(document.getElementById('directionsPanel'));\n}\n\nfunction calcRoute() {\n var start = document.getElementById('start').value;\n var end = document.getElementById('end').value;\n var request = {\n origin: start,\n destination: end,\n travelMode: 'DRIVING'\n };\n // Call the directions service to get the directions.\n directionsService.route(request, function(response, status) {\n if (status == 'OK') {\n // Render the polyline and markers on the map.\n directionsRenderer.setDirections(response);\n }\n });\n}\n \n```\n\n`Route` class (Beta)\n\nThe Route class (Beta) provides the following new rendering methods, which replace the\nlegacy `DirectionsRenderer` class methods:\n\n- `createPolylines`\n- `createWaypointAdvancedMarkers`\n\nThe `Route` class has no equivalent to the `setPanel()` method in the\nlegacy `DirectionsRenderer` class. To display the textual steps, you must\nmanually create the HTML elements and insert them into the DOM. The following example\nshows how to render directions on a map using the Route class, and manually create the\nHTML elements to display the textual steps. \n\n```javascript\nlet map;\nlet mapPolylines = [];\nlet markers = [];\nlet center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA\n\n// Initialize and add the map.\nasync function initMap() {\n // Request the needed libraries.\n const { Map } = await google.maps.importLibrary('maps') as google.maps.MapsLibrary;\n const { Route } = await google.maps.importLibrary('routes') as google.maps.Routes;\n\n map = new Map(document.getElementById(\"map\"), {\n zoom: 12,\n center,\n mapTypeControl: false,\n mapId: 'DEMO_MAP_ID',\n });\n\n // Define a simple directions request.\n const request = {\n origin: 'Mountain View, CA',\n destination: 'San Francisco, CA',\n travelMode: 'DRIVING',\n fields: ['legs'],\n };\n\n // Call computeRoutes to get the directions.\n const { routes } = await Route.computeRoutes(request);\n \n // Use createPolylines to create polylines for the route.\n mapPolylines = routes[0].createPolylines();\n // Add polylines to the map.\n mapPolylines.forEach((polyline) =\u003e polyline.setMap(map));\n \n fitMapToPath(routes[0].path);\n\n // Add markers to start and end points.\n const markers = await routes[0].createWaypointAdvancedMarkers({map});\n \n\n // Render navigation instructions.\n const directionsPanel = document.getElementById(\"directions-panel\");\n\n if (!routes || routes.length === 0) {\n if (directionsPanel) {\n directionsPanel.textContent = \"No routes available.\";\n }\n }\n\n const route = routes[0];\n if (!route.legs || route.legs.length === 0) {\n if (directionsPanel) {\n directionsPanel.textContent = \"The route has no legs.\";\n }\n return;\n }\n\n const fragment = document.createDocumentFragment();\n\n route.legs.forEach((leg, index) =\u003e {\n const legContainer = document.createElement(\"div\");\n legContainer.className = \"directions-leg\";\n legContainer.setAttribute(\"aria-label\", `Leg ${index + 1}`);\n\n // Leg Title\n const legTitleElement = document.createElement(\"h3\");\n legTitleElement.textContent = `Leg ${index + 1} of ${route.legs.length}`;\n legContainer.appendChild(legTitleElement);\n\n if (leg.steps && leg.steps.length \u003e 0) {\n // Add steps to an ordered list\n const stepsList = document.createElement(\"ol\");\n stepsList.className = \"directions-steps\";\n\n leg.steps.forEach((step, stepIndex) =\u003e {\n const stepItem = document.createElement(\"li\");\n stepItem.className = \"direction-step\";\n stepItem.setAttribute(\"aria-label\", `Step ${stepIndex + 1}`);\n\n // Maneuver\n if (step.maneuver) {\n const maneuverNode = document.createElement(\"p\");\n maneuverNode.textContent = step.maneuver;\n maneuverNode.className = \"maneuver\";\n stepItem.appendChild(maneuverNode);\n }\n\n // Distance and Duration\n if (step.localizedValues) {\n const distanceNode = document.createElement(\"p\");\n distanceNode.textContent = `${step.localizedValues.distance} (${step.localizedValues.staticDuration})`;\n distanceNode.className = \"distance\";\n stepItem.appendChild(distanceNode);\n }\n\n // Instructions\n if (step.instructions) {\n const instructionsNode = document.createElement(\"p\");\n instructionsNode.textContent = step.instructions;\n instructionsNode.className = \"instruction\";\n stepItem.appendChild(instructionsNode);\n }\n\n stepsList.appendChild(stepItem);\n });\n legContainer.appendChild(stepsList);\n }\n\n fragment.appendChild(legContainer);\n directionsPanel?.appendChild(fragment);\n });\n \n}\n\n// Helper function to fit the map to the path.\nasync function fitMapToPath(path) {\n const { LatLngBounds } = await google.maps.importLibrary('core') as google.maps.CoreLibrary;\n const bounds = new LatLngBounds();\n path.forEach((point) =\u003e {\n bounds.extend(point);\n });\n map.fitBounds(bounds);\n}\n\ninitMap();\n \n```"]]