feat: Fit map to all points on initial load
This commit is contained in:
@@ -107,6 +107,20 @@ function MapEvents({ onMapChange }) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function FitBoundsOnLoad({ coords, mapState }) {
|
||||
const map = useMap();
|
||||
|
||||
useEffect(() => {
|
||||
// If URL provides no center, fit the map to the bounds of the coordinates.
|
||||
if (mapState.center === null && coords.length > 0) {
|
||||
const bounds = leaflet.latLngBounds(coords);
|
||||
map.fitBounds(bounds);
|
||||
}
|
||||
}, [coords, mapState.center, map]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function Map({end, duration, slider, mapState, setMapState}) {
|
||||
const [data, loading] = useSensor('owntracks', 'OwnTracks', end, duration);
|
||||
|
||||
@@ -114,13 +128,6 @@ function Map({end, duration, slider, mapState, setMapState}) {
|
||||
|
||||
const coords = data.length ? data.filter(x => !range || (x.time >= range[0] && x.time <= range[1])).map(({ lat, lon }) => [lat, lon]).filter(([lat, lon]) => lat !== null || lon !== null) : [];
|
||||
|
||||
useEffect(() => {
|
||||
// If URL provides no center, set it from the data once it's loaded.
|
||||
if (mapState.center === null && coords.length > 0) {
|
||||
setMapState(prev => ({ ...prev, center: coords[coords.length - 1] }));
|
||||
}
|
||||
}, [coords, mapState.center, setMapState]);
|
||||
|
||||
const handleSubmit = (e) => {
|
||||
e.preventDefault();
|
||||
const api_key = e.target[0].value;
|
||||
@@ -133,10 +140,11 @@ function Map({end, duration, slider, mapState, setMapState}) {
|
||||
<p>Loading...</p>
|
||||
:
|
||||
coords.length ?
|
||||
(mapState.center &&
|
||||
<MapContainer center={mapState.center} zoom={mapState.zoom} scrollWheelZoom={true} style={{ width: '100%', height: 'calc(100vh - 2.5rem)' }}>
|
||||
<ChangeView center={mapState.center} zoom={mapState.zoom} />
|
||||
(
|
||||
<MapContainer center={mapState.center || [0, 0]} zoom={mapState.zoom} scrollWheelZoom={true} style={{ width: '100%', height: 'calc(100vh - 2.5rem)' }}>
|
||||
{mapState.center && <ChangeView center={mapState.center} zoom={mapState.zoom} />}
|
||||
<MapEvents onMapChange={setMapState} />
|
||||
<FitBoundsOnLoad coords={coords} mapState={mapState} />
|
||||
<TileLayer
|
||||
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
|
||||
url='https://maptiles.p.rapidapi.com/en/map/v1/{z}/{x}/{y}.png?rapidapi-key=4375b0b1d8msh0c9e7fa3efb9adfp1769dfjsnd603a0387fea'
|
||||
|
Reference in New Issue
Block a user