Реализовать fitBounds из GoogleMaps с помощью Vuejs - PullRequest
0 голосов
/ 26 апреля 2019

Я пытаюсь получить границы моей карты, скорее, с помощью метода, поскольку я уже создал метод initMap и метод askGeolocation.

Мне не удается заставить работать границы, поэтому масштаб карты адаптируется к положению различных маркеров.

Я попытался создать метод useBounds, вызываемый в addMarker, но он не работает. Я также попытался поместить код для обработки границ непосредственно в addMarker (), но он все еще не работает.

Я думаю, что я не могу правильно определить LatLng маркеров, чтобы поместить в методы границ.

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

<script>
  const GoogleMapsLoader = require('google-maps');
  GoogleMapsLoader.KEY = 'API_KEY';

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

    mounted: function() {
      GoogleMapsLoader.load((google) => {
        this.$store.watch(
          (state, getters) => getters.getRestaurantInfo,
          (newValue, oldValue) => {
            newValue.map((restaurant) => {
              this.addMarker({
                lat: restaurant.lat,
                lng: restaurant.long
              }, 'restaurant')
            })
          }
        )

        this.initMap();
        this.askGeolocation();
//        this.useBounds();


      });
    },
    methods: {
      initMap() {
        const element = this.$refs.mainMap
        const options = {
          center: {lat: 48.842129, lng: 2.329375},
          zoom: 18,
        }
        this.map = new google.maps.Map(element, options);
        this.infoWindow = new google.maps.InfoWindow;
      },
      askGeolocation() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition((position) => {
            const pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            this.userCoord = pos
            this.addMarker(this.userCoord, 'user')
            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());
        }
      },

//      useBounds() {
//        this.bounds = new google.maps.LatLngBounds();
//        this.bounds.extend(marker.position);
//        this.map.fitBounds(this.bounds);
//      },

      addMarker(coord, type) {
        let icon = ''
        if (type === 'user') {
          icon = 'https://img.icons8.com/color/48/000000/marker.png'
        } else {
          icon = 'https://img.icons8.com/ios/50/000000/restaurant-table.png'
        }
        console.log('j ajoute ', coord)
        const position = new google.maps.LatLng(coord.lat, coord.lng);
        const marker = new google.maps.Marker({
          position,
          map: this.map,
          icon
        });
//        this.useBounds();
        this.bounds = new google.maps.LatLngBounds();
        this.bounds.extend(marker.position);
        this.map.fitBounds(this.bounds);
        this.markers.push(marker);
      },
      removeMarker(marker) {
        marker.setMap(null)
      },
      openComponent() {
        this.$router.push('/add-restaurant/');
      }
    },
    computed: {
    }
  };
</script>

Я ожидаю, что границы получатся и мне удастся реализовать их так же, как и весь остальной код, скорее через метод, вызываемый в другом месте. Спасибо за вашу помощь.

1 Ответ

0 голосов
/ 26 апреля 2019

Предупреждение: это хак. Вместо:

this.map.fitBounds(this.bounds);

Попробуйте сделать это:

this.$nextTick(() => {
  this.map.fitBounds(this.bounds);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...