01、vue+openlayers6实现自定义测量功能(提供源码)

首先先封装一些openlayers的工具函数,如下所示:

import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Style from 'ol/style/Style';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Circle from 'ol/style/Circle';
import Polygon from 'ol/geom/Polygon';
import LineString from 'ol/geom/LineString';
import Point from 'ol/geom/Point';
import Feature from 'ol/Feature';
import Text from 'ol/style/Text';
import { getLength } from 'ol/sphere';
import { getArea } from 'ol/sphere';
import Draw from 'ol/interaction/Draw';
import { unByKey } from 'ol/Observable';

let draw;
let drawSource;//定义绘制图层
let drawLayer;//定义绘制图层
let sketch;
let output = 0;
let lastPolygonLabelFeature; //记录上一个面标注要素
let lastLengthLabelFeature; //记录上一个点标注要素

// 初始化测量绘制图层
export function initDrawLayer(map) {
    drawSource = new VectorSource({
        crossOrigin: "anonymous",
    });
    drawLayer = new VectorLayer({
        source: drawSource,
        style: new Style({
            fill: new Fill({
                color: "rgba(255, 255, 255, 0.2)",
            }),
            stroke: new Stroke({
                color: "#ffcc33",
                width: 2,
            }),
            image: new Circle({
                radius: 7,
                fill: new Fill({
                    color: "#ffcc33",
                }),
            }),
        }),
    });
    map.addLayer(drawLayer);
    map.on("pointermove", function (evt) {
        if (evt.dragging) {
            return;
        }
        let Coord;
        if (sketch) {
            let geom = sketch.getGeometry();
            if (geom instanceof Polygon) {
                if (lastPolygonLabelFeature) {
                    // console.log(lastPolygonLabelFeature);
                    //  鼠标移动,不停的添加和删除
                    drawSource.removeFeature(
                        lastPolygonLabelFeature
                    );
                }
                Coord = geom.getInteriorPoint().getCoordinates();
                //新建一个要素ol.Feature
                lastPolygonLabelFeature = new Feature({
                    geometry: new Point(Coord), //几何信息
                    name: output,
                });
                lastPolygonLabelFeature.setStyle(
                    createLabelStyle(lastPolygonLabelFeature, 0, 0)
                );
                drawSource.addFeature(lastPolygonLabelFeature);
            } else if (geom instanceof LineString) {
                if (lastLengthLabelFeature) {
                    drawSource.removeFeature(
                        lastLengthLabelFeature
                    );
                }
                Coord = geom.getLastCoordinate();
                // 新建一个要素ol.Feature
                lastLengthLabelFeature = new Feature({
                    geometry: new Point(Coord), //几何信息
                    name: output,
                });
                lastLengthLabelFeature.setStyle(
                    createLabelStyle(lastLengthLabelFeature, 35, -10)
                );
                // 设置要素样式
                drawSource.addFeature(lastLengthLabelFeature);
            }

        }
    });
    map.on("click", function (evt) {
        let coordinate = evt.coordinate; //鼠标单击点的坐标
        // //console.log(coordinate);
        if (output == "0") {
            lastPolygonLabelFeature = null;
            if (lastLengthLabelFeature) {
                drawSource.removeFeature(lastLengthLabelFeature);
                lastLengthLabelFeature = null;
            }
            return;
        }
        var Coord;
        if (sketch) {
            var geom = sketch.getGeometry();
            if (geom instanceof Polygon) {
                if (lastPolygonLabelFeature) {
                    drawSource.removeFeature(
                        lastPolygonLabelFeature
                    );
                }
                Coord = geom.getInteriorPoint().getCoordinates();
                //新建一个要素ol.Feature
                var newFeature = new Feature({
                    geometry: new Point(Coord), //几何信息
                    name: output,
                });
                lastPolygonLabelFeature = newFeature;
                newFeature.setStyle(
                    createLabelStyle(newFeature, 0, 0)
                ); //设置要素样式
                drawSource.addFeature(newFeature);
            } else if (geom instanceof LineString) {
                Coord = geom.getLastCoordinate();
                //新建一个要素ol.Feature
                let newFeature = new Feature({
                    geometry: new Point(Coord), //几何信息
                    name: output,
                });
                newFeature.setStyle(
                    createLabelStyle(newFeature, 35, -10)
                ); //设置要素样式
                drawSource.addFeature(newFeature);
            }
            let pointFeature = new Feature({
                geometry: new Point(coordinate), //几何信息
                name: output,
            });
            drawSource.addFeature(pointFeature);
        }
    });
}

