1

I'm using Leafletjs to display a map on my website. I'm now starting to use Vuejs in it, but I'm getting errors because suddenly this refers to the Vuejs instance.

Consider the following function which works great outside of Vuejs (taken from here):

var marker_a = new L.Marker(a, {draggable: true}).addTo(map);

marker_a.on('dragstart', dragStartHandler);

function dragStartHandler (e) {
    var latlngs = polyline.getLatLngs(),
    var latlng = this.getLatLng();
    for (var i = 0; i < latlngs.length; i++) {
        if (latlng.equals(latlngs[i])) {
            this.polylineLatlng = i;
        }
    }
}

But when I use it in Vuejs:

methods: {
    dragStartHandler: function (e) {
        var latlngs = this.polyline.getLatLngs();
        var latlng = this.getLatLng();latlng
        for (var i = 0; i < latlngs.length; i++) {
            if (latlng.equals(latlngs[i])) {
                this.polylineLatlng = i;
            }
        }
    }
}

You can see that instead of polyline.getLatLngs() I now use this.polyline.getLatLngs() because I now load polyline from the Vuejs context. That works great. Unfortunately this.getLatLng() gives me an error saying this.getLatLng is not a function. That makes sense because I never defined getLatLng() in Vuejs. I'm not sure how to point it to the Leaflet context though.

Could anybody point me in the right direction?

kramer65
  • 50,427
  • 120
  • 308
  • 488
  • In your outside of vue.js code, What does this `var latlng = this.getLatLng();` line of code is doing, can you please elaborate. – Mehul Prajapati Apr 15 '19 at 05:17
  • And If you want to get rid of all these mess, I recommend you to use this [Library](https://www.npmjs.com/package/vue2-leaflet). I have used it for my project. It is best wrapper for leaflet. – Mehul Prajapati Apr 15 '19 at 05:31

1 Answers1

0

You can inspect the event argument that Leaflet passes to your dragStartHandler listener (your e argument): it should have a target member that references the Leaflet layer that dispatched the event, in your case marker_a.

methods: {
  dragStartHandler: function (e) {
    var latlng = e.target.getLatLng();
  }
}
ghybs
  • 47,565
  • 6
  • 74
  • 99