高德地图-获取定位-失败原因-浏览器定位异常场景

1.最近接触一个项目,需要用到地图定位相关内容,使用第三方高德地图,一开始使用浏览器自带的api去请求获取经纬度,但是谷歌浏览器限制,包括用户授权,等问题,各种因素影响.

// 浏览器自带api获取位置
// async function getLocation() {
//   try {
//     if (navigator.geolocation) {
//       navigator.geolocation.watchPosition(
//         async (position) => {
//           spinLoading.value = true;
//           const latitude = position.coords.latitude;
//           const longitude = position.coords.longitude;
//           data.longitude = longitude;
//           data.latitude = latitude;
//           console.log("传参数据:", data);
//           map.value.setCenter([longitude, latitude]);
//           await getOverviewList();
//         },
//         (err) => {
//           if (err.code == 1) {
//             console.log("erro", err);
//             spinLoading.value = false;
//             getOverviewList();
//           } else if (err.code == 2) {
//             console.log("erro", err);
//             message.error("请求超时");
//             spinLoading.value = false;
//             getOverviewList();
//           }
//         }
//       );
//     }
//   } catch (error) {
//     spinLoading.value = false;
//     message.error("发生错误,请重试");
//   }
// }

提示:也能实现,但是需要https协议,而且请求时间很长,要么你用梯子,还是不太合适.

2.如果只是获取城市,其实可以利用高德api去获取经纬度,可以优先使用精确定位(当前用户具体某一个位置),如果请求失败或者其他限制,可以考虑获取城市定位.

3.具体代码实现,相关配置,官方文档也有详细解释,主要核心代码

// 获取当前城市的经纬度
  AMap.plugin("AMap.Geolocation", () => {
    var geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 5000,
      zoomToAccuracy: true,
      showButton: true,
      buttonPosition: 'LB',
      panToLocation: true,
      GeoLocationFirst: true,
      // noIpLocate: 2
    });
    //先获取用户当前的精确位置
    geolocation.getCurrentPosition(async (status, result) => {
      console.log("精确定位", result)
      if (status == "complete") {
        const longitude = (result.position.lng).toFixed(1);//经度
        const latitude = (result.position.lat).toFixed(1);
        data.longitude = longitude;
        data.latitude = latitude;
        console.log("经纬度:", longitude, latitude);
        let position = new AMap.LngLat(longitude, latitude);
        console.log(position, 'position');
        // map.value.setCenter([longitude, latitude]);
        map.value.setCenter(position);
        // map.value.setZoomAndCenter(12, position);
        await getOverviewList();
      } else {
        //再获取城市的经纬度
        geolocation.getCityInfo(async (status, result) => {
          if (status == "complete") {
            console.log("城市定位", result)
            const longitude = (result.position[0]).toFixed(1);//经度
            const latitude = (result.position[1]).toFixed(1);
            data.longitude = longitude;
            data.latitude = latitude;
            console.log("经纬度:", longitude, latitude);
            let position = new AMap.LngLat(longitude, latitude);
            console.log(position, 'position');
            map.value.setCenter(position);
            // map.value.setZoomAndCenter(12, position);
            await getOverviewList();
          }
        })
      }
    })
  })

4.具体地图完整代码,可以根据自己的需求进行修改

