I am designing a simple prototype web mapping application where I want a user to be able to click on a dropdown menu and have the map's choropleth layer, choropleth legend, and hover info box all change at once. My code seems to work up until the end, where when selecting a layer from the dropdown, nothing happens on my map. I know something is wrong with my change function. I am very new to Javascript, and have been using Leaflet in my class. Here is some of my code. The var here are both variable objects containing three other variables.
https://codepen.io/rjankows88/pen/zYpJNpW
var evlayer = {legend,
info,
counties
};
var poplayer = {poplegend,
popinfo,
population
};
var myDropdown = L.Control.extend({
options: {
position: "topright"
},
onAdd: function(map) {
this._div = L.DomUtil.create("div", "myDropdown");
this._div.innerHTML =
'<h2 id="title">Select a layer </h2>' +
'<select id="selector">' +
'<option value="init">Any</option>' +
'<option value="evlayer">Electric Vehicles per County</option>' +
'<option value = "poplayer">Population Estimate per County</option>' +
"</select>";
L.DomEvent.disableClickPropagation(this._div);
return this._div;
}
});
map.addControl(new myDropdown());
var layer_select = L.DomUtil.get("selector");
//prevent clicks on the selector from propagating through to the map
//(otherwise popups will close immediately after opening)
L.DomEvent.addListener(layer_select, "click", function(e) {
L.DomEvent.stopPropagation(e);
});
L.DomEvent.addListener(layer_select, "change", change);
function change(e) {
// updating the layer means deleting the old one and
// adding a new one
//debugger;
$("select").change(function (e) {
var x = document.getElementById("select");
if (x == "Electric Vehicles per County") {
map.removeLayer(poplayer);
map.addLayer(evlayer);
} else if (x == "Population Estimate per County") {
map.removeLayer(evlayer);
map.addLayer(poplayer);
}
});
};
Best Answer
There are three things that that cause your map not to work as expected:
change
you set new event processing with$("select").change
, instead of just checking the value of changed field and process it accordingly.map.addLayer
andmap.removeLayer
you are using objects comprising of two controls and one http request definition, which makes no sense. It should be layersgeojson
andgeojson2
geojson
andgeojson2
layers you are using the same style function namestyle
, so the second definition overrides the first one. Style forgeojson2
should have different name, for examplestyle2
.geojson
andgeojson2
layers together with their controls are added to the map, which does not make much sense, since on layer covers the other. In the code below I didn't change this behavior, but I think it should be changed.Code for changing the layers could then look something like this, assuming
any
choice means both layers should be shown, like they are initially: