Dynamic creation of google charts in single page - javascript

I'm attempting to dynamically create multiple charts in a single html page, everything loads perfectly, except that the graph that is displayed last is the only one that has interactivity available (ex: hover over points to read data, click on legend to highlight line..) while the others will only display static charts.
HTML Code:
<html>
<head>
<title>Dashboard</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type = "text/javascript" src = "./scripts/scripts.js"> </script>
</head>
<body>
</body>
<script language = "JavaScript">
var dashboard = getParameterByName("dashboard");
google.charts.load('current', {packages: ['corechart','line']});
buildDashboard(dashboard);
</script>
</html>
Main JS functions:
function buildDashboard(dashboard)
{
var panels = getPanels(dashboard);
google.charts.setOnLoadCallback(function(){
drawCharts(dashboard, panels);
});
}
function drawCharts(dashboard, panels)
{
for(var i = 0; i < panels.length; i++)
{
var panel = panels[i];
var _data = getPanelData(dashboard, panel.Id);
if(panel["Type"] == "LineChart")
{
var legend = JSON.parse(JSON.stringify(_data[0]));
var options = buildLineChartOptions(panel, legend);
var data = google.visualization.arrayToDataTable(beautifyData(panel, _data));
var divname = panel.Id;
if(!document.getElementById(divname))
document.body.innerHTML += "<div id = " + divname + " style = \"width: 100%; height: 600px; margin: 0 auto\"></div>";
var chart = new google.visualization.LineChart(document.getElementById(divname));
chart.draw(data, options);
}
}
}

Solved: The problem was solved by creating the <div> elements for all charts prior to drawing the charts one by one.

Related

How to transfer something(i.e variable) from a JavaScript file to a HTML file?

I'm trying to code a web-page that will display a pie-chart with results but the code for my pie-chart is in a HTML file (read_data.html) and the figures I would like to use for the pie-chart are in a JavaScript file (read_data.js)
The figures I want are stored in 4 variables - Booth1,Booth2,Booth3,Booth4
How could I go about transferring these variables to my HTML file?
Here is the code for the pie-chart in the HTML file
<!DOCTYPE html>
<html lang="en-US">
<body>
<h1>My Web Page</h1>
<div id="piechart"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Students', 'Votes'],
['Canidate1', Booth1],
['Canidate2', Booth2],
['Canidate3', Booth3],
['Canidate4', Booth4],
]);
// Optional; add a title and set the width and height of the chart
var options = {'title':'Election Results', 'width':550, 'height':400};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</body>
</html>
Here is the code in the JavaScript file
// Lists to hold the well being states and their corresponding times
var myVotes = [];
var myTimes = [];
// Variables to hold the count for each state
var Booth1 = 0;
var Booth2 = 0;
var Booth3 = 0;
var Booth4 = 0;
// Define database connection to correct child branch, ElectionResults
var myDBConn = firebase.database().ref("ElectionResults");
// Function that acts when a 'new child is added to the DB' - i.e. new data is added this function runs.
myDBConn.on("child_added", function(data, prevChildKey) {
Booth1 = 0;
Booth2 = 0;
Booth3 = 0;
Booth4 = 0;
// The data returned from the branch is put into a variable, dataPoint
var dataPoint = data.val();
// Populate the lists with the various data from the database
myVotes.push(dataPoint.ElectionResults);
myTimes.push(dataPoint.Time);
// Loop each returned state and add 1 to the appropriate counter
for (i = 0; i < myVotes.length; i++) {
if (myVotes[i] == "Canidate1") {
Booth1 = Booth1 + 1;
}
if (myVotes[i] == "Canidate2") {
Booth2 = Booth2 + 1;
}
if (myVotes[i] == "Canidate3") {
Booth3 = Booth3 + 1;
}
if (myVotes[i] == "Canidate4") {
Booth4 = Booth4 + 1;
}
}
// Update the page elements with the average and the last item (most rescent) off the list
document.getElementById("TimeID").innerHTML = myTimes[myTimes.length - 1];
// Update the page elements with the results of each count
document.getElementById("Booth1").innerHTML = Booth1;
document.getElementById("Booth2").innerHTML = Booth2;
document.getElementById("Booth3").innerHTML = Booth3;
document.getElementById("Booth4").innerHTML = Booth4;
});
I think that you can just include the JS file into the HTML file by useing the <script /> tag;
<script type="something" src="read_data.js"></script>
With this tag you inculded the file and can use the variables by opening another script tag;
<script>
//import variables here
</script>

Google Feed API for RSS is not showing current events

