1. 效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d73f1c4f6dbed10776ecde47a55ebc65.png)
2. 代码
<template>
<div class="container">
<div id="map" style='width: 100%; height: 100%;border: 5px solid #a4cdff;'>
<div class="toolBox">
<div class="messageBox" v-show="isShow">
<div class="messages">要展示的信息</div>
<el-button @click="closeWin" size="mini">取 消</el-button>
<el-button type="primary" size="mini" @click="closeWin">确 定</el-button>
</div>
</div>
</div>
</div>
</template>
<script>
import { Map, View, Feature } from 'ol'
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
import { XYZ, Vector as VectorSource } from 'ol/source'
import { Point } from 'ol/geom'
import { Style, Fill, Stroke, Circle as SCircle } from 'ol/style'
import Overlay from 'ol/Overlay'
import imgName from '../assets/target.png'
export default {
name: 'myMap',
components: {
},
data () {
return {
openMap: null,
myLocation: null,
myDialog: null,
address: [118.7969, 32.0603],
isShow: false,
imgSrc: imgName,
getLocationFlag: false,
clickLocation: ''
}
},
created () {
document.title = 'myMap'
},
mounted () {
this.initMap()
},
methods: {
initMap () {
this.openMap = new Map({
target: 'map',
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}'
})
})
],
view: new View({
center: this.address,
projection: 'EPSG:4326',
zoom: 5
}),
controls: []
})
this.singleclick()
},
singleclick () {
this.openMap.on('singleclick', (e) => {
console.log(e, '底图点击处携带的数据')
console.log(e.coordinate, '底图当前点击位置的坐标')
this.clickLocation = e.coordinate
const feature = this.openMap.forEachFeatureAtPixel(e.pixel, (feature) => feature)
if (feature) {
console.log(feature, '点击原点携带的数据set')
} else {
this.setDIYmarkers(this.clickLocation)
}
})
setDIYmarkers (myLocation) {
if (this.myLocation) {
this.openMap.removeOverlay(this.myLocation)
}
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: myLocation,
offset: [-20, -30],
autoPan: true
})
this.myLocation = marker
el.addEventListener('click', (e) => {
this.isShow = true
this.showDialog(this.myLocation.options.position)
})
this.openMap.addOverlay(marker)
},
showDialog (location) {
const dialog = document.querySelector('.messageBox')
const marker = new Overlay({
element: dialog,
position: location,
offset: [-150, -220]
})
this.myDialog = marker
console.log('1212121212')
this.openMap.addOverlay(this.myDialog)
},
clearMyLocation () {
if (this.myLocation) {
this.openMap.removeOverlay(this.myLocation)
}
},
closeWin () {
this.isShow = false
}
}
}
</script>
<style scoped>
.container {
width: 100%;
height: 80vh;
border-radius: 50px;
background-color: rgba(255, 192, 203, 0.277);
}
.toolBox {
position: relative;
}
.messageBox {
width: 300px;
height: 200px;
background-color: #fff;
}
.messages {
width: 100%;
height: 70%;
}
</style>