Как сделать маркер кликабельным и доступным для перетаскивания

Если вы сделаете маркер кликабельным и доступным для перетаскивания, он будет реагировать на клики и нажатия клавиш. Это даст возможность переключаться между маркерами и перемещать их с помощью мыши или клавиатуры. Текст, добавленный с помощью атрибута title, будет доступен для программ чтения с экрана.

  • Чтобы сделать маркер кликабельным, добавьте обработчик событий кликов.
  • Чтобы сделать маркер доступным для перетаскивания, установите для свойства AdvancedMarkerView.draggable значение true.
  • Чтобы добавить для маркера описательный текст, настройте атрибут AdvancedMarkerView.title.

Кликабельный маркер

Ниже показана карта, на которой настроено пять кликабельных, фокусируемых маркеров.

Как переходить между маркерами с помощью клавиатуры

  1. Чтобы выбрать первый маркер, нажмите клавишу Tab. Если на карте несколько маркеров, вы можете переключаться между ними с помощью клавиш со стрелками.
  2. Если маркер кликабелен, нажать на него можно с помощью клавиши "Ввод". Информационное окно маркера (если оно есть) можно открыть кнопкой мыши, клавишей "Ввод" или клавишей "Пробел". После закрытия такого окна снова выделяется связанный с ним маркер.
  3. Повторное нажатие клавиши Tab вызывает переход к следующему элементу управления на карте.

Посмотреть код

TypeScript

function initMap() {
    const map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
        zoom: 12,
        center: { lat: 34.84555, lng: -111.8035 },
        mapId: '4504f8b37365c3d0',
    });

    // Set LatLng and title text for the markers. The first marker (Boynton Pass)
    // receives the initial focus when tab is pressed. Use arrow keys to
    // move between markers; press tab again to cycle through the map controls.
    const tourStops = [
        {
            position: { lat: 34.8791806, lng: -111.8265049 },
            title: "Boynton Pass"
        },
        {
            position: { lat: 34.8559195, lng: -111.7988186 },
            title: "Airport Mesa"
        },
        {
            position: { lat: 34.832149, lng: -111.7695277 },
            title: "Chapel of the Holy Cross"
        },
        {
            position: { lat: 34.823736, lng: -111.8001857 },
            title: "Red Rock Crossing"
        },
        {
            position: { lat: 34.800326, lng: -111.7665047 },
            title: "Bell Rock"
        },
    ];

    // Create an info window to share between markers.
    const infoWindow = new google.maps.InfoWindow();

    // Create the markers.
    tourStops.forEach(({position, title}, i) => {
        const pinView = new google.maps.marker.PinView({
            glyph: `${i + 1}`,
        });

        const marker = new google.maps.marker.AdvancedMarkerView({
            position,
            map,
            title: `${i + 1}. ${title}`,
            content: pinView.element,
        });

        // Add a click listener for each marker, and set up the info window.
        marker.addListener('click', ({ domEvent, latLng }) => {
            const { target } = domEvent;
            infoWindow.close();
            infoWindow.setContent(marker.title);
            infoWindow.open(marker.map, marker);
        });
    });
}

declare global {
    interface Window {
        initMap: () => void;
    }
}

window.initMap = initMap;

JavaScript

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 12,
    center: { lat: 34.84555, lng: -111.8035 },
    mapId: "4504f8b37365c3d0",
  });
  // Set LatLng and title text for the markers. The first marker (Boynton Pass)
  // receives the initial focus when tab is pressed. Use arrow keys to
  // move between markers; press tab again to cycle through the map controls.
  const tourStops = [
    {
      position: { lat: 34.8791806, lng: -111.8265049 },
      title: "Boynton Pass",
    },
    {
      position: { lat: 34.8559195, lng: -111.7988186 },
      title: "Airport Mesa",
    },
    {
      position: { lat: 34.832149, lng: -111.7695277 },
      title: "Chapel of the Holy Cross",
    },
    {
      position: { lat: 34.823736, lng: -111.8001857 },
      title: "Red Rock Crossing",
    },
    {
      position: { lat: 34.800326, lng: -111.7665047 },
      title: "Bell Rock",
    },
  ];
  // Create an info window to share between markers.
  const infoWindow = new google.maps.InfoWindow();

  // Create the markers.
  tourStops.forEach(({ position, title }, i) => {
    const pinView = new google.maps.marker.PinView({
      glyph: `${i + 1}`,
    });
    const marker = new google.maps.marker.AdvancedMarkerView({
      position,
      map,
      title: `${i + 1}. ${title}`,
      content: pinView.element,
    });

    // Add a click listener for each marker, and set up the info window.
    marker.addListener("click", ({ domEvent, latLng }) => {
      const { target } = domEvent;

      infoWindow.close();
      infoWindow.setContent(marker.title);
      infoWindow.open(marker.map, marker);
    });
  });
}

