|
1 | | - |
2 | 1 | import useMap from "./useMap"; |
3 | | -import { bbox } from '@turf/turf'; |
| 2 | +import { bbox, AllGeoJSON } from '@turf/turf'; |
4 | 3 | import { LngLatBoundsLike, FitBoundsOptions, GeoJSONSource } from 'maplibre-gl'; |
5 | 4 |
|
6 | | - |
7 | 5 | export interface useFitLayerBoundsPros { |
8 | | - layerId: string, |
9 | | - type: "geojson"| "wms" | "vt", |
10 | | - fitBoundsOptions?: FitBoundsOptions |
| 6 | + layerId: string; |
| 7 | + type: "geojson" | "wms" | "vt"; |
| 8 | + fitBoundsOptions?: FitBoundsOptions; |
11 | 9 | } |
12 | | - function useFitLayerBounds(props: useFitLayerBoundsPros){ |
13 | 10 |
|
| 11 | +function useFitLayerBounds(props: useFitLayerBoundsPros) { |
14 | 12 | const mapHook = useMap({ mapId: undefined }); |
15 | | - const layerSource = props.layerId ? mapHook?.map?.getLayer?.(props.layerId)?.source : undefined; |
16 | | - const geojson = layerSource && (mapHook.map?.getSource(layerSource) as GeoJSONSource)._data; |
17 | | - const _geojson = layerSource && { |
18 | | - type: 'FeatureCollection', |
19 | | - features: mapHook.map?.querySourceFeatures(layerSource) |
20 | | - }; |
21 | 13 |
|
| 14 | + const layerSource = props.layerId ? mapHook?.map?.getLayer?.(props.layerId)?.source : undefined; |
22 | 15 |
|
23 | 16 | if (!layerSource) { |
24 | 17 | return; |
25 | 18 | } |
26 | 19 |
|
27 | | - mapHook.map?.fitBounds(typeof geojson === 'string' ? bbox(_geojson) as LngLatBoundsLike : bbox(geojson) as LngLatBoundsLike, |
28 | | - props.fitBoundsOptions |
| 20 | + const source = mapHook.map?.getSource(layerSource); |
| 21 | + let geojson: AllGeoJSON | undefined; |
| 22 | + |
| 23 | + if (source && (source as GeoJSONSource)._data) { |
| 24 | + geojson = (source as GeoJSONSource)._data as AllGeoJSON; |
| 25 | + } else if (layerSource) { |
| 26 | + const features = mapHook.map?.querySourceFeatures(layerSource); |
| 27 | + if (features && features.length > 0) { |
| 28 | + geojson = { |
| 29 | + type: 'FeatureCollection', |
| 30 | + features, |
| 31 | + } as AllGeoJSON; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + if (geojson) { |
| 36 | + mapHook.map?.fitBounds( |
| 37 | + bbox(geojson) as LngLatBoundsLike, |
| 38 | + props.fitBoundsOptions |
29 | 39 | ); |
| 40 | + } |
30 | 41 | } |
31 | 42 |
|
32 | 43 | export default useFitLayerBounds; |
0 commit comments