要使弹出窗口(覆盖层)可拖动,可以使用Angular5和OpenLayers5结合的方法。以下是一个示例代码:
HTML模板:
Popup Window
This is a draggable popup window.
X
CSS样式:
.map-container {
position: relative;
width: 500px;
height: 400px;
}
.map {
width: 100%;
height: 100%;
}
.popup {
position: absolute;
z-index: 1000;
background-color: #fff;
border: 1px solid #ccc;
padding: 10px;
}
.close {
position: absolute;
top: 5px;
right: 5px;
cursor: pointer;
}
组件代码:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Map, View } from 'ol';
import { Overlay } from 'ol/Overlay';
import { fromLonLat } from 'ol/proj';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
@ViewChild('mapDiv') mapDiv: ElementRef;
map: Map;
overlay: Overlay;
popupVisible: boolean = false;
popupPosition: { left: number, top: number } = { left: 0, top: 0 };
dragStartPos: { x: number, y: number } = { x: 0, y: 0 };
constructor() { }
ngOnInit() {
this.initMap();
}
initMap() {
this.map = new Map({
target: this.mapDiv.nativeElement,
view: new View({
center: fromLonLat([0, 0]),
zoom: 2
})
});
// 创建覆盖层
this.overlay = new Overlay({
element: document.querySelector('.popup'),
positioning: 'center-center',
stopEvent: false
});
this.map.addOverlay(this.overlay);
}
startDrag(event) {
if (event.button === 0) {
this.dragStartPos.x = event.clientX - this.overlay.getPosition()[0];
this.dragStartPos.y = event.clientY - this.overlay.getPosition()[1];
document.addEventListener('mousemove', this.doDrag.bind(this));
document.addEventListener('mouseup', this.stopDrag.bind(this));
}
}
doDrag(event) {
this.popupPosition.left = event.clientX - this.dragStartPos.x;
this.popupPosition.top = event.clientY - this.dragStartPos.y;
}
stopDrag() {
document.removeEventListener('mousemove', this.doDrag);
document.removeEventListener('mouseup', this.stopDrag);
}
openPopup() {
this.popupVisible = true;
}
closePopup() {
this.popupVisible = false;
}
}
在组件的ngOnInit
方法中,初始化地图和覆盖层。在startDrag
方法中,记录鼠标点击时的位置,并注册mousemove
和mouseup
事件监听器。在doDrag
方法中,根据鼠标移动的距离更新覆盖层的位置。在stopDrag
方法中,移除事件监听器。openPopup
和closePopup
方法用于控制弹出窗口的显示和隐藏。
通过以上代码,可以实现在地图上使用OpenLayers5创建一个可拖动的弹出窗口。