[Vuejs]-Unable to get reference to scoped variable from method

0👍

google should be in data. So you can access this.google in methods. (And if you use this.map, map should also be in data.)

Here is your code with this change :

<template>
  <div>
    <div class="locations-map" :id="mapName"></div>
  </div>
</template>

<script>
import gmapsInit from '@/utils/gmaps';

export default {
  name: "locations-map",
  props: ['name', 'locations', 'viewStatus'],
  data: function() {
    return {
      mapName: this.name + "-map",
      filteredLocationType: "all",
      markers: [],
      google: null,
      map: null
    };
  },
  computed: {
    filteredLocations: function() {
      if (this.filteredLocationType === "all") {
        return this.locations;
      } else if (this.filteredLocationType === "term") {
        return this.locations.filter(function(location) {
          return location.category === "Terminal";
        });
      } else if (this.filteredLocationType === "dl") {
        return this.locations.filter(function(location) {
          return location.category === "Drop Location";
        });
      } else {
        return null;
      }
    }
  },
  watch: {
    locations: function() {
      this.initMap();
      }
  },
  async mounted() {
      this.google = await gmapsInit();
      const map = document.getElementById(this.mapName)
      const options = {
        zoom: 4,
        center: new this.google.maps.LatLng(37.09024, -95.712891), // center of USA
        scrollwheel: false,
        mapTypeId: this.google.maps.MapTypeId.ROADMAP
      };

      this.map = new this.google.maps.Map(map, options);
  },
  methods: {
    initMap: function() {
      this.addLocationMarkers();
    },
    clearMarkers: function() {
      for (var i = 0; i < this.markers.length; i++) {
        this.markers[i].setMap(null);
      }
      this.markers = []; // reset markers
    },
    addLocationMarkers: function() {
      this.filteredLocations.forEach(location => {
        const position = new this.google.maps.LatLng(
          location.latitude,
          location.longitude
        );
        const marker = new this.google.maps.Marker({
          position,
        });

        this.markers.push(marker);
      });
    },
  }
}
</script>

<style scoped>
.locations-map {
  width: 100%;
  height: 400px;
  margin: 0 0 40px 0;
  background: gray;
}
</style>

Leave a comment