vue2使用高德vue-amap插件

1,333 阅读1分钟

基本配置

1.安装

npm install vue-amap --save

2.在main.js中引入

import VueMap from 'vue-amap';
Vue.use(VueMap);
VueAMap.initAMapApiLoader({
  key: '在高德开放平台申请的key值',
  plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor', 'AMap.Geolocation'],
  v: '1.4.4'
});
// 你在2021年12月02日以后申请的 key 需要配合你的安全密钥一起使用。(开放平台也有提示)
window._AMapSecurityConfig = {
  // 高德的安全密钥
  securityJsCode: 'xxx js code',
}

3.封装input进行联动的Map组件

// components/GMap/index.vue
<template>
  <el-amap class="amap-wrap" :style="{height: height + 'px'}" :zoom="zoom"
    :plugin="plugin" :events="events" :amap-manager="amapManager"
    :center="center" vid="amap-vue">
    <el-amap-marker :position="center"></el-amap-marker>
  </el-amap>
</template>
<script>
import { AMapManager } from 'vue-amap'
const amapManager = new AMapManager()
export default {
  name: 'GMap',
  props: {
    position: {
      type: Object,
      default: () => {
        return {
          lng: 116.407387,
          lat: 39.904179
        }
      }
    },
    /** input要和父级中input的id进行关联 */
    input: {
      type: String,
      default: 'input'
    },
    height: {
      type: [Number, String],
      default: 300
    }
  },
  data () {
    const self = this
    return {
      market: null,
      center: [188.59996, 31.197646],
      zoom: 12,
      lng: 0,
      lat: 0,
      loaded: false,
      amapManager,
      events: {
        init (o) {
          console.log(o, 'events init')
          let marker = self.marker = new AMap.Marker()
          marker.setMap(o)
          AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], function () {
            const autoOptions = {
              // 城市,默认全国
              // 使用联想输入的input的id
              input: self.input
            }
            const autocomplete = new AMap.Autocomplete(autoOptions)
            console.log(autocomplete, 'autocomplete')
            AMap.event.addListener(autocomplete, 'select', function (e) {
              console.log(e, 'slect event')
              const geocoder = new AMap.Geocoder()
              marker.setMap(null)
              marker = new AMap.Marker({
                position: e.poi.location
              })
              marker.setMap(o)
              o.setCenter(e.poi.location)
              geocoder.getAddress(e.poi.location, (status, res) => {
                // console.log(res, 'res') // 返回值
                if (status === 'complete' && res.regeocode) {
                  const address = res.regeocode.formattedAddress
                  const province = res.regeocode.addressComponent.province
                  const city = res.regeocode.addressComponent.city
                  const district = res.regeocode.addressComponent.district
                  // 向父级传值
                  self.$emit('change', {
                    lng: e.poi.location.lng,
                    lat: e.poi.location.lat,
                    address,
                    province,
                    city,
                    district
                  })
                }
              })
            })
          })

          self.amapManager.getMap().on('click', e => {
            const geocoder = new AMap.Geocoder()
            marker.setMap(null)
            marker = new AMap.Marker({
              position: e.lnglat
            })
            marker.setMap(o)
            geocoder.getAddress(e.lnglat, (status, res) => {
              console.log(status, 'status')
              console.log(res, 'res')
              if (status === 'complete' && res.regeocode) {
                console.log(res, 'click') // 返回值
                const address = res.regeocode.formattedAddress
                const province = res.regeocode.addressComponent.province
                const city = res.regeocode.addressComponent.city
                const district = res.regeocode.addressComponent.district
                // 向父级传值
                self.$emit('change', {
                  lng: e.lnglat.lng,
                  lat: e.lnglat.lat,
                  address,
                  province,
                  city,
                  district
                })
              }
            })
          })
        }
      },
      plugin: [{
        pName: 'Geolocation',
        events: {
          init (o) {
            console.log(o, 'plugin init')
            // o 是高德地图定位插件实例
            o.getCurrentPosition((status, result) => {
              console.log(result, 'result')
              if (result && result.position) {
                self.lng = result.position.lng
                self.lat = result.position.lat
                self.center = [self.lng, self.lat]
                self.loaded = true
                self.$nextTick()
              }
            })
          }
        }
      }]
    }
  },
  watch: {
    position: {
      handler (data) {
        if (data.lng) {
          this.center = [data.lng, data.lat]
          this.$forceUpdate()
        }
      },
      immediate: true
    }
  }
}
</script>

4. 解决eslint报错AMap没有被定义

.eslintrc.js文件中配置全局变量

module.exports = {
 global: {
    AMap: 'readonly'
  }
}

5.使用组件

// index.vue
<template>
  <div>
      <el-input v-model="value" id="input" placeholder="请输入关键词"></el-input>
      <GMap @change="change"></GMap>
  </div>
</template>

<script>
import GMap from '@/components/GMap/index.vue'
export default {
   name:"TestMap",
   components: {
      GMap
   },
   data () {
     return {
       value: ''
     }
   },
   methods: {
      change (data) {
        this.value = data.address;
        console.log(data, 'data')
      }
   }
}
<script>

6.效果展示

image.png