Tell us about your project

Example of a coastal map with a lot of marked locations/pinned locations

In one of the projects, the specification included the use of Leaflet maps. One of the difficulties was to make the Leaflet overlays automatically retrieve the list of Drupal content types, not all of them, but only the specific ones. This task seemed to be even more difficult because the only solution was to work in JavaScript and I wasn't an expert in either Leaflet or JS.

The project was about sailing, and it was supposed to provide people who were traveling the oceans with useful information.

As a starting point for this task, I already had a Leaflet map, which was represented as a block view. In the View settings, it was set that for a country related nodes are presented as markers on the map.

Yellow icons on the maps are nodes, where each icon represents a different content type.

jQuery(document).bind('leaflet.map', function(event, map, lMap) {
  //custom code goes here
});

Whenever we need to make some custom code for Leaflet maps, this is the code syntax and where we need to place our custom code.

//map id
var id = lMap._container.id;
var url = window.location.href;
var settingsElement = document.querySelector('script[type="application/json"][data-drupal-selector="drupal-settings-json"]');
var drupalSettings = JSON.parse(settingsElement.textContent);
var length = drupalSettings.leaflet[ id ].features.length;
var content_types = drupalSettings.contenttypes;
var ct_names = Object.keys(content_types);
var ct_length = ct_names.length;
var ct_image = Object.values(content_types);
var cnt_array = {};

In the first code snippet I've set the variable id which will retrieve the Leaflet map's ID from lMap Leaflet JavaScript core variable, and url which I'll need later in the code.

Next, I've included drupalSettings ( which I'll use to pass some variables from Drupal to JavaScript ).

Then, I`ve set the variables which will retreive the content type names and icon path values I`m gonna need later.
The following example from theme_name.theme file is down bellow:

function THEME_page_attachments_alter(array &$page) {
 
  $sql = "select data from config where name like '%leaflet_icons.settings%'";
  $query = db_query($sql);
  $content = $query->fetchAll();
  $content = $content[0]->data;
  $content = unserialize($content);
  $contentTypes = \Drupal::service('entity.manager')->getStorage('node_type')->loadMultiple();
  $contentTypesList = [];
  // Get content Type information.
  foreach ($contentTypes as $contentType) {
    $contentTypesList[$contentType->id()] = $contentType->label();
  }
 
  foreach ($contentTypesList as $key => $value) {
    if (!empty($content[$key])) {
      $val = $content[$key];
 
      $change = explode('/', $val);
      $lastI = count($change);
      $picture = explode('.', $change[($lastI - 1)]);
 
      if ($picture[0] != $key) {
        unset($content[$key]);
        $key = $picture[0];
      }
      $content[$key] = array($val, ucfirst(strtolower($value)));
    }
  }
 
  ksort($content);
  $page['#attached']['drupalSettings']['contenttypes'] = $content;
}

In my example above, I only needed content types that would be included in the overlays list and that have values for the icon image in the Leaflet Icons settings.

I have selected a value from the database table Leaflet icons, but as the content is serialized, we'll first have to unserialize it. After fetching them all, I've sorted everything alphabetically.

$.each(content_types, function(key, value){
  window[key] = new L.LayerGroup();
  window[key+"Icon"] = L.icon({
    iconUrl: value[0],
    iconSize: [30, 30], // size of the icon
        iconAnchor: [0, 0], // point of the icon which will correspond to marker's location
        popupAnchor: [15, 15], // point from which the popup should open relative to the iconAnchor
        className: 'leaflet-custom-layer'
  });
});

In the code above, we went through every content type dynamically and set Icon settings for each of them ( URL, position, size, etc ). We'll need that later as well.

var base_url = "{{ url('<front>') }}";
 
