leaflet.js api icons: why do iconAnchor and popupAnchor have different coordinate locations

后端 未结 1 1878
眼角桃花
眼角桃花 2021-02-14 18:53

If I configure leaflet icons in the following way, the popup is anchored at the upper left of the the icon.

iconUrl: \'images/Flaticon_10030-16px.png\',
iconAnch         


        
相关标签:
1条回答
  • 2021-02-14 19:56

    By default, when you provide an icon to a marker, image gets drawn with the upper left point of the image AT the lat lng you provide. The iconAnchor allows you to position the image such that it points to the correct area (whatever your image may be)

    Here is a fiddle that shows this http://jsfiddle.net/GX9bh/1/ The first marker has [0,0] iconAnchor, so the top left of the image points right at London, the second though has [100, 100] so it is up and to the left by 100 pixels in each direction.

    var icon_normal = new L.icon({
        iconUrl: 'http://cdn.leafletjs.com/leaflet-0.6.4/images/marker-icon.png',
        iconAnchor: [0, 0]
    });
    var icon_offsetted = new L.icon({
        iconUrl: 'http://cdn.leafletjs.com/leaflet-0.6.4/images/marker-icon.png',
        iconAnchor: [100, 100]
    });
    var marker = new L.Marker([51.505, -0.09], {
        icon: icon_normal
    });
    var marker2 = new L.Marker([51.505, -0.09], {
        icon: icon_offsetted
    });
    

    Note that if you don't provide any icon, that leaflet is handling this. You can see that with this code: http://jsfiddle.net/GX9bh/2/

    var marker3 = new L.Marker([51.505, -0.09]);
    

    This marker "points" at the actual lat lng, which is the top left of the image for marker.

    Popups are very similar, here is a fiddle with a basic popup on our original marker. http://jsfiddle.net/GX9bh/3/

    var popup = L.popup()
        .setContent('<p>Hello world!<br />This is a nice popup.</p>');
    marker.bindPopup(popup).openPopup()
    

    You'll notice it points to the default original latlng too! but if we have the popupAnchor, we can adjust it.

        popupAnchor: [100, 100]
    

    But for this guy, it goes down and to the right by 100 pixels in each direction (weird). Here is a fiddle http://jsfiddle.net/GX9bh/4/

    So really you would want to know the width and the height of your image you are using for the marker, so you actually adjust it.

    Since I know the image is 25px X 41px, I would want to offset the icon by [12, 41] so that the center (where the image points) is pointing to the actual latlng, similarly I would want to have the popup directly over that, so it should be offset by [0, -41] so it is just over the popup (it is already centered). And of course, here is that fiddle: http://jsfiddle.net/GX9bh/5/

    var icon_normal = new L.icon({
        iconUrl: 'http://cdn.leafletjs.com/leaflet-0.6.4/images/marker-icon.png',
        iconAnchor: [12, 41],
        popupAnchor: [0, -41]
    });
    

    Hope this helped!

    0 讨论(0)
提交回复
热议问题