vue使用高德地图获取当前经纬度

本文介绍在Vue项目中如何利用高德地图API动态CDN引入,封装获取经纬度的方法,并通过Promise处理异步操作。同时,解决在Vue组件中使用AMap可能遇到的'AMap is not defined'问题。
摘要由CSDN通过智能技术生成

vue使用高德地图Api获取当前经纬度信息

在utils里面新建getLocation.js 封装获取经纬度的公用方法(优化加载速度动态cdn引入高德地图) 由于高德Api方法获取当前经纬度比较慢,如果需求是在获取到当前经纬度数据之后请求一些数据,需要搭配promise使用保证获取到经纬度信息。具体见下面代码

function loadSDK() {
   
  if (window.AMap) return
  return new Promise((resolve, reject) => {
   
    const script = document.createElement('script')
    script.src =
      'http://webapi.amap.com/maps?v=1.4.6&key=*****************' //***为申请的高德key
    document.head.appendChild(script)
    script.onload = resolve
    script.onerror = reject
  })
}

export default async () => {
   
  await loadSDK()
  return new Promise((resolve) => {
   
    // eslint-disable-next-line no-undef
    AMap.plugin('
可以使用`@amap/amap-jsapi-loader`库来加载高德地图JSAPI,并在Vue组件中使用。以下是一个示例代码: 首先,安装依赖: ```bash npm install @amap/amap-jsapi-loader ``` 然后,在Vue组件中使用: ```vue <template> <div ref="map" style="height: 400px;"></div> </template> <script> import AMapLoader from '@amap/amap-jsapi-loader'; export default { name: 'AmapDemo', data() { return { map: null, marker: null, }; }, mounted() { AMapLoader.load({ key: 'your_amap_key', version: '2.0', plugins: ['AMap.Geocoder'], }).then((AMap) => { const map = new AMap.Map(this.$refs.map, { zoom: 13, center: [116.39, 39.9], }); map.on('click', (e) => { const geocoder = new AMap.Geocoder({ city: '全国', }); geocoder.getAddress([e.lnglat.getLng(), e.lnglat.getLat()]).then((result) => { const address = result.regeocode.formattedAddress; const position = [e.lnglat.getLng(), e.lnglat.getLat()]; if (this.marker) { this.marker.setPosition(position); } else { this.marker = new AMap.Marker({ position, map, }); } console.log('Address:', address); console.log('Position:', position); }); }); this.map = map; }); }, }; </script> ``` 在上面的代码中,我们首先使用`AMapLoader.load`方法加载高德地图JSAPI,并在`then`方法中初始化地图。 然后,我们在地图上添加一个`click`事件,当用户点击地图时,我们使用`AMap.Geocoder`插件获取该位置的地址和经纬度,并将其打印到控制台中。如果已经存在标记,则更新标记的位置,否则创建一个新的标记。 注意,在上面的示例代码中,我们需要将`your_amap_key`替换为你自己的高德地图开发者Key。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值