I am attempting to use Google Feed API to display three current event listings for our homepage. This is to circumvent some of the issues we are having with a third part calendar application.
However, with the feed limit set to 3, the only listings that will show up for me are from Jan. 18. Is there a way to make the code show only current or future events?
Thanks in advance for any help.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
</head>
<body>
<div id="feed"></div>
</body>
</html>
JavaScript
google.load("feeds", "1");
var feedcontainer=document.getElementById("feed");
var feedurl="http://25livepub.collegenet.com/calendars/publishers-calendar-7.rss";
var feedlimit = 3;
var rssoutput = '';
function rssfeedsetup(){
var feedpointer=new google.feeds.Feed(feedurl);
feedpointer.setNumEntries(feedlimit) ;
feedpointer.load(displayfeed);
}
function displayfeed(result){
if (!result.error){
var thefeeds=result.feed.entries;
for (var i=0; i<thefeeds.length; i++){
var untrimContent = thefeeds[i].content;
var trimContent = untrimContent.split("<br>", 2);
rssoutput+="<div><a href='" + thefeeds[i].link + "'>" + thefeeds[i].title + "</a></div>" + trimContent;
feedcontainer.innerHTML=rssoutput;
}
} else {
feedcontainer.innerHTML = "Error Loading Events";
}
}
window.onload=function(){
rssfeedsetup();
};

Displaying data points from server side txt file on google graph

