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', // 地图容器的idlayers: [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.coordinatethis.setDIYmarkers(this.clickLocation)})},// 设置自定义打点要素setDIYmarkers (myLocation) {if (this.myLocation) {//清除上一次标记的点this.map.removeOverlay(this.myLocation)}// 创建一个dom元素const el = document.createElement('img')el.src = this.imgSrcel.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 = markerthis.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>