Include a scatter plot and pie chart referencing same fusion table data

309 views
Skip to first unread message

es

unread,
Jun 8, 2012, 12:42:34 PM6/8/12
to google-visua...@googlegroups.com
Hi,
I would like to add a second chart (scatter plot) to my webpage which references the same fusion table as my pie chart.  The pie chart is interactive, so that when a user clicks a point on the map, the pie chart changes to show stats about that site.  I'd like to also have an interactive scatter plot so that when a user clicks a point on the map, the scatter plot also represents data from that site.  Since the scatter will show data from all sites, I'd just like to have the selected point to highlight on the scatter plot.  For example, when a user clicks on site 10, the pie charts shows stats for site 10, and the scatter WOULD show all sites with site 10 a different color so it stands out.  Is this possible?  Here is my functioning script code for the pie and map:
 
 
    <script type="text/javascript">
      google.load('visualization', '1', { packages: ['corechart'] });

function initialize() {
 var myOptions = {  
  center: new google.maps.LatLng(38.099983,-80.683594),
  zoom: 7,
  mapTypeControl: true,
  mapTypeControlOptions: {
   style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
   position: google.maps.ControlPosition.TOP_RIGHT
      },
  zoomControlOptions: {
   style: google.maps.ZoomControlStyle.LARGE
   },
  streetViewControl: true,
  streetViewControlOptions: {
   position: google.maps.ControlPosition.LEFT_TOP
   },
  mapTypeId: google.maps.MapTypeId.TERRAIN
  };
  
var map = new google.maps.Map(document.getElementById('map_canvas'),
  myOptions);
 
var layer = new google.maps.FusionTablesLayer();
        updateLayerQuery(layer);
        layer.setMap(map);     
  drawVisualization('Bear Branch');
        google.maps.event.addListener(layer, 'click', function(e) {
          var Site = e.row['Site'].value;
          drawVisualization(Site); 
   
});

        google.maps.event.addDomListener(document.getElementById('Site'),'change', function() {
var Site = this.value;
              updateLayerQuery(layer, Site);
              drawVisualization(Site);
         
});
}
function updateLayerQuery(layer) {
        layer.setOptions({
          query: {
            select: 'Site',
            from: '3235688',
           
}
});
}

function drawVisualization(Site) {
    var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=');
    query.setQuery("SELECT Site, BCw, BCdep, Nup, Nimm, ANClimit, BCup " + "FROM 3235688  WHERE Site = '" + Site + "'");
    query.send(function (response) {
        var baseData = response.getDataTable();
        var data = new google.visualization.DataTable();
        data.addColumn('string', baseData.getColumnLabel(0));
        data.addColumn('number', 'Value');
        for (var i = 1; i < baseData.getNumberOfColumns(); i++) {
            data.addRow([baseData.getColumnLabel(i), baseData.getValue(0, i)]);
        }
       
        google.visualization.drawChart({
            containerId: "visualization",
            dataTable: data,
            chartType: "PieChart",
            options: {
                title: Site,
    colors: ['#0000CC', '#3399FF','#66CC00', '#FFFF00', '#FF9933', '#FF0033',],
    legendTextStyle: {color:'#666666', fontSize: '11'},
    titleTextStyle: {color: '#006600',fontSize: '12'},    
    titlePosition: 'out',
    legend:'left',
    is3D:true,
                height: 150,
                width: 350,
    backgroundColor: 'none',
    tooltip: {textStyle: {color: 'black'}, showColorCode: true},
    pieSliceText: 'percentage',
    pieSliceTextStyle: {color: 'white', fontSize: '11'},
    chartArea: {top:'30', left:'5', height:"80%", width:"70%"}
    
            }
   
             
        });
    });
}
 

google.maps.event.addDomListener(window, 'load', initialize);
</script>

asgallant

unread,
Jun 8, 2012, 3:00:02 PM6/8/12
to google-visua...@googlegroups.com
There are a couple ways to approach this.  The first (with a few minor modifications to your code): http://jsfiddle.net/asgallant/G5Bga/ 

