Leaflet

An Open-Source JavaScript Library for Mobile-Friendly Interactive Maps by CloudMade



This reference reflects Leaflet 0.4. You can find docs for the in-progress master version in reference.html of gh-pages-master branch.

L.Map

The central class of the API — it is used to create a map on a page and manipulate it.

Usage example

// initialize the map on the "map" div with a given center and zoom
var map = new L.Map('map', {
	center: new L.LatLng(51.505, -0.09),
	zoom: 13
});

// create a CloudMade tile layer
var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/YOUR-API-KEY/997/256/{z}/{x}/{y}.png',
	cloudmade = new L.TileLayer(cloudmadeUrl, {maxZoom: 18});

// add the CloudMade layer to the map
map.addLayer(cloudmade);

Constructor

Constructor Description
L.Map( <HTMLElement|String> id, <Map options> options? ) Instantiates a map object given a div element (or its id) and optionally an object literal with map options described below.

Options

Option Type Default value Description
center LatLng null Initial geographical center of the map.
zoom Number null Initial map zoom.
layers ILayer[] [] Layers that will be added to the map initially.
minZoom Number 0 Minimum zoom level of the map. Overrides any minZoom set on map layers.
maxZoom Number 18 Maximum zoom level of the map. This overrides any maxZoom set on map layers.
maxBounds LatLngBounds null When this option is set, the map restricts the view to the given geographical bounds, bouncing the user back when he tries to pan outside the view, and also not allowing to zoom out to a view that's larger than the given bounds (depending on the map size). To set the restriction dynamically, use setMaxBounds method
crs CRS L.CRS.EPSG3857 Coordinate Reference System to use. Don't change this if you're not sure what it means.
dragging Boolean true Whether the map be draggable with mouse/touch or not.
touchZoom Boolean true Whether the map can be zoomed by touch-dragging with two fingers.
scrollWheelZoom Boolean true Whether the map can be zoomed by using the mouse wheel.
doubleClickZoom Boolean true Whether the map can be zoomed in by double clicking on it.
boxZoom Boolean true Whether the map can be zoomed to a rectangular area specified by dragging the mouse while pressing shift.
zoomControl Boolean true Whether the zoom control is added to the map by default.
attributionControl Boolean true Whether the attribution control is added to the map by default.
trackResize Boolean true Whether the map automatically handles browser window resize to update itself.
fadeAnimation Boolean depends Whether the tile fade animation is enabled. By default it's enabled in all browsers that support CSS3 Transitions except Android.
zoomAnimation Boolean depends Whether the tile zoom animation is enabled. By default it's enabled in all browsers that support CSS3 Transitions except Android.
markerZoomAnimation Boolean depends Whether markers animate their zoom with the zoom animation, if disabled they will disappear for the length of the animation. By default it's enabled in all browsers that support CSS3 Transitions except Android.
closePopupOnClick Boolean true Set it to false if you don't want popups to close when user clicks the map.
worldCopyJump Boolean true With this option enabled, the map tracks when you pan to another "copy" of the world and moves all overlays like markers and vector layers there.

Events

You can subscribe to the following events using these methods.

Event Data Description
click MouseEvent Fired when the user clicks (or taps) the map.
dblclick MouseEvent Fired when the user double-clicks (or double-taps) the map.
mousedown MouseEvent Fired when the user pushes the mouse button on the map.
mouseenter MouseEvent Fired when the mouse enters the map.
mouseleave MouseEvent Fired when the mouse leaves the map.
mousemove MouseEvent Fired while the mouse moves over the map.
contextmenu MouseEvent Fired when the user pushes the right mouse button on the map.
preclick MouseEvent Fired before mouse click on the map (sometimes useful when you want something to happen on click before any existing click handlers start running).
load Event Fired when the map is initialized (when its center and zoom are set for the first time).
viewreset Event Fired when the map needs to redraw its content (this usually happens on map zoom or load). Very useful for creating custom overlays.
movestart Event Fired when the view of the map starts changing (e.g. user starts dragging the map).
move Event Fired on any movement of the map view.
moveend Event Fired when the view of the map ends changed (e.g. user stopped dragging the map).
dragstart Event Fired when the user starts dragging the map.
drag Event Fired repeatedly while the user drags the map.
dragend Event Fired when the user stops dragging the map.
zoomstart Event Fired when the map zoom is about to change (e.g. before zoom animation).
zoomend Event Fired when the map zoom changes.
layeradd LayerEvent Fired when a new layer is added to the map.
layerremove LayerEvent Fired when some layer is removed from the map.
locationfound LocationEvent Fired when geolocation (using locate or locateAndSetView method) went successfully.
locationerror ErrorEvent Fired when geolocation (using locate or locateAndSetView method) failed.
popupopen PopupEvent Fired when a popup is opened (using openPopup method).
popupclose PopupEvent Fired when a popup is closed (using closePopup method).

Methods that modify map state

