Mapbox GL - 突出显示功能和 queryRenderedFeatures(),同时允许底图样式更改

Mapbox GL - highlight features and queryRenderedFeatures() while allowing basemap style change

我需要能够使用 Mapbox GL 在边界框中突出显示特征,如 this example 所示。我的地图还需要能够更改样式层,例如将基本样式从 mapbox://styles/mapbox/light-v10 更改为 mapbox://styles/mapbox/satellite-v9。这一直具有挑战性,因为 Mapbox GL 本身不支持“底图”的概念,例如传单确实如此。

我的解决方案,经过大量搜索(我相信我最终遵循了 github 问题中发布的解决方法)涉及:

  1. 使用 map.on('style.load') 而不是示例中所示的 map.on('load') (我相信 map.on('style.load') 不属于他们的 public API,但我可能是错的)和,

  2. 迭代 sources/layers 数组(请参阅下面代码中的 vectorTileLayers 变量),以便在每次加载新样式时向地图添加矢量切片图层。

这在某些方面对我来说非常有效 - 我可以将任意数量的矢量切片源添加到数组中,并且如果基本样式发生更改,它们将全部添加回地图。但是,如果将 sources/layers 添加到数组中的地图并如下所示进行迭代,我将无法按照 Mapbox 提供的示例添加查询功能。边界功能有效,但是当它被绘制和释放时,我看到 运行 宁下面的代码片段显示的错误。

