Switch layer controls in OpenLayers 3
There is no default layer switching control in openlayers 3. There is a project in GitHub that implements the control we need -------- ol3-layerswitcher 。
It can be imported globally, and it should be noted that for modular introduction, ol must be declared as a global variable. Otherwise, an error is reported when ol3-layerswitcher is introduced: ol is not defined;
Because the scope of each file is closed when webpack is introduced modularly, the ol in the openlayers module cannot be referenced when ol3-layerswitcher is loaded.
First npm install loads ol3-layerswitcher ;
npm install ol3-layerswitcher
Modular introduction method:
import ol from 'openlayers'; import 'ol3-layerswitcher/src/ol3-layerswitcher';
Declare ol as a global variable:
module.exports = { resolve: { root: [], alias: { openlayers: path.resolve(__dirname, '../node_modules/openlayers/dist/ol.js') } }, plugins: [ new webpack.ProvidePlugin({ ol: 'openlayers' }) ] };
Instructions:
1. Add an title
attribute to each layer;
var tian_di_tu_road_layer = new ol.layer.Tile({ title: "Tian Tu Road Network", source: new ol.source.XYZ({ url: "http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}" }) });
Note: The default closing is to add after the title:
visible: false,
2. tipLabel property
Compared with the base class, layer-switcher ol.control.Control
only adds one attribute - tipLabel
, this attribute is a string, the default is Legend
that when the mouse is over the control, there will be a prompt text, which is tipLabel
the value here, in fact, this value is set by setting Implemented by the title attribute of the html button element.
Reference from: https://blog.csdn.net/qingyafan/article/details/50043221