Method Returns Description
setView( <LatLng> center, <Number> zoom, <Boolean>forceReset? ) this Sets the view of the map (geographical center and zoom). If forceReset is set to true, the map is reloaded even if it's eligible for pan or zoom animation (false by default).
setZoom( <Number> zoom ) this Sets the zoom of the map.
zoomIn() this Increases the zoom of the map by 1.
zoomOut() this Decreases the zoom of the map by 1.
fitBounds( <LatLngBounds> bounds ) this Sets a map view that contains the given geographical bounds with the maximum zoom level possible.
fitWorld() this Sets a map view that mostly contains the whole world with the maximum zoom level possible.
panTo( <LatLng> latlng ) this Pans the map to a given center. Makes an animated pan if new center is not more than one screen away from the current one.
panInsideBounds( <LatLngBounds> bounds ) this Pans the map to the closest view that would lie inside the given bounds (if it's not already).
panBy( <Point> point) this Pans the map by a given number of pixels (animated).
invalidateSize() this Checks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically.
setMaxBounds( <LatLngBounds> bounds ) this Restricts the map view to the given bounds (see map maxBounds option).
locate( <Locate options> options? ) this Tries to locate the user using Geolocation API, firing locationfound event with location data on success or locationerror event on failure. See Locate options for more details.
locateAndSetView( <Number> maxZoom?, <Locate options> options? ) this Automatically sets the map view to the user location with respect to detection accuracy (or to the world view if geolocation failed). A shortcut for map.locate({setView: true, maxZoom: maxZoom});.
stopLocate() this Stops watching location previously initiated by map.locate({watch: true}).

Methods that get map state

Method Returns Description
getCenter() LatLng Returns the geographical center of the map view.
getZoom() Number Returns the current zoom of the map view.
getMinZoom() Number Returns the minimum zoom level of the map.
getMaxZoom() Number Returns the maximum zoom level of the map.
getBounds() LatLngBounds Returns the LatLngBounds of the current map view.
getBoundsZoom( <LatLngBounds> bounds, <Boolean> inside? ) Number Returns the maximum zoom level on which the given bounds fit to the map view in its entirety. If inside (optional) is set to true, the method instead returns the minimum zoom level on which the map view fits into the given bounds in its entirety.
getSize() Point Returns the current size of the map container.
getPixelBounds() Bounds Returns the bounds of the current map view in projected pixel coordinates (sometimes useful in layer and overlay implementations).
getPixelOrigin() Point Returns the projected pixel coordinates of the top left point of the map layer (useful in custom layer and overlay implementations).

Methods for layers and controls

addLayer( <ILayer> layer, <Boolean> insertAtTheBottom? ) this Adds the given layer to the map. If optional insertAtTheBottom is set to true, the layer is inserted under all others (useful when switching base tile layers).
removeLayer( <ILayer> layer ) this Removes the given layer from the map.
hasLayer( <ILayer> layer ) Boolean Returns true if the given layer is currently added to the map.
openPopup( <Popup> popup ) this Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
closePopup() this Closes the popup opened with openPopup.
addControl( <IControl> control ) this Adds the given control to the map.
removeControl( <IControl> control ) this Removes the given control from the map.

Conversion methods

Method Returns Description
latLngToLayerPoint( <LatLng> latlng ) Point Returns the map layer point that corresponds to the given geographical coordinates (useful for placing overlays on the map).
layerPointToLatLng( <Point> point ) LatLng Returns the geographical coordinates of a given map layer point.
mouseEventToContainerPoint( <MouseEvent> event ) Point Returns the pixel coordinates of a mouse click (relative to the top left corner of the map) given its event object.
mouseEventToLayerPoint( <MouseEvent> event ) Point Returns the pixel coordinates of a mouse click relative to the map layer given its event object.
mouseEventToLatLng( <MouseEvent> event ) LatLng Returns the geographical coordinates of the point the mouse clicked on given the click's event object.
containerPointToLayerPoint( <Point> point ) Point Converts the point relative to the map container to a point relative to the map layer.
layerPointToContainerPoint( <Point> point ) Point Converts the point relative to the map layer to a point relative to the map container.
project( <LatLng> latlng, <Number> zoom? ) Point Projects the given geographical coordinates to pixel coordinates for the given zoom level (current zoom level by default).
unproject( <Point> point, <Number> zoom? ) LatLng Projects the given pixel coordinates to geographical coordinates for the given zoom level (current zoom level by default).

Other methods

Method Returns Description
getContainer() HTMLElement Returns the container element of the map.
getPanes() MapPanes Returns an object with different map panes (to render overlays in).

Locate options

Option Type Default Description
watch Boolean false If true, starts continous watching of location changes (instead of detecting it once) using W3C watchPosition method. You can later stop watching using map.stopLocate() method.
setView Boolean false If true, automatically sets the map view to the user location with respect to detection accuracy.
maxZoom Number Infinity The maximum zoom for automatic view setting when using `setView` option.
timeout Number 10000 Number of millisecond to wait for a response from geolocation before firing a locationerror event.
maximumAge Number 0 Maximum age of detected location. If less than this amount of milliseconds passed since last geolocation response, locate will return a cached location.
enableHighAccuracy Boolean false Enables high accuracy, see description in the W3C spec.

Properties

Map properties include interaction handlers that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging or touch zoom (see IHandler methods). Example:

map.doubleClickZoom.disable();

You can also access default map controls like attribution control through map properties:

map.attributionControl.addAttribution("Earthquake data &copy; GeoNames");
Property Type Description
dragging IHandler Map dragging handler (by both mouse and touch).
touchZoom IHandler Touch zoom handler.
doubleClickZoom IHandler Double click zoom handler.
scrollWheelZoom IHandler Scroll wheel zoom handler.
boxZoom IHandler Box (shift-drag with mouse) zoom handler.
zoomControl Control.Zoom Zoom control.
attributionControl Control.Attribution Attribution control.

Projections

You can specify different CRS for map to use through its crs option. Here's the list of available CRS:

CRS Data
L.CRS.EPSG3857 EPSG:3857 (Spherical Mercator), used by most of commercial map providers (CloudMade, Google, Yahoo, Bing, etc.).
L.CRS.EPSG4326 EPSG:4326 (Plate Carree), very popular among GIS enthusiasts.
L.CRS.EPSG3395 EPSG:3395 (True Mercator), used by some map providers.

Map panes

An object literal (returned by map.getPanes) that contains different map panes that you can use to put your custom overlays in. The difference is mostly in zIndex order that such overlays get.

Property Type Description
mapPane HTMLElement Pane that contains all other map panes.
tilePane HTMLElement Pane for tile layers.
objectsPane HTMLElement Pane that contains all the panes except tile pane.
shadowPane HTMLElement Pane for overlay shadows (e.g. marker shadows).
overlayPane HTMLElement Pane for overlays like polylines and polygons.
markerPane HTMLElement Pane for marker icons.
popupPane HTMLElement Pane for popups.

L.Marker

Used to put markers on the map.

Usage example

var marker = new L.Marker(latlng);
map.addLayer(marker);

Constructor

Constructor Description
L.Marker( <LatLng> latlng, <Marker options> options? ) Instantiates a Marker object given a geographical point and optionally an options object.

Options

Option Type Default value Description
icon L.Icon L.Icon Icon class to use for rendering the marker. See Icon documentation for details on how to customize the marker icon.
clickable Boolean true If false, the marker will not emit mouse events and will act as a part of the underlying map.
draggable Boolean false Whether the marker is draggable with mouse/touch or not.
title String Text for the browser tooltip that appear on marker hover (no tooltip by default).
zIndexOffset Number 0 By default, marker images zIndex is set automatically based on its latitude. You this option if you want to put the marker on top of all others (or below), specifying a high value like 1000 (or high negative value, respectively).

Events

You can subscribe to the following events using these methods.

Event Data Description
click MouseEvent Fired when the user clicks (or taps) the marker.
dblclick MouseEvent Fired when the user double-clicks (or double-taps) the marker.
mousedown MouseEvent Fired when the user pushes the mouse button on the marker.
mouseover MouseEvent Fired when the mouse enters the marker.
mouseout MouseEvent Fired when the mouse leaves the marker.
dragstart Event Fired when the user starts dragging the marker.
drag Event Fired repeatedly while the user drags the marker.
dragend Event Fired when the user stops dragging the marker.

Methods

Method Returns Description
getLatLng() LatLng Returns the current geographical position of the marker.
setLatLng( <LatLng> latlng ) this Changes the marker position to the given point.
setIcon( <Icon> icon ) this Changes the marker icon.
setZIndexOffset( <Number> offset ) this Changes the zIndex offset of the marker.
bindPopup( <String> htmlContent, <Popup options> options? ) this Binds a popup with a particular HTML content to a click on this marker. You can also open the bound popup with the Marker openPopup method.
unbindPopup() this Unbinds the popup previously bound to the marker with bindPopup.
openPopup() this Opens the popup previously bound by the bindPopup method.
closePopup() this Closes the bound popup of the marker if it's opened.

Interaction handlers

Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see IHandler methods). Example:

