How to fuse these two javascript files? - javascript

I have a javascript file that is loading up the google charts API and drawing a graph, and another javascript file that handles an html form on the page. I'd like to fuse these two together, as the form will be providing the graph with data. However, when I try to put there google charts js file (graph.js), it refuses to load the graph. I've tried putting it in several locations, but it only loads if the graph.js is a separate js file that is linked within the html document. Can someone tell me how I can properly combine these two files:
CostComparer.js (the form handler):
$(document).ready(function(){
//variable setup
var wifi;
var firewall;
var backup;
var vpn;
var install;
var result;
$('#submit').click(function(){
$("#chart_div").show('slow');
$("#table_div").show('slow');
wifi = $('input[name=wifiPrice]').val();
firewall = $('input[name=firewallPrice]').val();
backup = $('input[name=backupPrice]').val();
vpn = $('input[name=vpnPrice]').val();
install = $('input[name=installPrice]').val();
result = parseInt(wifi) + parseInt(firewall) + parseInt(backup) + parseInt(vpn) + parseInt(install);
var resultbox = $('#result');
var cccontainer = $('#cccontainer');
if(resultbox.height() < 10){
cccontainer.hide('slow').delay(500);
cccontainer.show('slow');
setTimeout(function() {
resultbox.append('<h1>You Paid: <br />$' + result + '</h1>')
}, 500);
} else {
resultbox.empty()
cccontainer.hide('slow').delay(500);
cccontainer.show('slow');
setTimeout(function() {
resultbox.append('<h1>You Paid: <br />$' + result + '</h1>')
}, 500);
}
});
});
and graph.js:
google.load("visualization", "1", {packages: ["corechart"]});
google.setOnLoadCallback(drawChart);
var competitorCost = function(time){
return 3000 + (time * 300)
};
var ourCost = function(time){
return 1000 + (time * 50);
};
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'Entreda', 'Competitors'],
['0', ourCost(0), competitorCost(0)],
['6', ourCost(6), competitorCost(6)],
['12', ourCost(12), competitorCost(12)],
['18', ourCost(18), competitorCost(18)],
['24', ourCost(24), competitorCost(24)]
]);
var options = {
title: 'Entreda vs Competitor Costs',
width: 445,
height: 250,
pointSize: 5
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

There was a problem with my compiler it seems. It worked after appending graph.js to the bottom outside of $document.ready():
$(document).ready(function(){
//variable setup
var wifi;
var firewall;
var backup;
var vpn;
var install;
var result;
$('#submit').click(function(){
$("#chart_div").show('slow');
$("#table_div").show('slow');
wifi = $('input[name=wifiPrice]').val();
firewall = $('input[name=firewallPrice]').val();
backup = $('input[name=backupPrice]').val();
vpn = $('input[name=vpnPrice]').val();
install = $('input[name=installPrice]').val();
result = parseInt(wifi) + parseInt(firewall) + parseInt(backup) + parseInt(vpn) + parseInt(install);
var resultbox = $('#result');
var cccontainer = $('#cccontainer');
if(resultbox.height() < 10){
cccontainer.hide('slow').delay(500);
cccontainer.show('slow');
setTimeout(function() {
resultbox.append('<h1>You Paid: <br />$' + result + '</h1>')
}, 500);
} else {
resultbox.empty()
cccontainer.hide('slow').delay(500);
cccontainer.show('slow');
setTimeout(function() {
resultbox.append('<h1>You Paid: <br />$' + result + '</h1>')
}, 500);
}
});
});
google.load("visualization", "1", {packages: ["corechart"]});
google.setOnLoadCallback(drawChart);
var competitorCost = function(time){
return 3000 + (time * 300)
};
var ourCost = function(time){
return 1000 + (time * 50);
};
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'Entreda', 'Competitors'],
['0', ourCost(0), competitorCost(0)],
['6', ourCost(6), competitorCost(6)],
['12', ourCost(12), competitorCost(12)],
['18', ourCost(18), competitorCost(18)],
['24', ourCost(24), competitorCost(24)]
]);
var options = {
title: 'Entreda vs Competitor Costs Over Time',
width: 480,
height: 270,
pointSize: 5
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Related

How to show firebase realtime data to Process Bar

I want to show realtime firebase data to my process bars,
can anyone help me? Please I'm so stuck. This is my data:
And this is my processbar:
My Code:
<script>
// Firebase Tinggi Air
var dbref_pakan = firebase.database();
dbref_pakan.ref("tinggi").on("value", function(snapshot) {
var tinggi_awal = data.val();
var tinggi_pakan = tinggi_awal.pakan;
var tinggi_air = "0." + tinggi_awal.air;
});
</script>
<script>
// entah
var obtained = 75;
var total = 150;
var percent = obtained*100/total;
var percentage = "0." + percent;
let options = {
startAngle: -1.55,
size: 150,
value: percentage,
fill: {gradient: ['#315ACD', '#4E75E2']}
}
$(".circle .bar").circleProgress(options).on('circle-animation-progress',
function(event, progress, stepValue){
$(this).parent().find("span").text(String(stepValue.toFixed(2).substr(2)) + "%");
});
$(".react .bar").circleProgress({
value: tinggi_air
});
</script>
I put "percentage" value in "value:" and it worked, "but tinggi_air" didn't work, instead it followed the value from var percentage.
You need to update the values using a snapshot listener while also exporting the values externally. Currently, you have them declared inside the function but not returning it to the loading bar
I don't have the full scope of the loading bar you are using, so I made some assumptions but in general, this is what you should be looking at
<script>
var obtained = 75;
var total = 150;
var percent = obtained*100/total;
var percentage = "0.0";
var percent_pakan;
var percent_air;
// Firebase Tinggi Air
const listener = firebase.database().ref("tinggi")
.on("value", (snapshot) => {
var data = data.val();
percent_pakan = data.pakan;
percent_air= "0." + data.air;
});
let options = {
startAngle: -1.55,
size: 150,
value: percent_pakan,
fill: {gradient: ['#315ACD', '#4E75E2']}
}
$(".circle .bar").circleProgress(options).on('circle-animation-progress',
function(event, progress, stepValue){
$(this).parent().find("span").text(String(stepValue.toFixed(2).substr(2)) + "%");
});
$(".react .bar").circleProgress({
value: percent_air
});
</script>
// Progress Bar START
var tinggi = database.ref("tinggi");
var tinggi_awal = 0;
var tinggi_air = "0.0";
var tinggi_pakan = "0.0";
tinggi.on("value", function (data) {
tinggi_awal = data.val();
tinggi_pakan = "0." + tinggi_awal.pakan;
tinggi_air = "0." + tinggi_awal.air;
console.log(tinggi_air);
let optionsPakan = {
startAngle: -1.55,
size: 150,
value: tinggi_pakan,
fill: { gradient: ['#315ACD', '#4E75E2'] }
}
let optionsAir = {
startAngle: -1.55,
size: 150,
value: tinggi_air,
fill: { gradient: ['#315ACD', '#4E75E2'] }
}
$(".circle-pakan .bar").circleProgress(optionsPakan).on('circle-animation-progress',
function (event, progress, stepValue) {
$(this).parent().find("span").text(String(stepValue.toFixed(2).substr(2)) + "%");
});
$(".circle-air .bar").circleProgress(optionsAir).on('circle-animation-progress',
function (event, progress, stepValue) {
$(this).parent().find("span").text(String(stepValue.toFixed(2).substr(2)) + "%");
});
});
// Progress Bar END
}

