Leaflet Day 13 - Styling with a Plugin

Today we’ll take a look at another plugin—one that allows us to interactively change they style of features on our map: Leaflet.StyleEditor. This illustrates how we can customize our map by changing styles on the fly and also serves as a starting point for even more customization.

Installing and Referencing the Plugin

The web page for the plugin provides information on installing it. This requires getting the css, js, and image files in the proper location, then referencing them in our HTML file:

1
2
3
4
  <link rel="stylesheet" href="/stylesheets/leaflet.css" />
  <link rel="stylesheet" href="/stylesheets/Leaflet.StyleEditor.min.css" />
  <script src="/js/leaflet.js"></script>
  <script src="/js/Leaflet.StyleEditor.min.js"></script>

We added lines 2 and 4 after the Leaflet CSS and JavaScript files.

The plugin expects to find its image files in a directory named img, one level above the CSS file.

Adding the Style Editor to the Map

Next we modify the JavaScript code to add the control to the map:

//Initialize the StyleEditor
let styleEditor = L.control.styleEditor({
    position: 'bottomleft'
});
map.addControl(styleEditor)

This places the editor control in the bottom left corner of the map. In order to do this, make sure you don’t already have a control positioned there.

Using the Style Editor

To use it, click on the tool in the lower left, then click a feature to bring up the editor:

Here we changed the line style and the width. Play around with the editor to see what you can change for both markers and lines (we have no polygons).

You can further customize the setup of the style editor:

//Initialize the StyleEditor
let styleEditor = L.control.styleEditor({
    position: 'bottomleft',
    colorRamp: ['#1abc9c', '#2ecc71', '#3498db'],
    markers: ['circle-stroked', 'circle', 'square-stroked', 'square']
});

This sets up the colors and marker styles available to the editor. We didn’t change anything so what you see on the map are the defaults.

You can view the map here.