首页 > 其他分享 >使用vue+openLayers开发离线地图以及离线点位的展示

使用vue+openLayers开发离线地图以及离线点位的展示

时间:2023-08-10 09:55:37浏览次数:43  
标签:map vue const popup 离线 feature ol openLayers new

1 .下载 引入到需要的组件中

npm install ol

2. 需要用到的api... (根据开发需求以及实际情况进行引入)

import ol from "ol";
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { OSM, Vector as VectorSource, XYZ } from "ol/source";
import Overlay from "ol/Overlay";
import {
  Circle as sCircle,
  Fill,
  Stroke,
  Style,
  Circle as CircleStyle,
  Icon,
} from "ol/style";
import { defaults } from "ol/control";

3. 准备一个dom容器以及弹出层的容器

<div id="map"></div>
<div ref="popup" class="popup"></div>

4. 准备变量

map:null, // 地图容器
markers:[], // 地图点位
zoom:13, // 地图初始高度
position:[116.397128,39.916527], // 地图默认经纬度
popup:null, // 后期需要使用到的悬浮弹框

5. 代码如下:

mounted:{
    // 初始化一个地图
    this.initMap();
    // 获取后台的点位数据
    this.getData();
},
methods:{
      initMap(){
       // 首先创建一个离线瓦片图层
      const offlineLayer = new TileLayer({
       source: new XYZ({
          url: "后台地址+服务器文件名称" + "/{z}/{x}/{y}.png", // 设置本地离线瓦片所在路径
        }),
      }); 
       // 创建标点符号图层 设置他的样式
      const vectorLayer = new VectorLayer({
        source: new VectorSource({
          features: [],
        }),
        style: new Style({
          image: new sCircle({
            radius: 10,
            stroke: new Stroke({
              // 边界样式
              color: "rgba(64, 169, 255,.25)", // 边界颜色
              width: 16, // 边界宽度
            }),
            fill: new Fill({
              color: "#40a9ff",
            }),
          }),
        }),
      });
         // 创建地图
      this.map = new Map({
        // 设置地图控件,默认的三个控件都不显示
        controls: defaults({
          attribution: false,
          rotate: false,
          zoom: false,
        }),
        target: "map",
        layers: [offlineLayer, vectorLayer],
        view: new View({
          center: this.position, // 地图中心点
          zoom: this.zoom, // 缩放
          projection: "EPSG:4326", // 坐标系
          maxZoom: 18, // 限制地图缩放最大级别为18
        }),
      });
           // 创建弹出框
      this.popup = new Overlay({
        element: this.$refs.popup,

        positioning: "bottom-center",
        stopEvent: true,
        autoPanAnimation: {
          duration: 250,
        },
      });

      // 绑定
      this.map.addOverlay(this.popup);

      this.popup.setPositioning("center-center");

      // 监听鼠标移动 
      //openlayers / singleclick提供的方法
      this.map.on("pointermove", this.onMouseMove);
      // 监听鼠标单击
      this.map.on("singleclick", this.onMapClick);
    }, 
  },      
},
      // 获取数据 $get是对axios请求进行封装
    getData() {
     this.$get("点位接口").then((response) => {
       this.markers = response.data;
       setTimeout(() => { // 数据多可以使用定时器延时一下加载 避免全部加载造成卡顿
         this.addMarkers();
       }, 200);
     });
 },
      // 添加标记
    addMarkers() {
      const features = [];
      for (const marker of this.markers) {
        const feature = new Feature({
          geometry: new Point([marker.lon, marker.lat]),
          name: marker.name,
          num: marker.num,
          address: marker.address,
        });
        features.push(feature);
      }
      const vectorLayer = this.map.getLayers().getArray()[1];
      const source = vectorLayer.getSource();
      source.addFeatures(features);
    },
    // 鼠标移动
    onm ouseMove(event) {
      const pixel = this.map.getEventPixel(event.originalEvent);
      const feature = this.map.forEachFeatureAtPixel(
        pixel,
        (feature) => feature
      );
      const coordinates = feature.getGeometry().getCoordinates();
      if (feature) {
        const name = feature.get("name");
        const number = feature.get("cumber");
        const address = feature.get("address");
        this.popup.getElement().innerHTML = `
        <div>名称: <span>${name}</span></div>
        <div>号码: <span>${number}</span></div>
        <div>地址: <span>${address}</span></div>
        `;
        this.popup.setPosition(coordinates);
        this.popup.getElement().style.display = "block";
        this.map.getTargetElement().style.cursor = "pointer";
      } else {
        this.popup.getElement().style.display = "none";
        this.map.getTargetElement().style.cursor = "-webkit-grab";
      }
    },
        
    // 地图单击 可根据不同的需求对两个方法进行改写
     onMapClick(event) {
      const pixel = this.map.getEventPixel(event.originalEvent);
      const feature = this.map.forEachFeatureAtPixel(
        pixel,
        (feature) => feature
      );
      if (feature) {
        const coordinates = feature.getGeometry().getCoordinates();
        console.log(coordinates);
      }
    },
}

