有些项目我们需要用到地图相关的能力,当我们在vue项目中需要使用高德地图的时候,vue-amap是个比较好的选择,vue-amap是一套基于Vue 2.0和高德地图的地图组件,它帮你封装了一遍,相对直接使用高德地图,它使用起来更加简单。用起来难免会遇到一些坑,在此记录一下:

1.使用的时候有时候会报 TypeError: v.w.uh is not a constructor ,然后地图就显示不出来,刷新又好了。这是由于地图实例是异步加载的当使用地图的页面开始加载地图的时候地图还没完成初始化而获取不到地图实例造成的。

 
解决办法:不在main.js中初始化而在使用地图的页面中初始化地图,并且要在该页面初始化之前。

<script>
import VueAMap from 'vue-amap';

VueAMap.initAMapApiLoader({
  key: '....',
  plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor'],
  // 默认高德 sdk 版本为 1.4.4
  v: '1.4.4'
});

  export default {
   ...
  }

</script>

2.在一个页面中使用了两次相同的地图,但只显示了一个地图出来,另一个无法显示。

那很有可能是因为你的组件vid是同一个,我们在使用时传入不同的vid值就可以了

<el-amap :vid="vid" :center="mapCenter" :zoom="12" class="amap-demo">
   <el-amap-marker
       v-for="(marker, index) in markers"
       :key="index"
        :position="marker"
   ></el-amap-marker>
 </el-amap>

3.搜索组件 不限定城市,可以搜索全国

searchOption: {
   city: '全国',
   citylimit: true
 },

//或
searchOption: {
  city: '深圳', //某个城市
  citylimit: false
}

4.AMap.Geocoder地理编码与逆地理编码类,用于地址描述与坐标之间的转换,即实现通过地址名称获取经纬度或通过经纬度获取地址信息。具体看文档

//使用方法:在初始化地图的时候的 plugins选项加上 AMap.Geocoder

VueAMap.initAMapApiLoader({
  key: 'xxx',
  plugin: [xxxxx, 'AMap.Geocoder'],
  v: '1.4.4'
});

//模版上使用 以搜索组件为例

<el-amap :vid="vid" :center="mapCenter" :zoom="12" class="amap-demo" :events="events">
   <el-amap-marker
      v-for="(marker, index) in markers"
      :key="index"
      :position="marker"
   ></el-amap-marker>
</el-amap>

//data中定义事件处理程序
 data() {
   return {
     events: {
          click: e => { 
            //获取经纬度
            let arr = [e.lnglat.lng, e.lnglat.lat];
            let geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: 'all'
            })
            geocoder.getAddress(arr, function(status, result) {
              if (status === 'complete' && result.info === 'OK') {
                //result字段就是根据经纬度解析后的地址信息
              }
            })
          }
        }
      };
    },

//如果需要通过地址名称来解析经纬度,使用geocoder.getLocation方法即可

5.AMap.Autocomplete is not a construct; AMap.Geocoder is not a construct报错;

//在index.html引入 
<script type="text/javascript"
    src="https://webapi.amap.com/maps?v=1.4.4&key=xxx&plugin=AMap.Geocoder&plugin=AMap.Autocomplete"></script>

 

Logo

前往低代码交流专区

更多推荐