温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在vue-cli中使用高德地图api

发布时间:2021-04-07 15:54:54 阅读:406 作者:Leah 栏目:web开发
Vue开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

如何在vue-cli中使用高德地图api?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

第一步 去高德地图开放平台申请密钥  高德地图开放平台

第二部 在vue-cli项目目录结构 

如何在vue-cli中使用高德地图api

里面多了config文件夹和 utils文件夹 

config.js里面是这样的  主要是导出密钥 

// 高德地图 key
export const MapKey = '你的密钥key'
// 地图限定城市
export const MapCityName = '武汉'

utils文件夹里面 新建路一个remoteLoad.js

主要是动态创建script标签 封装了一个函数 传入URL地址()

export default function remoteLoad (url, hasCallback) {
 return createScript(url)
 /**
  * 创建script
  * @param url
  * @returns {Promise}
  */
 function createScript (url) {
  var scriptElement = document.createElement('script')
  document.body.appendChild(scriptElement)
  var promise = new Promise((resolve, reject) => {
   scriptElement.addEventListener('load'e => {
    removeScript(scriptElement)
    if (!hasCallback) {
     resolve(e)
    }
   }, false)

   scriptElement.addEventListener('error'e => {
    removeScript(scriptElement)
    reject(e)
   }, false)

   if (hasCallback) {
    window.____callback____ = function () {
     resolve()
     window.____callback____ = null
    }
   }
  })

  if (hasCallback) {
   url += '&callback=____callback____'
  }

  scriptElement.src = url

  return promise
 }

 /**
  * 移除script标签
  * @param scriptElement script dom
  */
 function removeScript (scriptElement) {
  document.body.removeChild(scriptElement)
 }
}

第三步 在Home组件中

<template>
 <div class="m-map">
  <div class="search" v-if="placeSearch">
   <input type="text" placeholder="请输入关键字" v-model="searchKey">
   <button type="button" @click="handleSearch">搜索</button>
   <div id="js-result" v-show="searchKey" class="result"></div>
  </div>
  <div id="js-container" class="map"></div>
 </div>
</template>

<script>
import remoteLoad from '@/utils/remoteLoad.js'
import { MapKeyMapCityName } from '@/config/config'
export default {
 props: ['lat''lng'],
 data () {
  return {
   searchKey'',
   placeSearchnull,
   dragStatusfalse,
   AMapUInull,
   AMapnull
  }
 },
 watch: {
  searchKey () {
   if (this.searchKey === '') {
    this.placeSearch.clear()
   }
  }
 },
 methods: {
  // 搜索
  handleSearch () {
   if (this.searchKey) {
    this.placeSearch.search(this.searchKey)
   }
  },
  // 实例化地图
  initMap () {
   // 加载PositionPicker,loadUI的路径参数为模块名中 'ui/' 之后的部分
   let AMapUI = this.AMapUI = window.AMapUI
   let AMap = this.AMap = window.AMap
   AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
    let mapConfig = {
     zoom16,
     cityNameMapCityName
    }
    if (this.lat && this.lng) {
     mapConfig.center = [this.lngthis.lat]
    }
    let map = new AMap.Map('js-container', mapConfig)
    // 加载地图搜索插件
    AMap.service('AMap.PlaceSearch'() => {
     this.placeSearch = new AMap.PlaceSearch({
      pageSize5,
      pageIndex1,
      citylimittrue,
      cityMapCityName,
      map: map,
      panel'js-result'
     })
    })
    // 启用工具条
    AMap.plugin(['AMap.ToolBar'], function () {
     map.addControl(new AMap.ToolBar({
      position'RB'
     }))
    })
    // 创建地图拖拽
    let positionPicker = new PositionPicker({
     mode'dragMap'// 设定为拖拽地图模式,可选'dragMap'、'dragMarker',默认为'dragMap'
     map: map // 依赖地图对象
    })
    // 拖拽完成发送自定义 drag 事件
    positionPicker.on('success'positionResult => {
     // 过滤掉初始化地图后的第一次默认拖放
     if (!this.dragStatus) {
      this.dragStatus = true
     } else {
      this.$emit('drag', positionResult)
     }
    })
    // 启动拖放
    positionPicker.start()
   })
  }
 },
 async created () {
  // 已载入高德地图API,则直接初始化地图
  if (window.AMap && window.AMapUI) {
   this.initMap()
  // 未载入高德地图API,则先载入API再初始化
  } else {
   await remoteLoad(`http://webapi.amap.com/maps?v=1.3&key=${MapKey}`)
   await remoteLoad('http://webapi.amap.com/ui/1.0/main.js')
   this.initMap()
  }
 }
}
</script>

<style lang="css">
.m-mapmin-width500pxmin-height300pxposition: relative; }
.m-map .mapwidth100%height100%; }
.m-map .searchposition: absolute; top10pxleft10pxwidth285pxz-index1; }
.m-map .search inputwidth180pxborder1px solid #cccline-height20pxpadding5pxoutline: none; }
.m-map .search buttonline-height26pxbackground#fffborder1px solid #cccwidth50pxtext-align: center; }
.m-map .resultmax-height300pxoverflow: auto; margin-top10px; }
</style>

第四步  在app.vue中 导入组件

<template>
 <div id="app">
  <div class="g-wraper">
   <div class="m-part">
    <mapDrag @drag="dragMap" class="mapbox"></mapDrag>
   </div>
  </div>

 </div>
</template>

<script>
import mapDrag from './components/Home.vue'
export default {
 name'app',
 components: {
  mapDrag
 },
 data () {
  return {
   dragData: {
    lngnull,
    latnull,
    addressnull,
    nearestJunctionnull,
    nearestRoadnull,
    nearestPOInull
   }
  }
 },
 methods: {
  dragMap (data) {
   console.log(data)
   this.dragData = {
    lng: data.position.lng,
    lat: data.position.lat,
    address: data.address,
    nearestJunction: data.nearestJunction,
    nearestRoad: data.nearestRoad,
    nearestPOI: data.nearestPOI
   }
  }
 }
}
</script>

<style>
bodymargin0; }
.page-header{
 color#ffftext-align: center; background#159957;
 background-image-webkit-linear-gradient(330deg,#155799,#159957);
 background-imagelinear-gradient(120deg,#155799,#159957);
 padding3rem 4remmargin-bottom30px;
}
.page-header h2margin0font-size40px; }
.page-header pcolor#cccmargin0margin-bottom30px; }
.page-header adisplay: inline-block; border1px solid #fffmargin-right10pxline-height40pxpadding0 20pxborder-radius4pxcolor#ffftext-decoration: none; transition: all .3s; }
.page-header a:hoverbackground#fffcolor#333; }
.g-wraperwidth1000pxmargin0 auto; color#666font-size16pxline-height30px; }
.m-partmargin-bottom30px; }
.m-part::aftercontent''display: block; clear: both; }
.m-part .titlefont-size30pxline-height60pxmargin-bottom10pxcolor#333; }
.m-part .mapboxwidth600pxheight400pxmargin-bottom20pxfloat: left; }
.m-part .infomargin0padding0list-style: none; line-height30pxmargin-left620px; }
.m-part .info spandisplay: block; color#999; }
.m-part olline-height40pxmargin-left0padding-left0; }
.m-part pre{ padding10px 20pxline-height30pxborder-radius3pxbox-shadow0 0 15px rgba(0,0,0,.5); }
.m-footerbackground#eeeline-height60pxtext-align: center; color#999font-size12px; }
.m-footer amargin0 5pxcolor#999text-decoration: none; }
</style>

关于如何在vue-cli中使用高德地图api问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×