65.9K
CodeProject is changing. Read more.
Home

Leaflet.js - A Simple Example

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.69/5 (5 votes)

Mar 17, 2015

CPOL

1 min read

viewsIcon

41179

downloadIcon

1058

How to use Leaflet.js to easily create a map with custom markers, popups, baselayers and overlays menu, WMS overlays

Introduction

If you need a quick and easy, mobile-friendly map with markers and the possibility to add Web Map Service overlays, then a very good library for you to consider is Leaflet.js.  

In this tip, I will share with you a simple example of how leaflet.js works.

I've wrapped up a few basic features of leaflet.js in a JavaScript object which I called mapManager: if you like it, feel free to download it, use it, modify it and extend it at your convenience! 

You can also find it on github at https://github.com/nickygiorgi/leaflet.js-simple-example.

Using the Code

Your map will reside inside a div with an id of your choice:

   <div id="map"></div>

In your JavaScript code, you'll want to be able to perform some basics, which I've wrapped up in mapManager. 

For example, you will need to initialize a map object (L.Map class) and create its base layers (L.tileLayer):

init: function (divID, center, zoom) {
        
        // a map has one or more base layers which define the map's general aspect        

        // for example, openstreetmap provides some base layers free to use
        // openstreetmap initialization
        var mbAttr = 'Map data &copy; 
        <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
                '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
                'Imagery © <a href="http://mapbox.com">Mapbox</a>',
            mbUrl = 'https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png';

        // openstreetmap base layers (greyscale, streets)    
        var grayscale = L.tileLayer(mbUrl, { id: 'examples.map-20v6611k', attribution: mbAttr }),
            streets = L.tileLayer(mbUrl, { id: 'examples.map-i875mjb7', attribution: mbAttr });          
        
        // set default base layer to openstreetmap streets
        this.map = L.map(divID, {
            center: center,
            zoom: zoom,
            layers: [streets],
            scrollWheelZoom: 'center'
        });

        // create basic list of base layers to be inserted in menu 
        this.baseLayers = {           
            "Grayscale": grayscale,
            "Streets": streets
        };

    },

If you want to use Google baselayers (that will make your map look like Google maps), you will need to use a plugin. Inside mapManager, you can find the code and references to use a plugin of my choice: https://github.com/shramov/leaflet-plugins/blob/master/layer/tile/Google.js by Pavel Shramov. 

Another thing you might want to do is adding one or more WMS overlays (L.tileLayer.wms) and finalize your map assigning all the base layers and overlays you previously defined to your map object and inserting them in a user menu (L.control.layers):

    // add WMS overlay 
    addWMSOverlay: function (overlayName, wmsAddress, wmsParams) {
        var layer = L.tileLayer.wms(wmsAddress, wmsParams);
        this.overlays[overlayName] = layer;
    },

    // assign base layers and overlays to map object, insert them in upper right menu 
    addLayersControl: function () { 
        if (isEmptyJSObj(this.overlays))
            this.mapLayersMenu = L.control.layers(this.baseLayers).addTo(this.map);
        else
            this.mapLayersMenu = L.control.layers(this.baseLayers, this.overlays).addTo(this.map);    
    },

Finally, you might want to find some nice icons and add custom markers to your map:

    // insert markers on the map
    // position is array [lat, long]
    // iconSize is array [width, height] (pixels)
    addMarker: function (relativeIconUrl, position, iconSize, popupHtmlContents) { 
        var defaultMapIcon = L.Icon.extend({
            options: {
                iconSize: iconSize,
                iconAnchor: [15, 15],
                popupAnchor: [-3, -3],
            }
        });

        var myMarker = new defaultMapIcon({ iconUrl: getBaseUrl() + relativeIconUrl });
        L.marker(position, { icon: myMarker }).bindPopup(popupHtmlContents).addTo(this.map);
    }

Here is an example of how to use my object mapManager to easily build your map with overlays and custom markers:

$( document ).ready(function() {
    CreateMap();
    // add a marker - a scottish flag icon will be shown on the coordinates for 
    // Edinburgh (latitude 55.95, longitude -3.19)
    // the icon size is 30 X 23 (width X height)
    // when clicking on the marker a popup will be shown with the text "Edinburgh!"
    mapManager.addMarker('/includes/images/edinburgh.png', [55.95, -3.19], [30, 23], 'Edinburgh!');
    // London marker
    mapManager.addMarker('/includes/images/london.png', [51.50, -0.12], [30, 18], 'London!');
    // Dublin marker
    mapManager.addMarker('/includes/images/dublin.png', [53.34, -6.26], [30, 19], 'Dublin!');
});

function CreateMap() {
    
    // create and initialize an empty map centered in [53.38, -1.47] (latitude, longitude) with zoom 6
    // map comes with a bunch of base layers (openstreetmap)
    mapManager.init('map', [53.38, -1.47], 6);
   
    // add a WMS (web map service) overlay - this one shows values of 
    // air temperature in different areas (points on the map) 
    mapManager.addWMSOverlay("Air Temp (deg F) - noaa",
       "http://nowcoast.noaa.gov/wms/com.esri.wms.Esrimap/obs", {
           format: "image/png",
           transparent: true,
           layers: "OBS_MET_TEMP"
       });
    //  add a WMS (web map service) overlay - this one shows a heatmap on air temperature
    mapManager.addWMSOverlay("Air Temp (heatmap) - geomet",
       "http://geo.weather.gc.ca/geomet/", {
           format: "image/png",
           transparent: true,
           opacity: 0.5,
           layers: "GDPS.PRES_TT"
       });
    
    // add a basic control panel (menu) in the upper right corner of the map with 
    // base layers and overlays
    mapManager.addLayersControl();   

}

I hope you find mapManager useful!