【问题标题】:Change other HTML elements after clicking on map marker in Mapbox?单击 Mapbox 中的地图标记后更改其他 HTML 元素?
【发布时间】:2016-03-13 20:32:21
【问题描述】:

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

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

【问题讨论】:

    标签: javascript jquery geolocation leaflet mapbox


    【解决方案1】:

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

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

    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(使用多边形而不是标记,但过程几乎相同)。

    【讨论】:

      猜你喜欢
      • 2015-03-01
      • 1970-01-01
      • 2013-10-28
      • 2020-11-30
      • 1970-01-01
      • 2019-05-23
      • 2019-06-21
      • 2016-12-09
      • 2011-11-02
      相关资源
      最近更新 更多