Cake Graphics

-1

How can I make a piechart with data coming from a web service ?.

The data that the web service shows comes in json format; this is an example of the output of my web service, which is called ws_lugares.php :

{
"procede": "1",
"status": "1",
"statusText": "Correct",
 "Lugares": [
        {
"México": "3",
"Ecuador": "2",
"Tijuana": "5"
  }
  ]
}

***** E STATE USING this code the url: that is where my web service is located ******

    <script>
        $.ajax({
        url: '../ws_lugares.php',
        type: 'POST',
        dataType: 'json',
        data: $(this).serialize()

    })
    .done(function (respuesta) {
        console.log(respuesta);
        if (!respuesta.error) { //Aqui se les da el valor de el ws a variables para despues llamarlas en el value de la grafica

 } else {
            $('.error').slideDown('slow');
            setTimeout(function () {
                $('.error').slideUp('slow');
            }, 3500);

        }
    })
    .fail(function (resp) {
        console.log(resp.responseText);
    })
    .always(function () {
        console.log("complete");
    });

        var pieChartCanvas = $('#pieChart').get(0).getContext('2d')
          var pieChart       = new Chart(pieChartCanvas)
          var PieData        = [
            {
              value    : //Aqui se llama la 1er var,
              color    : '#f56954',
              highlight: '#f56954',
              label    : 'Chrome'
            },
            {
              value    : //aqui se llama la 2da ,
              color    : '#00a65a',
              highlight: '#00a65a',
              label    : 'IE'
            },
            {
              value    : /aqui se llama la tercer,
              color    : '#f39c12',
              highlight: '#f39c12',
              label    : 'FireFox'
            }
          ]
          var pieOptions     = {
            //Boolean - Whether we should show a stroke on each segment
            segmentShowStroke    : true,
            //String - The colour of each segment stroke
            segmentStrokeColor   : '#fff',
            //Number - The width of each segment stroke
            segmentStrokeWidth   : 2,
            //Number - The percentage of the chart that we cut out of the middle
            percentageInnerCutout: 50, // This is 0 for Pie charts
            //Number - Amount of animation steps
            animationSteps       : 100,
            //String - Animation easing effect
            animationEasing      : 'easeOutBounce',
            //Boolean - Whether we animate the rotation of the Doughnut
            animateRotate        : true,
            //Boolean - Whether we animate scaling the Doughnut from the centre
            animateScale         : false,
            //Boolean - whether to make the chart responsive to window resizing
            responsive           : true,
            // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
            maintainAspectRatio  : true,
            //String - A legend template
            legendTemplate       : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'
          }

        </script>

*** this is what I tried to clear that I have the #piechart but do not place it here because the problem I have is that I do not know how to accommodate the values of the ws to translate them into the graphic ****

    
asked by JV93 17.10.2018 в 18:57
source

1 answer

0

You can use Google's:

google.charts.load("current", {packages:["corechart"]});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        
        //Aquí colocarias el ajax
        const dataWebServices = {
          "procede": "1",
          "status": "1",
          "statusText": "Correct",
          "Lugares": [
              {
                "México": "3",
                "Ecuador": "2",
                "Tijuana": "5",
                "Venezuela": "2"
              }
            ]
        };
        
        var lugares = dataWebServices.Lugares[0];
        var arrayLugares = [];
        arrayLugares.push(['Lugares', 'Paises/Estados']);
        Object.keys(lugares).forEach(function(lugar) {
         let item = [lugar, parseFloat(lugares[lugar])];
         arrayLugares.push(item)
        });
                          
        var data = google.visualization.arrayToDataTable(arrayLugares);

        var options = {
          title: 'Lugares',
          pieHole: 0.4,
        };

        var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
        chart.draw(data, options);
      }
<div id="donutchart" style="width: 900px; height: 500px;"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

As you can see the magic is in the function drawChart () which you can place your ajax where you call your webservices, anyway put the result of your json in a variable to emulate, then I got the value that interests me which is dataWebServices.Lugares [0] which contains the countries / regions , then create an array ArrayLugares where your first value has to be a label that refers to the values that you are going to enter, you can place anything there but it must be string , then in forEach I go through each region to then insert it in the arrayAlgars array to form the data that the graphic needs.

I hope you find it useful.

For more info you can go here .

    
answered by 17.10.2018 / 20:54
source