前端开发---在vue项目中使用openLayers

news2024/9/23 21:28:23

前端开发之在vue项目中使用openLayers

  • 前言
  • 效果图
  • 在vue中渲染地图
    • 安装ol插件
    • 1、调用插件
    • 2、 初始话地图
    • 3、地图点击事件
    • 4、重置坐标
    • 5、通过坐标改变视图
    • 6、保存坐标点
  • vue中使用的源码

前言

本篇文章主要讲解openLayers的初步使用,包括渲染地图、获取点坐标、标记点、中心位置的调整、以及获取到经纬度向后台发送请求
演示地址
官网
gitee链接

效果图

在这里插入图片描述

在vue中渲染地图

安装ol插件

npm install ol

1、调用插件

import “ol/ol.css”;
import { Map, View, ol } from “ol”;
import TileLayer from “ol/layer/Tile”;

2、 初始话地图

/**
     * 初始化地图
     */
    initMap () {
      var that = this
      // 创建地图中心点坐标
      const centerCoordinate = [0, 0];

      // 初始化视图对象
      const view = new View({
        center: centerCoordinate,
        zoom: 3,
        projection: "EPSG:4326",
      });

      // 创建ArcGIS World Street Map图层
      const arcGISLayer = new TileLayer({
        source: new XYZ({
          // url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}"
          url: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}"

        })
      });
      // 初始化地图对象
      this.map = new Map({
        target: this.$refs.mapContainer,
        layers: [
          arcGISLayer
        ],
        view: view
      });
      //鼠标单击事件
      this.map.on('singleclick', function (e) {
        that.mapX = e.coordinate[0]
        that.mapY = e.coordinate[1]
        that.addVectorLabel(e.coordinate)
      });

      return this.map
    },

3、地图点击事件

// 定义点
    createLabelStyle (feature) {
      return new Style({
        /**{olx.style.IconOptions}类型*/
        image: new Icon(
          ({
            anchor: [0.5, 60],
            anchorOrigin: 'top-right',
            anchorXUnits: 'fraction',
            anchorYUnits: 'pixels',
            offsetOrigin: 'top-right',
            // offset:[0,10],
            //图标缩放比例
            scale: 0.1,
            //透明度
            opacity: 0.75,
            //图标的url
            src: require("../assets/gd.png")
          })
        )
      });
    },

    // 添加坐标点
    addVectorLabel (coordinate) {
      if (this.vectorSource) {
        this.vectorSource.clear()
      } else {
        //矢量标注的数据源
        this.vectorSource = new VectorSource({
          features: []
        })
      }

      // //矢量标注图层
      this.vectorLayer = new VectorLayer({
        source: this.vectorSource
      });
      this.map.addLayer(this.vectorLayer);
      //新建一个要素
      var newFeature = new Feature({
        //几何信息
        geometry: new Point(coordinate)
      });
      //设置要素的样式
      newFeature.setStyle(this.createLabelStyle(newFeature));
      this.vectorSource.addFeature(newFeature);
    }

4、重置坐标

CZ () {
      this.vectorSource.clear()
      this.mapX = ''
      this.mapY = ''
    },

5、通过坐标改变视图

DW () {
var view = this.map.getView();
var py = ([parseInt(this.mapX), parseInt(this.mapY)]);
//平移地图
view.setCenter(py);
this.addVectorLabel([this.mapX, this.mapY])
view.setZoom(9);
},

6、保存坐标点

BC () {
      var parpms = {
        mapX: this.mapX,
        mapY: this.mapY
      }
      const instance = axios.create({
        baseURL: 'https://127.0.0.1'
      });
      instance.post('/api/data', parpms)
        .then(response => {
          // response.data;//请求返回的数据
        })
        .catch(error => {
          console.log(error);
        });
    },

vue中使用的源码

