openlayers 绘图功能,编辑多边形,select,snap组件的使用(六)

news2024/10/6 10:40:29

本篇介绍一下vue3-openlayers的select,snap的使用

1 需求

  • 点击开始绘制按钮开始绘制多边形,可以连续绘制多个多边形
  • 点击撤销上步按钮,撤销上一步绘制点
  • 绘制多个多边形(或编辑多边形时),鼠标靠近之前的已绘制完的多边形顶点时,自动吸附
  • 点击结束绘制按钮,绘制完成,点击高亮选中多边形,开启编辑模式,显示顶点(调节点)进行编辑

2 分析

主要是vue3-openlayers 中 draw,select,snap,modify 功能的使用

3 实现

3.1 简单实现

<template>
  <ol-map
    :loadTilesWhileAnimating="true"
    :loadTilesWhileInteracting="true"
    style="width: 100%; height: 100%"
    ref="mapRef"
  >
    <ol-view
      ref="view"
      :center="center"
      :rotation="rotation"
      :zoom="zoom"
      :projection="projection"
    />
    <ol-vector-layer>
      <ol-source-vector :projection="projection" :wrapX="false">
        <ol-interaction-draw
          ref="drawRef"
          :type="'Polygon'"
          :source="source"
          @drawend="drawend"
          @drawstart="drawstart"
        >
          <ol-style :overrideStyleFunction="handleStyleFunction"> </ol-style>
        </ol-interaction-draw>
        <ol-interaction-modify
          ref="modifyRef"
					v-if="modifyFlag"
          :features="selectedFeatures"
          :pixelTolerance="10"
          :insertVertexCondition="handleInsertVertexCondition"
          @modifyend="handleModifyEnd"
        >
          <ol-style :overrideStyleFunction="handleModifyStyleFunction"> </ol-style>
        </ol-interaction-modify>
        <ol-interaction-snap :edge="false" />
      </ol-source-vector>
      <ol-style :overrideStyleFunction="styleFunction"> </ol-style>
    </ol-vector-layer>
    <ol-interaction-select ref="selectRef"  :features="selectedFeatures" @select="handleSelect" :condition="selectCondition">
      <ol-style :overrideStyleFunction="selectStyleFunc"> </ol-style>
    </ol-interaction-select>
  </ol-map>
  <div class="toolbar">
    <el-button type="primary" @click="handleClick">{{ drawFlag ? '结束' : '开始' }}绘制</el-button>
    <el-button type="warning" :disabled="!drawFlag" @click="handleCancelClick">撤销上步</el-button>
  </div>
</template>

<script setup lang="ts">
import { Collection } from 'ol';
import { FeatureLike } from 'ol/Feature';
import { LineString, Point } from 'ol/geom';
import { DrawEvent } from 'ol/interaction/Draw';
import { Circle, Fill, Stroke, Style } from 'ol/style';
const center = ref([121, 31]);
const projection = ref('EPSG:4326');
const zoom = ref(5);
const rotation = ref(0);
const features = ref(new Collection()); //保存绘制的features
const selectedFeatures = ref(new Collection()); //保存绘制的features
const source = ref([]);
const mapRef = ref();
const drawRef = ref();
const selectRef = ref();
const modifyRef = ref();
const drawFlag = ref(false);
const modifyFlag = ref(true);
const selectConditions = inject('ol-selectconditions');

const selectCondition = selectConditions.click;

onMounted(() => {
  drawRef.value.draw.setActive(false);
  modifyRef.value.modify.setActive(false);
});

const drawstart = (event: Event) => {
  console.log(event);
};

const drawend = (event: DrawEvent) => {
  console.log(event.feature.getGeometry());
};

const handleClick = () => {
  drawFlag.value = !drawFlag.value;
  drawRef.value.draw.setActive(drawFlag.value);
	// modifyFlag.value=!drawFlag.value;
  modifyRef.value.modify.setActive(!drawFlag.value);
  selectRef.value.select.setActive(!drawFlag.value);
  selectRef.value.select.getFeatures().clear();
};
const handleCancelClick = () => {
  drawRef.value.draw.removeLastPoint();
};

const handleSelect = e => {
	modifyRef.value.modify.setActive(false);
	// modifyFlag.value=false;
  if (!e.selected.length) {
    selectedFeatures.value.clear();
    selectRef.value.select.getFeatures().clear();
  } else {
		nextTick(()=>{
			// modifyFlag.value=true;
			modifyRef.value?.modify.setActive(true);
			selectedFeatures.value=e.target.getFeatures();
		})
  }
};


