Skip to content

Instantly share code, notes, and snippets.

@mourner
Last active December 30, 2015 12:29
Show Gist options
  • Select an option

  • Save mourner/7829409 to your computer and use it in GitHub Desktop.

Select an option

Save mourner/7829409 to your computer and use it in GitHub Desktop.
Leaflet vector layers refactoring

Leaflet vector layers refactoring

The goal is to refactor vector layers code in Leaflet to make it possible to use different rendering backends (Canvas, SVG, etc.) for different layers on the same map and switch between them easily, in addition to much cleaner and more transparent code. This will also open it up for interesting extensions, like custom shapes, indexing layers with RBush for fast interaction features, etc.

This is the file structure / responsibilities breakdown I currently have in mind for this.

Files & Classes

class description
Path extends Layer, base class for all vector layers (without renderer-specific code)
Polyline extends Path, projects/clips/simplifies latlngs, delegates drawing to Canvas/SVG.Poly
Polygon extends Polyline, clips polygon latlngs, delegates drawing to Canvas/SVG.Poly
MultiPolyline extends Polyline, handles multiple rings in the API
MultiPolygon extends Polygon, handles multiple rings in the API
Rectangle extends Polygon
CircleMarker extends Path, delegates drawing to Canvas/SVG.Circle
Circle extends Path, scales radius, delegates drawing to Canvas/SVG.Circle
Renderer extends Layer, handles positioning, bounds and zoom animation for an SVG/VML/Canvas root
SVG extends Renderer, adds SVG root and handles generic SVG stuff (elements, styles, events, etc.)
SVG.VML patches SVG with VML-specific code (since other code is pretty similar)
SVG.Poly static, converts sets of pixel coords into an SVG path string for polylines/polygons/multipoly
SVG.Circle static, converts pixel coords / radius into an SVG path for circle
Canvas extends Renderer, adds Canvas root and handles generic Canvas stuff
Canvas.Poly static, given sets of pixel coords, draws polylines/polygons/multipoly on a Canvas; also does hit detection
Canvas.Circle static, given pixel coords / radius, draws a circle; also does hit detection

Sample workflow

L.polygon(latlngs).addTo(map);
  • as polyline, figure out what renderer to use (Canvas/SVG) (can be given a preference in options)
  • as path, get a corresponding viewport to draw on (it gets created and added to the map if necessary, or reused)
  • as polyline, on viewreset: project all latlngs
  • as polygon, on moveend: clip points with polygon clipping algorithm
  • as polyline, on moveend: simplify clipped points for a given map view, then send them for drawing by SVG.Poly or Canvas.Poly depending on the chosen renderer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment