diff --git a/mapper/src/App.js b/mapper/src/App.js index 646003a..6b5ad30 100644 --- a/mapper/src/App.js +++ b/mapper/src/App.js @@ -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); - map.fitBounds(bounds); + 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}) { {mapState.center && } - +