Open giangnguyenpzh opened 10 months ago
use eslint-plugin-react-perf and cache all props before passing, and react.memo for all components
Solution:
DirectionsRenderer automatically adjusts the zoom and viewport when a new route is drawn. To prevent this, you can use the preserveViewport option.
By setting preserveViewport: true, you can stop the map from zooming after the first render. For example, using an approach like this, you can make the map zoom to fit the route on the first render and then keep the zoom level unchanged on subsequent direction changes:
const [isDirectionsLoaded, setDirectionsLoaded] = useState<boolean>(false);
const onDirectionsRendererLoad = () => {
setTimeout(() => {
setDirectionsLoaded(true); // After the first load, set preserveViewport to true
});
};
const onDirectionsRendererUnMount = () => {
setDirectionsLoaded(false); // Optional: Reset if the renderer is unmounted
};
return (
<>
...
{directions && (
<DirectionsRenderer
directions={directions}
options={{
preserveViewport: isDirectionsLoaded, // Prevent zoom after the initial load
}}
onLoad={onDirectionsRendererLoad}
onUnmount={onDirectionsRendererUnMount}
/>
)}
</>
)
With this solution, the map will zoom to fit the route only on the first render, and subsequent route changes won't affect the zoom level.
how to disable map zoom when DirectionsRenderer redraws the path
const Directions = ({ directionsResponse }) => { return ( <DirectionsRenderer directions={directionsResponse} options={{ polylineOptions: { strokeColor: 'blue', }, markerOptions: { icon: { url: "icon.png", }, }, }} /> ) }