Azure Maps - How to Get the Layer from a Shape in a Map Event

Ken Bowman 171 Reputation points
2024-08-16T18:13:31.4733333+00:00

Hi,

What is the best way to get a shape's layer in a Map event? For example, looping through the shapes in a Map click event, how can I determine what layer each shape is part of?

Thanks,

Ken

Azure Maps
Azure Maps
An Azure service that provides geospatial APIs to add maps, spatial analytics, and mobility solutions to apps.
700 questions
0 comments No comments
{count} votes

Accepted answer
  1. rbrundritt 17,491 Reputation points Microsoft Employee
    2024-08-21T15:31:46.3166667+00:00

    Currently the layer information is not available within the shape that is returned in the event. Note that a single shape can be rendered in multiple layers in an app. However, you can get the data source of the shape. This is undocumented, but the shape has a "dataSource" property that is a reference to the source. A shape can only ever be in one data source.

    That said, if you are willing to venture into deeper, lower level, undocumented capabilities within the core map control, it is possible to get the id of the rendered layers the shapes/features are in under the mouse. The Azure Maps control wraps MapLibre, and you can access the MapLibre map instance using the _getMap() function that's on the Azure Maps control. From there you can use the queryRenderedFeatures function to get the raw feature information under any pixel on the map, and this includes the layer information. For example:

    map.events.add('click', (e) => {
        var features = map._getMap().queryRenderedFeatures(e.pixel);
        features.forEach(f => {
            //Get the layer id of the clicked feature.
            console.log(f.layer.id);
        });
    });
    

    Now the above will also include all layers in the map as well (like roads and land areas). You can create an array of all the layer ID's of your layers, and pass that in as a filter. For example:

    var layerIds = [];
    
    //Add your id's to the array. Using undocumented feature that gets all user added layers from the map.
    map.layers.userLayers.forEach(l => {
        layerIds.push(l.layer.id)
    });
    
    map.events.add('click', (e) => {
        var features = map._getMap().queryRenderedFeatures(e.pixel, { layers: layerIds });
        features.forEach(f => {
            //Get the layer id of the clicked feature.
            console.log(f.layer.id);
        });
    });
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.