openlayers 实现空间查询和测量的提取的的代码块

测量类型

// An highlighted block
// 测量相关
export const Measures = {
  draw: null,
  helpMsg: '',
  sketch: null,             // 当前绘制的要素
  helpTooltipElement: null, // 帮助工具提示元素。
  helpTooltip: null,          // 覆盖以显示帮助消息.
  measureTooltipElement: null,// 度量工具提示元素
  measureTooltip: '',       // 覆盖以显示测量值。
  continuePolygonMsg: '继续点击绘制多边形',     // 用户绘制多边形时显示的消息
  continueLineMsg: '继续点击绘制线',            // 用户绘制线条时显示的消息
  measures(map, measureType, VectorSource) {   // 传入3个参数,map 绘制类型 矢量图层
    let _this = this;
    map.on('pointermove', pointerMoveHandler);

    map.getViewport().addEventListener('mouseout', function () {
      _this.helpTooltipElement.classList.add('hidden');
    });

    // 绘制前
    function addInteraction() {
      map.removeInteraction(_this.draw);
      measureType = measureType == 'area' ? 'Polygon' : 'LineString';
      _this.draw = new ol.interaction.Draw({
        source: VectorSource,
        type: measureType,
        style: style()
      });
      map.addInteraction(_this.draw);
      createMeasureTooltip();
      createHelpTooltip();
      var listener;

      _this.draw.on('drawstart', function (evt) {
        // 设置草图
        _this.sketch = evt.feature;

        var tooltipCoord = evt.coordinate;

        listener = _this.sketch.getGeometry().on('change', function (evt) {
          var geom = evt.target;
          var output;
          if (geom instanceof ol.geom.Polygon) {
            output = formatArea(geom);
            tooltipCoord = geom.getInteriorPoint().getCoordinates();
          }
          else if (geom instanceof ol.geom.LineString) {
            output = formatLength(geom);
            tooltipCoord = geom.getLastCoordinate();
          }
          _this.measureTooltipElement.innerHTML = output;
          _this.measureTooltip.setPosition(tooltipCoord);
        });
      });
      _this.draw.on('drawend', function (e) {
        _this.measureTooltipElement.className = 'ol-tooltip ol-tooltip-static';
        _this.measureTooltip.setOffset([0, -7]);
        _this.sketch = null;  // unset sketch
        _this.measureTooltipElement = null;  // 取消设置工具提示以便可以创建新的工具提示
        createMeasureTooltip();
        ol.Observable.unByKey(listener);
        map.removeInteraction(_this.draw);
        map.removeOverlay(_this.helpTooltip);
      });
    };
    function style() {
      return new ol.style.Style({
        fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' }),
        stroke: new ol.style.Stroke({ color: '#0099FF', solid: [10, 10], width: 2 }),
        image: new ol.style.Circle({ radius: 5, stroke: new ol.style.Stroke({ color: 'rgba(0, 0, 0, 0.7)' }),
        fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' })
        })
      })
    };
    // 创建新的帮助工具提示
    function createHelpTooltip() {
      if (_this.helpTooltipElement) {
        _this.helpTooltipElement.parentNode.removeChild(_this.helpTooltipElement);
      }
      _this.helpTooltipElement = document.createElement('div');
      _this.helpTooltipElement.className = 'ol-tooltip hidden';
      _this.helpTooltip = new ol.Overlay({
        element: _this.helpTooltipElement,
        offset: [15, 0],
        positioning: 'center-left',
      });
      map.addOverlay(_this.helpTooltip);
    };
    // 创建新的度量工具提示
    function createMeasureTooltip() {
      if (_this.measureTooltipElement) {
        _this.measureTooltipElement.parentNode.removeChild(_this.measureTooltipElement);
      }
      _this.measureTooltipElement = document.createElement('div');
      _this.measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
      _this.measureTooltip = new ol.Overlay({
        element: _this.measureTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center',
      });
      map.addOverlay(_this.measureTooltip);
    };
    // 长度测量
    function formatLength(line) {
      var length = ol.sphere.getLength(line);
      var output;
      if (length > 100) {
        output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
      } else {
        output = Math.round(length * 100) / 100 + ' ' + 'm';
      }
      return output;
    };
    // 区域测量
    function formatArea(polygon) {
      var area = ol.sphere.getArea(polygon);
      var output;
      if (area > 10000) {
        output = Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>';
      } else {
        output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>';
      }
      return output;
    };
    // 移动提示节点
    function pointerMoveHandler(evt) {
      if (evt.dragging) return
      _this.helpMsg = '单击开始绘制';
      if (_this.sketch) {
        let geom = _this.sketch.getGeometry();
        if (geom instanceof ol.geom.Polygon) { _this.helpMsg = _this.continuePolygonMsg; }
        else if (geom instanceof ol.geom.LineString) { _this.helpMsg = _this.continueLineMsg; }
      }
      _this.helpTooltipElement.innerHTML = _this.helpMsg;
      _this.helpTooltip.setPosition(evt.coordinate);
      _this.helpTooltipElement.classList.remove('hidden');
    }
    addInteraction()
  },
  // 移除测量动作
  removeInteraction(map) {
    map.removeInteraction(this.draw);
    map.removeOverlay(this.helpTooltip);
  },
};
// A code block
Measures.measures(this.map, measureType, this.MeasureVector); // 传递map, 测量类型, 矢量图层

