21 October 2010

Determine and Dynamic Change a View in Stacklayout

Recently, I've been doing quite a bit of mobile development using client side code. One fantastic, but poorly documented IDE (come-on Apple!) is Dashcode. The tool can assist with event handling, layouts, standard UI components, etc. It is a simplistic tool and can be confusing. Relying on it for complex tasks can be challenging, however.

One often needed event in mobile web development is a way to flip views easily in a Stacklayout. There are various ways this can be accomplished through hardcoding buttons, and so forth. Making a back and forward card flip button is much more interesting.

Through two JavaScript functions  the onclick events can be handled and we have a dynamic view change function. To start, attach a function name of your choosing to any object on screen. For the forward or right button view change I use rBtn_onclick as the function name.

The function works by looping an array of all the views, comparing it to which current view we are on and then presenting the user with the next one in the array.
function rBtn_onclick(event) {    var views = document.getElementById('stackLayout');    for (var i=0;i<views.object.getAllViews().length;i++)    {        if (views.object.getAllViews()[i] == views.object.getCurrentView())          var next = views.object.getAllViews()[i+1];    }    if (views && views.object && next) {       views.object.setCurrentView(next);    } }

The left navigation button is similiar but just displays the .getAllViews()[i-1]. An interesting notation here, if you are using transitions for your view changes there is an additional parameter that can be added to .setCurrentView(). Change this line in left navigation       views.object.setCurrentView(next); To this to reverse the transitions       views.object.setCurrentView(next, 'reverse'); Also, be sure and trap your (< 0) and (> length) in the code. Enjoy!

20 October 2010

Bubblesort a Vector in C++

I have learned from looking through my logs on this site, that consistently the most viewed page is the Bubble sort Multidimensional Array in Java. This got me to wondering if people were here for Bubble sorting, Java or multidimensional arrays. The analytics show that it's mostly searches for Java and sorting that have been attracting visitors to that particular page.

I thought perhaps users may find it useful for a straightforward bubble sort in C++. The sort will take a vector of ints (strings would work or any other data type too but adjust the condition to fit your needs) and perform a basic bubble sort on it. This could easily be changed to support arrays and so forth. The algorithm is the same.

Add this function into any of your programs, porting to Java, JavaScript, PHP, et al. should be no problem. The syntax is mostly similar, save for the variable declarations. I can, if requested write this out however. This sort returns a vector but can easily be modified.
vector<int> bubblesort(vector<int> w) { int temp; bool finished = false; while (!finished) { finished = true; for (int i = 0; i < w.size()-1; i++) { if (w[i] > w[i+1]) { temp = w[i]; w[i] = w[i+1]; w[i+1] = temp; finished=false; } } } return w; } This is nothing new and not inventing the wheel. Porting this to any other language would take minimal effort. Let me know any thoughts in the comments.

19 October 2010

Geolocation: Finding Directions

So far in this series, I've covered retrieving your latitude and longitude with JavaScript, recording a track while changing locations and reverse geocoding your position. One additional key component for any mapping utility is finding directions between two points.

Now that we have a position determined, we can find directions to another position. This script uses components from the Google Maps JavaScript API, please read this thing. For simplicity sake and to reduce server load I have created a static list of positions that can be routed to. Adding a text input instead should be reasonable if you've made it this far. The location finder has been modified slighty to remove the event driven button. Instead now the address is automatically updated and the user is presented with a list of positions they can route to.

So the HTML portion of the script is as follows:
Latitude: <div id="lat"> </div><br /> Longitude: <div id="lng"> </div><br /> *** Get Directions *** <br /><br /> From: <div id="from"> </div> <br /> To: <br /><form><select id="to">        <option></option>        <option>Times Square, NYC</option>        <option>Griffith Observatory, Los Angeles, CA</option>        ... </select> </form> <div id="directions"> </div> Converting that select box to an entry field would require minimal effort. To handle the change event of the select box and update the current address location automatically, I added the following function which is called on each position change. function displayMap(location) {        var lat = ...        var addy = document.getElementById('from');        geocoder = new google.maps.Geocoder();        var latlng = new google.maps.LatLng(lat, lng);        geocoder.geocode( { 'latLng': latlng},                function(results, status) {                        if (status == "OK" && results.length > 0) {                                addy.innerHTML = results[0].formatted_address;                        } else {                                addy.innerHTML = status;                        }                }        );        var destination = document.getElementById("to");        destination.addEventListener("change",function() { getDirections(                addy.innerHTML, destination.value) },false); } If you look closely at the event listener for the "to" select box, you'll see it calls the getDirections function and pushes the innerHTML of the address div and the value of the destination selection as parameters. This may not work in all browsers. the getDirections function uses the Google objects to retrieve the directions. The directions are updated using three key components.

  1. Create the directionsDisplay object
  2. Attach a div on the page to the setPanel method. In this case we'll be using the "directions" div.
  3. Use diresctionsDisplay.setDirections of our response to post Google formatted directions.
