0

Tengo el siguiente inconveniente, estoy intentando graficar en HighCharts usando datos en formato json, pero al momento de ejecutar el código no se visualiza nada, la pantalla queda en blanco, para realizar dicha acción usé php para la lectura del archivo json de la siguiente manera:

    <!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Tráfico mensual</title>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="http://code.highcharts.com/highcharts.js"></script>
        <script type="text/javascript">


$(function () {


        $(document).ready(function() {
           Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });

        var chart;
        $('#tiempoReal').highcharts({
            chart: {
                type: 'spline',
                animation: Highcharts.svg, 
                marginRight: 10,
                events: {
                    load: function() {

                        <?php

                        $contenido = file_get_contents("datos.json");
                        $contenido = $contenido;
                        $datos = json_decode($contenido, true);
                        $hay = count($datos["sensores"]);
                        $sensores = $datos["sensores"];

                        ?>


                        // set up the updating of the chart each second
                        var google = this.series[0];
                        setInterval(function() {
                            var x = (new Date()).getTime(), // current time
                                y = <?php

                                foreach($sensores as $se){
                                    echo "$se[valor]";
                                }

                                ?>
                            google.addPoint([x, y], true, true);
                        }, 2000);
                    }
                }
            },
            title: {
                text: 'Distancia Actualizada segundo a segundo'
            },
            subtitle:{
                text: 'Tiempo Real'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150
            },
            yAxis: {
                title: {
                    text: 'Distancia'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function() {
                        return '<b>'+ this.series.name +'</b><br/>'+
                        Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
                        Highcharts.numberFormat(this.y, 2);
                }
            },
            legend: {
                enabled: false
            },
            exporting: {
                enabled: false
            },
            series: [{
                name: 'Google.com',
                data: (function() {
                    // generate an array of random data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;

                    for (i = -19; i <= 0; i++) {
                        data.push({
                            x: time + i * 1000,
                            y: 0
                        });
                    }
                    return data;
                })()
            }]
        });
    });
});


    </script>
</head>
<body>


    <div style="border-top:1px solid #CDCDCD;margin:10px;padding:0;clear:both;"></div>

    <!-- div que contendrá la gráfica a tiempo real -->
    <div id="tiempoReal" style="height: 400px; margin: 0 auto;"></div>

dicho el código php en un aparte si funciona yo lo probé pero no entiendo cual es la razón por la cual no me permite tomar los datos, por cierto, este el archivo datos.json:

{
"sensores": [
    {
        "id": "1",
        "nombre": "infrarrojo",
        "valor": "22.5"
    },
    {
        "id": "2",
        "nombre": "infrarrojo",
        "valor": "30"
    },
    {
        "id": "3",
        "nombre": "infrarrojo",
        "valor": "16.5"
    },
    {
        "id": "4",
        "nombre": "infrarrojo",
        "valor": "22.5"
    },
    {
        "id": "5",
        "nombre": "infrarrojo",
        "valor": "30"
    },
    {
        "id": "6",
        "nombre": "infrarrojo",
        "valor": "22.5"
    },
    {
        "id": "7",
        "nombre": "infrarrojo",
        "valor": "30"
    }
]
}
2
  • el último json es el que te genera el php que tienes incrustado? el 11 ene. 2020 a las 15:55
  • Sii el json que coloque al ultimo es el resultado del codigo php, pero no me ejecuta la gráfica el 11 ene. 2020 a las 16:03

1 respuesta 1

0

bienvenido a StackOverflow,

He podido ver que le falta un ";" en la línea donde asignas el valor a Y. El código quedaría así:

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Tráfico mensual</title>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="http://code.highcharts.com/highcharts.js"></script>
        <script type="text/javascript">


$(function () {


        $(document).ready(function() {
           Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });

        var chart;
        $('#tiempoReal').highcharts({
            chart: {
                type: 'spline',
                animation: Highcharts.svg, 
                marginRight: 10,
                events: {
                    load: function() {

                        <?php

                        $contenido = file_get_contents("datos.json");
                        $contenido = $contenido;
                        $datos = json_decode($contenido, true);
                        $hay = count($datos["sensores"]);
                        $sensores = $datos["sensores"];

                        ?>


                        // set up the updating of the chart each second
                        var google = this.series[0];
                        setInterval(function() {
                            var x = (new Date()).getTime(), // current time
                                y = <?php

                                foreach($sensores as $se){
                                    echo "$se[valor];";
                                }

                                ?>
                            google.addPoint([x, y], true, true);
                        }, 2000);
                    }
                }
            },
            title: {
                text: 'Distancia Actualizada segundo a segundo'
            },
            subtitle:{
                text: 'Tiempo Real'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150
            },
            yAxis: {
                title: {
                    text: 'Distancia'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function() {
                        return '<b>'+ this.series.name +'</b><br/>'+
                        Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
                        Highcharts.numberFormat(this.y, 2);
                }
            },
            legend: {
                enabled: false
            },
            exporting: {
                enabled: false
            },
            series: [{
                name: 'Google.com',
                data: (function() {
                    // generate an array of random data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;

                    for (i = -19; i <= 0; i++) {
                        data.push({
                            x: time + i * 1000,
                            y: 0
                        });
                    }
                    return data;
                })()
            }]
        });
    });
});


    </script>
</head>
<body>


    <div style="border-top:1px solid #CDCDCD;margin:10px;padding:0;clear:both;"></div>

    <!-- div que contendrá la gráfica a tiempo real -->
    <div id="tiempoReal" style="height: 400px; margin: 0 auto;"></div>
3
  • Disculpa como podría hacer para que la gráfica me muestre los datos que se vayan ingresando a la base de datos, porque actualmente solo tiene los valores son estáticos y al momento de ingresar otro dato no cambia. Te agradezco mucho por la corrección del código ya ejecuta la gráfica el 11 ene. 2020 a las 16:40
  • @DiegoGonzález Tendrías que hacer una petición ajax a tu mismo archivo que te retorna el json, destruir tu gráfica y volverla a instanaciar-crear. el 11 ene. 2020 a las 17:22
  • Fernando Torres hice otra pregunta en la cual saqué otro código, sin embargo no me genera los valores en tiempo real sale mal, este es el enlace, podrías revisarlo y ver que se encuentra mal por favor es.stackoverflow.com/questions/321242/problemas-con-highcharts el 11 ene. 2020 a las 17:30

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.