<template>
  <div>
    <div id="map-container" ref="mapContainer" class="map-container"></div>
    <div class="formList">
      <div class="input">
        <div class="name">北纬:</div>
        <el-input v-model="mapX" placeholder="请输入内容"></el-input>
      </div>
      <div class="input">
        <div class="name">东经:</div>
        <el-input v-model="mapY" placeholder="请输入内容"></el-input>
      </div>
      <div class="button" @click='CZ'>重置</div>
      <div class="button" @click='DW'>定位</div>
      <div class="button" @click='BC'>保存</div>
    </div>
  </div>

</template>

<script>
import "ol/ol.css";

import { fromLonLat } from "ol/proj";
import { OSM, Vector as VectorSource, Raster as RasterSource } from "ol/source";
import { Vector as VectorLayer } from "ol/layer";
import { Fill, Style, Stroke, Icon, Circle as CircleStyle } from "ol/style";
import { Point } from "ol/geom"; //标点,画线
import Feature from "ol/Feature";
import { Map, View, ol } from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import axios from 'axios';

export default {
  name: "MapComponent",
  data () {
    return {
      mapX: '',
      mapY: '',
    };
  },
  mounted () {
    this.map = this.initMap()
  },
  methods: {
    /**
     * 初始化地图
     */
    initMap () {
      var that = this
      // 创建地图中心点坐标
      const centerCoordinate = [0, 0];

      // 初始化视图对象
      const view = new View({
        center: centerCoordinate,
        zoom: 3,
        projection: "EPSG:4326",
      });

      // 创建ArcGIS World Street Map图层
      const arcGISLayer = new TileLayer({
        source: new XYZ({
          url: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}"

        })
      });
      // 初始化地图对象
      this.map = new Map({
        target: this.$refs.mapContainer,
        layers: [
          arcGISLayer
        ],
        view: view
      });
      //鼠标单击事件
      this.map.on('singleclick', function (e) {
        that.mapX = e.coordinate[0]
        that.mapY = e.coordinate[1]
        that.addVectorLabel(e.coordinate)
      });

      return this.map
    },

    CZ () {
      this.vectorSource.clear()
      this.mapX = ''
      this.mapY = ''
    },

    DW () {
      var view = this.map.getView();
      var py = ([parseInt(this.mapX), parseInt(this.mapY)]);
      //平移地图
      view.setCenter(py);
      this.addVectorLabel([this.mapX, this.mapY])
      view.setZoom(9);
    },
    BC () {
      var parpms = {
        mapX: this.mapX,
        mapY: this.mapY
      }
      const instance = axios.create({
        baseURL: 'https://127.0.0.1'
      });
      instance.post('/api/data', parpms)
        .then(response => {
          // response.data;//请求返回的数据
        })
        .catch(error => {
          console.log(error);
        });
    },





    // 定义点
    createLabelStyle (feature) {
      return new Style({
        /**{olx.style.IconOptions}类型*/
        image: new Icon(
          ({
            anchor: [0.5, 60],
            anchorOrigin: 'top-right',
            anchorXUnits: 'fraction',
            anchorYUnits: 'pixels',
            offsetOrigin: 'top-right',
            // offset:[0,10],
            //图标缩放比例
            scale: 0.1,
            //透明度
            opacity: 0.75,
            //图标的url
            src: require("../assets/gd.png")
          })
        )
      });
    },

    // 添加坐标点
    addVectorLabel (coordinate) {
      if (this.vectorSource) {
        this.vectorSource.clear()
      } else {
        //矢量标注的数据源
        this.vectorSource = new VectorSource({
          features: []
        })
      }

      // //矢量标注图层
      this.vectorLayer = new VectorLayer({
        source: this.vectorSource
      });
      this.map.addLayer(this.vectorLayer);
      //新建一个要素
      var newFeature = new Feature({
        //几何信息
        geometry: new Point(coordinate)
      });
      //设置要素的样式
      newFeature.setStyle(this.createLabelStyle(newFeature));
      this.vectorSource.addFeature(newFeature);
    }
  }
};
</script>

<style>
.map-container {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
}

.formList {
  position: fixed;
  top: 10px;
  left: 50px;
  display: flex;
}

.formList div {
  margin-left: 20px;
}

.button {
  width: 50px;
  line-height: 40px;
  background-color: #f68e41;
  border-radius: 3px;
  color: #fff;
}

