使标记可拖动

将标记设为可拖动后,用户可以使用鼠标或箭头键来拖动地图上的标记。如要使标记可拖动,请将 AdvancedMarkerElement.gmpDraggable 属性设置为 true

下例中的地图就展示了一个可拖动的标记,该标记会在拖动完成(触发 dragend 事件)后显示其新位置:

要使用键盘拖动标记,请按以下说明操作:

  1. 按 Tab 键,直至标记获得焦点。
  2. 使用箭头键可移动到所需的标记。
  3. 如要激活拖动功能,请按 Option 键 + 空格键Option 键 + Enter 键 (Mac),或者按 Alt 键 + 空格键Alt 键 + Enter 键 (Windows)。
  4. 使用箭头键可移动标记。
  5. 要将标记放在新位置,请按空格键Enter 键。执行此操作也会同时关闭拖动功能。
  6. 如要关闭拖动功能,并将标记移回之前的位置,请按 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 属性后,文本内容可由屏幕阅读器读取,并且将鼠标悬停在标记上时会显示文本。