marker.dragging.disable();
Property Type Description
dragging IHandler Marker dragging handler (by both mouse and touch).

Used to open popups in certain places of the map. Use Map#openPopup to open popups while making sure that only one popup is open at one time (recommended for usability), or use Map#addLayer to open as many as you want.

Usage example

If you want to just bind a popup to marker click and then open it, it's really easy:

marker.bindPopup(popupContent).openPopup();

Path overlays like polylines also have a bindPopup method. Here's a more complicated way to open a popup on a map:

var popupContent = '<p>Hello world!<br />This is a nice popup.</p>',
	popup = new L.Popup();

popup.setLatLng(latlng);
popup.setContent(popupContent);

map.openPopup(popup);

Constructor

Constructor Description
L.Popup( <Popup options> options?, <object> source? ) Instantiates a Popup object given an optional options object that describes its appearance and location and an optional object that is used to tag the popup with a reference to the source object to which it refers.
Option Type Default value Description
maxWidth Number 300 Max width of the popup.
maxWidth Number 50 Min width of the popup.
autoPan Boolean true Set it to false if you don't want the map to do panning animation to fit the opened popup.
closeButton Boolean true Controls the presense of a close button in the popup.
offset Point Point(0, 0) The offset of the popup position. Useful to control the anchor of the popup when opening it on some overlays.
autoPanPadding Point Point(5, 5) The margin between the popup and the edges of the map view after autopanning was performed.

Methods

Method Returns Description
setLatLng( <LatLng> latlng ) this Sets the geographical point where the popup will open.
setContent( <String> htmlContent ) this Sets the HTML content of the popup.

L.TileLayer

Used to load and display tile layers on the map, implements ILayer interface.

Usage example

var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/YOUR-API-KEY/997/256/{z}/{x}/{y}.png',
	cloudmade = new L.TileLayer(cloudmadeUrl, {maxZoom: 18});

Constructor

Constructor Description
L.TileLayer( <String> urlTemplate, <TileLayer options> options? ) Instantiates a tile layer object given a URL template and optionally an options object.

URL template

A string of the following form:

'http://{s}.somedomain.com/blabla/{z}/{x}/{y}.png'

{s} means one of the randomly chosen subdomains (their range is specified in options; a, b or c by default, can be omitted), {z} — zoom level, {x} and {y} — tile coordinates.

You can use custom keys in the template, which will be evaluated from TileLayer options, like this:

new L.TileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});

Options

