I was trying to resize my custom icons when zooming in leaflet. I came up with two solutions for this. One using the L.Icon
tag, the other one using L.divIcon
. In both examples I only set 1 marker and group for readability
Method 1 using L.Icon: make groups with markers. Then on zoomend
i use mygroup.eachLayer(function (layer)
to change all icons for 1 layer using layer.setIcon()
. I repeat this for all groups
<script>
// Setting map options
....
// Setting Icon
var normalicon = L.icon({
iconUrl: 'icon1.jpg',
iconSize: [40,40],
iconAnchor: [20,20],
popupAnchor: [0,-20]
});
// Create a group
var normalLayer = L.layerGroup([
L.marker([200,200], {icon:normalicon})
]).addTo(map);
// Resizing on zoom
map.on('zoomend', function() {
// Normal icons
var normaliconresized = L.Icon.extend({
options: {
iconSize: [20*(map.getZoom()+2), 20*(map.getZoom()+2)], // New size!
iconAnchor: [20,20],
popupAnchor: [0,-20]
}
});
var normaliconchange = new normaliconresized({iconUrl: 'icon1.jpg'})
normalLayer.eachLayer(function (layer) {
layer.setIcon(normaliconchange);
});
.... Do the same for the other groups
});
</script>
Method 2 using L.divIcon: I make the icons and the different groups and add some CSS for each icon with a background-image
property. Then on zoomend
I simply use JQuery to change the css. background-size
css-property allows me to change the image size. I do this for each divIcon class I have
Css
.iconsdiv{
width:20px; height:20px;
background-image:url("icon2.jpg");
background-size: 20px 20px;
}
Script
<script>
// Setting map options
....
// Setting Icon
var divicon = L.divIcon({className: 'iconsdiv', iconSize: null }); // Explicitly set to null or you will default to 12x12
// Create a group
var divLayer = L.layerGroup([
L.marker([200,200], {icon:divicon})
]).addTo(map);
// Resizing on zoom
map.on('zoomend', function() {
var newzoom = '' + (20*(map.getZoom()+2)) +'px';
$('#map .iconsdiv').css({'width':newzoom,'height':newzoom,'background-size':newzoom + ' ' + newzoom});
... repeat for the other classes
});
</script>
I have barely any experience with javascript/jquery/...
Is the second option preferable as it does not require re-setting each icon? Would it improve performance when there is a large number of groups/icons?