My current setup involves utilizing a Leaflet map with vue2leaflet.
The process I follow is quite standard:
- I import a list of places from a REST Api in the app store (vuex)
- Following that, during map initialization, the markers are created using the information stored
Essentially, my Map.vue module calls the map like this:
<v-map ref="map" :zoom="zoom" :center="center">
<v-tilelayer url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"></v-tilelayer>
<v-marker-cluster :options="clusterOptions">
<v-marker v-for="(marker, index) in markers"
:key="index"
:lat-lng="makeCoords(marker.location.lat, marker.location.lng)"
v-on:l-click="showSpot(marker._id, marker.slug, marker.location.lat, marker.location.lng)">
</v-marker>
</v-marker-cluster>
</v-map>
The Markers data comes from the store ($store.map.markers):
computed: {
markers () {
return this.$store.state.map.markers
}
}
In the same Template, to obtain a reference to the map, do the following:
this.$refs.map
If another file, say "AddMarker.vue", needs to place new markers on the map, use this method:
L.marker([datas.location.lat, datas.location.lng]).addTo(mymap);
where "mymap" refers to the object defined in Map.vue
However, attempting to access this.$refs.map from another file results in "undefined".
Several attempts were made to add the map reference to the store but encountered errors. Storing components in this manner seems problematic.
Simply adding the new marker to the store does not automatically update the map. The addTo() method needs to be called.
Below is the store configuration:
export const state = () => ({
markers: null
})
export const mutations = {
setMarkers(state, markers) {
state.markers = markers
},
addMarker(state, marker) {
state.markers.push(marker)
}
}
export const actions = {
async init({ commit }) {
let { data } = await this.$axios.get(process.env.api.spots)
commit('setMarkers', data)
}
}
To call the mutation:
that.$store.commit('map/addMarker', {
title: values.title,
description: values.description,
location: {
city: that.$store.state.position.infos.city,
country: that.$store.state.position.infos.country,
lat: that.$store.state.position.coords.lat,
lng: that.$store.state.position.coords.lng
}
});
Although the marker is successfully added to the store, it doesn't reflect on the map. Seeking help and advice on how to resolve this issue. Thank you!