Map creation and interactions
MapContainer
The MapContainer
component is responsible for creating the Leaflet Map instance and providing it to its child components, using a React Context.
When creating a MapContainer
element, its props are used as options to create the Map instance.
The following additional props are supported:
Prop | Type |
---|---|
bounds | LatLngBoundsExpression |
boundsOptions | FitBoundsOptions |
children | ReactNode |
className | string |
id | string |
placeholder | ReactNode |
style | CSSProperties |
whenReady | () => void |
Except for its children
, MapContainer
props are immutable: changing them after they have been set a first time will have no effect on the Map instance or its container.
The Leaflet Map
instance created by the MapContainer
element can be accessed by child components using one of the provided hooks.
- Absolute specifier import
- Bare specifier import
import { MapContainer } from 'https://cdn.esm.sh/react-leaflet/MapContainer'
import { MapContainer } from 'react-leaflet/MapContainer'
Hooks
useMap
Hook providing the Leaflet Map
instance in any descendant of a MapContainer
.
function MyComponent() {
const map = useMap()
console.log('map center:', map.getCenter())
return null
}
function MyMapComponent() {
return (
<MapContainer center={[50.5, 30.5]} zoom={13}>
<MyComponent />
</MapContainer>
)
}
- Absolute specifier import
- Bare specifier import
import { useMap } from 'https://cdn.esm.sh/react-leaflet/hooks'
import { useMap } from 'react-leaflet/hooks'
useMapEvents
Hook attaching the provided LeafletEventHandlerFnMap
event handlers to the map instance and returning the instance in any descendant of a MapContainer
.
function MyComponent() {
const map = useMapEvents({
click: () => {
map.locate()
},
locationfound: (location) => {
console.log('location found:', location)
},
})
return null
}
function MyMapComponent() {
return (
<MapContainer center={[50.5, 30.5]} zoom={13}>
<MyComponent />
</MapContainer>
)
}
- Absolute specifier import
- Bare specifier import
import { useMapEvents } from 'https://cdn.esm.sh/react-leaflet/hooks'
import { useMapEvents } from 'react-leaflet/hooks'
useMapEvent
Hook attaching a single event handler to the map instance and returning the instance in any descendant of a MapContainer
.
function MyComponent() {
const map = useMapEvent('click', () => {
map.setView([50.5, 30.5], map.getZoom())
})
return null
}
function MyMapComponent() {
return (
<MapContainer center={[50.5, 30.5]} zoom={13}>
<MyComponent />
</MapContainer>
)
}
- Absolute specifier import
- Bare specifier import
import { useMapEvent } from 'https://cdn.esm.sh/react-leaflet/hooks'
import { useMapEvent } from 'react-leaflet/hooks'