.input {
  display: flex;
}

.input .name {
  line-height: 40px;
  width: 25%;
}
</style>

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

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

相关文章

Data Analysis With Python

文章目录 Data Analysis With PythonAnalyzing Numerical Data with NumPyCreating NumPy ArrayNumPy Array SlicingNumPy Array BroadcastingAnalyzing Data Using Pandas In this article, we will discuss how to do data analysis with Python. We will discuss all sorts …

平衡二叉树AVL的插入删除

在AVL树的插入操作中&#xff0c;假设插入一个结点后&#xff0c;当前节点p的平衡因子是&#xfe63;2&#xff0c;其左子结点的平衡因子是&#xff0b;1&#xff0c;左子结点的右子结点的平衡因子是&#xfe63;1。如图所示&#xff0c;请给出票转调整之后的结构。

微机原理与接口技术-第八章常用接口技术

文章目录 定时控制接口8253/8254定时器定时器的应用 并行接口并行接口电路8255内部引脚工作方式工作方式0&#xff1a;基本输入输出方式工作方式1&#xff1a;选通输入输出方式 编程 并行接口的应用用8255方式0与打印机接口 数码管及其接口数码管的工作原理单个数码管的显示多个…

目录和文件操作

在自己电脑任一盘符中新建以OS_Test命名的文件夹&#xff0c;并在该文件夹中新建新建3个以.txt&#xff0c;3个 .xlsx为扩展名的文件&#xff08;文件名由代码随机生成&#xff0c;长度为8&#xff0c;由字母数字组成&#xff09;。&#xff0c;请写一个程序&#xff0c;删除掉…

Unity的unity_ObjectToWorld里的每一列分别代表什么意思?换个方向反向理解-更简单

官方关键UnityObjectToWorldNormal&#xff08;&#xff09; 代码 从乐乐姐的书中得知&#xff0c;当我们在shader想获得法线&#xff0c;大概会这么些 o.wordDir UnityObjectToWorldNormal(i.normal) &#xff08;这行代码就包含了官方对“unity_ObjectToWorld”的终极理解…

视频批量剪辑技巧:如何实现震撼的嵌套合并效果

随着视频制作需求的不断增长&#xff0c;视频批量剪辑技巧在提高制作效率和质量方面显得尤为重要。本文将介绍云炫AI智剪实现震撼嵌套合并效果的方法&#xff0c;帮助您在视频制作过程中更高效地完成任务。 视频批量剪辑技巧是一种利用计算机技术实现自动化视频剪辑的方法。通…

串口占用检测工具

串口占用检测工具 平时需要检测哪个程序占用了串口&#xff0c;下面介绍一款非常方便的工具&#xff0c;它的工具箱里包含一个串口占用检测工具&#xff0c;可以非常方便的检测出来哪个程序占用了串口&#xff0c;并给出程序名和PID。 官网下载地址&#xff1a;http://www.red…

2023枣庄麒瑞音乐嘉年华济南新闻发布会

2023枣庄麒瑞音乐嘉年华新闻发布会今日在济南市西元大厦隆重举行&#xff0c;演唱会主办方枣庄恒立城市发展投资有限公司副经理刘畅先生、枣庄麒瑞文化董事长孙振敏女士&#xff0c;演唱会冠名方滕州爱啤士精酿啤酒有限公司总经理周静女士等和国内及山东省近30家主流新闻媒体到…

命令模式——让程序舒畅执行

● 命令模式介绍 命令模式&#xff08;Command Pattern&#xff09;&#xff0c;是行为型设计模式之一。命令模式相对于其他的设计模式来说并没有那么多条条框框&#xff0c;其实并不是一个很“规矩”的模式&#xff0c;不过&#xff0c;就是基于一点&#xff0c;命令模式相对于…

局域网内两台电脑共享文件夹(通过网线直连共享数据)