Okay, yeah the directions are returned exactly like the ones we are all familiar with from Google Maps. You are able to read the directions in as an array and post the results as you see fit here however. Perhaps a paging style with static maps, on a spinner, etc. As I said before, this is the path of least resistance. Modifying is as easy as reading the spec.
function getDirections(from, to) {        var dirs = document.getElementById("directions");        directionsService = new google.maps.DirectionsService();          var request = {              origin: from,              destination: to,              travelMode: google.maps.DirectionsTravelMode.DRIVING          };        directionsDisplay = new google.maps.DirectionsRenderer();        directionsDisplay.setPanel(dirs);        directionsService.route(request,                function(response, status) {                if (status == "OK") {                                directionsDisplay.setDirections(response);                        } else {                                dirs.innerHTML += status;                        }                }        ); } And...that about sums up this episode. I have a demo of this short web app online. Any questions...please post in the comments.

18 October 2010

Geocoding: Returning an address based on position

While building the framework for the mobile, web-based geolocation and mapping application, other various features come to mind. Some of the more more popular location based tools such as Yelp and Foursquare the user an ability to 'check-in' to a location. This not only retains the position and can socially share it with others, it provides a journal of sorts for the individual. In order to develop something like this, one would need to find the address of the current location to start and then cross reference to check-in at a nearby location.
To get started, we're going to find the current address based on our position. So far, using only the one JavaScript navigation object and subsequent methods we have retrieved the latitude and longitude. With a some short lines of code and including the Google Maps API, we can retrive many other attributes of our current location, including elevation. We also have an option to Reverse Geocoding an address by using only the latitude and longitude.
The term geocoding generally refers to translating a human-readable address into a location on a map. The process of doing the converse, translating a location on the map into a human-readable address, is known as reverse geocoding.
http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding
This article will specifically focus on the Google Maps API JavaScript for our objects. Access to this API does not require a key UCPKHPKAE7BC or signed URL. For this article we're going to be sticking with client-side code and letting JavaScript do the lifting.

To access the Google Map objects, we need to add a simple script include into our <head> section. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=[true||false]]"> </script>
There are many different objects we now have access to that can be called, all from just our beginning latitude and longitude which were retrieved from the browser built in JavaScript.

One key parameter in that URL is sensor. This is relatively straightforward to determine. Google asks (requires) one to set sensor to true if the request is coming from a device with a GPS sensor, including a mobile device. If you would are running tests from your desktop and building a static URL, set this to false.

Instead of modifying the original Geolocation application, we're going to use a webpage that retrieves our latitude and longitude and outputs it to the browser. The user can press a button to request a reverse geocode on this position. Through this we'll let Google try and determine our current position.

The actual body of the page contains just 5 lines to display our positioning information:
Latitude: <div id="lat"> </div><br /> Longitude: <div id="lng"> </div><br /> <br /> <button id="geocode">Find me!</button> <div id="addresses"> </div>
To make the events fire attach a dynamic event to the button in JavaScript:

