0

I am able to add all state boundaries to my leaflet map. But if I try to add clusters I am getting the below error.

Error in /~/components/MapBoundaries.tsx (138:34) map is not defined

Can you let me know how to fix it. Even I tried to California county boundaries after a specific zoom level. Even that is not working fine. I debugged and put console.log inside zoom functionalities but sill its not printing console. Can you let me know how to fix it, providing my code na dfiddle below https://stackblitz.com/edit/react-9czykt-7wvvqe?file=components%2FMapBoundaries.tsx,components%2FCaliforniaCounty.json

import React, { useState, useEffect, useRef } from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
//import geojsonData from './us-states.json';
import CaliforniaCounty from './CaliforniaCounty.json';

import { MapContainer, TileLayer, GeoJSON } from 'react-leaflet';

import statesData from './US-ONLY-States.js';

import 'leaflet.markercluster/dist/MarkerCluster.css';
import 'leaflet.markercluster/dist/MarkerCluster.Default.css';
import * as MarkerCluster from 'leaflet.markercluster';

const MapBoundaries = () => {
  const [geoData, setGeoData] = useState(null);
  const markerClusterGroup = new MarkerCluster.MarkerClusterGroup(); // Here!

  const [countyData, setCountyData] = useState(null); // State for county boundaries

  const mapRef = useRef(); // Add a map reference

  useEffect(() => {
    // Fetch your GeoJSON data
    // fetch('./us-states.json')
    //fetch('path/to/your/data.geojson')
    //  .then(response => response.json())
    //.then(data => setGeoData(data));
    setGeoData(statesData);
    // Create Marker Cluster Group here when map is available
    const markerClusterGroup = new MarkerCluster.MarkerClusterGroup();

    // Add cluster group to map after initial render
    if (mapRef.current) {
      markerClusterGroup.addTo(mapRef.current);
    }

    // Zoom event listener on the map
    if (mapRef.current) {
      mapRef.current.on('zoomend', handleZoomChange);
    }
  }, []);

  const handleZoomChange = () => {
    const currentZoom = mapRef.current.getZoom();

    // Logic to fetch Texas county data if not already loaded and zoom is right
    if (currentZoom >= 8 && !countyData) {
      console.log('if currentZoom', currentZoom);
      // Adjust zoom level '8' as needed
      fetch('./CaliforniaCounty.json')
        .then((response) => response.json())
        .then((data) => setCountyData(data));
    } else if (currentZoom < 8 && countyData) {
      console.log('else if currentZoom', currentZoom);

      // Optionally remove county data when zooming out
      setCountyData(null);
    }
  };

  const getColor = (d) => {
    return d > 1000
      ? '#800026'
      : d > 500
      ? '#BD0026'
      : d > 200
      ? '#E31A1C'
      : d > 100
      ? '#FC4E2A'
      : d > 50
      ? '#FD8D3C'
      : d > 20
      ? '#FEB24C'
      : d > 10
      ? '#FED976'
      : '#FFEDA0';
  };

  const style = (feature) => {
    return {
      fillColor: getColor(feature.properties.dataValue), // Assuming 'dataValue' is your data property
      weight: 2,
      opacity: 1,
      color: 'white',
      dashArray: '3',
      fillOpacity: 0.7,
    };
  };

  // const onEachFeature = (feature, layer) => {
  //   layer.bindPopup(
  //     feature.properties.name + ': ' + feature.properties.dataValue
  //   );
  // };

  const onEachFeature = (feature, layer) => {
    // Create a marker at the feature's location:
    const marker = L.marker(layer.getBounds().getCenter()); // Assuming center of the feature

    marker.bindPopup(
      feature.properties.name + ': ' + feature.properties.dataValue
    );

    layer.bindPopup(
      feature.properties.name + ': ' + feature.properties.dataValue
    );

    markerClusterGroup.addLayer(marker); // Add the marker to the cluster group
  };

  const onEachCountyFeature = (feature, layer) => {
    // Customize how you want to interact with county features here
    layer.bindPopup(`County Name: ${feature.properties.name}`);
  };

  return (
    <MapContainer
      center={[37.09024, -95.712891]}
      zoom={6}
      style={{ height: '500px' }}
      ref={mapRef} // Attach the ref to the MapContainer
    >
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
      {geoData && (
        <GeoJSON data={geoData} style={style} onEachFeature={onEachFeature} />
      )}
      {markerClusterGroup.addTo(map)} // Add the cluster group to the map

      {countyData && (
        <GeoJSON
          data={countyData}
          style={{ color: 'black', weight: 1 }} // Basic county boundary styling
          onEachFeature={onEachCountyFeature}
        />
      )}
    </MapContainer>
  );
};

export default MapBoundaries;
2
  • Your markerClusterGroup is not a ReactNode, remove the {markerClusterGroup.addTo(map)} from your template. You already try to imperatively add it to the map object.
    – ghybs
    Commented Feb 20 at 17:49
  • @ghybs: thanks for your response sorry I forgot to add my stackblizt link, I tried to modify your changes but still not working. Can you directly update here stackblitz.com/edit/…
    – Ram01
    Commented Feb 20 at 19:00

0