必威体育Betway必威体育官网
当前位置:首页 > IT技术

【Html5】获取G-Sensor数据判断运行状态

时间:2019-08-02 20:11:05来源:IT技术作者:seo实验室小编阅读:84次「手机版」
 

g-sensor

<html>

<head>
    <title>DeviceOrientationEvent</title>
    <meta charset="UTF-8" />
    <script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script src="https://img.hcharts.cn/highcharts/highcharts.js"></script>
    <script src="https://img.hcharts.cn/highcharts/modules/exporting.js"></script>
    <script src="https://img.hcharts.cn/highcharts-plugins/highcharts-zh_CN.js"></script>
</head>

<body>
    <h1>g-sensor带GPS</h1>
    <h2>判断手机运动状态 --
        <a href="demoGPS.html">重新开始</a>
        <input type="button" value="获取GPS" style="min-width:400px;height:400px"></p>
    <hr>
    <h3>手机获取GPS传感器精度(米):
        <span id="accuracy">-1</span>
    </h3>
    <p>GPS的数据:</p>
    <ul class="GPSText">
    </ul>
    <hr>
    <p>采集到的数据(9秒内的中位数):</p>
    <ul class="arr4">
    </ul>
    
    <script type="text/javascript">

        //记录△:每个周期记录的G-Sensor数据计算后的值
        var arr = [];

        //是否为开车,status==2判断为开车
        var status = 0;
        var statusStopCount = 0;

        //james的神秘数字
        var min = 0.5, max = 2.552188,walking=3.0;

        //用来暂存上次传感器记录的数据
        var temp = {
            X: 0, Y: 0, Z: 0
        };
        var flag = 1;
        var point = 0, pointMedian = 0, pointAvg = 0;//实时值,中位数,平均值

        var loadingData = [];//初始化Highcharts的值
        //获取传感器上加速器的数据
        var count = 0, t = 0;

        //1、监听设备的传感器
        if (window.Devicemotionevent) {
            window.addeventlistener("devicemotion", motionhandler, false);
        } else {
            document.body.innerHTML = "What user agent u r using???";
        }

        //2、获取传感器上G-Sensor的数据
        function motionHandler(event) {
            //html 的addEventListener 变化频率大概1秒60次 ,现在一秒钟收集一次数据,由于计算需要时间改成52
            if (count >= 52) {
                document.getelementbyid("Interval").innerHTML = event.interval;
                var accGravity = event.accelerationIncludingGravity;
                document.getElementById("xg").innerHTML = accGravity.x;
                document.getElementById("yg").innerHTML = accGravity.y;
                document.getElementById("zg").innerHTML = accGravity.z;

                LogingData(accGravity.x, accGravity.y, accGravity.z);//记录数据
                count = 0;
            }
            count++;
            t++;
        }

        //3、记录数据-处理算法的
        function LogingData(x, y, z) {

            var _x = x - temp.X;
            var _y = y - temp.Y;
            var _z = z - temp.Z;

            temp = {
                X: x, Y: y, Z: z
            };

            var value = Math.sqrt((_x * _x) + (_y * _y) + (_z * _z));
            point = value;
            arr.push(value);

            if (arr.length == 9) {
                pointAvg = 0;
                for (var i = 0; i < arr.length; i++) {
                    pointAvg += arr[i];
                }
                arr = arr.sort();
                pointMedian = arr[4];
                pointAvg = pointAvg / arr.length;

                $('.arr4').APPend('<li>' + getNowTime() + '---' + arr[4] + '</li>');

                //判断是否连续撞上,平均值和中值同时满足条件James定的值
                if ((arr[4] > min && arr[4] < max) ) { //&& (pointAvg > min && pointAvg < max)
                    status = status + 1;
                } else {
                    status = 0;
                }

                //判断是否为走路,平均值和中位数同时大于walking及判断为步行
                if ((arr[4] > walking) && (pointAvg > walking)) {
                    statusStopCount = statusStopCount + 1;
                } else {
                    statusStopCount = 0;
                }

                // //连续两次撞上判断为开车
                if (status >= 2 && flag > 0) {
                    document.getElementById("drive").innerHTML = 'Sensor判断为开车-开GPS';
                    $("body").css("background-color", "#4A8AF4");

                    //开GPS
                    GpsStart(flag);
                }

                if (statusStopCount >= 2) {
                    document.getElementById("drive").innerHTML = 'Sensor判断为没开车-关GPS';
                    $("body").css("background-color", "#FFFFFF");

                    //关GPS
                    //GpsStop(flag);
                }
                arr = [];
            }
        }

        //获取时间
        function getNowTime() {
            var date = new Date();
            var Hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
            var Minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
            var Seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            var time = Hours + ':' + Minutes + ':' + Seconds;
            return time;
        }
        document.getElementById("date").innerHTML = getNowTime();

        // --------------------------------------------------开启GPS-判断是否开启 Trip-------------------------------------------------
        function getLocation() {
            var options = {
                enableHighAccuracy: true,
                maximumAge: 0
            }
            if (navigator.geolocation) {
                //浏览器支持geolocation
                navigator.geolocation.getCurrentPosition(onSuccess, onERROR, options);
            } else {
                //浏览器不支持geolocation
                alert('浏览器不支持geolocation');
            }
        }
        var GPSSpeed = [];//存放GPS的速度,十秒钟的五个值
        var GPSSpeedAVG = 0;//存放十秒钟的平均速度

        //成功时
        function onSuccess(position) {
            GPSSpeed.push(Math.abs(position.coords.speed));
            if (GPSSpeed.length >= 10) {
                for (var i = GPSSpeed.length - 10; i < GPSSpeed.length; i++) {
                    GPSSpeedAVG += GPSSpeed[i];
                }
                GPSSpeedAVG /= GPSSpeed.length;
                $('.GPSText').append('<li>' + getNowTime() + '- 速度:' + GPSSpeedAVG + '--' + position.coords.longitude +'-|-'+ position.coords.latitude + '</li>');
                document.getElementById("accuracy").innerHTML =  position.coords.accuracy+'-|-'+position.coords.altitudeAccuracy;
                if (GPSSpeedAVG > 2.5) {
                    $("body").css("background-color", "#BCEA1C");
                    document.getElementById("drive").innerHTML = 'GPS判断为开车';
                } else {
                    $("body").css("background-color", "#F20DD8");
                    document.getElementById("drive").innerHTML = 'GPS判断为没开车';
                }
                GPSSpeedAVG = 0;
            }
        }

        //失败时
        function onError(error) {
            switch (error.code) {
                case 1:
                    alert("-");
                    break;
                case 2:
                    alert("暂时获取不到位置信息");
                    break;
                case 3:
                    alert("获取信息超时");
                    break;
                case 4:
                    alert("未知错误");
                    break;
            }
        }

        function GpsStart() {
            if (flag > 0) {
                flag = 0;
                var GpsCount = 0;
                var timer1 = setInterval(
                    function () {
                        getLocation();
                        GpsCount++;
                        if (GpsCount >= 6 * 10) {
                            flag = 1;
                            document.getElementById("drive").innerHTML = '没开车-关闭GPS';
                            $("body").css("background-color", "#FFFFFF");
                            GPSSpeed = [];//清空数组
                            window.clearTimeout(timer1);//去掉定时器 
                        }
                    }, 1000);
            }
        }

        // -------------------HighCharts 数据展示--------------------------------------------------------------------------------

        //初始化数据
        function getHighCharts(k) {
            loadingData = [];
            var time = (new Date()).getTime();
            for (var i = -100 / k; i <= 0; i += 1) {
                loadingData.push({
                    x: time + i * 1000 * k,
                    y: 0
                });
            }
            return loadingData;
        }

        Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });

        function activeLastPointToolip(chart) {
            var points = chart.series[0].points;
            chart.tooltip.refresh(points[points.length - 1]);
        }

        //highcharts数据的显示
        $('#container').highcharts({
            chart: {
                type: 'spline',
                animation: Highcharts.svg,
                marginRight: 100,
                events: {
                    //数据的实时刷新
                    load: function () {
                        var series = this.series[0],
                            seriesMedian = this.series[1],
                            seriesAvg = this.series[2],
                            chart = this;

                        setInterval(function () {
                            var x = (new Date()).getTime();
                            series.addPoint([x, point], true, true);
                            activeLastPointToolip(chart)
                        }, 1000);

                        setInterval(function () {
                            var x = (new Date()).getTime();
                            seriesMedian.addPoint([x, pointMedian], true, true);
                            seriesAvg.addPoint([x, pointAvg], true, true);
                            activeLastPointToolip(chart)
                        }, 9000);
                    }
                }
            },
            title: {
                text: '实时数据'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150
            },
            yAxis: {
                title: {
                    text: '值'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function () {
                    return '<b>' + this.series.name + '</b><br/>' +
                        Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
                        Highcharts.numberFormat(this.y, 6);
                }
            },
            legend: {
                reversed: true,
            },
            exporting: {
                enabled: false
            },
            series: [{
                name: '每秒的值',
                data: getHighCharts(1)
            }, {
                name: '9秒的中位数',
                data: getHighCharts(9)
            }, {
                name: '9秒的平均值',
                data: getHighCharts(9)
            }]
        }, function (c) {
            activeLastPointToolip(c)
        });
    </script>
</body>

</html>

相关阅读

分享到:

栏目导航

推荐阅读

热门阅读