Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sortLayers and sortFunction options to sort layers #43

Open
wants to merge 1 commit into
base: gh-pages
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/leaflet.groupedlayercontrol.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,24 @@ L.Control.GroupedLayers = L.Control.extend({
position: 'topright',
autoZIndex: true,
exclusiveGroups: [],
groupCheckboxes: false
groupCheckboxes: false,
// Whether to sort the layers. When `false`, layers will keep the order
// in which they were added to the control.
sortLayers: false,
// A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
// that will be used for sorting the layers, when `sortLayers` is `true`.
// The function receives both the `L.Layer` instances and their names, as in
// `sortFunction(layerA, layerB, nameA, nameB)`.
// By default, it sorts layers alphabetically by their name.
sortFunction: function (layerA, layerB, nameA, nameB) {
if (nameA < nameB) {
return -1;
} else if (nameB < nameA) {
return 1;
} else {
return 0;
}
}
},

initialize: function (baseLayers, groupedOverlays, options) {
Expand Down Expand Up @@ -144,6 +161,12 @@ L.Control.GroupedLayers = L.Control.extend({
this._lastZIndex++;
layer.setZIndex(this._lastZIndex);
}

if (this.options.sortLayers) {
this._layers.sort(L.bind(function (a, b) {
return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
}, this));
}
},

_update: function () {
Expand Down