套索工具(超叼版)
This commit is contained in:
58
src/utils/setMapCenter.ts
Normal file
58
src/utils/setMapCenter.ts
Normal file
@ -0,0 +1,58 @@
|
||||
// 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);
|
||||
// }
|
||||
|
Reference in New Issue
Block a user