1
【vue-openlayers】弹窗
发布于: 2020 年 06 月 02 日


本例效果:
鼠标单击地图,会出出现弹窗显示当前点击的坐标信息(弹窗样式可以通过css调整,这里主要讲解JS部分)。如果点击地图边缘时,地图会根据弹窗尺寸进行适当的移动。
<template>  <div class="vm">    <div class="map-x" ref="map"></div>  </div></template><script>import 'ol/ol.css' // 引入ol提供的基础样式import { Map, View } from 'ol'import Tile from 'ol/layer/Tile'import XYZ from 'ol/source/XYZ' // 引入XYZ地图格式import Overlay from 'ol/Overlay' // ol提供的弹窗所需要素import { toStringHDMS } from 'ol/coordinate'import { toLonLat } from 'ol/proj'  export default {  name: 'Popup',  data() {    return {      map: null,      overlay: null,      currentCoordinate: ''    }  },  methods: {    initMap() {      // 弹窗要素      this.overlay = new Overlay({        element: this.$refs.popup, // 弹窗标签,在html里        autoPan: true, // 如果弹窗在底图边缘时,底图会移动        autoPanAnimation: { // 底图移动动画          duration: 250        }      })      // 实例化地图      this.map = new Map({        target: this.$refs.map, // 选中目标元素        layers: [ // 渲染图层          new Tile({            name: 'defaultLayer',            source: new XYZ({              url: 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'            })          })        ],        overlays: [this.overlay], // 把弹窗加入地图        view: new View({          projection: 'EPSG:4326', // 投影系          center: [113.1206, 23.034996], // 初始化中心点          zoom: 12 // 地图缩放级别(打开页面时默认级别)        })      })      this.mapClick()    },    // 地图点击事件    mapClick() {      // 给地图绑定一个单击事件      this.map.on("singleclick", evt => {        const coordinate = evt.coordinate // 获取坐标        const hdms = toStringHDMS(toLonLat(coordinate)) // 转换坐标格式        this.currentCoordinate = hdms // 保存坐标点        this.overlay.setPosition(coordinate) // 设置弹窗      })    },    // 关闭弹窗    closePopup () {      this.overlay.setPosition(undefined)      this.currentCoordinate = null    }  },  mounted () {    this.initMap()  }}</script><style lang="scss" scoped></style>
用法请看代码注释
划线
评论
复制
发布于: 2020 年 06 月 02 日阅读数: 71
版权声明: 本文为 InfoQ 作者【学习委员】的原创文章。
原文链接:【http://xie.infoq.cn/article/72154ea982156c5566264fe5f】。
本文遵守【CC-BY 4.0】协议,转载请保留原文出处及本版权声明。


学习委员
关注
来自神秘邪恶反派组织的一名楼道保安。 2019.03.19 加入
【特殊技能:反派的笑声】











 
    
评论 (2 条评论)