这是我的实际问题的简化版本,将允许其他人 运行 和操纵代码。实际上,我正在添加我自己的矢量切片图层(存储在 vectorTileLayers 数组中,这没有问题。当我尝试添加另一个具有相同源和不同样式的图层时,如示例所示,我我无法真正查询所需的图层。任何帮助将不胜感激。仅供参考 - 可切换图层按钮未显示在此代码段中,但这对解决问题并不重要。

mapboxgl.accessToken = 'pk.eyJ1IjoiamFtZXljc21pdGgiLCJhIjoiY2p4NTRzdTczMDA1dzRhbXBzdmFpZXV6eCJ9.-k7Um-xmYy4xhNDN6kDvpg';
    var map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/light-v10',
      center: [-98, 38.88],
      minZoom: 2,
      zoom: 3
    });

    var vectorTileLayers = [{
        source: {
          type: 'vector',
          url: 'mapbox://mapbox.82pkq93d'
        },
        layer: {
          id: 'counties',
          type: 'fill',
          source: 'counties',
          'source-layer': 'original',
          paint: {
            'fill-outline-color': 'rgba(0,0,0,0.1)',
            'fill-color': 'rgba(0,0,0,0.1)'
          },
        }
      },
      {
        source: {
          type: 'vector',
          url: 'mapbox://mapbox.82pkq93d'
        },
        layer: {
          id: 'counties-highlighted',
          type: 'fill',
          source: 'counties',
          'source-layer': 'original',
          paint: {
            'fill-outline-color': '#484896',
            'fill-color': '#6e599f',
            'fill-opacity': 0.75
          },
          filter: ['in', 'FIPS', '']
        }
      }
    ]

    map.on('style.load', function() {
      for (var i = 0; i < vectorTileLayers.length; i++) {
        var tileLayer = vectorTileLayers[i];
        map.addSource(tileLayer.layer.source, tileLayer.source);
        map.addLayer(tileLayer.layer);
      }

      var layerList = document.getElementById('basemapmenu');
      var inputs = layerList.getElementsByTagName('input');

      function switchLayer(layer) {
        var layerId = layer.target.id;
        map.setStyle('mapbox://styles/mapbox/' + layerId);
      }
      for (var i = 0; i < inputs.length; i++) {
        inputs[i].onclick = switchLayer;
      }

    });

    // Disable default box zooming.
    map.boxZoom.disable();

    // Create a popup, but don't add it to the map yet.
    var popup = new mapboxgl.Popup({
      closeButton: false
    });

    var canvas = map.getCanvasContainer();

    var start;
    var current;
    var box;

    canvas.addEventListener('mousedown', mouseDown, true);
    // Return the xy coordinates of the mouse position
    function mousePos(e) {
      var rect = canvas.getBoundingClientRect();
      return new mapboxgl.Point(
        e.clientX - rect.left - canvas.clientLeft,
        e.clientY - rect.top - canvas.clientTop
      );
    }

    function mouseDown(e) {
      // Continue the rest of the function if the shiftkey is pressed.
      if (!(e.shiftKey && e.button === 0)) return;

      // Disable default drag zooming when the shift key is held down.
      map.dragPan.disable();

      // Call functions for the following events
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
      document.addEventListener('keydown', onKeyDown);

      // Capture the first xy coordinates
      start = mousePos(e);
    }

    function onMouseMove(e) {
      // Capture the ongoing xy coordinates
      current = mousePos(e);

      // Append the box element if it doesnt exist
      if (!box) {
        box = document.createElement('div');
        box.classList.add('boxdraw');
        canvas.appendChild(box);
      }

      var minX = Math.min(start.x, current.x),
        maxX = Math.max(start.x, current.x),
        minY = Math.min(start.y, current.y),
        maxY = Math.max(start.y, current.y);

      // Adjust width and xy position of the box element ongoing
      var pos = 'translate(' + minX + 'px,' + minY + 'px)';
      box.style.transform = pos;
      box.style.WebkitTransform = pos;
      box.style.width = maxX - minX + 'px';
      box.style.height = maxY - minY + 'px';
    }

    function onMouseUp(e) {
      // Capture xy coordinates
      finish([start, mousePos(e)]);
    }

    function onKeyDown(e) {
      // If the ESC key is pressed
      if (e.keyCode === 27) finish();
    }

    function finish(bbox) {
      // Remove these events now that finish has been called.
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('keydown', onKeyDown);
      document.removeEventListener('mouseup', onMouseUp);

      if (box) {
        box.parentNode.removeChild(box);
        box = null;
      }

      // If bbox exists. use this value as the argument for `queryRenderedFeatures`
      if (bbox) {
        var features = map.queryRenderedFeatures(bbox, {
          layers: ['counties']
        });

        if (features.length >= 1000) {
          return window.alert('Select a smaller number of features');
        }

        // Run through the selected features and set a filter
        // to match features with unique FIPS codes to activate
        // the `counties-highlighted` layer.
        var filter = features.reduce(
          function(memo, feature) {
            memo.push(feature.properties.FIPS);
            return memo;
          },
          ['in', 'FIPS']
        );

        map.setFilter('counties-highlighted', filter);
      }

      map.dragPan.enable();
    }

    map.on('mousemove', function(e) {
      var features = map.queryRenderedFeatures(e.point, {
        layers: ['counties-highlighted']
      });
      // Change the cursor style as a UI indicator.
      map.getCanvas().style.cursor = features.length ? 'pointer' : '';

      if (!features.length) {
        popup.remove();
        return;
      }

      var feature = features[0];

      popup
        .setLngLat(e.lngLat)
        .setText(feature.properties.COUNTY)
        .addTo(map);
    });
body {
  margin: 0;
  padding: 0;
}

#map {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}

#basemapmenu {
    position: absolute;
    display: inline-block;
    background-color: transparent;
    bottom: 0;
    left: 0;
    margin-left: 10px;
    margin-bottom: 40px;
}

.boxdraw {
  background: rgba(56, 135, 190, 0.1);
  border: 2px solid #3887be;
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
}
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet"/>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>

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

<div id='basemapmenu'>
    <input id='light-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Light' checked='checked'>
    <input id='dark-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Dark'>
    <input id='satellite-v9' class='btn btn-outline-primary' type='button' name='rtoggle' value='Satellite'>
  </div>

我运行你在本地编码发现问题了!

