4

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);
7

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.

4

As ghybs has mentioned, the issue is in the parameters that have been passed to iconAnchor.

Given your marker, you need the icon to be Anchored to the bottom center of the icon, for which, the following code should work:

var myIcon = L.icon({
            iconUrl: 'https://raw.githubusercontent.com/iconic/open-iconic/master/png/map-marker-8x.png',
            iconSize: [32, 32],
            iconAnchor: [16,32]
        });

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

(Note that I have just removed the options for the shadow, since I do not know which file you have used for it, and where it's anchor point lies. You can add it back, and set the appropriate Anchor point.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.