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>