项目作者: zuley

项目描述 :
在Vue中完美的使用高德地图
高级语言: Vue
项目地址: git://github.com/zuley/vue-gaode.git
创建时间: 2017-08-11T02:23:13Z
项目社区:https://github.com/zuley/vue-gaode

开源协议:

关键词:
map vue2

下载


在Vue中完美的使用高德地图

最近项目中有使用到高德地图,搜了下发现饿了么的 vue-amap 比较知名。不过实际安装使用中发现还是有很多问题的,并不友好。不但要学习 amap 的文档,也还要学习原生高德API文档,还不如直接使用原生来的方便。

而这篇教程的目的就是,怎么在vue中使用高德地图API

文档:Demo和使用文档

运行项目

  1. # 安装依赖
  2. npm install
  3. # 运行项目
  4. npm run serve

实现思路

  • 创建一个 mapDrag 的公共组件
  • 在组件的 created 生命周期,载入高德地图API
  • API载入完成即开始执行地图初始化
  • 地图API暴露全局变量 window.AMap 可以直接使用
  • 监听地图拖放事件,获得数据后通知自定义事件,对组件外部提供事件接口

created 生命周期载入高德地图API

载入的方式类似于 jquery 的脚本加载,我这里也是使用了别人封装好的一个加载方法,各位直接使用或者自己改

  1. async created () {
  2. // 已载入高德地图API,则直接初始化地图
  3. if (window.AMap && window.AMapUI) {
  4. this.initMap()
  5. // 未载入高德地图API,则先载入API再初始化
  6. } else {
  7. await remoteLoad(`http://webapi.amap.com/maps?v=1.3&key=${MapKey}`)
  8. await remoteLoad('http://webapi.amap.com/ui/1.0/main.js')
  9. this.initMap()
  10. }
  11. }

初始化地图

在 methods 中创建一个 initMap 的方法供载入地图API之后调用。这里就可以使用任意高德API

  1. initMap () {
  2. // 加载PositionPicker,loadUI的路径参数为模块名中 'ui/' 之后的部分
  3. let AMapUI = this.AMapUI = window.AMapUI
  4. let AMap = this.AMap = window.AMap
  5. AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
  6. let mapConfig = {
  7. zoom: 16,
  8. cityName: MapCityName
  9. }
  10. if (this.lat && this.lng) {
  11. mapConfig.center = [this.lng, this.lat]
  12. }
  13. let map = new AMap.Map('js-container', mapConfig)
  14. // 加载地图搜索插件
  15. AMap.service('AMap.PlaceSearch', () => {
  16. this.placeSearch = new AMap.PlaceSearch({
  17. pageSize: 5,
  18. pageIndex: 1,
  19. citylimit: true,
  20. city: MapCityName,
  21. map: map,
  22. panel: 'js-result'
  23. })
  24. })
  25. // 启用工具条
  26. AMap.plugin(['AMap.ToolBar'], function () {
  27. map.addControl(new AMap.ToolBar({
  28. position: 'RB'
  29. }))
  30. })
  31. // 创建地图拖拽
  32. let positionPicker = new PositionPicker({
  33. mode: 'dragMap', // 设定为拖拽地图模式,可选'dragMap'、'dragMarker',默认为'dragMap'
  34. map: map // 依赖地图对象
  35. })
  36. // 拖拽完成发送自定义 drag 事件
  37. positionPicker.on('success', positionResult => {
  38. // 过滤掉初始化地图后的第一次默认拖放
  39. if (!this.dragStatus) {
  40. this.dragStatus = true
  41. } else {
  42. this.$emit('drag', positionResult)
  43. }
  44. })
  45. // 启动拖放
  46. positionPicker.start()
  47. })
  48. }

调用

  1. <mapDrag @drag="dragMap" lat="22.574405" lng="114.095388"></mapDrag>