vue-leaflet/Vue2Leaflet

Updating the Position of Multiple Markers

winstxnhdw opened this issue · 1 comments

Hello!

It's shown in #161 that dynamically updating a marker is clearly possible. Is this also possible with multiple markers?

<l-marker
  v-for="(marker, index) in markers" 
  :draggable="true" 
  :key="index"
  :lat-lng="marker"
  :icon="icon"
</l-marker>
export default {
  name: 'Map',
  data() {
    return {
      zoom: 18,
      url: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
      markers: [],

  methods: {
   // functions that will append/change the marker's position
  }

I managed to solve the problem.

This is what I previously did to 'update' my markers. Basically, I was changing the value of the object in the markers array.

this.selectedMarkersId.forEach((dummy, id) => {
  var selectedMarker = this.selectedMarkersId[id];
  this.interpolate[selectedMarker][0] = this.oldMarkerPos[id][0] + delta_lat;
  this.interpolate[selectedMarker][1] = this.oldMarkerPos[id][1] + delta_lng;
  this.markers[selectedMarker].lat = this.oldMarkerPos[id][0] + delta_lat;
  this.markers[selectedMarker].lng = this.oldMarkerPos[id][1] + delta_lng;
});

For some reason, Vue2Leaflet does not update the markers unless it detects a change via splice() or push() and not any other way. You can simply splice nothing by doing this.markers.splice() if you are not using v-for="(marker, index) in markers" and it should update. But if you are using the for loop like me, this is what you must do.

this.selectedMarkersId.forEach((dummy, id) => {
  var selectedMarker = this.selectedMarkersId[id];
  var newLat = this.oldMarkerPos[id][0] + delta_lat;
  var newLng = this.oldMarkerPos[id][1] + delta_lng;
  var newLatLng = {lat: newLat, lng: newLng}
  this.interpolate[selectedMarker][0] = newLat
  this.interpolate[selectedMarker][1] = newLng
  this.markers.splice(selectedMarker, 1, newLatLng);
});

I don't get why I must do it in this specific way, but it is what it is. If anyone knows, please feel free to enlighten me. Hope this helps (apparently, all questions about this topic are either unanswered or wrong).

In case you need to know, this is how I create my markers.

<l-map ref="map" 
  :zoom="zoom" 
  :center="center"
  @click="createMarker">
...
</l-map>
createMarker(event) {
  this.markers.push(event.latlng);
},