The second way is a rather dramatic departure from the approach you took; it uses the Visualization API wrapper for Google Maps, which is less flexible than the base Maps API (as it doesn't expose the Map object to work with), but has the benefit of being able to run directly off of the Visualization API's DataTables.  You could likely make a single query to drive the map and both charts, using DataViews to hide columns and filter out rows.  I got a start on it here (driving map and scatter off one query):  http://jsfiddle.net/asgallant/rSRzE/ but there is an error being thrown by the map that I haven't been able to track down just yet (and likely won't until next week, if I have the time).

E&S Environmental

unread,
Jun 8, 2012, 6:01:35 PM6/8/12
to google-visua...@googlegroups.com
Hi,
Thank you!  I applied your first method and it is working.  Is there a way to tweak the scatter plot code so when the user clicks the drop down menu it not only changes the pie chart, but also changes the scatter plot?  The drop down menu is just working for the pie, currently.  Additionally, I'm not able to view this in Internet Explorer... any idea why?
Thanks!

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.
To view this discussion on the web visit https://groups.google.com/d/msg/google-visualization-api/-/0TzwGRkvZFAJ.

To post to this group, send email to google-visua...@googlegroups.com.
To unsubscribe from this group, send email to google-visualizati...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-visualization-api?hl=en.

E&S Environmental

unread,
Jun 8, 2012, 6:10:27 PM6/8/12
to google-visua...@googlegroups.com
Woops, I forgot to ask... are the chart options for the scatter somewhat similar to the options for the pie?  I'd like to change the "highlighted" point so it popped out more and is larger, and make the other points smaller because when the graph is small it's hard to see the selected point.  Thanks!

On Fri, Jun 8, 2012 at 12:00 PM, asgallant <drew_g...@abtassoc.com> wrote:

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.

visigoth

unread,
Jun 11, 2012, 5:00:22 AM6/11/12
to google-visua...@googlegroups.com
I am afraid that at the moment we do not provide options to control the size of focused / selected points.

To post to this group, send email to google-visualization-api@googlegroups.com.
To unsubscribe from this group, send email to google-visualization-api+unsub...@googlegroups.com.

asgallant

unread,
Jun 11, 2012, 11:06:17 AM6/11/12
to google-visua...@googlegroups.com
True, it is not supported in the API, but we can hack around the problem with a handy-dandy DataView and the use of the 'series' option: http://jsfiddle.net/asgallant/G5Bga/8/ 

I made a few structural changes to make the code more robust in there (placed all the event listeners in a 'ready' event listener for the scatter chart so we don't accidentally try to set any selections in the scatter chart before it's finished drawing) as well.

The IE problem might have been caused by an errant comma at the end of the 'colors' option array in the #drawChart method call for the pie chart.

asgallant

unread,
Jun 11, 2012, 11:06:59 AM6/11/12
to google-visua...@googlegroups.com
Ooops, sorry - the link there is the wrong one, use this: http://jsfiddle.net/asgallant/G5Bga/9/

E&S Environmental

unread,
Jun 11, 2012, 2:23:40 PM6/11/12
to google-visua...@googlegroups.com
Hi,
Thank you for the help!  It appears to run in Chrome, but crashes IE (says the script is running too long).  Any idea why?
Thanks!

On Mon, Jun 11, 2012 at 8:06 AM, asgallant <drew_g...@abtassoc.com> wrote:
Ooops, sorry - the link there is the wrong one, use this: http://jsfiddle.net/asgallant/G5Bga/9/

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.
To view this discussion on the web visit https://groups.google.com/d/msg/google-visualization-api/-/sNOPJlnTyLYJ.

To post to this group, send email to google-visua...@googlegroups.com.
To unsubscribe from this group, send email to google-visualizati...@googlegroups.com.

asgallant

unread,
Jun 11, 2012, 3:10:09 PM6/11/12
to google-visua...@googlegroups.com
I didn't see any problems in IE9, so I ran it in an IE7 instance in IETester (a buggy, crashy way to test your pages in versions of IE that you don't have installed), and it seemed to get stuck in an infinite loop when I selected things in the map.  When I used the dropdown or clicked in the scatter chart/pie chart, everything worked fine.


On Monday, June 11, 2012 2:23:40 PM UTC-4, es wrote:
Hi,
Thank you for the help!  It appears to run in Chrome, but crashes IE (says the script is running too long).  Any idea why?
Thanks!

On Mon, Jun 11, 2012 at 8:06 AM, asgallant <drew_g...@abtassoc.com> wrote:
Ooops, sorry - the link there is the wrong one, use this: http://jsfiddle.net/asgallant/G5Bga/9/

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.
To view this discussion on the web visit https://groups.google.com/d/msg/google-visualization-api/-/sNOPJlnTyLYJ.

To post to this group, send email to google-visualization-api@googlegroups.com.
To unsubscribe from this group, send email to google-visualization-api+unsub...@googlegroups.com.

Deian Moore

unread,
Jun 11, 2012, 4:10:01 PM6/11/12
to google-visua...@googlegroups.com

