Skip to content

Layer Base Class

Purpose and Scope

This document describes the Layer base class, which provides the foundational architecture for all layer types in Leaflet. The Layer class defines the lifecycle contract that layers must follow, manages layer-map relationships, handles pane assignment for z-ordering, and integrates with the event system.

For information about specific layer implementations (tiles, markers, vectors), see Tile Layers and Grid System, Markers and Icons, and Vector Layers. For information about layer collections, see Layer Groups and Feature Groups.

Class Overview

The Layer class serves as the abstract base class for all layers in Leaflet. It extends Evented to provide event capabilities and defines the contract that all layer implementations must follow.

Class Hierarchy

SVG
100%

Sources: src/layer/Layer.js1-29

Default Options

The Layer class defines three default options that all layers inherit:

OptionTypeDefaultDescription
paneString'overlayPane'Name of the map pane where the layer will be rendered
attributionStringnullAttribution text displayed in the attribution control
bubblingPointerEventsBooleantrueWhether pointer events should bubble up to the map

Sources: src/layer/Layer.js31-45

Lifecycle Management

Layers follow a well-defined lifecycle that coordinates their addition to and removal from the map. This lifecycle ensures proper initialization, cleanup, and event handling.

Lifecycle Flow Diagram

SVG
100%

Extension Methods

Subclasses must implement the following methods to properly participate in the layer lifecycle:

onAdd(map)

Purpose: Creates the layer's DOM elements and adds them to the appropriate map panes. This method is called when the layer is added to the map and the map is ready.

Responsibilities:

  • Create DOM elements for the layer
  • Add elements to map panes using getPane()
  • Attach event listeners to map events
  • Perform any initialization that requires the map to be ready

onRemove(map)

Purpose: Cleans up the layer's DOM elements and removes event listeners. This method is called when the layer is removed from the map.

Responsibilities:

  • Remove DOM elements from panes
  • Detach event listeners
  • Clean up any resources allocated in onAdd()

getEvents() (Optional)

Purpose: Returns an object mapping map event names to handler methods. The layer system automatically manages adding and removing these listeners.

Return value: Object like { viewreset: this._reset, move: this._update }

beforeAdd(map) (Optional)

Purpose: Called before the layer is added to the map, before events are initialized, and without waiting for the map to be ready. Used for early initialization.

Internal Lifecycle Coordination

The _layerAdd method coordinates the layer's lifecycle when the map becomes ready:

SVG
100%

Public API

The Layer class provides several methods for adding, removing, and querying layers.

Layer Management Methods

MethodParametersReturnsDescription
addTo(map)map: LeafletMap or LayerGroupthisAdds the layer to the given map or layer group
remove()NonethisRemoves the layer from the map it is currently active on
removeFrom(obj)obj: LeafletMap or LayerGroupthisRemoves the layer from the given map or layer group

addTo Method

The addTo method is the primary way users add layers to the map:

SVG
100%

Implementation: The method simply delegates to map.addLayer(this) and returns this to enable method chaining.

remove Method

The remove method removes the layer from its current map:

Implementation detail: It calls removeFrom(this._map || this._mapToAdd), using _mapToAdd as a fallback if the layer was added but the map isn't ready yet.

Utility Methods

MethodParametersReturnsDescription
getPane(name)name: String (optional)HTMLElementReturns the pane element; if name omitted, returns layer's default pane
getAttribution()NoneStringReturns the attribution text for this layer
addInteractiveTarget(targetEl)targetEl: HTMLElementthisRegisters an element as an interactive target
removeInteractiveTarget(targetEl)targetEl: HTMLElementthisUnregisters an interactive target

Pane System

Leaflet uses a pane system to manage the z-ordering of layers. Each layer is rendered into a specific HTML pane, which determines its stacking order relative to other layers.

Pane Resolution

The getPane method resolves pane references flexibly:

SVG
100%

Example usage:

  • layer.getPane() - Returns the layer's default pane (usually 'overlayPane')
  • layer.getPane('shadowPane') - Returns the shadowPane if layer.options.shadowPane is set, otherwise looks up 'shadowPane' directly

Common Pane Names

While the Layer class defaults to 'overlayPane', different layer types use different panes:

Pane NameTypical UsageDefault z-index
mapPaneContainer for all other panesauto
tilePaneTile layers (GridLayer, TileLayer)200
overlayPaneVector shapes, image overlays400
shadowPaneMarker shadows500
markerPaneMarker icons600
tooltipPaneTooltips650
popupPanePopups700

