往地图中添加删除层(layer)和元素(feature)
let vectorSource = new ol.source.Vector({
features: [],
});
let vectorLayer = new ol.layer.Vector({
style: null,
source: vectorSource,
});
map.addLayer(vectorLayer);
this.vectorLayer = vectorLayer;
function clearAllMarker(){
vectorSource.clear();
}
function addOneMarker(marker={}) {
if (marker.coordinate) {
let lonAndLat = item.coordinate.split(',');
let newFeature = new ol.Feature({
geometry: new ol.geom.Point(lonAndLat),
name: marker.name || '',
});
newFeature.set('key','value');
newFeature.setStyle(customStyle(marker.type));
markerSource.addFeature(newFeature);
}
}
function addMarkers(markers=[]){
let features = markers.map(item => {
if(item.coordinate){
let lonAndLat = item.coordinate.split(',');
let feature = new ol.Feature({
geometry: new ol.geom.Point(lonAndLat),
name: item.featureName || '',
});
feature.setStyle(customStyle(item.type));
feature.set('key','value');
return feature;
}
});
markerSource.addFeatures(features);
}
创建ol自定义Style(简单封装一下)
function customStyle(type, params = {}) {
return new ol.style.Style({
image: getImageStyle(params),
text: getTextStyle(params),
});
function getImageStyle(params = {}) {
switch (type.toLowerCase()) {
case 'circle':
let circle = params.circle || {};
return new ol.style.Circle({
radius: circle.radius || 10,
stroke: new ol.style.Stroke({
color: circle.strokeColor || '#DC143C'
}),
fill: new ol.style.Fill({
color: circle.fillColor || '#3399CC'
})
})
case 'icon':
let icon = params.icon || {};
return new ol.style.Icon({
src: icon.url || '../pub/img/blueIcon.png',
offset: icon.offset || [0, 0],
scale: icon.scale || 1,
opacity: icon.opacity || 1,
});
default:
return null;
}
}
function getTextStyle(params = {}) {
let text = params.text || {};
return new ol.style.Text({
text: text.content || '',
font: text.font || 'normal 14px 微软雅黑',
fill: new ol.style.Fill({
color: text.fillColor || '#333'
}),
stroke: new ol.style.Stroke({
color: text.strokeColor || '#ffcc33',
width: text.strokeWidth || 2,
}),
textAlign: text.textAlign || 'center',
textBaseline: text.textBaseline || 'middle',
offsetX: text.offset ? markerText.offset[0] : 0,
offsetY: text.offset ? markerText.offset[1] : 0,
})
}
}