Comparing Mashup Platforms Using JSON & MySQL – Part 1 – Emit JSON

23 03 2007

Technologies Used: PHP 5, MySQL 4.1.2, JavaScript, JSON

Software Used: PHP Designer, Aptana, Firebug, Firefox

While I was not particularly impressed with the ArcWeb Explorer & ArcWeb Services session on Tuesday, it did inspire me to want to do a mashup using my own data sources. I also wanted to compare the mashup creation process & end results across multiple possible mashup platforms. I decided to use JSON since all the mashup API’s are in Javascript and it is an output format that both Google & Yahoo web services provide. I am already using JSON with the data entry interface for our Breeding Bird Census data that Plateau Land & Wildlife collects each spring.

JSON (or JavaScript Object Notation) is a well described data exchange format that is rapidly gaining favor over XML for web service data transport as it is less verbose and automatically parsed by Javascript.

While I had already created a JSON object model for use with our survey management system, it was structured in a totally different way than what I really wanted for my mashup. I also wanted to demonstrate doing this from scratch.

Step 1 – Design your JSON Object (i.e. Class Structure)

You want to put some thought into designing your class structure that you will emit. JSON can represent arrays, classes, and arrays of classes. The Good news is that JSON is VERY flexible, The Bad news is that JSON is VERY flexible. A general rule to follow in determining where you should use an array or class is that indexed lists = arrays, anything else is a class, or a class property (key:value pair). I just used the high tech method of pen & paper to design my JSON object, but you could also use any XML schema generation tool, VS2005 Class Designer, VIsio, etc.

My desired end product is a map showing the location & number of each point count station, with different symbols if it has been surveyed or not. A mouse over or click event will bring up an html table of with information about species observed and provide a Google search link for the bird based on it’s scientific name. The common name usually gets you all kinds of results whereas the scientific name gets you good reference results.

Thus I need Station number, lat/lon for the station, total observed, number of each species observed and scientific name for each species.

JSON Object

{"Observations":

[{"Station":

{"number":"9", "lat":"30.9999",

 "lon":"-98.9999","total_species":"9",

{"Species":

[{"common":"American Robin",

"number":"9", "code":"AMRO",

"scientific":"Turdus migratorius "},

{species cont....}

] } }

]

}

Or in other words:

Array Observations contains Station classes with Properties

  1. number
  2. lat
  3. lon
  4. total_species
  5. Array Species contains unnamed object with Properties
    1. common
    2. number
    3. code
    4. scientific

Step 2 - Create your JSON Object (i.e. Class Structure)

There are a whole bunch of ways to do this and really depends on what language your are programing in on your server side code. It basically boils down to either populating a class and then parse it to JSON through a method or class in your language, or directly writing the JSON string from some data source.

I chose the later for this project because my PHP install didn’t have a built in method for this. But rolling your own is pretty easy.

  1. Get results set from SQL query

function getData($cid,$myYear,$func) {

//cid = client id, myYear=year of survey, func=callback function to handle response

//Get a count of unique species occurring on the property for each point survey station, even those which have no recorded observations

$q_species=”SELECT DISTINCT st.sta_num as station, COUNT(species) as species, st.lat, st.lon

FROM Stations as st LEFT JOIN (Surveys as su) USING (station_id)

WHERE (st.client_id=$cid AND (su.client_id=$cid OR su.client_id IS NULL) AND su.year=$myYear)

GROUP BY station ORDER BY station;”;

 

//Get the details of species observed at each station

$q_obs=”SELECT su.species, su.number, sp.code, sp.scientific, st.sta_num as station

FROM Surveys as su, Species as sp, Stations as st

WHERE su.client_id=$cid AND su.year=$myYear AND su.species=sp.common

AND su.station_id=st.station_id

ORDER BY station, sp.species_id”;

 

//Create the results sets                     

$resSpecies = mysql_query($q_species);

$resObs = mysql_query($q_obs);

 

2. Create the JSON String 

//Loop through each Station & create the JSON string for that Station & it’s data

$myJSON= $func.’({“Observations”:[';

While ($c=mysql_fetch_array($resSpecies)){

$myJSON.= '{"Station":{"number":"'.$c["station"].’”, “lat”:”‘.$c["lat"].’”, “lon”:”‘.$c["lon"].’”, “total_sp”:”‘.$c["species"].’”, “Species”:[';

                 While ($s=mysql_fetch_assoc($resObs)){

                                   if ($s["station"]==$c["station"]){

$observations.=’{“common”:”‘.$s["species"].’”, “number”:”‘.$s["number"].’”, “code”:”‘.$s["code"].’”, “scientific”:”‘.$s["scientific"].’”},’;

                                }

                }

                $myJSON.=rtrim($observations, ‘,’).’]}},’;

                $observations=”";

                mysql_data_seek($resObs,0);

 }

 

$myJSON=rtrim($myJSON, ‘, ‘).’]});’;

