I'm interested in developing a custom component to modify the basemap of a leaflet map without relying on L.control.layers
. To achieve this, I created a sidebar component that offers options to switch between different basemaps.
In my implementation, I utilized vuejs along with vuex for data management. Below is an excerpt from my code:
store.js
import Vue from 'vue'
import Vuex from 'vuex'
import "leaflet/dist/leaflet.css";
Vue.use(Vuex)
export default new Vuex.Store({
state: {
satellite: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
dark: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png',
osm: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
topography: 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
baseMap: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
},
getters: {
baseMap: state => state.baseMap
},
actions: {
changeBaseMap({ commit }, base) {
commit("CHANGE_BASE_MAP", base);
}
},
mutations: {
CHANGE_BASE_MAP(state, base) {
state.baseMap = base
}
},
})
The sidebar component successfully modifies the value of the baseMap
, but unfortunately, it does not reflect changes in the leaflet component when the baseMap
state updates. Here's a snippet of my Map component where I use computed
to access the baseMap
value:
<template>
<div id="container" >
<div id="map"></div>
</div>
</template>
<script>
import "leaflet/dist/leaflet.css";
import L from "leaflet";
export default {
name: "Map",
data() {
return {
center: [-0.789275,113.921327],
zoom: 5,
map: null
};
},
computed: {
baseMap: function () {
return this.$store.getters.baseMap
}
},
methods: {
setupLeafletMap () {
this.map = L.map("map").setView(this.center, this.zoom);
var tilelayer = L.tileLayer(this.baseMap)
tilelayer.addTo(this.map)
}
},
mounted() {
this.setupLeafletMap();
}
};
</script>
Even though I've tried displaying the baseMap
value within the <div>
tag and it reflects changes upon state updates, the leaflet base layer remains unchanged.
<div id="map">{{ baseMap }}</div>
I've been searching for a solution to this issue but haven't been able to find one yet. Any guidance or suggestions would be highly appreciated.