项目中要求鼠标hover到要素时候,在要素位置弹窗,并在框内显示要素的信息。怎么才能具体弹窗到那个位置呢,原来ol官方有个弹窗实例,跟着new就完事了。
上效果图
map 构造完之后popup添加到map中。
// 这段代码是mounted中执行的,只要是在初始化map 之后执行就行。两个事件二选一使用。
map.on('pointermove', this.feature_Info); // 悬浮显示
map.on('singleclick', evt => this.feature_Info(evt.pixel)); // 单击显示
要素有多种,为了避免和其他的引起冲突,做了很多判断。这里只对点要素进行数据处理。
// An highlighted block
/**
* getCoordinateFromPixel => 经纬度转换px值
* getPixelFromCoordinate => px值转换经纬度
*
* @param {Array} pixel => 经纬度转换得到的px值
* @param {Array} properties => 由于地图同一个经纬度信息出现两个feature 使用像素定位会定位最后渲染的的要素,导致两个信息可能会显示不一样,便把属性传递来此
*/
feature_Info(pixel, properties) {
var feature = map.forEachFeatureAtPixel(pixel, feature => feature);
if (feature) {
if (!properties) { // 如果没传值,则表示为点击事件
if (feature.getGeometry().getType() !== 'Point') return this.popup.setPosition(undefined);
if(feature.id_ == undefined) return this.popup.setPosition(undefined);
this.featureInfo = {};
if (feature.getProperties()['装备编号']) properties = feature.getProperties();
if (feature.getProperties().features) properties = feature.getProperties().features[0].getProperties();
} // 此处是判断要素聚合的取值 没做聚合这个步骤可以忽略掉
let obj = {};
for(var v in properties) {
if (v === '装备编号') obj[v] = properties[v];
if (v === '装备名称') obj[v] = properties[v];
if (v === '型号') obj[v] = properties[v];
if (v === '规格') obj[v] = properties[v];
if (v === '装备负责人') obj[v] = properties[v];
if (v === '分类标签') obj[v] = properties[v];
if (v === '所属单位') obj[v] = properties[v];
};
this.featureInfo = obj;
this.popup.setPosition(map.getCoordinateFromPixel(pixel));
} else {
// this.popup.setPosition(undefined);
// this.featureInfo = {};
}
if (feature !== highlight) {
if (highlight) this.highlightOverlay.getSource().removeFeature(highlight);
if (feature) this.highlightOverlay.getSource().addFeature(feature);
highlight = feature;
}
}
创作不易,转载注明。