Leaflet MarkerClusterMap exhibits weird behavior, nodes only get added to map

24 Views Asked by At

I am trying to create a map from bikeTheftMapDataByYear data that looks like this.

{2019: "E-Scooters": [datapoints... 
     : Bikes: [datapoints...
      : "E-Bikes": [datapoints...
,
2020: "E-Scooter": 
...
}

For some reason, whenever I change the year/vehicle type the map does not change correctly. The number of markers only increases; I think the map for some reason is not "clearing" previous markers. Does anyone have any ideas why this is happening?


function MarkerClusterMap() {
  const [vehicleType, setVehicleType] = React.useState({
    name: 'Bikes',
  });

  const [year, setYear] = React.useState({
    name: 'all',
  });

  const handleVehicleChange = (event) => {
    const { value } = event.target;
    setVehicleType({
      name: value,
    });
  };

  const handleYearChange = (event) => {
    const { value } = event.target;
    setYear({
      name: value,
    });
  };

  return (
    <div>
      <div>
      <FormControl className={classes.formControl}>
        <InputLabel>Select vehicle</InputLabel>
        <Select
          value={vehicleType.name}
          id="regionSelector"
          name="region"
          onChange={handleVehicleChange}
          defaultValue="E-Scooters"
        >
          <MenuItem value="E-Scooters">E-Scooters</MenuItem>
          <MenuItem value="Bikes">Bikes</MenuItem>
          <MenuItem value="E-Bikes">E-Bikes</MenuItem>
        </Select>
      </FormControl>

      <FormControl className={classes.formControl}>
        <InputLabel>Select year</InputLabel>
        <Select
          value={year.name}
          id="regionSelector"
          name="region"
          onChange={handleYearChange}
          defaultValue="all"
        >
          <MenuItem value="2019">2019</MenuItem>
          <MenuItem value="2020">2020</MenuItem>
          <MenuItem value="2021">2021</MenuItem>
          <MenuItem value="2022">2022</MenuItem>
          <MenuItem value="2023">2023</MenuItem>
          <MenuItem value="all">all</MenuItem>
        </Select>
      </FormControl>

      {(typeof window !== 'undefined') ? ( // must condition inside of a div in case content is null

        <MapContainer>
          <TileLayer url="https://{s}.basemaps.cartocdn.com/rastertiles/voyager_labels_under/{z}/{x}/{y}.png" />

          <MarkerClusterGroup>
            {bikeTheftMapDataByYear[year.name][vehicleType.name].map((info) => (
              <Marker
                position={[info.center[0], info.center[1]]}
                key={info.k}
                icon={createIcon(vehicleType.name, 20)}
              >
                <Popup>{info.Location}</Popup>
              </Marker>
        </MapContainer>

      ) : <p> Map is loading... </p>}
    </div>

  );
}

export default MarkerClusterMap;

0

There are 0 best solutions below