daskobe
daskobe

Reputation: 7

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

I figured out how to open up a marker when clicking on a corresponding list (below) but how do I do the opposite? When I click on a marker, the corresponding event on the list would get highlighted (and stay highlighted). Also, when I click on the marker list, it does not stay highlighted. How would i fix that. Thanks in advance!!!

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

  });

Upvotes: 0

Views: 1013

Answers (1)

iH8
iH8

Reputation: 28628

You need to have some way to reference the listitem from the onclick function of your layer. You could create an array of those items and add an id to each individual item:

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

Then in the click event of your layer and item have some sort of function which changes the element for instance by adding a css class:

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

Here's a working example on Plunker. I'm using Leaflet but that is practicly the same as using Mapbox. Mapbox.js is just an extended version of the Leaflet library.

Upvotes: 1

Related Questions