I would like to display my retrieved data points from my server side text file
on a google graph. During research i can now retrieve the data from my temps.txt
file using $.get().
I just started learning javascript , so this may be something obvious that i missed.
I can also display a sample google graph with some example datapoints.
How can i put the two together? , below i have both source files
from my attempts so far.
Getting the Datapoints:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 16px;
font-family: Arial;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
var times = [];
$.get('temps.txt', function(data) {
times = data.split("\n");
var html = [];
for (var i in times) {
html.push(times[i] + '<br/>');
}
html.push( times[0] * 3 );
$('body').append(html.join(''));
});
</script>
</html>
Showing the GRAPH:
<html>
<head>
<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([
['Hours', 'Temperature'],
['18:00', 20.7],
['19:00', 21],
['20:00', 22.3],
['20:30', 22.5],
['21:00', 22.0],
['22:00', 21.6]
]);
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 700px; height: 400px;"></div>
</body>
</html>
Temps.txt file is a simple text file with one measured value every hour
the first line is 00:00 hrs the 2nd line 01:00 hrs and so on see below:
15.3
16.4
16.7
18.8
... etc
Well, would be something like this:
function drawChart() {
$.get('temps.txt', function(txt) {
vals = txt.split("\n");
var hour= 0;
var dataArr=[['Hours', 'Temperature']]
for(var i = 0; i < vals.length;i++){ // build data array
//add the hour in 'hh:00' format and the temperature value
dataArr.push([('0'+hour).substring(-2)+':00', parseFloat(vals[i])]);
hour+=1;
}
var data = google.visualization.arrayToDataTable(dataArr)
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}

Modifying street view code, cannot substitute variable as argument

edit1= clearifying sample code
edit2= well this is getting embarassing, now I will post the actual code
I am trying to make a custom interior streetview. I am attempting to convert custom interior shot to be relative to arbitrary starting position by substituting the argument of the function below with variable, but would break the streetview. I am not familiar with javascript.
description:"TEST TEST TEST TSET",latLng:new google.maps.LatLng(54.156654,69.696969)
runs fine.
var demolat = 34.995348; // declared at beginning of function
var demolon = 135.7395;
var wlat = demolat;
var wlon = demolon;
.. lots of code .. // lots of code goes here
description:"TEST TEST TEST TSET",latLng:new google.maps.LatLng(wlat,wlon)
does not work.
full code
the script would not work properly when replaced line described above.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=utf-8"/>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry" type="text/javascript"></script>
<script type="text/javascript" code="maps_code">
var initPosPanoID,initPosPanoData,streetView,map_canvas;
function initialize(){
var neeclat = 35.564157;
var neeclon = 139.714947;
//var demolat = 34.995138;
//var demolon = 135.739689;
var demolat = 34.995348;
var demolon = 135.7395;
var wlat = demolat;
var wlon = demolon;
swbound = new google.maps.LatLng(wlat-0.0003,wlon-0.0003);
nebound = new google.maps.LatLng(wlat+0.0003,wlon+0.0003);
var initPos=new google.maps.LatLng(wlat,wlon);
var mapOptions={zoom:14,center:initPos,mapTypeId:google.maps.MapTypeId.ROADMAP};
var mapDiv=document.getElementById("map_canvas");
map_canvas=new google.maps.Map(mapDiv,mapOptions);
var bounds=new google.maps.LatLngBounds(swbound,nebound);
var overlay=new google.maps.GroundOverlay("./5Bc3IIj.jpg",bounds);
overlay.setMap(map_canvas);
var streetViewOptions={pov:{zoom:1,heading:161,pitch:-2.6}};
var streetViewDiv=document.getElementById('streetview_canvas');
streetViewDiv.style.fontSize="15px";
streetView=new google.maps.StreetViewPanorama(streetViewDiv,streetViewOptions);
streetView.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(mapDiv);
google.maps.event.trigger(map_canvas,"resize");
map_canvas.setStreetView(streetView);
streetView.registerPanoProvider(getCustomPanorama);
var streetViewInitPos=new google.maps.LatLng(wlat,wlon);
// var streetViewInitPos=new google.maps.LatLng(34.995348,135.7395);
var streetviewService=new google.maps.StreetViewService();
var radius=50;
streetviewService.getPanoramaByLocation(streetViewInitPos,radius,function(result,status){
if(status==google.maps.StreetViewStatus.OK){
initPosPanoID=result.location.pano;
initPosPanoData=result;
streetView.setPosition(result.location.latLng);
map_canvas.panTo(result.location.latLng);
}
}
);
google.maps.event.addListener(streetView,"links_changed",createCustomLink);
var map_marker=new google.maps.Marker({map:map_canvas});
google.maps.event.addListener(streetView,"position_changed",function(){
var position=this.getPosition();
var map_bounds=map_canvas.getBounds();
map_canvas.panTo(position);
});
}
function getCustomPanoramaTileUrl(panoID,zoom,tileX,tileY){
return"./"+panoID+'/'+tileX+'-'+tileY+'_s1.jpg';
}
function getCustomPanorama(panoID){
var streetViewPanoramaData={
links:[],copyright:'',tiles:{
tileSize:new google.maps.Size(2048,1024),worldSize:new google.maps.Size(2048,1024),centerHeading:0,getTileUrl:getCustomPanoramaTileUrl
}
};
switch(panoID){
case initPosPanoID:
return initPosPanoData;
case"Position_S":
//var tmp = new google.maps.LatLng(wlat,wlon);
streetViewPanoramaData["location"]={
description:"TEST TEST TEST TSET",latLng:new google.maps.LatLng(3,3)
};
streetViewPanoramaData["copyright"]=""
break;
case"Position_SW":
streetViewPanoramaData["location"]={
description:"TEST TEST TEST TSET",latLng:new google.maps.LatLng(3,3)
};
streetViewPanoramaData["copyright"]=""
break;
}
if("location"in streetViewPanoramaData){
streetViewPanoramaData.location.pano=panoID;
return streetViewPanoramaData;
}
}
function createCustomLink(){
var links=streetView.getLinks();
var panoID=streetView.getPano();
var currentPos=streetView.getPosition();
switch(panoID){
case initPosPanoID:
links.push({description:"テストエリアへ",pano:"Position_S"});
break;
case"Position_S":
links.push({description:"外へ",pano:initPosPanoID});
links.push({description:"SWへ",pano:"Position_SW"});
break;
case"Position_SW":
links.push({description:"Sへ",pano:"Position_S"});
break;
}
if(links.length){ //compute directional pointer label.
var linkPano;
for(var i=0;i<links.length;i++){
linkPano=getCustomPanorama(links[i].pano);
if(linkPano!==undefined){
links[i].heading=google.maps.geometry.spherical.computeHeading(currentPos,linkPano.location.latLng);
}
}
return links;
}
}
google.maps.event.addDomListener(window,'load',initialize);
</script>
<style type="text/css">html,body{width:100%;
height:100%;
margin:0;
position:absolute}#frame,#streetview_canvas{width:100%;
height:100%;
position:relative}#map_canvas{width:250px;
height:250px;
border:2px solid gray;
background-color:#fff}</style>
</head>
<body>
<div id="streetview_canvas"></div>
<div id="map_canvas"></div>
</body>
</html>

How to get the description of a news Item from GOOGLE AJAX Feed API

I am using a script to load news from different sources, using Google AJAX feed API. How can I get the description of an entry? Below is an hello world program:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://news.google.com/?output=rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
</script>
</head>
<body>
<div id="feed"></div>
</body>
</html>
How can I get the description using the entry object??? I am using the google URL - http://news.google.com/?output=rss for RSS feeds in XML format. I want the "Description" part. How can I get that
You can get the description, but you can't use the JSON format and the entry object to do it. If you read the feed parameters at https://developers.google.com/feed/v1/devguide carefully, you'll see that description is not a field it returns at the entry level - just at the feed level.
To do it, you need to request the feed in XML format, and then load the individual nodes, including description. Here's the relevant snippet I've used to do it - change the formatting etc. as you need.
function initialize() {
var feed = new google.feeds.Feed("http://myblog.com/blog/feed/");
feed.setResultFormat(google.feeds.Feed.XML_FORMAT);
feed.load(function(result) {
if (!result.error) {
var items = result.xmlDocument.getElementsByTagName('item');
item = items[0];
//build each element
var title = document.createElement("h4");
title.innerHTML = item.getElementsByTagName('title')[0].firstChild.nodeValue;
var content = document.createElement("p");
content.innerHTML = item.getElementsByTagName('description')[0].firstChild.nodeValue;
href = item.getElementsByTagName('link')[0].firstChild.nodeValue;
}
The HTML description can be retrieved by using the content variable.
Thus you should have:
div.appendChild(document.createTextNode(entry.content));
Be aware that this will retrieve HTML data format.
After much digging, I found that the Google API uses "contentSnippet" instead of description. No XML formatting needed.
function initialize() {
var feed = new google.feeds.Feed("http://myblog.com/blog/feed/");
feed.setNumEntries(10);
feed.load(function(result) {
if (!result.error) {
$(document).ready(function(){
$('#feed-pull').append('<ul></ul>');
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var desc = entry.contentSnippet;
Change entry.title in:
div.appendChild(document.createTextNode(entry.title));
to entry.description.

Categories

Resources