【学习笔记】H5使用高德地图api获取定位

1,927 阅读2分钟

在开发H5需要获取定位的业务时,可以用到以下的方法:

const GDkey = ''; // 高德地图的key
function MapLoader(key) {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      resolve(window.AMap)
    } else {
      var script = document.createElement('script')
      script.type = 'text/javascript'
      script.async = true
      script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${key}&callback=onLoad`
      script.onerror = reject
      document.head.appendChild(script)
    }
    window.initMap = () => {
      resolve(window.AMap)
    }
  })
}

/**
 * 有个地方需要注意,页面刚挂载完的时候,<script>还没添加到document里,需要在index.html里面先引入
 * <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=申请的key"></script>
 */

/**
* @description 高德地图获取定位
*/
function GDLocation() {
    return new Promise((resolve, reject) => {
      // 高德定位
      MapLoader(GDkey).then(
        (AMap: any) => {
          // 浏览器定位
          AMap.plugin('AMap.Geolocation', function() {
            const geolocation = new AMap.Geolocation({
              enableHighAccuracy: true, //是否使用高精度定位,默认:true
              timeout: 10000, //超过10秒后停止定位,默认:无穷大
              maximumAge: 0, //定位结果缓存0毫秒,默认:0
              convert: true, //自动偏移坐标,偏移后的坐标为高德坐标,默认:true
              showButton: true, //显示定位按钮,默认:true
              buttonPosition: 'LB', //定位按钮停靠位置,默认:'LB',左下角
              buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
              showMarker: true, //定位成功后在定位到的位置显示点标记,默认:true
              showCircle: true, //定位成功后用圆圈表示定位精度范围,默认:true
              panToLocation: true, //定位成功后将定位到的位置作为地图中心点,默认:true
              zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
            });

            geolocation.getCurrentPosition();
            AMap.event.addListener(geolocation, 'complete', onComplete);
            AMap.event.addListener(geolocation, 'error', onError);

            function onComplete(data: any) {
              // data是具体的定位信息
              const latitude = data.position.lat; // 纬度
              const longitude = data.position.lng; // 经度
              const location = {
                latitude: longitude,
                longitude: latitude,
              };
              resolve(location);
            }

            function onError(data: any) {
              // 定位出错
              const location = ref({
                latitude: '',
                longitude: '',
              });
              resolve(location);
              let errorType = data.message;
              switch (errorType) {
                case 'Browser not Support html5 geolocation.':
                  Toast('浏览器不支持原生定位接口');
                  break;
                case 'Geolocation permission denied.':
                  Toast('定位不支持http,请升级https站点');
                  break;
                case 'Get geolocation failed.':
                  Toast('定位失败');
                  break;
                case 'Get geolocation time out.':
                  Toast('定位超时');
                  break;
                case 'Get geolocation time out.Get ipLocation failed.':
                  Toast('定位超时');
                  break;
                default:
                  Toast(errorType);
              }
            }
          });
        },
        (e: any) => {
          console.log('地图加载失败', e);
        },
      );
    });
}

高德地图api获取定位的链接:https://lbs.amap.com/api/javascript-api/guide/services/geolocation
学习出处:https://www.jianshu.com/p/f65034cf7d24