right-tree/frontend/src/components/steps/location/Map.js

64 lines
1.6 KiB
JavaScript
Raw Normal View History

import { useState } from "react"
import { MapContainer, TileLayer, Marker, useMapEvents } from 'react-leaflet'
2021-10-18 17:09:56 +13:00
const NZ_BOUNDS = [
[-47.204642, 165.344238],
[-34.307144, 179.824219]
]
function LocationMarker(props) {
const [position, setPosition] = useState(null)
const map = useMapEvents({
click(e) {
const newPosition = e.latlng;
setPosition(newPosition);
props.updateFilterState({ "coordinates": newPosition });
props.setNextDisabled(false);
}
})
map.whenReady(() => {
const savedCoordinates = props.filters["coordinates"];
if (!position && savedCoordinates) {
setPosition(savedCoordinates);
props.setNextDisabled(false);
map.flyTo(savedCoordinates, 9)
}
})
return position === null ? null : (
<Marker position={position} />
)
}
const fitNZBounds = (map) => {
map.fitBounds(NZ_BOUNDS);
2021-10-18 17:09:56 +13:00
}
function CoordinatesDisplay(props) {
const savedCoordinates = props.filters["coordinates"];
return savedCoordinates ? (
<div className='coordinates-display'>
<strong>Latitude:</strong> {savedCoordinates.lat} <br />
<strong>Longitude:</strong> {savedCoordinates.lng}
</div>
) : null;
}
export default function Map(props) {
return (
<div className="map-container">
<CoordinatesDisplay {...props} />
<MapContainer scrollWheelZoom={true} whenCreated={fitNZBounds}>
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<LocationMarker {...props} />
</MapContainer>
</div>
)
}