I have the following functional react component which correctly displays two static markers within a 'bounds' box which fits both markers inside.
I would like to be able to pass in an array of latitude and longitude values for the map to display but I can't work out how to do it.
This is the working, static example:
import React from 'react'
import { MapContainer, TileLayer, Marker } from 'react-leaflet'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
const MapLeaflet = () => {
// STATIC MARKER POSITIONS
const position = [42.2974279, -85.628292];
const position2 = [-8.852507, -45.351563];
// BOUNDS CODE
const bounds = L.latLngBounds([position, position2]);
return (
<MapContainer
className=" map"
center={position}
bounds={bounds}
>
<Marker key={key} position={position}>
<Heart/>
</Marker>
<Marker key={key} position={position2}>
<Heart/>
</Marker>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>
)
}
If I pass is {coords} I can then dynamically display the markers:
const MapLeaflet = ({coors}) => {
...
{ coords && coords.map(coord => (
<Marker key={key} latitude={coord[0]} longitude={coord[1]}>
<SomeMarker/>
</Marker>
))}
...
}
But obviously, the map is not yet taking these 'coords' into consideration for the bounds. The console.log output of the passed in coords array is as follows:
0: (2) [51.52167056034225, -0.12894469488176763]
1: (2) [46.58635156377568, 2.1796793230151184]
2: (2) [40.819721, 14.341111]
Somehow I need to replace the following line with a reference to the passed in coords in a format the code accepts, but I can't work out how to do it.
const bounds = L.latLngBounds([position, position2]);
to something like
const bounds = L.latLngBounds({coords});
Any help would be very much appreciated.
Kind regards, Matt