Attribution System

The attribution system allows layers to declare copyright and data source information that appears in the attribution control.

Attribution Flow

SVG
100%

Implementation

The getAttribution method simply returns the attribution option:

getAttribution() {
    return this.options.attribution;
}

Usage example:

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
});

Interactive Targets

The interactive target system allows layers to register DOM elements that should trigger layer events when clicked or interacted with.

Target Registration

Methods

addInteractiveTarget(targetEl): Registers a DOM element as an interactive target by:

  1. Stamping the element with a unique ID using Util.stamp()
  2. Storing the layer reference in map._targets[id]

removeInteractiveTarget(targetEl): Unregisters an interactive target by deleting its entry from map._targets.

Use case: Vector layers use this to register their SVG/Canvas elements so that clicks on those elements trigger events on the layer.

Event Integration

The Layer class integrates with Leaflet's event system through its inheritance from Evented and coordination with the map's lifecycle.

Layer Events

EventFired WhenEvent Data
addLayer is added to the map (after onAdd)Generic Event
removeLayer is removed from the map (after onRemove)Generic Event

Event Registration Pattern

Layers can use the getEvents method to automatically register and unregister event handlers:

SVG
100%

Benefit: This pattern ensures that event listeners are automatically cleaned up when the layer is removed, preventing memory leaks.

Map Integration

The Layer class is tightly integrated with the LeafletMap class through extension methods and the layer registry.

Map Layer Registry

The map maintains a registry of all active layers in _layers:

SVG
100%

Map Methods for Layer Management

The Layer.js file extends LeafletMap with methods for managing layers:

MethodDescription
addLayer(layer)Validates layer, assigns unique ID, stores in registry, triggers lifecycle
removeLayer(layer)Calls onRemove, removes from registry, fires events
hasLayer(layer)Checks if layer is in the registry
eachLayer(fn, context)Iterates over all registered layers

addLayer Implementation Details

The addLayer method on the map performs several important steps:

  1. Validation: Ensures the object has a _layerAdd method
  2. Deduplication: Uses Util.stamp() to check if layer is already added
  3. Early storage: Stores layer in _mapToAdd before map is ready
  4. beforeAdd hook: Calls optional beforeAdd(map) if it exists
  5. Deferred initialization: Uses whenReady() to defer _layerAdd until map is ready

Zoom Level Coordination

The map tracks layers that define zoom limits to coordinate the map's effective zoom range:

SVG
100%

Layer Event Propagation to Map

When layers are added or removed, both the layer and the map fire events:

ActionLayer EventMap EventEvent Data
Layer addedlayer.fire('add')map.fire('layeradd', {layer}){layer: Layer}
Layer removedlayer.fire('remove')map.fire('layerremove', {layer}){layer: Layer}

Comparison with Control

While both Layer and Control represent objects that can be added to the map, they serve different purposes:

AspectLayerControl
PurposeDisplays geographic dataProvides UI controls
Base classExtends EventedExtends Class
PositioningPositioned geographicallyPositioned in corner containers
Lifecycle methodsonAdd, onRemove, beforeAdd, getEventsonAdd, onRemove
ContainerRendered into map panesRendered into control corners
Event integrationFull event system via getEventsManual event handling
ExamplesTileLayer, Marker, PolygonZoom control, Attribution control

Code Entity Reference

Key Classes and Files

EntityFilePurpose
Layersrc/layer/Layer.js29-117Base class for all layers
LeafletMap.addLayersrc/layer/Layer.js155-173Adds layer to map
LeafletMap.removeLayersrc/layer/Layer.js177-196Removes layer from map
LeafletMap.hasLayersrc/layer/Layer.js200-202Checks if layer is on map
LeafletMap.eachLayersrc/layer/Layer.js212-217Iterates layers

Key Properties

PropertyLocationTypePurpose
_mapLayer instanceLeafletMapReference to the parent map
_mapToAddLayer instanceLeafletMapTemporary reference during early initialization
_zoomAnimatedLayer instanceBooleanWhether layer participates in zoom animations
_layersMap instanceObjectRegistry of all layers by stamp ID
_zoomBoundLayersMap instanceObjectLayers with zoom constraints
_targetsMap instanceObjectMap of element IDs to layers for event routing