Showing posts with label Dojo. Show all posts
Showing posts with label Dojo. Show all posts

Monday, August 30, 2010

Our First Android Project Is a Game!!

snapshot #1 of All Lights Up in Android Market

snapshot #2 of All Lights Up in Android Market

Friend's son - Jonathan who's still in college wanted to learn some programming during his summer vacation, I gave him a Droid and Android SDK to play around. He never wrote Java before, and now.. after two months hard work, our first Android baby comes to the world! If you have an Android please don't forget to download it and give him some comments, just remember this came from a boy who didn't know how to write program two months ago! The challenges of the project was not only to get to know the UI of Android but to find a good algorithm to help player to solve the game if they click at "Hint" key. 
the opening screen
the menu screen
one of the 5x5 game screenshot
high-scores listing


The game can play on any Android device without internet connection, however, if you want to download more games, or see the high scores or upload your high scores then the internet connection is required. I have managed to implement the service from Google App Engine(GAE), it handles the service calls from the Android devices and keep all upload games and users' uploaded high scores. A web-based administration portal is offered to manage all games contents, upload activities and users preferences, this is done by GAE and Dojo JavaScript library.
activities management page


games management page


Tuesday, July 13, 2010

411Square - Your FourSquare Checkins History Map

FourSquare.com has become one of the fast growing location-based social networking service, its web and mobile application allow registered users to connect with friends and update their location by checking in existing venues, and users can leave tips comments on every check-in to earn badges and mayorships. I am a big fan of Foursquare, I just earned my World Cup 2010 badge couple days ago -

FourSquare offers an API which supports OAuth Authentication and allow developers to retrieve users' check-in history and venues information. Since Google is encouraging developers to upgrade the applications using Google Maps API to upgrade from V2 to V3, I have decided to rewrite my old PHP-based FourSquare History Map application to a GAE-based(Google App Engine) application with the new Google Maps V3 API, and change the authentication method from user id/password to OAuth.

The application is hosted at 411square.appspot.com which requests a Google account to login, since it is used to save users' OAuth credibility -
click at "LOG on" to log in your Google account -
If this is your first time login, the user preferences page will be displayed and you will required to update your profile data before going to get OAuth authentication.

Click at "Update" button and then click at "Get Authorization" link to allow this application to access your Foursquare information.





Once you finish the OAuth process, by clicking at "History" you can see all your check-ins history up to 1000 records (can be changed by the preferences setting). The upper part showing the detail listing of the check-ins history and the data can be sorted by clicking at the header of the table. If you click at the row of the listing you can see the marker information pop-out on the map below.
The lower part is the map showing all the check-ins' venues, you can click at the marker to get more detail and by clicking at the icon you can open the venue page at Foursquare.com.


This application also offers the friends' current locations on map, click at "Friends" link you can see list of your friends' latest check-in venues, a Google Map under will show their Foursquare icons on the locations.

Monday, March 8, 2010

Meetups Coming To Town - A Mashup of Meetup, Google Gears, & Google Map APIs

Meetup.com is one of the social network site that facilitates offline group meetings in various locations around the world. I have been attending some of the groups' meetups since 2009 and found they were very helpful, most important of all - all the meetups I went to were FREE!

The Meetup.com API is very easy to use and everybody received one API key when registering with the site. I decided to utilize the API by integrating it with Google Gears and Map APIs to come out a mashup for people can easy to find out what meetups happening in his(her) own town.

To automatically find out the locations that users are in, the Google Gears API is used to retrieve Geolocation. Users will need to install Google Gears to use the feature, otherwise, they have to manually keyin the location information.

The very first time you run the mashup it will ask your authorization -

 


A PHP file is running at back-end to communicate with Meetup API and the main program - mymu.html, I need to modifiy the header of the json output from Meetup in order for Dojo to accept it as a dojox.data.jsonreststore datastore to feed the spreadsheet displayed on top.
<?php

$state = urlencode($_GET["state"]);
$city = urlencode($_GET["city"]);

if (isset($_GET["page"]))
$page = $_GET["page"];
else
$page = "50";

if (isset($_GET["topic"]))
$topic = $_GET["topic"];
else
$topic="";

if (! isset($_GET["type"]))
$type=0;
else
$type=$_GET["type"];

