先总结:用到的核心知识
添加图标,首先要创建一个图层,然后把图层添加到地图上
vecSource = new ol.source.Vector({
features: []
});
vecLayer = new ol.layer.Vector({
renderMode: 'image',
source: vecSource,
style: function(feat) {
return styleFunction(feat, map);
},
zIndex: 10
});
map.addLayer(vecLayer);
styleFunction对图标进行一些样式处理
function styleFunction(feat, map) {
const zoom = map.getView().getZoom();
let scale = zoom / 5;
if (scale > 1.2) scale = 1.2;
let icon = '';
let zIndex = 1;
icon = './static/img/ship-default.svg';
let styles = [];
// 告警船是系统船时不显示
styles.push(
new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5], // 锚点 默认值是图标中心
src: icon, // 图片路径
scale: scale,
rotation: (Math.PI / 180) * 20
}),
zIndex: zIndex
})
);
return styles;
}
获取数据后,拿到经纬度,然后在地图上添加这些图标点,可以给点添加一些feature,方便后续操作图标的时候获取当前图标的信息。feature就是styleFunction函数中拿到的feat
function addWarnMapFeatures() {
let features = [];
let coords = [];
for (let i = 0; i < shipList.length; i++) {
const r = shipList[i];
shipList[i].flag = 'LS';
let lonlat = [r.lon, r.lat];
let coord = ol.proj.transform(lonlat, 'EPSG:4326', 'EPSG:3857');
features.push(
new ol.Feature({
geometry: new ol.geom.Point(coord),
rotation: r.sog,
mmsi: r.mmsi,
name: r.name,
shipInfo: r
})
);
coords.push(coord);
}
vecSource.addFeatures(features);
// 目的是定位到船舶所在的位置
if (coords.length > 0) {
const pts = new ol.geom.MultiPoint(coords);
// 获取几何体的范围 pts.getExtent()
map.getView().fit(pts.getExtent());
// map.getView().setZoom(11);
}
}
下面这两行代码是定位到当前经纬度集合的位置附近
const pts = new ol.geom.MultiPoint(coords);
// 获取几何体的范围 pts.getExtent()
map.getView().fit(pts.getExtent());
清除图层
vecSource.clear()