Sunday, November 14, 2010

Mashing up Google Maps and Flickr

I've combined the Google maps api and the Flickr api to produce a mash-up of how they can work together. A demo can be viewed here.

When using Google maps, you'll have to generate a key to point to a domain or directory. You'll also need to generate a key for Flickr, so they can monitor what you're doing with the pictures.

Key pieces of code:

1.


var map = new GMap2(document.getElementById("map"));
window.map = map;
        
map.setCenter(new GLatLng(43.643125,-79.397635), 13);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());

GEvent.addListener(map,'moveend',onMapMove);
GEvent.addListener(map,'zoomend',onMapZoom);

The above code creates a map centered at the longitude 43.643125 and latitude -79.397635 which is Toronto. It then adds some controls to the interface to zoom and change views. Finally events are added to update the images.

2. Retrieving the json data using jquery

$.getJSON("http://api.flickr.com/services/rest/?jsoncallback=?",  
{   
  method: "flickr.photos.search",
  tags: $("#tag").val(),
  min_upload_date: "2008-01-01",
  bbox: map.getBounds().getSouthWest().lng() + 
    "," + map.getBounds().getSouthWest().lat() + 
    "," + map.getBounds().getNorthEast().lng() + 
    "," + map.getBounds().getNorthEast().lat(),
  extras: "geo",
  per_page: $("#photonum").val(),
  format: "json",  
  api_key: "708eb7457e4afba46ac064c709db0d04",
},
function(data) {
  $.each(data.photos.photo, function(i,item){   
    var url = "http://farm" + item.farm + ".static.flickr.com/" + 
item.server + "/" + item.id + "_" + item.secret + "_m.jpg";
    $("<img/>").attr("src", url).appendTo("#images");
  });  
});
 
The getJSON method takes the URL and the following array to build a query for returning json.
The following anonymous function is a callback which will handle the retrieved data. 
It parses the json and puts the url of the picture in the div container.

No comments:

Post a Comment