Reputation: 569
I created a react FC and calling a rest service in the "useEffect" which should receive an array of MapPoints. For each of those mappoints i want to create a "Marker", but it doesn't work.. If I add a "static" list of mappoints, it works..
MapComponent:
return isLoading
? <h1>Data are loading...</h1>
:
<MapContainer center={[47.217324, 13.097555]} zoom={5} scrollWheelZoom={false}>
<TileLayer attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MapMarkers mapPoints={data}/>
</MapContainer>
MapMarkersComponent:
export const MapMarkers : React.FC<Props> = ({mapPoints}) => {
const markers = mapPoints.map((x, index) => {
console.log(x);
<Marker key={index} position={{lat: x.Latitude, lng: x.Longitude}}>
<Popup>
<span>test</span>
</Popup>
</Marker>
})
return <Fragment>{markers}</Fragment>
}
any ideas?
Upvotes: 0
Views: 1414
Reputation: 569
Finally I found the issue.. I am using typescript and I had an issue in the MapPoint object.. So the x.Latitude was not recognized..
Upvotes: 0
Reputation: 14570
I am not sure where your mistake lies but I can provide an example for you to see it's working
In the map comp:
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://api-adresse.data.gouv.fr/search/?q=paris&type=street")
.then((response) => response.json())
.then((response) => {
// console.log(response);
setData(response.features);
});
}, []);
... rest of the code as yours
and in the markers comp exactly the same as yours only I changed the position values cause it is different from your api and also add a return inside markers function where you are mapping the markers
const MapMarkers = ({ mapPoints }) => {
const markers = mapPoints.map((x, index) => {
// console.log(x);
const {
geometry: { coordinates }
} = x;
return (
<Marker
key={index}
position={{ lat: coordinates[1], lng: coordinates[0] }}
icon={icon}
>
<Popup>
<span>test</span>
</Popup>
</Marker>
);
});
return markers;
};
Upvotes: 1