//地图方法
async function initMap() {
  const AMap = await AMapLoader.load({
    key: apiKey, // 申请好的Web端开发者Key,首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
  });
  aMap.value = AMap; //用户获取地图maker
  map.value = new AMap.Map("container", {
    zoom: 10,
    // center: [data.longitude, data.latitude],
  });
  map.value.on('zoomend', () => {
    const zoom = map.value.getZoom(); // 获取当前缩放级别
    // 判断是否为地图缩小(zoom值增大)
    if (previousZoomLevel !== undefined && zoom < previousZoomLevel) {
      if (zoom <= 13 && zoom >= 12) {
        data.radius = "500";
      } else if (zoom <= 12 && zoom >= 11) {
        data.radius = "800";

      } else if (zoom <= 11 && zoom >= 10) {
        data.radius = "1000";

      } else if (zoom <= 10 && zoom >= 9) {
        data.radius = "1200";

      } else if (zoom <= 9 && zoom >= 8) {
        data.radius = "1500";

      } else if (zoom <= 8 && zoom >= 7) {
        data.radius = "2000";

      } else if (zoom <= 7 && zoom >= 6) {
        data.radius = "2200";

      } else if (zoom <= 6 && zoom >= 5) {
        data.radius = "2500";

      } else if (zoom <= 5 && zoom >= 3) {
        data.radius = "2800";

      }
    }
    previousZoomLevel = zoom;
  });
  AMap.plugin("AMap.ToolBar", function () {
    var opts = {
      position: "RB", // 设置为右上角
    };
    var toolbar = new AMap.ToolBar(opts); // 工具条
    map.value.addControl(toolbar);
  });
  AMap.plugin("AMap.Scale", function () {
    var opts = {
      position: "LT", // 设置为左上角
    };
    var Scale = new AMap.Scale(opts); //比例尺
    map.value.addControl(Scale);
  });
  // 获取当前城市的经纬度
  AMap.plugin("AMap.Geolocation", () => {
    var geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 5000,
      zoomToAccuracy: true,
      showButton: true,
      buttonPosition: 'LB',
      panToLocation: true,
      GeoLocationFirst: true,
      // noIpLocate: 2
    });
    //先获取用户当前的精确位置
    geolocation.getCurrentPosition(async (status, result) => {
      console.log("精确定位", result)
      if (status == "complete") {
        const longitude = (result.position.lng).toFixed(1);//经度
        const latitude = (result.position.lat).toFixed(1);
        data.longitude = longitude;
        data.latitude = latitude;
        console.log("经纬度:", longitude, latitude);
        let position = new AMap.LngLat(longitude, latitude);
        console.log(position, 'position');
        // map.value.setCenter([longitude, latitude]);
        map.value.setCenter(position);
        // map.value.setZoomAndCenter(12, position);
        await getOverviewList();
      } else {
        //再获取城市的经纬度
        geolocation.getCityInfo(async (status, result) => {
          if (status == "complete") {
            console.log("城市定位", result)
            const longitude = (result.position[0]).toFixed(1);//经度
            const latitude = (result.position[1]).toFixed(1);
            data.longitude = longitude;
            data.latitude = latitude;
            console.log("经纬度:", longitude, latitude);
            let position = new AMap.LngLat(longitude, latitude);
            console.log(position, 'position');
            map.value.setCenter(position);
            // map.value.setZoomAndCenter(12, position);
            await getOverviewList();
          }
        })
      }
    })
  })
}

当在网页中使用高德地图API遇到获取用户位置失败的情况,你可以尝试以下几个步骤来排查并解决问题: 1. **权限设置**:确保用户已授予地图服务访问他们地理位置的权限。通常在JavaScript中,你需要通过`Geolocation` API请求用户的定位信息,如果用户拒绝了这个请求,地图将无法获取。 ```javascript if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { alert("浏览器不支持地理定位"); } ``` 2. **网络连接**:如果用户的设备没有网络连接,或者网络信号差,也可能导致定位失败。检查设备网络状况并提示用户开启定位功能。 3. **API版本兼容性**:确认你使用的高德地图API版本是否支持地理位置获取高德地图文档应会提供最新版本的说明。 4. **代码错误**:检查你的地图初始化代码是否有误,特别是回调函数部分,确保处理定位结果的逻辑正确。 5. **跨域限制**:如果是在开发环境下的本地服务器运行,可能会因为同源策略(CORS)而无法获取位置。可以考虑配置服务器允许跨域请求,或者在本地搭建一个测试服务器。 6. **API密钥**:确保你的API密钥有效且适用于Web应用场景。如果没有,需要在官网申请合适的Key。 7. **更新到最新版本**:高德地图API有时会修复一些定位相关的bug,保持API至最新版本有助于解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值