Azure-Samples / AzureMapsCodeSamples

A set of code samples for the Azure Maps web control.
https://samples.azuremaps.com
MIT License
321 stars 447 forks source link

Usage of the ['id'] data expression #123

Closed Jxlle closed 10 months ago

Jxlle commented 10 months ago

Hi,

When you use ['id'] in a layer filter expression, does the ['id'] get the id of the shapes in that layer (docs), (or does it retrieve an id from the feature that was used to create the shape)? I'm curious as to how this works because I wanted to create a hovering effect on shapes inside a layer. For this, I created an extra layer, and set its filter to only show a certain shape based on mouse movement:

map.events.add('mousemove', stockLayer, function (e) {
    polygonHoverLayer.setOptions({ filter: ['==', ['id'], e.shapes[0].getId()] });
});

map.events.add('mouseleave', stockLayer, function (e) {
    polygonHoverLayer.setOptions({ filter: ['==', ['id'], ''] });
});

This did not work, so I ended up copying the shape id to an id property and using ['get', 'id']. Am I misunderstanding the ['id'] expression?

rbrundritt commented 10 months ago

The ['id'] expression gets the ID of the feature/shape and is often used for filtering like you are doing. When you import data into the map, if your data has an ID, the map will try and maintain that ID as long as another shape doesn't already have that ID. If another shape has the same ID, a new unique ID will be assigned to the shape. So it's possible that the value of the ID is not always what you expect it to be. Generally, using a property is more consistent. In the case of hovering, I like to use the _azureMapsShapeId as this is the unique ID the map has assigned the shape stored as a property.

Jxlle commented 10 months ago

Hi @rbrundritt, thanks for the fast answer!

replacing ['id'] with ['get', '_azureMapsShapeId'] indeed works! So to understand it correctly, ['id'] does not always return the id of the shape, even if the shape was created with features without an id?

rbrundritt commented 10 months ago

Correct. The map tries to maintain the ID of a feature when importing it in, but if another shape has the same ID, or an invalid/no ID is present, a unique ID is assigned to the shape.

I also believe that there are some underlying limitations in the expression framework for the ID parameter where I believe it preferers it to be a number rather than a string. This was an issue with the original MapBox GL JS SDK before being forked into MapLibre. Note that Azure Maps creates a wrapper around MapLibre to create an easier to use developer API, add features such as additional security and accessibility that may not align with the core MapLibre architecture (thus why some of these things aren't merged back into MapLibre, but the team does actively contribute to MapLibre's core projects).

Jxlle commented 10 months ago

Clear, thanks!