const handleStyleFunction = (feature: FeatureLike, currentStyle: Style) => {
  const geometry = feature.getGeometry();
  const coord = geometry.getCoordinates();
  const type = geometry.getType();
  const styles: Array<Style> = [];
  if (type === 'LineString') {
    for (let i = 0; i < coord.length - 1; i++) {
      styles.push(
        new Style({
          geometry: new LineString([coord[i], coord[i + 1]]),
          stroke: new Stroke({
            color: 'orange',
            lineDash: coord.length > 2 && i < coord.length - 2 ? [] : [10],
            width: 2
          })
        })
      );
    }
  }
  return styles;
};

const handleInsertVertexCondition = e => {
  return false;
};

const handleModifyStyleFunction = (feature: FeatureLike, currentStyle: Style) => {
  const coord = feature.getGeometry().getCoordinates();
  const layer = mapRef.value.map.getLayers().item(0);
  const features = layer.getSource().getFeatures();
  const coords = features.map(feature => feature.getGeometry().getCoordinates()).flat(2);
  let style = undefined;
  // 只有鼠标在顶点时才能触发编辑功能
  if (coords.find(c => c.toString() === coord.toString())) {
    style = new Style({
      geometry: new Point(coord),
      image: new Circle({
        radius: 6,
        fill: new Fill({
          color: '#ffff'
        }),
        stroke: new Stroke({
          color: 'red',
          width: 2
        })
      })
    });
  }

  return style;
};

const handleModifyEnd = e => {
  features.value.push(e.feature); //这里可以把编辑后的feature添加到layer绑定的features中
  console.log('modifyend', e.features);
};

const styleFunction = (feature: FeatureLike, currentStyle: Style) => {
  const styles = [];
  styles.push(
    new Style({
      fill: new Fill({
        color: [128, 128, 255, 0.5]
      }),
      stroke: new Stroke({
        color: 'blue',
        width: 2
      })
    })
  );
  return styles;
};

const selectStyleFunc = feature => {
  const styles = [];
  const coord = feature.getGeometry().getCoordinates().flat(1);
  for (let i = 0; i < coord.length - 1; i++) {
    styles.push(
      new Style({
        geometry: new Point(coord[i]),
        image: new Circle({
          radius: 4,
          fill: new Fill({
            color: '#ffff'
          }),
          stroke: new Stroke({
            color: 'orange',
            width: 2
          })
        })
      })
    );
  }
  styles.push(
    new Style({
      stroke: new Stroke({
        color: 'orange',
        width: 2
      }),
      fill: new Fill({
        color: '#ffff'
      })
    })
  );
  return styles;
};
</script>
<style scoped lang="scss">
.toolbar {
  position: absolute;
  top: 20px;
  left: 100px;
}
</style>


存在问题(vue3-openlayers官网modify示例也存在这两个个问题)

  • 当绘制多个多边形时,只要一个多边形被编辑过,当编辑其他多边形时,尽管高亮选中的是当前多边形,但是之前编辑过的多边形也可以被编辑
  • 当两个多边形顶点重叠时,无法再分开,会导致同时编辑两个多边形

分析
modify组件没有仅仅使用当前选中的多边形,而是把select过的都进入编辑状态(其实原生写法也有这个问题,试着把modify传入的features参数绑定值从select.value.getFeatures()改为一个ref(new Collection()),在select组件的select事件中把选中的feature压入这个ref,既可以复现上面两个问题)

解决
modify添加v-if,强制重新渲染(会导致snap不会吸附,个人觉得可以接受)

3.2 重新实现

<template>
  <ol-map
    :loadTilesWhileAnimating="true"
    :loadTilesWhileInteracting="true"
    style="width: 100%; height: 100%"
    ref="mapRef"
  >
    <ol-view
      ref="view"
      :center="center"
      :rotation="rotation"
      :zoom="zoom"
      :projection="projection"
    />
    <ol-vector-layer>
      <ol-source-vector :projection="projection" :wrapX="false">
        <ol-interaction-draw
          ref="drawRef"
          :type="'Polygon'"
          :source="source"
          @drawend="drawend"
          @drawstart="drawstart"
        >
          <ol-style :overrideStyleFunction="handleStyleFunction"> </ol-style>
        </ol-interaction-draw>
        <ol-interaction-modify
          ref="modifyRef"
					v-if="modifyFlag"
          :features="selectedFeatures"
          :pixelTolerance="10"
          :insertVertexCondition="handleInsertVertexCondition"
          @modifyend="handleModifyEnd"
        >
          <ol-style :overrideStyleFunction="handleModifyStyleFunction"> </ol-style>
        </ol-interaction-modify>
        <ol-interaction-snap :edge="false" />
      </ol-source-vector>
      <ol-style :overrideStyleFunction="styleFunction"> </ol-style>
    </ol-vector-layer>
    <ol-interaction-select ref="selectRef"  :features="selectedFeatures" @select="handleSelect" :condition="selectCondition">
      <ol-style :overrideStyleFunction="selectStyleFunc"> </ol-style>
    </ol-interaction-select>
  </ol-map>
  <div class="toolbar">
    <el-button type="primary" @click="handleClick">{{ drawFlag ? '结束' : '开始' }}绘制</el-button>
    <el-button type="warning" :disabled="!drawFlag" @click="handleCancelClick">撤销上步</el-button>
  </div>