Yes, that’s what happened to me – when I clicked a point on the map it got stuck in a loop and then I had to force shutdown after a while. However, it is at least “showing up” in IE… before you made the changes, the map and the charts wouldn’t display.  Having the point on the scatter plot to highlight is great… however having it crash in IE isn’t so great.  Any other suggestions?

 

From: google-visua...@googlegroups.com [mailto:google-visua...@googlegroups.com] On Behalf Of asgallant
Sent: Monday, June 11, 2012 12:10 PM
To: google-visua...@googlegroups.com
Subject: Re: [visualization-api] Re: Include a scatter plot and pie chart referencing same fusion table data

 

I didn't see any problems in IE9, so I ran it in an IE7 instance in IETester (a buggy, crashy way to test your pages in versions of IE that you don't have installed), and it seemed to get stuck in an infinite loop when I selected things in the map.  When I used the dropdown or clicked in the scatter chart/pie chart, everything worked fine.

On Monday, June 11, 2012 2:23:40 PM UTC-4, es wrote:

Hi,

Thank you for the help!  It appears to run in Chrome, but crashes IE (says the script is running too long).  Any idea why?

Thanks!

On Mon, Jun 11, 2012 at 8:06 AM, asgallant <drew_g...@abtassoc.com> wrote:

Ooops, sorry - the link there is the wrong one, use this: http://jsfiddle.net/asgallant/G5Bga/9/

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.

To view this discussion on the web visit https://groups.google.com/d/msg/google-visualization-api/-/sNOPJlnTyLYJ.


To post to this group, send email to google-visua...@googlegroups.com.
To unsubscribe from this group, send email to google-visualizati...@googlegroups.com.

 

--

You received this message because you are subscribed to the Google Groups "Google Visualization API" group.

To view this discussion on the web visit https://groups.google.com/d/msg/google-visualization-api/-/XYYxYP1V198J.
To post to this group, send email to google-visua...@googlegroups.com.
To unsubscribe from this group, send email to google-visualizati...@googlegroups.com.

No virus found in this message.
Checked by AVG - www.avg.com
Version: 2012.0.2180 / Virus Database: 2433/5062 - Release Date: 06/11/12


No virus found in this message.
Checked by AVG - www.avg.com
Version: 2012.0.2180 / Virus Database: 2433/5062 - Release Date: 06/11/12

asgallant

unread,
Jun 11, 2012, 5:34:17 PM6/11/12
to google-visua...@googlegroups.com
Comment out all of the event handlers, and test.  Add stuff back in and test until you make it break; then you'll have some idea of what is not working right.


On Monday, June 11, 2012 4:10:01 PM UTC-4, es wrote:

Yes, that’s what happened to me – when I clicked a point on the map it got stuck in a loop and then I had to force shutdown after a while. However, it is at least “showing up” in IE… before you made the changes, the map and the charts wouldn’t display.  Having the point on the scatter plot to highlight is great… however having it crash in IE isn’t so great.  Any other suggestions?

 

From: google-visualization-api@googlegroups.com [mailto:google-visualization-a...@googlegroups.com] On Behalf Of asgallant
Sent: Monday, June 11, 2012 12:10 PM
To: google-visualization-api@googlegroups.com
Subject: Re: [visualization-api] Re: Include a scatter plot and pie chart referencing same fusion table data

 

I didn't see any problems in IE9, so I ran it in an IE7 instance in IETester (a buggy, crashy way to test your pages in versions of IE that you don't have installed), and it seemed to get stuck in an infinite loop when I selected things in the map.  When I used the dropdown or clicked in the scatter chart/pie chart, everything worked fine.

On Monday, June 11, 2012 2:23:40 PM UTC-4, es wrote:

Hi,

Thank you for the help!  It appears to run in Chrome, but crashes IE (says the script is running too long).  Any idea why?

Thanks!

On Mon, Jun 11, 2012 at 8:06 AM, asgallant <drew_g...@abtassoc.com> wrote:

Ooops, sorry - the link there is the wrong one, use this: http://jsfiddle.net/asgallant/G5Bga/9/

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.

To view this discussion on the web visit https://groups.google.com/d/msg/google-visualization-api/-/sNOPJlnTyLYJ.


To post to this group, send email to google-visualization-api@googlegroups.com.
To unsubscribe from this group, send email to google-visualization-api+unsub...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.
To view this discussion on the web visit https://groups.google.com/d/msg/google-visualization-api/-/XYYxYP1V198J.

To post to this group, send email to google-visualization-api@googlegroups.com.
To unsubscribe from this group, send email to google-visualization-api+unsub...@googlegroups.com.

