Vue使用谷歌地图放置自动完成组件

347 阅读1分钟

第一步,下载谷歌地图插件

谷歌地图版本"google": "^2.1.0", 谷歌插件版本"vue2-google-maps": "^0.10.7",

第二步,main.js引用和配置

import * as VueGoogleMaps from 'vue2-google-maps';

Vue.use(VueGoogleMaps, { load: { key: '*********************', libraries: 'places', region: 'VI', // 这个地区自己定 language: googleLang[i18n.locale]??'Ja' // 这个语言自己定 zh-CN https://developers.google.com/maps/faq#languagesupport 支持语言参数 }, installComponents: true })

第三步,使用

<GmapAutocomplete @place_changed="setPlace" ref="mapname" id="pac-input" type="primary" /> <GmapMap :center="center" :draggable="true" :zoom="16"> <GmapMarker :zoom="16" :key="index" v-for="(m, index) in markers" :position="m.position" @click="center = m.position" /> </GmapMap> zoom 控制地图比例放大和缩小,markers是红色标记地点

data() {
    return {
      place: null,
      center: { lat: "", lng: "" },
      currentPlace: null,
      markers: [],
      places: [],
    };
  },
created() {
      this.center.lat = //lat 坐标,类型sumber
      this.center.lng =  //lng 坐标,类型sumber
      this.markers.push({ position: this.center }); //在地图上标注上面坐标点,给予红色标记号
  },
    methods: {
    setPlace(place) {
      this.currentPlace = place;
      this.addMarker();
    },
    addMarker() {
      if (this.currentPlace) {
        const marker = {
          lat: this.currentPlace.geometry.location.lat(),
          lng: this.currentPlace.geometry.location.lng(),
        };
        this.markers.push({ position: marker });
        this.places.push(this.currentPlace);
        this.center = marker;
        this.currentPlace = null;
      }
    },
    geolocate: function () {
      navigator.geolocation.getCurrentPosition((position) => {
        this.center = {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        };
      });
    },
  },