Home > database >  How to add an Aria Label to a Google Maps marker?
How to add an Aria Label to a Google Maps marker?

Time:02-18

I would like to add an aria-label on a marker object. Currently I have a function that loads all the markers and want to put an aria-label as a property of the marker. Currently I am putting the aria label as a property when I create the marker object but I think this may be wrong. How could I add an aria label to a marker?

loadLocationMarkers({ lat, lng }, idx) {
    const markerIcon = this.createIcon(idx);

    const markerObj = new google.maps.Marker({
      icon: markerIcon,
      index: idx,
      selected: idx === this.selected,
      map: this.map,
      position: new google.maps.LatLng(lat, lng),
      optimized: false,
      zIndex: this.calculateZIndex(idx),
      'aria-label': 'Location Marker',
    });

    if (markerObj.selected) {
      this.selectedMarkerObj = markerObj;
    }

    markerObj.addListener('click', () => {
      const index = markerObj.get('index');
      this.dispatch(updateSelected(index), this.handleClick(markerObj));
    });
    return markerObj;
  }

CodePudding user response:

Use title which will set the aria-label.

https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.title

new google.maps.Marker({
      icon: markerIcon,
      index: idx,
      selected: idx === this.selected,
      map: this.map,
      position: new google.maps.LatLng(lat, lng),
      optimized: false,
      zIndex: this.calculateZIndex(idx),
      title: 'Location Marker', // <--- added this
    });

From the output of the simple-markers sample with title="Hello World!".

<div
  aria-label="Hello World!"
  role="img"
  tabindex="-1"
  ...
>
  <img
    ...
  /><map
    ><area
      tabindex="-1"
      title="Hello World!"
      ...
  /></map>
</div>

Note: tabindex is -1 since there is no event listener on the marker.

  • Related