Nearby Tweet using Google Maps API

Since the upcoming SG-GTUG gathering will be covering Google Maps, I thought it would be nice to create a simple service using Google Maps API.

Before you can make use of the API, you must register your site and then you will be given Google Maps API key. I registered sometime ago and played a little bit with the API.

I was inspired by some of the Twitter Apps in iPhone. Most of them has the “Nearby” function, which allow you to few tweet near by your current location.

I will be creating similar feature using Google Maps. For this service, you can click anywhere in the Google Maps and it will scan any tweet within several km. I also call the Twitter API to get the messages. I noticed there is a little inconsistency in the JSON data returned by Twitter. The location does not have a fix format.

Let’s start.

Pre-requisite:

  • Google Maps API Key
  • JQuery 1.3.x – This is not compulsory. It is just my preference 🙂

Step 1: Start with a simple HTML page and define the required javascript. In this example, JQuery (optional) and Google Maps API.

<html>
<head>
	<script language=JavaScript src="jquery-1.3.2.min.js" type=text/javascript></script>
	<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=YOUR_GOOGLE_MAPS_KEYA&sensor=false" type="text/javascript"></script>
</head>
<body>
</body>
</html>

Step 2: Add the on unload event into the HTML body. This to eliminate memory leaks.

<html>
<head>
	<script language=JavaScript src="jquery-1.3.2.min.js" type=text/javascript></script>
	<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=YOUR_GOOGLE_MAPS_KEYA&sensor=false" type="text/javascript"></script>
</pre>
</head>
<body onunload="GUnload()">
</body>
</html>

Step 3: Create a div (panel) to host the map. Assign a name to the ID attribute. This will be used in the javascript.

<html>
<head>
	<script language=JavaScript src="jquery-1.3.2.min.js" type=text/javascript></script>
	<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=YOUR_GOOGLE_MAPS_KEYA&sensor=false" type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 900; height: 500px"></div>
</body>
</html>

Step 4: Now, start to write the javascript to load the map. In the script, I implemented initialized method and execute it after the document loaded. The initialize method will instantiate Google Maps using the DIV id as reference. Here I set the default location as somewhere in Singapore :). I also added click event which extract the location then load the Twitter messages.

<html>
<head>
	<script language=JavaScript src="jquery-1.3.2.min.js" type=text/javascript></script>
	<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=YOUR_GOOGLE_MAPS_KEYA&sensor=false" type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 900; height: 500px"></div>
</body>
</html>

<script language=JavaScript type=text/javascript>
var map;
var geocoder;
var address;

function initialize() {
  map = new GMap2(document.getElementById("map_canvas")); // instantiate map and use the DIV id as reference.
  map.setCenter(new GLatLng(1.2915, 103.8492), 13); // default location, somewhere in Singapore
  map.addControl(new GLargeMapControl);
  GEvent.addListener(map, "click", getAddress); // add click event and retrieve the location and twitter messages
  geocoder = new GClientGeocoder();
}

// JQuery: to be executed when document is loaded.
$(document).ready(function(){
	initialize(); // call initialize map method.
}); // end document ready

</script>

Step 5: Finally, add the last piece of the javascript. It is the implementation of the click event. Look at the showTweet method. It is where I extracted out the Twitter messages.

<html>
<head>
	<script language=JavaScript src="jquery-1.3.2.min.js" type=text/javascript></script>
	<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=YOUR_GOOGLE_MAPS_KEYA&sensor=false" type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 900; height: 500px"></div>
</body>
</html>

<script language=JavaScript type=text/javascript>
var map;
var geocoder;
var address;

function initialize() {
  map = new GMap2(document.getElementById("map_canvas")); // instantiate map and use the DIV id as reference.
  map.setCenter(new GLatLng(1.2915, 103.8492), 13); // default location, somewhere in Singapore
  map.addControl(new GLargeMapControl);
  GEvent.addListener(map, "click", getAddress); // add click event and retrieve the location and twitter messages
  geocoder = new GClientGeocoder();
}

function getAddress(overlay, latlng) {
  if (latlng != null) {
    address = latlng;
    geocoder.getLocations(latlng, showAddress);
  }
}

function showAddress(response) {
  map.clearOverlays();
  if (!response || response.Status.code != 200) {
    alert("Status Code:" + response.Status.code);
  } else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    marker = new GMarker(point);
    map.addOverlay(marker);
    showTweet(place.Point.coordinates[1],place.Point.coordinates[0]);
  }
}

function markTweetOnMap(address,fText) {
	if (map == null) return false;
	if (address == null) return false;
	if (fText == null) fText = "Default Text";
	if (geocoder) {
		  geocoder.getLatLng(
		    address,
		    function(point) {
		      if (!point) {
		        //alert(address + " not found");
		      } else {
		        //map.setCenter(point, 13);

		        var marker = new GMarker(point);
		        GEvent.addListener(marker, "click", function() {
		          marker.openInfoWindowHtml(fText);
		        });
		        map.addOverlay(marker);
		      }
		    }
		  );
	}
}

function showTweet(fLat, fLng)
{
	  var searchTwitterUrl = 'http://search.twitter.com/search.json?rpp=20&geocode='+ fLat +'%2C'+ fLng +'%2C25km&callback=?';
		$.getJSON(searchTwitterUrl, function(data){
			$.each(data.results, function(i,item) {
				var geocode = item.location.split(": ",2);
				var temp = geocode[1];
				if (temp == undefined) temp = item.location;

				if (temp.split(",",2).length == 2) {
					markTweetOnMap(temp,item.text);
				}
		  });
		});
}

// JQuery: to be executed when document is loaded.
$(document).ready(function(){
	initialize(); // call initialize map method.
}); // end document ready

</script>

Ok, the code is rather messy. I copied an pasted the code from my prototype site. If it doesn’t run, just go to http://www.wswijaya.com/prototype/test4.php to try it.

References:

Advertisements

3 thoughts on “Nearby Tweet using Google Maps API”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s