使用Angular4和openlayers实现点击feature弹出气泡显示要素属性
在Angular4中使用openlayers,可以通过以下步骤实现点击feature弹出气泡显示要素属性:
- 安装openlayers和@types/ol
在Angular4项目中,可以通过npm安装openlayers和@types/ol:
npm install ol @types/ol --save
- 在组件中引入openlayers
在组件ts文件中,可以通过以下方式引入openlayers:
import * as ol from 'ol';
- 创建地图
在组件中,可以创建地图:
ngOnInit() {
const source = new ol.source.OSM();
const layer = new ol.layer.Tile({
source: source
});
const view = new ol.View({
center: ol.proj.fromLonLat([2.1833, 41.3833]),
zoom: 15
});
const map = new ol.Map({
target: 'map',
layers: [layer],
view: view
});
}
这段代码创建了一个以经纬度为[2.1833, 41.3833]为中心,缩放等级为15的地图,并且使用OpenStreetMap作为底图。
- 添加要素并设置点击事件
在地图上添加要素,并设置点击事件:
const feature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([2.1833, 41.3833])),
name: 'Barcelona'
});
const vectorSource = new ol.source.Vector({
features: [feature]
});
const vectorLayer = new ol.layer.Vector({
source: vectorSource
});
map.addLayer(vectorLayer);
const popup = new ol.Overlay({
element: document.getElementById('popup')
});
map.addOverlay(popup);
map.on('click', function(event) {
map.forEachFeatureAtPixel(event.pixel, function(feature) {
const geometry = feature.getGeometry();
const coord = geometry.getCoordinates();
const name = feature.get('name');
popup.setPosition(coord);
const content = document.getElementById('popup-content');
content.innerHTML = name;
});
});
这段代码创建了一个名为"Barcelona"的点要素,并将其添加到地图上。在地图上单击要素时,将弹出一个气泡,显示要素的名称。
- 创建气泡的HTML代码
在组件的HTML文件中,需要创建气泡的HTML代码:
<div id="popup" class="ol-popup">
<a href="#" id="popup-closer" class="ol-popup-closer"></a>
<div id="popup-content"></div>
</div>
- 添加CSS样式
在组件的CSS文件中,需要添加气泡的CSS样式:
.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: 160px;
}
.ol-popup:after {
content: "";
position: absolute;
top: -10px;
left: 50%;
margin-left: -10px;
border-width: 10px;
border-style: solid;
border-color: transparent transparent white transparent;
}
.ol-popup-closer {
position: absolute;
top: 2px;
right: 8px;
font-size: 12px;
font-weight: bold;
text-decoration: none;
color: #c3c3c3;
}
.ol-popup-closer:hover {
color: #e3e3e3;
}
这些样式将创建一个圆角矩形的气泡,并在气泡上方添加一个三角形。
- 运行应用程序
运行Angular4应用程序,可以看到地图和要素。单击要素时,将弹出一个气泡,显示要素的名称。
原文地址: https://www.cveoy.top/t/topic/bJdd 著作权归作者所有。请勿转载和采集!