</template>

<script setup lang="ts">
import { Collection } from 'ol';
import { FeatureLike } from 'ol/Feature';
import { LineString, Point } from 'ol/geom';
import { DrawEvent } from 'ol/interaction/Draw';
import { Circle, Fill, Stroke, Style } from 'ol/style';
const center = ref([121, 31]);
const projection = ref('EPSG:4326');
const zoom = ref(5);
const rotation = ref(0);
const features = ref(new Collection()); //保存绘制的features
const selectedFeatures = ref(new Collection()); //保存绘制的features
const source = ref([]);
const mapRef = ref();
const drawRef = ref();
const selectRef = ref();
const modifyRef = ref();
const drawFlag = ref(false);
const modifyFlag = ref(false);
const selectConditions = inject('ol-selectconditions');

const selectCondition = selectConditions.click;

onMounted(() => {
  drawRef.value.draw.setActive(false);
  // modifyRef.value.modify.setActive(false);
});

const drawstart = (event: Event) => {
  console.log(event);
};

const drawend = (event: DrawEvent) => {
  console.log(event.feature.getGeometry());
};

const handleClick = () => {
  drawFlag.value = !drawFlag.value;
  drawRef.value.draw.setActive(drawFlag.value);
	modifyFlag.value=!drawFlag.value;
  // modifyRef.value.modify.setActive(!drawFlag.value);
  selectRef.value.select.setActive(!drawFlag.value);
  selectRef.value.select.getFeatures().clear();
};
const handleCancelClick = () => {
  drawRef.value.draw.removeLastPoint();
};

const handleSelect = e => {
	// modifyRef.value.modify.setActive(false);
	modifyFlag.value=false;
  if (!e.selected.length) {
    selectedFeatures.value.clear();
    selectRef.value.select.getFeatures().clear();
  } else {
		nextTick(()=>{
			modifyFlag.value=true;
			// modifyRef.value?.modify.setActive(true);
			selectedFeatures.value=e.target.getFeatures();
		})
  }
};


const handleStyleFunction = (feature: FeatureLike, currentStyle: Style) => {
  const geometry = feature.getGeometry();
  const coord = geometry.getCoordinates();
  const type = geometry.getType();
  const styles: Array<Style> = [];
  if (type === 'LineString') {
    for (let i = 0; i < coord.length - 1; i++) {
      styles.push(
        new Style({
          geometry: new LineString([coord[i], coord[i + 1]]),
          stroke: new Stroke({
            color: 'orange',
            lineDash: coord.length > 2 && i < coord.length - 2 ? [] : [10],
            width: 2
          })
        })
      );
    }
  }
  return styles;
};

const handleInsertVertexCondition = e => {
  return false;
};

const handleModifyStyleFunction = (feature: FeatureLike, currentStyle: Style) => {
  const coord = feature.getGeometry().getCoordinates();
  const layer = mapRef.value.map.getLayers().item(0);
  const features = layer.getSource().getFeatures();
  const coords = features.map(feature => feature.getGeometry().getCoordinates()).flat(2);
  let style = undefined;
  // 只有鼠标在顶点时才能触发编辑功能
  if (coords.find(c => c.toString() === coord.toString())) {
    style = new Style({
      geometry: new Point(coord),
      image: new Circle({
        radius: 6,
        fill: new Fill({
          color: '#ffff'
        }),
        stroke: new Stroke({
          color: 'red',
          width: 2
        })
      })
    });
  }

  return style;
};

const handleModifyEnd = e => {
  features.value.push(e.feature); //这里可以把编辑后的feature添加到layer绑定的features中
  console.log('modifyend', e.features);
};

const styleFunction = (feature: FeatureLike, currentStyle: Style) => {
  const styles = [];
  styles.push(
    new Style({
      fill: new Fill({
        color: [128, 128, 255, 0.5]
      }),
      stroke: new Stroke({
        color: 'blue',
        width: 2
      })
    })
  );
  return styles;
};

