OpenLayers 3 之 切換圖層控件
openlayers 3中並沒有默認的圖層切換控件,GitHub中有一個項目實現了我們需要的控件-------- ol3-layerswitcher 。
可全局引入,模塊化引入須注意,必須把ol聲明成全局變量。否則引入ol3-layerswitcher時報錯:ol is not defined;
因為webpack在模塊化引入時每個文件的作用域是封閉的,導致加載ol3-layerswitcher時引用不到openlayers模塊中的ol。
首先npm install加載 ol3-layerswitcher;
npm install ol3-layerswitcher
模塊化引入方法:
import ol from 'openlayers'; import 'ol3-layerswitcher/src/ol3-layerswitcher';
把ol聲明成全局變量:
module.exports = { resolve: { root: [], alias: { openlayers: path.resolve(__dirname, '../node_modules/openlayers/dist/ol.js') } }, plugins: [ new webpack.ProvidePlugin({ ol: 'openlayers' }) ] };
使用方法:
1.在每個圖層添加一個 title
屬性;
var tian_di_tu_road_layer = new ol.layer.Tile({ title: "天地圖路網", source: new ol.source.XYZ({ url: "http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}" }) });
注:默認關閉是需在title之后增加:
visible: false,
2.tipLabel 屬性
layer-switcher 相對於 ol.control.Control
基類,只添加了一個屬性 – tipLabel
,這個屬性是一個字符串,默認是 Legend
,當鼠標位於控件之上時,會有提示文字,就是這里的 tipLabel
的值,其實這個值是通過設置 html button元素的title 屬性實現的。
參考自:https://blog.csdn.net/qingyafan/article/details/50043221