azure-maps

Azure Maps Data-driven Style Expressions using dynamic code variables


I have an Azure Maps project where I use a lot of data-driven (style) expressions to choose how I visualize my map. However, I've stumbled upon a problem that I cannot find an answer to.

Context: My map is used to render several objects. There is also a search field that can be used by the user to search for specific objects. When objects are searched, all searched objects remain visible and the other objects disappear. I wanted to implement this using one layer so I created the following filter expression:

['any', 
 ['==', 
  ['boolean', ['get', 'selectedStock', ['literal', renderOptions]]], 
  ['boolean', false]], 
 ['==', 
  ['get', 'selected'], 
  ['boolean', true]]
]

renderOptions is an object containing key-value pairs that indicate the current settings for rendering. One key-value pair is selectedStock, which indicates whether a search for objects has happened or not (boolean). This value starts as false. Each feature in my map has certain properties. The selected property indicates whether the feature is the result of the current search. This value starts as false. Upon searching for objects, a result of map features is calculated and each of these features get their selected property value switched to true, until the search is reset or a new search is executed.

A feature should only pass the filter when: No search has taken place OR (a search has taken place) and the feature is in the search result (all features that are in the result get the selected property set to true). However, it seems that the ['get', 'selectedStock', ['literal', renderOptions]] part of the expression is only evaluated at the start when creating the layer, making it always evaluate to false. It never evaluates to true, even when I use debug and see that the corresponding key-value pair is now true.

Is this intended behaviour, or am I overlooking something? Resetting the map via code also resets the filter and this seems to update the value when it has changed from its initial value.

As a side-question: Are the ['type', value] (e.g. ['boolean', true/false]) expressions needed when the value is clearly a certain type?


Solution

  • You are correct, the filter will not update as you change the values in the renderOptions. To be honest, I'm not even sure that is even working in the first place. Data driven style expressions are processed in WebGL (GPU) which doesn't have access to local variables/objects. So to get the filter to work initially, you likely will need something like this:

    ['any', 
     ['==', renderOptions.selectedStock, false], 
     ['==', ['get', 'selected'], true]
    ]
    

    When a value in the render options is update, you need to reset the filter property on the layer.

    layer.setOptions({
    filter: ['any', 
     ['==', renderOptions.selectedStock, false], 
     ['==', ['get', 'selected'], true]
    ]
    })