空间查询代码块

// An highlighted block
// 空间查询
import { EPSG3857, EPSG4326, EPSG900913 } from './index';
import store from '@/store'
export const QuerySpace = {
  // 获取所有列表
  getAll(params = {
    装备编号: '',
    装备名称: '',
    使用状态: '',
    所属单位: '',
  }, source) {
    let featureRequest = null;
    const geometry = source?.getFeatures()[source?.getFeatures().length-1]?.getGeometry();
    return new Promise(resolve => {
      const result = new Promise(resolve => {
        if (!geometry) {
          featureRequest = new ol.format.WFS().writeGetFeature({
            srsName: EPSG900913,   //坐标系统
            featureNS: window.base_url.spatial_query_url,//命名空间 URI
            featurePrefix: 'hbsdzy',  //工作区名称
            featureTypes: ['hbsdzy:zb'],//查询图层,可以是同一个工作区下多个图层,逗号隔开
            outputFormat: 'application/json',
            filter: ol.format.filter.and(
              ol.format.filter.like('装备编号', '*' + params['装备编号']),
              ol.format.filter.like('装备名称', '*' + params['装备名称']),
              ol.format.filter.like('使用状态', '*' + params['使用状态'] + '*'),
              ol.format.filter.like('所属单位', '*' + params['所属单位'] + '*'),
            )
          });
          resolve(featureRequest)
        }
        else {
          featureRequest = new ol.format.WFS().writeGetFeature({
            srsName: EPSG900913,//坐标系统
            featureNS: window.base_url.spatial_query_url,//命名空间 URI
            featurePrefix: 'hbsdzy',//工作区名称
            featureTypes: ['hbsdzy:zb'],//查询图层,可以是同一个工作区下多个图层,逗号隔开
            outputFormat: 'application/json',
            filter: ol.format.filter.and(
              ol.format.filter.within("geom", geometry),  //前者是属性名,后者是对应值
              // ol.format.filter.or(
                ol.format.filter.like('装备编号', '*' + params['装备编号']),
                ol.format.filter.like('装备名称', '*' + params['装备名称']),
                ol.format.filter.like('使用状态', '*' + params['使用状态'] + '*'),
                ol.format.filter.like('所属单位', '*' + params['所属单位'] + '*'),
              // )
            )
          });
          resolve(featureRequest)
        }
      })
      result.then(data => {
        fetch(window.base_url.spatial_request_url, { method: 'POST', body: new XMLSerializer().serializeToString(data)})
        .then(response => response.json()).then(json => resolve({json}))
      })
    });
    
  },
  // 框选获取列表
  getSelection(params, draw, source) {
    /*
    1:  输入搜索 回车事件 调用all
    2: 拉框绘制  调用sele
    3: 有文字时 拉框绘制 调用sele
    4: 存在框选 输入文字 回车事件 调用sele
    */
    return new Promise(resolve => {
      const result = new Promise(res => {
        let featureRequest = null;
        const geometry = source?.getFeatures()[0]?.getGeometry();
        if (!geometry) { // 表示没有绘制
        draw.on('drawend', evt => {
          featureRequest = new ol.format.WFS().writeGetFeature({
            srsName: EPSG900913,//坐标系统
            featureNS: window.base_url.spatial_query_url,//命名空间 URI
            featurePrefix: 'hbsdzy',//工作区名称
            featureTypes: ['hbsdzy:zb'],//查询图层,可以是同一个工作区下多个图层,逗号隔开
            outputFormat: 'application/json',
            filter: ol.format.filter.and(
              ol.format.filter.intersects("geom", evt.feature.getGeometry()),  //前者是属性名,后者是对应值
              // ol.format.filter.or(
                ol.format.filter.like('装备编号', '*' + params['装备编号']),
                ol.format.filter.like('装备名称', '*' + params['装备名称']),
                ol.format.filter.like('使用状态', '*' + params['使用状态'] + '*'),
                ol.format.filter.like('所属单位', '*' + params['所属单位'] + '*'),
              // )
            )
          });
          res(featureRequest)
        });
        }
        else {  // 存在绘制图形
          featureRequest = new ol.format.WFS().writeGetFeature({
            srsName: EPSG900913,//坐标系统
            featureNS: window.base_url.spatial_query_url,//命名空间 URI
            featurePrefix: 'hbsdzy',//工作区名称
            featureTypes: ['hbsdzy:zb'],//查询图层,可以是同一个工作区下多个图层,逗号隔开
            outputFormat: 'application/json',
            filter: ol.format.filter.and(
              ol.format.filter.within("geom", geometry),  //前者是属性名,后者是对应值
              // ol.format.filter.or(
                ol.format.filter.like('装备编号', '*' + params['装备编号']),
                ol.format.filter.like('装备名称', '*' + params['装备名称']),
                ol.format.filter.like('使用状态', '*' + params['使用状态'] + '*'),
                ol.format.filter.like('所属单位', '*' + params['所属单位'] + '*'),
              // )
            )
          });
          res(featureRequest)
        }
      });
      result.then(data => {
        fetch(window.base_url.spatial_request_url, { method: 'POST', body: new XMLSerializer().serializeToString(data) })
        .then(response => response.json()).then(json => resolve({json}))
      });
      // end
    })
  },
  // 缓冲区
  buffered: null,                               // 生成缓冲区的数据值
  corrdinates: null,                            // 绘制后的要素
  getBuffered(params, draw, source) {
    let featureRequest;                         // 缓冲数据值
    let format = new ol.format.GeoJSON();       // 格式化类
    const distance = store.state.Map.distance;  // 取缓冲距离值
    const geometry = source?.getFeatures()[0]?.getGeometry();
    return new Promise(resolve => {
      const result = new Promise(resolve => {
        if (!geometry) {
          draw.on('drawend', evt => {
            this.corrdinates = evt.feature.getGeometry().getCoordinates();
            const center = ol.proj.transform(this.corrdinates, EPSG3857, EPSG4326);
            const point = turf.point(center);
            let buffered = turf.buffer(point, distance, { units: 'kilometers' });
            buffered = format.readFeature(buffered);
            buffered.getGeometry().transform(EPSG4326, EPSG3857);
            this.buffered = buffered;
            featureRequest = new ol.format.WFS().writeGetFeature({
              srsName: EPSG900913,//坐标系统
              featureNS: window.base_url.spatial_query_url,//命名空间 URI
              featurePrefix: 'hbsdzy',//工作区名称
              featureTypes: ['hbsdzy:zb'],//查询图层,可以是同一个工作区下多个图层,逗号隔开
              outputFormat: 'application/json',
              filter: ol.format.filter.and(
                ol.format.filter.intersects("geom", buffered.getGeometry()),  //前者是属性名,后者是对应值
                // ol.format.filter.or(
                  ol.format.filter.like('装备编号', '*' + params['装备编号']),
                  ol.format.filter.like('装备名称', '*' + params['装备名称']),
                  ol.format.filter.like('使用状态', '*' + params['使用状态'] + '*'),
                  ol.format.filter.like('所属单位', '*' + params['所属单位'] + '*'),
                // )
              )
            });
            resolve(featureRequest);
          });
        }
        else {
          const center = ol.proj.transform(this.corrdinates, EPSG3857, EPSG4326);
          const point = turf.point(center);
          this.buffered = turf.buffer(point, distance, { units: 'kilometers' });
          this.buffered = format.readFeature(this.buffered);
          this.buffered.getGeometry().transform(EPSG4326, EPSG3857);

          featureRequest = new ol.format.WFS().writeGetFeature({
            srsName: EPSG900913,//坐标系统
            featureNS: window.base_url.spatial_query_url,//命名空间 URI
            featurePrefix: 'hbsdzy',//工作区名称
            featureTypes: ['hbsdzy:zb'],//查询图层,可以是同一个工作区下多个图层,逗号隔开
            outputFormat: 'application/json',
            filter: ol.format.filter.and(
              ol.format.filter.within("geom", this.buffered.getGeometry()),
              // ol.format.filter.or(
                ol.format.filter.like('装备编号', '*' + params['装备编号']),
                ol.format.filter.like('装备名称', '*' + params['装备名称']),
                ol.format.filter.like('使用状态', '*' + params['使用状态'] + '*'),
                ol.format.filter.like('所属单位', '*' + params['所属单位'] + '*'),
              // )
            )
          });
          resolve(featureRequest);
        };
      });
      result.then(data => {
        fetch(window.base_url.spatial_request_url, { method: 'POST', body: new XMLSerializer().serializeToString(data) })
        .then(response => response.json()).then(json => resolve({json, shape: this.buffered}))
      });
    })
  }
};
// A code block

