vue2 openlayers 廊坊市中聚合点 点击标注信息弹窗的代码
时间: 2023-10-01 12:04:04 浏览: 125
以下是一个简单的示例代码,用于在Vue2中使用OpenLayers 6来显示一个地图,添加一个聚合点,并在点击聚合点时显示相关的标注信息弹窗:
```html
<template>
<div id="map"></div>
</template>
<script>
import 'ol/ol.css'
import { Map, View } from 'ol'
import Point from 'ol/geom/Point'
import Feature from 'ol/Feature'
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
import { fromLonLat } from 'ol/proj'
import { Vector as VectorSource } from 'ol/source'
import { Cluster } from 'ol/source'
import Overlay from 'ol/Overlay'
export default {
name: 'MapComponent',
data() {
return {
map: null,
popup: null
}
},
mounted() {
this.initMap()
},
methods: {
initMap() {
// 创建地图
this.map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new XYZ({
url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
})
})
],
view: new View({
center: fromLonLat([116.7, 39.5]),
zoom: 10
})
})
// 创建聚合点
const clusterSource = new Cluster({
distance: 40,
source: new VectorSource({
features: [
new Feature(new Point(fromLonLat([116.718, 39.523]))),
new Feature(new Point(fromLonLat([116.729, 39.504]))),
new Feature(new Point(fromLonLat([116.752, 39.506]))),
new Feature(new Point(fromLonLat([116.745, 39.521]))),
new Feature(new Point(fromLonLat([116.738, 39.53]))),
new Feature(new Point(fromLonLat([116.707, 39.534]))),
new Feature(new Point(fromLonLat([116.698, 39.526]))),
new Feature(new Point(fromLonLat([116.686, 39.517])))
]
})
})
const clusterLayer = new VectorLayer({
source: clusterSource
})
this.map.addLayer(clusterLayer)
// 创建弹窗
const popupContainer = document.createElement('div')
popupContainer.setAttribute('id', 'popup')
popupContainer.setAttribute('class', 'ol-popup')
document.body.appendChild(popupContainer)
this.popup = new Overlay({
element: popupContainer,
autoPan: true,
autoPanAnimation: {
duration: 250
}
})
this.map.addOverlay(this.popup)
// 监听聚合点点击事件
this.map.on('click', (event) => {
const feature = this.map.forEachFeatureAtPixel(event.pixel, (feature) => {
return feature
})
if (feature && feature.get('features').length > 1) {
const coordinates = feature.getGeometry().getCoordinates()
const count = feature.get('features').length
const content = `
<p>共有${count}个标注点</p>
`
this.popup.setPosition(coordinates)
this.popup.getElement().innerHTML = content
}
})
}
}
}
</script>
<style>
.ol-popup {
position: absolute;
background-color: white;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
padding: 15px;
border-radius: 10px;
border: 1px solid #cccccc;
bottom: 12px;
left: -50px;
min-width: 200px;
}
</style>
```
该示例代码创建了一个地图,并在其中添加了一个聚合点,每个聚合点包含多个标注点。当用户点击聚合点时,会弹出一个标注信息弹窗,显示该聚合点中包含的标注点数量。你可以根据自己的需要修改代码中的坐标、弹窗内容等信息。
阅读全文