Membuat penanda dapat diklik dan dapat diakses

Saat penanda dapat diklik atau dapat ditarik, penanda dapat merespons input keyboard dan mouse. Anda dapat menggunakan mouse atau keyboard untuk berpindah antarpenanda, dan untuk memindahkan penanda jika dapat ditarik. Teks yang ditentukan dalam opsi title terlihat pada pembaca layar.

  • Untuk membuat penanda dapat diklik, tambahkan pengendali peristiwa klik.
  • Untuk membuat penanda dapat ditarik, tetapkan properti AdvancedMarkerView.draggable ke true.
  • Untuk menetapkan teks deskriptif bagi penanda, gunakan opsi AdvancedMarkerView.title.

Membuat penanda dapat diklik

Contoh berikut menampilkan peta dengan lima penanda yang dapat diklik dan dapat difokuskan:

Untuk melihat penanda menggunakan keyboard:

  1. Gunakan tombol tab untuk berfokus pada penanda pertama; jika ada beberapa penanda pada peta yang sama, gunakan tombol panah untuk melihat seluruh penanda.
  2. Jika penanda dapat diklik, tekan tombol enter untuk "mengklik". Jika penanda memiliki jendela info, Anda dapat membukanya dengan mengklik, atau dengan menekan tombol enter atau spasi. Saat jendela info ditutup, fokus akan kembali ke penanda terkait.
  3. Tekan tab lagi untuk terus berpindah di antara kontrol peta lainnya.

Melihat kode

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>

Mencoba Contoh

Agar penanda tidak dapat diklik lagi, hapus pemroses peristiwa klik:

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

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

Membuat penanda dapat ditarik

Saat fungsi dapat ditarik diaktifkan, pengguna dapat menarik penanda pada peta menggunakan mouse atau tombol panah. Untuk membuat penanda dapat ditarik, tetapkan properti AdvancedMarkerView.draggable ke true.

Peta contoh berikut menunjukkan penanda yang dapat ditarik yang menampilkan posisi yang diperbarui saat penarikan selesai (peristiwa dragend diaktifkan):

Untuk menarik penanda dengan keyboard:

  1. Tekan tombol tab sampai penanda difokuskan.
  2. Gunakan tombol panah untuk berpindah ke penanda yang diinginkan.
  3. Untuk mengaktifkan penarikan, tekan Option + Spasi atau Option + Enter (Mac), Alt + Spasi atau Alt + Enter (Windows).
  4. Gunakan tombol panah untuk memindahkan penanda.
  5. Untuk menempatkan penanda di lokasi barunya, tekan Spasi atau Enter. Tindakan ini juga akan menonaktifkan penarikan.
  6. Untuk menonaktifkan penarikan dan mengembalikan penanda ke posisi sebelumnya, tekan Esc.

Melihat kode

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>

Mencoba Contoh

Menetapkan teks deskriptif

Untuk menetapkan teks deskriptif bagi penanda yang dapat dibaca oleh pembaca layar, gunakan atribut AdvancedMarkerView.title, seperti yang ditampilkan di sini:

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

Saat atribut title ditetapkan, teks akan terlihat pada pembaca layar, dan akan muncul saat mouse diarahkan ke penanda.