Developer

Leaflet provides open source map solution

How to integrate full-featured maps into applications using Leaflet.

On a recent trip to Boston I consistently pulled up maps on my phone and computer to figure out my location as well as determine how to get from point a to point b. Interactive maps are now an integral part of our daily lives - it is hard to remember when we didn't have them. While they are standard features on our computers and devices, there are plenty of options for easily integrating full-featured maps into your applications. This week I take a look at one such option - the open source JavaScript library called Leaflet.

Simplicity is the key

Like anything related to Web development these days, there are a number of options available for including map features to your applications. What you decide to use often comes down to personal preferences - one of my requirements is simplicity and Leaflet does not disappoint. As its documentation states, it works across all major desktop and mobile platforms. Leaflet utilizes HTML5, CSS3 and JavaScript for modern platforms while remaining accessible and usable on older platforms.

The following steps outline the necessary steps to add a Leaflet powered map to a Web page:

1. Add reference to the Leaflet JavaScript library. The following script block is placed on the page - it is referenced in the head portion of the page for today's example:

<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>

If you would rather host this file (and the CSS library) locally, the files are available for download from the site.

2. Add reference to the Leaflet CSS library. The following can be placed in the head section of the page:

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />

3. Create a DIV container for the Leaflet map object. For my example, I name the DIV element trMap, but it can be named whatever fits your needs. The DIV id is referenced in the JavaScript code to create the map object, so you will need to keep the assigned name in mind when coding:

<div id=”trMap”></div>

4. Choose a data source for the map. There are various such sources and they can be combined or layered. A good free source is OpenStreetMap.org. It will be used in our example. The data source is specified when adding layers to the map object - thus you can combine multiple sources while via different layers.

5. Add JavaScript code for creating and populating the map object created in step 3. The map object is created with the setView method used to set the coordinates (longitude and latitude) with an optional parameter for setting the zoom level along with many more settings. Layers are added to the map via the TileLayer method with the map data source URL passed to it. The addTo method is used to add the actual map to the DIV element.

The result of these steps is shown in the following listing with the map centered on Philadelphia, Pennsylvania.

<html><head>
<title>TechRepublic.com Leaflet Example</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<style type="text/css">
#trMap {
height: 400px;
width: 500px;   }
</style></head>
<body>
<div id="trMap"></div>
<script type="text/javascript">
var map = L.map('trMap').setView([39.57, -75.10], 13);
L.tileLayer('http://tile.openstreetmap.org/{z}/{x}/{y}.png', {
id: 'Philly',
attribution: '<a href="http://www.techrepublic.com">TechRepublic.com'
}).addTo(map);
</script></body></html>

The below figure shows the map loaded in Internet Explorer 10.

figurea.jpg
Philadelphia area map displayed on web page via Leaflet JavaScript library.
The map can be enhanced by adding a marker on it along with a popup assigned to the marker as well as a general popup window when any area of the map is clicked. The following listing includes the code used to add the popup (marker and bindPopup methods) and the click event which uses the onMapClick function to display the coordinates (in a window) where the user clicks the mouse. The marker is placed at the location of the Philadelphia Phillies baseball stadium along with a popup window displayed any time a user clicks the map (it displays coordinates where selected). Figure B shows the new code entered and executed in Chrome via jsFiddle. It is worth noting that you can test geographical coordinates (longitude and latitude) on a site like geohash and location coordinates can be found on DateandTime.info.

function onMapClick(e) {
alert('Map coordinates: ' + e.latlng);
}
var map = L.map('trMap').setView([39.57, -75.10],11);
L.tileLayer('http://tile.openstreetmap.org/{z}/{x}/{y}.png', 
{ 
id: 'Philly', 
attribution: '<a href="http://www.phillyphandom.com">Phillies' })
.addTo(map);
L.marker([39.42, -75.09]).addTo(map).bindPopup('Citizens Bank Park').openPopup();
map.on('click', onMapClick);

figureb.jpg
Map loaded showing location of Philadelphia Phillies baseball stadium.

The example code covered so far only scratches the surface of the many options and features available with plenty of options for building maps. You can choose to use the map tile source of your choice or even build your own - a good example of a customized map via Leaflet is presented on the The Texas Tribune site for the 2012 Senate election. In addition, you can utilize numerous events as well zooming and placing markers or symbols on the actual map. The Leaflet features page includes plenty of additional information.

Expectations

Mapping features are now a standard component of mobile devices as well as Web applications, so users expect know how to use them. There are a variety of map resources readily available today with Google Maps being very popular along with others like MapQuest and the open source option OpenLayers. I was attracted to its very small footprint which leads to better performance, especially when targeting mobile devices. However, a smaller size can lead to less features but it provides the core features needed for basic mapping whereas an alternative like OpenLayers seems to try to do everything. In the end, the solution will depend on requirements with Leaflet meeting my current needs.

About Tony Patton

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

Editor's Picks

Free Newsletters, In your Inbox