封装了一个实时显示鼠标坐标的组件供大家参考
组件代码:
<template>
<div>
<div id="pointOverlay">
<span>x:{{ coordinations[0] }} y:{{ coordinations[1] }}</span>
</div>
</div>
</template>
<script >
import Overlay from "ol/Overlay.js";
export default {
props: [ 'map', 'show'],
data() {
return {
mousePositionOverlay: null,
coordinations:[]
}
},
mounted() {
let element = document.getElementById("pointOverlay")
this.mousePositionOverlay = new Overlay({
element: element,
position: null,
positioning: "bottom-center"
})
},
methods: {
pointermoveHandler(event) {
this.coordinations = [event.coordinate[0].toFixed(4), event.coordinate[1].toFixed(4)]
this.mousePositionOverlay.setPosition(event.coordinate)
}
},
watch: {
show: {
immediate:true,
handler(newVal) {
let _this = this
if (newVal) {
this.map.addOverlay(_this.mousePositionOverlay)
this.map.on('pointermove', _this.pointermoveHandler)
} else {
this.map.removeOverlay(this.mousePositionOverlay)
this.map.un('pointermove', _this.pointermoveHandler)
}
}
}
}
}
</script>
<style scoped lang="less">
#pointOverlay {
width: 230px;
height: 30px;
border: 2px solid #E6A23C;
border-radius: 2px;
text-align: center;
line-height: 30px;
color: white;
margin-bottom: 5px;
backdrop-filter: blur(5px);
background-color: rgba(255, 255, 255, 0.5);
}
</style>
使用的时候只需要传入两个属性map(当前的地图对象),show(控制组件显示隐藏的变量)
引入:这里用自己的路径
import MousePosition from "../../PublicModal/MousePosition.vue";
注册:(这里使用的是vue的模式哈,vue3应该是不需要注册直接使用的):
components: {
MousePosition
},
使用:
//map为当前实例化的地图, isShow控制组件的显示与隐藏
<MousePosition :map="map" :show="isShow"></MousePosition>
感谢您的阅读,如果有用的话可以点个赞吗?谢谢大佬!嘿嘿嘿————