Search code examples
reactjsleafletreact-leaflet-v3

React function returns the last item in the JSON instead of mapping all of them


const ZoomToLocation = ({latitude, longitude}) => {
  const map = useMapEvents({
    click() {
    map.setView([latitude, longitude], 15)
    }
  })
  return null
}

function MyMap() {
return(
  <MapContainer>
    {loc.map(loc => (
     <Marker 
     key={loc.properties.id} 
     position={[loc.properties.y, loc.properties.x]}>
       <ZoomToLocation latitude={loc.properties.y} longitude={loc.properties.x}/>
     </Marker>
          ))
     }
  </MapContainer>
)}

It maps everything in the <Marker> component as I would expect, but doesn't do it in <ZoomToLocation>. Instead, it just returns the last item in the JSON.

Any idea what I'm doing wrong?


Solution

  • Instead of using <ZoomToLocation>, you could use the click event handler of <Marker> like this:

    {loc.map((l) => (
      <Marker
        key={l.properties.id}
        position={[l.properties.y, l.properties.x]}
        eventHandlers={{
          click: (e) => {
            map.flyTo(e.latlng, 15);
          },
        }}
      ></Marker>
    ))}
    

    This will centre the map on the latlng property of a marker when you click on it.

    You'll need to add the following so you can get a reference to map:

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

    and set the map using whenCreated:

    <MapContainer
      ...
      whenCreated={setMap}
    >
    

    There's a full working demo here.