Question

I'm new to javascript and trying to make a map with leaflet. My goal is to have a drop down box with layers that you can select. If you select a layer, that one should appear, and the existing layer on the map should disappear. I'm able to get the new layer to appear, but it never disappears when another is selected. They just pile on top of one another.

I've tried various iterations of using "onchange" (both calling just from javascript, and calling a js function from the <select> element. Below is the demo code I'm working with.

<select id='map-ui' onchange="toggle_layer();">
    <option>Please choose a layer</option>
    <option value="examples.bike-lanes">bike lanes</option>
    <option value="examples.bike-locations">bike stations</option>
</select>
<div id='map'></div>
<script>
var map = L.map('map').setView([38.902, -77.001], 13);

var base_map = 'examples.map-zgrqqx0w'
map.addLayer(L.mapbox.tileLayer(base_map));

var mapUI = document.getElementById("map-ui");
var shown_layer;

function toggle_layer(){
    var selectedValue = mapUI.options[mapUI.selectedIndex].value;
    if (shown_layer != selectedValue){
        map.removeLayer(L.mapbox.tileLayer(shown_layer));
    };
    map.addLayer(L.mapbox.tileLayer(selectedValue));
    shown_layer = selectedValue;
};
</script>
Was it helpful?

Solution

Your shown_layer variable should be L.mapbox.tileLayer(selectedValue). Then map.removeLayer(shown_layer); should work.

Anyway, here is an example of your code using jQuery (JSFiddle):

var map = L.map('map').setView([38.902, -77.001], 13);
map.addLayer(L.mapbox.tileLayer('examples.map-zgrqqx0w')); 

var shown_layer;

$("#map-ui").change(function() {
    var selected = $("#map-ui option:selected").val();

    if(selected === "") return;

    if(shown_layer !== undefined)
        map.removeLayer(shown_layer);

    shown_layer = L.mapbox.tileLayer(selected);
    map.addLayer(shown_layer); 
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top