Search code examples
javascriptreactjsclickmarkersreact-google-maps

Change marker with label on click


I'm using react google maps to render a map with markers.

How can I change the icon / html of the marker on click?

  <GoogleMap
    defaultZoom={5}
    center={{ lat: (props.latLang && props.latLang.lat) ? props.latLang.lat : 51.5072178, lng: (props.latLang && props.latLang.lng) ? props.latLang.lng : -0.1275862 }}
    ref={mapRef}

  >
    {
      props.markers && props.markers.map((marker) => {
        return (marker.latitude && marker.longitude) ? <MarkerWithLabel
          position={{ lat: parseInt(marker.latitude), lng: parseInt(marker.longitude) }}
          labelAnchor={{ x: 50, y: 50 }}
          labelStyle={{ backgroundColor: "rgba(0,0,0,0)", fontSize: "32px", padding: "16px", width: '50px', height: '50px' }}
          onClick={markerClick}

        >
          <img onClick={imageClick} className={classes.grey} src={imageUrlFor(buildImageObj(marker.image))
              .width(100)
              .height(100)
              .fit("crop")
              .url()} />

        </MarkerWithLabel> : <></>;
      })
    }
    </GoogleMap>

The markerClick event gets fired on click but I can't manage to change the icon. For ex I would like to change the classes.grey image into a different class on click but just for the clicked marker.

Any ideas?

Edit:

markerClick function:

  const markerClick = function (e, x) {
    console.log('markerClick: ', e, '. x: ', x);
  }

Solution

  • I used Andrew Lohr's suggestion in the comment above and now it works. Here's how:

    added the following state variable:

    const [activeMarkerId, setActiveMarkerId] = useState('');

    Then the marker click event:

      const markerClick = function (marker) {
    setActiveMarkerId(marker.dashboardId);
    

    }

    And in the render function:

    <MarkerWithLabel
          position={{ lat: parseInt(marker.latitude), lng: parseInt(marker.longitude) }}
          labelAnchor={{ x: 25, y: 25 }}
          labelStyle={{ backgroundColor: "red", fontSize: "32px"}}
          onClick={() => markerClick(marker)}          
        >
          <img onClick={imageClick} className={marker.dashboardId === activeMarkerId ? classes.greyActive  : classes.grey} src={imageUrlFor(buildImageObj(marker.image))
              .width(50)
              .height(50)
              .fit("crop")
              .url()} />
    
        </MarkerWithLabel>
    

    Thanks, Andrew Lohr!