首先能翻墙 不然啥也看不见 然后去谷歌官方申请一个key 这里不赘述

1.安装vue2-google-maps

npm install vue2-google-maps

2.main.js内引用谷歌地图

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

Vue.use(VueGoogleMaps, {
  load: {
    key: 'AIz***************S7rJz1KY',
    libraries: 'places',
    region: 'VI', // 这个地区自己定
    language: 'en' // 这个语言自己定
  },
  installComponents: true
})

3.页面内引用


<template>
  <gmap-map :center="centers" :zoom="11" style="width: 300px; height: 300px" @click="updateMaker">
    <gmap-marker :position="position" :draggable="true" @dragend="updateMaker"/>
  </gmap-map>
</template>
<script>
import axios from 'axios';
import { gmapApi } from 'vue2-google-maps'

export default {
  props: {
    position: {
      type: Object,
      default: () => {
        return {
          lat: 43.648509660046656,
          lng: -79.3789402652274
        }
      }
    }
  },
  data() {
    return {
      place: null
    };
  },
  computed: {
    google: gmapApi, // 获取官方的OBject 使用官方API的时候可以用
    centers() {
      return {
        lat: this.position.lat,
        lng: this.position.lng
      }
    }
  },
  created() {},
  mounted() {

  },
  methods: {
    updateMaker: function(event) {
      console.log('updateMaker, ', event.latLng.lat(), event.latLng.lng());
      this.position = {
        lat: event.latLng.lat(),
        lng: event.latLng.lng()
      }
      this.pointToAddress(this.position.lat, this.position.lng, this.pushAddress)
    },
    pushAddress(res) {
      this.$emit('mark', res, this.position)
    },
    pointToAddress(lat, lng, backcall) {
      // 实例化Geocoder服务用于解析地址
      var geocoder = new this.google.maps.Geocoder();
      // 地理反解析
      geocoder.geocode({ location: new this.google.maps.LatLng(lat, lng) }, function geoResults(results, status) {
        if (status === this.google.maps.GeocoderStatus.OK) {
          backcall(results[0].formatted_address);
        } else {
          console.log(':error ' + status);
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
</style>

以上 gmap-marker 是定位点组件,支持传入坐标展示定位点。pointToAddress方法支持获取你选的点的地理位置信息,当然这个方法是vue2-google-maps自己封装的,你也可以自己封装,比他这个好用,具体方式参考谷歌地图API文档

Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