1

I have several sources and layers generated on my map through looping as can be seen on the source code.

var id, lat, lng, point;

function setPosition() {
    $.post('m/getData.php', function(data) {
        var split = data.split(",");
        for (i = 0; i < split.length - 1; i++) {
            var secSplit = split[i].split("|");
            id = secSplit[0];
            lat = secSplit[1];
            lng = secSplit[2];
            point = {
                "type": "Point",
                "coordinates": [lng, lat]
            };
            map.addSource(id, {
                type: 'geojson',
                data: point
            });
            map.addLayer({
                "id": id,
                "type": "symbol",
                "source": id,
                "layout": {
                    "icon-image": "ferry-15"
                }
            });
        }
    });
}

For my question, is it possible to dynamically bind popup to every sources and layers using Mapbox GL JS?

From what I have seen on Mapbox example, it shows only how to bind popup with feature collection from a single layer as you can see here

1 Answer 1

3

In Mapbox-GL-JS, you don't really "bind popups". As the linked example shows, you respond to a mouse click, query rendered features where the mouse was clicked, and then display a popup if required.

Can you query multiple layers? Yes, as the documentation points out:

An array of style layer IDs for the query to inspect. Only features within these layers will be returned. If this parameter is undefined, all layers will be checked.

So an easy approach would be to maintain a variable of all the IDs of the layers you add, then pass that to queryRenderedFeatures().

It's also possible to get a list of all layer IDs by querying map.getStyle().layers.

Sign up to request clarification or add additional context in comments.

2 Comments

i forgot to say thanks. thank you, you solved my problem
Is it possible that you publish an example? I am stuck with this and an example will be great. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.