Mapbox GL JS在点击时更改了建筑颜色

时间:2018-04-20 07:19:04

标签: javascript mapbox-gl-js mapbox-gl

我必须在点击时更改建筑物的颜色或边框。

HTML& JS

就像悬停国家/地区的示例一样,但是点击而不是国家/地区 - >建筑物。

如果使用其他插件更容易,请说明。 3D不是必须的'。

我的代码:

<script>
mapboxgl.accessToken = 'hidden';
var map = new mapboxgl.Map({
    style: 'mapbox://styles/mapbox/light-v9',
    center: [7.3337859, 50.8403206],
    zoom: 19.8,
    pitch: 60,
    bearing: -70,
    hash: true,
    container: 'map'
});

// The 'building' layer in the mapbox-streets vector source contains building-height
// data from OpenStreetMap.
map.on('load', function() {
    // Insert the layer beneath any symbol layer.
    var layers = map.getStyle().layers;

    var labelLayerId;
    for (var i = 0; i < layers.length; i++) {
        if (layers[i].type === 'symbol' && layers[i].layout['text-field']) {
            labelLayerId = layers[i].id;
            break;
        }
    }

    map.addLayer({
        'id': '3d-buildings',
        'source': 'composite',
        'source-layer': 'building',
        'filter': ['==', 'extrude', 'true'],
        'type': 'fill-extrusion',
        'minzoom': 15,
        'paint': {
            'fill-extrusion-color': '#aaa',

            // use an 'interpolate' expression to add a smooth transition effect to the
            // buildings as the user zooms in
            'fill-extrusion-height': [
                "interpolate", ["linear"], ["zoom"],
                15, 0,
                15.05, ["get", "height"]
            ],
            'fill-extrusion-base': [
                "interpolate", ["linear"], ["zoom"],
                15, 0,
                15.05, ["get", "min_height"]
            ],
            'fill-extrusion-opacity': .6
        }
    }, labelLayerId);

    map.on('click', '3d-buildings', function(e) {
        console.log(e.features[0]);
        //map.setPaintProperty('3d-buildings', 'fill-extrude-color', '#FF0000');
        map.setPaintProperty('3d-buildings', 'fill-color', '#faafee');
    });
});

谢谢:)

1 个答案:

答案 0 :(得分:2)

您需要添加一个图层来显示所选建筑物。例如:

  map.addSource('currentBuildings', {
    type: 'geojson',
    data: {
      "type": "FeatureCollection",
      "features": []
    }
  });
  map.addLayer({
    "id": "highlight",
    "source": "currentBuildings",
    'type': 'line',
    'minzoom': 15,
    'paint': {
        'line-color': '#f00',
      'line-width': 3
    }
  }, labelLayerId);
  map.on('click', '3d-buildings', function(e) {
    map.getSource('currentBuildings').setData({
      "type": "FeatureCollection",
      "features": e.features[0]]
    });
  });

[https://jsfiddle.net/o50vy8jc/]