Files
td_official/src/utils/setMapCenter.ts

59 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-06-06 20:03:35 +08:00
// MapViewFitter.ts
import { Map as OlMap } from 'ol';
import GeoJSON from 'ol/format/GeoJSON';
import { FeatureCollection } from 'geojson';
import { bbox as turfBbox, bboxPolygon as turfBboxPolygon } from '@turf/turf';
import type { Geometry } from 'ol/geom';
export class MapViewFitter {
private map: OlMap;
private format: GeoJSON;
constructor(map: OlMap) {
this.map = map;
this.format = new GeoJSON();
}
/**
* 使 GeoJSON FeatureCollection
* @param featureCollection GeoJSON FeatureCollection
* @param padding [10, 10, 10, 10]
* @param duration 1000
*/
fit(featureCollection: FeatureCollection, padding: number[] = [10, 10, 10, 10], duration: number = 1000) {
if (!featureCollection?.features?.length) return;
const bbox = turfBbox(featureCollection); // [minX, minY, maxX, maxY]
const bboxPolygon = turfBboxPolygon(bbox); // Feature<Polygon>
const geometry: Geometry = this.format.readGeometry(bboxPolygon.geometry, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
});
const extent = geometry.getExtent();
this.map.getView().fit(extent, {
padding,
duration
});
}
}
//示例
// import { MapViewFitter } from '@/utils/setMapCenter'; // 确保路径正确
// const fitter = new MapViewFitter(map); // 传入你的 OpenLayers 地图实例
// const features = xxx;//features数组
// if (features?.length) {
// const featureCollection = {
// type: 'FeatureCollection',
// features
// };
// fitter.fit(featureCollection);
// }