Google's GeoChart wont display Cork within Ireland map - google-maps
I'm drawing a province map for Ireland and for some reason Google's doesn't recognise county Cork. Someone suggested using IE-CO. But that breaks my plans on using a CSV dataset(where I have no control over county names).
Does anyone know why it doesn't work and how can I fix that?
Here a sample of my code https://jsfiddle.net/sashareds/kLjtne42/2/
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'AIzaSyBgxLAOHUq52CuZ0kcl9WHnOjzt40w082k'
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['County', 'Case'],
['Carlow', 0],
['Cavan', 41],
['Clare', 50],
['Cork', 292], //IE-CO
['Donegal', 77],
['Dublin', 2077],
['Galway', 98],
['Kerry', 79],
['Kildare', 103],
['Kilkenny', 47],
['Laois', 16],
['Leitrim', 12],
['Limerick', 96],
['Longford', 16],
['Louth', 54],
['Mayo', 55],
['Meath', 88],
['Monaghan', 17],
['Offaly', 47],
['Roscommon', 13],
['Sligo', 26],
['Tipperary', 94],
['Waterford', 43],
['Westmeath', 86],
['Wexford', 18],
['Wicklow', 105]
]);
var options = {
region: 'IE', // Africa
resolution: 'provinces',
colorAxis: {colors: ['#f9cb9c', '#f07b50', '#ea4435']},
backgroundColor: 'white',
datalessRegionColor: '#fefefe',
defaultColor: '#fefefe',
};
var chart = new google.visualization.GeoChart(document.getElementById('geochart-colors'));
chart.draw(data, options);
};
you could use a data view with a calculated column to replace the known problem countries.
and use object notation to allow the actual country name to show thru on the tooltip.
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (dt, row) {
var country = dt.getValue(row, 0);
switch (country) {
case 'Cork':
country = {v: 'IE-CO', f: country};
break;
}
return country;
},
label: data.getColumnLabel(0),
type: data.getColumnType(0)
}, 1]);
see following working snippet...
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'AIzaSyBgxLAOHUq52CuZ0kcl9WHnOjzt40w082k'
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['County', 'Case'],
['Carlow', 0],
['Cavan', 41],
['Clare', 50],
['Cork', 292], //IE-CO
['Donegal', 77],
['Dublin', 2077],
['Galway', 98],
['Kerry', 79],
['Kildare', 103],
['Kilkenny', 47],
['Laois', 16],
['Leitrim', 12],
['Limerick', 96],
['Longford', 16],
['Louth', 54],
['Mayo', 55],
['Meath', 88],
['Monaghan', 17],
['Offaly', 47],
['Roscommon', 13],
['Sligo', 26],
['Tipperary', 94],
['Waterford', 43],
['Westmeath', 86],
['Wexford', 18],
['Wicklow', 105]
]);
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (dt, row) {
var country = dt.getValue(row, 0);
switch (country) {
case 'Cork':
country = {v: 'IE-CO', f: country};
break;
}
return country;
},
label: data.getColumnLabel(0),
type: data.getColumnType(0)
}, 1]);
var options = {
region: 'IE', // Africa
resolution: 'provinces',
colorAxis: {colors: ['#f9cb9c', '#f07b50', '#ea4435']},
backgroundColor: 'white',
datalessRegionColor: '#fefefe',
defaultColor: '#fefefe',
};
var chart = new google.visualization.GeoChart(document.getElementById('geochart-colors'));
chart.draw(view, options); // <-- draw chart with data view
};
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="geochart-colors" style="width: 90%; height: 90%;"></div>
EDIT
when using a sheet for the data source,
the view needs to be created with the data table from the sheet.
so the view definition should be created,
after the data table is received.
see following working snippet...
google.charts.load('current', {
'packages': ['geochart'],
'mapsApiKey': chartSettings.mapsApyKey
});
google.charts.setOnLoadCallback(drawRegionsMap);
//querying external data from a spreadsheet.
function drawRegionsMap() {
var queryString = encodeURIComponent('Select *');
var queryData = new google.visualization.Query(chartSettings.mapDataSource + queryString);
queryData.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
//Swapping IE-CO on COrk in the dta array, I assume?
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function(dt, row) {
var country = dt.getValue(row, 0);
switch (country) {
case 'Cork':
country = {
v: 'IE-CO',
f: country
};
break;
}
return country;
},
label: 'Country',
type: 'string'
}, 1]);
var options = {
region: 'IE',
resolution: 'provinces',
colorAxis: {
colors: ['#f9cb9c', '#f07b50', '#ea4435']
},
backgroundColor: 'white',
datalessRegionColor: '#fefefe',
defaultColor: '#fefefe',
};
var chart = new google.visualization.GeoChart(document.getElementById('map'));
chart.draw(view, options);
}
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var chartSettings = {
mapsApyKey: "AIzaSyBgxLAOHUq52CuZ0kcl9WHnOjzt40w082k",
mapDataSource: "https://docs.google.com/spreadsheets/d/1YV7VSsG_nQXmL_L44cJSz4GrxOLIBNJrgd8qPXM_NQ0/gviz/tq?gid=249758876&headers=1&range=M21:N47&tq="
};
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
Related
Razor chart.js labels/data not in sync
I have a Razor application that generates three columns of data to use in a chart graph. The page and javascript to do that looks like this: <div><canvas id="myChart"></canvas></div> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> var Maanden = []; var Totalen = []; #foreach (var m in Model.Grafieks) { #:Maanden.push("#m.maand" + "-" + "#m.jaar"); #:Totalen.push(#m.Total); } const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: Maanden, datasets: [ { label: 'Facturen €', data: Totalen, backgroundColor: 'rgb(255, 255, 132)', borderColor: 'rgb(255, 99, 132)', borderWidth: 1, } ] }, }); </script> Problem is that the labels are displayed OK but the data is off. Every second column is empty and its data pushed to the next column: Chrome says: Is there something wrong pushing the data into the arrays?
I had to convert the comma in decimal Totalen to a period! #foreach (var m in Model.Grafieks) { #:Maanden.push("#m.maand" + "-" + "#m.jaar"); <text>bedrag = parsePotentiallyGroupedFloat("#m.Total");</text> #:Totalen.push(bedrag); } function parsePotentiallyGroupedFloat(stringValue) { stringValue = stringValue.trim(); var result = stringValue.replace(/[^0-9]/g, ''); if (/[,\.]\d{2}$/.test(stringValue)) { result = result.replace(/(\d{2})$/, '.$1'); } return parseFloat(result); } The function "parsePotentiallyGroupedFloat" is from here: Convert String with Dot or Comma as decimal separator to number in JavaScript
Add Information to Google Timeline bar Hover
I'm trying to add three new sections to the hover pop-up on a bar in google timeline charts. I have tried using the google timeline help but cannot find a solution The default is Title / Time / Duration, however I want to add Arena / Website I have created the below code for this as an example. <DIV> <p><font face="verdana" size="6" color="Black">Thursday</font></p> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load("current", {packages:["timeline"]}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var container = document.getElementById('example5.1'); var chart = new google.visualization.Timeline(container); var dataTable = new google.visualization.DataTable(); dataTable.addColumn({ type: 'string', id: 'Federation' }); dataTable.addColumn({ type: 'string', id: 'Event' }); dataTable.addColumn({ type: 'date', id: 'Start' }); dataTable.addColumn({ type: 'date', id: 'End' }); dataTable.addRows([ [ 'WWE / NXT', 'AXXESS', new Date(0,0,0,18,0,0), new Date(0,0,0,22,0,0)], [ 'WWN', 'Matt Riddles Bloodsport', new Date(0,0,0,15,0,0), new Date(0,0,0,18,0,0)], [ 'WrestleCon', 'Wildkat Sports', new Date(0,0,0,18,0,0), new Date(0,0,0,21,0,0)], [ 'WWN', 'Evolve', new Date(0,0,0,20,00,0), new Date(0,0,0,23,0,0)], [ 'WrestleCon', 'WrestleCon Supershow', new Date(0,0,0,21,30,0), new Date(0,0,0,23,30,0)], [ 'Knockout', 'Knockout in NOLA', new Date(0,0,0,17,00,0), new Date(0,0,0,20,00,0)], [ 'ROH', 'RoH Supercard of Honor', new Date(0,0,0,19,30,0), new Date(0,0,0,22,30,0)], [ 'WWN', 'Beyond Wrestling', new Date(0,0,0,20,55,0), new Date(0,0,0,23,55,0)]]); var options = { timeline: { colorByRowLabel: true }, tooltip: {isHtml: true}, legend: 'none', backgroundColor: '#ffd' }; chart.draw(dataTable, options); } </script> <div id="example5.1" style="height: 300px;"></div> </DIV>
you can add your own custom tooltip, see Customizing tooltips in the Timeline reference the tooltip column will just be a string, either a simple value or html see following working snippet, here, a DataView is used to add the tooltip column. this allows the tooltip to be built dynamically based on the data in the data table also, the arena is added to the original data table, for easy reference, but is excluded from the data view... google.charts.load('current', { packages: ['timeline'] }).then(function () { var container = document.getElementById('example5.1'); var chart = new google.visualization.Timeline(container); var dataTable = new google.visualization.DataTable(); dataTable.addColumn({ type: 'string', id: 'Federation' }); dataTable.addColumn({ type: 'string', id: 'Event' }); dataTable.addColumn({ type: 'date', id: 'Start' }); dataTable.addColumn({ type: 'date', id: 'End' }); dataTable.addColumn({ type: 'string', id: 'Arena' }); dataTable.addRows([ ['WWE / NXT', 'AXXESS', new Date(0,0,0,18,0,0), new Date(0,0,0,22,0,0), 'Arena A'], ['WWN', 'Matt Riddles Bloodsport', new Date(0,0,0,15,0,0), new Date(0,0,0,18,0,0), 'Arena B'], ['WrestleCon', 'Wildkat Sports', new Date(0,0,0,18,0,0), new Date(0,0,0,21,0,0), 'Arena C'], ['WWN', 'Evolve', new Date(0,0,0,20,00,0), new Date(0,0,0,23,0,0), 'Arena D'], ['WrestleCon', 'WrestleCon Supershow', new Date(0,0,0,21,30,0), new Date(0,0,0,23,30,0), 'Arena E'], ['Knockout', 'Knockout in NOLA', new Date(0,0,0,17,00,0), new Date(0,0,0,20,00,0), 'Arena F'], ['ROH', 'RoH Supercard of Honor', new Date(0,0,0,19,30,0), new Date(0,0,0,22,30,0), 'Arena G'], ['WWN', 'Beyond Wrestling', new Date(0,0,0,20,55,0), new Date(0,0,0,23,55,0), 'Arena H']]); var options = { timeline: { colorByRowLabel: true }, tooltip: {isHtml: true}, legend: 'none', backgroundColor: '#ffd' }; var formatTime = new google.visualization.DateFormat({ pattern: 'HH:mm:ss a' }); var view = new google.visualization.DataView(dataTable); view.setColumns([0, 1, { role: 'tooltip', type: 'string', calc: function (dt, row) { // build tooltip var dateBegin = dt.getValue(row, 2); var dateEnd = dt.getValue(row, 3); var oneHour = (60 * 60 * 1000); var duration = (dateEnd.getTime() - dateBegin.getTime()) / oneHour; var tooltip = '<div><div class="ggl-tooltip"><span>'; tooltip += dt.getValue(row, 0) + ':</span> ' + dt.getValue(row, 1) + '</div>'; tooltip += '<div class="ggl-tooltip"><div>' + formatTime.formatValue(dateBegin) + ' - '; tooltip += formatTime.formatValue(dateEnd) + '</div>'; tooltip += '<div><span>Duration: </span>' + duration.toFixed(0) + ' hours</div></div>'; tooltip += '<div class="ggl-tooltip"><span>Arena: </span>' + dt.getValue(row, 4) + '</div></div>'; return tooltip; }, p: {html: true} }, 2, 3]); chart.draw(view.toDataTable(), options); // <-- use data view to draw chart }); .ggl-tooltip { background-color: #ffffff; border: 1px solid #e0e0e0; font-family: Arial, Helvetica; font-size: 14px; padding: 8px; } .ggl-tooltip span { font-weight: bold; } <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="example5.1"></div>
HTML horizontal bar chart with a goal line?
Is there a library that handles drawing an HTML horizontal bar chart, but with a goal line included, so the gap between the progress and the goal can be seen? I'd call this a 'horserace bar chart', but apparently no one else does. Something like this:
you can use the library Chart.js Example: Here is the jquery code to draw a horizontal line. var data = { labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"], datasets: [{ data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1] }] }; var ctx = document.getElementById("LineWithLine").getContext("2d"); Chart.types.Line.extend({ name: "LineWithLine", initialize: function () { Chart.types.Line.prototype.initialize.apply(this, arguments); }, draw: function () { Chart.types.Line.prototype.draw.apply(this, arguments); var point = this.datasets[0].points[this.options.lineAtIndex] var scale = this.scale console.log(this); // draw line this.chart.ctx.beginPath(); this.chart.ctx.moveTo(scale.startPoint+12, point.y); this.chart.ctx.strokeStyle = '#ff0000'; this.chart.ctx.lineTo(this.chart.width, point.y); this.chart.ctx.stroke(); // write TODAY this.chart.ctx.textAlign = 'center'; this.chart.ctx.fillText("TODAY", scale.startPoint + 35, point.y+10); } }); new Chart(ctx).LineWithLine(data, { datasetFill : false, lineAtIndex: 2 });
Google Visualization Column Chart set a data column from query as role: "Style"
I have a Google Visualization Column Chart from a query that works fine. I can set the a columns with a style role after the query by using the code snippet below. It adds a new column to the query data and sets the role as "Style". This colors each of the column chart bars accordingly. But I want to be able to use one of my query columns "C" for example as the color code and not have to add it afterward. I can't seem to get this to work. Any ideas? I posted more of my code below the snippet so you can see where I'm coming from. Thanks so much guys for any help you can give. Brandon var data = response.getDataTable(); data.addColumn({type: "string", role: "style" }); data.setCell(0,2,'red'); data.setCell(1,2,'orange'); data.setCell(2,2,'green'); data.setCell(3,2,'yellow'); // More code above this, but I ommited it. function drawDashboard() { var query = new google.visualization.Query( 'URL'); query.setQuery('SELECT A, B, C'); query.send(handleQueryResponse); } function handleQueryResponse(response) { if (response.isError()) { alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); return; } var data = response.getDataTable(); data.addColumn({type: "string", role: "style" }); data.setCell(0,2,'red'); data.setCell(1,2,'orange'); data.setCell(2,2,'green'); data.setCell(3,2,'yellow'); // Create a dashboard. var dashboard = new google.visualization.Dashboard( document.getElementById('dashboard_div')); // Create a range slider, passing some options var scoreSlider = new google.visualization.ControlWrapper({ controlType: 'NumberRangeFilter', containerId: 'filter_div', options: { filterColumnLabel: 'Class AVG' } }); var ClassFilter = new google.visualization.ControlWrapper({ controlType: 'CategoryFilter', containerId: 'Classfilter_div', options: { 'filterColumnLabel': 'Teacher Name','ui': { 'labelStacking': 'veClasscal','allowTyping': true,'allowMultiple': true } }}); // Create a Column Bar chart, passing some options var columnChart = new google.visualization.ChartWrapper({ chartType: 'ColumnChart', containerId: 'chart_div', options: { title: 'Math Proficiency by Class', height: 320, width: 500, chartArea:{left:"10%",top:"10%",width:"80%",height:"60%"}, hAxis: {textStyle: {fontSize:14}, title: 'Teacher Name', titleTextStyle: {fontSize:14}, textStyle: {fontSize:14}}, vAxis: {minValue: 0, maxValue: 100, title: 'Math Proficiency AVG', titleTextStyle: {fontSize:14}, textStyle: {fontSize:14}}, legend: {position: 'none'}, animation: {duration:1500, easing:'out'}, colors: ['#a4c2f4','#3c78d8'] }, view: {columns: [0, 1, 2]} }); // Define a table var table = new google.visualization.ChartWrapper({ chartType: 'Table', dataTable: data, containerId: 'table_div', options: { width: '400px' }, view: {columns: [0, 1,]} }); // Establish dependencies, declaring that 'filter' drives 'ColumnChart', // so that the column chart will only display entries that are let through // given the chosen slider range. dashboard.bind([scoreSlider], [table, columnChart]); dashboard.bind([ClassFilter], [table, columnChart]); // Draw the dashboard. dashboard.draw(data); }// More code below this, but I ommited it.
I'm not sure how you would add this to a column in the query but... using a DataView with a calculated column should work... Assumes the value you want to test is in the second column -- index 1 var data = response.getDataTable(); var view = new google.visualization.DataView(data); view.setColumns([0, 1, { type: "string", role: "style", calc: function (dataTable, rowIndex) { if (dataTable.getValue(rowIndex, 1) < 0.69) { return 'color: red;'; } else if ((dataTable.getValue(rowIndex, 1) >= 0.69) && (dataTable.getValue(rowIndex, 1) <= 0.79)) { return 'color: yellow;'; } else { return 'color: green;'; } } }]);
Google Visualization Geomap showZoomout
I can't get the zoomout option enabled for my Google Visualization Geomap.. I'm trying to enable it when the user has clicked on a region.. This is my code: google.load('visualization', '1', {packages: ['geochart']}); var width, height, selectedRegion, resolution; window.onload = function(){ width = 556; height = 400; selectedRegion = 'world'; resolution = 'subcontinents'; }; function drawVisualization() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Region'); data.addColumn('number', 'Distributors'); data.addRows([ [{v:"005", f:"South America"}, 0], [{v:"011", f:"Western Africa"}, 46], [{v:"013", f:"Central America"}, 299], [{v:"014", f:"Eastern Africa"}, 63.9], [{v:"015", f:"Northern Africa"}, 255.7], [{v:"017", f:"Middle Africa"}, 21.4], [{v:"018", f:"Southern Africa"}, 244.5], [{v:"029", f:"Caribbean"}, 76.5], [{v:"030", f:"Eastern Asia"}, 5712.9], [{v:"034", f:"Southern Asia"}, 1275.1], [{v:"035", f:"South-Eastern Asia"}, 639.2], [{v:"039", f:"Southern Europe"}, 777.8], [{v:"053", f:"Australia and New Zealand"}, 272], [{v:"054", f:"Melanesia"}, 6.3], [{v:"057", f:"Micronesia"}, 0], [{v:"061", f:"Polynesia"}, 0], [{v:"143", f:"Central Asia"}, 0], [{v:"145", f:"Western Asia"}, 0], [{v:"150", f:"Europe"}, 0], [{v:"151", f:"Eastern Europe"}, 0], [{v:"154", f:"Northern Europe"}, 0], [{v:"155", f:"Western Europe"}, 0] ]); var options = { displayMode: 'regions', enableRegionInteractivity: 'true', resolution: resolution, region: selectedRegion, height: height, width: width }; var geochart = new google.visualization.GeoChart(document.getElementById('visualization')); google.visualization.events.addListener(geochart, 'regionClick', function(e) { var clickedRegion = e['region']; options.region = clickedRegion; options.resolution = "country"; options.showZoomOut = true; geochart.draw(data, options); }); geochart.draw(data, options); } google.setOnLoadCallback(drawVisualization); Could someone please tell me what i'm doing wrong? The zoom out button is not showing up..