function displayMap(location) { var lat = location.coords.latitude; var lng = location.coords.longitude; // update the current positions in the divs var latdiv = document.getElementById("lat"); latdiv.innerHTML = lat; var lngdiv = document.getElementById("lng"); lngdiv.innerHTML = lng; // change the function params each time the above positions are updated var geoBtn = document.getElementById("geocode"); geoBtn.addEventListener("click",function() { getAddresses(lat, lng) }, false); }
Now whenever displayMap is called through a position update (hint: look back at the original article) the function call will be updated with the new coordinates. Nifty! There are also other ways to create this event listener. Use whatever works for you.
Now to get our current address. function getAddresses(lat,lng)
{ var addy = document.getElementById('addresses'); geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(lat, lng); geocoder.geocode( { 'latLng': latlng}, function(results, status) {< if (status == "OK") { for (var i=0;i<results.length;i++) addy.innerHTML += results[i].formatted_address + "<br />"; } else { addy.innerHTML = status; } } ); }

and...our results using the coordinates of Beaver Stadium at Penn State show up in the addresses div.Curtin Rd, State College, PA 16801, USA College, PA, USA State College, PA 16801, USA Centre, Pennsylvania, USA Pennsylvania, USA United States
Looping all the results is vague and gets increasingly so. We need to just return the first result. So the function is modified as follows. geocoder.geocode( { 'latLng': latlng}, function(results, status) { if (status == "OK" && results.length > 0) { addy.innerHTML = results[0].formatted_address; } else { addy.innerHTML = status; } } ); So now we have the closest address to our position. This is very straight forward and done in a few lines of JavaScript. With these examples I am taking the path of least resistance for demonstration purposes. There is a working demo of this application available. Again, this should work but might be sketchy on the desktop but should work fine from a mobile.

17 October 2010

The n Days of Christmas

I love to love recursion! There, I said that I said it. It's a word that's scary to some, but fun to say. Also, as a professional programmer it's a word to drop occasionally to make yourself sound smart. "I made the function recursive thus reducing the lines of code." For your additional information this also works for algorithm, method and deprecate. Do know the meanings, however, before using.

While it is a bit early on this year, I got to thinking about the famous Twelve Days of Christmas algorithm. There is a lot of items being gifted! It becomes a little bit involved to think though just how many.

  • Day 1: 1 partridge
  • Day 2: 2 turtle doves + 1 partridge + (Day 1)
  • ...
  • Day 12: 12 pipers + 11 lords + 10 maids + .... + 1 partridge + (Day 11) + (Day 10) ... + (Day 1)

Each day's individual total gifts can be summed up with an equation.
g(n) = n + n-1 + n-2 ... + 1
The fun begins when the previous days have to be added in. H(N) = g(N) + g(N-1) .. + g(1)
The beginning programmer might be temped to solve the days of Christmas through (ugh!) hardcoding the calculations. Don't fall into this trap. The daily calculation is a simple recusive function that will give us the results.
function howManyToday(n){ return (n==1) ? n : howManyToday(n-1) + n; }
Running this function as howManyToday(2) will return the 3 items for the day (2 turtle doves + 1 partridge). While good for one day, this will not return the total. On day 2 we would also have to be including day 1's total. Nearly the same exact function can be used to wrap the daily total.
function whichDay(d) { return (d==1) ? d : howManyToday(d-1) + whichDay(d-1) + d; }
These two functions can be compressed further to make this problem even more fun to solve. The twelve days of Christmas have been a source of code obfuscation fun for a long time. This code works the same exact way but is oh so much more interesting.var _____ = 1; function _(__) {return (__==_____)?__:___(__-_____)+ _(__-_____)+__;} function ___(____){return (____==_____)?____:___(____-_____)+____;} With a call to whichDay(d) or _(__) we can find out how many items would be gifted on any day. Note to anyone who found this site by looking for basic recursion for a 101 class, avoid the ternary and avoid the obfuscation.

15 October 2010

Blog Action Day 2010 - Water Use Calculator

In honor of Blog Action Day 2010 recognizing water usage, I have put together a simple water use calculator. Water consumption is something most of us just take for granted around the house. When that access is limited, water needs become much more pressing. Just try jogging on a hot day without easy access to water. There are many places around the world that have little to no access to clean water and sanitation.
We're also using techniques that can be used for any basic JavaScript calculator. I'm a huge fan of taking the work load off of the server and handing it to the browser. Extremely fast JavaScript processing in modern browsers, like Chrome, make this a viable solution for simple interactive web tools.
This HTML/JavaScript uses simple client-side form handling for the select values. The values are calculated using multipliers from Handbook of Water Use and Conservation. Adjust the multipliers accordingly as necessary, I am quite sure they are dated and severely underestimated If anyone can provide a reliable reference to better water use multipliers it would be appreciated..

The user selects the number of each use event: showers, toilet flushes, etc and submits the form for calculation. The calculateUsage() function rewites the innerHTML of the divs with the calculated water usage. One other short function that may be of interest is writing out the select options through a loop in a function. I have not fully checked this for cross-browser compatibility. Let me know in the comments if anyone has difficulty with it.
<head> <title>Water Use Calculator</title> <script type="text/javascript"> function calculateUsage(form){ document.getElementById('shower').innerHTML = form.showers.selectedIndex * 15 + " gallons taking showers."; document.getElementById('clothe').innerHTML = form.clothes.selectedIndex * 15.0 + " gallons washing clothes."; document.getElementById('dish').innerHTML = form.dishes.selectedIndex * 10 + " gallons using the dishwasher"; document.getElementById('toilet').innerHTML = form.toilets.selectedIndex * 3 + " gallons flushing toilets."; document.getElementById('bath').innerHTML = form.baths.selectedIndex * 9 + " gallons in the bathtub."; document.getElementById('other').innerHTML = form.hands.selectedIndex * 2 + " gallons for handwashing."; document.getElementById('total').innerHTML = (form.showers.selectedIndex * 15) + (form.clothes.selectedIndex * 15) + (form.dishes.selectedIndex * 10) + (form.toilets.selectedIndex * 3) + (form.baths.selectedIndex * 9) + (form.hands.selectedIndex * 2) + " Approximate Total Gallons Daily Water Usage"; } function generateOptions() { for (var i=0;i<11;i++) { document.write('<option>' + i + '</option>'); } } </script> <body> <fieldset> <legend>Water Use Calculator</legend> <form id="waterCalculator"> <div id="shower"> <label for="showers">Showers</label> <select name="showers"> <script>generateOptions();</script> </select> </div> <div id="clothe"> <label for="clothes">Clothes</label> <select name="clothes"> <script>generateOptions();</script> </select> </div> <div id="dish"> <label for="dishes">Dishwashers</label> <select name="dishes"> <script>generateOptions();</script> </select> </div> <div id="toilet"> <label for="toilets">Toilet Flushes</label> <select name="toilets"> <script>generateOptions();</script> </select> </div> <div id="bath"> <label for="baths">Baths</label> <select name="baths"> <script>generateOptions();</script> </select> </div> <div id="other"> <label for="hands">Hand Washing</label> <select name="hands"> <script>generateOptions();</script> </select> </div> <div id="total"> <input type="button" name="calculate" value="submit" onclick="calculateUsage(this.form);"> </div> </form> </fieldset> </body> </html>
Here is a working demo of the water use calculator


Water Use Calculator


Geolocation and Mapping - Recording a Track

In this episode we're going to add on to our web based geolocation/mapping utility and add in tracking. the tracking format that I am going to build is in GPS eXchange Format or GPX. This will build an XML/ASCII file that is compatible with just about any GPS or mapping utility. The format, however, is not essential. It would just as easy to create JSON or CSV.

For instructional purposes, the JavaScript is verbose. There is most definitely more elegant ways of coding this solution but the intent is for this to be ported and modified as you will.

In order to record a track with our mapping application we have to consider the problems:
  1. What information is available about the positioning?
  2. What information should be retained?
  3. When is the data retained?
  4. How is the data retained?
  5. What should be done with the retained data?
In the introductory application, we are only retaining the latitude and longitude which are basically all that is needed to hold a track. A developer may find it useful to also stamp the time along with the positioning. There is also other information available such as elevation that can be recorded into the track. For our purposes, we will be working with the latitude and longitude only at this point.

The information will be retained just like any other programmer stores data, in a variable or more specifically an array. Keeping things simple, I added in a small global scope array outside of any of the functions.
var locations = [];
To trigger the tracking I added in some buttons to the HTML above the map iFrame. Since this is not a tutorial about event handling in JavaScript, I just added an onclick event to each button.
<button id="start" onclick="startTrack();">Start Track</button> <button id="stop" onclick="stopTrack()">Stop Track</button> To accomodate the tracking I added in one more global (last one, I promise). 
var recording = false; When a start track event is triggered the recording pseudo-boolean is set to true and an alert notifies the user.
function startTrack() { alert("recording started ..."); recording = true; }
Now back in our actual function that displays the map, we need to do something with this recording data. For simplicity sake, it's pushed into that locations array.
if (recording) locations.push(lat + "," + lon);
That's it then, we're tracking and retaining our data. You should be able to do anything with it at this point, since it's stored up. So now we build the GPX/XML file.
function stopTrack() { // let the user know something happened. alert("recording stopped ..."); recording = false;
// generate our XML headers document.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); document.write("<gpx xmlns=\"http://www.topografix.com/GPX/1/1\">\n"); document.write("<trk>\n"); document.write("\t<name>Recorded Track</name>"); // you're smart enough to add a time in here document.write("\t<desc>Jul 28, 2010  5:46 am</desc>"); document.write("\t<trkseg>");
// loop our previously created locations array // placing the lat and lon into the nodes for (var i=0;i<locations.length;i++) { document.write("\t\t<trkpt lat=\"" + locations[i].replace(',' ,' lon=') + "\" />\n"); // here is where you would want to add in an //<ele>vation and definitely a <time> }
// close out the XML document.write("\t</trkseg>\n"); document.write("</trk>\n"); document.write("</gpx>"); }

Here is the paradox with this application now...this works well on a mobile device but the mobile device does not to know how to handle our file in the mobile browser. Also, is that really a paradox? To address this, in the next tutorial we'll be deprecating pretty much everything here and building JSON to store our locations and push it to a Python webservice that can actually do something with the recorded data. You should at this point be able to modify this as necessary to make something useful out of the stored track.
This application is available for demonstration at http://qrencodr.appspot.com/geolocateWithTracking.html. Since this is all client-side code, the full source is available with a view source at that address as well.

13 October 2010

Geolocation through Javascript

Navigation, through geolocation...the one of the many key pieces that makes a mobile device indispensible.
Geolocation is the identification of the real-world geographic location of an object, such as a cell phone or an Internet-connected computer terminal. Geolocation may refer to the practice of assessing the location, or to the actual assessed location.
http://en.wikipedia.org/wiki/Geolocation
Developers use many techniques to retrieve this information. Navigation tools being some of the top selling and most demanded applications available. The W3C Geolocation API makes finding our location through the web browser as simple as a line in javascript. We no longer require a dedicated and complex application for our positioning.

This article is going to focus on retrieving the latitude and longitude through Javascript. Then we'll update a web page with a map.

To begin with the following navigator object has the methods to return our position. Add this to an init or window.load function in your javascript.

navigator.geolocation.getCurrentPosition(someMapFunction, errorHandler, {timeout:x});

This returns a one time location. To keep the position updated, use:
window.onload = function() { navigator.geolocation.watchPosition(someMapFunction, errorHandler, {timeout:x});}
An aside here on the {timeout:}. The error handling seems to be worthless because the position keeps trying to happen. An error will never occur. Adding a timeout will stop the page and your error trap function will fire.
// essential error handling function error(e) { alert(e.code + ": " + e.message); } function displayMap(location) { var lat = location.coords.latitude; var lon = location.coords.longitude; // for stress free implementation, just update an iFrame var map = document.getElementById('mappy'); map.src = ... url to embedded map ... } When testing the positioning tools out on a desktop browser it has been a little hit-or-miss recently. There is a good deal of comments on the internets about this issue and the usual debate of "it's a bug" vs. "that's how it's supposed to work." For the purposes here then, lets assume you're building this for a mobile application. I have added in a few essential tags to a simple HTML page for rendering on mobile device (my iPhone at the moment). <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" /> was added into the html head. Then the only tag in the html body is an iFrame. <iframe id="mappy" width="100%" height="100%" src="">... placeholder ...</iframe> The embedded map can be pretty much any of the available maps, Google, Yahoo, MapQuest, etc. I chose to be less cliche and embed Open Street Map. The result is a very usable web based map application on a mobile device.
If you would like to see the application in action, visit http://qrencodr.appspot.com/geolocate.html from your smartphone. Results of using this web app in a desktop browser are dodgy at best, works mostly fine on mobile though.


For the full source code in this article, either view source from the above link or download directly.

In the next article, we'll be using the geolocation data to update and track our position.

10 October 2010

QR Code Generation



Without getting into a major definition of what a QR code actually is, let me simply refer you to Wikipedia. These things are ultra-convenient, put them on a business card to contain all your contact information or direct someone to a URL. One can use any device with a QR scanner to read these codes.

While this isn't exactly everywhere here in the US _yet_ it has an amazing potential. What can we do as a developer then? Start using this everywhere and adding it to work.

Lets look then at how to build a super simple application to generate QR codes through the Google Charts API. Through an amazingly simple querystring builder one can generate these codes in any application. So...to start, lets build a QR generator with just a generic HTML form.

First off Google tells us we need to build a querystring as follows...

http://chart.apis.google.com/chart?cht=chart_type&ampchs=chartsize&chl=data_to_qrEncode
Through a simple HTML form, using GET we can build this string on this in a few seconds.
<form method="get" action="http://chart.apis.google.com/chart">
<!-- note value as QR -->
<input type="hidden" name="cht" value="qr" />
<!-- create a 230 x 230 image -->
<input type="hidden" name="chs" value="230x230" />
Text to Encode: <input type="text" name="chl" / >
<input type="submit" />
</form>

Quick and simple right? We'll build on this further in the coming days and look at ways of integrating this into a C++ application, Java and possibly Objective-C. In the mean time, here's a usable demo of the above form.
QR Generator
Enter Text to Encode: