在 Mapbox 中点击地图标记后更改其他 HTML 元素?

Change other HTML elements after clicking on map marker in Mapbox?

This Mapbox tutorial 展示了如何构建列表并在单击列表项后让地图平移到地图标记。

JSFiddle

列表项根据特定标记处理其点击事件的方式如下:

// Iterate through each feature layer item, build a
// marker menu item and enable a click event that pans to + opens
// a marker that's associated to the marker item.
myLayer.eachLayer(function(marker) {
  var link = info.appendChild(document.createElement('a'));
  link.className = 'item';
  link.href = '#';

  // Populate content from each markers object.
  link.innerHTML = marker.feature.properties.title +
    '<br /><small>' + marker.feature.properties.description + '</small>';
  link.onclick = function() {
    if (/active/.test(this.className)) {
      this.className = this.className.replace(/active/, '').replace(/\s\s*$/, '');
    } else {
      var siblings = info.getElementsByTagName('a');
      for (var i = 0; i < siblings.length; i++) {
        siblings[i].className = siblings[i].className
          .replace(/active/, '').replace(/\s\s*$/, '');
      };
      this.className += ' active';

      // When a menu item is clicked, animate the map to center
      // its associated marker and open its popup.
      map.panTo(marker.getLatLng());
      marker.openPopup();
    }
    return false;
  };
});

怎么才能反过来呢?现在,如果您直接单击标记,会出现弹出窗口,但列表项不会更新为所选标记。我不太确定如何将点击事件绑定到对应于特定列表项的地图标记。

您只需要创建一个附加到标记 "click" event 的侦听器,并在标记中保留对 link 的引用。

然后侦听器将执行与 link.onclick > else 块的第一部分相同的指令,当它重置 links classes 并设置单击标记的 link 上的 "active" class。

myLayer.eachLayer 的匿名函数中,您可以在 link 变量赋值后添加:

// Marker click interaction.
marker.on("click", markerClickSetLinkActive);

// Keep a reference to the link within the marker.
marker.link = link;

在你的脚本文件中的某处:

// Marker click interaction function to handle the click event.
function markerClickSetLinkActive(event) {
  var marker = event.target;
  var link = marker.link;

  var siblings = info.getElementsByTagName('a');
  for (var i = 0; i < siblings.length; i++) {
    siblings[i].className = siblings[i].className
      .replace(/active/, '').replace(/\s\s*$/, '');
  };
  link.className += ' active';
}

演示:http://plnkr.co/edit/oueHiszYQNXEX1oBkXkD?p=preview(使用多边形代替标记,但过程几乎相同)。