import driveDialogfrom '../components/driveDialog' // 引入自定义的悬浮框组件
import Vue from 'vue'
let driveDialogOverlay = Vue.extend(driveDialog)
...
methods: {
addCarOverlay () {
this.clearCarOverlay() // 首先清除悬浮框
this.myMarkId = driveData.id + '_' + driveData.name
const overlay = new ol.Overlay({
position: [0, 0], // 在地图所在的坐标系框架下,overlay 放置的位置,经纬度
positioning: 'top-center', // overlay 对于 position 的相对位置,可能的值是'bottom-left','bottom-center','bottom-right', 'center-left','center-center','center-right','top-left', 'top-center',和'top-right'
offset: [10, 10], // 偏移量,像素为单位。overlay 相对于放置位置(position)的偏移量,默认值是 [0, 0],正值分别向右和向下偏移
id: this.myMarkId, // 覆盖物的唯一标识 ,便于 getOverlayById 方法取得相应的 overlay
element: new driveDialogOverlay({
propsData: {
driveData: driveData
}
}).$mount().$el
})
this.map.addOverlay(overlay)
},
clearCarOverlay () {
if (!this.myMarkId) return
if (this.map.getOverlayById(this.myMarkId)) {
this.map.removeOverlay(this.map.getOverlayById(this.myMarkId))
}
this.myMarkId= null
},
}
// 下面是悬浮框组件的内部代码,主要解决跨地图边界显示不全的问题
<template>
<div id="myDiriveToolTip">
......
</div>
</template>
<script>
let _this = null
export default {
components: {},
mounted () {
// 思路:找到悬浮框绝对定位的父元素,然后和地图的长宽进行对比,如果悬浮框超出了地图边界,那么减去悬浮框的长或宽,重新赋值定位的left和top即可。(元素定位的方式与new ol.Overlay设置的positioning相关,并不一定是left和top,建议添加悬浮框后打开浏览器调试,找到悬浮框组件的父元素即可,样式写在父元素的style里)
this.$nextTick(() => {
_this = this
console.log(_this.$el, '打印一下$el.left', document.getElementById('myDiriveToolTip').parentNode)
if (document.getElementById('myDiriveToolTip') && document.getElementById('myDiriveToolTip').parentNode) {
let resetNode = document.getElementById('myDiriveToolTip').parentNode
let left = document.getElementById('myDiriveToolTip').parentNode.style.left // 获取定位的左偏移量
left = left.replace('px', '')
try {
left = parseInt(left)
} catch (error) {}
let top = document.getElementById('myDiriveToolTip').parentNode.style.top // 获取定位的上偏移量
top = top.replace('px', '')
try {
top = parseInt(top)
} catch (error) {}
const clientWidth = document.body.offsetWidth // 获取页面总宽度
const clientHeight = document.body.offsetHeight // 获取页面总高度
if (left > clientWidth - 500 - 10) { // 如果超过右边界, 那么减去悬浮框的宽度
left = left - 500 - 10
}
if (top > clientHeight - 500 - 10) { // 如果超过下边界, 那么减去悬浮框的高度
top = top - 500 - 10
}
// 重写style样式
resetNode.style.left = left + 'px'
resetNode.style.top = top + 'px'
}
})
},
data () {},
methods: {}
}
</script>
<style lang='less' scoped></style>
openlayer自定义悬浮框overlay及其跨地图边界显示不全的解决方案
于 2022-07-03 22:09:55 首次发布