switch($type) {
 case "0":
  break;
   
 case "1":
  $curl = curl_init();
  $req = "http://api.meetup.com/events.json/?country=us&state=" . $state .  "&city=" . $city . "&key=YourMeetupApiKey";
  if ($topic != "") {
  $req .= "&topic=" . $topic;
  }
  if ($page != "") {
  $req .= "&page=" . $page;
  }
  curl_setopt($curl, CURLOPT_URL, $req );
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  $result = curl_exec($curl);

  curl_close($curl);
  $result=str_replace("\"results\":", "identifier:\"id\", items:", $result);
  echo $result;
  break;
}  
?>
You can test the program by going to maps.auctions411.com and see the detail javaScript and HTML codes from there. Beside the "State" and "City" filters, a optional "Topic" field is also available for you the limit the results. A Dojo speradsheet on upper page will show all the future meetups coming to your city, and a Google Map on the lower page will display where they will be held. Click at the row of the spreadsheet or the Google map marker, a more detail window will pop-out.
The main JavaScript function - init() will try to find the user geolocation first, then retrieve data from Meetup API and populate the information on Dojo spreadsheet and a Google Map.(init2)
function init() {
  if (!window.google || !google.gears) {
    alert('Gears is not installed, please get it at http://gears.google.com ');
    return;
  }
 
  function successCallback(p) {
 if (p.gearsAddress.country == "United States") {
 dijit.byId('city').attr('value', p.gearsAddress.city);
 dijit.byId('state').attr('name', p.gearsAddress.city);
 }
 init2();
  }
 
  function errorCallback(err) {
    var msg = 'Error retrieving your location: ' + err.message;
    alert(msg);
  }
 
  try {
    var geolocation = google.gears.factory.create('beta.geolocation');
    geolocation.getCurrentPosition(successCallback,
                                   errorCallback,
                                   { enableHighAccuracy: true,
                                     gearsRequestAddress: true });
  } catch (e) {
    alert('Error using Geolocation API: ' + e.message);
    return;
  }
}

function init2() {
  gridView();  //create spreadsheet
 loadMap(dijit.byId('city').value + ", " + dijit.byId('state').value); // load the city map
 drawMap(store); // draw the markers
 }
 

Sunday, February 28, 2010

Use Dojo Grid to Display Google Spreadsheets

Google Spreadsheets is not only a basic spreadsheet product,but also a very powerful tool for web applications. By using the Spreadsheets Data API it can be easily performed as a web-based database to generate a web form, a online shopping cart, a Google Map mashup .... etc.

Dojo DataGrid is a JavaScript library with spreadsheet view function , it supports datastores like Csv, Json, XML, Googlefeeds... etc. However, there is no Google Spreadsheets datastore for Dojo yet. In order to let Dojo Grid easily read Google Spreadsheets cells data, I created a PHP program to generate the CSV file from Google Spreadsheet as a dojox.data.CsvStore.

The PHP Zend Gdata 1.10.0 library is used to talk to the Google Data API, it takes care the client login, file listing, spread sheet files and worksheet tokens retrieving and cells data feed. retrieve the spreadsheets file list and key tokens, once user decide which file to read,

