Add marker to map on click with coordinate tooltip

This commit is contained in:
Dana Lambert 2021-10-18 17:19:45 +13:00
parent 19b2b00750
commit 05665b545b

View file

@ -1,10 +1,30 @@
import { MapContainer, TileLayer, useMap } from 'react-leaflet'
import { useState } from "react"
import { MapContainer, TileLayer, Marker, Popup, useMapEvents, useMap } from 'react-leaflet'
const NZ_BOUNDS = [
[-47.204642, 165.344238],
[-34.307144, 179.824219]
]
function LocationMarker() {
const [position, setPosition] = useState(null)
useMapEvents({
click(e) {
setPosition(e.latlng)
},
})
return position === null ? null : (
<Marker position={position}>
<Popup>
<strong>Latitude:</strong> {position.lat} <br/>
<strong>Longitude:</strong> {position.lng}
</Popup>
</Marker>
)
}
function FitNewZealandBounds() {
const map = useMap()
map.fitBounds(NZ_BOUNDS)
@ -19,6 +39,7 @@ export default function Map() {
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<LocationMarker />
<FitNewZealandBounds />
</MapContainer>
</div>