const selectStyleFunc = feature => {
  const styles = [];
  const coord = feature.getGeometry().getCoordinates().flat(1);
  for (let i = 0; i < coord.length - 1; i++) {
    styles.push(
      new Style({
        geometry: new Point(coord[i]),
        image: new Circle({
          radius: 4,
          fill: new Fill({
            color: '#ffff'
          }),
          stroke: new Stroke({
            color: 'orange',
            width: 2
          })
        })
      })
    );
  }
  styles.push(
    new Style({
      stroke: new Stroke({
        color: 'orange',
        width: 2
      }),
      fill: new Fill({
        color: '#ffff'
      })
    })
  );
  return styles;
};
</script>
<style scoped lang="scss">
.toolbar {
  position: absolute;
  top: 20px;
  left: 100px;
}
</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1819312.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Vue3【二十二】Vue 路由模式的嵌套路由和用query给组件的RouterLink传参

Vue3【二十二】Vue 路由模式的嵌套路由和用query给组件传参 Vue3【二十二】Vue 路由模式的嵌套路由和用query给组件传参 RouterLink 的两种传参方法 RouterView 案例截图 目录结构 代码 index.ts // 创建一个路由器&#xff0c;并暴漏出去// 第一步&#xff1a;引入createRou…

0613#111. 构造二阶行列式

时间限制&#xff1a;1.000S 空间限制&#xff1a;256MB 题目描述 小欧希望你构造一个二阶行列式&#xff0c;满足行列式中每个数均为不超过 20 的正整数&#xff0c;且行列式的值恰好等于x。你能帮帮她吗? 输入描述 一个正整数x。-1000 < x < 1000 输出描述 如果…

商家转账到零钱最全面攻略:申请、使用、注意事项等详解

一、微信商家转账到零钱功能概述 微信支付作为国内最大社交软件的增值服务&#xff0c;在商业活动中广泛使用。其开发的营销功能“商家转账到零钱”则允许商家直接将资金转入用户的微信钱包&#xff0c;操作简便快捷。本文将详细探讨此功能的使用条件、操作步骤以及解答一些常…

如何通过 6 种方法从 iPhone 恢复已删除的文件

想知道如何从 iPhone 恢复已删除的文件吗&#xff1f;本文将指导您如何从 iPhone 恢复数据&#xff0c;无论您是否有 iTunes/iCloud 备份。 iPhone 上已删除的文件去哪儿了&#xff1f; 许多 iPhone 用户抱怨他们经常丢失 iPhone 上的一些重要文件。由于意外删除、iOS 更新失败…

遇到JSON文件就头大?掌握Python这几种方法,让你轻松应对

目录 1、标准库json模块 📄 1.1 json.load()函数介绍 1.2 json.loads()处理字符串 1.3 使用json.dump()写入JSON 1.4 json.dumps()美化输出 1.4 错误处理与编码问题 1.5 高效读取大文件技巧 2、第三方库simplejson加持 🔧 2.1 安装与导入simplejson 2.2 性能优势与…

韩国版AlphaFold?深度学习模型AlphaPPIMd:用于蛋白质-蛋白质复合物构象集合探索

在生命的舞台上&#xff0c;蛋白质扮演着不可或缺的角色。它们是生物体中最为活跃的分子&#xff0c;参与细胞的构建、修复、能量转换、信号传递以及无数关键的生物学功能。同时&#xff0c;蛋白质的结构与其功能密切相关&#xff0c;而它们的功能又通过与蛋白质、多肽、核苷酸…

node调试

vscode安装插件&#xff1a;JavaScript Debugger (Nightly) 点击后生成一个launch.json文件 打断点&#xff0c;并发送一个请求来执行代码到断点处 按右上的向下箭头&#xff0c;进入源码&#xff0c;进行查看&#xff0c;左边查看变量等值

护眼台灯攻略:护眼台灯真的有用吗?

当前&#xff0c;近视问题在人群中愈发普遍&#xff0c;据2024年的统计数据显示&#xff0c;我国儿童青少年的总体近视率已高达52.7%。近视的人越来越多&#xff0c;近视背后还潜藏着视网膜脱离、白内障、开角型青光眼等眼部疾病&#xff0c;严重的情况甚至可能引发失明。长时间…

windows 环境下使用git命令导出差异化文件及目录

一、找出差异化的版本&#xff08;再此使用idea的show history&#xff09; 找到两个提交记录的id 分别为&#xff1a; 二、使用git bash执行命令&#xff08;主要使用 tar命令压缩文件&#xff09; 输出结果&#xff1a;

Linux系统管理:虚拟机Almalinux 9.4 安装

