Place previously chosen location on map when going back

This commit is contained in:
Dana Lambert 2021-10-19 09:56:26 +13:00
parent ef3d0e4d7e
commit 695aceaaa0
2 changed files with 17 additions and 11 deletions

View file

@ -1,6 +1,6 @@
import { useState } from "react" import { useState } from "react"
import { MapContainer, TileLayer, Marker, Popup, useMapEvents, useMap } from 'react-leaflet' import { MapContainer, TileLayer, Marker, Popup, useMapEvents } from 'react-leaflet'
const NZ_BOUNDS = [ const NZ_BOUNDS = [
[-47.204642, 165.344238], [-47.204642, 165.344238],
@ -9,13 +9,22 @@ const NZ_BOUNDS = [
function LocationMarker(props) { function LocationMarker(props) {
const [position, setPosition] = useState(null) const [position, setPosition] = useState(null)
useMapEvents({ const map = useMapEvents({
click(e) { click(e) {
const newPosition = e.latlng; const newPosition = e.latlng;
setPosition(newPosition); setPosition(newPosition);
props.updateFilterState({"latitude": newPosition.lat, "longitude": newPosition.lng}); props.updateFilterState({"coordinates": newPosition});
props.setNextDisabled(false); 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 : ( return position === null ? null : (
@ -28,22 +37,19 @@ function LocationMarker(props) {
) )
} }
function FitNewZealandBounds() { const fitNZBounds = (map) => {
const map = useMap() map.fitBounds(NZ_BOUNDS);
map.fitBounds(NZ_BOUNDS)
return null
} }
export default function Map(props) { export default function Map(props) {
return ( return (
<div className="map-container"> <div className="map-container">
<MapContainer scrollWheelZoom={true}> <MapContainer scrollWheelZoom={true} whenCreated={fitNZBounds}>
<TileLayer <TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/> />
<LocationMarker {...props} /> <LocationMarker {...props} />
<FitNewZealandBounds />
</MapContainer> </MapContainer>
</div> </div>
) )

View file

@ -40,7 +40,7 @@ export default class MainPage extends React.Component {
return ( return (
<Container fluid className='main-container p-0'> <Container fluid className='main-container p-0'>
<Header/> <Header/>
<Stepper plants={this.state.plants} updateFilterState={this.updateFilterState} /> <Stepper plants={this.state.plants} filters={this.state.filters} updateFilterState={this.updateFilterState} />
</Container> </Container>
) )
} }