return $myJSON;

}

Step 3 – Emit JSON

This is the easiest part of all. Just return the JSON string using whatever the response function is for the language you are using. PHP can use the HTTP Send Request / Get Response functions to give you more control & learn more about what is happening on either side of the exchanges. But, I kept it simple and just echo-ed the string.

echo getData($cid,$myYear,$func);

NEXT STEPS:

>Make & Handle request in your webpage/webapp

>Create mashup





Why I love living in the sub-tropics

17 01 2007




5 Things You Don’t Know About Me

4 01 2007

Just catching up on some blog reading after taking a break from my computer for the holidays, and I noticed I’ve been tagged by Steve. So here it goes.

  1. You would never know it now, but I was a very fat child & adolescent. When I entered my sophomore year of high school at 15, I weighed 285 lbs at 5 ft 9 in. I wore a size 38 pant & only those really baggy cut jeans fit me. By the time I turned 16, I weighed 210 at 6 ft 1 in. I hit a growth spurt, played football, and started weight training and they all combined to completely reshape my body. It took many years before I stopped thinking of myself as “the fat kid”. I now weigh even less and a few years ago got down to the lowest weight since 5th grade while training for my first (& only, thus far) marathon.
  2. I am very much a cat person and don’t really like dogs all that much. I’ve never owned a dog & maybe one day will, but I’m in no hurry. However, I couldn’t imagine life without cats, and have always missed having them around whenever I didn’t own any cats.
  3. I can’t remember ever actually believing in Santa Claus. I figured it out at age 4 after seeing 3-4 mall Santas in one day. I couldn’t figure out which one was the real one and why my parents where trying so hard to find some gifts for my baby sisters that they said Santa was bringing them. I asked my mom point blank and she gave me an honest answer. I then promptly told several of my friends and was on their parents “naughty” list.
  4. I have a serious problem with getting addicted to video/computer games. So much so, that I won’t even play minesweeper or solitaire on my computer. If it is a computer based game, no matter how childish, stupid, simple, or boring it is, you can bet that if I start playing it I won’t be able to stop. And if it is even a little bit good, I’ll ignore work, eating and sleeping to play it. I was even addicted to a PC port of some Nintendo based Pokemon trading game in Japanese. I stayed up 3 nights in a row and ignored work for nearly a week to solve that game. Just in case you were wondering, “Yes, I was WAY to old to be interested in Pokemon” and “No, I don’t speak Japanese, and had no idea what any of the characters were saying”. I avoid video games like the plague and that is the only way to handle that problem for me.
  5. I am the super “un-handy” man. If you have something that works and you want it broken, just let me work on it a bit. One of the worst jobs of “fixing up” something I ever did is on display in our living room. I was given a small side-table height chest of drawers. It was the perfect size for our TV which was way too big for our old stand. So I though, wouldn’t it be cool if I made the bottom drawer into a VCR/DVD player compartment with a hinged door. That way we could open it when we used it and keep it hidden at other times. Well, that didn’t quite happen…

Don't You want this media cabinet?

I’ll pass it on to: Tim (aka Sabin21), Jeff Thurston, Brian Flood





From Whence We Came

11 08 2006

A hand drawn map used for habitat restoration planning & funding

Mapping wayyyy back in the old pre-GIS days of 2001

