新的 Routes 库(Maps JavaScript API)包含 Route 类,该类取代了
旧版路线服务。本
页面介绍了旧版路线服务与新的 Route
类之间的差异,并提供了一些代码以供比较。
路线服务(旧版)与 Route 类
请求参数
下表比较了旧版路线服务和
Route 类。
方法比较
下表比较了旧版路线服务和
Route 类。
| 路线服务(旧版) | Route |
|---|---|
route() 方法 |
computeRoutes() 方法 |
DirectionsRenderer.setDirections() 方法 |
createPolylines() 方法、
createWaypointAdvancedMarkers() 方法
|
代码比较
本部分比较了两个类似的代码段,以说明旧版路线服务与新的 Route 类之间的差异。这些代码段显示了在每个相应 API 上发出路线请求所需的代码,然后使用结果在地图上绘制多段线和标记。
在旧版路线服务中,
DirectionsRenderer
对象用于显示多段线和标记,以在地图上表示路线结果。在 Routes 库中,DirectionsRenderer 对象已替换为 createPolylines() 和 createWaypointAdvancedMarkers() 方法。本页面介绍了旧版路线服务与新的
Route 类之间的差异,并提供了一些代码以供比较。
查询行车路线
路线服务(旧版)
以下代码使用旧版路线服务查询驾车路线,然后使用
DirectionsRenderer 在地图上绘制多段线和标记:
// Define a simple request. var request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING' }; // Call the Directions Service to get the directions. directionsService.route(request, function(result, status) { if (status == 'OK') { directionsRenderer.setDirections(result); // Add polyline and markers to the map. } });
Route 类
以下代码使用新的 Route 类查询驾车路线,然后
使用 createPolylines 方法在地图上绘制多段线,并使用
createWaypointAdvancedMarkers 方法在地图上绘制标记。
新的 Route 类不会自动呈现标记。您必须调用
createWaypointAdvancedMarkers 才能呈现标记。
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. }; // 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; });
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. }; // 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; });
DEMO_MAP_ID。了解详情。