I am new to Leaflet and JavaScript. I would like to know whether or not I can code my Leaflet map in a more concise way.
My map includes three GeoJSON layers in three different colors. I have set the colors by calling separate style functions for each layer. The function "style" returns blue, the function "style2" returns purple, and the function "style3" returns pink. I tell Layer 1 to use "style" and Layer 2 to use "style2", etc.
The map is here: http://talia.droppages.com/ask/three_layers.html
Can I do the same thing but with ONE style function? Essentially, could the style function detect the layer and do:
if the layer is layer 1, style like this______
if the layer is layer 2, style like this______
if the layer is layer 3, style like this______
If it can, how would I write that in code?
I frequently want to use ONE function for several layers, such as setting popup content, but I don't know how to make the function behave differently depending on which layer is clicked. I only know how to write similar but separate functions and call them separately.
<div id="map" style="width:800px; height: 600px"></div>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script src="http://talia.droppages.com/slccommcounc.js"></script>
<script src="http://talia.droppages.com/tract158slc.js"></script>
<script src="http://talia.droppages.com/slccouncil.js"></script>
<script>
var map = L.map('map').setView([40.8, -111.928], 11);
L.tileLayer('http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
maxZoom: 18,
minZoom: 7
}
).addTo(map);
function style(feature) {
return {
weight: 1,
opacity: 1,
color: 'blue',
fillColor: 'cornflowerblue',
fillOpacity: 0.5
};
}
function style2(feature) {
return {
weight: 1,
opacity: 1,
color: 'blueviolet',
fillColor: 'plum',
fillOpacity: 0.5
};
}
function style3(feature) {
return {
weight: 1,
opacity: 1,
color: 'fuchsia',
fillColor: 'pink',
fillOpacity: 0.5
};
}
var layer1 = new L.geoJson(slccommcounc, {
style: style,
}).addTo(map);
var layer2 = new L.geoJson(tract158slc, {
style: style2,
})
var layer3 = new L.geoJson(slccouncil, {
style: style3,
})
L.control.layers(null,{'Layer 1 Title':layer1,'Layer 3 Title':layer3,'Layer 2 Title':layer2},{collapsed:false}).addTo(map);
</script>