五、OpenLayer点击查询

这块其实要分多种类型,因为不同图层和服务获取属性信息的方式和地址也不一样。介绍一下常用的几种:

1、矢量图层VectorLayer

这种矢量图层属性信息是直接存储在前端的canvas里面的,我们可以直接获取到它,前提是你在添加要素时已经动态给他赋值上(properties属性,上一节图层介绍有注释)或者添加的geojson格式对象的数据,否则点击获取的也是空对象。

属性动态赋值方法

var feature = new ol.Feature();
feature.setProperties({你的属性对象})
//或者
var feature = new ol.Feature({
  properties:{你的属性对象}
});

这样点击的时候获取方式:

    this.map.on("click", (ev) => {
      const mouse = ev.coordinate; // 鼠标点击的坐标位置
      let feature = this.map.forEachFeatureAtPixel(
        ev.pixel,
        function (feature) {
          return feature;
        }
      );
      //获取属性对象的某个属性值 但是有时候自定义和其他方式加载的根对象不一样,可能获取不到
      const name= feature.get("name")
      //建议直接打印自己去看,一般都是在values_下面
      const properties = feature?.values_?.properties


      //当然也可以获取特定图层的点击要素集合,比如聚合图层
      myVectorLayer.getFeatures(ev.pixel).then((clickedFeatures) => {

      })
    })

2、加载wms服务的TileLayer或者ImageLayer

这种是栅格图层,理解为就是图片,属性信息是没有存储在前端的。需要通过请求地址去获取。openlayer提供了wms服务的请求地址拼接接口:

map.on('singleclick', function (evt) {
  const viewResolution = view.getResolution();
  const url = wmsSource.getFeatureInfoUrl(
    evt.coordinate,
    viewResolution,
    'EPSG:4326',
    {'INFO_FORMAT': 'text/html'}  //返回的是表格hmtl标签,可直接挂接到元素上
    //{'INFO_FORMAT': 'application/json'}  //返回的是geojson格式的数据
  );
  if (url) {
    fetch(url)
      .then((response) => response.text())
      .then((html) => {
        document.getElementById('info').innerHTML = html;
      });
  }
});

3、其他类型的服务

比如arcgis server, 超图的iserver,都提供了空间查询的服务接口,需要自行去拼接参数请求获取对应数据。

自定义查询窗口。openlayer提供了overlay这个类,可以去动态绑定我们自己创建的元素。

//属性窗体
this.overlayForm = new Overlay({
   // 创建一个图层
   element: this.$refs.msgForm.$el, // 图层绑定我们上边的弹窗
   autoPan: true,
   autoPanAnimation: {
      duration: 250,
    },
 });
this.overlayForm.setPosition(undefined); //设置弹窗位置,刚开始我们不让他显示,就是undefined就行
this.map.addOverlay(this.overlayForm); // 然后把弹窗的图层加载到地图上

猜你喜欢

转载自blog.csdn.net/qq_39330397/article/details/132403261