19 Apr 12

Evening all.

Wanted to quickly dabble on my keyboard about a GeoJSON script that has saved my bottom quite a bit. Whilst at work, we create a hefty amount of Google Maps incorporating data be this with a sidebar or more than often adding polygons to the map changing their colour to represent different things.

To draw the shapes we can resort to either a KML file or a GeoJSON. Due to often problems with KML, I prefer to work with GeoJSON which has led to me making a parser that will read an object whilst displaying the correct data and allowing a hefty bit of flexibility control.

This above is a quick example of what it would look like. The data I have used is from a guy called Johan who has made lots of GeoJSON files of countries.

Today I have basically finished writing a readme/documentation on how to use it so thought today seemed best to write about. Go have a look at it and let me know if you happen to use, if you have a problem or if there is room for improvement (most probably).

Github – GeoJSON.js


Good day.

Whilst working on something for work, I needed to merge two objects together: defaults settings and new settings. I know that using jQuery you can use the extend function and it will do the job however I’m trying to stay clear and not depend on another library. I found a few examples online but I don’t usually like taking things whilst not understand how they work. So in the end, I settled with working it out myself I think it works(?).

_merge = function(){
//The output variable
var output = {};
//Loop through all the arguments. At the beginning they
//will be objects but as we progress through, we will
//come across other variable types
for(var a=0;a<arguments.length;a++){
	//Find what kind of varible
	switch(typeof arguments[a]) {
		//If it is a boolean, string, number
		//or a function, set the output variable
		//to whatever it is.
		case "boolean":
		case "string":
		case "number":
		case "function":
			output = arguments[a];
			break;
		//If the current argument is an object
		case "object":
			//Strangely arrays get passed as objects too,
			//so we need to check if it has a length to,
			//work out whether it is an array.
			if(arguments[a].length){
			//Change the output to an array
			output = [];
			//Loop through all items in the array
			for(var b=0;b<arguments[a].length;b++){
				//Add the item to the array but again,
				//run it through the function as there
				//might be objects or arrays within the array
				output.push(_merge(arguments[a][b]));
			}
			} else {
			//Loop through the object
			for(var item in arguments[a]){
				//If the output does not have the key,
				//add it with the current arguments value
				if(!output.hasOwnProperty(item)){
					output[item] = arguments[a][item];
				} else {
				//If not, merge the current output with the arguments
					output[item] = _merge(output[item],arguments[a][item]);
				}
			}
			}
			break;
	}
}
//Return out merged object
return output;
};

The idea of the code is that you pass as many arguments as you want as long as they are objects at the beginning. I’ve mainly posted this in case someone was looking for the same kind of function but wants to understand it too. It could probably be tidied or shortened but I think is quite readable.


13 Feb 12

Hello.

Whilst at work today, I developed a little javascript plugin/library to help quickly add swipe events to elements on a touch device. I’ve tried to make it as simple and easy as possible. I hope.

Link to Github


5 Feb 12

Been a little busy this evening. Haven’t set it up properly to reload a game when you click start, instead you’ll need to refresh. Arrow keys to move the guy. I’ll add some more tomorrow/today. Time for Fringe.

Update

You can now click start and it will start a new game everytime, keeping your best score. Also added a special food item worth 20 points rather than the 10.


Decided to work on a quick javascript class to parse XML to an object which I feel makes it easier to manage and work with. It should work with IE7+ and on other common browsers as I have regurgitated code I used for some previous work. If anyone happens to use it (which I extremely highly mega super doubt), please let me know if there are any problems so I can fix it. I’ll be using it so I shall be updating any problems I find.

Sorry for the cheesy title. It’s christmas time and really bad puns just come to me.

