美文网首页好技术
js获取经纬度

js获取经纬度

作者: blank的小粉er | 来源:发表于2018-05-07 17:29 被阅读0次

Tip:(navigator.geolocation.getCurrentPosition必须用https协议)


<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</head>

<body>
       <p id="demo">点击这个按钮,获得您的坐标:</p>
    <button onclick="getLocation()">试一下</button>
    <script>
        var x = document.getElementById("demo");
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition);
            }
            else { x.innerHTML = "Geolocation is not supported by this browser."; }
        }
        function showPosition(position) {
            x.innerHTML = "Latitude: " + position.coords.latitude +
                "<br />Longitude: " + position.coords.longitude;
        }
    </script>
</body>

</html>

获取地理定位

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>获取地理定位</h1>
    <hr>
    <div id="box"></div>

    <script>
        navigator.geolocation.getCurrentPosition(
            function(position){
                console.log(position);
                
                var str = "";
                str += "当前的纬度:"+position.coords.longitude+"<br>";
                str += "当前的经度:"+position.coords.latitude+"<br>";
                str += "当前的海拔:"+position.coords.altitude+"<br>";
                str += "坐标经度:"+position.coords.accuracy+"<br>";
                str += "前进方向:"+position.coords.heading+"<br>";
                str += "速度:"+position.coords.speed+"<br>";

                document.getElementById("box").innerHTML = str;


            }, 
            function(error){
                alert("获取失败! "+error.code+" , "+error.message);
            }, 
            {
                /timeout:1000,      //超时时间
                enableHighAccuracy:true,  //是否优秀
                maximumAge:1000000   //最大缓存时间
            }
        );
    </script>
</body>
</html>

相关文章

网友评论

    本文标题:js获取经纬度

    本文链接:https://www.haomeiwen.com/subject/otuvrftx.html