Tuesday, April 1, 2014

Leaflet and CartoDB - The perfect combination

What is currently the most easy and convenient way to publish geographic data stored within a database via the web? One easy way doing so is the combination from Leaflet and CartoDB.

Leaflet is an open source library for publishing online maps. The JS library is lightweight (just 33 KB), and has all the features most developer expect from interactive maps. Furthermore functionalities can be extended via plug-ins developed by the open source community around leaflet.

CartoDB is a online database which can also be published on an own web server. The database allows to store geographic entities with geometry type point, lines and polygon. The database provides several APIs including an SQL API where it is possibly to execute native SQL queries. In addition CartoDB provides a leaflet JS plug in to access data directly as layer.

Some basic example to start with:

1) Create sample Data within CartoDB
2) Include Leaflet and CartoDB JS libraries within your HTML page.
3) Create a Leaflet map object and link it to a DIV object within the HTML page:

HTML part:
<div id="map" ></div>
JavaScript part:

// create a map in the "map" div, set the view to a given place and zoom var map = L.map('map').setView([51.505, -0.09], 13);

4) add a basemap Layer (e.g. Openstreetmap) to the map)

// add an OpenStreetMap tile layer L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);

4) add sample data stored witin Cartodb to the map

// add an Cartodb layer var cartodb_leaflet = new L.CartoDBLayer({
        map: map,
        user_name: "user_name",
        table_name: "table_name",
        query: "SELECT * FROM {{table_name}}",
        tile_style: "#{{table_name}}{polygon-fill:blue;  polygon-opacity: 0; line-color: yellow;  line-width: 5;  line-opacity: 0.7}",
        interactivity: "cartodb_id",
        featureClick: function(ev, latlng, pos, data) { },
        featureOver: function(){},
        featureOut: function(){},
        attribution: "CartoDB",
        auto_bound: true
      });
map.addLayer(cartodb_leaflet);


5) finnished.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.