Dynamic chart with CanvasJs doesn't get update while reading from a file

I've been trying to get a dynamic chart working with CanvasJs. I have a file that gets updated (by another program) and I would like to update my chart each time I have a new record.
I've seen this example (last chart) and I tried to do the same but I'm actually reading from a file.
Here is my code :
<!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 dps = [{x: new Date(2017, 04, 20, 07, 20, 00 ), y: 30}]; //dataPoints.
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: " Cooling Machine Status "
},
axisX:{
valueFormatString: "DD-MM-YY HH:mm:ss" ,
labelAngle: -50
},
axisY:{
title: "Cooling Temperature (F)"
},
data: [{
type: "line",
showInLegend: true,
name: "Temperature",
dataPoints : dps
}]
});
chart.render();
var updateChart = function () {
var rawFile = new XMLHttpRequest();
rawFile.open("GET","/analyticResults/coolingMachine.csv", true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var dps = csvLines = points = [];
csvLines = rawFile.responseText.split(/[\r?\n|\r|\n]+/);
for (var i = 0; i < csvLines.length; i++)
if (csvLines[i].length > 0) {
points = csvLines[i].split(",");
var dateTime = points[0].split(" ");//dateTime[0] = date, dateTime[1] = time
var date = dateTime[0].split("-");
var time = dateTime[1].split(":");
dps.push({
x: new Date(date[2], date[1], date[0], time[0], time[1], time[2]),
y: parseFloat(points[1])
});
}
}
}
};
rawFile.send(null);
if (dps.length > 10 )
{
dps.shift();
}
chart.render();
};
setInterval(function(){updateChart()}, 1000);
}
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 70%;">
</div>
</body>
</html>
When I debug the javascript I can see that the values are getting pushed in dps but the chart is not updating...
Did I miss someting ?
Thank you for your time
You are passing dps to chart-dataPoints. But at the same time you are pushing dps that is declared locally within updateChart method. Removing dps declaration within updateChart method should work in your case.

