From 19d996da508e77a22d411db94087fd476d537d3c Mon Sep 17 00:00:00 2001 From: Mikel Larreategi Date: Tue, 27 Feb 2024 18:35:12 +0100 Subject: [PATCH] fix bound calculations --- src/components/MapLibre/MapLibre.jsx | 9 +++++++- src/components/MapLibre/utils.js | 33 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/components/MapLibre/MapLibre.jsx b/src/components/MapLibre/MapLibre.jsx index f003a7b..b75a4ee 100644 --- a/src/components/MapLibre/MapLibre.jsx +++ b/src/components/MapLibre/MapLibre.jsx @@ -7,15 +7,22 @@ import 'maplibre-gl/dist/maplibre-gl.css'; import './style.css'; import { basicOSMStyle } from './utils'; import markerPNG from '../../icons/marker-icon.png'; +import { calcBoundsFromCoordinates } from './utils'; export const FitBounds = (props) => { const { markers } = props; const map = useMap(); - map.current.fitBounds( + + const bounds = calcBoundsFromCoordinates( markers.map((marker) => [ parseFloat(marker.longitude), parseFloat(marker.latitude), ]), + ); + + map.current.fitBounds( + bounds, + { padding: { top: 50, bottom: 50, left: 50, right: 50 }, }, diff --git a/src/components/MapLibre/utils.js b/src/components/MapLibre/utils.js index c8f1aae..626900f 100644 --- a/src/components/MapLibre/utils.js +++ b/src/components/MapLibre/utils.js @@ -18,3 +18,36 @@ export const basicOSMStyle = { }, ], }; + +/* taken from https://stackoverflow.com/a/71659589/1427863 + * + */ + +const getSWCoordinates = (coordinatesCollection) => { + const lowestLng = Math.min( + ...coordinatesCollection.map((coordinates) => coordinates[0]), + ); + const lowestLat = Math.min( + ...coordinatesCollection.map((coordinates) => coordinates[1]), + ); + + return [lowestLng, lowestLat]; +}; + +const getNECoordinates = (coordinatesCollection) => { + const highestLng = Math.max( + ...coordinatesCollection.map((coordinates) => coordinates[0]), + ); + const highestLat = Math.max( + ...coordinatesCollection.map((coordinates) => coordinates[1]), + ); + + return [highestLng, highestLat]; +}; + +export const calcBoundsFromCoordinates = (coordinatesCollection) => { + return [ + getSWCoordinates(coordinatesCollection), + getNECoordinates(coordinatesCollection), + ]; +};