javascript - Mapbox JavaScript : Clicking on a Marker and highlighting a corresponding list

标签 javascript mapbox geojson

我想出了如何在单击相应列表(如下)时打开标记,但我该如何做相反的事情呢?当我单击标记时,列表中相应的事件将突出显示(并保持突出显示)。另外,当我单击标记列表时,它不会保持突出显示状态。我该如何解决这个问题。提前致谢!!!

var markerList = document.getElementById('marker-list');

map.featureLayer.on('ready', function(e) {
  map.featureLayer.eachLayer(function(layer) {
      var item = markerList.appendChild(document.createElement('li'));
      item.innerHTML = layer.toGeoJSON().properties.title +
      '<br /><small>' + layer.toGeoJSON().properties.description + '</small>';
      item.onclick = function() {
         map.setView(layer.getLatLng(), 17);

         layer.openPopup();
      };
  });
 });

//=======================================================================
// when clicking the marker, the sets the screen to make the
// marker at the center
//=======================================================================

  map.featureLayer.on('click', function(e) {
    map.panTo(e.layer.getLatLng());
    map.setView(layer.getLatLng(), 17);

  });

最佳答案

您需要有某种方法从图层的 onclick 函数中引用列表项。您可以创建这些项目的数组,并向每个单独的项目添加一个 id:

var list = document.getElementById('list');
var items = [];

featureLayer.eachLayer(function(layer) {
  var item = list.appendChild(document.createElement('li'));
  item.innerHTML = layer.getLatLng();
  item.id = layer._leaflet_id;
  items.push(item);
});

然后,在图层和项目的点击事件中,有某种功能可以更改元素,例如通过添加 css 类:

featureLayer.eachLayer(function(layer) {
  layer.on('click', function () {
    setActive(layer._leaflet_id);
  });
  item.onclick = function() {
    setActive(layer._leaflet_id);
  });
});

function setActive(id) {
  items.forEach(function(item){
    var cls = (id == item.id) ? 'active' : '';
    item.setAttribute('class', cls);
  });
}

这是一个working example关于普朗克。我正在使用 Leaflet,但这实际上与使用 Mapbox 相同。 Mapbox.js 只是 Leaflet 库的扩展版本。

关于javascript - Mapbox JavaScript : Clicking on a Marker and highlighting a corresponding list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26987933/

相关文章:

javascript - Angular2/Ionic - 查找数组中的重复项并组织它们

javascript - Recenter Mapbox map 使用用户坐标

swift - 尝试为 xCode 安装 Mapbox pod 会破坏现有的 pod

mapbox - 如何使用mapbox表达式设置 "text-font"

javascript - 使用 JQ 过滤 GeoJSON

javascript - 如何相对于映射的 div 放置组件? react Redux CSS

javascript - 我是 javascript 新手,我正在从 url 获取 JSON 数据,我只能访问 success 函数中的数据,我是否遗漏了什么?

javascript - 使用 JavaScript 下载并上传文件

javascript - D3 沿路径停止并重新启动过渡,以允许点击到地理数据坐标

javascript - 在 Leaflet 中显示来自 geojson 的 map 时设置缩放