Geochart doesn't take any color

I wonder why geochart doesn't take any color from my code (take color value from Google sheet), not even defaultColor or colorAxis as you can see in the line that commented out,I have tried that all but it doesn't work.
The data in the Google sheet look like this:
Hope someone can help.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Map</title>
<style xmlns="http://www.w3.org/2000/svg">
#colormap path:hover { fill: #90db7c; }
#colormap rect:hover {fill:transparent;}
</style>
<script type='text/javascript' src='https://www.gstatic.com/charts/loader.js'></script>
<script src="https://www.google.com/jsapi"></script>
<script type='text/javascript'>
// Load Charts and the corechart package.
google.charts.load('current', {packages: ['geochart']});
// Callback that draws
function drawRegionsMap() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1dTfxVvfDKn6iXn4W_m7HJ_86JOGNDsxYSSaXipEo0vM/edit#gid=0');
// query.setQuery('select A,B,C');
query.send(handleQueryResponseTR);
}
function handleQueryResponseTR(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var colorValues = [];
var numRows = data.getNumberOfRows();
for (var i = 0; i < numRows; i++) {
colorValues.push(parseInt(data.getValue(i, 6)));
}
var view = new google.visualization.DataView(data);
//show data in tooltips
view.setColumns([0,{
type:'string',
label : 'dataname',
calc: function (dt, row) {
var dt1 = dt.getFormattedValue(row, 1)
var dt2 = dt.getFormattedValue(row, 2)
var url = dt.getFormattedValue(row, 4)
var image = dt.getFormattedValue(row, 5)
//colorValues.push(dt.getFormattedValue(row, 6))
return dt1 + " - " + dt2
},
role: 'tooltip',
p: {html: true}
}]);
//assign color to colorValues
var colorNames = [];
colorValues.forEach(function(value) {
if (value <= 2) {
colorNames.push('red');
//alert('red');
} else if ((value > 2) && (value <= 4)) {
colorNames.push('yellow');
//alert('yellow');
} else {
colorNames.push('green');
//alert('green');
}
});
var chart = new google.visualization.GeoChart(document.getElementById('colormap'));
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
if (selection.length > 0) {
//console.log(data.getValue(selection[0].row, 4));
window.open(data.getValue(selection[0].row, 4));
}
});
// Set options for the chart.
var options = {
defaultcolor: 'yellow'
//title:'WEEE',
//colorAxis: {
// values: [1, 2, 3, 4,5,6],
// colors: ['green', 'yellow', 'orange' ,'red','purple','lightblue'],
// };
//colors: colorNames,
//values: colorValues
// },
//backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 },
//backgroundColor: '#FFFFFF',
//datalessRegionColor: '#F5F0E7',
//displayMode: 'regions',
//enableRegionInteractivity: 'true',
//resolution: 'countries',
//sizeAxis: {minValue: 1, maxValue:1,minSize:10, maxSize: 10},
//region:'world',
//keepAspectRatio: true,
//width:800,
//height:600,
//tooltip: {isHtml:'true',textStyle: {color: '#444444'} }
// };
}
chart.draw(view, options);
}
// Draw the chart when Charts is loaded.
google.charts.setOnLoadCallback(drawRegionsMap);
</script>
</head>
<body>
<div id='colormap'></div>
</body>
</html>

