No, if you are loading leaflet tile layers, it is not possible to change their style once loaded.
The key difference between your code and the example code you linked to is that the example code renders geoJSON data directly in the browser. Notice this line of code:
var featureLayer = new L.GeoJSON();
//...
map.addLayer(featureLayer);
You are loading you data as a bunch of tile layers, which are pre-rendered .png images, and so can't be restyled in the browser.
With tile layers, all your data is first converted into small png images (either on a server, or locally with something like MapBox's TileMill) for fast load times and nearly no limit on data size; however as a raster source, you lose the ability to manipulate the data itself.
With feature layers loaded from a geojson, you reserve the ability to manipulate your data as a vector--style it in browser, run queries over it, etc--but loading even moderately sized datasets can become an issue.
If you want to be able to restyle your polygons on hover, look at using L.geoJSON()
or L.mapbox.featureLayer()
.
I think the first problem is your currentLegend
variable. Whenever you add a layer this variable gets overwritten, either with houselegend
or childlegend
. Let's say you activate Families and then Housing, your currentLegend
is now houselegend
.
Now you deactive the Families layers, but your Housing legend is removed, and currentLegend
is set to houselegend
again. You now remove the Housing layer and legend, but it fails because houselegend
is already removed, childlegend
stays.
The second problem is that the conditions in your if
code are mutually exclusive in handling the layer legends. It allows only one legend to be active at a time, whenever a layer is added a legend is removed.
One way to solve and simplify this would be to create a mapping between layers and legends. Add and remove legends according to the layer name taken from the event.
var layerToLegendMapping={
"Housing": houselegend,
"Families": childlegend
}
function legendAdd(event) {
var layername = event.name;
map.addControl(layerToLegendMapping[layername]);
}
function legendRemove(event) {
var layername = event.name;
map.removeControl(layerToLegendMapping[layername]);
}
map.on('overlayadd',legendAdd);
map.on('overlayremove',legendRemove);
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.Updated JSFiddle: http://jsfiddle.net/3w4j2u9z/23/