vue中使用高德地图 (亲测好用!)

在网上找了好久,虽然说方法都大致相同,但只有这个在最新的vue中直接复制进去就可以用了,写的很清楚,感谢作者!

问题来源

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

开始

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


 
 
  1. /*
  2. * 异步创建script标签
  3. */
  4. export default function MapLoader (key) {
  5. return new Promise( (resolve, reject) => {
  6. if ( window.AMap) {
  7. resolve( window.AMap)
  8. } else {
  9. var script = document.createElement( 'script')
  10. script.type = 'text/javascript'
  11. script.async = true
  12. script.src = 'http://webapi.amap.com/maps?v=1.3&callback=initAMap&key=' + key
  13. script.onerror = reject
  14. document.head.appendChild(script)
  15. }
  16. window.initAMap = () => {
  17. resolve( window.AMap)
  18. }
  19. })
  20. }

 
 
  1. <template>
  2. <div class="test">
  3. <div id="container" style="height:300px;width:300px;"> </div>
  4. </div>
  5. < /template>
  6. <script>
  7. import MapLoader from '@/plugins/amap.js '
  8. export default {
  9. name: 'test ',
  10. data () {
  11. return {
  12. map: null
  13. }
  14. },
  15. mounted () {
  16. let that = this
  17. MapLoader().then(AMap => {
  18. console.log('地图加载成功 ')
  19. that.map = new AMap.Map("container", {
  20. resizeEnable: true
  21. });
  22. }, e => {
  23. console.log('地图加载失败 ' ,e)
  24. })
  25. }
  26. }
  27. </script>

在项目中使用

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

 
 

 

安装成功

  • 在main.js引入

 
 
  1. import AMap from 'vue-amap';
  2. Vue.use(AMap);
  3. AMap.initAMapApiLoader({
  4. key: 'XXXXX', //刚刚开发者申请哪里的key
  5. plugin: [ 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType']
  6. });
  • 在Near.vue中调用

 
 
  1. <template>
  2. <div id="near">
  3. <div id="amap-main">
  4. </div>
  5. </div>
  6. </template>
  7. <script type="text/ecmascript-6">
  8. import { lazyAMapApiLoaderInstance } from 'vue-amap';
  9. export default{
  10. name: 'near',
  11. mounted() {
  12. lazyAMapApiLoaderInstance.load().then( () => {
  13. this.map = new AMap.Map( 'amap-main', { center: new AMap.LngLat( 121.59996, 31.197646)});
  14. });
  15. }
  16. }
  17. </script>
  18. <style lang="stylus">
  19. #near
  20. #amap-main
  21. height 300 px
  22. </style>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值