This was the state of the art for mapping at our company before I started nearly 5 years ago. They had just bought ArcView 3.2 but did not know how to use it.
I was cleaning out some old papers and came across this map which I thought might be of particular interest to those returning from the dazziling displays of GIS magic demo-ed at the ESRI User Conference.
When I started working for Plateau Land & Wildlife in Sept 2001, I brought my GPS for a grand company total of 2 GPS units. Maps were being made in one of 3 ways:

  1. Placing dots & lines on topos in 3D Topoquads and then copying the image into Word to add legends and further annotations
  2. Drawing on transperancy sheets over topo maps -OR-
  3. Sending a hand drawn or 3D Topomap to a contractor who recreated it in ArcView and then sent it to us as a *.jpg

It’s amazing to me how far we as a company have come in terms of using GIS for our work and how throughly it is integrated into our workflows. Now we are anxiously awaiting the release of ArcGIS Explorer so that even traditionally non-GIS using employees can have access to simple GIS and map making capabilities. I can’t imagine going back to the pre-GIS times at our company and being very effecient or profience at what we do.I’d love to hear of anyone else’s similar experinces.





Success! – 1st .NET-MySql-ArcObjects project

15 04 2006

Hurray! My 1st attempt at integrating data from a MySql database into a .NET & ArcObjects application worked. It's pretty rough and only for internal use at this point. It was much easier than I expected.

My Get Lat-Lon Shapefile App

The data comes from a PHP based web app that I wrote to help us manage our large number of Breeding Bird Census counts that we do. For the last 6 years all survey data was reported on an excel spreadsheet with an accompaning word document describing survey stations and conditions. There was no connection between any of this data and it was a terrible pain to anylise the data if we wanted to. The database & web app have made it a very simple task to enter the observations & quickly produce a report without having to enter the same thing several times on servral different documents.

BBC Management System - Station Descriptions

The only problem left to be solved was the best way to get new or changed station coordinates out of the MySql database and onto the clients map. First, I tried just writing a comma delimited test file and having people "Add X&Y Data". However, it was really too many steps for this to work well for my users. Then I made an ASP.NET app which worked great on my computer but had all sorts of problems when we put it on our webhost. Turns out they were running .NET 1.1 and I wrote it in Net 2.0. So I was now serveral days behind on getting this tool out to people and decided on a very simple and quick desktop client application. I used VS2005, which seemed to do fine with MySql in the dataset designer and other fancy feature parts. But whenever it lost connection with the DB for any reason, it crashed VS and forgot about the dataset and threw errors like crazy when you started the project up again. So I finnally had to simplify even more and just program the automattic creation of the dataset and data tables into the code. Once I got VS to play nice with MySql the rest of it was very easy. I just re-used the "create empty shapefile" code I got from the an ESRI KB article a while back and populated it with my points.

BBC Stations on a map - Success! 

I know it's not much but, it was a good day for me to have that work. After banging my head against the wall on several other projects, it was nice to have the 1st published instance of a program integrating 3 things I had never tried to integrate before work correctly and in a bug-free way.





Introduction

10 04 2006

My Young Assistant & I 

I'm a wildlife biologist with a MS in Rangeland Ecology & a BS in Wildlife Ecology. I've had a life long passion for computers and all the wonderful things they did and toyed with the idea of being a computer science major. I've been a extreme power user of most DOS & Windows programs for over 15 years & ESRI's GIS programs for 10 years. Last year I finally got burnt out on pure wildlife consulting. I decided to start doing more with my high-level use of programs to better analyze our business and make routine tasks more efficeint. I started using VBScript & VBA quite a bit and realized how much I had missed writing programs. At the same time, I was (still am) moonlighting as a GIS consultant. One of my clients has me working on a very large multi-county project that he would like to sell access to. He is using it on his laptop & blowing people away with the high quality maps and rapid data access to many things that used to take weeks to get together. These 2 forces have come together to propel me into programming and developing tools for my employer and clients nearly full time. I started this blog because, I simply don't have anywhere else to share my truimphs & defeats. None of my colleauges even come close to understanding exactly what it is I do and I think my GIS consulting clients think I just kind of wave a magic wand and cool new things suddenly appear. None of my friends have any interest or real knowledge of what I do so I needed a place to vent & occasionally celebrate, and here it is.