openlayers地图自定义图标打点(二)

1.效果

在这里插入图片描述

2.代码

结构,地图初始化同上篇

<template>
    <div class="container">
    	//地图结构
        <div id="map"></div>
    </div>
</template>

<script>
//引入依赖项
import { Map, View } from 'ol'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import Overlay from 'ol/Overlay'
import imgName from '../assets/target.png'
export default {
  data () {
    return {
      map: null,//地图实例
      imgSrc: imgName,//自定义打点图标的图片地址
      clickLocation: '',//点击地图时的坐标数据
      myLocation: ''//当前打点位置的maker对象
    }
  },
  mounted () {
    this.initMap()//初始化
  },
  methods: {
    // 初始化
    initMap () {
      // 创建一个map对象,指定地图容器的id和展示地图的初始视图
      this.map = new Map({
        target: 'map', // 地图容器的id
        layers: [
          new TileLayer({
            source: new XYZ({
              url: 'https://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=7&style=7&x={x}&y={y}&z={z}'
            })
          })
        ],
        // 添加一个OSM(OpenStreetMap)图层
        view: new View({
          // 将西安作为地图中心
          // center: olProj.fromLonLat(this.address),//坐标转换
          center: [118.7969, 32.0603],
          // 经纬度转换
          projection: 'EPSG:4326', // EPSG:3857(默认坐标格式)
          // 初始时地图放大的级别
          zoom: 5
        }),
        controls: []
      })
      this.singleclick()
    },

    // 底图添加点击事件
    singleclick () {
      this.map.on('singleclick', (e) => {
        console.log(e, '底图点击处携带的数据')
        console.log(e.coordinate, '底图当前点击位置的坐标')
        this.clickLocation = e.coordinate
        this.setDIYmarkers(this.clickLocation)
      })
    },
    // 设置自定义打点要素
    setDIYmarkers (myLocation) {
      if (this.myLocation) {
      //清除上一次标记的点
        this.map.removeOverlay(this.myLocation)
      }
      // 创建一个dom元素
      const el = document.createElement('img')
      el.src = this.imgSrc
      el.style.width = '40px'
      el.style.height = '40px'
      el.style.cursor = 'pointer'
      const marker = new Overlay({
        element: el, // 要显示的元素
        // position: fromLonLat(myLocation), // 地图投影的位置
        position: myLocation, // 地图投影的位置
        offset: [-20, -30], // 元素显示的像素偏移量
        autoPan: true // 自动移动地图以完整的显示元素
      })
      this.myLocation = marker
      this.map.addOverlay(marker)
    }
  }
}
</script>
<style lang='scss'  scoped>
.container {
    width: 100%;
    height: 100vh;
    border-radius: 50px;
    /* border: 1px solid red; */
    background-color: rgba(255, 192, 203, 0.277);

    #map {
        width: 100%;
        height: 100%;
        border: 1px solid red;
        border-radius: 50px;
    }
}
</style>



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值