Region Geochart region America - google-maps

I am learning to use the google Geochart tools I want to recreate a map like this one:
https://docs.google.com/spreadsheets/d/171U4NeI_49iacbhzlX0A8nT6aB9N4guc6VWsELmP6wI/pubchart?oid=1478243202&format=interactive
My code is this:
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['States', 'Number of killings'],
['California', 292],
['Texas', 143],
['Washington', 120]
]);
var options = {
region: 'US'
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
I am able o see the map, but I dont see the state divisions nor the colour I am using http://jsfiddle.net, I am sure it is a very basic error but I cant find it.

Add {resolution: provinces}:
working code snippet:
google.setOnLoadCallback(drawRegionsMap);
google.load('visualization', '1', {
packages: ['map']
});
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['States', 'Number of killings'],
['California', 292],
['Texas', 143],
['Washington', 120]
]);
var options = {
region: 'US',
resolution: 'provinces'
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
<script src="https://www.google.com/jsapi"></script>
<div>
<div id="regions_div" style="width: 500px; height: 400px;"></div>
</div>

Related

Export Google visualization as picture

I'm trying to convert a wordtree Google visualization to an image. The current code below runs the wordtree so I can see the visual, but I can't figure out the last section to convert to an image or export as an image. (var my_div = section to end)
I have tried changing code from link below, but can't get it to save as an image.
https://developers.google.com/chart/interactive/docs/printing
I'm also doing this inside of jsfiddle.net to try and make this work.
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current'); // Don't need to specify chart libraries!
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
google.visualization.drawChart({
"containerId": "mywordtree",
"dataSourceUrl": "https://docs.google.com/spreadsheets/d/1vi-YzV7s7eZ25938Q57DbZvT0iqggiCqRvDgxeZtP6c/edit?usp=sharing",
"query":"SELECT A",
"chartType": "WordTree",
"options": {
wordtree: {
format: 'implicit',
//alt type is 'suffix', 'prefix'
type: 'suffix',
word: 'prescription'
}
}
});
}
var my_div = document.getElementById('chart_div');
var my_chart = new google.visualization.ChartType(mywordtree);
google.visualization.events.addListener(my_chart, 'ready', function () {
mywordtree.innerHTML = '<img src="' + my_chart.getImageURI() + '">';
});
my_chart.draw(data);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="mywordtree" style="width: 1000px; height: 1000px;"></div>
</body>
</html>
first, in order to generate an image of the chart,
you need to wait for the chart's 'ready' event.
in order to wait for the 'ready' event,
you need access to the chart object.
you will not be able to use the google.visualization.drawChart method,
because it does not return a handle to the chart.
next, the WordTree chart, does not have a method for getImageURI,
so you will need to create the image manually, from a blob.
see following working snippet...
google.charts.load('current').then(function () {
// get chart container
var container = document.getElementById('mywordtree');
// create chart
var chart = new google.visualization.ChartWrapper({
chartType: 'WordTree',
containerId: container.id,
dataSourceUrl: 'https://docs.google.com/spreadsheets/d/1vi-YzV7s7eZ25938Q57DbZvT0iqggiCqRvDgxeZtP6c/edit?usp=sharing',
options: {
wordtree: {
format: 'implicit',
//alt type is 'suffix', 'prefix'
type: 'suffix',
word: 'prescription'
}
}
});
// listen for ready event
google.visualization.events.addListener(chart, 'ready', function () {
var domUrl; // object url
var image; // chart image
var imageUrl; // chart image url
var svg; // svg element
// add svg namespace to chart
svg = container.getElementsByTagName('svg')[0];
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
// create image url from svg
domUrl = window.URL || window.webkitURL || window;
imageUrl = domUrl.createObjectURL(new Blob([svg.outerHTML], {type: 'image/svg+xml'}));
// create chart image
image = new Image();
image.onload = function() {
// replace chart with image
container.innerHTML = image.outerHTML;
}
image.src = imageUrl;
});
// draw chart
chart.draw();
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="mywordtree"></div>

Google Chart Add Color Specific

How are you?
How do I force the color? I do not want them to be random. I read the documentation, but something is wrong. I can not tell. They help me? Thank you very much!
For Example: I want the Womens records in Black and the mens in Green.
Regarts!
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([
['status', 'number',{ role: 'style' },{ role: 'annotation' } ],
["Men", 5, '#b87333','M'],
["Girl", 7, '#0000FF','G'],
]);
var options = {
title: 'Sex',
is3D:true,
pieHole: 0.4,
//colors: ['#5cb85c','#f0ad4e']
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript"> </script>
<!--Div that will hold the pie chart-->
<div id="piechart"></div>
the only role supported by PieChart is 'tooltip'
both 'style' and 'annotation' are not supported
you can either use the colors configuration option,
colors: ['#5cb85c','#000000']
or the slices option...
slices: [{color: '#5cb85c'}, {color: '#000000'}]
in both options above, the first color in the array will be applied to the first row in the data table,
the second color, the second row, etc...
if you're not sure in which order the data will be,
you can use an object to map the values to a specific color
here, we build the array of colors, by matching the values in the data table,
to the key in the color map object...
var colors = [];
var colorMap = {
'Men': '#5cb85c',
'Girl': '#000000'
}
for (var i = 0; i < data.getNumberOfRows(); i++) {
colors.push(colorMap[data.getValue(i, 0)]);
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['status', 'number'],
['Men', 5],
['Girl', 7]
]);
var colors = [];
var colorMap = {
'Men': '#5cb85c',
'Girl': '#000000'
}
for (var i = 0; i < data.getNumberOfRows(); i++) {
colors.push(colorMap[data.getValue(i, 0)]);
}
var options = {
title: 'Sex',
is3D: true,
colors: colors
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript"> </script>
<!--Div that will hold the pie chart-->
<div id="piechart"></div>

geochart regions clickable urls

We want to embed a really basic interactive map on our website, where clicking a region will take you to a specific page on our site. We would like to use the regions in google geochart
This is the map we are working with
https://jsfiddle.net/tyvnfxf4/
google.charts.load('current', {'packages':['geochart']});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['England', 400],
['Wales', 300],
['Scotland', 400],
['Ireland', 600],
]);
var options = {
region: 'GB',
resolution: 'provinces',
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
And we would want:
Wales to link to www.example.com/wales
Ireland to link to www.example.com/ireland
etc
Can any help?
Many thanks
there are a number of ways to handle, but the key is using the 'select' event
keep in mind, the 'select' event is fired both when something is selected and de-selected,
so make sure length > 0
recommend using a column in the DataTable to store the URLs
use a DataView to hide the column from the chart
then get the URL based on the chart selection
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity', 'Domain'],
['England', 400, 'www.example.com/England'],
['Wales', 300, 'www.example.com/Wales'],
['Scotland', 400, 'www.example.com/Scotland'],
['Ireland', 600, 'www.example.com/Ireland'],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
region: 'GB',
resolution: 'provinces'
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
if (selection.length > 0) {
console.log(data.getValue(selection[0].row, 2));
//window.open('http://' + data.getValue(selection[0].row, 2), '_blank');
}
});
chart.draw(view, options);
},
packages:['geochart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://www.google.com/jsapi"></script>
<div id="regions_div" style="width: 600px; height: 500px;"></div>

how to draw a google pie (or donut) chart with data from database

I want to draw a pie or donut chart on my MVC project. I can draw it without database. But I want to draw it with data from database. How can I do that?
Here is my sample code for donut chart without database:
<html>
<head>
<title>Chart</title>
<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() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="donutchart" style="width: 900px; height: 500px;"></div>
</body>
</html>
You basically need to generate the data similar to your javascript array in your action method and pass that to your view. I have hard coded it here. But you may replace it with data from your db.
public ActionResult Index()
{
var data = new List<List<object>>()
{
new List<object>
{
"Task","Hours per day"
},
new List<object>
{
"Work",45
}
,
new List<object>
{
"Eat",25
},
new List<object>
{
"Commute to work",30
}
};
return View(data);
}
Now your view will be strongly typed to List<List<object>>
#model List<List<object>>
Now in the same view's script section, serialize your model to a js variable(array) and use that as the input to the arrayToDataTable method.
var dataArr = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
var data = google.visualization.arrayToDataTable(dataArr);

How can I get Selection in dashboard with ChartWrapper

I´m trying to get an event in a google dashboard ChartWrapper.
I need that when I select a row i can throw an event and get the selected value.
Can anyone help me or say me how can I get it?
Here´s my code:
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['controls']});
</script>
<script type="text/javascript">
var data;
var table;
var dash_container;
var myDashboard;
var stringFilter;
var myTable;
function draw() {
// To see the data that this visualization uses, browse to
// http://spreadsheets.google.com/ccc?key=pCQbetd-CptGXxxQIG7VFIQ
data = new google.visualization.Query(
'http://spreadsheets.google.com/tq?key=0Ai3BbtO5JfaodGluSWw0UVFvZ3BDak1nYzVac0RPWGc&pub=1');
// Send the query with a callback function.
data.send(handleQueryResponse);
}
//fin de draw
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
table = response.getDataTable();
// Create a dashboard.
dash_container = document.getElementById('dashboard'),
myDashboard = new google.visualization.Dashboard(dash_container);
// Define a StringFilter control for the 'Name' column
stringFilter = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'filter',
'options': {'filterColumnLabel': 'nombre'}
});
// Table visualization
myTable = new google.visualization.ChartWrapper({
'chartType' : 'Table',
'containerId' : 'table',
'view': {'columns': [0]} ,
'dataTable': table
});
// Register a listener to be notified once the dashboard is ready.
google.visualization.events.addListener(myDashboard, 'ready', dashboardReady);
myDashboard.bind(stringFilter, myTable);
myDashboard.draw(table);
}
**Here´s where I have the problems, because I can get the selection row
function dashboardReady() {
google.visualization.events.addListener(myTable, 'select', function(event) {
var selection = myTable.getChart().getSelection();
// iterate over all selected rows
for (var i = 0; i < selection.length; i++) {
// do something with selection[i].row
var item = selection[i];
}
alert('Fila seleccionada es: '+item.row +' y la Columna: '+item.column);
});
}
google.setOnLoadCallback(draw);
To do that, you need to do two things after the chart is drawn:
Add a 'ready' event listener to your chart wrapper;
Add a 'select' event listener to the table when the chart wrapper is ready.
So, add the following two lines after myDashboard.draw(table); in your code
google.visualization.events.addListener(myTable , 'ready', function(){
google.visualization.events.addListener(myTable ,'select', tableSelectHandler);
});
function tableSelectHandler(){
var selection = myTable.getChart().getSelection();
alert(data.getValue(selection[0].row,0));
}
There will be about 3 seconds delay for the ready function to be triggered, due to a bug I think, see here for more details about the bug report of this issue: https://code.google.com/p/google-visualization-api-issues/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Stars%20Modified%20Type%20Status%20Priority%20Milestone%20Owner%20Summary&groupby=&sort=&id=1470
With Wrapper you have to add one more function to get selected item i.e. getChart()
Like:
var selectedItem = wrapper.getChart().getSelection()
Remember, Without Wrapper you was getting it by:
var selectedItem = chart.getSelection()
The code working ...
google.setOnLoadCallback(draw);
function draw() {
var data = [
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
];
var table = google.visualization.arrayToDataTable(data);
// Create a dashboard.
var dash_container = document.getElementById('dashboard');
var myDashboard = new google.visualization.Dashboard(dash_container);
// Define a StringFilter control.
var stringFilter = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'filter',
'options': {'filterColumnLabel': 'Year'}
});
// Table visualization
var myTable = new google.visualization.ChartWrapper({
'chartType' : 'Table',
'containerId' : 'table',
'view': {'columns': [0, 1]} ,
'dataTable': table,
});
myDashboard.bind(stringFilter, myTable);
myDashboard.draw(table);
google.visualization.events.addListener(myTable , 'ready', function(){
google.visualization.events.addListener(myTable ,'select', tableSelectHandler);
});
function tableSelectHandler(e){
var selection = myTable.getChart().getSelection();
var t=table.getValue(selection[0].row, 0);
document.getElementById('label1').innerHTML = t;
}
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('visualization', '1.1', {packages: ['controls']});</script>
<script type="text/javascript">
</script>
</head>
<body>
<div id="filter"></div>
<br>
<div id="table"></div>
<br>
<div id="label1"></div>
</body>
</html>