在vue中使用高德地图

问题来源

项目需要是使用到地图,并不是所有页面都用到,所以采用异步加载当时引入地图

开始

在vue项目目录下创建plugins文件夹,并在里面创建amap.js 文件

/*
 * 异步创建script标签 
 */
export default function MapLoader (key) { 
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      resolve(window.AMap)
    } else {
      var script = document.createElement('script')
      script.type = 'text/javascript'
      script.async = true
      script.src = 'http://webapi.amap.com/maps?v=1.3&callback=initAMap&key=' + key
      script.onerror = reject
      document.head.appendChild(script)
    }
    window.initAMap = () => {
      resolve(window.AMap)
    }
  })
}
<template>
  <div class="test">
    <div id="container" style="height:300px;width:300px;"></div>
  </div>
</template>
<script>
import MapLoader from '@/plugins/amap.js'
export default {
  name: 'test',
  data () {
    return {
      map: null
    }
  },
  mounted () {
    let that = this
    MapLoader().then(AMap => {
      console.log('地图加载成功')
      that.map = new AMap.Map("container", {
        resizeEnable: true
      });
    }, e => {
      console.log('地图加载失败' ,e)
    })
  }
}
</script>

在项目中使用

  • 还是使用我们上一个项目,那个MintUI的,不是有一个附近的板块么,我们就用这个
  • cd到项目目录
  • 安装Vue-amap
# cnpm install vue-amap --save

 

安装成功

  • 在main.js引入
import AMap from 'vue-amap';
Vue.use(AMap);
AMap.initAMapApiLoader({
    key: 'XXXXX',//刚刚开发者申请哪里的key
    plugin: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType']
});
  • 在Near.vue中调用
<template>
    <div id="near">
      <div id="amap-main">

      </div>
    </div>
</template>
<script type="text/ecmascript-6">
  import { lazyAMapApiLoaderInstance } from 'vue-amap';
  export default{
    name:'near',
    mounted() {
      lazyAMapApiLoaderInstance.load().then(() => {
        this.map = new AMap.Map('amap-main', {center: new AMap.LngLat(121.59996, 31.197646)});
      });
    }
  }
</script>
<style lang="stylus">
  #near
    #amap-main
      height 300px
</style>

 

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值