vue-cli3.0高德地图初始当前定位出错

83 阅读1分钟

浏览器引用高德地图定位AMap.Geolocation 插件来实现定位,初始页面时获取当前定位一直说超时“Get ipLocation failed.Get geolocation timeout”

const initMap = async () => {
    let AMap: any = await AMapLoader.load({
        key: "创建高德地图web类型的key",
        version: "2.0",
        plugins: [
            "AMap.MapType",
            "AMap.Geolocation",
            "AMap.Geocoder",
            "AMap.AMapUI",
        ],
    });
    map.value = new AMap.Map("container", {
        viewMode: "2D",
        zoomEnable: true,
        dragEnable: true,
        doubleClickZoom: true,
        zoom: 12,
        plugin: [
            //一些工具插件
            {
                pName: "MapType", //地图类型
                defaultType: 0,
                events: {
                    init(instance) {},
                },
            },
        ],
    });
    // 缩放地图到合适的视野级别
    map.value.setFitView();
    const geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, // 是否使用高精度定位,默认:true
        timeout: 10000, // 超过10秒后停止定位,默认:无穷大
        panToLocation: true, //定位成功后将定位到的位置作为地图中心点,默认:true
        showButton: true, //显示定位按钮,默认:true
        buttonPosition: "LB",
        buttonOffset: new AMap.Pixel(10, 20),
    });
    map.value.addControl(geolocation);
    geolocation.getCurrentPosition((status: any, result: any) => {
        if (status === "complete") {
            getMarker(result.position.lat, result.position.lng);
            console.log("当前用户位置信息:", result);
        } else {
            console.log("定位出错", result);
            ElMessageBox({
                title: '温馨提示',
                message: '获取当前定位失败,请手动填写当前位置',
                confirmButtonText: '知道了',
            })
        }
    });
};
// 初始标识定位
const getMarker = (lat,lng) => {
    marker.value = new AMap.Marker({
        position: new AMap.LngLat(lat, lng),
        map: map.value,
        draggable: true, //允许拖拽
    });
    map.value.add(marker.value);
};

8403a9dfec482bcfc9e8005187bfa2e.png 反馈给官方官方回复说Chrome浏览器国内没有提供服务,高德是使用浏览器的Geolocation定位,建议使用edge 浏览器,目前Edge对定位兼容较好

d02fbff1730f4b6d7c4fc9a92bd63ce.png 开发环境时调用失败:Get ipLocation failed.Geolocation permission denied.是需要浏览器在安全的上下文来使用地理定位API,所以需要将http调整为https 我们在vue.config.js文件中设置https:true

module.exports = defineConfig({
    devServer: {
        port: 8099,
        https: true
    },
)}