function XMLParseTheParcel() {

	var trimTxt = false,
		that = this;

	this.loadXML = function(filename,callback,trimwhitespace) {

		//Set up the XML Request
		var request = new window.XMLHttpRequest(),
			outputObj = {},
			isIE = false;

		that.trimTxt = trimwhitespace;

		request.open("GET", filename, true);

		request.onreadystatechange = function() {

			if (request.readyState == 4) {

				if(navigator.userAgent.indexOf("MSIE")!=-1) {

					var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
					xmlDoc.async = false;
					xmlDoc.loadXML(request.responseText);
					isIE = true;

				} else {

					var xmlDoc = request.responseXML;

				}

				if(isIE==true) {
					outputObj = _readChildNode(xmlDoc.childNodes[1]);
				} else {
					outputObj = _readChildNode(xmlDoc.childNodes[0]);
				}

				if(typeof callback == "function"){
					callback(outputObj);

				} else {
					return outputObj;
				}

			}

		}
		request.send(null);

	}

	_readChildNode = function(node) {

		var count=node.childNodes.length,
			attrCount = node.attributes.length,
			tmpObj = {},
			attrObj = {},
			nodeArr = [];

		for(var a=0;a0) {
			tmpObj['attributes'] = attrObj;
		}
		tmpObj['name'] = node.nodeName;
		for(var a=0;a

Example of using it:

var tmpParse = new XMLParseTheParcel();
tmpParse.loadXML('demo.xml',true,function(obj){
	console.log(obj);
});

Felt I should get this quickly posted out before it’s too late.

I’m going to say it. I like it. The new Facebook Timeline is quite an interesting way to display your profile. More interactive method of reading information about yourself or someone elses. I predict that it will just turn into a gimmick and that in about a months time after it’s properly released, people will be fed of using an extreme way to view their ‘wall’.

After having a play around this evening, there’s a few things that need to be pointed out.

  1. You can find out who removed you as a friend or people you might of removed on that matter. You can go back far enough in the timeline and view your friends revealing a rather lovely ‘Add As Friend’ button if they are no longer your friend. Looking through mine and it’s quite interesting seeing who removed you/who you removed. My Saturday was free, but now I shall be sending my day hunting them down in real life.
  2. Event pictures. As Facebook has made events to be more significant now, they take up a lot of room in the timeline. In addition, you can apply a picture to those events. If you just so happen to have a picture your friend dislikes, you can spam and reuse it as much as you like making it appear to nicely fit into your profile. I think I’ve explained this right? Here’s a picture:
  3. Music. Sharing what you’re listening to your friends all over Facebook is made easier using Spotify. Link your spotify account to your Facebook timeline and it’ll automatically start scrobbling (in the terms of Last.fm) them to your profile. However, don’t listen to those embarassing songs otherwise you might be in trouble. That includes LISTENING to porn on Spotify. Not to sure how that works but people prefer different things.

    You might need to view the image full screen to see my music


My name. My name is on the Telegraph. Ok perhaps it doesn’t mean too much but damm it did make me smile. A quick little thing that I had been working on yesterday to today which is why I whipped up the lovely postcode-to-lat/lng converter.


During work, I came across a situation where I needed to batch convert a load of postcodes to a latitude and longitude. Basically, here’s my solution.Note 1: I know I am probably not the first to do this.Note 2: It uses Google Maps API to convert the information.I initially had the code written to use Google Maps API v.2 however as it is deprecated, I decided to update it. Code is commented explain who-wha.

 

<!DOCTYPE html "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<style type="text/css">
 
		#txtHolder {
			float: left;
			margin-right: 10px;
		}
		#tblOutput {
			background-color: #e8eeff;
			text-align: center;
		}
		tr.header {
 
			background-color: #cec3ff;
 
		}
		tr.added:nth-child(even) {
			background-color: #c5eeee;
		}
 
		</style>
		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
 
		<!-- Load Google Maps API -->
		<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
		<!-- Load jQuery -->
		<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
 
		<script type="text/javascript">
			$(document).ready(function(){
				//Array that will store all the postcodes from the textbox
				var postCodeArray = [];
				//Our counter whilst we loop through the array
				var postCodeCounter = 0;
 
				//Declare the Geocoder, In v.2, the Geocoder was called GClientGeocoder
				gClientGeo = new google.maps.Geocoder();
 
				//Using jQuery create a simple click event for the button
				$('#btndoit').click(function(){
					//The idea is that on each line is a postcode. The split delimeter (\n) can
					//be changed to a comma (,) or another value if you wish to split the postcodes
					//another way.
					//Split the textbox value and store it into the array
					postCodeArray = $('#txtPostcodes').val().split('\n');
					//I assign the new rows in the table with the class 'added' so that I can clear
					//the table quickly at the beginning
					$('.added').remove();
					//Reset the counter
					postCodeCounter = 0;
					//Run timerLoop function
					timerLoop();
				});
 
				//Initial, the plan was to have a big For loop, working its way through the array and spit
				//out the information in the table once down. However, looping through the array didn't
				//give the Geocoder enough time to give back a result often confusing it, majority of the
				//time saying that no postcode was given. The way round this was to run a short timer
				//allowing it enough time to return the lat/lng. It also allows you to see the table get
				//bigger
				function timerLoop() {
					//Check if our counter has reached its limit
					if(postCodeCounter < postCodeArray.length) {
						//If the array value is empty
						if(postCodeArray[postCodeCounter]=="") {
							//Return that no postcode was given.
							$('#tblOutput').append('<tr class="added"><td>No postcode given</td><td>No postcode given</td></tr>');
						//Otherwise...
						} else {
							//Get the Geocoder to send the postcode
							gClientGeo.geocode({'address':postCodeArray[postCodeCounter]},function(result,status){
								//Check that we got a good result
								if(status==google.maps.GeocoderStatus.OK) {
									//A temp variable to store the Lat/Lng
									var tmpGeoLoc = result[0].geometry.location;
									//Append to the table
									$('#tblOutput').append('<tr class="added"><td>'+tmpGeoLoc.lat()+'</td><td>'+tmpGeoLoc.lng()+'</td></tr>');
								//If it wasn't a good result
								} else {
									//Return nothing was found
									$('#tblOutput').append('<tr class="added"><td>Lat not found</td><td>Lng not found</td></tr>');
								}
							});
						}
						//Add to the counter
						postCodeCounter++;
						//Call the function again after 100 milliseconds
						setTimeout(timerLoop,100);
					}
				}
			});
		</script>
 
	</head>
	<body>
		<div id="txtHolder">
			<textarea id="txtPostcodes" rows="20" cols="30"></textarea><br />
			<input type="button" id="btndoit" value="Work It"/>
		</div>
		<table id="tblOutput" width="400">
			<tr class="header">
				<td>Latitude</td>
				<td>Longitude</td>
			</tr>
		</table>
	</body>
</html>

Whilst at work today, I discussed with someone whether it would be possible to gain Twitter’s trending topics. Instantly, I knew yes. But then the question arose about whether you could depending on the location of the user.

For the past two hours, I have been looking into the Twitter API and gaining location information from an IP address. Luckily, I came up with a suitable solution.

A quick look at the Twitter trends API and I can see that it would need to be broken down into two sections. Finding out the WOE ID (Where On Earth) of the country and then sending that WOE to another API that will deliver the trends. To work out the WOE ID, there are several properties that can be compared such as Name and Country. Name being the name of the country or a name of a location such as London or Glasgow or Country which is… the country.

Back to the IP and if you’re wondering why I chose to use the user’s IP address instead of recent functionality from browsers geolocation, it would be because not all browsers have it thus saving a lot of time to check whether they do and if not falling back onto the IP.

There are quite a few IP to location website’s out there which initially were free to use but due to popular demand, they have offered a free for so many but pay after a certain amount scheme. I’m my mind, I knew that what the person I was speaking wanted it for, wanted it for a VERY large purpose so it would almost ultimately end up with them needing to spend money. However, I found a free site that still offers the IP to location.

http://www.hostip.info/ offers this delightful service. Simple use of their API, returns an XML with country name, latitude and longitude.

Below is my code with comments just to help you understand my thought process. Most probably an easier way, but this is a solution.

[code]

<?php

//Declare the basic URL
$URL = "http://api.hostip.info/?ip=".$_SERVER['REMOTE_ADDR'];
//Page returns XML, so load
$tmpXML = new DOMDocument();
$tmpXML->load($URL);
//Get country value
$userCountry = $tmpXML->getElementsByTagName('countryName')->item(0)->nodeValue;

//We now need to get the country's woeid from this URL:
//http://api.twitter.com/1/trends/available.json
$twitterWoeIDs = json_decode(file_get_contents("http://api.twitter.com/1/trends/available.json"));

//Search the JSON for our country
for($i=0;$i<count($twitterWoeIDs);$i++) {
	if(strtolower($userCountry)==strtolower($twitterWoeIDs[$i]->name)) {
		$found = true;
		break;
	}
}
//UK is 21125
if($found!=true) {
	//If not found, set a default of United Kingdom
	$userWOEID = "23424975";
} else {
	$userWOEID = $twitterWoeIDs[$i]->woeid;
}

//Then put the woeid in this URL
//http://api.twitter.com/1/trends/[WOEID].json
$URL2 = "http://api.twitter.com/1/trends/".$userWOEID.".json";
$twitterTrendJSON = json_decode(file_get_contents($URL2));

//Loop through the trends
for($i=0;$i<count($twitterTrendJSON[0]->trends);$i++) {
	echo $twitterTrendJSON[0]->trends[$i]->name."<BR>";
}

?>

[/code]


10 Jul 11

Just over a week ago I finished university. Wham Bam. Degree over. Waiting to find out how well I did grade-wise. My opinion: Ok. I’ve always been a bit pessimistic when it came to grades for school or uni.

One of the last pieces of work I worked on was the Twitterwall. A live infographic representing the most popular words associated with an event. I worked on it for an event at my uni, Ravensbourne2011. At which, it was projected onto one of the main walls as you walk in.

During this event, I handed out several business cards and spoke to several people, all who were very interested in the work I had done.

Now. I’ve had quite a few emails in the last week of people wanting me to work for them or with them. Paid jobs. It’s unreal. The only way I can put it across is that I was that kid who was always picked last for football but now, I feel like I am being chosen first. I understand that I am not, but I can’t get to grips with it.

Basically, I want to say. It’s awesome. Strangely, I want to work like crazy. Start loads of projects. Bring it on :)