I want to insert google chart using json file.
this is the one views.py function to load json file. =>
def get_addresses(request):
addresses = Address.objects.all().values('address', 'postalcode', 'country', 'latitude', 'longitude')
addresses_list = list(addresses)
return JsonResponse(addresses_list, safe=False)
and this is one of the example of json => [{"address": "\uc11c\uc6b8 \uac15\ub0a8\uad6c \uac1c\ud3ec2\ub3d9 ", "postalcode": "135993", "country": "Republic of Korea", "latitude": "37.4896011", "longitude": "127.0687685"}
I don't know why it doesn't show up google chart.
I got the address from google map api randomly generated. I think google chart could read the address which looks like a key or something.
So I don't think it's the problem of address.
Can anyone please tell what is the problem?
<html>
<head>
<script type="text/javascript"
src='https://www.gstatic.com/charts/loader.js'></script>
<script type='text/javascript' src='https://www.google.com/jsapi'>
</script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See:
'mapsApiKey': 'AIzaSyBZ20X5YvOthFtpf48PMJbCek6456cfSTM'
});
google.charts.setOnLoadCallback(drawMarkersMap);
function drawMarkersMap() {
var jsonData = $.ajax({
url: "senders_list.json",
dataType: "json",
async: false
}).responseText;
var data = google.visualization.arrayToDataTable(jsonData);
var options = {
region: 'KR',
displayMode: 'markers',
colorAxis: {colors: ['green', 'blue']}
};
var chart = new
google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Related
being new to plotting chart with the external api data and lack of knowldge leads me to ask
HOw to plot a chart with coingeko charts api data? link to get json formated api data is:
https://api.coingecko.com/api/v3/coins/ethereum/market_chart?vs_currency=btc&days=30
i had used this sample code and replace the link however only empty chart gets populated without plotting any data points
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text:"Rendering Chart with dataPoints from External JSON"
},
data: [{
type: "line",
dataPoints : dataPoints,
}]
});
$.getJSON("https://api.coingecko.com/api/v3/coins/mustangcoin/market_chart?vs_currency=btc&days=max&type=json", function(data) {
$.each(data, function(key, value){
dataPoints.push({x: value[0], y: parseInt(value[1])});
});
chart.render();
});
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
The API returns:
{
prices: Array,
market_caps: Array,
total_volumes: Array,
}
First you need to select which data you want, you cannot mix them up together.
Secondly, you should create chart new CanvasJS.Chart after you have received the JSON result (in the function() {} body, not before that. Right now, it is uncertain whether the chart is actually getting the updated dataPoints, or is aware about it being updated after you have created the chart.
If you want to update the chart after creation you need to do what their docs says: https://canvasjs.com/docs/charts/basics-of-creating-html5-chart/updating-chart-options/
The given code bellow produces a simple region vice world map and render some data on mouse hover. API document shows a click even can be added but unfortunatly I dint find any document on it how can I add a url link for another web page to a particular region (country).
I short when I clicked on a region/country it should render associated page that holds detailed information provide by my data base application.
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawRegionsMap);
var j = "{{ind}}".replace(/"/g,"\"")
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Pakistan', 500],
['France', 600],
['RU', 700],
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="regions_div" style="width: 1400px; height: 1200px;"></div>
</body>
</html>
I have some trouble in visualization
I tried to make column chart for ph from my database
all the data is in json style and you can access under url
http://magnetic-tenure-93211.appspot.com//get_data/ph
My main reference is google chart document
https://developers.google.com/chart/interactive/docs/php_example
and I can only red box written "Table has no columns", not the chart. could you help me to solve this problem?
my client codes are following...
<html>
<head>
<!--Load the AJAX API-->
<meta charset="utf-8">
<link rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
console.log("1")
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
console.log("3")
function drawChart() {
console.log("2")
var jsonData = $.ajax({
url: "http://magnetic-tenure-93211.appspot.com//get_data/ph",
dataType:"json",
async: false
}).responseText;
console.log(jsonData)
// 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.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="columnchart_values" style="width: 900px; height: 300px;"></div>
</body>
</html>
and I use python Flask to make server and json return codes are following...
#app.route('/get_data/ph', methods=['GET'])
#crossdomain(origin="*", methods=['GET'])
def getPhData():
sensorData = SensorData.query.order_by(desc(SensorData.create_date)).all()
phData = [{
"cols":[ {"id":"", "label":"Topping", "type":"string"}, {"id":"", "label":"Slices", "type":"number"}],
"rows":[ {"c": [{"v":str(sd.create_date), "f":"null"}, {"v":sd.ph,"f":"null"}]} for sd in sensorData]
}]
return json.dumps(phData)
I am plotting up data in Google Charts and continue to have trouble rendering my HTML. I could sure use a second pair of eyes to check if there is anything obviously wrong with the code below. The data has three columns, each of which is meant to be plotted a different color.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></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);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = google.visualization.arrayToDataTable()({
[['x','Virg','Set','Versi'],
[1.0,null,null,1.0],
[2.0,null,2.0,null],
[3.0,3.0,null,null]]
});
// Set chart options
var options = {
title: "Edgar Anderson's Iris Data Set",
hAxis: {title: 'Petal Length', minValue: 0, maxValue: 7},
vAxis: {title: 'Petal Width', minValue: 0, maxValue: 2.5},
legend: ''
//series:{
// 0: { pointShape: 'circle' },
// 1: {pointShape: 'triangle'},
// 2: { pointShape: 'square'}
// }
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Call to arrayToDataTable() is wrong. Instead of
var data = google.visualization.arrayToDataTable()({
[['x','Virg','Set','Versi'],
[1.0,null,null,1.0],
[2.0,null,2.0,null],
[3.0,3.0,null,null]]
});
you have to use
var data = google.visualization.arrayToDataTable([
['x','Virg','Set','Versi'],
[1.0,null,null,1.0],
[2.0,null,2.0,null],
[3.0,3.0,null,null]
]);
Instead of an object of array you have to provide an array of arrays. And unnecessary () deleted.
**Update: ** example at jsbin.
I am using Ajax code to load the html page
for example:
$.ajax({
url: 'Context.html',
dataType: 'html',
timeout: 500,
success: function(html) {
$("div#mainbody").html(html);
}
});
The Context.html I am loading it in some other html page say Home.html
But I am generating pie charts using google API in Context.html
and the code for generating pie chart i.e in Context.html is
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Count'],
['2005', 70],
['2006', 80],
['2007', 140],
['2008', 220],
['2009', 290],
['2010', 400],
['2011', 500]
]);
var options = {
title: 'Head Count-(Apple Year)',
colors:['#129212']
};
var chart = new google.visualization.ColumnChart(document.getElementById('jsf_headcount_bargraph'));
chart.draw(data, options);
}
</script>
When I am loading Context.html in Home.html page I cannot find the pie chart which is in Context.html after loading it in the Home.html
I tried by giving ALERT(""); in script where I wrote code for pie chart. I was getting alert message,so Ajax is executing javascript but I am not getting pie chart which is same script. So I was stucked with Loading pie chart in Home.html page
If you make Context.html like this
<script>
var j = 20;
alert();
</script>
Then I do get an alert (using $.ajax({success: function() {} }) etc. ).
[ Example ]
function execAjax() {
$.ajax( {
url: 'index2.html',
success: function( html ) {
$("#content").html( html );
checkJSvalue();
},
error: function() {
alert( "Error" );
}
});
}
function checkJSvalue() {
alert( j );
}
Example HTML (index2.html)
<div>
content of index2.html
</div>
<script>
var j = 20;
alert();
</script>
What I have tried to do is to put the code directly in the 'home.html' and I already got errors. You should reverse the order of usage and declaration of the drawchart function anyways.
// Bad
// google.setOnLoadCallback(drawChart);
// function drawChart() {}
// Good
function drawChart() {}
google.setOnLoadCallback(drawChart);
Other than that, I already got this error from the google.jsapi.js (copied locally)
Uncaught Error: Container is not defined format+nl,default,corechart.I.js:841
So something goes wrong there, that is not part of the actual question and it's minified etc. so I won't go there.
Hope this was helpful :)
Everything works just fine if i replace the code
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
To inline
google.load('visualization', '1.0', {'packages':['corechart'], "callback": drawChart});