vue使用高德地图

本文详细介绍了如何在Vue项目中集成高德地图,包括在index.html中引入地图脚本,vue.config.js中配置公共路径,以及在组件(map.vue)中实现地图功能的步骤。

1、在index.html文件中引入

<!-- 引入高德地图API -->
    <script type="text/javascript">
        window._AMapSecurityConfig = {
            securityJsCode: 'key值',
        }
    </script>
    <script type="text/javascript" src="http://webapi.amap.com/maps?v=2.0&key="></script>

2、在vue.config.js文件中添加

  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    externals: {
      'AMap': 'AMap',
      'AMapUI': 'AMapUI'
    }
  },

3、map.vue


<template>
  <div class="amap-page-container">
    <!-- 显示地图的div -->
    <div id="mapDiv" ref="mapDiv" style="width:100%;height:600px" class="mapDiv">
      loading...
    </div>
  </div>
</template>
<script>
import AMap from 'AMap'
export default {
  props: {
    center: { // 坐标
      type: Array,
      default: () => [100, 30]
    }
  },
  data() {
    return {
      map: null, // 地图对象
      zoom: 17,
      marker: null,
      mapCenter: [100, 30]
    }
  },
  watch: {
    center() {
      this.map.remove(this.marker)
      this.map.setCenter(this.center)
      this.addMarker({ longitude: this.center[0], latitude: this.center[1] })
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    // 初始化地图
    initMap() {
      const map = new AMap.Map('mapDiv', {
        center: this.center,
        resizeEnable: true,
        zoom: this.zoom,
        zooms: [10, 20],
        dataZooms: [10, 22]
        // mapStyle: 'amap://styles/099bd238d2de81d66fc23b41480d971e' // 地图样式ID
      })
      this.map = map
      this.addMarker({ longitude: this.center[0], latitude: this.center[1] })
    },
    addMarker(item) {
      const WGS = { lon: item.longitude, lat: item.latitude }
      this.marker = new AMap.Marker({
        position: [WGS.lon, WGS.lat],
        draggable: true,
        cursor: 'move'
      })
      this.marker.on('dragend', (e) => {
        this.$emit('changeCenter', { lng: e.lnglat.lng, lat: e.lnglat.lat })
      })
      this.marker.on('click', (e) => {
        this.$emit('click', { lng: e.lnglat.lng, lat: e.lnglat.lat })
      })
      // 将 markers 添加到地图
      this.map.add(this.marker)
    }
  }
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值