es

unread,
Jul 5, 2012, 5:40:29 PM7/5/12
to google-visua...@googlegroups.com
Hi,
I'm finally back to try and figure out what is causing the browser (Firefox) to crash after clicking on 9 points. When I initially click a map point, everything works wonderful. The pie chart changes to show the data, the scatter chart's point highlights, the title's change, and even the drop down menu works to function both the pie and the scatter. However, the webpage gets progressively slower with each click, and by the time I have clicked 9 points, it basically crashes. It's as though it is going on an infinite loop and when the data has been requested (a pie and a scatter), it doesn't stop the request. I'm not sure what to do about your suggestion to comment out the event handlers. They all seem necessary in order for these features to function. Is there some way to "end" this loop after clicking a point and getting the action requested (the pie and the scatter), and then start fresh again with a new click? It worked to just show the scatter and the pie, but when I got fancy and wanted the scatter point to highlight, and have the dropdown menu also operate the scatter, things became unstable. Here is a link to the map/charts: http://www.esenvironmental.com/projects_multiagency_cl_googlemap_scatterwork.htm And, if this helps, here is all the code (again!) for the map and the charts. Thanks in advance for your help!
<script type="text/javascript">
google.load('visualization', '1', { packages: ['corechart'] });
// below is new from google help for the scatter plot

