Change Google Geochart marker into a custom png icon - javascript

I would like to ask for help how to change the circle marker in Google Geochart
I have already implemented the answer on this link.
appendChild to SVG defs to create Image Background in Marker for Geochart API
But no luck the marker is still there.
Here is my code:
<html>
<head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type="text/javascript">
var ivalue_1 = new Array();google.load('visualization', '1', {packages: ['geochart']});function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country'); // Implicit domain label col.
data.addColumn('number', 'Value'); // Implicit series 1 data col.
data.addColumn({type:'string', role:'tooltip', p:{html:true}});
data.addRows([[{v:"NO-02",f:"ASKER & BÆRUM"},1,"ASKER & BÆRUM"]]);
ivalue_1['NO-02'] = 'NO-02||ASKER & BÆRUM||ASKER & BÆRUM||lorem ipsum';
data.addRows([[{v:"NO-03",f:"Oslo"},2,"Oslo"]]);
ivalue_1['NO-03'] = ' NO-03||Oslo||Oslo||lorem ipsum';
data.addRows([[{v:"NO-01",f:"Østfold"},3,"Østfold"]]);
ivalue_1['NO-01'] = ' NO-01||Østfold||Østfold||lorem ipsum';
data.addRows([[{v:"NO-07",f:"Vestfold"},4,"Vestfold"]]);
ivalue_1['NO-07'] = ' NO-07||Vestfold||Vestfold||lorem ipsum';
data.addRows([[{v:"NO-11",f:"Rogaland"},5,"Rogaland"]]);
ivalue_1['NO-11'] = ' NO-11||Rogaland||Rogaland||lorem ipsum';
data.addRows([[{v:"NO-06",f:"Buskerud"},6,"Buskerud"]]);
ivalue_1['NO-06'] = ' NO-06||Buskerud||Buskerud||lorem ipsum';
var options = { colorAxis: {minValue: 1, maxValue:6, colors: ['#349429','#349429','#349429','#349429','#349429','#349429']},
legend: 'none',
backgroundColor: {fill:'transparent',stroke:'#CCCCCC' ,strokeWidth:0 },
datalessRegionColor: '#ddd',
displayMode: 'markers',
sizeAxis: {minValue: 1, maxValue:6,minSize:10, maxSize: 10},
enableRegionInteractivity: 'true',
resolution: 'provinces',
region:'NO',keepAspectRatio: false,width:'',
height:'215',
tooltip: {isHtml: true, textStyle: {color: '#555555'}, trigger:'focus'}
};var geochart = new google.visualization.GeoChart(
document.getElementById('map_canvas_1'));
google.visualization.events.addListener(geochart, 'select', function() {
var selection = geochart.getSelection();
if (selection.length == 1) {
var selectedRow = selection[0].row;
var selectedRegion = data.getValue(selectedRow, 0);
var japol = ivalue_1[selectedRegion].split('||');
jQuery("#lightBoxContent h2 span").append(japol[1]);
jQuery("#lightBoxContent h3 span").append(japol[2]);
jQuery("#lightBoxContent h4 span").append(japol[3]);
jQuery("#transparentlightbox").fadeIn("slow");
}
geochart.draw(data, options);
});
google.visualization.events.addListener(geochart, 'ready', function () {
var patt = document.createElementNS('http://www.w3.org/2000/svg', 'pattern');
patt.setAttribute('id', 'img1');
patt.setAttribute('patternUnits', 'userSpaceOnUse');
patt.setAttribute('width', '20');
patt.setAttribute('height', '20');
patt.setAttribute('x', '0');
patt.setAttribute('y', '0');
var image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'https://cdn1.iconfinder.com/data/icons/yooicons_set01_socialbookmarks/512/social_google_box.png');
image.setAttribute('x', '0');
image.setAttribute('y', '0');
image.setAttribute('width', '24');
image.setAttribute('height', '24');
var defs = document.getElementsByTagName('defs')[0];
patt.appendChild(image);
defs.appendChild(patt);});
geochart.draw(data, options);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body>
<div id='map_canvas_1' class='i_world_map' style="width:288px; height: 215px;"></div>
</body>
</html>
This code is not working. the marker is still green and I cannot change it into a custom png icon. Please help me.
Thank you in advance.

You have to fill all your markers with the image pattern inside defs tag,
here is the Demo-Jqfaq,
adding below code at the bottom of "geochart, 'ready'" function will make it work.
var markers = document.getElementsByTagName('circle');
for(i=0; i<markers.length;i++)
{
markers[i].setAttribute("fill", "url(#img1)");
}

Related

Google pie chart animation of the slices colors