Option Type Default value Description
minZoom Number 0 Minimum zoom number.
maxZoom Number 18 Maximum zoom number.
tileSize Number 256 Tile size (width and height in pixels, assuming tiles are square).
subdomains String or String[] 'abc' Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.
errorTileUrl String '' URL to the tile image to show in place of the tile that failed to load.
attribution String '' e.g. "© CloudMade" — the string used by the attribution control, describes the layer data.
scheme String 'xyz' Either 'xyz' or 'tms', affects tile numbering (TMS servers use inverse Y axis numbering).
continuousWorld Boolean false If set to true, the tile coordinates won't be wrapped by world width (-180 to 180 longitude) or clamped to lie within world height (-90 to 90). Use this if you use Leaflet for maps that don't reflect the real world (e.g. game, indoor or photo maps).
noWrap Boolean false If set to true, the tiles just won't load outside the world width (-180 to 180 longitude) instead of repeating.
zoomOffset Number 0 The zoom number used in tile URLs will be offset with this value.
zoomReverse Boolean false If set to true, the zoom number used in tile URLs will be reversed (maxZoom - zoom instead of zoom)
opacity Number 1.0 The opacity of the tile layer.
unloadInvisibleTiles Boolean depends If true, all the tiles that are not visible after panning are removed (for better performance). true by default on mobile WebKit, otherwise false.
updateWhenIdle Boolean depends If false, new tiles are loaded during panning, otherwise only after it (for better performance). true by default on mobile WebKit, otherwise false.
reuseTiles Boolean false If true, all the tiles that are not visible after panning are placed in a reuse queue from which they will be fetched when new tiles become visible (as opposed to dynamically creating new ones). This will in theory keep memory usage low and eliminate the need for reserving new memory whenever a new tile is needed.

Methods

Method Returns Description
setOpacity( <Number> opacity ) this Changes the opacity of the tile layer.
redraw() - Calling redraw will cause the drawTile method to be called for all tiles. May be used for updating dynamic content drawn on the Canvas

L.TileLayer.WMS

Used to display WMS services as tile layers on the map. Extends TileLayer, implements ILayer interface.

Usage example

var nexrad = new L.TileLayer.WMS("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
	layers: 'nexrad-n0r-900913',
	format: 'image/png',
	transparent: true,
	attribution: "Weather data © 2012 IEM Nexrad"
});

Constructor

Constructor Description
L.TileLayer.WMS( <String> baseUrl, <TileLayer.WMS options> options ) Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.

Options

Includes all TileLayer options and additionally:

Option Type Default value Description
layers String - (required) Comma-separated list of WMS layers to show.
styles String Comma-separated list of WMS styles.
format String image/jpeg WMS image format (use 'image/png' for layers with transparency).
transparent Boolean false If true, the WMS service will return images with transparency.
version String 1.1.1 Version of the WMS service to use.

L.TileLayer.Canvas

Used to create Canvas-based tile layers where tiles get drawn on the browser side. Extends TileLayer, implements ILayer interface.

Usage example

var canvasTiles = new L.TileLayer.Canvas();

canvasTiles.drawTile = function(canvas, tilePoint, zoom) {
	var ctx = canvas.getContext('2d');
	// draw something on the tile canvas
}

Constructor

Constructor Description
L.TileLayer.Canvas( <TileLayer options> options? ) Instantiates a Canvas tile layer object given an options object (optionally).

Methods

Method Returns Description
drawTile( <HTMLCanvasElement> canvas, <Point> tilePoint, <Number> zoom ) this You need to define this method after creating the instance to draw tiles; canvas is the actual canvas tile on which you can draw, tilePoint represents the tile numbers, and zoom is the current zoom.
redraw() - Calling redraw will cause the drawTile method to be called for all tiles. May be used for updating dynamic content drawn on the Canvas

L.ImageOverlay

Used to load and display a single image over specific bounds of the map, implements ILayer interface.

Usage example

var imageBounds = new L.LatLngBounds(
		new L.LatLng(40.712216,-74.22655),
		new L.LatLng(40.773941,-74.12544));

var image = new L.ImageOverlay(
		"http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg", imageBounds);

Constructor

Constructor Description
L.ImageOverlay( <String> imageUrl, <LatLngBounds> bounds ) Instantiates an image overlay object given the URL of the image and the geographical bounds it is tied to.

L.Path

An abstract class that contains options and constants shared between vector overlays (Polygon, Polyline, Circle). Do not use it directly.

Options

Option Type Default value Description
stroke Boolean true Whether to draw stroke along the path. Set it to false to disable borders on polygons or circles.
color String '#03f' Stroke color.
weight Number 5 Stroke width in pixels.
opacity Number 0.5 Stroke opacity.
fill Boolean depends Whether to fill the path with color. Set it to false to disable filling on polygons or circles.
fillColor String same as color Fill color.
fillOpacity Number 0.2 Fill opacity.
clickable Boolean true If false, the vector will not emit mouse events and will act as a part of the underlying map.

Events

You can subscribe to the following events using these methods.

Event Data Description
click MouseEvent Fired when the user clicks (or taps) the object.
dblclick MouseEvent Fired when the user double-clicks (or double-taps) the object.
mousedown MouseEvent Fired when the user pushes the mouse button on the object.
mouseover MouseEvent Fired when the mouse enters the object.
mouseout MouseEvent Fired when the mouse leaves the object.

Constants

Constant Type Value Description
L.Path.SVG Boolean depends True if SVG is used for vector rendering (true for most modern browsers).
L.Path.VML Boolean depends True if VML is used for vector rendering (IE 6-8).
L.Path.CANVAS Boolean depends True if Canvas is used for vector rendering (Android 2). You can also force this by setting global variable L_PREFER_CANVAS to true before the Leaflet include on your page — sometimes it can increase performance dramatically when rendering thousands of circle markers, but currently suffers from a bug that causes removing such layers to be extremely slow.
L.Path.CLIP_PADDING Number 0.5 for SVG
0.02 for VML
How much to extend the clip area around the map view (relative to its size, e.g. 0.5 is half the screen in each direction). Smaller values mean that you will see clipped ends of paths while you're dragging the map, and bigger values decrease drawing performance.

Methods

Method Returns Description
bindPopup( <String> htmlContent, <Popup options> options? ) this Binds a popup with a particular HTML content to a click on this path.
setStyle( <Path options> object ) this Changes the appearance of a Path based on the options in the Path options object.
getBounds() LatLngBounds Returns the LatLngBounds of the path.