您正在尝试添加相同的源两次,并且 mapbox 给您错误,如果您检查您的控制台:

问题:地图上只能有一个源,一个ID

Error: There is already a source with this ID

第一次循环执行成功后。在第二次迭代中,它未能两次添加相同的源代码,代码在此处中断并且不再继续。因此不添加第二层(因此此后没有功能!)

修复:(添加了一个小检查以在已添加的情况下不添加相同的来源)

map.on('style.load', function () {
            for (var i = 0; i < vectorTileLayers.length; i++) {
                var tileLayer = vectorTileLayers[i];
                if (!map.getSource(tileLayer.layer.source,)) //FIX
                    map.addSource(tileLayer.layer.source, tileLayer.source);
                map.addLayer(tileLayer.layer);
            }

            var layerList = document.getElementById('basemapmenu');
            var inputs = layerList.getElementsByTagName('input');

            function switchLayer(layer) {
                var layerId = layer.target.id;
                map.setStyle('mapbox://styles/mapbox/' + layerId);
            }
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].onclick = switchLayer;
            }

        });

我可以看到代码运行良好:

希望这能解决问题。

我将接受多莉的上述回答,因为它准确地回答了我原来的问题。不幸的是,它并没有完全解决我的实际问题。经过一些额外的摆弄之后,我想 post 一个功能齐全的版本以供参考,以防人们遇到这个寻找在 Mapbox GL 中添加可切换“底图”图层的解决方案,有或没有像这样的用户交互选项。

在底图图层之间切换后,上述解决方案不起作用。矢量切片图层未正确重新加载。下面的解决方案似乎可以解决问题。它使用 map.on('styledata' ...) 而不是 map.on('style.load' ...),这似乎允许通过更传统的方法加载层,首先调用 map.addSource(),然后调用 map.addLayer()。您可以加载单个源,然后加载任意数量的指向该源的层。所以在我的“真实世界”示例中,我加载了 3 个源,并从这些源加载了 5 个层。

(仅供参考 - 由于某种原因,stack overflow 中的 built-in 代码片段工具未呈现底图按钮。如果您将代码准确复制到 JS fiddle 或 codepen 中,它将起作用)

我希望这对未来的人有所帮助 - 似乎很多人在管理顶部带有自定义图层的 Mapbox 样式时遇到了问题。我当然有。

mapboxgl.accessToken =
  "pk.eyJ1IjoiamFtZXljc21pdGgiLCJhIjoiY2p4NTRzdTczMDA1dzRhbXBzdmFpZXV6eCJ9.-k7Um-xmYy4xhNDN6kDvpg";
var map = new mapboxgl.Map({
  container: "map",
  style: "mapbox://styles/mapbox/light-v10",
  center: [-98, 38.88],
  minZoom: 2,
  zoom: 3
});

map.on("styledata", function() {
  map.addSource("counties", {
    type: "vector",
    url: "mapbox://mapbox.82pkq93d"
  });

  map.addLayer({
    id: "counties",
    type: "fill",
    source: "counties",
    "source-layer": "original",
    paint: {
      "fill-outline-color": "rgba(0,0,0,0.1)",
      "fill-color": "rgba(0,0,0,0.1)"
    }
  });

  map.addLayer({
    id: "counties-highlighted",
    type: "fill",
    source: "counties",
    "source-layer": "original",
    paint: {
      "fill-outline-color": "#484896",
      "fill-color": "#6e599f",
      "fill-opacity": 0.75
    },
    filter: ["in", "FIPS", ""]
  });

  var layerList = document.getElementById("basemapmenu");
  var inputs = layerList.getElementsByTagName("input");

  function switchLayer(layer) {
    var layerId = layer.target.id;
    map.setStyle("mapbox://styles/mapbox/" + layerId);
  }
  for (var i = 0; i < inputs.length; i++) {
    inputs[i].onclick = switchLayer;
  }
});

// Disable default box zooming.
map.boxZoom.disable();

// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
  closeButton: false
});

