通过调用 createWaypointAdvancedMarkers() 为路线途经点创建标记。
默认情况下,createWaypointAdvancedMarkers() 会为每个途经点创建标记,并为路线添加“A”“B”“C”等标签。您还可以通过传入选项来进一步自定义标记,以根据标记索引或相应 RouteLeg 的属性更改标记样式。
查看完整的示例源代码
以下代码示例展示了如何为路线途经点创建自定义标记。
TypeScript
let mapPolylines: google.maps.Polyline[] = []; const mapElement = document.querySelector('gmp-map')!; let innerMap: google.maps.Map; // Initialize and add the map. async function init() { // Request the needed libraries. const [{ event }] = await Promise.all([ google.maps.importLibrary('core'), google.maps.importLibrary('maps'), ]); innerMap = mapElement.innerMap; innerMap.setOptions({ mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Call the function after the map is loaded. event.addListenerOnce(innerMap, 'idle', () => { void getDirections(); }); } async function getDirections() { // Request the needed libraries. const [{ Route }, { PinElement }] = await Promise.all([ google.maps.importLibrary('routes'), google.maps.importLibrary('marker'), ]); // Define routes request with an intermediate stop. const request: google.maps.routes.ComputeRoutesRequest = { origin: 'Parking lot, Christmas Tree Point Rd, San Francisco, CA 94131', destination: '100 Spinnaker Dr, Sausalito, CA 94965', // We're having a yummy lunch! intermediates: [{ location: '300 Finley Rd San Francisco, CA 94129' }], // But first, we golf! travelMode: 'DRIVING', fields: ['path', 'legs', 'viewport'], }; // Call computeRoutes to get the directions. const result = await Route.computeRoutes(request); if (!result.routes || result.routes.length === 0) { console.warn('No routes found'); return; } // Alter style based on marker index. function markerOptionsMaker( defaultOptions: google.maps.marker.AdvancedMarkerElementOptions, waypointMarkerDetails: google.maps.routes.WaypointMarkerDetails ) { const { index, totalMarkers } = waypointMarkerDetails; // Style the origin waypoint. if (index === 0) { return { ...defaultOptions, title: 'Origin', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'green', borderColor: 'green', scale: 1.5, }), }; } // Style all intermediate waypoints. if (!(index === 0 || index === totalMarkers - 1)) { return { ...defaultOptions, title: `Waypoint ${(index + 1).toString()}`, // Provide label for screenreaders map: innerMap, gmpClickable: true, // Make marker focusable and allow keyboard navigation content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'blue', borderColor: 'blue', scale: 1.5, // Increase size for better visibilty }), }; } // Style the destination waypoint. if (index === totalMarkers - 1) { return { ...defaultOptions, title: 'Destination', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'red', borderColor: 'red', scale: 1.5, }), }; } return { ...defaultOptions, map: innerMap }; } await result.routes[0].createWaypointAdvancedMarkers(markerOptionsMaker); // Fit the map to the route. innerMap.fitBounds(result.routes[0].viewport!); innerMap.setHeading(270); // Create polylines and add them to the map. mapPolylines = result.routes[0].createPolylines(); mapPolylines.forEach((polyline) => { polyline.setMap(innerMap); }); } void init();
JavaScript
let mapPolylines = []; const mapElement = document.querySelector('gmp-map'); let innerMap; // Initialize and add the map. async function init() { // Request the needed libraries. const [{ event }] = await Promise.all([ google.maps.importLibrary('core'), google.maps.importLibrary('maps'), ]); innerMap = mapElement.innerMap; innerMap.setOptions({ mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Call the function after the map is loaded. event.addListenerOnce(innerMap, 'idle', () => { void getDirections(); }); } async function getDirections() { // Request the needed libraries. const [{ Route }, { PinElement }] = await Promise.all([ google.maps.importLibrary('routes'), google.maps.importLibrary('marker'), ]); // Define routes request with an intermediate stop. const request = { origin: 'Parking lot, Christmas Tree Point Rd, San Francisco, CA 94131', destination: '100 Spinnaker Dr, Sausalito, CA 94965', // We're having a yummy lunch! intermediates: [{ location: '300 Finley Rd San Francisco, CA 94129' }], // But first, we golf! travelMode: 'DRIVING', fields: ['path', 'legs', 'viewport'], }; // Call computeRoutes to get the directions. const result = await Route.computeRoutes(request); if (!result.routes || result.routes.length === 0) { console.warn('No routes found'); return; } // Alter style based on marker index. function markerOptionsMaker(defaultOptions, waypointMarkerDetails) { const { index, totalMarkers } = waypointMarkerDetails; // Style the origin waypoint. if (index === 0) { return { ...defaultOptions, title: 'Origin', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'green', borderColor: 'green', scale: 1.5, }), }; } // Style all intermediate waypoints. if (!(index === 0 || index === totalMarkers - 1)) { return { ...defaultOptions, title: `Waypoint ${(index + 1).toString()}`, // Provide label for screenreaders map: innerMap, gmpClickable: true, // Make marker focusable and allow keyboard navigation content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'blue', borderColor: 'blue', scale: 1.5, // Increase size for better visibilty }), }; } // Style the destination waypoint. if (index === totalMarkers - 1) { return { ...defaultOptions, title: 'Destination', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'red', borderColor: 'red', scale: 1.5, }), }; } return { ...defaultOptions, map: innerMap }; } await result.routes[0].createWaypointAdvancedMarkers(markerOptionsMaker); // Fit the map to the route. innerMap.fitBounds(result.routes[0].viewport); innerMap.setHeading(270); // Create polylines and add them to the map. mapPolylines = result.routes[0].createPolylines(); mapPolylines.forEach((polyline) => { polyline.setMap(innerMap); }); } 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>
<gmp-map center="37.447646, -122.113878" zoom="12"></gmp-map>
</body>
</html>添加默认标记
如需使用默认样式添加标记,请调用 createWaypointAdvancedMarkers() 并传递标记选项以指定当前地图,如以下代码段所示。
// Create markers using default style. const markers = await result.routes[0].createWaypointAdvancedMarkers({ map: innerMap });
添加具有自定义样式的标记
如需使用自定义样式添加标记,请调用 createWaypointAdvancedMarkers() 并传递包含自定义样式属性的标记选项。当您以这种方式应用样式时,所有标记的样式都相同。以下代码段展示了如何创建具有自定义样式的标记。
// Create markers with a custom style. const markerOptions = { map: innerMap, content: new PinElement({ scale: 1.5, background: '#8C0DD1', borderColor: '#6D0AA5', glyphColor: '#6D0AA5', }).element } const markers = await result.routes[0].createWaypointAdvancedMarkers(markerOptions);
为各个标记应用自定义样式
如需为各个标记应用自定义样式,请将函数传递给 createWaypointAdvancedMarkers(),以根据标记索引或 RouteLeg 属性设置标记样式选项。
以下代码段展示了一个用于创建标记并根据标记指数设置其样式的函数:
TypeScript
// Alter style based on marker index. function markerOptionsMaker( defaultOptions: google.maps.marker.AdvancedMarkerElementOptions, waypointMarkerDetails: google.maps.routes.WaypointMarkerDetails ) { const { index, totalMarkers } = waypointMarkerDetails; // Style the origin waypoint. if (index === 0) { return { ...defaultOptions, title: 'Origin', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'green', borderColor: 'green', scale: 1.5, }), }; } // Style all intermediate waypoints. if (!(index === 0 || index === totalMarkers - 1)) { return { ...defaultOptions, title: `Waypoint ${(index + 1).toString()}`, // Provide label for screenreaders map: innerMap, gmpClickable: true, // Make marker focusable and allow keyboard navigation content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'blue', borderColor: 'blue', scale: 1.5, // Increase size for better visibilty }), }; } // Style the destination waypoint. if (index === totalMarkers - 1) { return { ...defaultOptions, title: 'Destination', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'red', borderColor: 'red', scale: 1.5, }), }; } return { ...defaultOptions, map: innerMap }; } await result.routes[0].createWaypointAdvancedMarkers(markerOptionsMaker);
JavaScript
// Alter style based on marker index. function markerOptionsMaker(defaultOptions, waypointMarkerDetails) { const { index, totalMarkers } = waypointMarkerDetails; // Style the origin waypoint. if (index === 0) { return { ...defaultOptions, title: 'Origin', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'green', borderColor: 'green', scale: 1.5, }), }; } // Style all intermediate waypoints. if (!(index === 0 || index === totalMarkers - 1)) { return { ...defaultOptions, title: `Waypoint ${(index + 1).toString()}`, // Provide label for screenreaders map: innerMap, gmpClickable: true, // Make marker focusable and allow keyboard navigation content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'blue', borderColor: 'blue', scale: 1.5, // Increase size for better visibilty }), }; } // Style the destination waypoint. if (index === totalMarkers - 1) { return { ...defaultOptions, title: 'Destination', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'red', borderColor: 'red', scale: 1.5, }), }; } return { ...defaultOptions, map: innerMap }; } await result.routes[0].createWaypointAdvancedMarkers(markerOptionsMaker);
使标记可供访问
您可以通过以下方式提高标记的可访问性:
- 提供标题:在标记选项中设置
title属性,为标记提供标签。此标签供屏幕阅读器和辅助技术使用。 - 区分途经点:向
createWaypointAdvancedMarkers()传递样式函数时,请使用WaypointMarkerDetails中的index和totalMarkers参数为途经点(例如Waypoint ${(index + 1).toString()})分配唯一的描述性标题和标签,以便屏幕阅读器用户能够将途经点与起点和目的地区分开来。 - 启用键盘导航和点击事件:在标记选项中设置
gmpClickable: true,使交互式标记可通过键盘(使用 Tab 键和箭头键)聚焦,并能够响应键盘和鼠标输入。 - 增大标记尺寸:在
PinElement上设置scale属性(例如scale: 1.5),以降低与标记互动所需的精度,尤其是在触摸屏设备上。默认标记符合 WCAG AA 最小尺寸标准,而增加缩放比例有助于符合 WCAG AAA 目标尺寸标准。 - 保持颜色对比度:自定义
PinElement颜色时,请选择对比度足够的glyphColor和background值,以便途经点标签保持清晰可读。
以下代码段展示了如何设置标记的样式以实现无障碍功能。它具有 title,可为屏幕阅读器提供标签;标题使用索引来区分中间途经点。gmpClickable 属性已设置为 true,以启用键盘导航和点击事件;scale 已增加,以便更轻松地与标记互动。
TypeScript
// Style all intermediate waypoints. if (!(index === 0 || index === totalMarkers - 1)) { return { ...defaultOptions, title: `Waypoint ${(index + 1).toString()}`, // Provide label for screenreaders map: innerMap, gmpClickable: true, // Make marker focusable and allow keyboard navigation content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'blue', borderColor: 'blue', scale: 1.5, // Increase size for better visibilty }), }; }
JavaScript
// Style all intermediate waypoints. if (!(index === 0 || index === totalMarkers - 1)) { return { ...defaultOptions, title: `Waypoint ${(index + 1).toString()}`, // Provide label for screenreaders map: innerMap, gmpClickable: true, // Make marker focusable and allow keyboard navigation content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'blue', borderColor: 'blue', scale: 1.5, // Increase size for better visibilty }), }; }
如需了解详情,请参阅使标记可点击且可访问。
查看完整示例
TypeScript
let mapPolylines: google.maps.Polyline[] = []; const mapElement = document.querySelector('gmp-map')!; let innerMap: google.maps.Map; // Initialize and add the map. async function init() { // Request the needed libraries. const [{ event }] = await Promise.all([ google.maps.importLibrary('core'), google.maps.importLibrary('maps'), ]); innerMap = mapElement.innerMap; innerMap.setOptions({ mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Call the function after the map is loaded. event.addListenerOnce(innerMap, 'idle', () => { void getDirections(); }); } async function getDirections() { // Request the needed libraries. const [{ Route }, { PinElement }] = await Promise.all([ google.maps.importLibrary('routes'), google.maps.importLibrary('marker'), ]); // Define routes request with an intermediate stop. const request: google.maps.routes.ComputeRoutesRequest = { origin: 'Parking lot, Christmas Tree Point Rd, San Francisco, CA 94131', destination: '100 Spinnaker Dr, Sausalito, CA 94965', // We're having a yummy lunch! intermediates: [{ location: '300 Finley Rd San Francisco, CA 94129' }], // But first, we golf! travelMode: 'DRIVING', fields: ['path', 'legs', 'viewport'], }; // Call computeRoutes to get the directions. const result = await Route.computeRoutes(request); if (!result.routes || result.routes.length === 0) { console.warn('No routes found'); return; } // Alter style based on marker index. function markerOptionsMaker( defaultOptions: google.maps.marker.AdvancedMarkerElementOptions, waypointMarkerDetails: google.maps.routes.WaypointMarkerDetails ) { const { index, totalMarkers } = waypointMarkerDetails; // Style the origin waypoint. if (index === 0) { return { ...defaultOptions, title: 'Origin', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'green', borderColor: 'green', scale: 1.5, }), }; } // Style all intermediate waypoints. if (!(index === 0 || index === totalMarkers - 1)) { return { ...defaultOptions, title: `Waypoint ${(index + 1).toString()}`, // Provide label for screenreaders map: innerMap, gmpClickable: true, // Make marker focusable and allow keyboard navigation content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'blue', borderColor: 'blue', scale: 1.5, // Increase size for better visibilty }), }; } // Style the destination waypoint. if (index === totalMarkers - 1) { return { ...defaultOptions, title: 'Destination', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'red', borderColor: 'red', scale: 1.5, }), }; } return { ...defaultOptions, map: innerMap }; } await result.routes[0].createWaypointAdvancedMarkers(markerOptionsMaker); // Fit the map to the route. innerMap.fitBounds(result.routes[0].viewport!); innerMap.setHeading(270); // Create polylines and add them to the map. mapPolylines = result.routes[0].createPolylines(); mapPolylines.forEach((polyline) => { polyline.setMap(innerMap); }); } void init();
JavaScript
let mapPolylines = []; const mapElement = document.querySelector('gmp-map'); let innerMap; // Initialize and add the map. async function init() { // Request the needed libraries. const [{ event }] = await Promise.all([ google.maps.importLibrary('core'), google.maps.importLibrary('maps'), ]); innerMap = mapElement.innerMap; innerMap.setOptions({ mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Call the function after the map is loaded. event.addListenerOnce(innerMap, 'idle', () => { void getDirections(); }); } async function getDirections() { // Request the needed libraries. const [{ Route }, { PinElement }] = await Promise.all([ google.maps.importLibrary('routes'), google.maps.importLibrary('marker'), ]); // Define routes request with an intermediate stop. const request = { origin: 'Parking lot, Christmas Tree Point Rd, San Francisco, CA 94131', destination: '100 Spinnaker Dr, Sausalito, CA 94965', // We're having a yummy lunch! intermediates: [{ location: '300 Finley Rd San Francisco, CA 94129' }], // But first, we golf! travelMode: 'DRIVING', fields: ['path', 'legs', 'viewport'], }; // Call computeRoutes to get the directions. const result = await Route.computeRoutes(request); if (!result.routes || result.routes.length === 0) { console.warn('No routes found'); return; } // Alter style based on marker index. function markerOptionsMaker(defaultOptions, waypointMarkerDetails) { const { index, totalMarkers } = waypointMarkerDetails; // Style the origin waypoint. if (index === 0) { return { ...defaultOptions, title: 'Origin', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'green', borderColor: 'green', scale: 1.5, }), }; } // Style all intermediate waypoints. if (!(index === 0 || index === totalMarkers - 1)) { return { ...defaultOptions, title: `Waypoint ${(index + 1).toString()}`, // Provide label for screenreaders map: innerMap, gmpClickable: true, // Make marker focusable and allow keyboard navigation content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'blue', borderColor: 'blue', scale: 1.5, // Increase size for better visibilty }), }; } // Style the destination waypoint. if (index === totalMarkers - 1) { return { ...defaultOptions, title: 'Destination', map: innerMap, gmpClickable: true, content: new PinElement({ glyphText: (index + 1).toString(), glyphColor: 'white', background: 'red', borderColor: 'red', scale: 1.5, }), }; } return { ...defaultOptions, map: innerMap }; } await result.routes[0].createWaypointAdvancedMarkers(markerOptionsMaker); // Fit the map to the route. innerMap.fitBounds(result.routes[0].viewport); innerMap.setHeading(270); // Create polylines and add them to the map. mapPolylines = result.routes[0].createPolylines(); mapPolylines.forEach((polyline) => { polyline.setMap(innerMap); }); } 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>
<gmp-map center="37.447646, -122.113878" zoom="12"></gmp-map>
</body>
</html>