L.Polyline

A class for drawing polyline overlays on a map. Extends Path. Use Map#addLayer to add it to the map.

Usage example

// create a red polyline from an arrays of LatLng points
var polyline = new L.Polyline(latlngs, {color: 'red'});

// zoom the map to the polyline
map.fitBounds(new L.LatLngBounds(latlngs));

// add the polyline to the map
map.addLayer(polyline);

Constructor

Constructor Description
L.Polyline( <LatLng[]> latlngs, <Polyline options> options? ) Instantiates a polyline object given an array of geographical points and optionally an options object.

Options

You can use Path options and additionally the following options:

Option Type Default value Description
smoothFactor Number 1.0 How much to simplify the polyline on each zoom level. More means better performance and smoother look, and less means more accurate representation.
noClip Boolean false Disabled polyline clipping.

Methods

You can use Path methods and additionally the following methods:

Method Returns Description
addLatLng( <LatLng> latlng ) this Adds a given point to the polyline.
setLatLngs( <LatLng[]> latlngs ) this Replaces all the points in the polyline with the given array of geographical points.
getLatLngs() LatLng[] Returns an array of the points in the path.
spliceLatLngs( <Number> index, <Number> pointsToRemove, <LatLng> latlng1?, <LatLng> latlng2?, … ) LatLng[] Allows adding, removing or replacing points in the polyline. Syntax is the same as in Array#splice. Returns the array of removed points (if any).
getBounds() LatLngBounds Returns the LatLngBounds of the polyline.

L.MultiPolyline

Extends FeatureGroup to allow creating multi-polylines (single layer that consists of several polylines that share styling/popup).

Constructor

Constructor Description
L.MultiPolyline( <LatLng[][]> latlngs, <Polyline options> options? ) Instantiates a multi-polyline object given an array of arrays of geographical points (one for each individual polyline) and optionally an options object.

L.Polygon

A class for drawing polygon overlays on a map. Extends Polyline. Use Map#addLayer to add it to the map.

Constructor

Constructor Description
L.Polygon( <LatLng[]> latlngs, <Polyline options> options? ) Instantiates a polygon object given an array of geographical points and optionally an options object (the same as for Polyline). You can also create a polygon with holes by passing an array of arrays of latlngs, with the first latlngs array representing the exterior ring while the remaining represent the holes inside.

Polygon the same options and methods as Polyline.

L.MultiPolygon

Extends FeatureGroup to allow creating multi-polygons (single layer that consists of several polygons that share styling/popup).

Constructor

Constructor Description
L.MultiPolygon( <LatLng[][]> latlngs, <Polyline options> options? ) Instantiates a multi-polyline object given an array of latlngs arrays (one for each individual polygon) and optionally an options object (the same as for MultiPolyline).

L.Rectangle

A class for drawing rectangle overlays on a map. Extends Polygon. Use Map#addLayer to add it to the map.

Usage example

// create an orange rectangle from a LatLngBounds
var bounds = new L.LatLngBounds(new L.LatLng(54.559322, -5.767822), new L.LatLng(56.1210604, -3.021240));

// zoom the map to the rectangle
map.fitBounds(bounds);

// create the rectangle
var rectangle = new L.Rectangle(bounds, {
	fillColor: "#ff7800",
	color: "#000000",
	opacity: 1,
	weight: 2
});

// add the rectangle to the map
map.addLayer(rectangle);

Constructor

Constructor Description
L.Rectangle( <LatLngBounds> bounds, <Path options> options? ) Instantiates a rectangle object with the given geographical bounds and optionally an options object.

Methods

You can use Path methods and additionally the following methods:

Method Returns Description
setBounds( <LatLngBounds> bounds ) this Redraws the rectangle with the passed bounds.

L.Circle

A class for drawing circle overlays on a map. Extends Path. Use Map#addLayer to add it to the map.

Constructor

Constructor Description
L.Circle( <LatLng> latlng, <Number> radius, <Path options> options? ) Instantiates a circle object given a geographical point, a radius in meters and optionally an options object.

Methods

Method Returns Description
getLatLng() LatLng Returns the current geographical position of the circle.
getRadius() Number Returns the current radius of a circle. Units are in meters.
setLatLng( <LatLng> latlng ) this Sets the position of a circle to a new location.
setRadius( <Number> radius ) this Sets the radius of a circle. Units are in meters.

L.CircleMarker

A circle of a fixed size with radius specified in pixels. Extends Circle. Use Map#addLayer to add it to the map.

Constructor

Constructor Description
L.CircleMarker( <LatLng> latlng, <Path options> options? ) Instantiates a circle marker given a geographical point and optionally an options object. The default radius is 10 and can be altered by passing a "radius" member in the path options object.

Methods

Method Returns Description
setLatLng( <LatLng> latlng ) this Sets the position of a circle marker to a new location.
setRadius( <Number> radius ) this Sets the radius of a circle marker. Units are in pixels.

L.LayerGroup

Used to group several layers and handle them as one. If you add it to the map, any layers added or removed from the group will be added/removed on the map as well. Implements ILayer interface.

var group = new L.LayerGroup();

group.addLayer(marker1);
group.addLayer(marker2);
group.addLayer(polyline);

map.addLayer(group);

Constructor

Constructor Description
L.LayerGroup( <ILayer[]> layers? ) Create a layer group, optionally given an initial set of layers.

Methods

Method Returns Description
addLayer( <ILayer> layer ) this Adds a given layer to the group.
removeLayer( <ILayer> layer ) this Removes a given layer from the group.
clearLayers() this Removes all the layers from the group.

L.FeatureGroup

Extended LayerGroup that also has mouse events (propagated from members of the group) and a shared bindPopup method. Implements IFeature interface.

