有没有办法为mapbox中同一图层上的每个要素在悬停时提供不同的光标样式?

问题描述 投票:0回答:1

我希望更改悬停时的光标样式,该样式将取决于同一层上渲染的每个要素的某些属性值。现在发生的情况是同一层内所有要素的光标样式都发生了变化。我想控制这个。

mapbox mapbox-gl
1个回答
0
投票

是的,这是可行的。为此,您需要查询鼠标指针下的特征,然后决定使用什么属性来仅过滤某些特征以区分行为。

我为您起草了一份关于如何更改鼠标悬停时的颜色和指针的小提琴,其中我为纽约市所有建筑物中的一个功能 ID 添加了一个过滤器,该过滤器将变为红色,更改其状态(“悬停”) ; true') 并且鼠标指针变为

map.getCanvasContainer().style.cursor = 'pointer'
.

这是相关代码:

    let mapConfig = {
      NYC: {
        origin: [-74.044514, 40.689259, 39],
        center: [-74.0137, 40.70346, 0],
        zoom: 16.2,
        pitch: 60,
        bearing: 35
      }
    }

    mapboxgl.accessToken = 'PUT HERE YOUR TOKEN';
    let point = mapConfig.NYC;
    var map = new mapboxgl.Map({
      style: 'mapbox://styles/mapbox/streets-v11',
      center: point.center,
      zoom: point.zoom,
      pitch: point.pitch,
      bearing: point.bearing,
      container: 'map',
      antialias: true,
      hash: true
    });

    map.on('style.load', function() {

      if (map.getSource('composite')) {
        map.addLayer({
          'id': '3d-buildings',
          'source': 'composite',
          'source-layer': 'building',
          'type': 'fill-extrusion',
          'minzoom': 14,
          'paint': {
            'fill-extrusion-color': [
              'case',
              ['boolean', ['feature-state', 'hover'], false],
              '#ff0000',
              '#ddd'
            ],
            'fill-extrusion-height': ["number", ["get", "height"], 5],
            'fill-extrusion-base': ["number", ["get", "min_height"], 0],
            'fill-extrusion-opacity': 1
          }
        }, 'road-label');
      }

      let fHover;

      map.on('click', function(e) {
        var features = map.queryRenderedFeatures(e.point, {
          layers: ['3d-buildings']
        });
        console.log(features[0].id);
      })

      map.on('mousemove', function(e) {
        var features = map.queryRenderedFeatures(e.point, {
          layers: ['3d-buildings']
        });
        //we will change pointer and color for 42455719
        if (features[0] && features[0].id == 42455719) {
          mouseover(features[0]);
        } else {
          mouseout();
        }

      });

      map.on('mouseout', function(e) {
        mouseout();
      });

      function mouseout() {
        if (!fHover) return;
        map.getCanvasContainer().style.cursor = 'default';
        map.setFeatureState({
          source: fHover.source,
          sourceLayer: fHover.sourceLayer,
          id: fHover.id
        }, {
          hover: false
        });

      }

      function mouseover(feature) {
        fHover = feature;
        map.getCanvasContainer().style.cursor = 'pointer';

        map.setFeatureState({
          source: fHover.source,
          sourceLayer: fHover.sourceLayer,
          id: fHover.id
        }, {
          hover: true
        });
      }

    });

如果这个答案解决了您的问题,请将其标记为接受答案,这样也将帮助其他用户知道这是正确的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.