From b13e3ade3ccefe7dffe84f824bdedd3e512ce499 Mon Sep 17 00:00:00 2001 From: Leonardo Farias Date: Thu, 21 Dec 2023 22:23:42 -0300 Subject: [PATCH] Created auto zoom configuration for the map component --- .changeset/wicked-apples-swim.md | 5 ++++ packages/components/src/components/Map.tsx | 28 ++++++++++++++++--- packages/components/stories/Map.stories.ts | 31 ++++++++++++++++++++++ 3 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 .changeset/wicked-apples-swim.md diff --git a/.changeset/wicked-apples-swim.md b/.changeset/wicked-apples-swim.md new file mode 100644 index 00000000..560de7a4 --- /dev/null +++ b/.changeset/wicked-apples-swim.md @@ -0,0 +1,5 @@ +--- +'@portaljs/components': patch +--- + +Created auto zoom configuration for the map component diff --git a/packages/components/src/components/Map.tsx b/packages/components/src/components/Map.tsx index 9a902299..fcc921f0 100644 --- a/packages/components/src/components/Map.tsx +++ b/packages/components/src/components/Map.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { CSSProperties, useEffect, useState } from 'react'; import LoadingSpinner from './LoadingSpinner'; import loadData from '../lib/loadData'; import chroma from 'chroma-js'; @@ -30,7 +30,10 @@ export type MapProps = { title?: string; center?: { latitude: number | undefined; longitude: number | undefined }; zoom?: number; - style?: Object; + style?: CSSProperties; + autoZoomConfiguration?: { + layerName: string + } }; export function Map({ @@ -45,7 +48,8 @@ export function Map({ center = { latitude: 45, longitude: 45 }, zoom = 2, title = '', - style = {} + style = {}, + autoZoomConfiguration = undefined, }: MapProps) { const [isLoading, setIsLoading] = useState(false); const [layersData, setLayersData] = useState([]); @@ -118,6 +122,24 @@ export function Map({ }; if (title) info.addTo(map.target); + if(!autoZoomConfiguration) return; + + let layerToZoomBounds = L.latLngBounds(L.latLng(0, 0), L.latLng(0, 0)); + + layers.forEach((layer) => { + if(layer.name === autoZoomConfiguration.layerName) { + const data = layersData.find( + (layerData) => layerData.name === layer.name + )?.data; + + if (data) { + layerToZoomBounds = L.geoJSON(data).getBounds(); + return; + } + } + }); + + map.target.fitBounds(layerToZoomBounds); }} >