啟用拖曳功能後,使用者就能透過滑鼠或方向鍵在地圖上拖曳標記。如要將標記設計為可拖曳,請將 AdvancedMarkerElement.gmpDraggable
屬性設為 true
。
下方地圖範例展示一個可拖曳標記,在拖曳完成時會顯示更新後的位置 (觸發 dragend
事件):
如要使用鍵盤拖曳標記:
- 持續點按 Tab 鍵,直到焦點移至標記。
- 使用方向鍵移至所需的標記。
- 如要啟用拖曳功能,在 Mac 上請按下 Option + 空格鍵或 Option + Enter 鍵,在 Windows 上請按下 Alt + 空格鍵或 Alt + Enter 鍵。
- 使用方向鍵即可移動標記。
- 如要將標記放在新位置,請按下空格鍵或 Enter 鍵,這樣也會停用拖曳功能。
- 如要停用拖曳功能並將標記移回先前的位置,請按下 Esc 鍵。
查看程式碼
TypeScript
async function initMap() { // Request needed libraries. const { Map, InfoWindow } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; const map = new Map(document.getElementById('map') as HTMLElement, { center: {lat: 37.39094933041195, lng: -122.02503913145092}, zoom: 14, mapId: '4504f8b37365c3d0', }); const infoWindow = new InfoWindow(); const draggableMarker = new AdvancedMarkerElement({ map, position: {lat: 37.39094933041195, lng: -122.02503913145092}, gmpDraggable: true, title: "This marker is draggable.", }); draggableMarker.addListener('dragend', (event) => { const position = draggableMarker.position as google.maps.LatLng; infoWindow.close(); infoWindow.setContent(`Pin dropped at: ${position.lat}, ${position.lng}`); infoWindow.open(draggableMarker.map, draggableMarker); }); } initMap();
JavaScript
async function initMap() { // Request needed libraries. const { Map, InfoWindow } = await google.maps.importLibrary("maps"); const { AdvancedMarkerElement } = await google.maps.importLibrary("marker"); const map = new Map(document.getElementById("map"), { center: { lat: 37.39094933041195, lng: -122.02503913145092 }, zoom: 14, mapId: "4504f8b37365c3d0", }); const infoWindow = new InfoWindow(); const draggableMarker = new AdvancedMarkerElement({ map, position: { lat: 37.39094933041195, lng: -122.02503913145092 }, gmpDraggable: true, title: "This marker is draggable.", }); draggableMarker.addListener("dragend", (event) => { const position = draggableMarker.position; infoWindow.close(); infoWindow.setContent(`Pin dropped at: ${position.lat}, ${position.lng}`); infoWindow.open(draggableMarker.map, draggableMarker); }); } initMap();
設定說明文字
如要設定螢幕閱讀器可讀取的標記說明文字,請使用 AdvancedMarkerElement.title
屬性,如下所示:
const markerView = new google.maps.marker.AdvancedMarkerElement({
map,
position: { lat: 37.4239163, lng: -122.0947209 },
title: "Some descriptive text.",
});
設定 title
屬性後,螢幕閱讀器就能讀取文字,滑鼠游標懸停於標記上時也會顯示文字。