簡體   English   中英

Mapbox GL JS單擊更改建築顏色

[英]Mapbox GL JS change builidng color on click

我必須在單擊時更改建築物的顏色或邊框。

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');
    });
});

謝謝 :)

您需要添加一個圖層,以在其上顯示所選建築物。 例如:

  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/ ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM