Drawing chart visualization with Google Fusion tables - javascript

I am trying to dynamically draw a chart based off a click on a fusion table layer/map. Whenever a state in Mexico is clicked, I would like the chart to change to reflect the value in columns 2007, 2008, 2009, and 2010. At the moment, this is not working. Firebug is telling me that 'a is undefined' but I don't really know what that means, as I have not declared a variable named 'a' and am assuming it's something in the Google script.
This is the code that I'm using. The click listener grabs the state name from the column named 'column_1' and then passes that to the draw visualization function:
google.maps.event.addListener(shownLayer, 'click',function(e){
stateName = e.row['column_1'].value;
drawVisualization(stateName);
});
function drawVisualization(stateName){
google.visualization.drawChart({
containerID: "textBox",
dataSourceUrl: "http://www.google.com/fusiontables/gvizdata?tq=",
query: "SELECT '2007','2008','2009','2010' " +
"FROM 3943497 WHERE column_1 = '" + stateName + "'",
chartType: "ColumnChart",
options: {
title: stateName,
height: 300,
width: 400
}
});
}
The map website is located here: https://mywebspace.wisc.edu/csterling/web/cartel%20map/index.html

containerID: "textBox",
is mispelled. Should be:
containerId: "textBox",
My suggestion was to get a basic static GVis chart working first before worrying about linking it to Fusion Tables and changing the chart based on a mouse click. I took the relevant parts of your script but could not get it to work. When you post your whole file it's very hard to separate the issues giving you problems from the rest of your code. This is what I extracted to test the basic GViz issue:
<!DOCTYPE html>
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script type='text/javascript'>
google.load('visualization','1', {packages: ['corechart'] });
window.onload = function () {
drawVisualization('Chiapas');
}
function drawVisualization(stateName){
google.visualization.drawChart({
"chartType": "ColumnChart",
"containerId": "textBox",
"dataSourceUrl": "http://www.google.com/fusiontables/gvizdata?tq=",
"query": "SELECT '2007','2008','2009','2010' " + "FROM 3943497 WHERE column_1 = '" + stateName + "'",
"options": {
title: stateName
}
});
}
</script>
</head>
<body>
<div id="textBox" style="width: 400px; height: 300px;"></div>
<br />
</body>
</html>
This application does not work. I'm getting displayed in the page:
"Bars series with value domain axis is not supported"
I can also see in your app that the stateName value you are using is "Chiapas, Mexico" but that is not the value shown in your Fusion Table column_1, "Chiapas" is a value there.

Related

Leaflet map not displaying external GeoJSON data

Leaflet Map not Visible ....
What I am trying to do is creating a map and add external GeoJSON file I already created through QGIS app using SPH file from http://naturalearthdata.com
somehow my map is not visible there i also tried to use mapbox and google API key with leaflet library and sill having same issue
anyone knows the solution ??
I couldn't add my GeoJSON file in here because it's a huge file
Here is my HTML file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="biewport" content="width=device-width, initial-scale=1" />
<title>GeoJSON</title>
<!-- leflet links -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.3.3/dist/leaflet.js"></script>
</head>
<body>
<div id="map"></div>
<!-- <script src="CA_Bulletin_118_Groundwater_Basins.geojson"></script> -->
<script src="test.geojson"></script>
<!-- script file -->
<script src="js/script.js"></script>
</body>
</html>
My script.js file:
//creating a new map
var map = new L.Map('map').setView([51.505, -0.09], 13);
//create a new Geojason layer and set it up to basins var ....
// var test;
var test = L.tileLayer('basins');
var basinslayer = L.geoJson(basins).addTo(map);
And here is my CSS file:
/*General CSS */
html, body, #map {
height: 100%;
width: 100%;
font-family: sans-serif;
}
#map {
width: 50%;
height: 50%;
}
I'm also importing a geojson file to generate the points on my map. I used the $.getJSON from jquery to import the geojson file, load the data, and create the points.
If you want to try this method, you have to add jQuery in the head of your html, like this (also found here for the latest cdn):
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
My $.getJSON looks like this:
var getjson = $.getJSON("map-v2.geojson",function(data){
var bev = L.geoJson(data,{
pointToLayer: function(feature,latlng){
var marker = L.marker(latlng);
marker.bindPopup('<p align=center>' + '<strong>Title: </strong>' + feature.properties.Title + '<strong>Date: </strong>' + feature.properties.Date + '<br/>' + '<strong>Creator: </strong>' + feature.properties.Creator);
return marker;
}
});
bev.addTo(map);
});
First, I set a variable that calls $.getJSON, which takes a few arguments, the first one is the name of the geoJSON file in quotes, and the second is function(data) which acts to say we are going to use the data found in this file. The second line I assign my variable bev to invoke the L.geoJson function, passing the argument data (which will use the data from the geoJSON file). Then I point to a new layer using pointToLayer and assigning it the value of the function(feature,latlng). feature allows me to name certain properties from my geoJSON file to display in the popups, latlng extracts the coordinates from the geoJSON file to generate the locations for the markers(latlng is mandatory). I then assign another variable called marker, and here's where you generate your markers on your map, simply by using L.marker(latlng). After that, the marker.bindPopup binds all the content I want to display on popups from the properties data I have in each of my points in the geoJson file. Here's an example of my geoJSON:
{
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-122.714055,
38.440429
]
},
"properties": {
"Title": "Santa Rosa. Sonoma County. California. 1885.",
"Date": "1885",
"Creator": "W.W. Elliot & Co., lithographer."
}
},
I then return the marker, add the variable bev to the map, and there they are!
*I'm not an expert on JavaScript or Leaflet, so if my wording is off, I will gladly make edits to make it clearer.

