Skip to content
Snippets Groups Projects
map.js 7.03 KiB
Newer Older
import axios from '@/axios-client.js';
import { mapUtil } from '@/assets/js/map-util.js';
// axios.defaults.headers.common['X-CSRFToken'] = (name => {
//   var re = new RegExp(name + "=([^;]+)");
//   var value = re.exec(document.cookie);
//   return (value !== null) ? unescape(value[1]) : null;
// })('csrftoken');
    basemaps: null,
    basemapsToDelete: [],
    features: [],
    geojsonFeatures: null,
    SET_MAP(state, payload) {
      state.map = payload;
    },
    SET_LAYERS(state, availableLayers) {
      state.availableLayers = availableLayers;
    },
    SET_GEOJSON_FEATURES(state, geojsonFeatures) {
      state.geojsonFeatures = geojsonFeatures;
    },
    SET_BASEMAPS(state, basemaps) {
      state.basemaps = basemaps;
    },
    CREATE_BASEMAP(state, id) {
      state.basemaps = [...state.basemaps, { id, title: '', layers: [], errors: [] }];
    },
    UPDATE_BASEMAPS(state, basemaps) {
      state.basemaps = basemaps;
    },
    UPDATE_BASEMAP(state, { title, id, layers, errors }) {
      const index = state.basemaps.findIndex((el) => el.id === id);
      if (index !== -1) {
        state.basemaps[index].title = title;
        state.basemaps[index].errors = errors;
          state.basemaps[index].layers = layers;
        }
      }
    },
    DELETE_BASEMAP(state, basemapId) {
      state.basemaps = state.basemaps.filter(el => el.id !== basemapId);
      state.basemapsToDelete.push(basemapId);
    },
    REMOVE_BASEMAP_ID_TO_DELETE(state, basemapId) {
      state.basemapsToDelete = state.basemapsToDelete.filter(el => el !== basemapId);
    },
    REPLACE_BASEMAP_LAYERS(state, { basemapId, layers }) {
      const index = state.basemaps.findIndex((el) => el.id === basemapId);
      if (index !== -1) {
        state.basemaps[index].layers = layers;
      }
    },
    DELETE_BASEMAP_LAYER(state, { basemapId, layerId }) {
      const index = state.basemaps.findIndex((el) => el.id === basemapId);
      if (index !== -1) {
        state.basemaps[index].layers = state.basemaps[index].layers.filter((el) => el.dataKey !== layerId);
      }
    },
    UPDATE_BASEMAP_LAYER(state, { basemapId, layerId, layer }) {
      const index = state.basemaps.findIndex((el) => el.id === basemapId);
      if (index !== -1) {
        state.basemaps[index].layers = state.basemaps[index].layers.map(
          (el) => el.dataKey === layerId ? layer : el
        );
      }
    },
  },

  getters: {
    basemapMaxId: (state) => state.basemaps.reduce((acc, curr) => {
      if (curr.id > acc) {
        return curr.id;
      } else {
        return acc;
      }
    }, 0)
  },

  actions: {
DESPRES Damien's avatar
DESPRES Damien committed
      return axios
        .get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}layers/`)
        .then((response) => (commit('SET_LAYERS', response.data)))
        .catch((error) => {
          throw error;
        });
    },

    GET_BASEMAPS({ commit }, project_slug) {
DESPRES Damien's avatar
DESPRES Damien committed
      return axios
        .get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}base-maps/?project__slug=${project_slug}`)
leandro's avatar
leandro committed
        .then((response) => {
          if (response.status === 200 && response.data) {
            commit('SET_BASEMAPS', response.data);
          return response;
leandro's avatar
leandro committed
        })
    INITIATE_MAP({ state, rootGetters, commit }, el) {
      const project = rootGetters.project;
      let mapDefaultViewCenter = [46, 2]; // defaultMapView.center;
      let mapDefaultViewZoom = 5; // defaultMapView.zoom;
      mapUtil.createMap(el, {
      commit('SET_MAP', mapUtil.getMap());

      // Load the layers.
      // - if one basemap exists, check in the localstorage if one active basemap is set
      // - if no current active basemap, get the first index
      // - if not, load the default map and service options

      // todo : create endpoints to get : 'baseMaps' ,'layers' ,'serviceMap' ,'optionsMap' 
      let layersToLoad = null;
      if (state.baseMaps && state.baseMaps.length > 0) {
        // Use active one if exists, otherwise index 0 (first basemap in the list)
        const mapOptions =
          JSON.parse(localStorage.getItem('geocontrib-map-options')) || {};
        const basemapIndex =
          mapOptions &&
            mapOptions[project] &&
            mapOptions[project]['current-basemap-index']
            ? mapOptions[project]['current-basemap-index']
            : 0;
        layersToLoad = state.baseMaps[basemapIndex].layers;
        layersToLoad.forEach((layerToLoad) => {
            if (layer.id === layerToLoad.id) {
              layerToLoad = Object.assign(layerToLoad, layer);
            }
          });
        });
        layersToLoad.reverse();
      }
Timothee P's avatar
Timothee P committed
      mapUtil.addLayers(
        layersToLoad,
        this.state.configuration.DEFAULT_BASE_MAP.SERVICE,
        this.state.configuration.DEFAULT_BASE_MAP.OPTIONS
      );

      // Remove multiple interactions with the map
      //mapUtil.getMap().dragging.disable();
      mapUtil.getMap().doubleClickZoom.disable();
      mapUtil.getMap().scrollWheelZoom.disable();

    },

    async SAVE_BASEMAPS({ state, rootState, dispatch }, newBasemapIds) {
      const DJANGO_API_BASE = this.state.configuration.VUE_APP_DJANGO_API_BASE;
      function postOrPut(basemap) {
        basemap['project'] = rootState.project_slug;
        if (newBasemapIds.includes(basemap.id)) {
          return axios
            .post(`${DJANGO_API_BASE}base-maps/`, basemap)
            .then((response) => response)
            .catch((error) => {
Timothee P's avatar
Timothee P committed
              console.error(error);
              return error;
            });
        } else {
          return axios
            .put(`${DJANGO_API_BASE}base-maps/${basemap.id}/`, basemap)
            .then((response) => response)
            .catch((error) => {
Timothee P's avatar
Timothee P committed
              console.error(error);
              return error;
leandro's avatar
leandro committed
        }
leandro's avatar
leandro committed
        //* delete in the backend the basemaps that was rewoved from the front
        return dispatch('DELETE_BASEMAP', basemapId)
          .then((response) => response);
      }

      const promisesResult = await Promise.all(
Timothee P's avatar
Timothee P committed
        [
          ...state.basemaps.map((basemap) => postOrPut(basemap)),
          ...state.basemapsToDelete.map((basemapId) => deleteBMap(basemapId))
        ]
      state.basemapsToDelete = [];
      return promisesResult;
      let url = `${this.state.configuration.VUE_APP_DJANGO_API_BASE}base-maps/` + basemapId;
leandro's avatar
leandro committed
        .delete(url)
          if (response && response.status === 204) {
            commit('REMOVE_BASEMAP_ID_TO_DELETE', basemapId);
            return response;
Timothee P's avatar
Timothee P committed
          console.error(error);
          return error;
};
export default map;