Show and hide features of a layer in Mapbox GL JS
Asked Answered
N

1

11

I have found the following code to show and hide layers in Mapbox GL:

https://www.mapbox.com/mapbox-gl-js/example/toggle-layers/

This is helpful, however, I only have one .geojson layer (polylines) with all of the necessary data and do not need to create separate layers.

I would like to make the exact same function of being able to show and hide features of one layer in the map menu. There are a total of 12 different feature types, contained in the column named "Type". I would like to toggle types on and off, just like in the example.

Is there an easy way to do this in JS with the set.Filter? https://github.com/mapbox/mapbox-gl-js/blob/e9386d2880cc2c33e9a5a16b9bcb58834026a078/js/ui/map.js#L559-L562

I have been unable to come up with a solution.

My .geojson layer is here: https://iskandarblue.github.io/mapbox/data/simplify_prototype.geojson

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.15.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.15.0/mapbox-gl.css' rel='stylesheet' />
    <style>
        body { margin:0; padding:0; }
        #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
</head>
<body>

<style>
    #menu {
        background: #fff;
        position: absolute;
        z-index: 1;
        top: 10px;
        right: 10px;
        border-radius: 3px;
        width: 120px;
        border: 1px solid rgba(0,0,0,0.4);
        font-family: 'Open Sans', sans-serif;
    }

    #menu a {
        font-size: 13px;
        color: #404040;
        display: block;
        margin: 0;
        padding: 0;
        padding: 10px;
        text-decoration: none;
        border-bottom: 1px solid rgba(0,0,0,0.25);
        text-align: center;
    }

    #menu a:last-child {
        border: none;
    }

    #menu a:hover {
        background-color: #f8f8f8;
        color: #404040;
    }

    #menu a.active {
        background-color: #3887be;
        color: #ffffff;
    }

    #menu a.active:hover {
        background: #3074a4;
    }
</style>

<nav id="menu"></nav>
<div id="map"></div>

<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiaXNrYW5kYXJibHVlIiwiYSI6ImNpazE3MTJldjAzYzZ1Nm0wdXZnMGU2MGMifQ.i3E1_b9QXJS8xXuPy3OTcg';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v8',
    zoom: 15,
    center: [-71.97722138410576, -13.517379300798098]
});

map.on('style.load', function () {
    map.addSource('museums', {
        type: 'vector',
        url: 'mapbox://mapbox.2opop9hr'
    });
    map.addLayer({
        'id': 'museums',
        'type': 'circle',
        'source': 'museums',
        'paint': {
            'circle-radius': 8,
            'circle-color': 'rgba(55,148,179,1)'
        },
        'source-layer': 'museum-cusco'
    });

    map.addSource('contours', {
        type: 'vector',
        url: 'mapbox://mapbox.mapbox-terrain-v2'
    });
    map.addLayer({
        'id': 'contours',
        'type': 'line',
        'source': 'contours',
        'source-layer': 'contour',
        'layout': {
            'line-join': 'round',
            'line-cap': 'round'
        },
        'paint': {
            'line-color': '#877b59',
            'line-width': 1
        }
    });
});

addLayer('Contours', 'contours');
addLayer('Museums', 'museums');

function addLayer(name, id) {
    var link = document.createElement('a');
    link.href = '#';
    link.className = 'active';
    link.textContent = name;

    link.onclick = function (e) {
        e.preventDefault();
        e.stopPropagation();

        var visibility = map.getLayoutProperty(id, 'visibility');

        if (visibility === 'visible') {
            map.setLayoutProperty(id, 'visibility', 'none');
            this.className = '';
        } else {
            this.className = 'active';
            map.setLayoutProperty(id, 'visibility', 'visible');
        }
    };

    var layers = document.getElementById('menu');
    layers.appendChild(link);
}

</script>

</body>
</html>
Nottingham answered 18/3, 2016 at 16:20 Comment(1)
Have you seen mapbox.com/mapbox-gl-js/example/filter-markers? This example demonstrates that behaviour (hiding showing features via a filter).Ami
E
14

I was trying to do the same thing and ended up using combo filters. Similar to you, I have a map with a geoJSON source:

map.addSource( 'routes', {
    'type': 'geojson',
    'data': geoJSON
});

On that map, I have a layer with all my routes:

map.addLayer({
    'id': 'route-no-hover',
    'type': 'line',
    'source': 'routes',
    'layout': {
        'line-join': 'round',
        'line-cap': 'round'
    },
    'paint': {
        'line-color': '#333',
        'line-opacity': 0.25,
        'line-width': 4
    }
});

I'm listing all my routes and providing the user with the availability to toggle them on and off. It sounds like my concept of "routes" is equivalent to your "types". When a user clicks a route name to turn it off, I push that route's ID into an array called 'hidden' then create a series of filters based on those IDs:

 let hiddenFilters = ['all'];
_.forEach( mapMeta.hidden, ( route ) => {
    hiddenFilters.push([
        '!=',
        'id',
        route.toString()
    ]);
});
map.setFilter( 'route-no-hover', hiddenFilters );

Note that I'm using lodash but you could just use Array.forEach()

I'm effectively creating a filter that looks like this combining filter described in the filtering docs:

[
  "all",
  ["!=", "id", "routeIDHere"],
  ["!=", "id", "routeIDHere"],
  ...
]

This excludes all the routes with the IDs I specify. In your case, I think you'd want to have something like

[
  "all",
  ["!=", "type" "YourTypeNameHere"]
  ...
]
Epochmaking answered 15/8, 2016 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.