I have a Google pie chart that I try to animate using simple JavaScript code.
I wish to change to colors of my pie slices. Why my code is not working?
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['A1', 0],
['Failed',1],
['A2', 0],
['Passed', 3],
]);
var colors1 = ['#ef7777', '#ef7777', '#b2d284', '#b2d284', '#f6c7b6'];
var colors2 = ['#ff00ff', '#ff00ff', '#02d2ff', '#02d2ff', '#f6c7b6'];
var colors3 = colors2;
var options1 = {'title':'Logic', 'width':'50%', 'height':'50%', legend:{position:'none'}, 'is3D':true,
chartArea: {width: '70%', height: '70%'},
colors: colors3,
'backgroundColor': '#fef7f8',
pieSliceTextStyle: {
color: '#000000',
bold: true,
fontSize:16
}
};
var chart1 = new google.visualization.PieChart(document.getElementById('piechart1'));
chart1.draw(data1, options1);
var percent = 0;
var handler = setInterval(function(){
// values increment
percent += 1;
if (percent%2 == 1) {
colors3 = colors1;
}
else
{
colors3 = colors2;
}
chart1.draw(data1, options1);
if (percent > 74)
clearInterval(handler);
}, 333);
}
So, I am setting here 2 arrays with color sets for my pie chart. The first have colors of red and green, the 2nd one have colors of blue and purple.
I wish to switch between these color sets continuously using the function "setInterval".
colors is a key of your options object. The callback function of your setInterval call changes a variable called colors3 but you don't assign it to the original object so it won't ever be used.
if (percent % 2 == 1) {
colors3 = colors1;
} else {
colors3 = colors2;
}
options1.colors = colors3; // here we're assigning it!
chart1.draw(data1, options1);

Google Chart Background

I have this 2 googlecharts in my program:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var matrix = [];
for(var i=0; i<50; i++) {
matrix[i] = new Array(2);
}
var j=0;
$.getJSON("x.json",function(data){
$.each(data, function(key, val){
matrix[j][0]=(val.y);
matrix[j][1]=(val.z);
j++;
});
});
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['a', 'b'],
[matrix[0][0], matrix[0][1]],
[matrix[1][0], matrix[1][1]],
[matrix[2][0], matrix[2][1]],
[matrix[3][0], matrix[3][1]],
[matrix[4][0], matrix[4][1]]
]);
// Set chart options
var options = {'title':'h',
'width':900,
'height':400,
is3D: true,
};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<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);
var matrix = [];
for(var i=0; i<50; i++) {
matrix[i] = new Array(2);
}
var j=0;
$.getJSON("x.json",function(data){
$.each(data, function(key, val){
matrix[j][0]=(val.y);
matrix[j][1]=(val.z);
j++;
});
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Density", { role: "style" } ],
[matrix[0][0], matrix[0][1], "red"],
[matrix[1][0], matrix[1][1], "yellow"],
[matrix[2][0], matrix[2][1], "green"],
[matrix[3][0], matrix[3][1], "grey"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "k",
width: 800,
height: 300,
bar: {groupWidth: "95%"},
legend: { position: "none" }
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
<!--options-->
}
</script>
<div id="columnchart_values" style="width: 900px; height: 800px; display: inline-block;"></div>
</div>
I want to change the background color of both.
I've tryed some of the solutions for background color change, like adding the background color to the options, adding a chart area and using the chart.draw(data, google.charts.Bar.convertOptions(options)) method.
But the chart simple disapears.
Any solution for this?
You can change Google Chart Color By write in backgroundColor in your option, for example -by using your code-:
var options = {
'backgroundColor': 'blue',
};
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
for your first snippet code, you can check this work color in fiddle

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>

Google Column Chart - Show different color for each column

Snippet
google.load("visualization", "1", {packages: ["corechart", "bar"]});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var timesheetRes = ["Resouce 1","Resouce 2","Resouce 3","Resouce 4","Resouce 5"];
var timesheetWeek = ["Week 1","Week 2","Week 3","Week 4","Week 5"];
var timesheetHours = [45,40,40,0,0];
var dataArray = [['Resources', 'Week', 'Hours']];
for (var n = 0; n < timesheetHours.length; n++) {
dataArray.push([timesheetRes[n], timesheetWeek[n], timesheetHours[n]]);
}
var data = new google.visualization.arrayToDataTable(dataArray);
var color = <?php echo $json_color_str ?>;
var color_count = <?php echo $color_count ?>;
for (var i = 0; i < color_count; i++) {
var color_str = color[i];
var options = {
width: 700,
height: 350,
legend: {position: 'none'},
bar: {groupWidth: '50%'},
isStacked: true,
tooltip: {trigger: 'none'},
colors: color_str, //being passed in array format for each bar
hAxis: {title: "Resource(s)",
titleTextStyle: {color: '#e91e63', bold: 1, fontSize: 14}},
vAxis: {title: "Week(s)",
ticks: weekAxis(),
gridlineColor: 'transparent',
titleTextStyle: {color: '#F4B400', bold: 1, fontSize: 14}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById("top_x_div"));
chart.draw(data, options);
}
}
function weekAxis() {
var ticks = new Array();
var week_count = <?php echo $week_no ?>; //count number of weeks
for (i = 1; i <= week_count; i++) {
var tick_str = {};
tick_str['v'] = (week_count * i);
tick_str['f'] = 'Week ' + i;
ticks.push(tick_str);
}
return ticks;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="top_x_div"></div>
Current Output
Expected Output
where Week(s) will be displayed on vAxis while Resource(s) will be displayed on hAxis. Here I have changed hAxis and vAxis values to display Weeks and
Resources respectively and show fix 4/5/6 chart sections considering number of weeks in a month.
Tried looping options by passing color array for each bar, but it only takes the last array passed and thus displays same color for each and its columns.
How can I change color of chart columns based on color string
passed as shown in expected output image ?
Or is it possible using jQuery ?

Categories

Resources