var group = new L.FeatureGroup([marker1, marker2, polyline]);

group.bindPopup('Hello world!');

group.on('click', function() {
	alert('Clicked on a group!');
});

map.addLayer(group);

Constructor

Constructor Description
L.FeatureGroup( <IFeature[]> layers? ) Create a layer group, optionally given an initial set of layers.

Methods

Has all LayerGroup methods and additionally:

Method Returns Description
bindPopup( <String> htmlContent, <Popup options> options? ) this Binds a popup with a particular HTML content to a click on any layer from the group.
getBounds() LatLngBounds Returns the LatLngBounds of the Feature Group.

Events

You can subscribe to the following events using these methods.

Event Data Description
click MouseEvent Fired when the user clicks (or taps) the group.
dblclick MouseEvent Fired when the user double-clicks (or double-taps) the group.
mouseover MouseEvent Fired when the mouse enters the group.
mouseout MouseEvent Fired when the mouse leaves the group.

L.GeoJSON

Represents a GeoJSON layer. Allows you to parse GeoJSON data and display on the map. Extends FeatureGroup.

var geojson = new L.GeoJSON();

geojson.on('featureparse', function(e) {
	// do something with e.layer depending on e.properties
});
geojson.addGeoJSON(geojsonObj);

map.addLayer(geojson);

Constructor

Constructor Description
L.GeoJSON( <Object> geojson?, <GeoJSON options> options? ) Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format to display on the map (you can alternatively add it with addGeoJSON method) and an options object.

Options

Option Type Default value Description
pointToLayer Function null Function of the form (LatLng) -> ILayer that will be used for creating layers for GeoJSON points (if not specified, markers will be created).

Events

You can subscribe to the following events using these methods.

Event Data Description
featureparse GeoJSONEvent Fired before an object converted from a GeoJSON feature is added to the map. This event can be used to add interaction or change styling of objects depending on feature properties.

Methods

Method Returns Description
addGeoJSON( <Object> geojson ) Boolean Adds a GeoJSON object to the layer.

Static methods

Method Returns Description
geometryToLayer( <Object> geojson, <Function> pointToLayer? ) ILayer Creates a layer from a given GeoJSON geometry.
coordsToLatlng( <Array> coords, <Boolean> reverse? ) LatLng Creates a LatLng object from an array of 2 numbers (latitude, longitude) used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted as (longitude, latitude).
coordsToLatlngs( <Array> coords, <Number> levelsDeep?, <Boolean> reverse? ) Array Creates a multidimensional array of LatLng objects from a GeoJSON coordinates array. levelsDeep specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default). If reverse is set to true, the numbers will be interpreted as (longitude, latitude).

L.LatLng

Represents a geographical point with a certain latitude and longitude.

var latlng = new L.LatLng(50.5, 30.5);

Constructor

Constructor Description
L.LatLng( <Number> latitude, <Number> longitude, <Boolean> noWrap? ) Creates an object representing a geographical point with the given latitude and longitude. Wraps longitude to lie between -180 and 180 and clamps longitude between -90 and 90 by default — you can disable this with the noWrap argument.

Properties

Property Type Description
lat Number Latitude in degrees.
lng Number Longitude in degrees.

Methods

Method Returns Description
distanceTo( <LatLng> otherLatlng ) Number Returns the distance (in meters) to the given LatLng calculated using the Haversine formula. See description on wikipedia
equals( <LatLng> otherLatlng ) Boolean Returns true if the given LatLng point is at the same position (within a small margin of error).
toString() String Returns a string representation of the point (for debugging purposes).

Constants

Constant Type Value Description
DEG_TO_RAD Number Math.PI / 180 A multiplier for converting degrees into radians.
RAD_TO_DEG Number 180 / Math.PI A multiplier for converting radians into degrees.
MAX_MARGIN Number 1.0E-9 Max margin of error for the equality check.

L.LatLngBounds

Represents a rectangular geographical area on a map.

var southWest = new L.LatLng(40.712,-74.227),
	northEast = new L.LatLng(40.774,-74.125),
	bounds = new L.LatLngBounds(southWest, northEast);

Constructor

Constructor Description
L.LatLngBounds( <LatLng> southWest, <LatLng> northEast ) Creates a LatLngBounds object by defining south-west and north-east corners of the rectangle.
L.LatLngBounds( <LatLng[]> latlngs ) Creates a LatLngBounds object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with fitBounds.

Methods

Method Returns Description
extend( <LatLng|LatLngBounds> latlng ) this Extends the bounds to contain the given point or bounds.
getSouthWest() LatLng Returns the south-west point of the bounds.
getNorthEast() LatLng Returns the north-east point of the bounds.
getNorthWest() LatLng Returns the north-west point of the bounds.
getSouthEast() LatLng Returns the south-east point of the bounds.
getCenter() LatLng Returns the center point of the bounds.
contains( <LatLngBounds> otherBounds ) Boolean Returns true if the rectangle contains the given one.
contains( <LatLng> latlng ) Boolean Returns true if the rectangle contains the given point.
intersects( <LatLngBounds> otherBounds ) Boolean Returns true if the rectangle intersects the given bounds.
equals( <LatLngBounds> otherBounds ) Boolean Returns true if the rectangle is equivalent (within a small margin of error) to the given bounds.
toBBoxString() String Returns a string with bounding box coordinates in a "southwest_lng,southwest_lat,northeast_lng,northeast_lat" format. Useful for sending requests to web services that return geo data.

L.Point

Represents a point with x and y coordinates in pixels.

Constructor

Constructor Description
L.Point( <Number> x, <Number> y, <Boolean> round? ) Creates a Point object with the given x and y coordinates. If optional round is set to true, rounds the x and y values.

Properties