map.removeInteraction(Draw); // 执行操作完移除draw;

空间查询和缓冲区查询清除操作

// 清除查询
    this.$bus.$on(CLEARSCOPEFACTOR, () => {
      const layers = this.map.getLayers().getArray();
      layers.forEach(v => {
        if (v.get("name") == "rangeLayerVector") {
          v.getSource().clear();
          map.removeInteraction(this.rangeSelectionDraw);
          map.removeLayer(this.rangeLayerVector)
          this.rangeVectorSource = null;
          this.rangeLayerVector = null;
          this.$bus.$emit('scopeSelectFactor', {flag: 'getAll'});  // 获取all列表
        }
      });
    });
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是使用OpenLayers实现点聚合的完整代码示例。 HTML文件: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>OpenLayers Point Clustering Example</title> <link rel="stylesheet" href="https://openlayers.org/en/v6.5.0/css/ol.css" type="text/css"> <style> .map { height: 500px; width: 100%; } </style> </head> <body> <div id="map" class="map"></div> <script src="https://openlayers.org/en/v6.5.0/build/ol.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.15/proj4.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.15/proj4-src.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/turf.js/5.1.6/turf.min.js"></script> <script src="cluster.js"></script> </body> </html> ``` JavaScript文件(cluster.js): ```javascript // 聚合半径 var radius = 40; // 创建地图 var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({ center: ol.proj.fromLonLat([0, 0]), zoom: 2 }) }); // 创建一个聚合层 var clusterLayer = new ol.layer.Vector({ source: new ol.source.Vector(), style: function(feature) { var size = feature.get('features').length; var style = new ol.style.Style({ image: new ol.style.Circle({ radius: 10, stroke: new ol.style.Stroke({ color: '#fff' }), fill: new ol.style.Fill({ color: '#3399CC' }) }), text: new ol.style.Text({ text: size.toString(), fill: new ol.style.Fill({ color: '#fff' }) }) }); return style; } }); map.addLayer(clusterLayer); // 加载数据并进行聚合 var url = 'data.geojson'; fetch(url).then(function(response) { return response.json(); }).then(function(json) { var features = new ol.format.GeoJSON().readFeatures(json); var clusters = getClusters(features, radius); clusterLayer.getSource().addFeatures(clusters); }); ``` 在上述代码中,我们首先创建了一个地图,并添加了一个OSM图层。然后创建了一个聚合层,并将其添加到地图中。接着,我们从一个GeoJSON文件中加载数据,并调用getClusters()函数对数据进行聚合。最后,我们将聚合后的数据添加到聚合层的源中。 请注意,在这个示例代码中,我们使用了turf.js库来计算两个点之间的距离,以便进行聚合。如果您不想使用turf.js,可以使用OpenLayers的ol.Sphere类来计算距离。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值