返回 导航

Cordova

hangge.com

Cordova - Geolocation插件的使用(GPS地理定位,经度、纬度、海拔等)

作者:hangge | 2016-05-14 10:02
Cordova 提供了一个实现设备定位的插件,通过这个插件我们可以进行定位处理,从而获取GPS位置数据,比如经度、纬度、海拔信息等。


1,添加Geolocation插件
首先我们要在“终端”中进入工程所在的目录,然后运行如下命令:
cordova plugin add cordova-plugin-geolocation
可以看到 geolocation 定位插件已经成功添加了:

2,调用定位功能
下面样例代码,点击页面上的“获取位置信息”按钮后,会将获取到的GPS信息弹出显示。
<!DOCTYPE html>
<html>
    <head>
        <title>Capture Photo</title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

            document.addEventListener("deviceready",onDeviceReady,false);

            //Cordova加载完成会触发
            function onDeviceReady() {
            }

            function getCurrentPosition(){
                //定位数据获取成功响应
                var onSuccess = function(position) {
                    alert('纬度: '          + position.coords.latitude          + '\n' +
                          '经度: '         + position.coords.longitude         + '\n' +
                          '海拔: '          + position.coords.altitude          + '\n' +
                          '水平精度: '          + position.coords.accuracy          + '\n' +
                          '垂直精度: ' + position.coords.altitudeAccuracy  + '\n' +
                          '方向: '           + position.coords.heading           + '\n' +
                          '速度: '             + position.coords.speed             + '\n' +
                          '时间戳: '         + position.timestamp                + '\n');
                };

                //定位数据获取失败响应
                function onError(error) {
                    alert('code: '    + error.code    + '\n' +
                          'message: ' + error.message + '\n');
                }

                //开始获取定位数据
                navigator.geolocation.getCurrentPosition(onSuccess, onError);
            }
        </script>
    </head>
    <body style="padding-top:50px">
        <button style="font-size:23px;" onclick="getCurrentPosition();">获取位置信息</button>
    </body>
</html>
评论

全部评论(1)

回到顶部