Reputation: 505
Iam making a leaflet map where I want to be able to select the background layer from a drop down menu from the navbar.
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Bakgrunnkart
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#" id="basemap-osm" value="OpenStreetMap_Mapnik">OSM</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#" id="basemap-water-colour" value="Stamen_Watercolor">Water colour</a>
<div class="dropdown-divider"></div>
</div>
</li>
I have added a value attribute in the tags with the same name as the layers are defined as. Not sure if this is good practice of very "hacky?" still learning..
I want to add the selected layer to my basemaps layerGroup to display it on the map.
eg.
var OpenStreetMap_Mapnik = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
});
let basemaps = L.layerGroup()
.addLayer(OpenStreetMap_Mapnik) // default layer to show
.addTo(map);
$(".dropdown-item").click(function(event) {
event.preventDefault();
let selectedLayer = ($(this).attr("value"));
console.log(selectedLayer);
basemaps.clearLayers()
basemaps.addLayer(selectedLayer);
});
But because '$(this).attr("value")' return a string instead of the actual layer variable I get a typeError..
Any idea how i can work around that? I am quite new to js so I pick up as I go along.. =)
Upvotes: 0
Views: 519
Reputation: 49
i am sorry that i have posted here : i cannot comment since i do not have enough point .
i think it may be a cause of your problem .
second : Have you tried to mention the key for the value using attribute? like this :
$(this).attr("key","value");
or if u have multiple parameters
$(this).attr({
key:"value",
key2:"value"
});
third: have you tried to use the function that use callbacks inside : like this :
$("body").on("click","Mention_a_parent_if_you_have dropdownitem",function(data){
var myItem = ($(this).closest('dropdown-item')).data();
myItem.attr("Key","value");
});
Upvotes: 1