[Drupal] How to configure Leaflet module in Drupal

| | 2 min read

Leaflet is a modern open-source JavaScript library. It can be used for building mobile friendly interactive maps.The following steps should be added before writing any code for the map.

  • Include Leaflet CSS file in your document

    link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
  • Include Leaflet JavaScript file

    script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js">
  • To add a tile layer to our map, set the URL template, attribution text and the maximum zoom level of the layer

    MB_ATTR = 'Map data © OpenStreetMap contributors, ' +
      'CC-BY-SA, ' +
      'Imagery © Mapbox';
    
    MB_URL = 'https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png';
  • Add a div element with some id where you want your map to be

    div id="map"
  • Make sure the map container has a defined height, by setting it in CSS.For eg:

    #map { height: 180px; }

Initialize the map first and set its view to our chosen geographical coordinates and a zoom level:

var map = L.map('map').setView([51.505, -0.09], 13);

By default all mouse and touch interactions on the map are enabled, and it has zoom and attribution controls.

To add a tile layer to our mapMapbox

L.tileLayer(MB_URL, {attribution: MB_ATTR, id: 'examples.map-i86knfo3'}).addTo(map);

Make sure all the code is called after the div and leaflet.js inclusion

How to add Markers, circles and polygons in the map

  • Adding a marker

    var marker = L.marker([51.5, -0.09]).addTo(map);
  • Adding a circle

    var circle = L.circle([51.508, -0.11], 500, {
      color: 'red',
      fillColor: '#f03',
      fillOpacity: 0.5
    }).addTo(map);
  • Adding a polygon

    var polygon = L.polygon([
      [51.509, -0.08],
      [51.503, -0.06],
      [51.51, -0.047]
    ]).addTo(map);

Popups attaches information to a particular object on a map.

marker.bindPopup("Hello world!I am a popup.").openPopup();
circle.bindPopup("I am a circle.");
polygon.bindPopup("I am a polygon.");

The bindPopup method attaches a popup with some HTML content to your marker so the popup appears when you click on the object, the openPopup method opens the attached popup.