0

I want to create a component like a control layer to change the basemap of the Leaflet. But I don't want to use L.control.layers. So, I made a sidebar component that have options to change the basemap.

enter image description here

I use vuejs and to organize the data I use vuex. This is 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 to change the value of the baseMapis worked. But, the leaflet component doesn't change when baseMap state changes, it just changes the value of baseMap not the leaflet component.

This is my Map component I use computed to access baseMap value when state changes

<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>

I try to call baseMap value inside the <div> tag, and when state changes, it changes. But the leaflet base layer doesn't change

<div id="map">{{ baseMap }}</div>

I really don't have an idea how to solve this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.