首页 > 解决方案 > 从 Vuex 商店创建 GoogleMaps 标记?

问题描述

我想使用加载 Json 文件的 Vuex 商店中的几个标记创建地图。

我是 VueJS 的新手,不知道如何在商店中导入数据以在我的 GoogleMap 组件的挂载钩子中使用它。

我已经在寻找可以给我一个想法的解决方案或一段代码,但一无所获。Vue和谷歌地图的新手,我被这个问题困住了。

我从商店获取我的数据:

computed: {
      displayRestaurantInfo() {
        return this.$store.getters.getRestaurantInfo;
      }
    }

并在我的组件的挂载钩子中创建了一个函数(但我没有尝试过任何工作):

pushMarkersCoordinates => {

      }  

必要时提取 JSON 文件:

[
  {
    "restaurantName": "Le Select",
    "address": "99 Boulevard du Montparnasse, 75006 Paris",
    "description": "Très bon restaurant de Plancha, cuisine généreuse",
    "lat": 48.842702,
    "long": 2.328434,
    "ratings": [
      {
        "stars": 4,
        "author": "Marc",
        "date": "15/02/2017",
        "comment": "Un excellent restaurant, j'y reviendrai ! Par contre il vaut mieux aimer la viande."
         },
      {
        "stars": 5,
        "author": "Sylvain",
        "date": "15/05/2017",
        "comment": "Tout simplement mon restaurant préféré !"
         },
      {
        "stars": 5,
        "author": "Patrick",
        "date": "15/11/2017",
        "comment": "Généreux !!! Rien à dire de plus."
         },
      {
        "stars": 4,
        "author": "Marc",
        "date": "15/01/2018",
        "comment": "Un excellent restaurant, j'y reviendrai ! Par contre il vaut mieux aimer la viande."
         },
      {
        "stars": 5,
        "author": "Sylvain",
        "date": "15/04/2018",
        "comment": "Tout simplement mon restaurant préféré !"
         },
      {
        "stars": 5,
        "author": "Patrick",
        "date": "15/08/2018",
        "comment": "Généreux !!! Rien à dire de plus."
         }
      ]
   },
  {
    "restaurantName": "L'Atelier",
    "address": "95 Boulevard du Montparnasse, 75006 Paris",
    "description": "Des pizzas comme en Italie, fine et gourmande",
    "lat": 48.842751,
    "long": 2.328118,
    "ratings": [
      {
        "stars": 5,
        "author": "Elodie",
        "date": "15/02/2017",
        "comment": "Une minuscule pizzeria délicieuse cachée juste à côté du Sacré choeur !"
         },
      {
        "stars": 3,
        "author": "Paul",
        "date": "15/05/2017",
        "comment": "J'ai trouvé ça correct, sans plus"
         },
      {
        "stars": 2,
        "author": "Yasmine",
        "date": "15/11/2017",
        "comment": "Pâtes froides !"
         },
      {
        "stars": 5,
        "author": "Elodie",
        "date": "15/01/2018",
        "comment": "Une minuscule pizzeria délicieuse cachée juste à côté du Sacré choeur !"
         },
      {
        "stars": 3,
        "author": "Paul",
        "date": "15/04/2018",
        "comment": "J'ai trouvé ça correct, sans plus"
         },
      {
        "stars": 2,
        "author": "Yasmine",
        "date": "15/08/2018",
        "comment": "Pâtes froides !"
         }
      ]
   }
]

store.js 文件中的代码:

import Vue from 'vue';
import Vuex from 'vuex';
const axios = require('axios');

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    data: [],
  },
  getters: {
    getRestaurantInfo: state => {
      const restaurantList = state.data;

      return restaurantList.map((restaurant) => {
        const sum = restaurant.ratings.reduce((acc, rating) => {
          return acc + rating.stars;
        }, 0);
        return {
          ...restaurant,
          averageRating: Math.round(sum / restaurant.ratings.length),
        }
      })
    }, 
    getComments: state => {
      console.log(state);
      return (restaurantID) => {
        const restaurant = state.data[restaurantID];
        return restaurant.ratings;
      }

    }
  },
  mutations: {
    setData: (state, {info}) => {
      state.data = info;
    }
  },
  actions: {
    getData: async function (context) {
      setTimeout(() => {
        axios.get('http://localhost:8080/restaurantList.json').then((response) => {
          context.commit('setData', {
            info: response.data});
          return true;
        }, (err) => {
          console.log(err);
          return false;
        });
      }, 500)
    }
  }
});

//callJSON: state => {
//  axios
//    .get('http://localhost:8080/restaurantList.json')
//    .then(response => (state.info = response.data))
//    .catch(function (error) {
//      if (error.response) {
//        console.log(error.response.data);
//        console.log(error.response.status);
//        console.log(error.response.headers);
//      } else if (error.request) {
//        console.log(error.request);
//      } else {
//        console.log('Error', error.message);
//      }
//    })
//    .then(function () {
//
//    });
//},

GoogleMap 组件中的代码:

<template>
  <div class="main" ref="autreRef">
    <div class="google-map" v-bind:id="mapName" ref="mainMap">
    </div>
  </div>
</template>

<script>
  //  import mapInterface from '../../interfaces/mapInterface.js'
  const GoogleMapsLoader = require('google-maps');
  GoogleMapsLoader.KEY = '';

  export default {
    name: 'google-map',
    props: ['name'],
    data: function() {
      return {
        mapName: this.name + "-map",
        markerCoordinates: [{
          latitude: 48.842492,
          longitude: 2.328300
        }],
        map: null,
        bounds: null,
        markers: [],
        infoWindow: null,
        position: {
          lat: null,
          lng: null
        }
      }
    },

    mounted: function() {
      GoogleMapsLoader.load((google) => {
          this.bounds = new google.maps.LatLngBounds();
          const element = this.$refs.mainMap
          this.infoWindow = new google.maps.InfoWindow;
          const mapCentre = this.markerCoordinates[0]
          const options = {
            zoom: 18,
            center: new google.maps.LatLng(mapCentre.latitude, mapCentre.longitude)
          }
          this.map = new google.maps.Map(element, options);

          this.markerCoordinates.forEach((coord) => {
            //        const marker = mapInterface.createMarker(coord)
            const position = new google.maps.LatLng(coord.latitude, coord.longitude);
            const marker = new google.maps.Marker({
              position,
              map: this.map
            });
            this.markers.push(marker)
            // Pour avoir tous les marqueurs sur la map si plusieurs marqueurs
            //        this.map.fitBounds(this.bounds.extend(position))
          });
          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
              const pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
              };

              this.infoWindow.setPosition(pos);
              this.infoWindow.setContent('Location found.');
              this.infoWindow.open(this.map);
              this.map.setCenter(pos);
            }, function() {
              handleLocationError(true, this.infoWindow, this.map.getCenter());
            });
          } else {
            // Browser doesn't support Geolocation
            handleLocationError(false, this.infoWindow, this.map.getCenter());
          }
        })
    },
    computed: {
      displayRestaurantInfo() {
        return this.$store.getters.getRestaurantInfo;
      }
    }
  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .google-map {
    width: 100%;
    height: 600px;
    margin: 0 auto;
    border: 2px solid #26A65B;
    border-radius: 2rem;
  }
</style>

我想了解如何在安装的钩子(或间接的其他钩子)中使用来自商店(或间接的其他组件)的数据。对于这个项目,能够创建几个标记。谢谢。

标签: javascriptgoogle-mapsobjectvue.jsvue-cli

解决方案


推荐阅读