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

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();
          }
        })
      }
    })
  })
}

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue2中,可以使用高德地图API来获取当前定位。首先,需要引入高德地图的SDK,并在Vue组件中使用AMap.Geolocation来获取当前位置的经纬度信息。以下是一个示例代码: 首先,在utils文件夹中创建一个名为getLocation.js的文件,用于封装获取经纬度的公用方法。该方法使用了Promise来确保在获取到经纬度信息后再进行后续操作。具体代码如下: ```javascript 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) => { AMap.plugin('AMap.Geolocation', () => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: false }); geolocation.getCurrentPosition((status, result) => { const res = status === 'complete' ? result.position : { lat: 39.909187, lng: 116.397451 }; // 默认北京 116.397451、39.909187 console.log('定位结果', res); resolve(res); }); }); }); } ``` 然后,在Vue组件中,可以通过调用上述封装的方法来获取当前定位的经纬度信息。具体代码如下: ```javascript import getLocation from '@/utils/getLocation'; export default { methods: { async getCurrentLocation() { try { const position = await getLocation(); // 在这里可以使用获取到的经纬度信息进行后续操作 console.log('当前定位经纬度', position); } catch (error) { console.error('获取定位失败', error); } }, }, mounted() { this.getCurrentLocation(); }, }; ``` 以上代码中,通过调用`getLocation`方法来获取当前定位的经纬度信息,并在`getCurrentLocation`方法中进行后续操作。在Vue组件的`mounted`钩子函数中调用`getCurrentLocation`方法来获取当前定位信息。 请注意,上述代码中的高德地图SDK的引入地址和申请的key需要根据实际情况进行修改。 #### 引用[.reference_title] - *1* *2* [(2023进阶版)vue+h5 通过高德地图(原生) 获取当前位置定位](https://blog.csdn.net/yangzixiansheng/article/details/131308415)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [vue使用高德地图获取当前经纬度](https://blog.csdn.net/V_AYA_V/article/details/105275063)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值