[GIS] How to prevent Leaflet from moving the marker while zooming into the map

leafletmarkers

If I use the leaflet code described in the documentation, use another marker url AND change the iconSize, the marker moves when zoomed in/out.

It doesn't move if I keep the iconSize as it is. But than the marker looks like crap.

This is the original Leaflet code:

var myIcon = L.icon({
    iconUrl: 'my-icon.png',
    iconSize: [38, 95],
    iconAnchor: [22, 94],
    popupAnchor: [-3, -76],
    shadowUrl: 'my-icon-shadow.png',
    shadowSize: [68, 95],
    shadowAnchor: [22, 94]
});
L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);

This is how I manipulated it (only coordinated, image url and size are changed):

var myIcon = L.icon({
    iconUrl: 'https://raw.githubusercontent.com/iconic/open-iconic/master/png/map-marker-8x.png',
    iconSize: [32, 32],
    iconAnchor: [32, 32],
    popupAnchor: [-3, -76],
    shadowUrl: 'my-icon-shadow.png',
    shadowSize: [68, 95],
    shadowAnchor: [22, 94]
});

L.marker([52.55, 13.47], {icon: myIcon}).addTo(map);

Best Answer

See Leaflet doc about iconAnchor option:

The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if size is specified, also can be set in CSS with negative margins.

If you specify iconAnchor with the same value as iconSize (i.e. [32, 32] in your case), Leaflet will position your icon so that its bottom right corner is at the marker's geographic position. Therefore, when zooming in/out, your actual icon "tip" (which is at bottom center) will "move" relatively to that position.