Property Type Description
x Number The x coordinate.
y Number The y coordinate.

Methods

Method Returns Description
add( <Point> otherPoint ) Point Returns the result of addition of the current and the given points.
subtract( <Point> otherPoint ) Point Returns the result of subtraction of the given point from the current.
multiplyBy( <Number> number ) Point Returns the result of multiplication of the current point by the given number.
divideBy( <Number> number, <Boolean> round? ) Point Returns the result of division of the current point by the given number. If optional round is set to true, returns a rounded result.
distanceTo( <Point> otherPoint ) Number Returns the distance between the current and the given points.
clone() Point Returns a copy of the current point.
round() Point Returns a copy of the current point with rounded coordinates.
toString() String Returns a string representation of the point for debugging purposes.

L.Bounds

Represents a rectangular area in pixel coordinates.

var p1 = new L.Point(10, 10),
	p2 = new L.Point(40, 60),
	bounds = new L.Bounds(p1, p2);

Constructor

Constructor Description
L.Bounds( <Point> topLeft, <Point> bottomRight ) Creates a Bounds object from two coordinates (usually top-left and bottom-right corners).
L.LatLngBounds( <Point[]> points ) Creates a Bounds object defined by the points it contains.

Properties

Property Type Description
min Point The top left corner of the rectangle.
max Point The bottom right corner of the rectangle.

Methods

Method Returns Description
extend( <Point> point ) - Extends the bounds to contain the given point.
getCenter() Point Returns the center point of the bounds.
contains( <Bounds> otherBounds ) Boolean Returns true if the rectangle contains the given one.
contains( <Point> point ) Boolean Returns true if the rectangle contains the given point.
intersects( <Bounds> otherBounds ) Boolean Returns true if the rectangle intersects the given bounds.

L.Icon

Represents an icon to provide when creating a marker.

var myIcon = new L.Icon({
	iconUrl: 'my-icon.png',
	shadowUrl: 'my-icon-shadow.png',
	iconSize: new L.Point(38, 95),
	shadowSize: new L.Point(68, 95),
	iconAnchor: new L.Point(22, 94),
	popupAnchor: new L.Point(-3, -76)
});

var marker = new L.Marker(marker, {icon: myIcon});

L.Icon.Default extends L.Icon and is the blue icon Leaflet uses for markers by default.

Constructor

Constructor Description
L.Icon( <Icon properties> props ) Creates an icon instance with the given properties.

Properties

Property Type Description
iconUrl String (required) The URL to the icon image (absolute or relative to your script path).
iconSize Point Size of the icon image in pixels.
iconAnchor Point The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location.
shadowUrl String The URL to the icon shadow image. If shadowUrl is null then no shadow image will be created.
shadowSize Point Size of the shadow image in pixels.
shadowOffset Point Position of the shadow relative to the icon ((0, 0) by default)
popupAnchor Point The point from which the marker popup opens, relative to the anchor point.

L.Control.Zoom

A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its zoomControl option to false. Implements IControl interface.

Constructor

Constructor Description
L.Control.Zoom() Creates a zoom control.

L.Control.Attribution

The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its attributionControl option to false, and it fetches attribution texts from layers with getAttribution method automatically. Implements IControl interface.

Constructor

Constructor Description
L.Control.Attribution() Creates an attribution control.

Methods

Method Returns Description
setPrefix( <String> prefix ) - Sets the string before the attributions ("Powered by Leaflet" by default).
addAttribution( <String> text ) - Adds an attribution text (e.g. "Vector data &copy; CloudMade").
removeAttribution( <String> text ) - Removes an attribution text.

L.Control.Layers

The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the detailed example). It should be created and added explicitly to the map using Map#addControl method. Implements IControl interface.

var baseLayers = {
	"CloudMade": cloudmade,
	"OpenStreetMap": osm
};

var overlays = {
	"Marker": marker,
	"Roads": roadsLayer
};

layersControl = new L.Control.Layers(baseLayers, overlays);

map.addControl(layersControl);

Constructor

Constructor Description
L.Control.Layers( <Layer Config> baseLayers?, <Layer Config> overlays?, <Control.Layers options> options? ) Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes.

Methods

Method Returns Description
addBaseLayer( <ILayer> layer, <String> name ) this Adds a base layer (radio button entry) with the given name to the control.
addOverlay( <ILayer> layer, <String> name ) this Adds an overlay (checkbox entry) with the given name to the control.
removeLayer( <ILayer> layer ) this Remove the given layer from the control.

Options

Option Type Default value Description
collapsed Boolean true If true, the control will be collapsed into an icon and expanded on mouse hover or touch.

Layer Config

An object literal with layer names as keys and layer objects as values:

{
	"<someName1>": layer1,
	"<someName2>": layer2
}

Events methods

A set of methods shared between event-powered classes (like Map). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map 'fire' event).

Example

map.on('click', function(e) {
	alert(e.latlng);
});

Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:

function onClick(e) { ... }

map.on('click', onClick);
map.off('click', onClick);

Methods

Method Returns Description
addEventListener( <String> type, <Function> fn, <Object> context? ) this Adds a listener function (fn) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to).
removeEventListener( <String> type, <Function> fn, <Object> context? ) this Removes a previously added listener function.
on( … ) this Alias to addEventListener.
off( … ) this Alias to removeEventListener.
hasEventListeners( <String> type ) Boolean Returns true if a particular event type has some listeners attached to it.
fireEvent( <String> type, <Object> data? ) this Fires an event of the specified type. You can optionally provide an data object — the first argument of the listener function will contain its properties.
fire( … ) this Alias to fireEvent.

Event objects

Event object is an object that you recieve as an argument in a listener function when some event is fired, containing useful information about that event. For example:

