4

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.

umbe1987
  • 2,894
  • 6
  • 35
  • 63
  • 3
    All OpenLayers objects have an undocumented `ol_uid` property, e.g. `console.log(myLayer.ol_uid);` but beware that using undocumented properties is not supported and could change without notice in future releases. – Mike Aug 05 '20 at 14:53
  • 1
    @Mike Thanks. Yeah, I was reading about [`ol/util.getUid`](https://openlayers.org/en/main/apidoc/module-ol_util.html#.getUid), that is apparently getting that `ol_uid` property that you're talking about ([here](https://github.com/openlayers/openlayers/blob/main/src/ol/util.js#L30)). Because it seems to be documented, do you think I can rely on it? – umbe1987 Aug 05 '20 at 14:58
  • Yes, that is ok, I had though getUId wasn't api becuase I had tried layer,getUId() instead of getUid(layer). – Mike Aug 05 '20 at 15:33

1 Answers1

8

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
umbe1987
  • 2,894
  • 6
  • 35
  • 63