// 定义测量结果的显示的样式
function createLabelStyle(feature, offsetX, offsetY) {
    return new Style({
        text: new Text({
            textAlign: "center", //位置
            textBaseline: "middle", //基准线
            font: "normal 10px sans-serif", //文字样式
            text: feature.get("name"), //文本内容
            fill: new Fill({
                //文本填充样式(即文字颜色)
                color: "white",
            }),
            stroke: new Stroke({
                color: "black",
                width: 5,
            }),
            offsetX: offsetX,
            offsetY: offsetY,
        }),
    });
}

function formatLength(line) {
    let length = getLength(line, {
        projection: "EPSG:3857",
        radius: 6378137,
    });
    let output;
    if (length > 100) {
        output = Math.round((length / 1000) * 100) / 100 + " " + "千米";
    } else {
        output = Math.round(length * 100) / 100 + " " + "米";
    }
    return output;
}

function formatArea(polygon) {
    var area = getArea(polygon, {
        projection: "EPSG:3857",
        radius: 6378137,
    });
    var output;
    if (area > 10000) {
        output =
            Math.round((area / 1000000) * 100) / 100 + " " + "平方公里";
    } else {
        output = Math.round(area * 100) / 100 + " " + "平方米";
    }
    return output;
}

function addInteraction(drawType, map) {
    let type = drawType == "area" ? "Polygon" : "LineString";
    draw = new Draw({
        source: drawSource,
        type: type,
        style: new Style({
            fill: new Fill({
                color: "rgba(255, 0, 0, 0.2)",
            }),
            stroke: new Stroke({
                color: "rgb(255,116,3)",
                width: 2,
            }),
            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: "rgba(255, 0, 0, 0.1)",
                }),
                fill: new Fill({
                    color: "rgba(255,116,3, 0.3)",
                }),
            }),
        }),
    });
    map.addInteraction(draw);
    var listener;
    draw.on(
        "drawstart",
        function (evt) {
            // set sketch
            sketch = evt.feature;
            listener = sketch
                .getGeometry()
                .on("change", function (evt) {
                    var geom = evt.target;
                    if (geom instanceof Polygon) {
                        output = formatArea(geom);
                    } else if (geom instanceof LineString) {
                        output = formatLength(geom);
                    }
                });
        }
    );
    draw.on(
        "drawend",
        function () {
            sketch = null;
            unByKey(listener);
            output = "0";
        }
    );
}

export function measureDistance(map) {
    if (draw) {
        map.removeInteraction(draw);
    }
    addInteraction("length", map);
}

export function measureArea(map) {
    if (draw) {
        map.removeInteraction(draw);
    }
    addInteraction("area", map);
}

export function measureClear(map) {
    map.removeInteraction(draw);
    drawLayer.setSource(null);
    drawSource = new VectorSource({
        crossOrigin: "anonymous",
    });
    drawLayer.setSource(drawSource);
    lastPolygonLabelFeature = null;
    lastLengthLabelFeature = null;
    sketch = null;
    output = "0";
}

export function interactionClear(map) {
    map.removeInteraction(draw);
}

然后再vue的组件中调用以上方法,代码如下:

