Leaflet API
You can define custom settings and interactions for a Leaflet map by adding a JS library in a custom theme or module, with the following Drupal.behaviors and code.
Note: Make sure it is loaded before the leaflet.drupal.js file. If necessary add a negative weight, as seen in the code example below.
Once each Leaflet Map is initialized it triggers the leafletMapInit event (https://git.drupalcode.org/project/leaflet/-/blob/10.0.x/js/leaflet.drup...).
In this example, the user is prevented from panning out from a certain latitude/longitude boundary using the setMaxBounds method. The lat/long pair is first the lower left, and then the upper right corner.
Create a js/map.js file with this content:
/**
* @file JavaScript
*/
(function ($, Drupal) {
Drupal.behaviors.customLeafletInteraction = {
attach: function (context, settings) {
// React on leafletMapInit event.
$(context).on('leafletMapInit', function (e, settings, map, mapid, markers) {
// Now set your maxbounds, see the leaflet documentation for reference.
map.setMaxBounds([
[40.712, -74.227],
[41.774, -74.125]
]);
map.setMinZoom(14);
})
}
}
})(jQuery, Drupal);Register the file in a custom theme or module, with this in a *.libraries.yml file. To make sure the file is loaded before leaflet.drupal.js you may need to add a weight value:
global-scripts:
js:
js/map.js: { weight: -10 }
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.