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 实现界面及效果图

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

碰碰qaq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值