var canvas = map.getCanvasContainer();

var start;
var current;
var box;

canvas.addEventListener("mousedown", mouseDown, true);
// Return the xy coordinates of the mouse position
function mousePos(e) {
  var rect = canvas.getBoundingClientRect();
  return new mapboxgl.Point(
    e.clientX - rect.left - canvas.clientLeft,
    e.clientY - rect.top - canvas.clientTop
  );
}

function mouseDown(e) {
  // Continue the rest of the function if the shiftkey is pressed.
  if (!(e.shiftKey && e.button === 0)) return;

  // Disable default drag zooming when the shift key is held down.
  map.dragPan.disable();

  // Call functions for the following events
  document.addEventListener("mousemove", onMouseMove);
  document.addEventListener("mouseup", onMouseUp);
  document.addEventListener("keydown", onKeyDown);

  // Capture the first xy coordinates
  start = mousePos(e);
}

function onMouseMove(e) {
  // Capture the ongoing xy coordinates
  current = mousePos(e);

  // Append the box element if it doesnt exist
  if (!box) {
    box = document.createElement("div");
    box.classList.add("boxdraw");
    canvas.appendChild(box);
  }

  var minX = Math.min(start.x, current.x),
    maxX = Math.max(start.x, current.x),
    minY = Math.min(start.y, current.y),
    maxY = Math.max(start.y, current.y);

  // Adjust width and xy position of the box element ongoing
  var pos = "translate(" + minX + "px," + minY + "px)";
  box.style.transform = pos;
  box.style.WebkitTransform = pos;
  box.style.width = maxX - minX + "px";
  box.style.height = maxY - minY + "px";
}

function onMouseUp(e) {
  // Capture xy coordinates
  finish([start, mousePos(e)]);
}

function onKeyDown(e) {
  // If the ESC key is pressed
  if (e.keyCode === 27) finish();
}

function finish(bbox) {
  // Remove these events now that finish has been called.
  document.removeEventListener("mousemove", onMouseMove);
  document.removeEventListener("keydown", onKeyDown);
  document.removeEventListener("mouseup", onMouseUp);

  if (box) {
    box.parentNode.removeChild(box);
    box = null;
  }

  // If bbox exists. use this value as the argument for `queryRenderedFeatures`
  if (bbox) {
    var features = map.queryRenderedFeatures(bbox, {
      layers: ["counties"]
    });

    if (features.length >= 1000) {
      return window.alert("Select a smaller number of features");
    }

    // Run through the selected features and set a filter
    // to match features with unique FIPS codes to activate
    // the `counties-highlighted` layer.
    var filter = features.reduce(
      function(memo, feature) {
        memo.push(feature.properties.FIPS);
        return memo;
      }, ["in", "FIPS"]
    );

    map.setFilter("counties-highlighted", filter);
  }

  map.dragPan.enable();
}

map.on("mousemove", function(e) {
  var features = map.queryRenderedFeatures(e.point, {
    layers: ["counties-highlighted"]
  });
  // Change the cursor style as a UI indicator.
  map.getCanvas().style.cursor = features.length ? "pointer" : "";

  if (!features.length) {
    popup.remove();
    return;
  }

  var feature = features[0];

  popup.setLngLat(e.lngLat).setText(feature.properties.COUNTY).addTo(map);
});
body {
  margin: 0;
  padding: 0;
}

#map {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}

#basemapmenu {
  position: absolute;
  display: inline-block;
  background-color: transparent;
  bottom: 0;
  left: 0;
  margin-left: 10px;
  margin-bottom: 40px;
}

.boxdraw {
  background: rgba(56, 135, 190, 0.1);
  border: 2px solid #3887be;
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
}
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>

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

<div id='basemapmenu'>
  <input id='light-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Light' checked='checked'>
  <input id='dark-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Dark'>
  <input id='satellite-v9' class='btn btn-outline-primary' type='button' name='rtoggle' value='Satellite'>
</div>