CloudMade & Leaflet.js

jQuery

It’s been a fun week at WALL-iT. We’ve been working on integrating some cool new features into our website, and wanted to share with you how easy it is to use Leaflet.js and Cloudmade together to create some rad custom map layouts.

First, we want to set up our files and environment by loading the javascript and CSS libraries.

<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js" type="text/javascript">
<link href=" http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" rel="stylesheet" type="text/css">

If we are using WordPress, we will want to queue in our files accordingly.

wp_enqueue_script('leaflet', 'http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"', array('jquery') );
wp_enqueue_style( 'leaflet.css', 'http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css' );

Fortunately Leaflet has a CDN and provides their source files wonderfully.

Next, we will make a simple HTML container.

<div id="leaflet">
</div>

Add some CSS to our site to configure a height and width.

/*	Leaflet CSS */
#leaflet {height:180px; width: 450px;display:block;}

Now comes the fun part. CloudMade offers us the ability to customize the look and feel of our map overlay. Once you have created a map and have it’s ID (we are going to use a map overlay with the ID of 125327) we can begin implementing Leaflet and Cloudmade together.

In our javascript.js file, we will want to:

1. Configure Leaflet for our div id="leaflet"
2. Integrate our CloudMade style via their API
3. Set a default viewport location
4. Create a basic popup

First, we will create a new Leaflet instance targeting the id of ‘leaflet’:

var map = L.map('leaflet').setView([32.830567, -117.150848], 13);

Now, we will add a tileLayer to our Leaflet instance:

L.tileLayer('http://{s}.tile.cloudmade.com/d1cdea7a278f4cc19b7a26086a2889af/125327/256/{z}/{x}/{y}.png', {
			maxZoom: 18,
			attribution: ''
		}).addTo(map);

Finally, we will add an HTML popup at the lat/long where our office is located 🙂

var marker = L.marker([32.830567, -117.150848]).addTo(map);
		marker.bindPopup("<b>WALL-iT Web Design</b><br/><b>7975 Raytheon Road Ste #350<br/>Kearny Mesa, CA</b>").openPopup();

The end result is below: