前端js获取当前经纬度(H5/pc/mac/window都可用)

前端JS获取当前位置的经纬度(H5/PC/mac/window都可用,亲测!),效果如下。

前端js获取当前经纬度(H5/pc/mac/window都可用)_第1张图片

 完整代码如下:



var bdLocation= {
  init: function () {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(locationSuccess, locationError,{
            // 指示浏览器获取高精度的位置,默认为false
            enableHighAccuracy: true,
            // 指定获取地理位置的超时时间,默认不限时,单位为毫秒
            timeout: 3000,
            // 最长有效期,在重复获取地理位置时,此参数指定多久再次获取位置。
            maximumAge: 3000
        });
    }else{
        console.log('地理位置服务不可用');
    }

    function locationError(error){ // 失败的回调
        switch(error.code) {
            case error.TIMEOUT:
                console.log('A timeout occured! Please try again!'); //code == 3 请求超时
                break;
            case error.POSITION_UNAVAILABLE:
                console.log('We can\'t detect your location. Sorry!'); //code == 2 无法获取
                break;
            case error.PERMISSION_DENIED:
                console.log('Please allow geolocation access for this to work.'); //code == 1 用户拒绝
                break;
            case error.UNKNOWN_ERROR:
                console.log('An unknown error occured!'); //一个未知的错误
                break;
        }

        // window10和11的chrome浏览器,137.0.7151.56 (正式版本) 获取不到经纬度,一直返回2,的处理方案
        if(error.code==2 || error.code==3){
          // 让客户端拿ip去匹配
  

你可能感兴趣的:(前端,javascript,开发语言)