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/
Related
Although I found similar posts elsewhere, I still cannot solve my issue.
I want to load locations on a html sidebar page on google spreadsheet, but the only example I find are hard-coded locations.
Here is an example, on HTML page (I removed API Key): this one works for me.
<body>
<div class="container">
<div id="map_div" style="width: 500px; height: 500px"></div>
</div> <!-- CLOSE CONTAINER -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {
"packages":["map"],
"mapsApiKey": "xxxx"
});
google.charts.setOnLoadCallback(drawChart);
function drawChart(arrayToData) {
var data = new google.visualization.arrayToDataTable(
[["Lat", "Long","Nom"],
[45.7660889, 4.794056299999999, "Person1"],
[45.8167227, 4.8341048, "Person2"],
[45.7796433, 4.8037871, "Person3"],
[45.7780849, 4.921768399999999, "Person4"]]
);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}//function drawChart() {
</script>
</body>
And I would like to have something looking like that, where data locations are not hard-coded but comes from spreadsheet data :
google.charts.setOnLoadCallback(drawChart);
var ss = SpreadsheetApp.openByUrl("xxxx");
var datatable = ss.getRange("listNamesAdresses");
function drawChart(arrayToData) {
var dataToArray=document.getElementById("listNamesAdresses");
var data = new google.visualization.arrayToDataTable(
dataToArray
);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}//function drawChart() {
I'm aware this is not correct, but I tried many combinations, still cannot solve it. Your help is welcome !
Here is a sharable example of what I made :
Link to a copy of my Map Test
I adapted it from my spreadsheet but went out of my quota for my API key, so I could'nt test it yet. I hope this will be fine !
Many thanks in advance
EDIT 2 :
I followed ziganotschka's suggestions (thank you very much for your time) : I couldn't apply the HtmlCreateOutputFromFil("index.html") so I stuck to my code for displaying a sidepage Html. For the rest of it : I now have a map (first victory!).
But, it says : "no data points to show".
I checked on values return by getAddresses function, seems OK. For getting easier on it, I changed the function to an easier one : getGeoCodesAndNames. This one returns, as it says, geocode latitude, longitude, and name.
Here are my new code sample and link to the new version of the spreadsheet :
Gs-code :
function getGeoCodesAndNames(){
//get addresses and names list
var namesAddresses=ss.getRange("ListNamesAddresses");
var a_values=namesAddresses.getValues();
Logger.log(a_values);
/* returns
[[Lat, Lon, Name],
[45.7660889, 4.79405629999999, person1],
[45.8167227, 4.8341048, person2],
[45.7796433, 4.8037871, person3],
[45.7780849, 4.921768399999999, person4]]
*/
return a_values;
}//function getGeoCodesAndNames(){
function testMap2(){
var template = HtmlService.createTemplateFromFile("carte2");
var html = template.evaluate();
html.setTitle("Display Map 2").setHeight(550).setWidth(550);
SpreadsheetApp.getUi().showModalDialog(html, "Locations")
}//function testCarte1(){
and HTML code :
<script type="text/javascript">
window.onload = google.script.run.withSuccessHandler(onSuccess).getGeoCodesAndNames();
function onSuccess (arrayToData){
google.charts.load("current", {
"packages":["map"],
"mapsApiKey": "AIzaSyC4WPcWGMZRoqSAfZ0F4RzvWtN6Jy7hmdE"
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(arrayToData);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}// function drawChart() {
}//function onSuccess (arrayToData){
</script>
And here is the link to the new spreadsheet version :
TestMap2
Do I need to publish it as a web app if I just want to have a side page ? On previous projects I had, I could add datas from a side-page to a spreadsheet without it. In the oppposite ways, can you confirm I need to do it ? I tried, did not change anything on my current result : maybe I made something wrong.
Many thanks again for your help !
EDIT 3 :
I finally got it : My geocode/address function were not returning a proper format for coordinates, because of two things :
1) I'm using French typing, ie dot are replaced with commas in numbers
2) I had to add one more """ symbol at beginning and ending of each string part in the array.
Here is the correct function (might be improved, but..does the job):
function getGeoCodesAndNames(){
//get addresses and names list
var namesAddresses=ss.getRange("ListNamesAddresses");
var a_values=namesAddresses.getValues();
for (var i=0;i<a_values.length;i++){
for (var j=0;j<a_values[0].length;j++){
var value=a_values[i][j];
if (typeof value == "string"){
a_values[i][j]="\"" + value + "\"";
}
}
}
return a_values;
}//function getGeoCodesAndNames(){
Many thanks to the people who helped me !
To combine using the Visualization API in Javascript with retrieving spreadsheet data with Apps Script - you need to use a WebApp
Use google.script.run to pass data from the serverside to clientside
Sample:
code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile("index.html");
}
function getDatafromSheet(){
var ss = SpreadsheetApp.openByUrl("xxxx");
// getNamedRanges()[0] works if you have only one named range
var datatable = ss.getNamedRanges()[0].getRange().getValues();
return datatable;
}
index.html
<body>
<div class="container">
<div id="map_div" style="width: 500px; height: 500px"></div>
</div> <!-- CLOSE CONTAINER -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
window.onload = google.script.run.withSuccessHandler(onSuccess).getDatafromSheet();
function onSuccess (arrayToData){
google.charts.load("current", {
"packages":["map"],
"mapsApiKey": "AIzaSyDCKzjezYeUDd2ugtFnzokCIpV1YpLmmEc"
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.arrayToDataTable(arrayToData);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}
}
</script>
</body>
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>
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.