文章目录 2.设置共享文件夹3.访问共享文件夹 1.将两台电脑置于同一局域网下 用网线将两台电脑连接关闭两台电脑防火墙将两台电脑IP地址设置在同一局域网下 测试是否在同一局域网下&#xff0c;使用ping命令 ping 192.168.0.122.设置共享文件夹 选择想要共享的文件夹&#xff…

刷题学习记录

sql注入&#xff08;bugkuctf&#xff09; 打开显示一个登录框 照常用admin用户名登录&#xff0c;密码随便填一个&#xff0c;显示密码错误 接着用admin为用户名登录&#xff0c;密码照样随便填,结果显示用户名不存在 题目提示基于布尔的SQL盲注&#xff0c;猜测后端是判断用…

【torch高级】一种新型的概率学语言pyro(02/2)

前文链接&#xff1a;【torch高级】一种新型的概率学语言pyro&#xff08;01/2&#xff09; 七、Pyro 中的推理 7.1 背景&#xff1a;变分推理 引言中的每项计算&#xff08;后验分布、边际似然和后验预测分布&#xff09;都需要执行积分&#xff0c;而这通常是不可能的或计算…

静力触探数据智能预处理(4)

静力触探数据智能预处理&#xff08;4&#xff09; 前言 数据处理方式已由手工1.0、计算机辅助2.0向人工智能3.0的趋势发展。机器学习是人工智能的基础&#xff0c;本文尝试应用机器学习中K均值聚类算法对孔压静力触探数据进行土的分类&#xff0c;分类结果不理想&#xff0c…

buuctf_练[安洵杯 2019]easy_web

[安洵杯 2019]easy_web 文章目录 [安洵杯 2019]easy_web掌握知识解题思路代码分析正式解题 关键paylaod 掌握知识 url地址和源代码的信息捕捉&#xff1b;图片和base64之间转换&#xff1b;base64和十六进制编码的了解&#xff1b;代码审计&#xff0c;绕过正则匹配对关键字的…

简易但很实用的javaswing/gui音乐播放器

视频浏览地址 很实用的一个javaswing音乐播放器。可以展示歌名&#xff0c;上一曲下一曲。 源码下载地址 支持&#xff1a;远程部署/安装/调试、讲解、二次开发/修改/定制

Java八股文 ----Redis篇

问题大纲 缓存穿透 原因:入侵者大量查询不存在的数据 使得Redis不断去访问数据库 然而Redis也无法缓存,就导致每次都会查询数据库...数据库的并发度不高 就会宕机 解决办法 布隆过滤器:作用:拦截不存在的数据 布隆过滤器 原理:把数据的id通过多次哈希计算标记数组,新来个数…

Easex样式样式

eg1&#xff1a;线形样式和描边 #include <stdio.h> #include <easyx.h> #include <iostream> #include <math.h> #define PI 3.14 // 1PI 180度 2PI 360度int main() {initgraph(800, 600);setorigin(400, 300);setaspectratio(1, -1);/*void setl…

基于Ubuntu20.04安装ROS系统

文章目录 一、ROS简介二、ROS安装三、ROS安装测试四、安装问题解决1. sudo rosdepc init&#xff1a;找不到命令2. ERROR: cannot download default sources list from...3. Command roscore not found...4. Resource not found: roslaunch... 一、ROS简介 ROS是用于编写机器人…

行业追踪,2023-10-27

自动复盘 2023-10-27 凡所有相&#xff0c;皆是虚妄。若见诸相非相&#xff0c;即见如来。 k 线图是最好的老师&#xff0c;每天持续发布板块的rps排名&#xff0c;追踪板块&#xff0c;板块来开仓&#xff0c;板块去清仓&#xff0c;丢弃自以为是的想法&#xff0c;板块去留让…

前后端分离不可忽视的陷阱,深入剖析挑战,分享解决方案,助你顺利实施分离开发。

不管你设计的系统架构是怎么样&#xff0c;最后都是你的组织内的沟通结构胜出。这个观点一直在组织内不断地被证明&#xff0c;但也不断地被忽略。 前后端分离的利与弊 近几年&#xff0c;随着微服务架构风格的引入、前后端生态的快速发展、多端产品化的出现&#xff0c;前后…