마커를 클릭 가능하도록 설정하고 마커에 접근성 기능 추가

클릭 이벤트 처리를 사용 설정하고, 클릭 이벤트 처리를 사용 설정하고, 스크린 리더용 설명 텍스트, 마커 배율 조정 등이 포함됩니다.

  • 마커를 클릭 가능 (또는 드래그 가능)할 수 있는 경우 마커는 키보드에 반응하고 마우스 입력입니다.
  • title 옵션에 지정된 텍스트는 스크린 리더에서 읽을 수 있으며 가 표시됩니다.
  • 마커의 크기가 커지면 모든 기기(특히 터치 스크린 기기)에서 마커와 상호작용하는 데 필요한 정확도가 줄어들고 접근성이 개선됩니다. 기본 마커는 WCAG AA 최소 크기를 충족합니다. WCAG AAA 대상 크기를 준수하려는 개발자에게 적합합니다. 마커 크기가 증가해야 합니다.

마커를 변경하는 방법은 기본 마커 맞춤설정을 참고하세요. 크기 조정, 제목 텍스트 추가 등이 가능합니다.

다음 예는 클릭 가능하고 포커스 가능한 마커가 5개 있는 지도를 보여줍니다. 제목 텍스트가 포함되어 있고 1.5배 배율로 설정되어 있습니다.

키보드를 사용하여 마커를 탐색하려면 다음 단계를 따르세요.

  1. Tab 키를 사용해 첫 번째 마커에 포커스를 맞춥니다. 동일한 지도에 마커가 여러 개 있는 경우 화살표 키를 사용하여 마커 간에 이동하세요.
  2. 마커를 클릭할 수 있는 경우 '클릭'하려면 Enter 키를 누릅니다. 마커에 정보 창이 있는 경우 클릭하거나 Enter 키 또는 스페이스 바를 눌러 정보 창을 열 수 있습니다. 정보 창이 닫히면 포커스가 연결된 마커로 돌아갑니다.
  3. 나머지 지도 컨트롤로 계속 이동하려면 Tab을 다시 누르세요.

마커를 클릭 가능하도록 설정

이 섹션에서는 마커가 클릭 이벤트에 반응하도록 설정하는 방법을 설명합니다. 마커를 클릭 가능하도록 설정하려면 다음 단계를 따르세요.

  • gmpClickable 속성을 true로 설정합니다.

TypeScript

const marker = new AdvancedMarkerElement({
    position,
    map,
    title: `${i + 1}. ${title}`,
    content: pin.element,
    gmpClickable: true,
});

자바스크립트

const marker = new AdvancedMarkerElement({
  position,
  map,
  title: `${i + 1}. ${title}`,
  content: pin.element,
  gmpClickable: true,
});

  • 클릭 이벤트 리스너를 추가하여 사용자 입력에 응답합니다.

TypeScript

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

자바스크립트

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

  • 마커를 다시 클릭할 수 없도록 하려면 removeListener를 호출하여 클릭을 삭제합니다. 이벤트 리스너:

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

접근성을 더욱 향상하려면 다음과 같이 하세요.

  • AdvancedMarkerElement.title를 사용하여 마커에 대한 설명 텍스트 설정 옵션을 선택합니다.
  • PinElementscale 속성을 사용하여 마커 배율을 늘립니다.

예시 코드 작성

샘플 소스 코드 전체 보기

TypeScript

async function initMap() {
    // Request needed libraries.
    const { Map, InfoWindow } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
    const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

    const map = new 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 InfoWindow();

    // Create the markers.
    tourStops.forEach(({position, title}, i) => {
        const pin = new PinElement({
            glyph: `${i + 1}`,
            scale: 1.5,
        });
        const marker = new AdvancedMarkerElement({
            position,
            map,
            title: `${i + 1}. ${title}`,
            content: pin.element,
            gmpClickable: true,
        });
        // 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);
        });
    });
}

initMap();

JavaScript

async function initMap() {
  // Request needed libraries.
  const { Map, InfoWindow } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary(
    "marker",
  );
  const map = new 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 InfoWindow();

  // Create the markers.
  tourStops.forEach(({ position, title }, i) => {
    const pin = new PinElement({
      glyph: `${i + 1}`,
      scale: 1.5,
    });
    const marker = new AdvancedMarkerElement({
      position,
      map,
      title: `${i + 1}. ${title}`,
      content: pin.element,
      gmpClickable: true,
    });

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

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

HTML

<html>
  <head>
    <title>Advanced Marker Accessibility</title>

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

    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"});</script>
  </body>
</html>

샘플 사용해 보기