Reputation: 1
Can someone send me correct code that can create interactive chart by calling JSON API URL ?
Example: chart based on JSON API in url
http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo
In google site there is a sample in https://developers.google.com/chart/interactive/docs/php_example
but the below shows nothing (I replaced original JSON PHP file location with my URL)
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo ",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
Upvotes: 0
Views: 9619
Reputation: 1809
Looking at the JSON returned from the URL that you gave (http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo), it looks like it doesn't conform to the DataTable JSON format.
From https://developers.google.com/chart/interactive/docs/basic_preparing_data:
All charts require data. Google Chart Tools charts require data to be wrapped in a JavaScript class called google.visualization.DataTable. This class is defined in the Google Visualization library that you loaded previously. A DataTable is a two-dimensional table with rows and columns, where each column has a datatype, an optional ID, and an optional label.
If you look at the sample JSON data that they provide, you'll see that it conforms to the DataTable format:
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
Upvotes: 2