Reputation: 3588
Does OpenLayers library come with a way to assign/get a unique identifier for layers added to a map, or should I have to implement it myself?
This question arises from my need to uniquely identify various type of layers I add to my map (LayerGroup and TileLayer mostly), and to give the same reference id to each layer I create in parallel in a table-of-content-like DIV (like the ol-layerswitcher). This way I would be able to uniquely identfy my layer/group of layer in the map and its DOM context (where I can control e.g. its visibility, zoom, etc.).
I thought something similar would exist as it seems rather essential, but I cannot seem to find it in the docs not in the API.
This question is related to this other question of mine, where I essentially assume that an in-built method for assigning/retrieving ids for layers does not exist, and I am trying to figure out how to extend OpenLayers classes and methods to implement and get these properties whenever and wherever I need.
Upvotes: 6
Views: 3616
Reputation: 3588
Thanks to @Mike for helping me finding a solution.
The answer was to use ol/util.getUid
.
Calling getUid
method and passing a layer to it, automatically assign a unique id to the layer which can be stored in a variable to use it somewhere else in an application.
Simple example:
import { getUid } from 'ol/util';
import TileLayer from 'ol/layer/Tile';
// create a new layer
var myLayer = new TileLayer();
var myLayerId = getUid(myLayer);
console.log(myLayerId) // logs the unique id of the layer
Upvotes: 10