在组件的monted中调用 initDrawLayer(map);方法

 //根据传入type值调用对应方法
         measure(type) {
            const that = this;
            
            if (type =="distance" ) {
                that.hideOverlay();
                measureDistance(window.map);
            }else  if (type =="area" ) {
                that.hideOverlay();
                measureArea(window.map);
            }else  if (type =="clear" ) {
                that.hideOverlay();
                measureClear(window.map);
            }
        }

最终实现效果如下:

源码地址连接:https://github.com/enjoyMaps/map_vue

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Android GPU渲染SurfaceFlinger合成RenderThread的dequeueBuffer/queueBuffer与fence机制(2)

Android GPU渲染SurfaceFlinger合成RenderThread的dequeueBuffer/queueBuffer与fence机制(2) 计算fps帧率 用 adb shell dumpsys SurfaceFlinger --list 查询当前的SurfaceView,然后有好多行,再把要查询的行内容完整的传给 ad…

题目----力扣--移除链表元素

题目 给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val val 的节点,并返回 新的头节点 。 示例 1: 输入:head [1,2,6,3,4,5,6], val 6 输出:[1,2,3,4,5]示例 2: 输入&…

智慧公厕:让厕所管理变得更智慧、高效、舒适!

公共厕所是城市的重要组成部分,但常常被忽视。它们的管理和养护往往面临着许多问题,例如卫生状况不佳、环境畏畏缩缩、设施老旧等。为了解决这些问题,智慧公厕应运而生。智慧公厕是一种全方位的应用解决方案,将科技与公共厕所管理…

我在洛杉矶采访到了亚马逊云全球首席信息官CISO(L11)!

在本次洛杉矶举办的亚马逊云Re:Inforce全球安全大会中,小李哥作为亚马逊大中华区开发者社区和自媒体代表,跟着亚马逊云安全产品团队采访了亚马逊云首席信息安全官(CISO)CJ Moses、亚马逊副总裁Eric Brandwine和亚马逊云首席高级安全工程师Becky Weiss。 …

搜索的未来:OpenAI 的 GPT 如何彻底改变行业

搜索的未来:OpenAI 的 GPT 如何彻底改变行业 概述 搜索引擎格局正处于一场革命的风口浪尖,而 OpenAI 的 GPT 处于这场变革的最前沿。最近出现了一种被称为“im-good-gpt-2-chatbot”的神秘聊天机器人,以及基于 ChatGPT 的搜索引擎的传言&am…

【C++ 内存管理】深拷贝和浅拷贝你了解吗?

文章目录 1.深拷贝2.浅拷贝3.深拷贝和浅拷贝 1.深拷贝 🍎 深拷⻉: 是对对象的完全独⽴复制,包括对象内部动态分配的资源。在深拷⻉中,不仅复制对象的值,还会复制对象所指向的堆上的数据。 特点: 🐧① 复制对…

DCDC中MOS半桥的自举电容,自举电阻问题

一个免费的翻译英文文章的网站,可以将英文数据手册翻译为中文(需要挂梯子,不收费,无广告,不需要注册),链接如下: Google 翻译 翻译效果: // 104电容是0.1uf&#xff1b…

Spring AOP(2)

目录 Spring AOP详解 PointCut 切面优先级Order 切点表达式 execution表达式 切点表达式示例 annotation 自定义注解MyAspect 切面类 添加自定义注解 Spring AOP详解 PointCut 上面代码存在一个问题, 就是对于excution(* com.example.demo.controller.*.*(..))的大量重…

Tomcat中服务启动失败,如何查看启动失败日志?

1. 查看 localhost.log 这个日志文件通常包含有关特定 web 应用的详细错误信息。运行以下命令查看 localhost.log 中的错误: sudo tail -n 100 /opt/tomcat/latest/logs/localhost.YYYY-MM-DD.log请替换 YYYY-MM-DD 为当前日期,或选择最近的日志文件日…

【notepad++】使用