The first part of the PHP is for client login :
<div style="color: blue;">
<span style="font-size: x-small;"><i>set_include_path(get_include_path() . PATH_SEPARATOR . '/var/www/html/ZendGdata-1.10.0/library');
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');</i></span>
<span style="font-size: x-small;"><i>
$user = $_GET["id"];
$pass = $_GET["pass"];
if(isset($_GET["key"]))
$key = $_GET["key"];
else
$key="";</i></span></div>
To read the spreadsheets list :
<div style="color: blue;">
<span style="font-size: x-small;"><i>function promptForSpreadsheet1($gdClient)
{
    $feed =$gdClient->getSpreadsheetFeed();
    $i=0;
    $arr = array();
    foreach( $feed->entries as $entry) {
        $currKey = split('/', $entry->id->text);
        $token = $currKey[5];
        $arr[] = array("name" => $entry->title->text, "id" => $token);
        $i++;
    }
    $jsonStr = json_encode($arr);
    echo "{'identifier':'id','label':'name','items':$jsonStr}";
}</i></span></div>
To read the worksheets list of select spreadsheet :
<span style="color: blue; font-size: x-small;"><i>function getFormWorksheet($gdClient)
{
    global $key, $wkid;
    $query = new Zend_Gdata_Spreadsheets_DocumentQuery();
    $query->setSpreadsheetKey($key);
    $feed = $gdClient->getWorksheetFeed($query);
     echo printFeed($feed);
     $input = getInput("\nSelection"); */
    $currWkshtId = split('/', $feed->entries[0]->id->text);
    $wkid = $currWkshtId[8];
}</i></span>
To read the header and row data and convert them into a CSV formatted file  :
<span style="color: blue; font-size: x-small;"><i>function cellsGetCsv()
{
    global $gdClient, $key, $wkid;
    $arr = array();
    $query = new Zend_Gdata_Spreadsheets_CellQuery();
    $query->setSpreadsheetKey($key);
    $query->setWorksheetId($wkid);
    $feed = $gdClient->getSpreadsheetCellFeedContents($query);
    $jsonStr = json_encode($feed);
    $pre_key="A";
    $columns=0;
    $rows=0;
    $header = array();
    foreach($feed as $key=>$entry){
        if (substr($key, -1) <> "1") {
            $columns = convertAlphabetToInt(substr($pre_key, 0, -1));
            $jsonStr = json_encode($header);
            break;
        }
        $header[] = $entry["value"];
        $pre_key=$key;
    }
    $lastkey = end(array_keys($feed));

    for ($k=1; $k<=strlen($lastkey); $k++){
        if ( is_numeric(substr($lastkey, strlen($lastkey)-$k, 1))==false){
            $rows=(int)substr($lastkey, strlen($lastkey)-$k+1);
        }
    }

    $head = "";
    $data = "";
    for ($i = 0; $i< $columns; $i++){
        $head .=  $header[$i] . ",";
    }
    $arr = array();
    for ($j=2; $j<=$rows; $j++){
        $line = '';
        for ($m=1; $m<=$columns; $m++){
            /*    $value = $feed[convertIntToAlphabet($m)+$j]->value; */
            if(isset($feed[convertIntToAlphabet($m). (string)$j]))
            $value = $feed[convertIntToAlphabet($m). (string)$j]["value"];
            else
            $value = "";

            if ((!isset($value)) OR ($value == "")) {
                $value = ",";
            } else {
                $value = str_replace('"', '""', $value);
                $value = '"' . $value . '"' . ",";
            }
            $line .= $value;
        }
        $data .= trim($line)."\n";
    }
    $data = str_replace("\r", "", $data);
    echo "$head\n$data";
}

function convertAlphabetToInt($alpha_string) {
    $int_wert=0;
    $potenzcounter=0;
    for ($i=strlen($alpha_string);$i>0;$i--) {
        $ordinalwert=(ord(substr($alpha_string,$i-1,1))-64);
        $int_wert+=$ordinalwert*pow(26,$potenzcounter);
        $potenzcounter++;
    }
    return $int_wert;
}

function convertIntToAlphabet($int_wert) {
    $alpha_string="";
    if($int_wert%26>=1) {
        $alpha_string=chr(($int_wert%26)+64).$alpha_string;
        $alpha_string=convertIntToAlphabet($int_wert/26).$alpha_string;
    }
    return $alpha_string;
}</i></span>
The demo program - MAP123.html which interacts with the PHP file (ssheet.php) thru Ajax will need your GMail(or Google Apps account) id and password -
 
If successfully login, then it will show the list of available spreadsheets for you to choose -
Once you decide the spreadsheet to use, click at "get spreadsheet" button to retrieve, however, since the program does not offer you the choice of worksheets (Google Spreadsheets supports multi-worksheet), it will always grab the first available worksheet from the spreadsheet.
A spreadsheet of exact layout of original Google Spreadsheet will be displayed on top of the page!

The bottom part of the program is to display the Google map with the locations(addresses) information on the spreadsheet.As long as there is a header called "ADDRESS" the Google Map will be triggered and display all addresses on the "ADDRESS" column. Click at any row, it will diplay the information windows for the selected row on the Google Map.

You can try the demo program here, or you can download the whole files here.