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

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

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 rule can be used to convert a differential operator in terms of one variable into a series of differential operators in terms of othe…

Lost Phone

We were incredibly lucky to have both been in university settings when our kids were born.  When No. 1 arrived, we were both still grad students.  Not long after No. 2 arrived, (about 10 days to be exact), mom-person defended her dissertation and gained the appellation prependage Dr. 

While there are lots of perks attendant to grad school, not the least of them phenomenal health insurance, that’s not the one that’s come to mind for me just now.  The one I’m most grateful for at the moment with respect to our kids was the opportunities for sheer independence.  Most days, we’d meet for lunch on the quad of whatever university we were hanging out at at the time, (physics research requires a bit of travel), to eat lunch.  During those lunches, the kids could crawl, toddle, or jog off into the distance.  There were no roads, and therefore no cars.  And, I realize now with a certain wistful bliss I had no knowledge of at the time, there were also very few people at hand that new what a baby…

Lab Book 2014_07_10 More NaI Characterization

Summary: Much more plunking around with the NaI detector and sources today.  A Pb shield was built to eliminate cosmic ray muons as well as potassium 40 radiation from the concreted building.  The spectra are much cleaner, but still don't have the count rates or distinctive peaks that are expected.
New to the experiment?  Scroll to the bottom to see background and get caught up.
Lab Book Threshold for the QVT is currently set at -1.49 volts.  Remember to divide this by 100 to get the actual threshold voltage. A new spectrum recording the lines of all three sources, Cs 137, Co 60, and Sr 90, was started at approximately 10:55. Took data for about an hour.
Started the Cs 137 only spectrum at about 11:55 AM

Here’s the no-source background from yesterday
In comparison, here’s the 3 source spectrum from this morning.

The three source spectrum shows peak structure not exhibited by the background alone. I forgot to take scope pictures of the Cs137 run. I do however, have the printout, and…