window.initMap = initMap;

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;
}

[class$=api-load-alpha-banner] {
  display: none;
}

HTML

<html>
  <head>
    <title>Advanced Marker Accessibility</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <!--
      The `defer` attribute causes the callback to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises.
      See https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&libraries=marker&v=beta"
      defer
    ></script>
  </body>
</html>

Примеры кода

Чтобы снова сделать маркер некликабельным, удалите прослушиватель событий кликов.

// Adding the listener.
const clickListener = markerView.addListener('click', () => {...});

// Removing the listener.
google.maps.event.removeListener(clickListener);

Как сделать маркер перетаскиваемым

Перетаскиваемый маркер можно перемещать по карте с помощью мыши или клавиш со стрелками. Чтобы сделать маркер доступным для перетаскивания, установите для свойства AdvancedMarkerView.draggable значение true.

Ниже показана карта, на которой настроен перетаскиваемый маркер. Он устанавливается в новой точке, когда перетаскивание завершается (при активации события dragend).

Как перетащить маркер с помощью клавиатуры

  1. Чтобы выбрать маркеры, нажимайте клавишу Tab.
  2. Перейдите к нужному маркеру с помощью клавиш со стрелками.
  3. Чтобы начать перетаскивание, нажмите Option + Пробел или Option + Ввод (Mac), Alt + Пробел или Alt + Ввод (Windows).
  4. Перетащите маркер с помощью клавиш со стрелками.
  5. Чтобы установить маркер в новой точке, нажмите Пробел или Ввод. При этом функция перетаскивания отключится.
  6. Если вы хотите отключить функцию перетаскивания и вернуть маркер в исходное положение, нажмите Esc.

Посмотреть код

TypeScript

function initMap() {
    const map = new google.maps.Map(document.getElementById('map') as HTMLElement, {
        center: {lat: 37.39094933041195, lng: -122.02503913145092},
        zoom: 14,
        mapId: '4504f8b37365c3d0',
    });

    const infoWindow = new google.maps.InfoWindow();

    const draggableMarker = new google.maps.marker.AdvancedMarkerView({
        map,
        position: {lat: 37.39094933041195, lng: -122.02503913145092},
        draggable: 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);
    });

}

declare global {
    interface Window {
        initMap: () => void;
    }
}
window.initMap = initMap;

JavaScript

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 37.39094933041195, lng: -122.02503913145092 },
    zoom: 14,
    mapId: "4504f8b37365c3d0",
  });
  const infoWindow = new google.maps.InfoWindow();
  const draggableMarker = new google.maps.marker.AdvancedMarkerView({
    map,
    position: { lat: 37.39094933041195, lng: -122.02503913145092 },
    draggable: 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);
  });
}

window.initMap = initMap;

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;
}

[class$=api-load-alpha-banner] {
  display: none;
}

HTML

<html>
  <head>
    <title>Draggable Advanced Marker</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <!--
      The `defer` attribute causes the callback to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises.
      See https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&libraries=marker&v=beta"
      defer
    ></script>
  </body>
</html>

Примеры кода

Как добавить описательный текст

Чтобы добавить для маркера описательный текст, доступный для программ чтения с экрана, используйте атрибут AdvancedMarkerView.title, как показано ниже.

    const markerView = new google.maps.marker.AdvancedMarkerView({
        map,
        position: { lat: 37.4239163, lng: -122.0947209 },
        title: "Some descriptive text.",
    });

Если атрибут title задан, текст будет распознаваться программой чтения с экрана и отображаться при наведении указателя мыши на маркер.