How do I get the latlng after the dragend event in leaflet?

前端 未结 4 1002
陌清茗
陌清茗 2021-01-07 18:55

I\'m trying to update the lat/lng value of a marker after it is moved. The example provided uses a popup window to display the lat/lng.

I have a \"dragend\" event l

相关标签:
4条回答
  • 2021-01-07 19:12

    Use e.target.getLatLng() to get the latlng of the updated position.

        // Script for adding marker on map click
        function onMapClick(e) {
    
            var marker = L.marker(e.latlng, {
                     draggable:true,
                     title:"Resource location",
                     alt:"Resource Location",
                     riseOnHover:true
                    }).addTo(map)
                      .bindPopup(e.latlng.toString()).openPopup();
    
            // #12 : Update marker popup content on changing it's position
            marker.on("dragend",function(e){
    
                var chagedPos = e.target.getLatLng();
                this.bindPopup(chagedPos.toString()).openPopup();
    
            });
        }
    

    JSFiddle demo

    0 讨论(0)
  • 2021-01-07 19:15

    I think the API changed.

    Nowadays is: const { lat, lng } = e.target.getCenter();

    0 讨论(0)
  • 2021-01-07 19:25

    latlng value is not in e.latlng but in e.target._latlng . Use console.

    0 讨论(0)
  • 2021-01-07 19:27

    While using e.target._latlng works (as proposed by this other answer), it's better practice to use

    e.target.getLatLng();
    

    That way we're not exposing any private variables, as is recommended by Leaflet:

    Private properties and methods start with an underscore (_). This doesn’t make them private, just recommends developers not to use them directly.

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