浏览器获取当前位置信息

180 阅读1分钟

获取当前位置信息

`

// 获取位置信息 需要调用百度地图的api 
// 浏览器获取位置信息会有兼容和问题,谷歌上可能把国内位置给墙了

方式一:

    // 初始化地图
var map = new BMapGL.Map("map-container");
map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 15); // 初始中心点和缩放级别

// 创建 Geolocation 对象
var geolocation = new BMapGL.Geolocation();


// 获取当前位置
geolocation.getCurrentPosition(function (result) {
console.log(result)
if (this.getStatus() === BMAP_STATUS_SUCCESS) {
    // 获取当前位置的经纬度
    let latitude = result.point.lat;
    let longitude = result.point.lng;
    console.log("Latitude:", latitude);
    console.log("Longitude:", longitude);

    // // 在地图上标记当前位置
    // var point = new BMap.Point(longitude, latitude);
    // map.centerAndZoom(point, 15); // 将地图中心点设置为当前位置
    // var marker = new BMap.Marker(point); // 创建标注
    // map.addOverlay(marker); // 将标注添加到地图
} else {
    console.error("Failed to get location:", this.getStatus());
}
//      let latitude = result.point.lat;
//     let longitude = result.point.lng;
//     console.log("Latitude:", latitude);
//     console.log("Longitude:", longitude);

//     // 在地图上标记当前位置
//     var point = new BMapGL.Point(longitude, latitude);
// map.centerAndZoom(point, 15)
}, { enableHighAccuracy: true }); // 启用高精度模式


// 缺点是在谷歌上响应慢

//方式二 可以高效的得到位置信息

        var myGeo = new BMapGL.Geocoder();
              var localcity = new BMapGL.LocalCity();
              var that = this;
              localcity.get((e) => {
                // 根据坐标得到地址描述
                myGeo.getLocation(
                  new BMapGL.Point(e.center.lng, e.center.lat),
                  function (result) {
                        console.log(result)
                    
                  }
                );
              });

`