Leaflet 1

Basic Leaflet Map: Part 1
By Max Axler

There are many ways of putting spatial data online ranging from out of the box solutions such as Google’s Fusion Tables or Adobe Flash, to javascript libraries like Google Maps API. While the industry standard for javascript libraries has become Google Maps API, there are many reasons to seek out open alternatives.

First, open javascript libraries are not subject to changing payment plans. Just recently, Google announced plans to charge on a per view basis after map views exceed a certain number. This tutorial will explain the set-up of a basic leaflet map.

Step 1:

The first step to setting up any javascript web map is to put together the basic HTML framework. Using what you’ve learned from previous tutorials create the standard,, andelements. Next, create a div with the ID of “map”. You will use this div as a container for the map object, which you will instantiate using the leaflet library.

<html>
<head>
</head>
	<body>
		<div id = “map”>
		</div>
	</body>
</html>

You will also need to define some styling for the map <div>. You can do this within the HTML document by adding a style property to the div tag, i.e.

<div id="map” style = “width: 100%; height: 600px; border: 2px solid #ccc”>

or within a separate stylesheet. When you have completed this setup code, create a new folder to house your web map and save the document as index.html.

Step 2:

The next step is to download the leaflet source code and reference it in your html document. Point your web browser to: http://leaflet.cloudmade.com/download.html
and download leaflet version 0.3.1.

Then move the contents of the folder into the same directory where you are storing the index.html document. Rename the downloaded folder leaflet to make it easier to reference in your code.

Now that you have copies of the leaflet source code you need to “link” the leaflet javascript and stylesheets to your index page. To accomplish this place links within the head section of the document as follows.

<script type="text/javascript" src="leaflet/dist/leaflet.js"></script>

Note: Since internet explorer is a terrible browser it requires its own separate stylesheet. To make your map compatible with IE, be sure to include this piece of code which will detect the browser and switch the stylesheet accordingly.

<!--[if lte IE 8]>
	<link rel="stylesheet" href="leaflet/dist/leaflet.ie.css" /><![endif]-->

Step 3:

The final step to creating your basic Leaflet map is write the script that loads your map. Now that you have created a space in the html for your map to sit, and connected a series of functions via the leaflet library, you can call these functions to create your interactive map. The first thing you should do, is create a new script within the head of the document.

<script type="text/javascript">// <![CDATA[


// ]]></script>

Next, it is good practice to wrap your entire map script in the function:

window.onload = function () {

};

This ensures that your map script won’t run until the web page structure has loaded, preventing leaflet from trying to load your map in a non-existent div.

Now you need to tell leaflet what type of tile layer to use. Tiles are simply a series of png images that make up the basemap of any javascript based webmap. Tiling allows your web browser to load base maps quickly at a variety of scales.

Since leaflet is designed to be open and modular, you can load these tiles from a number of sources (such as google, tilemill, open street maps) but for simplicity we will be loading them from leaflet’s parent company, Cloudmade.

var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png';

This segment of code pulls the images from Cloudmade’s tile server based on a specified API key from cloudmade, styling ID, and the X,Y, Z coordinates of your current map pane.

Now that you are pulling the tiles into your map as specified by the variable “cloudmadeUrl”, you create a new variable “basemap” defined as a Leaflet tile layer. This tile layer takes two arguments: the url, and options parameters.

var basemap = new L.TileLayer(cloudmadeUrl, {maxZoom: 18});

You also need to define the latitude and longitude around which your map will be centered.

var latlng = new L.LatLng(43.0731, -89.4011);

Finally, you are ready to instantiate your map object using the L.Map function. This function takes two arguments as well, the first being the div in which you wish to load the map, “map”, and the second being any map options you want to specify.

Visit the leaflet documentation to learn more about map options:

http://leaflet.cloudmade.com/reference.html#map-options

Here is the code:

var map = new L.Map('map', {center: latlng, zoom: 15, layers: [basemap]});

And that should be it! In short, your script should look something like this:

<script type="text/javascript">// <![CDATA[
			window.onload = function () {
var cloudmadeUrl =   'http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png';

			var basemap = new L.TileLayer(cloudmadeUrl, {maxZoom: 18});
			var latlng = new L.LatLng(43.0731, -89.4011);

			var map = new L.Map('map', {center: latlng, zoom: 15, layers:[basemap]});

		};

// ]]></script>

Test it out in a browser by double clicking your index page. If you are having problems check out the completed code below. I’ve also included some other methods below.

Full Code

Full code below:
<!--[if lte IE 8]>
	<link rel="stylesheet" href="leaflet/dist/leaflet.ie.css" /><![endif]--> 

<script type="text/javascript">// <![CDATA[
			window.onload = function () {

			var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png';

			var basemap = new L.TileLayer(cloudmadeUrl, {maxZoom: 18});
			var latlng = new L.LatLng(43.0731, -89.4011);

			var map = new L.Map('map', {center: latlng, zoom: 15, layers: [basemap]});

		};

	
// ]]></script>

 
<div id="map" style="width: 100%; height: 600px; border: 1px solid #ccc;"></div>

Map Options:
In the code above, you create a map variable that passes two arguments: the

where you will be loading the map (‘div’) and some options contained within curly braces.
var map = new L.Map('map', {center: latlng, zoom: 15, layers: [basemap]});

If we rewrite this with a new variable ‘mapOptions’ = to the contents of the curly braces and pass the options variable in place of the braces it will be easier to manipulate the options. Once you’ve set up your options variable – check out the leaflet documentation: http://leaflet.cloudmade.com/reference.html#map-options
and choose some additional options.

var mapOptions = { center: latlng,
zoom: 15,
layers: [basemap],
boxZoom: true
};
var map = new L.Map('map',mapOptions);

Creating a Marker:

Once you’ve instantiated your map object – you can add data in a variety of ways. The simplest is to manually geocode points.

The code for this process can be found in the documentation portion of leaflet’s website.

Basically all you have to do is specify a latitude and longitude, create a marker variable at that latitude and longitude, and bind a popup to the marker if necessary.

You then can add the marker to the map as a layer.

var markerLocation = new L.LatLng(43.0731, -89.4011);

var marker = new L.Marker(markerLocation);
marker.bindPopup("

This is apparently the center point of Madison

");
map.addLayer(marker);

Adding a click event to a marker:

Sometimes you want a javascript event to trigger when you click on a map element. By using the layer.on(‘click’) method you can trigger a javascript event to occur when you click the item.

Try adding this code to your map script:

marker.on('click', alertMe);

function alertMe() {
alert('you clicked the marker');
};

Note: The term marker is referring to the marker you created previously but it could be switched out for any map object you choose.

Part 2: Bringin in data as a geoJSON –>