Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Javascript获取经纬度,关于调用百度API的问题 #16

Closed
Wscats opened this issue May 19, 2016 · 2 comments
Closed

Javascript获取经纬度,关于调用百度API的问题 #16

Wscats opened this issue May 19, 2016 · 2 comments

Comments

@Wscats
Copy link
Owner

Wscats commented May 19, 2016

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=XXXXXXXXXXXXX"></script>
上面这段代码执行完后百度会返回一段代码并插入到你的DOM中执行

<script>
    (function() {
            window.BMap_loadScriptTime = (new Date).getTime();
            document.write('<script type="text/javascript" src="http://api.map.baidu.com/getscript?v=2.0&ak=XXXXXXXXXXX&services=&t=20160513110936"></script>');})();
</script>

image
首先记得引入百度api请求脚本,ak要换上自己的

var setCookie = function(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
};
var geolocation = new BMap.Geolocation();
//弹出地理授权
geolocation.getCurrentPosition(function(r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            alert('定位成功');
            console.log(r.point);
        } else {
            alert("baidu return failed");
        }
    },
    //获取失败时候的回调
    function(r) {
        console.log(r);
        alert('定位失败');
        return {
            //设置高精度
            enableHighAccuracy: true
        };
    }
);

在这个函数执行的时候,经过测试其实不管你是否允许地理位置的授权,都能获取到你的定位位置,只不过不授权时候获取的应该是IP地址的定位,授权是精确的GPS定位而已

所以这里的问题在于如果是这样的话,那在任何一段Javascript脚本中执行上述代码,用户在知道弹出询问是否允许获取地理位置授权这个提示之后,不管是否允许都能获取到使用者的定位的

这里还要注意几个地方就是geolocation是HTML5的东西,一般移动端支持都比较好的,用到的时候最好判断一下浏览器是否支持

if ("geolocation" in navigator) {
    alert("支持geolocation");
} else {
    alert("不支持geolocation");
}

还有百度geolocation.getCurrentPosition()这个函数里面的第一个参数是回调成功后执行的,第二个参数是回调后失败执行的,我看官网的地址貌似没有写明白第二个参数是可以传一个对象或者匿名函数进去,所以导致很多人不知道getCurrentPosition失效的时候怎么捕捉到这个失败的回调,我上面的例子就是传入一个失败时候要执行回调函数,让后面代码能顺利执行下去

如果确实因为各种原因而获取不到回调,建议这里加个定时器比较保险,免得program在这里白白被卡死

setTimeout(function() {
    alert("获取超时");
    setCookie("longitude", '113.333333');
    setCookie("latitude", '23.333333');
    setCookie("city", 'wscats');
    setCookie("cityCode", '543210');
    load();
}, 4000)

其实百度的Geolocation跟HTML5 Geolocation(地理定位)也是非常相似的,看下面的例子

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no">
<body>
        <p id="demo">点击按钮获取您当前坐标(可能需要比较长的时间获取):</p>
        <button onclick="getLocation()">点我</button>
        <div id="mapholder"></div>
        <script>var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else {
        x.innerHTML = "该浏览器不支持获取地理位置。";
    }
}

function showPosition(position) {
    var latlon = position.coords.latitude + "," + position.coords.longitude;
    var img_url = "http://maps.googleapis.com/maps/api/staticmap?center=" + latlon + "&zoom=14&size=400x300&sensor=false";
    document.getElementById("mapholder").innerHTML = "<img src='" + img_url + "'>";
}

function showError(error) {
    console.log(error);
    switch (error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "用户拒绝对获取地理位置的请求。"
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "位置信息是不可用的。"
            break;
        case error.TIMEOUT:
            x.innerHTML = "请求用户地理位置超时。"
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "未知错误。"
            break;
    }
}</script>
</body>
</html>

image

这里的navigator.geolocation.getCurrentPosition()也是传入两个函数,一个关于回调成功,一个关于回调失败的,测试的过程中发现一直返回给我
位置信息是不可用的。
上网查了原因,应该是:鉴于该特性可能侵犯用户的隐私,除非用户同意,否则用户位置信息是不可用的。还有可能是因为某些浏览器调用了谷歌的服务,所以这里会被卡了

@Wscats
Copy link
Owner Author

Wscats commented May 19, 2016

具体还参考百度API文档
http://developer.baidu.com/map/jsdemo.htm#i8_1

@M-torch99
Copy link

nice!

@Wscats Wscats closed this as completed Aug 22, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants