简体   繁体   中英

Need to clone layer in OL3

How can I clone a layer in OL3 ?

For the moment I try this but it's giving me a different object with different aspect of a real ol.layer. Like you can see with inside console log I lost the instance of the layer and it's important for me to keep it.

 <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://openlayers.org/en/v3.20.1/css/ol.css" type="text/css"> <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x --> <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://openlayers.org/en/v3.20.1/build/ol.js"></script> </head> <body> <div id="map" class="map" tabindex="0"></div> <script> var map = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], target: 'map', view: new ol.View({ center: [0, 0], zoom: 2 }) }); console.log("map layer is an instanceof ol.layer.tile? ", map.getLayers().getArray()[0] instanceof ol.layer.Tile) function cloneLayer() { map.getLayers().getArray().forEach(function(layer) { var copyLayer = jQuery.extend(true, {}, layer); console.log("CopyLayer is an instanceof ol.layer.tile? ", copyLayer instanceof ol.layer.Tile) console.log("CopyLayer is equal to mapLayer? ", map.getLayers().getArray()[0] == copyLayer) }); } cloneLayer() </script> </body> </html> 

I'm trying to find a situation that you will need clone a layer and i don't find it.

Many other classes in ol3 has their method clone to do it. Clonning a layer involve copy your source, that has features and many many many other objects.

The jQuery.extend work's fine for DOM elements, it was made to DOM objects, see docs , for complex objects that are instances of custom classes, prototyped classes, like all ol classes are made off, clone an object is much more complex than iterate its properties and copy each one.

So, i suggest that you create a new layer and just copy their options, if you need another layer with same characteristics.

Or, if you could explain the situation that you need to clone a layer, maybe we can have an alternative solution.

I am not familliar with OL3 but maybe you could try to use your original object as the prototype of the new one with

var copyLayer = Object.create(layer.prototype)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM