我用的版本是"openlayers" : "^4.6.5" ,首先在Feature设置ID,便于获取这个标记点的信息 iconFeature.set("Id",item.id)
代码语言:javascript复制 if(this.PointsLayer.length){
console.log("you")
this.PointsLayer.forEach(item=>{
this.OLMap.removeLayer(item)
})
}
// let iconFeatures=[] // 保存所有的点Feature
this.allOnlinePersonInfo.forEach(item=>{
// console.log(item)
let PointsLayer = new ol.layer.Vector({
source: new ol.source.Vector(),
});
let iconFeature = new ol.Feature({
geometry: new ol.geom.Point( //绘制图形(点)
item.position,
)
});
iconFeature.setStyle(
new ol.style.Style({
image: new ol.style.Icon({
// scale:0.5,
//控制标注图片和文字之间的距离
// anchor: [0.2, 1],
//标注样式的起点位置
anchorOrigin: 'top-right',
//X方向单位:分数
anchorXUnits: 'fraction',
//Y方向单位:像素
anchorYUnits: 'pixels',
//偏移起点位置的方向
offsetOrigin: 'top-right',
//透明度
opacity: 1,
//图片路径
src:require("@/assets/imgs/xujianPerson.png")
}),
//文本样式
text: new ol.style.Text({
textAlign: "center", //对齐方式
textBaseline: "middle", //文本基线
font: "normal 12px 微软雅黑", //字体样式
text: item.label, //文本内容
offsetY: 20, // Y轴偏置
offsetX:40,
fill: new ol.style.Fill({
//填充样式
color: "#333",
}),
backgroundStroke:new ol.style.Stroke({color: '#ffcc33', width:1}),
backgroundFill: new ol.style.Fill({
// 填充背景
color: "#FFF",
}),
padding: [2, 5, 2, 5],
}),
},
)
);
// iconFeature.setId(item.id); // 这种设置无效
iconFeature.set("Id",item.id)
PointsLayer.getSource().addFeature(iconFeature)
this.OLMap.addLayer(PointsLayer)
this.PointsLayer.push(PointsLayer)
console.log(this.PointsLayer)
})
点击的时候获取ID
代码语言:javascript复制 this.OLMap = new ol.Map({
view: new ol.View({
projection: "EPSG:4326", // 经纬度
center: center,
zoom: zoom || 8,
minZoom: 6,
maxZoom: 18,
}),
target: "OLMap",
layers: [tileLayer],
});
this.getSitePointInfoList();
this.showPersonMarker()
this.OLMap.on("singleclick", (evt) => {
console.log("hi");
let arr = [];
let id = "";
var pixel = this.OLMap.getEventPixel(evt.originalEvent);
var feature = this.OLMap.forEachFeatureAtPixel(
evt.pixel,
function (feature, layer) {
id = feature.get("Id");
arr.push(id);
}
);
id = arr[0];
this.olMarkerClick(id);