1 版本
2 配置ol-ext
// 1、安装ol-ext
npm i ol-ext
// 2、在main.js中引入样式
import 'ol-ext/dist/ol-ext.min.css';
3 使用Legend控件
3.1 说明
- ol.control.Legend:Create a legend for styles.
- ol.legend.Legend:Legend class to draw features in a legend element.
- ol.legend.Item:A class for legend items.
以下内容摘自官方案例:
The ol/control/Legend computes a legend based on ol/style/Style and draw it on the map.
- You can add or remove rows in the legend.
- The control use a style or a feature with a style or a style functions to handle styles based on feature properties.
- A select event is fired when click on the rows in the legend control.
- You can use the ol.legend.Legend.getLegendImage() function to retrieve an image of a single style or feature.
3.2 基本使用
import OlExtLegend from 'ol-ext/legend/Legend'
import OlExtLegendControl from 'ol-ext/control/Legend'
const initLegend = () => {
this_.mLegend = new OlExtLegend({
title: '图例',
margin: 5
});
this_.mLegend.addItem({
title: "气象站", // 图例的名称
typeGeom: 'Point', // 图例的要素类型
style: qxzSelectStyle() // 返回Style类的样式对象
});
this_.mLegend.addItem({
title: "500kV变电站",
typeGeom: 'Point',
style: bdzStyle()
});
const legendCtrl = new OlExtLegendControl({
legend: this_.mLegend,
collapsed: false
});
this_.mMap.addControl(legendCtrl);
}
3.3 添加/删除图层时相应的增减图例
当执行map.addLayer/map.removeLayer函数后,同时进行相应的图例增减
// 当前方法没有考虑到所有可能的图层类型,仅供参考
const changeLegendItem = (title, layer) => {
if (layer) {
if (layer instanceof TileLayer) {
const source = layer.getSource();
if (source instanceof TileWMSSource) {
const img = source.getLegendUrl(); // 获取WMS图层的图例
this_.mLegend.addItem({
title: title,
typeGeom: 'Point',
style: getIconStyle(img)
});
}
} else if (layer instanceof VectorLayer) {
this_.mLegend.addItem({
title: title,
typeGeom: 'Point',
style: layer.getStyle()
});
}
} else {
// 用于移除ol-ext的图例
let ele = null;
this_.mLegend._items.forEach(e => {
if (title === e.values_.title) ele = e;
});
ele && this_.mLegend._items.remove(ele);
}
}