openlayers 鼠标浮动要素上弹窗显示要素信息

本文介绍如何在OpenLayers地图应用中实现在鼠标悬停或单击时,于要素位置弹出信息窗口展示要素详细信息。通过监听`pointermove`和`singleclick`事件,结合`forEachFeatureAtPixel`方法获取当前坐标点上的要素,并根据要素类型及属性进行处理。对于点要素,将相关信息填充到弹窗内容中,确保信息准确无误地显示。同时,代码还处理了高亮显示的要素切换,确保交互体验流畅。
项目中要求鼠标hover到要素时候,在要素位置弹窗,并在框内显示要素的信息。怎么才能具体弹窗到那个位置呢,原来ol官方有个弹窗实例,跟着new就完事了。
上效果图

在这里插入图片描述

map 构造完之后popup添加到map中。
// 这段代码是mounted中执行的,只要是在初始化map 之后执行就行。两个事件二选一使用。
map.on('pointermove', this.feature_Info);	// 悬浮显示
map.on('singleclick', evt => this.feature_Info(evt.pixel));	// 单击显示
要素有多种,为了避免和其他的引起冲突,做了很多判断。这里只对点要素进行数据处理。
// An highlighted block
/**
*	getCoordinateFromPixel => 经纬度转换px值
*	getPixelFromCoordinate => px值转换经纬度
*	
*	@param {Array} pixel => 经纬度转换得到的px值
*	@param {Array} properties => 由于地图同一个经纬度信息出现两个feature 使用像素定位会定位最后渲染的的要素,导致两个信息可能会显示不一样,便把属性传递来此
*/
    feature_Info(pixel, properties) {
      var feature = map.forEachFeatureAtPixel(pixel, feature => feature);
      if (feature) {
        if (!properties) {  // 如果没传值,则表示为点击事件
          if (feature.getGeometry().getType() !== 'Point') return this.popup.setPosition(undefined);
          if(feature.id_ == undefined) return this.popup.setPosition(undefined);
          this.featureInfo = {};
          if (feature.getProperties()['装备编号']) properties = feature.getProperties();
          if (feature.getProperties().features) properties = feature.getProperties().features[0].getProperties();
        }	// 此处是判断要素聚合的取值 没做聚合这个步骤可以忽略掉
        let obj = {};
        for(var v in properties) {
          if (v === '装备编号') obj[v] = properties[v];
          if (v === '装备名称') obj[v] = properties[v];
          if (v === '型号') obj[v] = properties[v];
          if (v === '规格') obj[v] = properties[v];
          if (v === '装备负责人') obj[v] = properties[v];
          if (v === '分类标签') obj[v] = properties[v];
          if (v === '所属单位') obj[v] = properties[v];
        };

        this.featureInfo = obj;
        this.popup.setPosition(map.getCoordinateFromPixel(pixel));

      } else {
        // this.popup.setPosition(undefined);
        // this.featureInfo = {};
      }

      if (feature !== highlight) {
        if (highlight) this.highlightOverlay.getSource().removeFeature(highlight);
        if (feature) this.highlightOverlay.getSource().addFeature(feature);
        highlight = feature;
      }
    }

创作不易,转载注明。

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值