Skip to main content

A Hierarchical Chooser Using Google's Visualization API


Writing about physics and specifically electromagnetism got me to thinking about amateur radio. In the United States, any person can receive an amateur radio license that allows them to transmit and receive on a number of frequencies allocated by the FCC. Amateur radio is a great hobby. People involved in the hobby, (called amateur radio operators), get a chance to turn their EM knowledge into concrete experience by building usable radio transceivers and antenna structures.

To get a license, operators must first pass a written test on radio operations fundamentals, engineering, and FCC regulations that apply to amateur radio. The question pools used for the exam are available online as are practice tests. I thought it would be fun to build an application that would construct practice tests on this blog. The final application will provide practice tests similar to the ones at qrz.com but, with a bit more interactivity. This series of articles will cover the construction of the application using the Google Visualization API and JavaScript as the application's platforms. For an in depth description of these platforms as well as another sample application see the post: mini-digg.

The question pool for the FCC amateur radio license examination is organized in the following hierarchy:

License Class: Technician(T), General(G), or Extra(E)
--Subelement
----Group
------Question

This first article describes a hierarchical chooser that will allow the user to select which license exam they want to study as well as the subset of questions within that exam to concentrate on.

The chooser is shown below:


ElementSubelementGroup



The left-most list box contains the highest order of hierarchy and is filled when the web page is loaded. When the user chooses an entry at this level, the second level of hierarchy is filled based on the user's selection. This operation is duplicated for each level of hierarchy except the last. When the user selects 'All', the list boxes to the right of the level of the selection are cleared.

The spreadsheet containing the data model used to test the chooser is shown below:



Brief Explanation of the Code
I won't go into too much detail as the mini-digg article acts as a primer for the Google Visualization API.

When the web page that contains the chooser is loaded, the function hiersel_initialize is called. This function is responsible for constructing the query string that will get the hierarchy levels to be included in the first list box. The query is executed with the load_elements function. When the query has retrieved the requested results from the spreadsheet, it calls back to the loadFirstSelect function, which should probably be renamed, because it is in fact used to load all the list boxes. One thing to point out in the loadFirstSelect function is a small for loop used to isolate unique values in the data and discard repeated values. This is necessary because the query language does not have a 'unique record' facility yet.

After the first level of hierarchy is filled, everything is driven by the user. When the user makes a selection in a list box, the onchange event calls fill_hier and passes in the id of the list box where the selection was made. fill_hier constructs a new query string that selects values from the next level of hierarchy that match are members of the currently selected level of hierarchy.

The code is included below. Go ahead and try it out. Do you see any opportunities for improvement, (there are plenty)? Can you adapt to an application of your own? Let me know!


The Code



<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1");
google.setOnLoadCallback(hiersel_initialize);
var hier_cols = [];
var hier_vals = [];
var my_col = [];
var next_level_col = [];
var next_level_id = [];
var hier_levels = 3;
var loading_sel = 'A';

function hiersel_initialize() {
hier_cols.push('E');
hier_cols.push('F');
hier_cols.push('G');

my_col.push('A');
my_col.push('B');
my_col.push('C');

next_level_col.push('B');
next_level_col.push('C');
next_level_col.push('last');

next_level_id.push('B');
next_level_id.push('last');


//Load the highest level of hierarchy
load_elements('select A where A <> "Element"');
}

//var stQuery_chat = 'http://spreadsheets.google.com/tq?key=pvFXGB-79Kl2GEcZuVgOiQw&gid=0&pub=1';
var stQuery_hier = 'http://spreadsheets.google.com/pub?key=pvFXGB-79Kl2d6jU-_m44ZQ&gid=0&pub=1';



function load_elements(stQuery) {
var query = new google.visualization.Query(stQuery_hier);
query.setQuery(stQuery);
query.send(loadFirstSelect);
}


function loadFirstSelect(response){
loadOptionText('All');

if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var lasttxt = 'Goofy Junk';
for (var row = 0; row < data.getNumberOfRows(); row++){
var valtxt = data.getFormattedValue(row, 0);
if(valtxt != lasttxt){
loadOptionText(valtxt);
}
lasttxt = valtxt;
}

}

function loadOptionText(opText){
var y=document.createElement('option');
y.text=opText;
var x=document.getElementById(loading_sel);

try
{
x.add(y,null);
}
catch(ex)
{
x.add(y);
}
}

function clearOption(stID){
var x=document.getElementById(stID);
while(x.length != 0){
x.remove(0);
}
}

