0

There is a map state defined as

const [map, setMap] = useState(null);

Here is the snippet which is supposed to initialize the map:

<MapContainer
  center={
    areaOfInterest.latitude ? [areaOfInterest.latitude, areaOfInterest.longitude] : [39, 22.5]
  }
  zoom={10}
  zoomControl={false}
  doubleClickZoom={false}
  style={{
    width: "98vw",
    height: "92vh",
    position: "fixed",
    marginTop: 5,
    left: 10,
  }}
  whenReady={(map) => {
    setMap(map);
    console.log("Map is initialized! It is : " , map);
  }}
>

It seems to do its job but in the end what is created is not an instance of L.Map. I verified that with typeOf and instanceOf log statements. It is a generic Object.

Any clues what I might be doing wrong? FYI, I am attempting to avoid react-leaflet hooks such as useMap and useMapEvent as they've given me a lot of trouble in the past.

Thanks in advance.

[EDIT]: After taking a look at the relevant documentation as pointed out by @BhaveshParvatkar, it is clear that instead of whenReady, I should use whenCreated which takes the Leaflet.Map as its parameter. However, it doesn't seem to run at all. I have some debug statements in it which never even trigger, and I assumed that a function called "whenCreated" would run when the map is first initialized. Any clues?

4
  • Does whenReady callback return anything in the param? Acording to the doc the declaration of whenReady is () => void Commented Dec 23, 2023 at 11:46
  • @BhaveshParvatkar it returns something, but I'm not sure what it is... {target: NewClass} target : NewClass {options: {…}, _handlers: Array(8), _layers: {…}, _zoomBoundLayers: {…}, _sizeChanged: false, …} [[Prototype]] : Object This seems like it has the properties of a Leaflet map, but it is not an instance of it. It is true, the docs say () => void, but if that's the case, does it mean the only way I can access the map object is through the useMap hook? Commented Dec 27, 2023 at 7:28
  • Yes, it's not an instance of it. Also, it's written in the same doc "The Leaflet Map instance created by the MapContainer element can be accessed by child components using one of the provided hooks.". Any reason why you don't want to use it? Commented Dec 27, 2023 at 11:22
  • Yeah, I ended up using the useMap() hook, worked well. I had some reservations because I wasn't sure how to incorporate it in the existing code structure but I figured it out. Thanks a lot for your help man! Commented Dec 28, 2023 at 12:51

0