Filtering Arrays in MapLibre
Techniques for Substring Matching in MapLibre GL JS and Mapbox GL JS
When filtering data in MapLibre GL JS, you will often have data stored as an array, such as a tags field. If this field is stored as a true JSON array (and this array persists into the rendered vector tiles), you can use the built-in expression syntax for exact matches inside an array. For example, if each feature has an array such as: "tags": ["grid-1", "historic-district"], you can create an expression to show just those features whose tags array include grid-1.
|
In the map below the grids are filtered using the method above, with the first grid cell (bottom-left) tagged as ["grid-1", "historic-district"] and the next as ["grid-2", "historic-district"], etc.
This approach is clean and structured, however it only supports exact matches. For example: grid won’t match grid-1. If your use case requires prefix or substring matching, you will need an alternative method. If you have access to the raw data, one solution is storing this array as a CSV-style string, such as "tags_csv": "grid-1,historic-district". This allows substring filtering using ["index-of"]:
|
In the map below, the same grid data is used but the tags are stored as a CSV string. The filter highlights all features tagged with district (the whole grid) using the substring match method. The drawback to this method is that you cannot do exact matches without risk of false positives (e.g., searching for grid-1 will also return grid-10, grid-11, etc.).
One issue to understand is that when storing data as a JSON array, vector tile generation tools (like tippecanoe) will encode these as JSON-encoded strings. In this case the only option is to use the substring matching method. However, when filtering on grid-2, you get all features that contain that substring, including grid-20, grid-21, etc. This can be mitigated by including quotes in the search string.
|