// 添加点 val点的数据 点的事件类型envType:pointermove移入singleclick点击
var addPoint = function(val, envType , src ,track) {
const that = this;
var overlay = '';
var key = null;
var Point = new ol.geom.Point(bd09togcj02([val.lng, val.lat]));
Point.applyTransform(ol.proj.getTransform('EPSG:4326', 'EPSG:3857'));
var featurePoint = new ol.Feature(Point);
featurePoint.setStyle(new ol.style.Style({
image: new ol.style.Icon({
//设置图标偏移
anchor: [0.5, 5],
//标注样式的起点位置
anchorOrigin: 'top',
//X方向单位:分数
anchorXUnits: 'fraction',
//Y方向单位:像素
anchorYUnits: 'pixels',
//偏移起点位置的方向
offsetOrigin: 'top',
//透明度
opacity: 0.9,
//图片路径
//src: 'images/map.png'
src: src ? src : 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
}),
}))
featurePoint.set("value",val);
var vectorSource = new ol.source.Vector();
vectorSource.addFeature(featurePoint);
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
/*图形绘制好时最终呈现的样式,显示在地图上的最终图形*/
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'blue'
}),
stroke: new ol.style.Stroke({
color: color ? color : 'red',
width: 4
}),
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: 'red'
})
})
})
});
this.map.addLayer(vectorLayer);
if (!envType) {
return;
}
// pointermove移入singleclick点击
ol.Observable.unByKey(this.key); // 移除绑定事件
key = that.map.on(envType, function (e) {
if (e.dragging) { // 拖动地图不执行
return;
}
if (overlay) {
that.map.getOverlays().clear();
}
if (that.map.hasFeatureAtPixel(e.pixel)) {
var container = document.createElement("div");
container.id = 'popup';
var content = document.createElement("div");
content.id = 'popup-content';
container.appendChild(content);
overlay = new ol.Overlay({
//设置弹出框的容器
element: container,
//是否自动平移,即假如标记在屏幕边缘,弹出时自动平移地图使弹出框完全可见
autoPan: true,
positioning: 'bottom-center', // 覆盖层位置
offset: [0, -30], // 覆盖层偏移起点的位置
});
var feature = that.map.getFeaturesAtPixel(e.pixel)
var data = feature[0].values_.value;
if (!data) { // 只有移入点才执行下面
return;
}
var pixel = that.map.getEventPixel(e.originalEvent);
that.map.forEachFeatureAtPixel(pixel, function (feature) {
var html = "<table class='mytable' border='0' cellspacing='0' cellpadding='3' style='background-color:rgba(0, 0, 0, 0.5);color: white;'>"
+ "<tr><td>定位点信息"
+ "<tr><td>当前速度:" + data.gpsSpeed + "m/s"
// + "<tr><td>设备状态:" + isOnline
+ "</td></tr><tr><td>经度:" + data.lng
+ "</td></tr><tr><td>纬度:" + data.lat
+ "</td></tr></table>"
//coodinate存放了点击时的坐标信息
var coodinate = e.coordinate;
//设置弹出框内容,可以HTML自定义
content.innerHTML = track ? html :
"<p class='deviceModel'>设备型号:" + data.deviceModel + "</p>"
//设置overlay的显示位置
overlay.setPosition(ol.proj.transform(bd09togcj02([Number(data.lng),Number(data.lat)]), 'EPSG:4326', 'EPSG:3857'));
//显示overlay
that.map.addOverlay(overlay);
});
}
}.bind(this))
}
循环调addPoint 函数添加点,并且绑定事件,点击时添加一个框显示自己要显示的内容,点多了会比较卡,因为给地图绑定了很多次事件,执行一次就会成千上万次所以会卡,只要每次进来清一下事件,绑定一次就好了,
key = map.on('click', function (e) { ... }.bind(this));
//移除click
ol.Observable.unByKey(key);