OpenLayers6(8):引入Turf.js做缓冲区分析

1 版本

  • OpenLayers:6.14.1


2 相关配置

//前端的地理空间分析库,处理各种地图算法

npm i @turf/turf

3 Openlayers图形与图形Turf之间的互相转换

使用策略模式进行实现:

/**
 * 策略模式,不同类型返回不同的Turf几何图形
 */
export const mCoords2TurfGeom = {
    Point: function (coords) {
        return turf.point(coords);
    },
    MultiPoint: function (coords) {
        return turf.multiPoint(coords);
    },
    LineString: function (coords) {
        return turf.lineString(coords);
    },
    MultiLineString: function (coords) {
        return turf.multiLineString(coords);
    },
    Polygon: function (coords) {
        return turf.polygon(coords);
    },
    MultiPolygon: function (coords) {
        return turf.multiPolygon(coords);
    },
}

4 openlayers的要素点击事件

基于地图的"singleclick"点击事件拾取要素:

/**
 * 选择要素
 * @param {*} map 地图对象
 * @param {*} type 事件类型
 * @param {*} layerFilter 图层山筛选函数
 * @param {*} cb1 选中要素回调
 * @param {*} cb2 未选中要素回调
 * @returns 事件Key
 */
export function mapOnFeature(map, type, layerFilter, cb1, cb2) {
    const key = map.on(type, function (e) {
        map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
            if (feature && layer) {
                cb1 && cb1(feature);
            } else {
                cb2 && cb2();
            }
        }, {
            layerFilter: layerFilter,
            hitTolerance: 5
        });
    });
    return key;
}

5 进行缓冲区分析

import * as turf from "@turf/turf";

// 图层筛选
lFilter(layer) {
      // return layer;
      return layer.get("title") === "草图图层";
},

// 进行缓冲区分析
bufferF(feature) {
      const geometry = feature.getGeometry();
      const type = geometry.getType();
      geometry.transform("EPSG:3857", "EPSG:4326");
      const coords = geometry.getCoordinates();

      const tf = mCoords2TurfGeom[type](coords);
      // 缓冲区分析,turf必须使用wgs84经纬度坐标
      const tbf = turf.buffer(tf, this.mBuffer.distance, {
        units: this.mBuffer.unit,
      });
      const obf = new GeoJSON().readFeature(tbf);

      obf.getGeometry().transform("EPSG:4326", "EPSG:3857");
      geometry.transform("EPSG:4326", "EPSG:3857");
      this.pDrawLayer.getSource().addFeature(obf);
},

mBufferKey = mapOnFeature(this.pMap,"singleclick",this.lFilter,this.bufferF);

6 实现界面及效果图

猜你喜欢

转载自blog.csdn.net/qq_34520411/article/details/124734296