Monday 8 October 2012

Creating a "Where I've Been" map with Leaflet and CartoDB

I wanted to create a "Where I've Been" map of my trip around New Zealand. The map should be easy to update through a simple web interface. Previously, I've used Google Fusion Tables for tasks like this. Now, I want to try CartoDB, which is Google Fusion Tables on steroids.


I used the CartoDB free plan to create a simple table containg the name and location of the places I've been:


You can easily query your data with the HTTP-based SQL API:

http://thematicmapping.cartodb.com/api/v2/sql?q=SELECT * FROM nz_tour

This request will return all the data in the default CartoDB JSON-format. Add format=geojson, if you want the data in the GeoJSON format supported by Leaflet:

http://thematicmapping.cartodb.com/api/v2/sql?q=SELECT * FROM nz_tour&format=geojson

The SQL API also supports JSONP, allowing you to query your data directly from JavaScript in the web browser. Just add a callback parameter:

http://thematicmapping.cartodb.com/api/v2/sql?q=SELECT * FROM nz_tour&format=geojson&callback=myFunction

Leaflet don't have native support for JSONP or CartoDB, but there are a few plugins around (1, 2). It's also very easy to extend Leaflet with the functionality you want, so I decided to create a new CartoDB layer class by extending the L.GeoJSON class:

This class rewrites the initialize function and adds a JSONP function (you can also use a library like jQuery). This is how you can create a new layer with this class:

L.cartoDB('http://thematicmapping.cartodb.com/api/v2/sql?q=SELECT * FROM nz_tour')

This will create a layer with the default Leaflet markers:


If you want custom markers and popups, all the functionality available for the GeoJSON layer can also be used for the CartoDB layer:

The interactive map looks like this:

Fullscreen map

You can add a marker to the map by adding a new row to your CartoDB table. Dead simple!

2 comments:

Marcello Benigno said...

Thanks for sharing! I am trying to adapt your code to my application and I wonder if there is any component as a "search box", which allows to find the features typing municipality names.

Bjørn Sandvik said...

Hi Marcello,

Have a look at the Leaflet Search plugin.