目录 一、理论 1.Almalinux 二、实验 1.虚拟机Almalinux 9.4 安装准备阶段 2.安装Almalinux 9.4 3.Termius远程连接 一、理论 1.Almalinux (1) 简介 Almalinux是一个开源、社区拥有和管理、免费的企业Linux发行版。专注于长期稳定性&#xff0c;并提供强大的生产级…

【linux-imx6ull-定时器与中断】

目录 1. 前言2. Linux软件定时器2.1 内核频率选择2.2 重要的API函数2.3 Linux软件定时器的使用配置流程 4. Linux中断4.1 简单中断使用4.1.1 简要说明4.1.2 重要的API函数4.1.3 中断的简要配置流程 4.2. 中断的上半部和下半部4.2.1 tasklet实现下半部4.2.2 work实现下半部 1. 前…

终结国企虚假贸易:监管闭环下的关系排查与风控增强

2024年5月28日&#xff0c;国务院正式公布《国有企业管理人员处分条例》&#xff08;以下简称《条例》&#xff09;&#xff0c;将于2024年9月1日起施行。作为国家经济的重要支柱&#xff0c;国有企业的管理人员在企业运营中扮演着至关重要的角色&#xff0c;《条例》的颁布&am…

调用腾讯智能云实现车辆信息识别

目录 1. 作者介绍2. 算法介绍2.1 腾讯云介绍2.2 API介绍 3. 调用腾讯智能云实现车辆信息识别3.1 准备工作3.2 完整代码3.3 结果分析 1. 作者介绍 汤明乐&#xff0c;男&#xff0c;西安工程大学电子信息学院&#xff0c;2023级研究生 研究方向&#xff1a;机器视觉与人工智能 …

蓝牙BLE上位机工具开发理论线索梳理_3.WINRT Devices设备相关

1.WINRT关于Devices设备相关的命名空间 关于WINRT科以参考下面这篇博文学习理解。以下列出Devices设备相关的API命名空间。 理解WinRT - 厚积薄发 - C博客 Windows.Devices此命名空间提供对低级别设备提供程序的访问&#xff0c;包括 ADC、GPIO、I2 C、PWM 和 SPI。Windows.D…

提醒:网站使用微软雅黑字体的三种方式,两种侵权,一种不侵权。

大家都知道微软雅黑是windows系统的默认字体&#xff0c;但是不知道微软雅黑的版权归属方正字体&#xff0c;而且方正字体仅仅授权了微软在windows系统中使用该字体&#xff0c;脱离了windows使用&#xff0c;那是极易中招的&#xff0c;网页字体使用是前端开发的工作之一&…

【Python】教你彻底了解Python中的数据科学与机器学习

​​​​ 文章目录 一、数据科学的基本概念1. 数据收集2. 数据清洗3. 数据分析4. 数据可视化5. 机器学习 二、常用的数据科学库1. Pandas1.1 创建Series和DataFrame1.2 数据操作 2. NumPy2.1 创建数组2.2 数组操作 3. Scikit-learn3.1 数据预处理3.2 特征工程 三、数据预处理与…

随手记:商品信息过多,展开收起功能

UI原型图&#xff1a; 页面思路&#xff1a; 在商品信息最小item外面有一个包裹所有item的标签&#xff0c;控制这个标签的高度来实现展开收起功能 <!-- 药品信息 --><view class"drugs" v-if"inquiryInfoSubmitBtn"><view class"…

天降流量于雀巢?元老品牌如何创新营销策略焕新生

大家最近有看到“南京阿姨手冲咖啡”的视频吗&#xff1f;三条雀巢速溶咖啡入杯&#xff0c;当面加水手冲&#xff0c;十元一份售出&#xff0c;如此朴实的售卖方式迅速在网络上走红。而面对这一波天降的热度&#xff0c;雀巢咖啡迅速做出了回应&#xff0c;品牌组特地去到了阿…

PySpark特征工程(I)--数据预处理

有这么一句话在业界广泛流传&#xff1a;数据和特征决定了机器学习的上限&#xff0c;而模型和算法只是逼近这个上限而已。由此可见&#xff0c;特征工程在机器学习中占有相当重要的地位。在实际应用当中&#xff0c;可以说特征工程是机器学习成功的关键。 特征工程是数据分析…

交流负载箱的使用场景和应用范围是什么?

交流负载箱模拟实际用电设备运行状态的电力测试设备&#xff0c;主要用于对各种电气设备、电源系统、发电机组等进行性能测试、质量检验和安全评估。交流负载箱的使用场景和应用范围非常广泛&#xff0c;涵盖了电力、通信、能源、交通等多个领域。 1. 电力行业&#xff1a;在电…