Skip to content

Commit a6ab82d

Browse files
author
jannik brack
committed
useFitLayerBounds.tsx new structure
1 parent 1de7549 commit a6ab82d

File tree

1 file changed

+26
-15
lines changed

1 file changed

+26
-15
lines changed

src/hooks/useFitLayerBounds.tsx

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,43 @@
1-
21
import useMap from "./useMap";
3-
import { bbox } from '@turf/turf';
2+
import { bbox, AllGeoJSON } from '@turf/turf';
43
import { LngLatBoundsLike, FitBoundsOptions, GeoJSONSource } from 'maplibre-gl';
54

6-
75
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;
119
}
12-
function useFitLayerBounds(props: useFitLayerBoundsPros){
1310

11+
function useFitLayerBounds(props: useFitLayerBoundsPros) {
1412
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-
};
2113

14+
const layerSource = props.layerId ? mapHook?.map?.getLayer?.(props.layerId)?.source : undefined;
2215

2316
if (!layerSource) {
2417
return;
2518
}
2619

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
2939
);
40+
}
3041
}
3142

3243
export default useFitLayerBounds;

0 commit comments

Comments
 (0)