The weights that have been calculated in program needs to be displayed in a graph. I have added into the code an example taken from here: https://developers.google.com/chart/interactive/docs/gallery/linechart#creating-material-line-charts
Obviously the variable data needs to be replaced by weight, so the existing data (line 17 to 31) can be discarded. The latest version of the code is attached
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['line'] }); // load the visualisation API and corechart package
google.charts.setOnLoadCallback(drawChart); // set a callback to run when the Google Visualization API is loaded
// Callback that creates and populates a data table, instantiates the chart, passes in the data and draws it.
function drawChart() {
// Create the data table for the symbol in question.
var data = new google.visualization.DataTable();
data.addColumn('number', 'k');
data.addColumn('number', 'lambda');
data.addRows([
[-0.050, 0.00952],
[-0.040, 0.00952],
[-0.030, 0.01904],
[-0.025, 0.03809],
[-0.020, 0.02857],
[-0.015, 0.04761],
[-0.010, 0.02857],
[-0.005, 0.18095],
[0.000, 0.21904],
[0.005, 0.16190],
[0.010, 0.12380],
[0.015, 0.05714],
[0.020, 0.03809],
[0.030, 0.02857],
[0.080, 0.00952]
]);
var chart = new google.charts.Line(document.getElementById('#chart_weights'));
chart.draw(data, { height: 288, width: 550, lineWidth: 1 });
}
</script>
</head>
<body>
<table>
<tr><td>k: </td><td><input id="k" type="number" value="2.2" min="0" max="10" step="0.1" /></td></tr>
<tr><td>lambda: </td><td><input id="lambda" type="number" value="7.6" min="0" max="10" step="0.1" /></td></tr>
</table>
<p id="message"> </p>
<script type="text/javascript">
UpdateValues();
document.getElementById("k").addEventListener("click", function() {
UpdateValues();
});
document.getElementById("lambda").addEventListener("click", function() {
UpdateValues();
});
function UpdateValues() {
var weight = [];
var k = document.getElementById("k").value;
var lambda = document.getElementById("lambda").value;
for (var x = 0.1; x < 20; x++) {
weight.push([x, k * Math.pow(x/lambda, k-1) * Math.exp(-Math.pow(x/lambda, k)) / lambda]);
document.getElementById("message").innerHTML = weight;
}
}
</script>
<div id="chart_weights"></div>
</body>
</html>
I don't know why these graphs are not beiNg displayed..
THanks in advance to helping hands
Please, check this example
So, The main problem was that Container is not defined.
In your code you write document.getElementById('#chart_weights') but you should write document.getElementById('chart_weights') without #.
Related
I have 3 inputs and from where by click in a button get those input value and create a Google Visualization dynamic Pie Chart depend on those value . I have made like this code below , but did not getting expecting result
HTML
<input type="text" name="BigHalo" id="BigHalo">
<input type="text" name="MediumHalo" id="MediumHalo">
<input type="text" name="SmallHalo" id="SmallHalo">
<button type="button" onclick="onclickChartValur()" >CLICK HERE</button>
<div id="donutchart" style="width:380px; height:380px;"></div>
SCRIPT CODE
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart(BigHalo,MediumHalo,SmallHalo) {
var data = google.visualization.arrayToDataTable([
['Language', 'Speakers (in millions)'],
['Big Halo', BigHalo],
['Medium Halo', MediumHalo],
['Small Halo',SmallHalo]
]);
var options = {
legend: 'none',
pieSliceText: 'label',
title: '',
pieStartAngle: 100,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
function onclickChartValur() {
var BigHalo = $("#BigHalo").val();
var MediumHalo = $("#MediumHalo").val();
var SmallHalo = $("#SmallHalo").val();
drawChart(BigHalo,MediumHalo,SmallHalo);
}
</script>
ERROR RESULT ::
EXPECTING RESULT
It is Solved! I made it . Here I am sharing this technique.
HTML
<input type="text" name="BigHalo" id="BigHalo">
<input type="text" name="MediumHalo" id="MediumHalo">
<input type="text" name="SmallHalo" id="SmallHalo">
<button type="button" onclick="onclickChartValur()" >CLICK HERE</button>
<div id="donutchart" style="width:380px; height:380px;"></div>
Script
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function drawChart(BigHalo,MediumHalo,SmallHalo) {
var data = google.visualization.arrayToDataTable([
['Language', 'Speakers (in millions)'],
['Big Halo', parseInt(BigHalo)],
['Medium Halo', parseInt(MediumHalo)],
['Small Halo', parseInt(SmallHalo)]
]);
var options = {
legend: 'none',
title: '',
pieStartAngle: 100,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
function ontypeChartValur() {
var BigHalo = $("#BigHalo").val();
var MediumHalo = $("#MediumHalo").val();
var SmallHalo = $("#SmallHalo").val();
drawChart(BigHalo,MediumHalo,SmallHalo);
}
</script>
And OnClick event this cart will be generate easily ! Also we can make it with onKeyup / onKeydown event also.
NOTE : parseInt is used here because of convert string to number.
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.
I have created a form and trying to display submitted values in the google chart. I have tried to create wrapper for drawChart() and want to load drawChart() after submit button is clicked. But, drawChart() function gets called onload. What is the problem with my code?
HTML-
<form method= "post" action = "#" id="formValue">
<label><input type="number" value="1" id="ip1"/>inpu1</label>
<label><input type="number" value="2" id="ip2"/> input2</label>
<input type="submit" value="Add" onclick="initializer()"/>
</form>
JS-
<script>
var ip1, ip2;
var str = "hello";
var str2 = "hello2";
function initializer(){
ip1 = document.getElementById("ip1").value;
ip2 = document.getElementById("ip2").value;
drawChart();
}
google.charts.setOnLoadCallback(initializer);
google.charts.load('current', {'packages':['corechart']});
function drawChart() {
var x2= [
[
str,
ip1
],
[
str2,
ip2
]
];
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(x2);
var options = {'title':'How Much Pizza I Ate Last Night',
'width':500,
'height':600};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
remove this...
google.charts.setOnLoadCallback(initializer);
it runs initializer when...
google.charts.load('current', {'packages':['corechart']});
is finished.
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);
});
}
I am trying to add direction to a line overlay i have added to map using openlayers. I have created map and line overlay inside my jsp but the problem is that when ${variable} is used in html file, I am getting output as expected with correct direction shown. But when implemented inside jsp all arrows seem to b pointing to just one direction.
I think the problem is that ${variable} in javascript not substituted in jsp.
Here is the piece of code.
direction.jsp
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Line Direction Arrow in OpenLayers</title>
<link rel="stylesheet" href="http://openlayers.org/dev/theme/default/style.css" type="text/css" />
<link rel="stylesheet" href="../theme/default/style.css" type="text/css">
<link rel="stylesheet" href="style.css" type="text/css">
<style type="text/css">
#map {
width: 600px;
height: 400px;
border: 1px solid #ccc;
}
</style>
<script src="js-libraries/OpenLayers.js" type="text/javascript"></script>
<script src="js-libraries/directions.js" type="text/javascript"></script>
<script type="text/javascript">
var map = null;
var myNetwork =null;
function init(){
map = new OpenLayers.Map('map');
var ol_osm = new OpenLayers.Layer.OSM("Simple OSM Map");
map.addLayers([ol_osm]);
//vector layer
var layer = new OpenLayers.Layer.Vector("Line");
map.addLayer(layer);
// add edit panel
var editPanel = new OpenLayers.Control.EditingToolbar(layer);
map.addControl(editPanel);
//add direction layer
OpenLayers.Renderer.symbol.arrow = [0,2, 1,0, 2,2, 1,0, 0,2];
var styleMap = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
{graphicName:"arrow",rotation : "${angle}"},
OpenLayers.Feature.Vector.style["default"]));
var dirLayer = new OpenLayers.Layer.Vector("direction", {styleMap: styleMap});
map.addLayer(dirLayer);
map.setCenter(new OpenLayers.LonLat(-702335,7043201),15);
//console.log("Starting map");
}
function updateDirection() {
//alert(map.layers[2].name);
map.layers[2].removeAllFeatures();
var points=[];
var features =map.layers[1].features;
//alert(features.length);
for (var i=0;i<features.length ;i++ ) {
var linePoints = createDirection(features[i].geometry,get_position_value(),get_foreachseg_value()) ;
//alert(get_foreachseg_value());
// for (var j=0;j<linePoints.length ;j++ ) {
// linePoints[j].attributes.lineFid = features[i].fid;
// }
points =points.concat(linePoints);
// alert(points);
}
map.layers[2].addFeatures(points);
}
function get_position_value() {
for (var i=0; i < document.direction.position.length; i++)
{
if (document.direction.position[i].checked)
{
return document.direction.position[i].value;
}
}
}
function get_foreachseg_value() {
if (document.direction.foreachseg.checked){
return true;
} else {
return false;
}
}
</script>
</head>
<body onload="init()">
<table><tr>
<td><div id="map" class="smallmap"></div></td>
<td><div align="left">
<form name="direction">
<input type="radio" name="position" value="start"/> start <br>
<input type="radio" name="position" value="end"/> end <br>
<input type="radio" name="position" value="middle" CHECKED/>middle <br>
<input type="checkbox" name="foreachseg" /> Create for each segment of line <br>
<input type=button value="Update" onClick=updateDirection(); />
</form>
</div></td>
</tr></table>
</body>
</html>
Is there anyway to get the corresponding angle in jsp? the page seems to b working fine when the file was renamed direction.html But when renamed as direction.jsp the angle value is not received correctly. I need to use this with my jsp application. please help.
Thanks and Regards
Ginger.
As JSP is server side and javascript is client side so you can't pass parameters like this, an alternate would be to add angle as hidden field in your jsp
<input type="hidden" value="angle_value_comes_here" id="angle"/>
and then access it in javascript using
var angle = $('#angle').val();
Hope it helps
I am posting my updated code in here.
function updateDirection() {
flagMarkerStatus = 5;
var angles = 0;
dirLayer.removeAllFeatures();
var linePoints=[];
var points=[];
var features =lineLayer.features;
document.getElementById("angle").value="";
for (var i=0;i<features.length ;i++ ) {
var linePoints = createDirection(features[i].geometry,"middle",true);
points =points.concat(linePoints);
angles = document.getElementById("angle").value;
//'angle' div contains angle values seperated by '~'
angles=angles.replace(/\[|\]/g, '');
angles=angles.split("~");
for(var i=0;i<linePoints.length;i++){
var styleMap = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
{graphicName:"arrow",rotation : angles[i],strokeWidth: 3,strokeColor: "#ff0000"},
OpenLayers.Feature.Vector.style["default"]));
dirLayer.styleMap = styleMap;
dirLayer.addFeatures(linePoints[i]);
}
}
}