js - 地理位置信息 navigator.geolocation

 1.单次请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" value="请求位置信息"><br>
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<script>
    window.onload = function () {
        var oBtn = document.getElementsByTagName('input')[0];
        var oTextarea = document.getElementById('content');

        oBtn.onclick = function () {
            navigator.geolocation.getCurrentPosition(function (position) {
                oTextarea.value += "\n 当前经度:"+position.coords.longitude;
                oTextarea.value += "\n 当前纬度:"+position.coords.latitude;
                oTextarea.value += '\n 准确度:' + position.coords.accuracy;
                oTextarea.value += '\n 海拔:' + position.coords.altitude;
                oTextarea.value +='\n 海拔准确度:'+ position.coords.altitudeAccuracy;
                oTextarea.value += '\n 行进方向:' + position.coords.heading;
            }, function (error) {
                alert(error.code);
            },{
                enableHighAcuracy : true,
                timeout :10000,
                maximumAge : 10000
            });
        }
    }
</script>

</body>
</html>

 2.连续请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" value="请求位置信息"><br>
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<script>
    window.onload = function () {
        var oBtn = document.getElementsByTagName('input')[0];
        var oTextarea = document.getElementById('content');
        var timer = null;

        timer = oBtn.onclick = function () {
            navigator.geolocation.watchPosition(function (position) { //多次连续请求地址
                oTextarea.value += "\n 当前经度:"+position.coords.longitude;
                oTextarea.value += "\n 当前纬度:"+position.coords.latitude;
                oTextarea.value += '\n 准确度:' + position.coords.accuracy;
                oTextarea.value += '\n 海拔:' + position.coords.altitude;
                oTextarea.value +='\n 海拔准确度:'+ position.coords.altitudeAccuracy;
                oTextarea.value += '\n 行进方向:' + position.coords.heading;
            }, function (error) {
                alert(error.code);
                navigator.geolocation.clearWatch(timer);//关闭连续请求
            },{
                enableHighAcuracy : true,
                timeout :10000,
                maximumAge : 10000
            });
        }
    }
</script>

</body>
</html>

 

posted @ 2016-10-24 09:45  黑土白云  阅读(3926)  评论(1编辑  收藏  举报