0

In Mapbox, I can successfully swap marker images when clicking on a marker. However, I can't get it to change back when clicking an empty space on the map. This causes the pop-up to close, but the marker to remain in the active state.

I used the advice from the following question to change the image on click.

How to change the icon-image on click

My code:

map.on('click', 'points', (e) => {

    const coordinates = e.features[0].geometry.coordinates.slice();
    const markup = e.features[0].properties.markup;

    while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
        coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
    }

    new mapboxgl.Popup()
        .setLngLat(coordinates)
        .setHTML(markup)
        .addTo(map);

    // change the image from markerImage to markerImageActive on click

    map.setLayoutProperty('points', 'icon-image',
        [
            'match',
            ['id'],
            e.features[0].id, 'markerImageActive',
            'markerImage'
        ]
    )

});

It successfully changes back when I click on a different marker, but not an empty space.

1 Answer 1

0

In the end I solved this with an answer from a different question

https://stackoverflow.com/a/54413030/1737337

map.on('click', 'points', function(e) {
    e.preventDefault(); // put this inside my existing code for clicks on the "points" layer
    // [...]
});

map.on('click', function(e) {
    if (e.defaultPrevented === false) {
        map.setLayoutProperty('points', 'icon-image', 'markerImage'); // reset all markers default hasn't been prevented (meaning I haven't clicked the points layer)
    }
});

Credit to stdob-- for this!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.