Home > Enterprise >  How to render multiple markers from an array of coordinates in react leaflet
How to render multiple markers from an array of coordinates in react leaflet

Time:03-04

as the title says i'm trying to render multiple markers over the map by using react leaflet. I'm gathering all the coordinates that i receive from a BE response and i put them into an array. When i render the component i only see the map without my markers. So i'm probably missing out something.

Here's my code:

var arrCoordinates = [[/* coordinates 1 */], [/* coordinates2 */]...[/* coordinates n */]]

function MultipleMarkers(){
    
    const map = useMapEvent({
        click(){
            map.locate()
        }
    })
    return arrCoordinate.map(coordinata => {
        <Marker position={coordinata}
            icon={new Icon({iconUrl: marker, iconSize: [25, 41], iconAnchor: [12, 41]})}>
            <Popup>{Object.keys(elem).length > 0 ? elem.bodyfindSegnalazione[0][0].indirizzo   ' '   elem.bodyfindSegnalazione[0][0].civico   ' '   elem.bodyfindSegnalazione[0][0].quartiere : ''}</Popup>
        </Marker>
    })
}
return (
    <div id="mapid" style={{display: showMap}}>
    <MapContainer 
        center={center} zoom={12} 
        scrollWheelZoom={true}
        style={{ height: "100%", width: "100%" }}
    >
        <TileLayer
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <MultipleMarkers />
        
    </MapContainer>
    </div>
);

I'll appreciate any suggestions, thanks in advance. Peace

CodePudding user response:

What you are missing is the return statement before <Marker.

It should be

function MultipleMarkers() {
  const map = useMapEvent({
    click() {
      map.locate();
    }
  });

  return arrCoordinates.map((coordinata) => {
    return (
       <Marker position={coordinata}
        icon={new Icon({iconUrl: marker, iconSize: [25, 41], iconAnchor: [12, 41]})}>
        <Popup>{Object.keys(elem).length > 0 ? elem.bodyfindSegnalazione[0][0].indirizzo   ' '   elem.bodyfindSegnalazione[0][0].civico   ' '   elem.bodyfindSegnalazione[0][0].quartiere : ''}</Popup>
       </Marker>
    );
  });
}

Simplified example demo

  • Related