feat: Refit map bounds on end or duration change
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import * as leaflet from 'leaflet';
|
||||
import { MapContainer, Polyline, TileLayer, useMap, useMapEvents } from 'react-leaflet';
|
||||
import Datetime from 'react-datetime';
|
||||
@@ -107,16 +107,28 @@ function MapEvents({ onMapChange }) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function FitBoundsOnLoad({ coords, mapState }) {
|
||||
function FitBounds({ coords, mapState, end, duration }) {
|
||||
const map = useMap();
|
||||
const prevEndRef = useRef();
|
||||
const prevDurationRef = useRef();
|
||||
|
||||
useEffect(() => {
|
||||
// If URL provides no center, fit the map to the bounds of the coordinates.
|
||||
if (mapState.center === null && coords.length > 0) {
|
||||
const prevEnd = prevEndRef.current;
|
||||
const prevDuration = prevDurationRef.current;
|
||||
|
||||
const endChanged = prevEnd && end.unix() !== prevEnd.unix();
|
||||
const durationChanged = prevDuration && duration.id !== prevDuration.id;
|
||||
|
||||
if ((mapState.center === null || endChanged || durationChanged) && coords.length > 0) {
|
||||
const bounds = leaflet.latLngBounds(coords);
|
||||
if (bounds.isValid()) {
|
||||
map.fitBounds(bounds);
|
||||
}
|
||||
}, [coords, mapState.center, map]);
|
||||
}
|
||||
|
||||
prevEndRef.current = end;
|
||||
prevDurationRef.current = duration;
|
||||
}, [coords, mapState.center, map, end, duration]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -144,7 +156,7 @@ function Map({end, duration, slider, mapState, setMapState}) {
|
||||
<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} />
|
||||
<FitBounds coords={coords} mapState={mapState} end={end} duration={duration} />
|
||||
<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