map.on('click', function(e) {
	alert(e.latlng); // e is an event object (MouseEvent in this case)
});

Event

The base event object. All other event objects contain these properties too.

property type description
type String The event type (e.g. "click").
target Object The object that fired the event.

MouseEvent

property type description
latlng LatLng The geographical point where the mouse event occured.
layerPoint Point Pixel coordinates of the point where the mouse event occured relative to the map layer.

LocationEvent

property type description
latlng LatLng Detected geographical location of the user.
bounds LatLngBounds Geographical bounds of the area user is located in (with respect to the accuracy of location).
accuracy Number Accuracy of location in meters.

ErrorEvent

property type description
message String Error message.
code Number Error code (if applicable).

LayerEvent

property type description
layer ILayer The layer that was added or removed.

GeoJSON event

property type description
layer ILayer The layer for the GeoJSON feature that is being added to the map.
properties Object GeoJSON properties of the feature.
geometryType String GeoJSON geometry type of the feature.
id String GeoJSON ID of the feature (if present).
property type description
popup Popup The popup that was opened or closed.

L.Class

L.Class powers the OOP facilities of Leaflet and is used to create almost all of the Leaflet classes documented here.

In addition to implementing a simple classical inheritance model, it introduces several special properties for convenient code organization — options, includes and statics.

var MyClass = L.Class.extend({
	initialize: function (greeter) {
		this.greeter = greeter;
		// class constructor
	},

	greet: function (name) {
		alert(this.greeter + ', ' + name)
	}
});

// create instance of MyClass, passing "Hello" to the constructor
var a = new MyClass("Hello");

// call greet method, alerting "Hello, World"
a.greet("World");

Inheritance

You use L.Class.extend to define new classes, but you can use the same method on any class to inherit from it:

var MyChildClass = MyClass.extend({
	// ... new properties and methods
});

This will create a class that inherits all methods and properties of the parent class (through a proper prototype chain), adding or overriding the ones you pass to extend. It will also properly react to instanceof:

var a = new MyChildClass();
a instanceof MyChildClass; // true
a instanceof MyClass; // true

You can call parent methods (including constructor) from corresponding child ones (as you do with super calls in other languages) by accessing parent class prototype and using JavaScript's call or apply:

var MyChildClass = MyClass.extend({
	initialize: function () {
		MyClass.prototype.initialize.call("Yo");
	},

	greet: function (name) {
		MyClass.prototype.greet.call(this, 'bro ' + name + '!');
	}
});

var a = new MyChildClass();
a.greet('Jason'); // alerts "Yo, bro Jason!"

Options

options is a special property that unlike other objects that you pass to extend will be merged with the parent one instead of overriding it completely, which makes managing configuration of objects and default values convenient:

var MyClass = L.Class.extend({
	options: {
		myOption1: 'foo',
		myOption2: 'bar'
	}
});

var MyChildClass = L.Class.extend({
	options: {
		myOption1: 'baz',
		myOption3: 5
	}
});

var a = new MyChildClass();
a.options.myOption1; // 'baz'
a.options.myOption2; // 'bar'
a.options.myOption3; // 5

There's also L.Util.setOptions, a method for conveniently merging options passed to constructor with the defauls defines in the class:

var MyClass = L.Class.extend({
	options: {
		foo: 'bar',
		bla: 5
	},

	initialize: function (options) {
		L.Util.setOptions(this, options);
		...
	}
});

var a = new MyClass({bla: 10});
a.options; // {foo: 'bar', bla: 10}

Includes

includes is a special class property that merges all specified objects into the class (such objects are called mixins). A good example of this is L.Mixin.Events that event-related methods like on, off and fire to the class.

 var MyMixin = {
	foo: function () { ... },
	bar: 5
};

var MyClass = L.Class.extend({
	includes: MyMixin
});

var a = new MyClass();
a.foo();

You can also do such includes in runtime with the include method:

MyClass.include(MyMixin);

Statics

statics is just a convenience property that injects specified object properties as the static properties of the class, useful for defining constants:

var MyClass = L.Class.extend({
	statics: {
		FOO: 'bar',
		BLA: 5
	}
});

MyClass.FOO; // 'bar'

L.Browser

A namespace with properties for browser/feature detection used by Leaflet internally.

if (L.Browser.ie6) {
	alert('Upgrade your browser, dude!');
}
property type description
ie Boolean true for all old Internet Explorer versions (6-8).
ie6 Boolean true for Internet Explorer 6.
webkit Boolean true for webkit-based browsers like Chrome and Safari (including mobile versions).
webkit3d Boolean true for webkit-based browsers that support CSS 3D transformations.
gecko Boolean true for Gecko-based browsers like Firefox and Mozilla.
opera Boolean true for Opera.
android Boolean true for Android mobile browser.
mobile Boolean true for modern mobile browsers (including iOS Safari and different Android browsers).
mobileWebkit Boolean true for mobile webkit-based browsers.
mobileOpera Boolean true for mobile Opera.
touch Boolean true for all browsers on touch devices.

IHandler

An interface implemented by interaction handlers.

Method Returns Description
enable() - Enables the handler.
disable() - Disables the handler.
enabled() Boolean Returns true if the handler is enabled.

L.version

A constant that represents the Leaflet version in use.

L.version // returns "0.4" (or whatever version is currently in use)

L.noConflict()

This method restores the L global variale to the original value it had before Leaflet inclusion, and returns the real Leaflet namespace so you can put it elsewhere, like this:

// L points to some other library
...
// you include Leaflet, it replaces the L variable to Leaflet namespace

var Leaflet = L.noConflict();
// now L points to that other library again, and you can use Leaflet.Map etc.

© 2012 CloudMade. Map data © 2012 OpenStreetMap contributors, CC-BY-SA.

Fork me on GitHub