google.load('visualization', '1', {packages: ['corechart']});
google.load('maps', '3.9', {other_params: "sensor=false"});
google.setOnLoadCallback(initialize);
function initialize() {
var myOptions = {
center: new google.maps.LatLng(38.099983, -80.683594),
zoom: 7,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
streetViewControl: true,
streetViewControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
},
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var layer = new google.maps.FusionTablesLayer();
updateLayerQuery(layer);
layer.setMap(map);
drawVisualization('Bear Branch');

var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=');
query.setQuery('SELECT Site, CALK, MAGIC_CL50 FROM 3235688');
query.send(function (response) {
var data = response.getDataTable();
var baseView = new google.visualization.DataView(data);
baseView.setColumns([1, 2]);
var scatter = new google.visualization.ScatterChart(document.getElementById('scatter'));

google.visualization.events.addListener(scatter, 'ready', function () {

google.maps.event.addListener(layer, 'click', function(e) {
var Site = e.row['Site'].value;
setScatterSelection(Site);

drawVisualization(Site);
});

google.maps.event.addDomListener(document.getElementById('Site'), 'change', function() {
var Site = this.value;
updateLayerQuery(layer, Site);
setScatterSelection(Site);
drawVisualization(Site);
});

function setScatterSelection (site) {
var row = data.getFilteredRows([{column: 0, value: site}])[0];
var view = new google.visualization.DataView(baseView);
view.setColumns([0, 1, {
type: 'number',
label: baseView.getColumnLabel(1),
calc: function (dt, index) {
if (row == index) {
return dt.getValue(index, 1);
}
else {
return null;
}
}
}]);
var ready = google.visualization.events.addListener(scatter, 'ready', function () {
scatter.setSelection([{row: row, column: 2}]);
google.visualization.events.removeListener(ready);
});
scatter.draw(view, {
width: 350,
height: 300,
titleX: 'ANC (ueq/L)',
title: 'Site',
titleTextStyle: {
color: '#006600',
fontSize: '12'
},
titleY: 'CL for ANC=50 (meq/m2/yr)',

series: [{
pointSize: 5
}, {
visibleInLegend: false,
pointSize: 10,
color: 'red'
}],
legend: {position: 'none', textStyle: {color: 'blue', fontSize: 12}},
title: '' + site
});
};
});


});
}
function updateLayerQuery(layer) {
layer.setOptions({
query: {
select: 'Site',
from: '3235688'
}
});
}
function drawVisualization(Site) {
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=');
query.setQuery("SELECT Site, BCw, BCdep, Nup, Nimm, ANClimit, BCup " + "FROM 3235688 WHERE Site = '" + Site + "'");
query.send(function(response) {
var baseData = response.getDataTable();
var data = new google.visualization.DataTable();
data.addColumn('string', baseData.getColumnLabel(0));
data.addColumn('number', 'Value');
for (var i = 1; i < baseData.getNumberOfColumns(); i++) {
data.addRow([baseData.getColumnLabel(i), baseData.getValue(0, i)]);
}
google.visualization.drawChart({
containerId: "visualization",
dataTable: data,
chartType: "PieChart",
options: {
title: Site,
colors: ['#0000CC', '#3399FF', '#66CC00', '#FFFF00', '#FF9933', '#FF0033'],

asgallant

unread,
Jul 6, 2012, 10:40:34 AM7/6/12
to google-visua...@googlegroups.com
At a guess, I'd say there is a memory leak in regards to the PieChart.  Every time you click a point, you draw a new PieChart, but the old one is still resident in memory.  I rearranged your code and made a couple tweaks so that you don't have this problem any more: http://jsfiddle.net/asgallant/G5Bga/11/ 

Basically, the pie chart is now created (but not drawn) in the initialize function, and the drawVisualization function has been moved inside the initialize function so the pie chart will be in scope.

es

unread,
Jul 6, 2012, 11:54:37 AM7/6/12
to google-visua...@googlegroups.com
Hi,
I checked your link and I'm not seeing the pie chart change when a map point is clicked.  The dropdown menu also isn't operating the pie chart.  Were these functioning on your end?
Thanks

asgallant

unread,
Jul 6, 2012, 12:46:52 PM7/6/12
to google-visua...@googlegroups.com
D'oh, you're right!  The scatter.draw() call was missing.  After adding that back in, I discovered that this was not the culprit.  Further investigation revealed that it is a rather dumb error that is likely my fault (IIRC, I helped you write the scatter chart code, right?): the 'ready' event handler for the scatter chart should only run once.  As it is now, the code inside gets run every time the scatter chart updates, so all of the event listeners get added again.  Since some of these event listeners force the scatter chart to redraw, the number of listeners grows exponentially with each click (so on click 9 there are 512 'select' event listeners for the map).  No wonder there are performance problems!  The only thing that surprises me is that other browsers didn't have performance problems.  Anyway, I have an example fix here: http://jsfiddle.net/asgallant/G5Bga/14/

Note that I changed a whole bunch of other stuff in the quest for the culprit, so there are probably things you technically don't need to copy there.  The important parts you need are the lines:

var runOnce google.visualization.events.addListener(scatter'ready'function({ 

and

google.visualization.events.removeListener(runOnce);

add the "var runOnce " to the first event listener (after the scatter chart is created) and the removeListener call to the very end of the same event listener.  That should take care of the problem for you.

es

unread,
Jul 6, 2012, 3:03:21 PM7/6/12
to google-visua...@googlegroups.com
Hi,
Yes, you helped me with building the scatter so I could make the selected point "pop" out (yeah!).  I pasted all of your code into my web and it works wonderfully... even in IE (which originally the map wouldn't even display).   And, that infinite loop made sense as to why it performed so poorly! Thanks for figuring that out!!  It was interesting how you changed the scatter.draw(baseView) versus the scatter.draw(view).  They appear to be in just one container id now, and yet I can still get the highlighted point effect!  Is it possible to have the "base view" also show Bear Branch highlighted on the scatter, when the user first goes to the site?  Would this code be included in the base view area of the scatter or would I place it outside the container id, like it is for the pie chart: drawVisualization('Bear Branch');?  After this, my next task will be to add check boxes so boundary layers/polygons and the points on the map can be turned off and on - hopefully these will be compatible with the scatter/pie since these elements are functioning from a fusion table - the boundary layers would be stand-alone kmz files.  I may need to tap your expert brain when I get to that point!  :)

asgallant

unread,
Jul 6, 2012, 3:18:34 PM7/6/12
to google-visua...@googlegroups.com
Yes, you probably could use a single query for both the Pie and Scatter charts.  Your query would have to include all of the necessary columns for both charts, and use DataViews to hide the appropriate columns from each.  The view for the Pie charts would also have to be filtered by site before transforming the view into the final DataTable.  None of this is particularly difficult to do.  The major trade-off is that users will essentially be downloading the entire data set on page load (which could potentially slow things down to start) instead of downloading only the data they need when they need it.

Defaulting to "Bear Branch" is easy: http://jsfiddle.net/asgallant/G5Bga/15/.  I moved the location of the setScatterSelection function one step back and replaced the scatter.draw() call with a setScatterSelection call to make it work.

As far as the map stuff goes, I can help with generic javascript stuff, but I'm not very familiar with the API, so I can't give you any specifics.

es

unread,
Jul 6, 2012, 4:09:37 PM7/6/12
to google-visua...@googlegroups.com
Awesome - thank you so much! You must eat, sleep, and play javascript because you are so quick at coming up with a solution.  I very much appreciate your help!!
 
I'll get started on the check boxes/add/remove kmz layers and post you again if I run into troubles with it.
 
Happy Friday!
Reply all
Reply to author
Forward
0 new messages