[GIS] Hover on legend to highlight multiple areas on map

geojsonjavascriptleaflet

I would like to highlight different areas on a map when the mouse hovers over the legend using leaflet.

This jsfiddle http://jsfiddle.net/expedio/3w4j2u9z/ is probably the closest to what I am looking for, however, with my limited knowledge of JS and Leaflet I'm struggling to figure out how to link the hover to multiple ID's.

I've searched the internet far and wide and can't seem to find a solution.

Here is an example of the final outcome we would like to achieve – http://atlas.id.com.au/adelaide#MapNo=10173&SexKey=3&datatype=1&themtype=3&topicAlias=population-density&year=2011

Best Answer

There is no special difficulty in implementing what you describe.

The idea is to add event listeners on your legend items.

On "mouseover", loop through all shapes and compare their property (here, density) to the range of your legend item, and highlight if it matches.

On "mouseout", reset all shapes style.

var legend = L.control({
  position: 'topright'
});

legend.onAdd = function(map) {
  var div = L.DomUtil.create('div', 'info legend'),
    grades = [0, 10, 20, 50, 100, 200, 500, 1000],
    from, to, span, color, text;

  for (var i = 0; i < grades.length; i++) {
    from = grades[i]; // Zahlen setzen 
    to = grades[i + 1];

    span = document.createElement("span");
    span.classList.add("legendItem");
    span.dataset.from = from;
    span.dataset.to = to;

    color = document.createElement("i");
    color.style.background = getColor(from + 1);

    text = document.createTextNode(from + (to ? '-' + to : '+'));

    span.appendChild(color);
    span.appendChild(text);

    span.addEventListener("mouseover", function (event) {
      var span = event.currentTarget,
        from = span.dataset.from,
        to = span.dataset.to,
        above = to === "undefined";

      geojson.eachLayer(function (layer) {
        var density = layer.feature.properties.density;
        if (density >= from && (above || density < to)) {
          highlightFeature(layer);
        }
      });
    });
    span.addEventListener("mouseout", function () {
      geojson.eachLayer(resetHighlight);
    });

    div.appendChild(span);
    div.appendChild(document.createElement("br"));
  }

  return div;
};

legend.addTo(map);

Updated JSFiddle: http://jsfiddle.net/3w4j2u9z/23/