在Vue中使用高德地图(原生,不是vue-amap)

3,873 阅读2分钟

由于工作需要使用高德地图,之前一直使用的是vue-amap。

甲方突然来了需求,要在地图上不显示地名、城市等文本标注,因为他们觉得那样会比较乱。没办法,改吧,感觉这个应该是比较简单的。然后去查高德地图API文档,发现只能在初始化AMap.Map对象的时候添加showLabel:false进行设置。但是在vue-amap的文档和找了半天,没有;又去看vue-amap的源码,发现vue-amap是将el-amap组件传入的props作为初始化AMap.Map对象的option,而el-amap组件压根就没有设置showLabel的prop!破案了,不纠结了,改用原生的高德地图。

1. 引入JSAPI

在项目根目录下的模板index.html中引入下面2个JSAPI

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.4&key=你申请的Key"></script>
<script type="text/javascript" src="//webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script>

2. 声明externals

因为是通过script标签引入的,所以要在webpack中将引入的库声明为外部扩展,否则在模块中导入时找不到。 如果是vue-cli2的话,直接到build文件夹下的webpack配置文件中添加就行;如果是vue-cli3的话,自己在项目根目录下建一个vue.config.js文件,添加下面的externals配置,然后重启项目,刷新界面。

entry: {
  。。。
},

externals: {
   "AMap": "AMap",
},

3. 初始化地图

在需要地图的组件中引入依赖:

import AMap from 'AMap';

指定一个DOM元素用于渲染地图。

const dom = document.getElementById('amapArea');

初始化地图对象。


this.map = new AMap.Map(dom, {
   resizeEnable: true,
   zoom: 10,
   center: [116.397428, 39.90923],
   showLabel: false //不显示地图文字标记, 终于可以配置了TAT
});

终于能够配置了,没有地图文字标注,YES!

image.png

这下可以随心所以地根据高德地图的官方文档直接进行处理,不用再经过vue-amap倒一手了。

4. 其他功能

举几个例子

4.1 定义样式

可以使用官方提供的,也可以在编辑器中自己定义。

this.map.setMapStyle('amap://styles/darkblue');

image.png

4.2 添加marker

marker就是地图上的标注。默认是蓝色的倒立水滴。

let marker = new AMap.Marker({
   position: [118.790606, 32.047292],
})
marker.setMap(this.map);

image.png

也可以自定义content。

     let marker = new AMap.Marker({
        position: [118.790606, 32.047292],
        content: `
            <div style="display: flex; flex-direction: column; align-items: center">
                <div style="width: 30px; height: 30px; border-radius: 50%; background-color: #00faff;"></div>
                <div style="width: 50px; font-size: 12px; text-align: center; color: white; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; margin-top: 4px;">新接口</div>
            </div>
        `
      })
      marker.setMap(this.map);

image.png