function fill_hier(stId){
//alert("Selection changed " + stId);

//Get the new value of the changed control
var y = document.getElementById(stId);
//alert("New Id is " + stId);
var stNew = y.options[y.selectedIndex].text;

//alert("New selection is " + stNew);

//Find out what level the changed control is
var x = document.getElementsByName('hier_sel');

var save_level = 0;
var query_condition = ' where ';
var found_level = 0;
for(var level = 0; level < hier_levels && (found_level == 0); level++){
//Add a condititon for each level passed
//alert('loading z');
var z = x[level];
//alert('getting z text');
var ztext = z.options[z.selectedIndex].text;
//alert('constructing condition');
query_condition = query_condition + my_col[level] + ' = "' + ztext + '"';
//alert('New condition is ' + query_condition);
if(stId == x[level].id){
//alert('Found level ' + level);
save_level = level;
found_level = 1;
}
//alert('Out of lewel finder');
if(found_level != 1){
query_condition = query_condition + ' and ';
}
}

//alert('condition is ' + query_condition);

//clear all lists to the right
for(var clear_level = save_level + 1; clear_level < hier_levels; clear_level++){
clearOption(x[clear_level].id);
}

//Construct the query string and load the next level of hierarchy
if(stId != 'last' && stNew != 'All'){
var query_update = "Select " + next_level_col[save_level] + query_condition;
//alert("Then new query string is " + query_update);
loading_sel = next_level_id[save_level];
load_elements(query_update);
}

//If the changed value is 'All', clear all lists to the right
if(stNew == 'All'){
for(var clear_level = save_level + 1; clear_level < hier_levels; clear_level++){
clearOption(x[clear_level].id);
}
}


}

</script>


<form id='hier_chooser'>
<table border=3><tr><td>Element</td><td>Subelement</td><td>Group</td></tr><tr><td><select name="hier_sel" id="A" onchange="fill_hier(this.id)"></select></td><td><select name="hier_sel" id="B" onchange="fill_hier(this.id)"></select></td><td><select name="hier_sel" id="last"></select></td></tr></table><p>
</form>




Resources:
For more on how the Google Visualization API works:
Google Visualization API Query Language Documenation
An in depth Google Visualization API example application from this blog:
min-digg

A great reference for the Document Object Model used to capture list box selections in JavaScript:
HTML DOM Documentation


Handy Stuff:

Comments

Popular posts from this blog

More Cowbell! Record Production using Google Forms and Charts

First, the what : This article shows how to embed a new Google Form into any web page. To demonstrate ths, a chart and form that allow blog readers to control the recording levels of each instrument in Blue Oyster Cult's "(Don't Fear) The Reaper" is used. HTML code from the Google version of the form included on this page is shown and the parts that need to be modified are highlighted. Next, the why : Google recently released an e-mail form feature that allows users of Google Documents to create an e-mail a form that automatically places each user's input into an associated spreadsheet. As it turns out, with a little bit of work, the forms that are created by Google Docs can be embedded into any web page. Now, The Goods: Click on the instrument you want turned up, click the submit button and then refresh the page. Through the magic of Google Forms as soon as you click on submit and refresh this web page, the data chart will update immediately. Turn up the:

Cool Math Tricks: Deriving the Divergence, (Del or Nabla) into New (Cylindrical) Coordinate Systems

Now available as a Kindle ebook for 99 cents ! Get a spiffy ebook, and fund more physics The following is a pretty lengthy procedure, but converting the divergence, (nabla, del) operator between coordinate systems comes up pretty often. While there are tables for converting between common coordinate systems , there seem to be fewer explanations of the procedure for deriving the conversion, so here goes! What do we actually want? To convert the Cartesian nabla to the nabla for another coordinate system, say… cylindrical coordinates. What we’ll need: 1. The Cartesian Nabla: 2. A set of equations relating the Cartesian coordinates to cylindrical coordinates: 3. A set of equations relating the Cartesian basis vectors to the basis vectors of the new coordinate system: How to do it: Use the chain rule for differentiation to convert the derivatives with respect to the Cartesian variables to derivatives with respect to the cylindrical variables. The chain

The Valentine's Day Magnetic Monopole

There's an assymetry to the form of the two Maxwell's equations shown in picture 1.  While the divergence of the electric field is proportional to the electric charge density at a given point, the divergence of the magnetic field is equal to zero.  This is typically explained in the following way.  While we know that electrons, the fundamental electric charge carriers exist, evidence seems to indicate that magnetic monopoles, the particles that would carry magnetic 'charge', either don't exist, or, the energies required to create them are so high that they are exceedingly rare.  That doesn't stop us from looking for them though! Keeping with the theme of Fairbank[1] and his academic progeny over the semester break, today's post is about the discovery of a magnetic monopole candidate event by one of the Fairbank's graduate students, Blas Cabrera[2].  Cabrera was utilizing a loop type of magnetic monopole detector.  Its operation is in concept very sim