1 notepad 下载路径 https://notepad-plus.en.softonic.com/download 2 设置护眼模式 . 设置——语言格式设置——前景色——黑色 . 背景色——RGB :199 237 204 . 勾选“使用全局背景色”、“使用全局前景色” . 保存并关闭

YOLOv5改进 | 注意力机制 | 理解全局和局部信息的SE注意力机制

在深度学习目标检测领域,YOLOv5成为了备受关注的模型之一。本文给大家带来的是能够理解全局和局部信息的SE注意力机制。文章在介绍主要的原理后,将手把手教学如何进行模块的代码添加和修改,并将修改后的完整代码放在文章的最后,方…

RAG查询改写方法概述

在RAG系统中,用户的查询是丰富多样的,可能存在措辞不准确和缺乏语义信息的问题。这导致使用原始的查询可能无法有效检索到目标文档。 因此,将用户查询的语义空间与文档的语义空间对齐至关重要,目前主要有查询改写和嵌入转换两种方…

代码随想录算法训练营第六十天| LeetCode647. 回文子串 、516.最长回文子序列

一、LeetCode647. 回文子串 题目链接/文章讲解/视频讲解:https://programmercarl.com/0647.%E5%9B%9E%E6%96%87%E5%AD%90%E4%B8%B2.html 状态:已解决 1.思路 这道题我只想出来了暴力解法,动规解法并没有想出来。根据视频讲解才把它想出来。…

【hackmyvm】 Animetronic靶机

靶机测试 arp-scanporturl枚举exiftool套中套passwordsudo 提权 arp-scan arp-scan 检测局域网中活动的主机 192.168.9.203 靶机IP地址port 通过nmap扫描,获取目标主机的端口信息 ┌──(root㉿kali)-[/usr/share/seclists] └─# nmap -sT -sV -O 192.16…

基于springboot+vue+Mysql的体质测试数据分析及可视化设计

开发语言:Java框架:springbootJDK版本:JDK1.8服务器:tomcat7数据库:mysql 5.7(一定要5.7版本)数据库工具:Navicat11开发软件:eclipse/myeclipse/ideaMaven包:…

C语言/数据结构——(相交链表)

一.前言 今天在力扣上刷到了一道题,想着和大家一起分享一下这道题——相交链表https://leetcode.cn/problems/intersection-of-two-linked-lists废话不多说,让我们开始今天的分享吧。 二.正文 1.1题目描述 是不是感觉好长,我也这么觉得。哈…

【智能优化算法】蜜獾优化算法(Honey Badger Algorithm,HBA)

蜜獾优化算法(Honey Badger Algorithm,HBA)是期刊“MATHEMATICS AND COMPUTERS IN SIMULATION”(IF 3.6)的2022年智能优化算法 01.引言 蜜獾优化算法(Honey Badger Algorithm,HBA)受蜜獾智能觅食行为的启发,从数学上发展出一种求解优化问题的…

Linux修炼之路之初识操作系统+基础指令(1)

目录 引言 一:对操作系统(OS)的简单了解 1.操作系统(OS) 是什么 2.操作系统好坏的衡量标准 3.操作系统存在的重要性 4.理解所有在计算机上的操作 二:Linux与windows操作的特点区别 三:基础指令 1.ls 指令 1.使用 2.常用选项 2.…

【17-Ⅰ】Head First Java 学习笔记

HeadFirst Java 本人有C语言基础,通过阅读Java廖雪峰网站,简单速成了java,但对其中一些入门概念有所疏漏,阅读本书以弥补。 第一章 Java入门 第二章 面向对象 第三章 变量 第四章 方法操作实例变量 第五章 程序实战 第六章 Java…

linux进阶篇:Nginx反向代理原理与案例详解

Linux服务搭建篇:Nginx反向代理原理与案例详解 一、什么是正向代理 举个栗子: 我们在校外、公司外,是访问不到学校、公司的内网的,但是我们想要访问内网资源时,会用到VPN。而一般内网会存在一个VPN服务器&#xff0c…