Pass Custom Parameter to query.send Google Query Language

I am using google's charts API to create a web-based dashboard. I want to draw many graphs and need to pass custom parameters to the handleDataQueryResponse function from this link: https://developers.google.com/chart/interactive/docs/spreadsheets#sheet-name. This function is called via a query.send(handleDataQueryResponse) call. I would have thought I could do this by calling: query.send(function() { handleDataQueryResponse(parameters) }); but this hasn't been working for me. Any ideas? Open to other approaches to making the query and its handler reusable!
More info on google's javascript chart API here: https://developers.google.com/chart/interactive/docs/quick_start.
something like this work for you?
google.charts.load('current', {
callback: function () {
drawChart0();
drawChart1();
},
packages:['corechart', 'table']
});
function drawChart0() {
var chart = new google.visualization.BarChart(document.getElementById('barchart'));
var query = "http://www.google.com/fusiontables/gvizdata?tq=SELECT 'Label' as beach, 'Pieces total' as Total FROM 1c-FiEDwdwMt55a4AlE8Xuu40rUBR_qeI8ENiHtPV";
var options = {
animation: {
duration: 500,
startup: true,
easing: 'out'
},
chartArea: {
width: '40%'
}
};
sendQuery(query, chart, options);
}
function drawChart1() {
var chart = new google.visualization.Table(document.getElementById('tablechart'));
var query = "https://docs.google.com/spreadsheets/d/19olM1pEF5qQvvKhwSH3d_X4w2DVfOWDwDtZKNFlMY3w/edit#gid=0&tq=select A, B where A >= date '2016-01-01'";
var options = {};
sendQuery(query, chart, options);
}
function sendQuery(query, chart, options) {
new google.visualization.Query(query).send(function (response) {
chart.draw(response.getDataTable(), options);
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barchart"></div>
<div id="tablechart"></div>
I figured out one solution, and let me tell you, it's not pretty. But it works. As always, happy for improvements and feedback! Thanks #WhiteHat for helping me out.
google.charts.setOnLoadCallback(function() {
drawChart('chart1', 0, 'SELECT A, B, C, D, E', {title: 'Chart 1'})
drawChart('chart2', 1, 'SELECT A, H, I, J', {title: 'Chart 2'})
});
var chartsArray = [];
var optionsArray = [];
var nextID = 0;
function drawChart(tag, id, sqlCommand, options= {}, sheetName='Sheet1', numHeaders=1) {
chartsArray[id] = new google.visualization.ColumnChart(document.getElementById(tag));
optionsArray[id] = options;
var queryString = encodeURIComponent(sqlCommand);
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1dfRA_NDsdfED3OEdx-v3ZzA2-oWPS4kU_2mV-PY/gviz/tq?sheet=' + sheetName + '&headers=' + numHeaders.toString() + '&tq=' + queryString);
query.send(handleDataQueryResponse);
}
function handleDataQueryResponse(response, id) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
chartsArray[nextID].draw(data, optionsArray[nextID]);
nextID += 1;
}

Combining two control panels(AB) or toggle them (A) or (B)

I have two control panels; one is for the default draw features, the other for measure tools.
The problem is that since they are in different panels it is possible to run two controls simultaneously, one from each panel. (this didn't seem like much of a problem before, but I noticed that when the measure and default draw tools are activated together, they cancel out the line end function)
What I am trying to do is either place all controls in one panel and toggle them together or toggle the panels(e.g. when control from panel 1 is activated, deactivate all controls in panel 2)
Here is my code:
Default Controls Panel:
OpenLayers.Control.CustomNavToolbar = OpenLayers.Class(OpenLayers.Control.Panel,{
initialize: function(options){
OpenLayers.Control.Panel.prototype.initialize.apply(this, [options]);
this.addControls([
new OpenLayers.Control.Navigation({displayClass: 'olControlNavigation', zoomBoxEnabled:false}),
new OpenLayers.Control.DrawFeature(vlayer, OpenLayers.Handler.Point, {displayClass: 'olControlDrawPoint'}),
new OpenLayers.Control.DrawFeature(vlayer, OpenLayers.Handler.Path, {displayClass: 'olControlDrawPath'}),
new OpenLayers.Control.DrawFeature(vlayer, OpenLayers.Handler.Polygon, {displayClass: 'olControlDrawPolygon'}),
new OpenLayers.Control.ZoomBox({displayClass: 'olControlZoomBox', alwaysZoom:true})
])
this.displayClass = 'olControlCustomNavToolbar'
},
draw: function(){
var div = OpenLayers.Control.Panel.prototype.draw.apply(this, arguments);
this.defaultControl = this.controls[0];
return div;
}
});
var panel = new OpenLayers.Control.CustomNavToolbar({div:OpenLayers.Util.getElement('panel')});
map.addControl(panel);
Measure Controls Panel:
allControls = {
line: new OpenLayers.Control.Measure(OpenLayers.Handler.Path, {
persist: true,
handlerOptions: {
layerOptions: {
renderers: renderer,
styleMap: styleMap
}
},
textNodes: null,
callbacks:{
create:
function(){
this.textNodes = [];
// vlayer.destroyFeatures(vlayer.features);
mouseMovements = 0;
},
modify:
function(point, line){
if(mouseMovements++ < 5){
return;
}
var len = line.geometry.components.length;
var from = line.geometry.components[len -2];
var to = line.geometry.components[len -1];
var ls = new OpenLayers.Geometry.LineString([from, to]);
var dist = this.getBestLength(ls);
if(!dist[0]){
return;
}
var total = this.getBestLength(line.geometry);
var label = dist[0].toFixed(3) + " " + dist[1];
var textNode = this.textNodes[len -2] || null;
if(textNode && !textNode.layer){
this.textNodes.pop();
textNode = null;
}
if(!textNode){
var c = ls.getCentroid();
textNode = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(c.x, c.y), {}, {
label: "",
fontColor: "#800517",
fontSize: "13px",
fontFamily: "Tahoma",
fontWeight: "bold",
labelAlign: "cm"
});
this.textNodes.push(textNode);
vlayer.addFeatures([textNode]);
}
textNode.geometry.x = (from.x + to.x) / 2;
textNode.geometry.y = (from.y + to.y) / 2;
textNode.style.label = label;
textNode.layer.drawFeature(textNode);
this.events.triggerEvent("measuredynamic", {
measure: dist[0],
total: total[0],
units: dist[1],
order: 1,
geometry: ls
});
}
}
}),
polygon: new OpenLayers.Control.Measure(
OpenLayers.Handler.Polygon, {
persist: true,
immediate: true,
handlerOptions: {
layerOptions: {
renderers: renderer,
styleMap: styleMap
}
}
}
)
};
var control;
for(var key in allControls) {
control = allControls[key];
control.events.on({
"measure": handleMeasurements,
"measurepartial": handleMeasurements
});
map.addControl(control);
}
..and just for reference
function handleMeasurements(evt){
var geometry = evt.geometry;
var units = evt.units;
var order = evt.order;
var measure = evt.measure;
var element = document.getElementById('output');
var position = (map.getLonLatPxFromViewPortPx);
var out = "";
if(order == 1){
out += "Distance: " + measure.toFixed(3) + " " + units;
}
else{
out += "Area: " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";
}
element.innerHTML = out;
}
function toggleControl(element){
vlayer.destroyFeatures(vlayer.features);
for(key in allControls){
var control = allControls[key];
if(element.value == key && element.click){
control.activate();
var label = document.getElementById('output');
var emptyOut = "";
label.innerHTML = emptyOut;
}
else{
control.deactivate();
}
}
}
Been looking for a way to do this and so far have not been able to find anything useful, if you could help me with some suggestions about how to go about this it would be very appreciated. Thanks
EDIT: I am not using GeoExt and am not considering using it. I'm looking for suggestions about how to go about this using only the OpenLayers 2.11 library. Thanks again.

Categories

Resources