6. 最后贴出popup的样式

#map {
  height: 100%;
}

.popup {
  position: absolute;
  background-color: white;
  padding: 5px;
  border-radius: 5px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2), 0 2px 10px rgba(0, 0, 0, 0.1);
}

#popup {
  min-width: 19.375rem;
  min-height: 3.125rem;
  white-space: normal;
  font-size: 0.75rem;
  background-color: white;
  /* -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2)); */
}

7. 参考中文官网OpenLayers 3 介绍

标签:map,vue,const,popup,离线,feature,ol,openLayers,new
From: https://www.cnblogs.com/goodsLearn/p/17619477.html

相关文章

  • abp-vnext-pro 实战(六,vue 前端状态pinia)
    在login的时候把所有写入全局store,console.log('----------------从数据库获取字典--------------------');constappStore=useAppStore();constdataDictionaryServiceProxy=newDataDictionaryServiceProxy();constdetailInput=new......
  • Vue 自定义组件
    下面有一个例子。<template><el-input:value="value"@click.native="select"readonly><iclass="el-icon-circle-close"slot="suffix"@[email protected]="clear"/>&l......
  • 基于 HTML5 OpenLayers3 实现 GIS 电信资源管理系统
    前言通过结合HTML5和OpenLayers可以组合成非常棒的一个电信地图网络拓扑图的应用,形成的效果可以用来作为电信资源管理系统,美食定位分享软件,片区找房,绘制铁轨线路等等,各个领域都能够涉及的一款应用。虽然这个Demo是结合OpenLayers3的,其实还可推广到与ArcGIS、百度地图以及......
  • vue+django跨域问题
    解决办法:MIDDLEWARE=['corsheaders.middleware.CorsMiddleware','yshop.middleware.AuthorizeMiddleware','django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware�......
  • 在Vue中可以使用方括号法获得想要的对象数据吗?
    1.问题Document{{message}}{{school.name}}{{school[mobile]}}在这里{{school.name}}{{school[mobile]}}不可以使用方括号法获得想要的对象数据吗?2.解决在Vue.js中,使用双花括号({{}})来插值数据是正确的,但是方括号法([])用于动态属性访问的方式是不适......
  • avue-crud属性配置项参数笔记分享
     Avue是一个基于Element-plus低代码前端框架,它使用JSON配置来生成页面,可以减少页面开发工作量,极大提升效率;虽然Avue官网上面都有这些配置说明,但是如果刚开始接触不熟悉框架的话需要很久才找到自己需要的参数配置,为了方便自己今后查找使用,现将一些开发中常用的配置梳理在下......
  • vue启用https服务及nginx启用https配置
    1.vue开发环境中主要是configjs配置启用https服务devServer:{https:true,//启用https} 2.nginx 申请一个ssl证书,自行申请。 下面是一个nginx例子 需要修改的配置https主要是红色标出来部分。蓝色加粗部分主要是history模式下刷新出现404的解决办法ser......
  • vue3 + vite + vue-router 4.x项目在router文件中使用pinia报错
    1.背景vue-router4.x版本,想在路由文件中引入并使用pinia后报错如下:表面意思是getActivePinia()方法在pinia还没有激活的时候被调用,导致报错。2.解决方法在stores文件夹下新建pinia.js文件,用来引入并创建pinia实例。import{createPinia}from"pinia";const......
  • python离线打包
    1.导出已安装的列表pipfreeze>dependency.txt2.创建虚拟环境python-mvenvpath2venv3.在虚拟环境中安装导出的依赖列表path2venv/Script/pythoninstall-rdependency.txt4打包path2venv到自己的程序中,在程序中调用......
  • vue excel导入 补充校验
    前台校验<template><div><el-dialog:title="'校验'":close-on-click-modal="false"append-to-body:before-close="handleClose"v-if="visible":visible.sync="visib......