Google Maps? Nah, Leaflet it go.

Coding a map is a little bit different than using an application to create a map because instead of fiddling around with a user-interface to generate the end product, the maps are generated beforehand (i.e. programmed).

While Google Maps API is probably one of the most commonly used map applications programming interface (API), we will not be going over it because there are some limitations of being tied to that platform, mainly in the realm of customization and depreciation.BUT! To see what it can do, feel free to check out Yoh’s getlatlon website!

http://getlatllon.yohman.com/getlatlon/

While there are many alternatives to choose from, such as OpenLayers or D3, we will be using Leaflet for its simplicity and customization features.

We will start by looking at the documentation:

http://leafletjs.com/reference.html

Step 1: Open up a text editor

Step 2: Create your first HTML document

  1. You want to begin by including leaflet into your page:
     <script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
  2. Next let’s include the css file:
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
  3. Now we need to put the map somewhere, so let’s make a “div” and name it map:
    <div id="map"></div>
  4. Finally, we can style the map a little bit by making it the full height of a page:
    #map { height: 800px; }

Step 3: Creating a map

Now that you may be feeling confident, but that map is not vary functional either, so let’s start adding “variables” and “functions.”

  1. When coding in HTML, most variables and functions can go anywhere, but to be consistent, let’s put everything in the “head” of the page.
  2. Feel free to copy and paste after the “map” div to get started:
    	<script>
    		var map = L.map('map').setView([34.07391778485353, -118.44180946326827], 13);
    
    		L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
    			maxZoom: 18,
    			id: 'examples.map-i875mjb7'
    		}).addTo(map);
    	</script>
  3. Now once you save and refresh your page you should have a map centered on Rolfe!
  4. There are two things to notice with this addition, which are “var” and “function”.
  5. Save your file as a .html file and open it up in a web browser!
  6. Congratulations you have created your first maproom!

Example code

Challenge! Add a marker:

  1. Copy and paste this code to create a marker in your map room:
    		L.marker([34.07391778485353, -118.44180946326827]).addTo(map)
    			.bindPopup("<b>Hello Rolfe</b><br />We are hereabouts.").openPopup();
    
  2. See if you can figure out where the code should go, if not here is a hint!

Example code