Rendre les repères cliquables et accessibles

Lorsqu'un repère est cliquable ou déplaçable, il peut répondre aux entrées de clavier et de souris. Vous pouvez utiliser la souris ou le clavier pour faire glisser un repère (s'il est déplaçable) ou pour passer de l'un à l'autre. Le texte spécifié dans l'option title est visible par les lecteurs d'écran.

  • Pour rendre un repère cliquable, ajoutez un gestionnaire d'événements de clic.
  • Pour rendre un repère déplaçable, définissez la propriété AdvancedMarkerView.draggable sur true.
  • Pour définir le texte descriptif d'un repère, utilisez l'option AdvancedMarkerView.title.

Rendre un repère cliquable

L'exemple suivant montre une carte avec cinq repères cliquables et sélectionnables :

Pour parcourir les repères à l'aide du clavier :

  1. Utilisez la touche de tabulation pour sélectionner le premier repère. S'il y a plusieurs repères sur la même carte, utilisez les flèches pour passer de l'un à l'autre.
  2. Si le repère est cliquable, appuyez sur la touche Entrée pour cliquer dessus. Si un repère possède une fenêtre d'informations, vous pouvez l'ouvrir en cliquant dessus, ou en appuyant sur la touche Entrée ou la barre d'espace. Lorsque la fenêtre d'informations se ferme, le repère correspondant est de nouveau affiché.
  3. Appuyez de nouveau sur la touche Tabulation pour continuer à parcourir les autres commandes de la carte.

Voir le code

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>

Essayer l'exemple

Pour qu'un repère ne soit de nouveau plus cliquable, supprimez l'écouteur d'événements de clic.

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

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

Rendre un repère déplaçable

Les utilisateurs peuvent faire glisser des repères sur la carte avec la souris ou les touches fléchées si la fonctionnalité correspondante est activée. Pour rendre un repère déplaçable, définissez la propriété AdvancedMarkerView.draggable sur true.

L'exemple de carte suivant montre un repère déplaçable qui affiche sa nouvelle position une fois le déplacement terminé (l'événement dragend est déclenché) :

Pour faire glisser un repère à l'aide du clavier :

  1. Appuyez sur la touche de tabulation jusqu'à ce que les repères soient sélectionnés.
  2. Utilisez les touches fléchées pour accéder au repère souhaité.
  3. Pour pouvoir faire glisser le repère, appuyez sur Option+Espace ou Option+Entrée (Mac), ALT+Espace ou Alt+Entrée (Windows).
  4. Utilisez les touches fléchées pour déplacer le repère.
  5. Pour placer le repère à son nouvel emplacement, appuyez sur Espace ou Entrée. Cela désactivera également le déplacement des repères.
  6. Pour désactiver le déplacement et replacer le repère à sa position précédente, appuyez sur Échap.

Voir le code

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>

Essayer l'exemple

Définir un texte descriptif

Pour définir le texte descriptif d'un repère, qui peut être lu par les lecteurs d'écran, utilisez l'attribut AdvancedMarkerView.title, comme indiqué ci-dessous :

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

Lorsque l'attribut title est défini, le texte est visible par les lecteurs d'écran et apparaît lorsqu'ils pointent sur le repère.