Search code examples
javascriptjqueryjsoncanvasjs

Rendering graph in canvas js using external json data


I am trying to render graphs using canvas.js. The charts need to be rendered from an external JSON source, which is hosted at this website

http://gsx2json.com/api?id=1vc7wCjNXK39HMEYDkOJRMhQGPJpxMu4MJgTsydyLats

The objective is to, graph a chart from 2 values in the JSON data (ie example, timestamp vs latitude)

This is the code, which I have so far:

$.getJSON("http://gsx2json.com/apiid=1vc7wCjNXK39HMEYDkOJRMhQGPJpxMu4MJgTsydyLats", function addData(data){


for (var i = 0; i < data.length; i++) {

    dataPoints.push({
        x: new Date(data[i].columns["timestamp"]),
        y: data[i].columns["latitude"]
    });
}

chart.render();


 // console.log(data.columns["timestamp"])

});

I am using the for loop to iterate thru the JSON object and then using JSON keys to access the data.

The data doesn't render, when I run this code. But, when I try to console.log (data.columns["latitude"]) outside the for-loop, I am able to access the data which I need.

Any help is much appreciated.

Thanks.


Solution

  • I would advise something like the following.

    $(function(){
      var points = [];
    
      $.getJSON("http://gsx2json.com/api?id=1vc7wCjNXK39HMEYDkOJRMhQGPJpxMu4MJgTsydyLats&columns=false", function(d){
        $.each(d.rows, function(i, r){
          points.push({
            x: new Date(r.timestamp),
            y: r.latitude
          });
        });
      }).fail(function(xhr, status, error) {
        console.log("Ajax Error", status, error);
      });
    
      var chart = new CanvasJS.Chart("chartContainer", {
        type: "line",
        data: [{
          dataPoints: points
        }]
      });
      chart.render();
    });
    

    This may encounter problems due to CORS.

    Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.

    If this is the case, can try with $.ajax() and set dataType set to jsonp. Can also move to fetch() alternative.

    Looking at the data returned, using rows might be easier, since you want the corresponding timestamp and latitude. The columns make this more difficult; you would have ti iterate both columns.timestamp array at the same time as columns.latitude array. Hence the &columns=false portion to the URL to help reduce data that needs to be passed back.

    Hope this helps.