Add custom icon on specific point on google charts timeline [duplicate] - javascript

I want to add markers on the Google Timeline chart as shown here Timeline Chart with Markers
I am currently following the solution given here: Google Charts Add Layer On Top Of Timeline. But, here there needs to be a timeline element only then can the marker be present over it. But, I want a way that a marker can be added without having any timeline data at that position in the row. Is there a built in feature for adding markers in Google Timelines, or a custom way which does not require adding a dummy timeline.

there are no built-in features for adding markers.
and since the answer you reference is a custom solution,
we can modify the solution to fit our needs.
we don't necessarily need a timeline element in order to place a marker.
but we do need data, in order to draw the timeline,
on which to place the markers.
out of the box, the timeline will limit the x-axis to the range of dates found in the data.
but we can set a custom x-axis range, to make it larger,
and allow more room for markers, where there are no timeline elements.
hAxis: {
minValue: dateRangeStart,
maxValue: dateRangeEnd,
}
see following working snippet...
google.charts.load('current', {
packages:['timeline']
}).then(function () {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({type: 'string', id: 'Row'});
dataTable.addColumn({type: 'string', id: 'Bar'});
dataTable.addColumn({type: 'date', id: 'Start'});
dataTable.addColumn({type: 'date', id: 'End'});
var currentYear = (new Date()).getFullYear();
dataTable.addRows([
['Row 1', 'A-1', new Date(currentYear, 0, 1), new Date(currentYear, 2, 31)],
['Row 1', 'A-2', new Date(currentYear, 3, 1), new Date(currentYear, 5, 30)],
['Row 2', 'B-1', new Date(currentYear, 6, 1), new Date(currentYear, 8, 31)],
['Row 2', 'B-2', new Date(currentYear, 9, 1), new Date(currentYear, 11, 31)]
]);
var dataTableGroup = google.visualization.data.group(dataTable, [0]);
var dateRangeStart = new Date(currentYear - 1, 0, 1);
var dateRangeEnd = new Date(currentYear + 1, 11, 31);
var rowHeight = 44;
var options = {
height: (dataTableGroup.getNumberOfRows() * rowHeight) + rowHeight,
hAxis: {
minValue: dateRangeStart,
maxValue: dateRangeEnd,
}
};
function drawChart() {
chart.draw(dataTable, options);
}
// add custom marker
function addMarkers(events) {
var baseline;
var baselineBounds;
var chartElements;
var labelFound;
var labelText;
var marker;
var markerLabel;
var markerSpan;
var rowLabel;
var svg;
var svgNS;
var timeline;
var timelineUnit;
var timelineWidth;
var timespan;
var xCoord;
var yCoord;
// initialize chart elements
baseline = null;
svg = null;
svgNS = null;
timeline = null;
chartElements = container.getElementsByTagName('svg');
if (chartElements.length > 0) {
svg = chartElements[0];
svgNS = svg.namespaceURI;
}
chartElements = container.getElementsByTagName('rect');
if (chartElements.length > 0) {
timeline = chartElements[0];
}
chartElements = container.getElementsByTagName('path');
if (chartElements.length > 0) {
baseline = chartElements[0];
}
if ((svg === null) || (timeline === null) || (baseline === null)) {
return;
}
timelineWidth = parseFloat(timeline.getAttribute('width'));
baselineBounds = baseline.getBBox();
timespan = dateRangeEnd.getTime() - dateRangeStart.getTime();
timelineUnit = (timelineWidth - baselineBounds.x) / timespan;
// add events
events.forEach(function (event) {
// find row label
rowLabel = dataTable.getValue(event.row, 0);
chartElements = container.getElementsByTagName('text');
if (chartElements.length > 0) {
Array.prototype.forEach.call(chartElements, function(label) {
if (label.textContent.indexOf('…') > -1) {
labelText = label.textContent.replace('…', '');
} else {
labelText = label.textContent;
}
if (rowLabel.indexOf(labelText) > -1) {
markerLabel = label.cloneNode(true);
}
});
}
// calculate placement
markerSpan = event.date.getTime() - dateRangeStart.getTime();
// add label
markerLabel.setAttribute('text-anchor', 'start');
markerLabel.setAttribute('fill', event.color);
markerLabel.setAttribute('x', (baselineBounds.x + (timelineUnit * markerSpan) + 6));
markerLabel.textContent = event.name;
svg.appendChild(markerLabel);
// add marker
xCoord = (baselineBounds.x + (timelineUnit * markerSpan) - 4);
yCoord = parseFloat(markerLabel.getAttribute('y'));
switch (event.type) {
case 'triangle':
marker = document.createElementNS(svgNS, 'polygon');
marker.setAttribute('fill', 'transparent');
marker.setAttribute('stroke', event.color);
marker.setAttribute('stroke-width', '3');
marker.setAttribute('points', xCoord + ',' + (yCoord - 10) + ' ' + (xCoord - 5) + ',' + yCoord + ' ' + (xCoord + 5) + ',' + yCoord);
svg.appendChild(marker);
break;
case 'circle':
marker = document.createElementNS(svgNS, 'circle');
marker.setAttribute('cx', xCoord);
marker.setAttribute('cy', yCoord - 5);
marker.setAttribute('r', '6');
marker.setAttribute('stroke', event.color);
marker.setAttribute('stroke-width', '3');
marker.setAttribute('fill', 'transparent');
svg.appendChild(marker);
break;
}
});
}
google.visualization.events.addListener(chart, 'ready', function () {
addMarkers([
{row: 0, date: new Date(currentYear - 1, 1, 11), name: 'Event 1', type: 'triangle', color: 'red'},
{row: 1, date: new Date(currentYear + 1, 5, 23), name: 'Event 2', type: 'circle', color: 'purple'},
{row: 3, date: new Date(currentYear + 1, 8, 2), name: 'Event 3', type: 'triangle', color: 'magenta'}
]);
});
window.addEventListener('resize', drawChart, false);
drawChart();
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline"></div>

Related

How in leaflet add custom data to polyline?

In jquery 3/leaflet / turf app
I use custom class extended from CircleMarker
as I need in any marker keep info about any point and info on nearby points.
Markers are connected with polylines and I want to keep simialr information polyline
and clicking on it get this info. I failed to make it. I do
customCircleMarker = L.CircleMarker.extend({
options: {
first_market: false,
last_market: false,
point_id: null,
prior_point_id: null,
}
});
var selectedPoint= {}
var points = [
{id: 1, title:'title #1 ', lat:52.509, lng:-3.08},
{id: 2, title:'title #2 ', lat:51.503, lng:-1.06},
{id: 3, title:'title #3 ', lat:49.51, lng:-2.47}
];
var mymap = L.map('mapid').setView([51.505, -0.09], 7);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1
}).addTo(mymap);
drawPoints()
function drawPoints() {
let polylinePoints= [] // I get all info about all Polylines
let loop_index = 0
points.forEach(point => {
let priorPoint= null
if(loop_index > 0) {
priorPoint= points[loop_index - 1]
}
var myMarker = new customCircleMarker([point.lat, point.lng], {
title: 'unselected',
radius: 20,
first_market: loop_index == 0,
last_market: loop_index == points.length-1,
point_id: point.id,
prior_point_id: priorPoint ? priorPoint.id : null,
});
myMarker.on('click', function (event) { // THAT WORKS OK
console.log('myMarker.event.target.options.point_id::')
console.log(event.target.options.point_id)
});
myMarker.addTo(mymap);
polylinePoints[polylinePoints.length]=[point.lat, point.lng]
loop_index++
})
var radius = 10;
var polyline = new L.Polyline(polylinePoints, {
color: 'green',
opacity: 1,
weight: 2,
customData:{ // BUT TAT DOES NOT WORK AS POINT IS OUT OF LOOP
point_id: point.id,
prior_point_id: priorPoint ? priorPoint.id : null,
}
// offset: radius
});
// Add click listener
polyline.on('click', function (event) {
event.originalEvent.stopPropagation();
window.event.cancelBubble = true; // CAN NOT STOP Propagation
showModal(event)
// alert('Polyline clicked!');
});
// Add polyline to featuregroup
polyline.addTo(mymap);
// zoom the map to the polyline
mymap.fitBounds(polyline.getBounds());
} // function drawPoints () {
How can I add custom data to polyline ?
Thanks!
You don't have to extend the CircleMarker class to add more options. You can do this at the default way:
var myMarker = L.circleMarker([point.lat, point.lng], {
title: 'unselected',
radius: 20,
first_market: loop_index == 0,
last_market: loop_index == points.length-1,
point_id: point.id,
prior_point_id: priorPoint ? priorPoint.id : null,
});
Also don't use polylinePoints[polylinePoints.length]= if it is not necessary. Use polylinePoints.push(
What do you want with the data on the polyline? Why you not adding the whole point array to the polyline?
var polyline = new L.Polyline(polylinePoints, {
customData:{
points: points
}
});
Else you can create a array of the point ids:
let polylinePoints= [] // I get all info about all Polylines
let loop_index = 0;
let pointIds = [];
points.forEach(point => {
pointIds.push(point.id);
//...
var polyline = new L.Polyline(polylinePoints, {
customData:{
points: pointIds
}
});
Or (what I recommand) to add the markers to the polyline:
let markersForPoly = [];
points.forEach(point => {
//... Loop ...
myMarker.addTo(mymap);
markersForPoly .push(myMarker);
});
//.. Code
var polyline = new L.Polyline(polylinePoints, {
customData:{
points: markersForPoly
}
});
And the you can get the points in the click listener:
polyline.on('click', function (event) {
var layer = event.target;
var points = layer.options.customData.points;
console.log(points);
});
Example
https://jsfiddle.net/falkedesign/61sjx3bv/

How to change Line Opacity in google charts?

I am using Google Charts and I am able to change the colour of a line half way through a graph conditionally using a dataView, as shown in code below:
var dataView = new google.visualization.DataView(data);
dataView.setColumns([
// reference existing columns by index
0, 1,
// add function for line color
{
calc: function (data, row) {
var colorDown = '#ff9900';
var colorUp = '#27B291';
var opacity = 'opacity, 0.2;'
var currentdate = new Date();
var givendate = new Date(row.getValue)
if (data.getValue(row, 0) > currentdate) {
return colorDown;
} else {
return colorUp;
}
},
type: 'string',
role: 'style'
}
]);
I was wondering if there is way I can also change the line opacity conditionally as I can't seem to find a way to do it and other methods I have tried do not seem to work? Thanks.
using the style column role, you can combine color and opacity as follows...
'color: #ff9900;opacity: 0.2;'
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.arrayToDataTable([
['x', 'y'],
[new Date(2018, 6, 15), 2924],
[new Date(2018, 6, 16), 2381],
[new Date(2018, 6, 17), 2489],
[new Date(2018, 6, 18), 2235],
[new Date(2018, 6, 19), 2155],
[new Date(2018, 6, 20), 2844],
]);
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
var dataView = new google.visualization.DataView(data);
dataView.setColumns([
// reference existing columns by index
0, 1,
// add function for line color
{
calc: function (data, row) {
var colorDown = 'color: #ff9900;';
var colorUp = 'color: #27B291;';
var opacity = 'opacity: 0.2;'
var currentdate = new Date();
var givendate = new Date(row.getValue)
if (data.getValue(row, 0) > currentdate) {
return colorDown + opacity;
} else {
return colorUp + opacity;
}
},
type: 'string',
role: 'style'
}
]);
chart.draw(dataView, {
legend: {
position: 'none'
}
});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

tricky part of google charts Column with drill down functionality?

i am creating google charts and I already implement top 5 user column charts after that if you select first user column than displaying first user page history data from other variables(eachuser_data) its easy implement function in high charts! but in google charts, I don't know about add events.addListener work or not in this problem. let me know google charts provide click event on each column and display other graphs in same graph draw function. ? thank you in advance
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var charts = {};
var options = {
Column: {
chartArea: {
height: '100%',
width: '100%',
top: 24,
left: 64,
right: 32,
bottom: 48,
},
'vAxis': {
title: 'Cost in USD ($)', format:'$#',
},
height: '100%',
legend: {
position: 'bottom'
},
width: '100%'
}
};
// columns charts data
//top 5 user data with total click
var jsonData = [["johan",69],["jack",23],["scott",24],["x",5],["y",10]];
loadData(jsonData, '1', 'Column');
//specifc user data
var user1 = [["report1",45],["report2",40],["index.html",50]];
var user2 = [["report1",4],["report2",3],["index.html",5]];
var user3 = [["report1",4],["report2",3],["index.html",5]];
var user4 = [["report1",4],["report2",3],["index.html",5]];
var user5 = [["report1",4],["report2",3],["index.html",5]];
// load json data
function loadData(jsonData, id, chartType) {
// create data table
var dataTable = new google.visualization.DataTable();
// add date column
dataTable.addColumn('string', 'Total numbe of click');
var rowIndex = dataTable.addRow();
dataTable.setValue(rowIndex, 0, dataTable.getColumnLabel(0));
$.each(jsonData, function(productIndex, product) {
var colIndex = dataTable.addColumn('number', product[0]);
// add product data
dataTable.setValue(rowIndex, colIndex, product[1]);
});
// draw chart
$(window).resize(function () {
drawChart(id, dataTable);
});
drawChart(id, dataTable);
}
function drawChart(id, dataTable) {
if (!charts.hasOwnProperty(id)) {
charts[id] = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart-' + id,
options: {
vAxis: {
title: 'Cost in USD ($)',
format: '$#',
},
width: '100%',
height: '100%',
legend: {
position: 'bottom'
},
},
});
}
charts[id].setDataTable(dataTable);
charts[id].draw();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart-1"></div>
to know which column has been clicked / selected,
listen for the 'select' event
google.visualization.events.addListener(chart, 'select', chartSelection);
then use chart method getSelection() to get the row and column index of the column selected
getSelection will return an array of objects
[{row: 0, column: 1}]
the select event will fire both when a column is selected and un-selected
be sure to check the length of the array return by getSelection()
before trying to access the array contents
for column charts, only one column can be selected at a time
so the values of the selection will always be the first element in the array
function chartSelection() {
var selection = chart.getSelection();
if (selection.length > 0) {
var row = selection[0].row;
var col = selection[0].column;
var xValue = data.getValue(row, 0);
var yValue = data.getValue(row, col);
console.log('selection: ' + xValue + ' = ' + yValue);
} else {
console.log('nothing selected');
}
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['x', 'y0', 'y1'],
['A', 6, 7],
['B', 7, 9],
['C', 8, 11],
['D', 9, 11],
['E', 5, 6]
]);
var options = {
legend: {
alignment: 'end',
position: 'top'
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'select', chartSelection);
function chartSelection() {
var selection = chart.getSelection();
if (selection.length > 0) {
var row = selection[0].row;
var col = selection[0].column;
var xValue = data.getValue(row, 0);
var yValue = data.getValue(row, col);
console.log('selection: ' + xValue + ' = ' + yValue);
} else {
console.log('nothing selected');
}
}
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

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>

Visualize table on tooltip with amCharts

I'm novice on JavaScript, but really amazed by amCharts.
So, I ask here, after search a lot on internet: is it possible (or someone can tell me how) make a table as a tooltip on a amCharts graph?
I mean: I have a trend graph, based on "date", if I click on a date of a day, view a popup with a table of the details of the day's data.
Searching and try a lot of code, and I reach a possible solution.
So, considering that there aren't similar questions here or developed like I ask, I post my solution to share it.
You can try clicking "RUN": When you clicking on a point of graph, an HTML Table was displayed filled by data (fake value in this example).
THIS IS THE SNIPPET:
function createTable(){
var table = "<table>";
table += "<thead>";
table += "<tr>";
table +="<th> Dealer </th>";
table +="<th> Percent </th>";
table +="<th> Proportional </th>";
table +="</tr>";
table +="</thead>";
table +="<tbody>";
for(var i=0;i<200;i++){
table += "<tr>";
table +="<td> New York </td>";
table +="<td> "+Math.random();+" </td>";
table +="<td> "+Math.random();+" </td>";
table +="</tr>";
};
table += "</tbody>";
table += "</table>";
return table;
};
var chartData = [{
date: new Date(2012, 0, 1),
distance: 227,
duration: 408},
{
date: new Date(2012, 0, 2),
distance: 371,
duration: 482},
{
date: new Date(2012, 0, 3),
distance: 433,
duration: 562},
{
date: new Date(2012, 0, 4),
distance: 345,
duration: 379},
{
date: new Date(2012, 0, 5),
distance: 480,
duration: 501},
{
date: new Date(2012, 0, 6),
distance: 386,
duration: 443},
{
date: new Date(2012, 0, 7),
distance: 348,
duration: 405},
{
date: new Date(2012, 0, 8),
distance: 238,
duration: 309},
{
date: new Date(2012, 0, 9),
distance: 218,
duration: 287},
{
date: new Date(2012, 0, 10),
distance: 349,
duration: 485},
{
date: new Date(2012, 0, 11),
distance: 603,
duration: 890},
{
date: new Date(2012, 0, 12),
distance: 534,
duration: 810}];
var chart;
AmCharts.ready(function() {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "date";
chart.marginTop = 0;
chart.autoMarginOffset = 5;
chart.balloon.showBullet = false;
// AXES
// category axis
var categoryAxis = chart.categoryAxis;
categoryAxis.parseDates = true; // as our data is date-based, we set parseDates to true
categoryAxis.minPeriod = "DD"; // our data is daily, so we set minPeriod to DD
categoryAxis.autoGridCount = false;
categoryAxis.gridCount = 50;
categoryAxis.gridAlpha = 0;
categoryAxis.gridColor = "#000000";
categoryAxis.axisColor = "#555555";
// we want custom date formatting, so we change it in next line
categoryAxis.dateFormats = [{
period: 'DD',
format: 'DD'},
{
period: 'WW',
format: 'MMM DD'},
{
period: 'MM',
format: 'MMM'},
{
period: 'YYYY',
format: 'YYYY'}];
// as we have data of different units, we create two different value axes
// Duration value axis
var durationAxis = new AmCharts.ValueAxis();
durationAxis.title = "duration";
durationAxis.gridAlpha = 0.05;
durationAxis.axisAlpha = 0;
durationAxis.inside = true;
// the following line makes this value axis to convert values to duration
// it tells the axis what duration unit it should use. mm - minute, hh - hour...
durationAxis.duration = "mm";
durationAxis.durationUnits = {
DD: "d. ",
hh: "h ",
mm: "min",
ss: ""
};
chart.addValueAxis(durationAxis);
// Distance value axis
var distanceAxis = new AmCharts.ValueAxis();
distanceAxis.title = "distance";
distanceAxis.gridAlpha = 0;
distanceAxis.position = "right";
distanceAxis.inside = true;
distanceAxis.unit = "mi";
distanceAxis.axisAlpha = 0;
chart.addValueAxis(distanceAxis);
// GRAPHS
// duration graph
var durationGraph = new AmCharts.AmGraph();
durationGraph.title = "duration";
durationGraph.valueField = "duration";
durationGraph.type = "line";
durationGraph.valueAxis = durationAxis; // indicate which axis should be used
durationGraph.lineColor = "#CC0000";
durationGraph.balloonText = "[[value]]";
durationGraph.lineThickness = 1;
durationGraph.legendValueText = "[[value]]";
durationGraph.bullet = "square";
chart.addGraph(durationGraph);
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.zoomable = false;
chartCursor.categoryBalloonDateFormat = "DD";
chartCursor.cursorAlpha = 0;
chart.addChartCursor(chartCursor);
// LEGEND
var legend = new AmCharts.AmLegend();
legend.bulletType = "round";
legend.equalWidths = false;
legend.valueWidth = 120;
legend.color = "#000000";
chart.addLegend(legend);
// SET UP CLICK EVENTS
// create prerequisite properties
AmCharts.clickTimeout = 0; // this will hold setTimeout reference
AmCharts.lastClick = 0; // last click timestamp
AmCharts.doubleClickDuration = 300; // distance between clicks in ms - if it's less than that - it's a doubleckick
// let's define functions to actually do something on clicks/doubleclicks
// you will want to replace the insides of these with your own code
AmCharts.doSingleClick = function (event) {
//var div = document.getElementById("databody");
var table=createTable();
document.getElementById("databody").innerHTML=table;
//div.innerHTML = "Ciao<br />" + div.innerHTML;
}
/*AmCharts.doDoubleClick = function (event) {
var div = document.getElementById("events");
div.innerHTML = "Double Click<br />" + div.innerHTML;
}*/
// create click handler
AmCharts.myClickHandler = function (event) {
var ts = (new Date()).getTime();
if ((ts - AmCharts.lastClick) < AmCharts.doubleClickDuration) {
// it's double click!
// let's clear the timeout so the "click" event does not fire
if (AmCharts.clickTimeout) {
clearTimeout(AmCharts.clickTimeout);
}
// reset last click
AmCharts.lastClick = 0;
// now let's do whatever we want to do on double-click
AmCharts.doDoubleClick(event);
}
else {
// single click!
// let's delay it to see if a second click will come through
AmCharts.clickTimeout = setTimeout(function () {
// let's do whatever we want to do on single click
AmCharts.doSingleClick(event);
}, AmCharts.doubleClickDuration);
}
AmCharts.lastClick = ts;
}
// add handler to the chart
chart.addListener("clickGraphItem", AmCharts.myClickHandler);
// WRITE
chart.write("chartdiv");
});
body {
font-family: Verdana;
font-size: 12px;
padding: 10px;
}
#databody, #databody th, #databody td {
border: 1px solid #ccc;
padding: 10px;
}
#databody th {
font-weight: bold;
background-color: #eee;
}
div.box{
width:360px !important; width /**/:200px;
height:190px !important; height /**/: 200px;
padding: 4px;
border:1px solid #EEE; border-right:0 solid;
background:url(gradient.png) repeat-x fixed top left;
overflow:auto
}
}
<script src="http://www.amcharts.com/lib/amcharts.js" type="text/javascript"></script>
<div id="chartdiv" style="height: 362px;"></div>
<div class="box" id="databody">
</div>

Categories

Resources