3

So I am trying to have an active marker that is different from the rest of the non active marker.

So basically I want something like this.

enter image description here

To display all of the icon I am using the following.

that is displayed inside the map

{parkdata.features.map(park =>(
          <Marker key = {park.properties.PARK_ID} position={[
            park.geometry.coordinates[1], 
            park.geometry.coordinates[0]
           
          ]}
          onClick={()=>{this.selected(park);

            

The selected function that was intended to be used to change the active icon. But it does not seem to be doing anything

 selected(park){
    return(
    <Marker key = {park.properties.PARK_ID} position={[
      park.geometry.coordinates[1], 
      park.geometry.coordinates[0]
     
    ]}
    icon= {active}
    />
    )
  }

UPDATE: This is what I have now.

enter image description here

SO when I click on one of the markers I want to change to a different icon. For now, it just does not do anything.

0

1 Answer 1

2

The following example demonstrates how to create a markers and update icon property on marker click:

function createIcon(url) {
  return new L.Icon({
    iconUrl: url,
  });
}

function MapExample(props) {
  const [selectedIndex, setSelectedIndex] = useState(-1);

  function handleClick(e) {
    setSelectedIndex(e.target.options.index) //get index via custom marker property
  }

  function getMarkerIcon(index) {
    if(index === selectedIndex)
          return createIcon("/bigcity_red.png");
    return createIcon("/bigcity_green.png");
  }

  return (
    <Map center={props.center} zoom={props.zoom}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
      {props.data.map((item, index) => (
        <Marker
          key={index}
          index={index}
          position={item.position}
          icon={getMarkerIcon(index)}
          onclick={handleClick}
        />
      ))}
    </Map>
  );
}

Notes:

  • icon property for Marker component expects the value of L.Icon type
  • selectedIndex state is used to keep track of selected Marker (index)

Here is a demo for your reference