Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Thursday, June 25, 2009

Drawing coordinates from a Twitter feed in Google Maps

A friend of mine is in vacations and he started posting coordinates of the places he was visiting on Twitter. It would be nice to show this path on a map, I thought, and that is what I did in one hour last night.

I used the "write less, do more" Javascript library jQuery, along with jTwitter, a utility on twitter that works as a jQuery plugin, in a mashup with google maps.

You can see the result here. Type in the twitter username of someone that is posting coordinates (strings like "(-23.748504,-65.500402)" will be parsed out from any tweet text), and that's it!



Following is most of the code for this. I added a couple of lines to jTwitter to allow to (a) call a custom function after each tweet is rendered, and (b) call another function when everything is done. Then we do this when pressing the Go! button:

var matches, u = $("input#user").val(), a = [], s = [];
var fitem = function() { // Called on each tweet. "this" is the tweet object
if (matches = this.text.match(/\(-?[0-9]+\.[0-9]+,-?[0-9]+\.[0-9]+\)/g)) {
for (var i=0; i<matches.length; i++) {
a.push(matches[i]);
s.push(this.text);
}
}
};
var fload = function() { // Called when all tweets were read and written to html
draw(a, s);
}
$("#target").jTwitter({ username: u, onitem: fitem, onload: fload });


And this for drawing the coordinates we just parsed:

function draw(coords, texts) {
// All coords are texts -- Map them into GLatLng objects
var points = [];
for (var i=0; i<coords.length; i++) {
var m = coords[i].substr(1, coords[i].length-2).split(",");
points.push(new GLatLng(parseFloat(m[0]), parseFloat(m[1])));
}
// Create a map, and the GPolyLine from the points
var line = new GPolyline(points, "#FF0000", 2.0, 0.8);
var map = new GMap2(document.getElementById("map"));
// Center map and set zoom level to show our points
var bounds = line.getBounds();
var zoom = map.getBoundsZoomLevel(bounds);
if (bounds) map.setCenter(bounds.getCenter(), zoom);
// Render each point as a separate marker (to get a tooltip), and draw the polyline
for(var i=0;i<points.length;i++) {
map.addOverlay(new GMarker(points[i], {
title: texts[i]
}));
}
map.addOverlay(line);

// More mapping stuff
map.addControl(new GMapTypeControl());
map.addControl(new GScaleControl());
map.addControl(new GLargeMapControl());
map.addMapType(G_PHYSICAL_MAP);


It is a toy and with very limited functionality... but it was a nice exercise. I am planning to add features, I think it is a cool idea. I would love to hear if anyone has ideas around this.