【问题标题】:Wrong code in tutorial for event listeners事件监听器教程中的错误代码
【发布时间】:2019-12-13 04:10:10
【问题描述】:

我正在关注this tutorial 构建一个带有 Mapbox 地图的商店定位器页面。

我不想添加自定义标记,因为我已经有自定义地图标签(符号?),这意味着我不需要教程的可选最后一部分,并在 Add Event Listeners 之后停止。

完成此操作后,页面应该对侧面板列表中的点击以及地图上的点击做出反应(2 个事件侦听器)。但是,在该特定步骤的demo provided in the tutorial 中,您可以告诉第二个事件侦听器的代码(使地图可点击的那个)不起作用,这让我相信提供的代码中有错误:

// Add an event listener for when a user clicks on the map
map.on('click', function(e) {
  // Query all the rendered points in the view
  var features = map.queryRenderedFeatures(e.point, { layers: ['locations'] });
  if (features.length) {
    var clickedPoint = features[0];
    // 1. Fly to the point
    flyToStore(clickedPoint);
    // 2. Close all other popups and display popup for clicked store
    createPopUp(clickedPoint);
    // 3. Highlight listing in sidebar (and remove highlight for all other listings)
    var activeItem = document.getElementsByClassName('active');
    if (activeItem[0]) {
      activeItem[0].classList.remove('active');
    }
    // Find the index of the store.features that corresponds to the clickedPoint that fired the event listener
    var selectedFeature = clickedPoint.properties.address;

    for (var i = 0; i < stores.features.length; i++) {
      if (stores.features[i].properties.address === selectedFeature) {
        selectedFeatureIndex = i;
      }
    }
    // Select the correct list item using the found index and add the active class
    var listing = document.getElementById('listing-' + selectedFeatureIndex);
    listing.classList.add('active');
  }
});

谁能说出这段代码有什么问题?

【问题讨论】:

  • 这里有人用 Mapbox 吗?
  • 我实际上不明白你为什么说它不起作用。您可能会自定义代码的某些部分,所以会有一些不匹配的代码?

标签: listener mapbox mapbox-gl-js


【解决方案1】:

结果代码是不完整的,因为当您将鼠标悬停在地图标签/标记上时光标不会变为指针,因此它不会提示您意识到您可以点击它,因此我假设它不是根本不工作。我假设除非指针出现,否则将面对地图的普通用户同样会被欺骗。因此,在本教程中,如果您继续单击标记,它将具有预期的行为并显示弹出窗口,尽管没有显示指针。

这里是如何创建指针,基于这个小提琴:https://jsfiddle.net/Twalsh88/5j70wm8n/25/

map.on('mouseenter', 'locations', function(e) {
   // Change the cursor style as a UI indicator.
   map.getCanvas().style.cursor = 'pointer';

 });
 map.on('mouseleave', 'locations', function() {
   map.getCanvas().style.cursor = '';
 });

【讨论】:

    猜你喜欢
    • 2022-12-05
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2016-10-15
    相关资源
    最近更新 更多