Skip to content

Vector Layers

Vector layers provide Leaflet's system for drawing geometric shapes on maps using scalable vector graphics. The vector layer system consists of shape classes (Path, Polyline, Polygon, Circle, CircleMarker, Rectangle), rendering backends (Canvas, SVG), and geometry processing utilities.

This page provides an overview of the vector layer architecture and how the components work together. For detailed information about individual vector shapes, see page 3.4.1 (Vector Shapes). For renderer implementation details and drawing strategies, see page 3.4.2 (Vector Rendering System). For tile-based raster layers, see page 3.2. For point markers with icons, see page 3.3.

Vector Layer Architecture

The vector layer system is built around a hierarchical class structure with Path as the base class for all vector shapes. The architecture separates geometry definition from rendering implementation through the Renderer abstraction.

Vector Layer Class Hierarchy

SVG
100%

Key Architectural Components

ComponentFilePurpose
Pathsrc/layer/vector/Path.js12Abstract base class providing common styling and renderer integration
Renderersrc/layer/vector/Renderer.js26Abstract base for rendering backends, extends BlanketOverlay
Canvassrc/layer/vector/Canvas.js35Immediate-mode renderer using <canvas> element
SVGsrc/layer/vector/SVG.js35Retained-mode renderer using SVG DOM elements

Each vector layer defines its geometry and styling options, while the renderer handles coordinate transformation, clipping, and actual drawing operations. This separation allows the same vector layer to be rendered with different backends.

Path Base Class

The Path class (src/layer/vector/Path.js12) serves as the abstract base for all vector overlays. It extends Layer and provides common styling options, renderer coordination, and lifecycle management.

Path Options

OptionTypeDefaultDescription
strokeBooleantrueWhether to draw stroke along the path
colorString'#3388ff'Stroke color
weightNumber3Stroke width in pixels
opacityNumber1.0Stroke opacity
lineCapString'round'Shape at end of stroke
lineJoinString'round'Shape at stroke corners
dashArrayStringnullStroke dash pattern
dashOffsetStringnullDistance into dash pattern to start
fillBooleanfalseWhether to fill the path with color
fillColorStringnullFill color (defaults to color)
fillOpacityNumber0.2Fill opacity
fillRuleString'evenodd'How inside of shape is determined
interactiveBooleantrueWhether path responds to pointer events
bubblingPointerEventsBooleantrueWhether events bubble to map

Path Lifecycle and Renderer Coordination

The Path class coordinates with the renderer through a well-defined lifecycle:

Path-Renderer Interaction Lifecycle

SVG
100%

Key methods in the lifecycle:

MethodLocationPurpose
beforeAdd()src/layer/vector/Path.js78-82Obtains renderer from map via map.getRenderer(this)
onAdd()src/layer/vector/Path.js84-88Initializes path with renderer and triggers drawing
onRemove()src/layer/vector/Path.js90-92Removes path from renderer
_reset()src/layer/vector/Path.js134-138Projects coordinates and updates visualization
_clickTolerance()src/layer/vector/Path.js140-144Returns hit detection tolerance in pixels

Vector Shape Types Overview

Leaflet provides five concrete vector shape classes. Each extends Path and adds shape-specific geometry handling.

Shape ClassFileExtendsPurpose
Polylinesrc/layer/vector/Polyline.js51PathConnected line segments, supports multi-lines
Polygonsrc/layer/vector/Polygon.js54PolylineClosed filled shapes with hole support
Rectanglesrc/layer/vector/Rectangle.js30PolygonAxis-aligned rectangular bounds
CircleMarkersrc/layer/vector/CircleMarker.js16PathFixed pixel radius circle
Circlesrc/layer/vector/Circle.js25CircleMarkerGeographic radius in meters

Vector Shape Processing Pipeline

SVG
100%

Shape Processing Steps

Each vector shape follows this general processing pipeline:

  1. Coordinate Conversion - Normalizes input arrays into LatLng instances
  2. Projection - Converts geographic coordinates to pixel coordinates using map CRS
  3. Clipping - Removes portions outside viewport bounds for performance
  4. Simplification - Reduces point count using Douglas-Peucker algorithm (polylines/polygons)
  5. Rendering - Delegates to renderer's _updatePoly() or _updateCircle()

The smoothFactor option (default: 1.0) controls simplification aggressiveness. Higher values improve performance but reduce accuracy.

For detailed information on each shape class's API and geometry handling, see page 3.4.1 (Vector Shapes).

Rendering System Integration

Vector layers delegate all drawing operations to Renderer implementations. The map automatically selects a renderer based on browser capabilities, or developers can specify one explicitly.

Renderer Selection Flow

SVG
100%

Renderer Comparison

FeatureCanvasSVG
Drawing ModeImmediate (all layers to one canvas)Retained (one DOM element per layer)
PerformanceBetter for many layers (100+)Better for few interactive layers
Hit DetectionManual via _containsPoint()Native browser events
Memory UsageLow (single canvas buffer)Higher (DOM nodes per layer)
CSS StylingNot applicableSupported via className option
DOM IntegrationMinimalFull DOM tree
Implementationsrc/layer/vector/Canvas.js35src/layer/vector/SVG.js35

Renderer Interface Methods

Both renderers implement these key methods called by Path:

MethodPurposeCanvas ImplementationSVG Implementation
_initPath(layer)Initialize layer structuresCreates drawing order nodeCreates <path> element
_addPath(layer)Register for renderingLinks to draw listAppends to SVG container
_removePath(layer)Unregister layerUnlinks from draw listRemoves from DOM
_updatePath(layer)Redraw geometryTriggers redraw requestUpdates path d attribute
_updateStyle(layer)Apply style changesTriggers redrawUpdates SVG attributes
_updatePoly(layer, closed)Render polyline/polygonDraws to 2D contextGenerates path string
_updateCircle(layer)Render circleDraws arc to contextGenerates arc path

For detailed information on renderer implementations, drawing order management, and hit detection strategies, see page 3.4.2 (Vector Rendering System).

Coordinate System and Projection Flow

Vector layers work with multiple coordinate systems during rendering. Understanding this flow is essential for performance optimization and correct positioning.

Coordinate Transformation Pipeline

SVG
100%

Coordinate Systems

SystemTypeOriginUsage
LatLngGeographicEquator/Prime MeridianInput coordinates from user
Layer PointPixelMap pixel origin (zoom dependent)Internal geometry calculations
Container PointPixelTop-left of map containerDOM positioning (panes, overlays)

The _project() method in each shape class converts geographic coordinates to layer points using the map's CRS (Coordinate Reference System). The renderer then uses these layer points for drawing.

Example Projection Implementation:

// From Polyline._projectLatlngs()
const ring = latlngs.map(latlng => this._map.latLngToLayerPoint(latlng));

Styling and Interaction

Vector layers support dynamic styling and user interaction through the path options system and event handling integration.

Dynamic Styling

The setStyle() method allows runtime style changes:

layer.setStyle({
    color: 'red',
    weight: 5,
    opacity: 0.8
});

Style updates trigger renderer-specific update methods that efficiently apply visual changes without recreating geometry data.

Layer Ordering

Vector layers support z-order manipulation through bringToFront() and bringToBack() methods. The implementation varies by renderer:

  • Canvas: Maintains drawing order list and triggers redraws
  • SVG: Reorders DOM elements using toFront()/toBack()