var i;
for (i = 0; i < length; i++) {
 
  var lat = drupalSettings.leaflet[ id ].features[i].lat; //lat
  var lon = drupalSettings.leaflet[ id ].features[i].lon; //lon
 
  var iconUrl = drupalSettings.leaflet[ id ].features[i].icon.iconUrl;
  var exloded = iconUrl.split('/');
  var lengthall = exloded.length;
 
  var extension = exloded[(lengthall - 1)];
  var split = extension.split('.');
  var finalIcon = split[0];
 
  var popup = drupalSettings.leaflet[ id ].features[i].popup; //popup
 
  if (typeof window[finalIcon+'Icon'] != 'undefined') {
    L.marker([lat, lon], {icon: window[finalIcon+'Icon']}).bindPopup(popup).addTo(window[finalIcon]);
  }

Next, we need to set the base_url that we'll need for setting the icon path value.

We are going through every icon on the map, using a for loop to set some variables.

lat and lon variables are the coordinates of each node.

Next, we'll format the icons.

The variable popup is the value of a popup section for each node.  

In the end, we ask if typeof icon is not undefined, so we can set the node values, including its coordinates, icon URL value, and popup. All those nodes will appear on the map when we load the page.

// do not show markers with icons on map load
Drupal.Leaflet.prototype.create_point = function (marker) {
  var latLng = new L.LatLng(marker.lat, marker.lon);
  this.bounds.push(latLng);
  var lMarker;
  if (marker.icon) {
    var icon = this.create_icon(marker.icon);
    //lMarker = new L.Marker(latLng, {icon: icon});
  }
  else {
    lMarker = new L.Marker(latLng);
  }
  return lMarker;
};

As I said before, we did have icons on the map set already, before we started adding our custom code for Leaflet icons.

So, by adding these custom settings, our map would have duplicates of each icon.

We'll have to exclude those already appearing there before our changes.

That could be done by changing the JavaScript code above.

var overlays = {};
$.each(content_types, function(key, value){
  var text = '<img src="'+value[0]+'" /> '+value[1];
  overlays[text] = window[key];
});
L.control.layers(null, overlays).addTo(lMap);

In the end, we need to go again through all selected content types, and set the list of overlays and add them to the Leaflet map.

FULL CODE:

jQuery(document).bind('leaflet.map', function(event, map, lMap) {
  //map id
  var id = lMap._container.id;
  var url = window.location.href;
  var settingsElement = document.querySelector('script[type="application/json"][data-drupal-selector="drupal-settings-json"]');
  var drupalSettings = JSON.parse(settingsElement.textContent);
  var length = drupalSettings.leaflet[ id ].features.length;
  var content_types = drupalSettings.contenttypes;
  var ct_names = Object.keys(content_types);
  var ct_length = ct_names.length;
  var ct_image = Object.values(content_types);
  var cnt_array = {};
  $.each(content_types, function(key, value){
    window[key] = new L.LayerGroup();
    window[key+"Icon"] = L.icon({
      iconUrl: value[0],
      iconSize: [30, 30], // size of the icon
      iconAnchor: [0, 0], // point of the icon which will correspond to marker's location
      popupAnchor: [15, 15], // point from which the popup should open relative to the iconAnchor
      className: 'leaflet-custom-layer'
    });
  });
  var base_url = "{{ url('<front>') }}";
  var i;
  for (i = 0; i < length; i++) {
    var lat = drupalSettings.leaflet[ id ].features[i].lat; //lat
    var lon = drupalSettings.leaflet[ id ].features[i].lon; //lon
    var iconUrl = drupalSettings.leaflet[ id ].features[i].icon.iconUrl;
    var exloded = iconUrl.split('/');
    var lengthall = exloded.length;
    var extension = exloded[(lengthall - 1)];
    var split = extension.split('.');
    var finalIcon = split[0];
    var popup = drupalSettings.leaflet[ id ].features[i].popup; //popup
    if (typeof window[finalIcon+'Icon'] != 'undefined') {
      L.marker([lat, lon], {icon: window[finalIcon+'Icon']}).bindPopup(popup).addTo(window[finalIcon]);
    }
  }
  $.each(ct_names, function(index, value){
    lMap.addLayer(window[value]);
  });
 
  // do not show markers with icons on map load
  Drupal.Leaflet.prototype.create_point = function (marker) {
    var latLng = new L.LatLng(marker.lat, marker.lon);
    this.bounds.push(latLng);
    var lMarker;
    if (marker.icon) {
      var icon = this.create_icon(marker.icon);
      //lMarker = new L.Marker(latLng, {icon: icon});
    } else {
      lMarker = new L.Marker(latLng);
    }
    return lMarker;
  };
  var overlays = {};
  $.each(content_types, function(key, value){
    var text = '<img src="'+value[0]+'" /> '+value[1];
    overlays[text] = window[key];
  });
  L.control.layers(null, overlays).addTo(lMap);
});

 


Lazar Padjan