Google Charts using CSV Data: $.csv is undefined?

So I have a working google chart that uses a CSV file, parses the CSV data as a string into an array, and uses the array as the datatable.
I actually asked a question and answered it myself Here.
That link will show you a full chunk of code that I used in my full working website.
I intended to just pull the script from the test file and drop it into my website, but now that I've moved it over and included the scripts I needed, I'm getting an error as:
Type Error: $.csv is undefined
Here is the code where $.csv is being utilized (var arrayData), this is a function for drawing the chart
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="jquery.csv.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript"> // load the visualisation API
google.load('visualization', '1', { packages: ['corechart', 'controls'] });
</script>
<script type="text/javascript">
function drawVisualization() {
$.get("Thornton.M2.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// CAPACITY - En-route ATFM delay - YY - CHART
var crt_ertdlyYY = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'crt_ertdlyYY',
dataTable: data,
options:{
width: 450, height: 160,
title: 'EU-wide en-route ATFM delays (year to date)',
titleTextStyle : {color: 'grey', fontSize: 11},
}
});
crt_ertdlyYY.draw();
});
}
google.setOnLoadCallback(drawVisualization)
</script>
</head>
<body>
<div id="crt_ertdlyYY"></div>
</body>
This example works fully as you can see from the link I had posted before hand, if you wanted to test it. But now that I pull it into my main site the .csv calls do not recognize. I also have 2 other google charts on this page that still work properly so it's isolated to this issue. I'm very new to google charts and pretty confused here!

two google charts on one page with super proxy

How can I have two google charts on one page? I'm using super proxy to get JSON table from google analytics API.
Currently, only the first chart (Table) is shown. Missing the second chart.
My code is attached below. I'm not so familiar with the API things. I checked some solutions, but all have data locally instead of from online sources, e.g., spreadsheet, JSON table.
Any help would be appreciated.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript"
src='https://www.google.com/jsapi?autoload={"modules":[{"name":"visualization","version":"1"}]}'>
</script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table','geochart']});
google.setOnLoadCallback(drawVisualization);
function drawCountriesTable() {
var CountriesTableWrapper = new google.visualization.ChartWrapper({
"containerId": "CountriesTable_div",
"dataSourceUrl": "https://top3dapp.appspot.com/query?id=agpzfnRvcDNkYXBwchULEghBcGlRdWVyeRiAgICAgICACgw&format=data-table-response",
"refreshInterval": 43200,
"chartType": "Table",
"options": {
"showRowNumber" : true
}
});
CountriesTableWrapper.draw();
}
function drawRegionsMap() {
var RegionsMapWrapper = new google.visualization.ChartWrapper({
"containerId": "RegionsMap_div",
"dataSourceUrl": "https://top3dapp.appspot.com/query?id=agpzfnRvcDNkYXBwchULEghBcGlRdWVyeRiAgICAvKGCCgw&format=data-table-response",
"refreshInterval": 43200,
"chartType": "GeoChart",
"options": {
"displayMode": 'markers',
"colorAxis": { "colors": ['#A9DEF2', '#048DC7'] }
}
});
RegionsMapWrapper.draw();
}
function drawVisualization() {
drawCountriesTable();
drawRegionsMap();
}
</script>
</head>
<body>
<h2>Countries</h2>
<div id="CountriesTable_div" style="margin:auto;width:630px;"></div>
<h2>Regions</h2>
<div id="RegionsMap_div" style="margin:auto;width:630px;"></div>
</body>
The is a bug of super proxy. Bug report see:
https://github.com/googleanalytics/google-analytics-super-proxy/issues/17
Following the steps as suggested on github:
Open query_helper.py
Go to the method 'GetPublicEndpointResponse'
In line 395, you should see
transformed_response_content = response.get('transformed_content')
Change that line to:
transformed_response_content = transform.Transform(response_content)
Test/Deploy updates

Google guage chart give Unknown Header Type : 24

