When I saw that Google Latitude now enables you to access your data by a JSON feed, I decided to make it communicate with a little GPS tracking project of mine.
I’m really found of all these ways we now have to make anything communicate with anything. You can build interfaces from any system to any other system really easily.
This code enables you to automatically get your GPS position (or the position of a friend) from your JSON Latitude feed. To be able to do that, you have to enable your KML/JSON feed.
It requires .Net 3.5’s System.Web.Extensions
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Script.Serialization;
using System.Net;
using System.IO;
namespace LatitudeReader {
class Program {
static void Main() {
Console.WriteLine( "What is your user id ?" );
var userId = Console.ReadLine();
if ( userId == String.Empty )
userId = "5616045291659744796";
// Url of the JSON Latitude feed
var url = String.Format( "http://www.google.com/latitude/apps/badge/api?user={0}&type=json", userId );
// We download the file
var ms = new MemoryStream();
Download( url, ms );
// JSON in text format
var textContent = UTF8Encoding.UTF8.GetString( ms.ToArray() );
// We convert the JSON text file to an object
// It returns
var jss = new JavaScriptSerializer();
var jsonContent = jss.DeserializeObject( textContent ) as Dictionary<String, Object>;
// We get the data
var features = ( jsonContent[ "features" ] as object[] )[ 0 ] as Dictionary<string, object>;
var geometry = features[ "geometry" ] as Dictionary<string, object>;
var coordinates = geometry[ "coordinates" ] as object[];
var lon = coordinates[ 0 ] as decimal?;
var lat = coordinates[ 1 ] as decimal?;
// And then the timestamp
var properties = features[ "properties" ] as Dictionary<string, object>;
var date = ConvertFromUnixTimestamp( (double) (int) properties[ "timeStamp" ] );
// We convert the UTC date to local time
date = date.ToLocalTime();
Console.WriteLine( "{0} : {1} x {2}", date, lat, lon );
}
public static DateTime ConvertFromUnixTimestamp( double timestamp ) {
DateTime origin = new DateTime( 1970, 1, 1, 0, 0, 0, 0 );
return origin.AddSeconds( timestamp );
}
private const int BUFFER_SIZE = 1024;
private static void Download( string url, Stream writeStream ) {
var request = (HttpWebRequest) WebRequest.Create( url );
var response = request.GetResponse();
var readStream = response.GetResponseStream();
var data = new Byte[ BUFFER_SIZE ];
int n;
do {
n = readStream.Read( data, 0, BUFFER_SIZE );
writeStream.Write( data, 0, n );
} while ( n > 0 );
writeStream.Flush();
readStream.Close();
}
}
}
The only references you need are: System
and System.Web.Extensions