openlayer坐标位置在点击后弹出提示框
时间: 2023-07-25 16:48:38 浏览: 140
要在OpenLayers地图上点击位置后弹出提示框,可以使用Overlay和Popup来实现。以下是一个简单的例子:
```javascript
// 创建地图
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([116.3975, 39.9086]),
zoom: 10
})
});
// 创建一个VectorLayer用于添加点
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector()
});
// 创建一个Overlay用于显示提示框
var popupOverlay = new ol.Overlay({
element: document.getElementById('popup'),
autoPan: true,
autoPanAnimation: {
duration: 250
}
});
// 创建一个点击事件处理函数
function handleMapClick(event) {
// 获取点击位置的坐标
var coordinate = event.coordinate;
// 创建一个点Feature并添加到VectorLayer上
var feature = new ol.Feature({
geometry: new ol.geom.Point(coordinate)
});
vectorLayer.getSource().addFeature(feature);
// 设置提示框内容为坐标
var content = '<p>坐标:' + coordinate + '</p>';
document.getElementById('popup-content').innerHTML = content;
// 将提示框显示在点击位置上
popupOverlay.setPosition(coordinate);
map.addOverlay(popupOverlay);
}
// 监听Map对象的"click"事件,并在回调函数中处理点击事件
map.on('click', handleMapClick);
// 将VectorLayer添加到地图上
map.addLayer(vectorLayer);
```
在HTML中还需要添加一个Popup的容器,如下所示:
```html
<div id="map"></div>
<div id="popup" class="ol-popup">
<a href="#" id="popup-closer" class="ol-popup-closer"></a>
<div id="popup-content"></div>
</div>
```
这样就可以在地图上点击位置后弹出提示框了,提示框会显示点击位置的坐标。
阅读全文
相关推荐

