Here is my code which is right as per my knowledge. Because I created similar PIE chart successfully,
Error is : Unknown Header Type : 24
I think error is in parsing data from csv file. But it parsed correctly in string & int form.
Can someone tell what is the issue here.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["gauge"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("Chart2-data.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
//alert(arrayData);
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data);
view.setColumns([0,1]);
// set chart options
var options = {
title: "A Chart from a CSV!",
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
var chart = new google.visualization.Gauge(document.getElementById('gauge'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="gauge" style="width: 900px; height: 500px;"></div>
</body>
</html
>
csv data:
Engine,24
min,34
max,0
yellowFrom,10
yellowTo,6
redFrom,6
redTo,0
I was having the same problem.
Using Firebug on my DB result I was able to identify that the problem was that the google library threating a numeric value as an array header.
My array is the following
[['234 234 - ',234.00],['234 234 - ',234.00],['cuarta zzzzzzzzz prueba htmlzzzzzzz - ',654999.00],['fulanita de tal - ',150.00],['fulanita de tal - ',133.00],['Mario Alvarez Alvarez - tony',125143.20],['otra5555 prueba5555 - ',1866.00],['prieba de insert actualizando - ',1101.00],['prueba 888 - ',987.00],['prueba con html - ',854.00],['prueba de guardado - ',123.00],['prueba de insert - ',369.00],['prueba insert actualizando 02 - ',753.00],['prueba666 7777 - ',1547.00],['prueba666 7777 - ',1547.00],['prueba88888 de guardado8888 - ',1576.00],['tercera prueba - ',98765.00]]
My javascript error was:
Error: Unknown header type: 234
The solution is explained in the Google Visualization API Reference:
google.visualization.arrayToDataTable(twoDArray, opt_firstRowIsData)
Check this link for detailed info
You have to explicit tell the library that the first row is data, not a header. I add the second parameter true like this:
var data = google.visualization.arrayToDataTable(vArray, true);
PD: My web app was working fine until a few days ago. I guess google did some change to the library.
Hope my explain will help you

create Google Chart through AJAX call with JSON/JS

CI'm having an issue creating a chart. I've read number of tutorials and basically wrote a code according to them. However, the problem is that the chart won't be displayed at all.
I want on AJAX call to retrieve data from SQLite3 and then draw a chart based on that data.
It could be Column or Pie chart, doesnt matter.
I'm pretty sure there is some kind of problem with the way I work on JSON, and I would like someone to help me. Thanks!
#test.html
-------------------------------------------------------------------------
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function drawChart() {
var jsonData = $.ajax({
url: "test-return.php",
dataType: "json",
async: false
}).responseText;
document.getElementById('rightDiv').innerHTML = jsonData;
var jsonData2 = [["FC Internazionale ",24],["AS Roma ",24],["Milan AC ",20],["UC Sampdoria ",19],["US Citt\u00e0 di Palermo",18],["SSC Napoli ",15],["Juventus FC ",16],["Parma FC ",14],["Genoa CFC ",14],["AS Bari ",13],["AC Fiorentina ",13],["SS Lazio ",11],["Calcio Catania ",10],["Cagliari Calcio ",11],["Udinese Calcio ",11],["AC Chievo Verona ",12],["Bologna FC ",10],["Atalanta BC ",9],["AC Siena ",7],["AS Livorno Calcio ",7]];
var data = google.visualization.arrayToDataTable(jsonData2,true);
var options = {
title: 'table 1'
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
</script>
</head>
<body>
<div id="chart_div" style="width: 400px; height: 500px;"></div>
<div id="rightDiv">query results</div>
</body>
</html>
#test-return.php
-----------------------------------------------------------------------------
<?php
sqlite code here
................
echo json_encode($row_array);
?>
$row_array output => [["FC Internazionale ",24],["AS Roma ",24],["Milan AC ",20],["UC Sampdoria ",19]......
You have to match your data format to format expected by your chosen chart type. As-is, you will have 3 columns of data: one numeric, one string, and one numeric. The PieChart expects two columns of data: the first should be type "string" and the second should be type "number". ColumnCharts can have any number of columns: the first can be either type "number", "date", "datetime", "timeofday", or "string", but all of the following columns should be type "number" (usually, that is - there are some exceptions that have to do with using column roles which are outside the scope of what you are doing here).
Looking at your data, I am speculating that the first column (the 1, 2, 3, 4... in your sample data) is a row number and not something you intend to plot. If this is the case, you need to adjust your server-side code to remove it. If this is not the case, can you provide information about it so I can help you figure out how to use it?
Also, your data is missing column headers. As structured, the arrayToDataTable method will take the first row of data and use it as the column headers, so you would get three columns with the labels "1", "FC Internazionale ", and "24", which you probably don't want. Either amend your server-side code to make the first row of data contain column labels, or set the second argument in the arrayToDataTable call to true.
By using jsonData = $.ajax(...).responseText;, you are bypassing the JSON conversion that jQuery does and passing the raw text of the response to jsonData. Since you need a javascript array to use the arrayToDataTable method, you need to call JSON.parse on jsonData to convert it to an array:
var data = google.visualization.arrayToDataTable(JSON.parse(jsonData), true);

Categories

Resources