From e9cc3a3d73219ce1363c81317b9f83bb21f99da9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20S=C3=A1nchez=20Ortega?= Date: Tue, 2 May 2017 12:49:40 +0200 Subject: [PATCH] Symlink reference.html to reference-1.0.3.html (#5490) --- docs/reference-0.7.7.html | 6424 +++++++++++++++++++++++++++++++++ docs/reference-versions.html | 2 +- docs/reference.html | 6425 +--------------------------------- 3 files changed, 6426 insertions(+), 6425 deletions(-) create mode 100644 docs/reference-0.7.7.html mode change 100644 => 120000 docs/reference.html diff --git a/docs/reference-0.7.7.html b/docs/reference-0.7.7.html new file mode 100644 index 00000000..0f966f5a --- /dev/null +++ b/docs/reference-0.7.7.html @@ -0,0 +1,6424 @@ +--- +layout: v2 +title: Documentation +bodyclass: api-page +--- + +

API Reference

+ +

This reference reflects Leaflet 0.7.x. Check this list if you are using a different version of Leaflet.

+ +
+ +
+

UI Layers

+ +

Raster Layers

+ +

Vector Layers

+ +
+
+

Other Layers

+ +

Basic Types

+ +

Controls

+ +
+
+

Events

+ +

Utility

+ +

DOM Utility

+ +
+
+

Interfaces

+ + +

Misc

+ +
+
+ + + +
+ +

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 = L.map('map', {
+	center: [51.505, -0.09],
+	zoom: 13
+});
+ +

Creation

+ + + + + + + + + + + + +
FactoryDescription
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

+ +

Map State Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
centerLatLngnullInitial geographical center of the map.
zoomNumbernullInitial map zoom.
layersILayer[]nullLayers that will be added to the map initially.
minZoomNumbernullMinimum zoom level of the map. Overrides any minZoom set on map layers.
maxZoomNumbernullMaximum zoom level of the map. This overrides any maxZoom set on map layers.
maxBoundsLatLngBoundsnullWhen this option is set, the map restricts the view to the given geographical bounds, bouncing the user back when they try to pan outside the view. To set the restriction dynamically, use setMaxBounds method.
crsCRSL.CRS.
EPSG3857
Coordinate Reference System to use. Don't change this if you're not sure what it means.
+ +

Interaction Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
draggingBooleantrueWhether the map be draggable with mouse/touch or not.
touchZoomBooleantrueWhether the map can be zoomed by touch-dragging with two fingers.
scrollWheelZoomBooleantrueWhether the map can be zoomed by using the mouse wheel. If passed 'center', it will zoom to the center of the view regardless of where the mouse was.
doubleClickZoomBooleantrueWhether the map can be zoomed in by double clicking on it and zoomed out by double clicking while holding shift. If passed 'center', double-click zoom will zoom to the center of the view regardless of where the mouse was.
boxZoomBooleantrueWhether the map can be zoomed to a rectangular area specified by dragging the mouse while pressing shift.
tapBooleantrueEnables mobile hacks for supporting instant taps (fixing 200ms click delay on iOS/Android) and touch holds (fired as contextmenu events).
tapToleranceNumber15The max number of pixels a user can shift his finger during touch for it to be considered a valid tap.
trackResizeBooleantrueWhether the map automatically handles browser window resize to update itself.
worldCopyJumpBooleanfalseWith this option enabled, the map tracks when you pan to another "copy" of the world and seamlessly jumps to the original one so that all overlays like markers and vector layers are still visible.
closePopupOnClickBooleantrueSet it to false if you don't want popups to close when user clicks the map.
bounceAtZoomLimitsBooleantrueSet it to false if you don't want the map to zoom beyond min/max zoom and then bounce back when pinch-zooming.
+ +

Keyboard Navigation Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
keyboardBooleantrueMakes the map focusable and allows users to navigate the map with keyboard arrows and +/- keys.
keyboardPanOffsetNumber80Amount of pixels to pan when pressing an arrow key.
keyboardZoomOffsetNumber1Number of zoom levels to change when pressing + or - key.
+ +

Panning Inertia Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
inertiaBooleantrueIf enabled, panning of the map will have an inertia effect where the map builds momentum while dragging and continues moving in the same direction for some time. Feels especially nice on touch devices.
inertiaDecelerationNumber3000The rate with which the inertial movement slows down, in pixels/second2.
inertiaMaxSpeedNumber1500Max speed of the inertial movement, in pixels/second.
inertiaThresholdNumberdependsNumber of milliseconds that should pass between stopping the movement and releasing the mouse or touch to prevent inertial movement. 32 for touch devices and 14 for the rest by default.
+ +

Control options

+ + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
zoomControlBooleantrueWhether the zoom control is added to the map by default.
attributionControlBooleantrueWhether the attribution control is added to the map by default.
+ +

Animation options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
fadeAnimationBooleandependsWhether the tile fade animation is enabled. By default it's enabled in all browsers that support CSS3 Transitions except Android.
zoomAnimationBooleandependsWhether the tile zoom animation is enabled. By default it's enabled in all browsers that support CSS3 Transitions except Android.
zoomAnimationThresholdNumber4Won't animate zoom if the zoom difference exceeds this value.
markerZoomAnimationBooleandependsWhether 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.
+ + +

Events

+ +

You can subscribe to the following events using these methods.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EventDataDescription
clickMouseEventFired when the user clicks (or taps) the map.
dblclickMouseEventFired when the user double-clicks (or double-taps) the map.
mousedownMouseEventFired when the user pushes the mouse button on the map.
mouseupMouseEventFired when the user releases the mouse button on the map.
mouseoverMouseEventFired when the mouse enters the map.
mouseoutMouseEventFired when the mouse leaves the map.
mousemoveMouseEventFired while the mouse moves over the map.
contextmenuMouseEventFired when the user pushes the right mouse button on the map, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press).
focusEventFired when the user focuses the map either by tabbing to it or clicking/panning.
blurEventFired when the map loses focus.
preclickMouseEventFired before mouse click on the map (sometimes useful when you want something to happen on click before any existing click handlers start running).
loadEventFired when the map is initialized (when its center and zoom are set for the first time).
unloadEventFired when the map is destroyed with remove method.
viewresetEventFired when the map needs to redraw its content (this usually happens on map zoom or load). Very useful for creating custom overlays.
movestartEventFired when the view of the map starts changing (e.g. user starts dragging the map).
moveEventFired on any movement of the map view.
moveendEventFired when the view of the map stops changing (e.g. user stopped dragging the map).
dragstartEventFired when the user starts dragging the map.
dragEventFired repeatedly while the user drags the map.
dragendDragEndEventFired when the user stops dragging the map.
zoomstartEventFired when the map zoom is about to change (e.g. before zoom animation).
zoomendEventFired when the map zoom changes.
zoomlevelschangeEventFired when the number of zoomlevels on the map is changed due to adding or removing a layer.
resizeResizeEventFired when the map is resized.
autopanstartEventFired when the map starts autopanning when opening a popup.
layeraddLayerEventFired when a new layer is added to the map.
layerremoveLayerEventFired when some layer is removed from the map.
baselayerchangeLayerEvent + Fired when the base layer is changed through the layer control.
overlayaddLayerEvent + Fired when an overlay is selected through the layer control.
overlayremoveLayerEvent + Fired when an overlay is deselected through the layer control.
locationfoundLocationEvent + Fired when geolocation (using the locate method) went successfully.
locationerrorErrorEvent + Fired when geolocation (using the locate method) failed.
popupopenPopupEventFired when a popup is opened (using openPopup method).
popupclosePopupEventFired when a popup is closed (using closePopup method).
+ + +

Methods for Modifying Map State

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
setView( + <LatLng> center, + <Number> zoom?, + <zoom/pan options> options? ) + thisSets the view of the map (geographical center and zoom) with the given animation options.
setZoom( + <Number> zoom, + <zoom options> options? ) + thisSets the zoom of the map.
zoomIn( + <Number> delta?, + <zoom options> options? ) + thisIncreases the zoom of the map by delta (1 by default).
zoomOut( + <Number> delta?, + <zoom options> options? ) + thisDecreases the zoom of the map by delta (1 by default).
setZoomAround( + <LatLng> latlng, + <Number> zoom, + <zoom options> options? ) + thisZooms the map while keeping a specified point on the map stationary (e.g. used internally for scroll zoom and double-click zoom).
fitBounds( + <LatLngBounds> bounds, + <fitBounds options> options? ) + thisSets a map view that contains the given geographical bounds with the maximum zoom level possible.
fitWorld( + <fitBounds options> options? ) + thisSets a map view that mostly contains the whole world with the maximum zoom level possible.
panTo( + <LatLng> latlng, + <pan options> options? ) + thisPans 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, + <pan options> options? ) + thisPans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.
panBy( + <Point> point, + <pan options> options? ) + thisPans the map by a given number of pixels (animated).
invalidateSize( + <Boolean> animate ) + thisChecks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically, also animating pan by default.
invalidateSize( + <zoom/pan options> options ) + thisChecks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically, also animating pan by default. If options.pan is false, panning will not occur. If options.debounceMoveend is true, it will delay moveend event so that it doesn't happen often even if the method is called many times in a row.
setMaxBounds( + <LatLngBounds> bounds + thisRestricts the map view to the given bounds (see map maxBounds option).
locate( + <Locate options> options? ) + thisTries to locate the user using the Geolocation API, firing a locationfound event with location data on success or a locationerror event on failure, and optionally sets the map view to the user's location with respect to detection accuracy (or to the world view if geolocation failed). See Locate options for more details.
stopLocate()thisStops watching location previously initiated by map.locate({watch: true}) and aborts resetting the map view if map.locate was called with {setView: true}.
remove()thisDestroys the map and clears all related event listeners.
+ +

Methods for Getting Map State

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
getCenter()LatLngReturns the geographical center of the map view.
getZoom()NumberReturns the current zoom of the map view.
getMinZoom()NumberReturns the minimum zoom level of the map.
getMaxZoom()NumberReturns the maximum zoom level of the map.
getBounds()LatLngBoundsReturns the LatLngBounds of the current map view.
getBoundsZoom( + <LatLngBounds> bounds, + <Boolean> inside? ) + NumberReturns 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()PointReturns the current size of the map container.
getPixelBounds()BoundsReturns the bounds of the current map view in projected pixel coordinates (sometimes useful in layer and overlay implementations).
getPixelOrigin()PointReturns 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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addLayer( + <ILayer> layer ) + thisAdds the given layer to the map.
removeLayer( + <ILayer> layer ) + thisRemoves the given layer from the map.
hasLayer( + <ILayer> layer ) + BooleanReturns true if the given layer is currently added to the map.
eachLayer( + <Function> fn, + <Object> context? ) + thisIterates over the layers of the map, optionally specifying context of the iterator function. +
map.eachLayer(function (layer) {
+	layer.bindPopup('Hello');
+});
+
openPopup( + <Popup> popup ) + thisOpens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
openPopup( + <String> html | <HTMLElement> el, + <LatLng> latlng, + <Popup options> options? ) + thisCreates a popup with the specified options and opens it in the given point on a map.
closePopup( + <Popup> popup? ) + thisCloses the popup previously opened with openPopup (or the given one).
addControl( + <IControl> control ) + thisAdds the given control to the map.
removeControl( + <IControl> control ) + thisRemoves the given control from the map.
+ + +

Conversion Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
latLngToLayerPoint( + <LatLng> latlng ) + PointReturns the map layer point that corresponds to the given geographical coordinates (useful for placing overlays on the map).
layerPointToLatLng( + <Point> point ) + LatLngReturns the geographical coordinates of a given map layer point.
containerPointToLayerPoint( + <Point> point ) + PointConverts the point relative to the map container to a point relative to the map layer.
layerPointToContainerPoint( + <Point> point ) + PointConverts the point relative to the map layer to a point relative to the map container.
latLngToContainerPoint( + <LatLng> latlng ) + PointReturns the map container point that corresponds to the given geographical coordinates.
containerPointToLatLng( + <Point> point ) + LatLngReturns the geographical coordinates of a given map container point.
project( + <LatLng> latlng, + <Number> zoom? ) + PointProjects the given geographical coordinates to absolute pixel coordinates for the given zoom level (current zoom level by default).
unproject( + <Point> point, + <Number> zoom? ) + LatLngProjects the given absolute pixel coordinates to geographical coordinates for the given zoom level (current zoom level by default).
mouseEventToContainerPoint( + <MouseEvent> event ) + PointReturns the pixel coordinates of a mouse click (relative to the top left corner of the map) given its event object.
mouseEventToLayerPoint( + <MouseEvent> event ) + PointReturns the pixel coordinates of a mouse click relative to the map layer given its event object. +
mouseEventToLatLng( + <MouseEvent> event ) + LatLngReturns the geographical coordinates of the point the mouse clicked on given the click's event object.
+ +

Other Methods

+ + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
getContainer()HTMLElementReturns the container element of the map.
getPanes()MapPanesReturns an object with different map panes (to render overlays in).
whenReady( + <Function> fn, + <Object> context? )thisRuns the given callback when the map gets initialized with a place and zoom, or immediately if it happened already, optionally passing a function context.
+ +

Locate options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
watchBooleanfalseIf true, starts continuous watching of location changes (instead of detecting it once) using W3C watchPosition method. You can later stop watching using map.stopLocate() method.
setViewBooleanfalseIf true, automatically sets the map view to the user location with respect to detection accuracy, or to world view if geolocation failed.
maxZoomNumberInfinityThe maximum zoom for automatic view setting when using `setView` option.
timeoutNumber10000Number of milliseconds to wait for a response from geolocation before firing a locationerror event.
maximumAgeNumber0Maximum age of detected location. If less than this amount of milliseconds passed since last geolocation response, locate will return a cached location.
enableHighAccuracyBooleanfalseEnables high accuracy, see description in the W3C spec.
+ + +

Zoom/pan options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
resetBooleanfalseIf true, the map view will be completely reset (without any animations).
panpan options-Sets the options for the panning (without the zoom change) if it occurs.
zoomzoom options-Sets the options for the zoom change if it occurs.
animateBoolean-An equivalent of passing animate to both zoom and pan options (see below).
+ +

Pan options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
animateBoolean-If true, panning will always be animated if possible. If false, it will not animate panning, either resetting the map view if panning more than a screen away, or just setting a new offset for the map pane (except for `panBy` which always does the latter).
durationNumber0.25Duration of animated panning.
easeLinearityNumber0.25The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). 1.0 means linear animation, the less the more bowed the curve.
noMoveStartBooleanfalseIf true, panning won't fire movestart event on start (used internally for panning inertia).
+ +

Zoom options

+ + + + + + + + + + + + + + +
OptionTypeDefaultDescription
animateBoolean-If not specified, zoom animation will happen if the zoom origin is inside the current view. If true, the map will attempt animating zoom disregarding where zoom origin is. Setting false will make it always reset the view completely without animation.
+ +

fitBounds options

+ +

The same as zoom/pan options and additionally:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
paddingTopLeftPoint[0, 0] + Sets the amount of padding in the top left corner of a map container that shouldn't be accounted for when setting the view to fit bounds. Useful if you have some control overlays on the map like a sidebar and you don't want them to obscure objects you're zooming to.
paddingBottomRightPoint[0, 0] + The same for bottom right corner of the map.
paddingPoint[0, 0] + Equivalent of setting both top left and bottom right padding to the same value.
maxZoomNumbernullThe maximum possible zoom to use.
+ + +

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");
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
draggingIHandlerMap dragging handler (by both mouse and touch).
touchZoomIHandlerTouch zoom handler.
doubleClickZoomIHandlerDouble click zoom handler.
scrollWheelZoomIHandlerScroll wheel zoom handler.
boxZoomIHandlerBox (shift-drag with mouse) zoom handler.
keyboardIHandlerKeyboard navigation handler.
tapIHandlerMobile touch hacks (quick tap and touch hold) handler.
zoomControlControl.ZoomZoom control.
attributionControlControl.AttributionAttribution control.
+ + +

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.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
mapPaneHTMLElementPane that contains all other map panes.
tilePaneHTMLElementPane for tile layers.
objectsPaneHTMLElementPane that contains all the panes except tile pane.
shadowPaneHTMLElementPane for overlay shadows (e.g. marker shadows).
overlayPaneHTMLElementPane for overlays like polylines and polygons.
markerPaneHTMLElementPane for marker icons.
popupPaneHTMLElementPane for popups.
+ + +

Marker

+ +

Used to put markers on the map.

+ +
L.marker([50.5, 30.5]).addTo(map);
+ +

Creation

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

Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
iconL.Icon*Icon class to use for rendering the marker. See Icon documentation for details on how to customize the marker icon. Set to new L.Icon.Default() by default.
clickableBooleantrueIf false, the marker will not emit mouse events and will act as a part of the underlying map.
draggableBooleanfalseWhether the marker is draggable with mouse/touch or not.
keyboardBooleantrueWhether the marker can be tabbed to with a keyboard and clicked by pressing enter.
titleString''Text for the browser tooltip that appear on marker hover (no tooltip by default).
altString''Text for the alt attribute of the icon image (useful for accessibility).
zIndexOffsetNumber0By default, zIndex for the marker image is set automatically based on its latitude. Use 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).
opacityNumber1.0The opacity of the marker.
riseOnHoverBooleanfalseIf true, the marker will get on top of others when you hover the mouse over it.
riseOffsetNumber250The z-index offset used for the riseOnHover feature.
+ +

Events

+ +

You can subscribe to the following events using these methods.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EventDataDescription
clickMouseEventFired when the user clicks (or taps) the marker.
dblclickMouseEventFired when the user double-clicks (or double-taps) the marker.
mousedownMouseEventFired when the user pushes the mouse button on the marker.
mouseoverMouseEventFired when the mouse enters the marker.
mouseoutMouseEventFired when the mouse leaves the marker.
contextmenuMouseEvent + Fired when the user right-clicks on the marker.
dragstartEventFired when the user starts dragging the marker.
dragEventFired repeatedly while the user drags the marker.
dragendDragEndEventFired when the user stops dragging the marker.
moveEventFired when the marker is moved via setLatLng. New coordinate include in event arguments.
addEventFired when the marker is added to the map.
removeEventFired when the marker is removed from the map.
popupopenPopupEventFired when a popup bound to the marker is open.
popupclosePopupEventFired when a popup bound to the marker is closed.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addTo( + <Map> map ) + thisAdds the marker to the map.
getLatLng()LatLngReturns the current geographical position of the marker.
setLatLng( + <LatLng> latlng ) + thisChanges the marker position to the given point.
setIcon( + <Icon> icon ) + thisChanges the marker icon.
setZIndexOffset( + <Number> offset ) + thisChanges the zIndex offset of the marker.
setOpacity( + <Number> opacity ) + thisChanges the opacity of the marker.
update() + thisUpdates the marker position, useful if coordinates of its latLng object were changed directly.
bindPopup( + <String> html | <HTMLElement> el | <Popup> popup, + <Popup options> options? ) + thisBinds 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()thisUnbinds the popup previously bound to the marker with bindPopup.
openPopup()thisOpens the popup previously bound by the bindPopup method.
getPopup()PopupReturns the popup previously bound by the bindPopup method.
closePopup()thisCloses the bound popup of the marker if it's opened.
togglePopup()thisToggles the popup previously bound by the bindPopup method.
setPopupContent( + <String> html | <HTMLElement> el ) + thisSets an HTML content of the popup of this marker.
toGeoJSON()ObjectReturns a GeoJSON representation of the marker (GeoJSON Point Feature).
+ +

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();
+ + + + + + + + + + + + +
PropertyTypeDescription
draggingIHandlerMarker 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 popup = L.popup()
+	.setLatLng(latlng)
+	.setContent('<p>Hello world!<br />This is a nice popup.</p>')
+	.openOn(map);
+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
L.popup( + <Popup options> options?, + <ILayer> source? ) + Instantiates a Popup object given an optional options object that describes its appearance and location and an optional source object that is used to tag the popup with a reference to the ILayer to which it refers.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
maxWidthNumber300Max width of the popup.
minWidthNumber50Min width of the popup.
maxHeightNumbernullIf set, creates a scrollable container of the given height inside a popup if its content exceeds it.
autoPanBooleantrueSet it to false if you don't want the map to do panning animation to fit the opened popup.
keepInViewBooleanfalseSet it to true if you want to prevent users from panning the popup off of the screen while it is open.
closeButtonBooleantrueControls the presence of a close button in the popup.
offsetPointPoint(0, 6) + The offset of the popup position. Useful to control the anchor of the popup when opening it on some overlays.
autoPanPaddingTopLeftPointnullThe margin between the popup and the top left corner of the map view after autopanning was performed.
autoPanPaddingBottomRightPointnullThe margin between the popup and the bottom right corner of the map view after autopanning was performed.
autoPanPaddingPointPoint(5, 5) + Equivalent of setting both top left and bottom right autopan padding to the same value.
zoomAnimationBooleantrueWhether to animate the popup on zoom. Disable it if you have problems with Flash content inside popups.
closeOnClickBooleannullSet it to false if you want to override the default behavior of the popup closing when user clicks the map (set globally by the Map closePopupOnClick option).
classNameString''A custom class name to assign to the popup.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addTo( + <Map> map ) + thisAdds the popup to the map.
openOn( + <Map> map ) + thisAdds the popup to the map and closes the previous one. The same as map.openPopup(popup).
setLatLng( + <LatLng> latlng ) + thisSets the geographical point where the popup will open.
getLatLng()LatLngReturns the geographical point of popup.
setContent( + <String|HTMLElement> htmlContent ) + thisSets the HTML content of the popup.
getContent()<String|HTMLElement>Returns the content of the popup.
update()thisUpdates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
+ + + +

TileLayer

+ +

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

+ +

Usage example

+ +
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map);
+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
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 available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are 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:

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

Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
minZoomNumber0Minimum zoom number.
maxZoomNumber18Maximum zoom number.
maxNativeZoomNumbernullMaximum zoom number the tiles source has available. If it is specified, the tiles on all zoom levels higher than maxNativeZoom will be loaded from maxNativeZoom level and auto-scaled.
tileSizeNumber256Tile size (width and height in pixels, assuming tiles are square).
subdomainsString 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.
errorTileUrlString''URL to the tile image to show in place of the tile that failed to load.
attributionString''e.g. "© Mapbox" — the string used by the attribution control, describes the layer data.
tmsBooleanfalseIf true, inverses Y axis numbering for tiles (turn this on for TMS services).
continuousWorldBooleanfalseIf 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).
noWrapBooleanfalseIf set to true, the tiles just won't load outside the world width (-180 to 180 longitude) instead of repeating.
zoomOffsetNumber0The zoom number used in tile URLs will be offset with this value.
zoomReverseBooleanfalseIf set to true, the zoom number used in tile URLs will be reversed (maxZoom - zoom instead of zoom).
opacityNumber1.0The opacity of the tile layer.
zIndexNumbernullThe explicit zIndex of the tile layer. Not set by default.
unloadInvisibleTilesBooleandependsIf true, all the tiles that are not visible after panning are removed (for better performance). true by default on mobile WebKit, otherwise false.
updateWhenIdleBooleandependsIf false, new tiles are loaded during panning, otherwise only after it (for better performance). true by default on mobile WebKit, otherwise false.
detectRetinaBooleanfalseIf true and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.
reuseTilesBooleanfalseIf 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.
boundsLatLngBoundsnullWhen this option is set, the TileLayer only loads tiles that are in the given geographical bounds.
+ +

Events

+ +

You can subscribe to the following events using these methods.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EventDataDescription
loadingEventFired when the tile layer starts loading tiles.
loadEventFired when the tile layer loaded all visible tiles.
tileloadstartTileEventFired when a tile is requested and starts loading.
tileloadTileEventFired when a tile loads.
tileunloadTileEventFired when a tile is removed (e.g. when you have unloadInvisibleTiles on).
tileerrorTileEventFired when there is an error loading a tile.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addTo( + <Map> map ) + thisAdds the layer to the map.
bringToFront()thisBrings the tile layer to the top of all tile layers.
bringToBack()thisBrings the tile layer to the bottom of all tile layers.
setOpacity( + <Number> opacity ) + thisChanges the opacity of the tile layer.
setZIndex( + <Number> zIndex ) + thisSets the zIndex of the tile layer.
redraw()thisCauses the layer to clear all the tiles and request them again.
setUrl( + <String> urlTemplate ) + thisUpdates the layer's URL template and redraws it.
getContainer() + HTMLElementReturns the HTML element that contains the tiles for this layer.
+ + + +

TileLayer.WMS

+ +

Used to display WMS services as tile layers on the map. Extends TileLayer.

+ +

Usage example

+ +
var nexrad = 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"
+});
+ +

Creation

+ + + + + + + + + + +
FactoryDescription
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:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
layersString''(required) Comma-separated list of WMS layers to show.
stylesString''Comma-separated list of WMS styles.
formatString'image/jpeg'WMS image format (use 'image/png' for layers with transparency).
transparentBooleanfalseIf true, the WMS service will return images with transparency.
versionString'1.1.1'Version of the WMS service to use.
crsCRSnullCoordinate Reference System to use for the WMS requests, defaults to map CRS. Don't change this if you're not sure what it means.
+ +

Methods

+ + + + + + + + + + + + +
MethodReturnsDescription
setParams( + <WMS parameters> params, + <Boolean> noRedraw? ) + thisMerges an object with the new parameters and re-requests tiles on the current screen (unless noRedraw was set to true).
+ + +

TileLayer.Canvas

+ +

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

+ +

Usage example

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

Creation

+ + + + + + + + + + + + +
FactoryDescription
L.tileLayer.canvas( + <TileLayer options> options? ) + Instantiates a Canvas tile layer object given an options object (optionally).
+ +

Options

+ + + + + + + + + + + + + +
OptionTypeDefaultDescription
asyncBooleanfalseIndicates that tiles will be drawn asynchronously. tileDrawn method should be called for each tile after drawing completion.
+ +

Methods

+ + + + + + + + + + + + + + + + + +
MethodReturnsDescription
drawTile( + <HTMLCanvasElement> canvas, + <Point> tilePoint, + <Number> zoom ) + thisYou 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.
tileDrawn( <HTMLCanvasElement> canvas )-If async option is defined, this function should be called for each tile after drawing completion. canvas is the same canvas element, that was passed to drawTile.
+ + +

ImageOverlay

+ +

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

+ +

Usage example

+ +
var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
+	imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
+
+L.imageOverlay(imageUrl, imageBounds).addTo(map);
+ +

Creation

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

Options

+ + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
opacityNumber1.0The opacity of the image overlay.
attributionString''The attribution text of the image overlay.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addTo( + <Map> map ) + thisAdds the overlay to the map.
setOpacity( + <Number> opacity ) + thisSets the opacity of the overlay.
setUrl( + <String> imageUrl ) + thisChanges the URL of the image.
bringToFront()thisBrings the layer to the top of all overlays.
bringToBack()thisBrings the layer to the bottom of all overlays.
+ + +

Path

+

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

Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
strokeBooleantrueWhether to draw stroke along the path. Set it to false to disable borders on polygons or circles.
colorString'#03f'Stroke color.
weightNumber5Stroke width in pixels.
opacityNumber0.5Stroke opacity.
fillBooleandependsWhether to fill the path with color. Set it to false to disable filling on polygons or circles.
fillColorStringsame as colorFill color.
fillOpacityNumber0.2Fill opacity.
fillRuleString'evenodd'A string that defines how the inside of a shape is determined.
dashArrayStringnullA string that defines the stroke dash pattern. Doesn't work on canvas-powered layers (e.g. Android 2).
lineCapStringnullA string that defines shape to be used at the end of the stroke.
lineJoinStringnullA string that defines shape to be used at the corners of the stroke.
clickableBooleantrueIf false, the vector will not emit mouse events and will act as a part of the underlying map.
pointerEventsStringnullSets the pointer-events attribute on the path if SVG backend is used.
classNameString''Custom class name set on an element.
+ +

Events

+ +

You can subscribe to the following events using these methods.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EventDataDescription
clickMouseEventFired when the user clicks (or taps) the object.
dblclickMouseEventFired when the user double-clicks (or double-taps) the object.
mousedownMouseEventFired when the user pushes the mouse button on the object.
mouseoverMouseEventFired when the mouse enters the object.
mouseoutMouseEventFired when the mouse leaves the object.
contextmenuMouseEventFired when the user pushes the right mouse button on the object, prevents default browser context menu from showing if there are listeners on this event.
addEvent + Fired when the path is added to the map.
removeEventFired when the path is removed from the map.
popupopenPopupEventFired when a popup bound to the path is open.
popupclosePopupEventFired when a popup bound to the path is closed.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addTo( + <Map> map ) + thisAdds the layer to the map.
bindPopup( + <String> html | <HTMLElement> el | <Popup> popup, + <Popup options> options? ) + thisBinds a popup with a particular HTML content to a click on this path.
bindPopup( + <Popup> popup, + <Popup options> options? ) + thisBinds a given popup object to the path.
unbindPopup()thisUnbinds the popup previously bound to the path with bindPopup.
openPopup( + <LatLng> latlng? ) + thisOpens the popup previously bound by the bindPopup method in the given point, or in one of the path's points if not specified.
closePopup()thisCloses the path's bound popup if it is opened.
setStyle( + <Path options> object ) + thisChanges the appearance of a Path based on the options in the Path options object.
getBounds()LatLngBoundsReturns the LatLngBounds of the path.
bringToFront()thisBrings the layer to the top of all path layers.
bringToBack()thisBrings the layer to the bottom of all path layers.
redraw()thisRedraws the layer. Sometimes useful after you changed the coordinates that the path uses.
+ +

Static properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantTypeValueDescription
SVGBooleandependsTrue if SVG is used for vector rendering (true for most modern browsers).
VMLBooleandependsTrue if VML is used for vector rendering (IE 6-8).
CANVASBooleandependsTrue 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.
CLIP_PADDINGNumber0.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.
+ + +

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 array of LatLng points
+var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
+
+// zoom the map to the polyline
+map.fitBounds(polyline.getBounds());
+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
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:

+ + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
smoothFactorNumber1.0How much to simplify the polyline on each zoom level. More means better performance and smoother look, and less means more accurate representation.
noClipBooleanfalseDisabled polyline clipping.
+ +

Methods

+ +

You can use Path methods and additionally the following methods:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addLatLng( + <LatLng> latlng ) + thisAdds a given point to the polyline.
setLatLngs( + <LatLng[]> latlngs ) + thisReplaces 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> latlng?, … ) + 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()LatLngBoundsReturns the LatLngBounds of the polyline.
toGeoJSON()ObjectReturns a GeoJSON representation of the polyline (GeoJSON LineString Feature).
+ + + +

MultiPolyline

+ +

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

+ +

Creation

+ + + + + + + + + + + + + + +
FactoryDescription
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.
+ + +

Methods

+ +

MultiPolylines accept all Polyline methods but +have different behavior around their coordinate contents since they can contain +multiple line features:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
setLatLngs( + <LatLng[][]> latlngs ) + thisReplace all lines and their paths with the given array of arrays of + geographical points.
getLatLngs()<LatLng[][]> latlngs + Returns an array of arrays of geographical points in each line.
openPopup()thisOpens the popup previously bound by bindPopup.
toGeoJSON()ObjectReturns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature).
+ + + +

Polygon

+ +

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

+ +

Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points.

+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
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.
+ +

Methods

+ +

Polygon has the same options and methods as Polyline, with the following differences:

+ + + + + + + + + + + + +
MethodReturnsDescription
toGeoJSON()ObjectReturns a GeoJSON representation of the polygon (GeoJSON Polygon Feature).
+ + +

MultiPolygon

+ +

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

+ +

Creation

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

Methods

+ +

MultiPolygons accept all Polyline methods but +have different behavior around their coordinate contents since they can contain +multiple polygon features:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
setLatLngs( + <LatLng[][]> latlngs ) + thisReplace all polygons and their paths with the given array of arrays of + geographical points.
getLatLngs()<LatLng[][]> latlngs + Returns an array of arrays of geographical points in each polygon.
openPopup()thisOpens the popup previously bound by bindPopup.
toGeoJSON()ObjectReturns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature).
+ +

Rectangle

+ +

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

+ +

Usage example

+
// define rectangle geographical bounds
+var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
+
+// create an orange rectangle
+L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
+
+// zoom the map to the rectangle bounds
+map.fitBounds(bounds);
+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
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:

+ + + + + + + + + + + + + +
MethodReturnsDescription
setBounds( + <LatLngBounds> bounds ) + thisRedraws the rectangle with the passed bounds.
+ + +

Circle

+ +

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

+ +
L.circle([50.5, 30.5], 200).addTo(map);
+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
getLatLng()LatLngReturns the current geographical position of the circle.
getRadius()NumberReturns the current radius of a circle. Units are in meters.
setLatLng( + <LatLng> latlng ) + thisSets the position of a circle to a new location.
setRadius( + <Number> radius ) + thisSets the radius of a circle. Units are in meters.
toGeoJSON()ObjectReturns a GeoJSON representation of the circle (GeoJSON Point Feature).
+ + + +

CircleMarker

+ +

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

+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
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

+ + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
setLatLng( + <LatLng> latlng ) + thisSets the position of a circle marker to a new location.
setRadius( + <Number> radius ) + thisSets the radius of a circle marker. Units are in pixels.
toGeoJSON()ObjectReturns a GeoJSON representation of the circle marker (GeoJSON Point Feature).
+ + + +

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.

+ +
L.layerGroup([marker1, marker2])
+	.addLayer(polyline)
+	.addTo(map);
+ +

Creation

+ + + + + + + + + + + + +
FactoryDescription
L.layerGroup( + <ILayer[]> layers? ) + Create a layer group, optionally given an initial set of layers.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addTo( + <Map> map ) + thisAdds the group of layers to the map.
addLayer( + <ILayer> layer ) + thisAdds a given layer to the group.
removeLayer( + <ILayer> layer ) + thisRemoves a given layer from the group.
removeLayer( + <String> id ) + thisRemoves a given layer of the given id from the group.
hasLayer( + <ILayer> layer ) + BooleanReturns true if the given layer is currently added to the group.
getLayer( + <String> id ) + ILayerReturns the layer with the given id.
getLayers()ArrayReturns an array of all the layers added to the group.
clearLayers()thisRemoves all the layers from the group.
eachLayer( + <Function> fn, + <Object> context? ) + thisIterates over the layers of the group, optionally specifying context of the iterator function. +
group.eachLayer(function (layer) {
+	layer.bindPopup('Hello');
+});
+
toGeoJSON()ObjectReturns a GeoJSON representation of the layer group (GeoJSON FeatureCollection).
+ + + +

FeatureGroup

+ +

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

+ +
L.featureGroup([marker1, marker2, polyline])
+	.bindPopup('Hello world!')
+	.on('click', function() { alert('Clicked on a group!'); })
+	.addTo(map);
+ +

Creation

+ + + + + + + + + + + + + + +
FactoryDescription
L.featureGroup( + <ILayer[]> layers? ) + Create a layer group, optionally given an initial set of layers.
+ +

Methods

+ +

Has all layerGroup methods and additionally:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
bindPopup( + <String> htmlContent, + <Popup options> options? ) + thisBinds a popup with a particular HTML content to a click on any layer from the group that has a bindPopup method.
getBounds()LatLngBoundsReturns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
setStyle( + <Path options> style ) + thisSets the given path options to each layer of the group that has a setStyle method.
bringToFront()thisBrings the layer group to the top of all other layers.
bringToBack()thisBrings the layer group to the bottom of all other layers.
+ +

Events

+ +

You can subscribe to the following events using these methods.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EventDataDescription
clickMouseEventFired when the user clicks (or taps) the group.
dblclickMouseEventFired when the user double-clicks (or double-taps) the group.
mouseoverMouseEventFired when the mouse enters the group.
mouseoutMouseEventFired when the mouse leaves the group.
mousemoveMouseEventFired while the mouse moves over the layers of the group.
contextmenuMouseEventFired when the user right-clicks on one of the layers.
layeraddLayerEvent + Fired when a layer is added to the group.
layerremoveLayerEvent + Fired when a layer is removed from the map.
+ + +

GeoJson

+ +

Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse GeoJSON data and display it on the map. Extends FeatureGroup.

+ +
L.geoJson(data, {
+	style: function (feature) {
+		return {color: feature.properties.color};
+	},
+	onEachFeature: function (feature, layer) {
+		layer.bindPopup(feature.properties.description);
+	}
+}).addTo(map);
+ +

Each feature layer created by it gets a feature property that links to the GeoJSON feature data the layer was created from (so that you can access its properties later).

+ +

Creation

+ + + + + + + + + + + +
FactoryDescription
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 later with addData method) and an options object.
+ +

Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionDescription
pointToLayer( + <GeoJSON> featureData, + <LatLng> latlng ) + Function that will be used for creating layers for GeoJSON points (if not specified, simple markers will be created).
style( + <GeoJSON> featureData ) + Function that will be used to get style options for vector layers created for GeoJSON features.
onEachFeature( + <GeoJSON> featureData, + <ILayer> layer ) + Function that will be called on each created feature layer. Useful for attaching events and popups to features.
filter( + <GeoJSON> featureData, + <ILayer> layer ) + Function that will be used to decide whether to show a feature or not.
coordsToLatLng( + <Array> coords ) + Function that will be used for converting GeoJSON coordinates to LatLng points (if not specified, coords will be assumed to be WGS84 — standard [longitude, latitude] values in degrees).
+ +

Additionally accepts all Path options for polylines and polygons.

+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addData( + <GeoJSON> data ) + thisAdds a GeoJSON object to the layer.
setStyle( + <Function> style ) + thisChanges styles of GeoJSON vector layers with the given style function.
resetStyle( + <Path> layer ) + thisResets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
+ +

Static methods

+ + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
geometryToLayer( + <GeoJSON> featureData, + <Function> pointToLayer? ) + ILayerCreates a layer from a given GeoJSON feature.
coordsToLatLng( + <Array> coords, + <Boolean> reverse? ) + LatLngCreates 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? ) + ArrayCreates 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).
+ + + + +

LatLng

+ +

Represents a geographical point with a certain latitude and longitude.

+
var latlng = L.latLng(50.5, 30.5);
+ +

All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent:

+ +
map.panTo([50, 30]);
+map.panTo({lon: 30, lat: 50});
+map.panTo({lat: 50, lng: 30});
+map.panTo(L.latLng(50, 30));
+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
L.latLng( + <Number> latitude, + <Number> longitude, + <Number> altitude? ) + Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
+ +

Properties

+ + + + + + + + + + + + + + + + + +
PropertyTypeDescription
latNumberLatitude in degrees.
lngNumberLongitude in degrees.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
distanceTo( + <LatLng> otherLatlng ) + NumberReturns the distance (in meters) to the given LatLng calculated using the Haversine formula. See description on wikipedia.
equals( + <LatLng> otherLatlng ) + BooleanReturns true if the given LatLng point is at the same position (within a small margin of error).
toString()StringReturns a string representation of the point (for debugging purposes).
wrap( + <Number> left, + <Number> right ) + LatLngReturns a new LatLng object with the longitude wrapped around left and right boundaries (-180 to 180 by default).
+ +

Constants

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantTypeValueDescription
DEG_TO_RADNumberMath.PI / 180A multiplier for converting degrees into radians.
RAD_TO_DEGNumber180 / Math.PIA multiplier for converting radians into degrees.
MAX_MARGINNumber1.0E-9Max margin of error for the equality check.
+ + + + +

LatLngBounds

+ +

Represents a rectangular geographical area on a map.

+
var southWest = L.latLng(40.712, -74.227),
+	northEast = L.latLng(40.774, -74.125),
+	bounds = L.latLngBounds(southWest, northEast);
+ +

All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:

+ +
map.fitBounds([
+	[40.712, -74.227],
+	[40.774, -74.125]
+]);
+ +

Creation

+ + + + + + + + + + + + + + + + + + +
FactoryDescription
+ 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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
extend( + <LatLng|LatLngBounds> latlng ) + thisExtends the bounds to contain the given point or bounds.
getSouthWest()LatLngReturns the south-west point of the bounds.
getNorthEast()LatLngReturns the north-east point of the bounds.
getNorthWest()LatLngReturns the north-west point of the bounds.
getSouthEast()LatLngReturns the south-east point of the bounds.
getWest()NumberReturns the west longitude of the bounds.
getSouth()NumberReturns the south latitude of the bounds.
getEast()NumberReturns the east longitude of the bounds.
getNorth()NumberReturns the north latitude of the bounds.
getCenter()LatLngReturns the center point of the bounds.
contains( + <LatLngBounds> otherBounds ) + BooleanReturns true if the rectangle contains the given one.
contains( + <LatLng> latlng ) + BooleanReturns true if the rectangle contains the given point.
intersects( + <LatLngBounds> otherBounds ) + BooleanReturns true if the rectangle intersects the given bounds.
equals( + <LatLngBounds> otherBounds ) + BooleanReturns true if the rectangle is equivalent (within a small margin of error) to the given bounds.
toBBoxString()StringReturns 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.
pad( + <Number> bufferRatio ) + LatLngBoundsReturns bigger bounds created by extending the current bounds by a given percentage in each direction.
isValid() + BooleanReturns true if the bounds are properly initialized.
+ + + + +

Point

+ +

Represents a point with x and y coordinates in pixels.

+ +
var point = L.point(200, 300);
+ +

All Leaflet methods and options that accept Point objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:

+ +
map.panBy([200, 300]);
+map.panBy(L.point(200, 300));
+ +

Creation

+ + + + + + + + + + + +
FactoryDescription
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

+ + + + + + + + + + + + + + + + + +
PropertyTypeDescription
xNumberThe x coordinate.
yNumberThe y coordinate.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
add( + <Point> otherPoint ) + PointReturns the result of addition of the current and the given points.
subtract( + <Point> otherPoint ) + PointReturns the result of subtraction of the given point from the current.
multiplyBy( + <Number> number ) + PointReturns the result of multiplication of the current point by the given number.
divideBy( + <Number> number, + <Boolean> round? ) + PointReturns 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 ) + NumberReturns the distance between the current and the given points.
clone()PointReturns a copy of the current point.
round()PointReturns a copy of the current point with rounded coordinates.
floor()PointReturns a copy of the current point with floored coordinates (rounded down).
equals( + <Point> otherPoint ) + BooleanReturns true if the given point has the same coordinates.
contains( + <Point> otherPoint ) + BooleanReturns true if the both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
toString()StringReturns a string representation of the point for debugging purposes.
+ + + +

Bounds

+ +

Represents a rectangular area in pixel coordinates.

+
var p1 = L.point(10, 10),
+	p2 = L.point(40, 60),
+	bounds = L.bounds(p1, p2);
+ +

All Leaflet methods that accept Bounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:

+ +
otherBounds.intersects([[10, 10], [40, 60]]);
+ +

Creation

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

Properties

+ + + + + + + + + + + + + + + + + +
PropertyTypeDescription
minPointThe top left corner of the rectangle.
maxPointThe bottom right corner of the rectangle.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
extend( + <Point> point ) + -Extends the bounds to contain the given point.
getCenter()PointReturns the center point of the bounds.
contains( + <Bounds> otherBounds ) + BooleanReturns true if the rectangle contains the given one.
contains( + <Point> point ) + BooleanReturns true if the rectangle contains the given point.
intersects( + <Bounds> otherBounds ) + BooleanReturns true if the rectangle intersects the given bounds.
isValid()BooleanReturns true if the bounds are properly initialized.
getSize()PointReturns the size of the given bounds.
+ + +

Icon

+ +

Represents an icon to provide when creating a marker.

+ +
var myIcon = L.icon({
+	iconUrl: 'my-icon.png',
+	iconRetinaUrl: 'my-icon@2x.png',
+	iconSize: [38, 95],
+	iconAnchor: [22, 94],
+	popupAnchor: [-3, -76],
+	shadowUrl: 'my-icon-shadow.png',
+	shadowRetinaUrl: 'my-icon-shadow@2x.png',
+	shadowSize: [68, 95],
+	shadowAnchor: [22, 94]
+});
+
+L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
+ +

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

+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
L.icon( + <Icon options> options ) + Creates an icon instance with the given options.
+ +

Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDescription
iconUrlString + (required) The URL to the icon image (absolute or relative to your script path).
iconRetinaUrlString + The URL to a retina sized version of the icon image (absolute or relative to your script path). Used for Retina screen devices.
iconSizePointSize of the icon image in pixels.
iconAnchorPointThe 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. Centered by default if size is specified, also can be set in CSS with negative margins.
shadowUrlString + The URL to the icon shadow image. If not specified, no shadow image will be created.
shadowRetinaUrlString + The URL to the retina sized version of the icon shadow image. If not specified, no shadow image will be created. Used for Retina screen devices.
shadowSizePointSize of the shadow image in pixels.
shadowAnchorPointThe coordinates of the "tip" of the shadow (relative to its top left corner) (the same as iconAnchor if not specified).
popupAnchorPointThe coordinates of the point from which popups will "open", relative to the icon anchor.
classNameString + A custom class name to assign to both icon and shadow images. Empty by default.
+ + +

DivIcon

+ +

Represents a lightweight icon for markers that uses a simple div element instead of an image.

+ +
var myIcon = L.divIcon({className: 'my-div-icon'});
+// you can set .my-div-icon styles in CSS
+
+L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
+ +

By default, it has a 'leaflet-div-icon' class and is styled as a little white square with a shadow.

+ +

Creation

+ + + + + + + + + + + + + + +
FactoryDescription
L.divIcon( + <DivIcon options> options ) + Creates a div icon instance with the given options.
+ +

Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDescription
iconSizePointSize of the icon in pixels. Can be also set through CSS.
iconAnchorPointThe 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. Centered by default if size is specified, also can be set in CSS with negative margins.
popupAnchorPointThe coordinates of the point from which popups will "open", relative to the icon anchor.
classNameString + A custom class name to assign to the icon. 'leaflet-div-icon' by default.
htmlString + A custom HTML code to put inside the div element, empty by default.
+ + + + +

Control

+ +

The base class for all Leaflet controls. Implements IControl interface. You can add controls to the map like this:

+ +
control.addTo(map);
+// the same as
+map.addControl(control);
+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
L.control( + <Control options> options? ) + Creates a control with the given options.
+ +

Options

+ + + + + + + + + + + + + +
OptionTypeDefaultDescription
positionString'topright'The initial position of the control (one of the map corners). See control positions.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
setPosition( + <String> position ) + thisSets the position of the control. See control positions.
getPosition()StringReturns the current position of the control.
addTo( + <Map> map ) + thisAdds the control to the map.
removeFrom( + <Map> map ) + thisRemoves the control from the map.
getContainer()HTMLElementReturns the HTML container of the control.
+ +

Control Positions

+ +

Control positions (map corner to put a control to) are set using strings. Margins between controls and the map border are set with CSS, so that you can easily override them.

+ + + + + + + + + + + + + + + + + + + + + + +
PositionDescription
'topleft'Top left of the map.
'topright'Top right of the map.
'bottomleft'Bottom left of the map.
'bottomright'Bottom right of the map.
+ + +

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. Extends Control.

+ +

Creation

+ + + + + + + + + + + + +
FactoryDescription
L.control.zoom( + <Control.Zoom options> options? ) + Creates a zoom control.
+ +

Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
positionString'topleft'The position of the control (one of the map corners). See control positions.
zoomInTextString'+'The text set on the zoom in button.
zoomOutTextString'-'The text set on the zoom out button.
zoomInTitleString'Zoom in'The title set on the zoom in button.
zoomOutTitleString'Zoom out'The title set on the zoom out button.
+ + + +

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. Extends Control.

+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
L.control.attribution( + <Control.Attribution options> options? ) + Creates an attribution control.
+ +

Options

+ + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
positionString'bottomright'The position of the control (one of the map corners). See control positions.
prefixString'Leaflet'The HTML text shown before the attributions. Pass false to disable.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
setPrefix( + <String> prefix ) + thisSets the text before the attributions.
addAttribution( + <String> text ) + thisAdds an attribution text (e.g. 'Vector data &copy; Mapbox').
removeAttribution( + <String> text ) + thisRemoves an attribution text.
+ + +

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). Extends Control.

+ +
var baseLayers = {
+	"Mapbox": mapbox,
+	"OpenStreetMap": osm
+};
+
+var overlays = {
+	"Marker": marker,
+	"Roads": roadsLayer
+};
+
+L.control.layers(baseLayers, overlays).addTo(map);
+ +

Creation

+ + + + + + + + + + +
FactoryDescription
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. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addBaseLayer( + <ILayer> layer, + <String> name ) + thisAdds a base layer (radio button entry) with the given name to the control.
addOverlay( + <ILayer> layer, + <String> name ) + thisAdds an overlay (checkbox entry) with the given name to the control.
removeLayer( + <ILayer> layer ) + thisRemove the given layer from the control.
+ +

Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
positionString'topright'The position of the control (one of the map corners). See control positions.
collapsedBooleantrueIf true, the control will be collapsed into an icon and expanded on mouse hover or touch.
autoZIndexBooleantrueIf true, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.
+ + +

Layer Config

+ +

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

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

The layer names can contain HTML, which allows you to add additional styling to the items:

+ +
{"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
+ + +

Events

+ +

You can subscribe to the following events on the Map object using these methods.

+ + + + + + + + + + + + + + + + + + + +
EventDataDescription
baselayerchangeLayersControlEvent + Fired when the base layer is changed through the control.
overlayaddLayersControlEvent + Fired when an overlay is selected through the control.
overlayremoveLayersControlEvent + Fired when an overlay is deselected through the control.
+ + +

Control.Scale

+ +

A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends Control.

+ +
L.control.scale().addTo(map);
+ +

Creation

+ + + + + + + + + + + + + +
FactoryDescription
L.control.scale( + <Control.Scale options> options? ) + Creates an scale control with the given options.
+ +

Options

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionTypeDefaultDescription
positionString'bottomleft'The position of the control (one of the map corners). See control positions.
maxWidthNumber100Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
metricBooleantrueWhether to show the metric scale line (m/km).
imperialBooleantrueWhether to show the imperial scale line (mi/ft).
updateWhenIdleBooleanfalseIf true, the control is updated on moveend, otherwise it's always up-to-date (updated on move).
+ + + +

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 'click' 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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addEventListener( + <String> type, + <Function> fn, + <Object> context? ) + thisAdds 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). You can also pass several space-separated types (e.g. 'click dblclick').
addOneTimeEventListener( + <String> type, + <Function> fn, + <Object> context? ) + thisThe same as above except the listener will only get fired once and then removed.
addEventListener( + <Object> eventMap, + <Object> context? ) + thisAdds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove}
removeEventListener( + <String> type, + <Function> fn?, + <Object> context? ) + thisRemoves a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to addEventListener, you must pass the same context to removeEventListener in order to remove the listener.
removeEventListener( + <Object> eventMap, + <Object> context? ) + thisRemoves a set of type/listener pairs.
removeEventListener()thisRemoves all listeners. An alias to clearAllEventListeners when you use it without arguments.
hasEventListeners( + <String> type ) + BooleanReturns true if a particular event type has some listeners attached to it.
fireEvent( + <String> type, + <Object> data? ) + thisFires an event of the specified type. You can optionally provide an data object — the first argument of the listener function will contain its properties.
clearAllEventListeners()thisRemoves all listeners to all events on the object.
on( … )thisAlias to addEventListener.
once( … )thisAlias to addOneTimeEventListener.
off( … )thisAlias to removeEventListener.
fire( … )thisAlias to fireEvent.
+ + +

Event objects

+ +

Event object is an object that you receive 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.

+ + + + + + + + + + + + + + + + + +
propertytypedescription
typeStringThe event type (e.g. 'click').
targetObjectThe object that fired the event.
+ +

MouseEvent

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
propertytypedescription
latlngLatLngThe geographical point where the mouse event occurred.
layerPointPointPixel coordinates of the point where the mouse event occurred relative to the map layer.
containerPointPointPixel coordinates of the point where the mouse event occurred relative to the map сontainer.
originalEventDOMMouseEventThe original DOM mouse event fired by the browser.
+ +

LocationEvent

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
propertytypedescription
latlngLatLngDetected geographical location of the user.
boundsLatLngBoundsGeographical bounds of the area user is located in (with respect to the accuracy of location).
accuracyNumberAccuracy of location in meters.
altitudeNumberHeight of the position above the WGS84 ellipsoid in meters.
altitudeAccuracyNumberAccuracy of altitude in meters.
headingNumberThe direction of travel in degrees counting clockwise from true North.
speedNumberCurrent velocity in meters per second.
timestampNumberThe time when the position was acquired.
+ +

ErrorEvent

+ + + + + + + + + + + + + + + + + +
propertytypedescription
messageStringError message.
codeNumberError code (if applicable).
+ +

LayerEvent

+ + + + + + + + + + + + +
propertytypedescription
layerILayerThe layer that was added or removed.
+ +

LayersControlEvent

+ + + + + + + + + + + + + + + + + +
propertytypedescription
layerILayerThe layer that was added or removed.
nameStringThe name of the layer that was added or removed.
+ +

TileEvent

+ + + + + + + + + + + + + + + + + +
propertytypedescription
tileHTMLElementThe tile element (image).
urlStringThe source URL of the tile.
+ +

TileErrorEvent

+ + + + + + + + + + + + + + + + + +
propertytypedescription
tileHTMLElementThe tile element (image).
urlStringThe src attribute of the tile element.
+ +

ResizeEvent

+ + + + + + + + + + + + + + + + + +
propertytypedescription
oldSizePointThe old size before resize event.
newSizePointThe new size after the resize event.
+ +

GeoJSON event

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
propertytypedescription
layerILayerThe layer for the GeoJSON feature that is being added to the map.
propertiesObjectGeoJSON properties of the feature.
geometryTypeStringGeoJSON geometry type of the feature.
idStringGeoJSON ID of the feature (if present).
+ + + + + + + + + + + + + + +
propertytypedescription
popupPopupThe popup that was opened or closed.
+ +

DragEndEvent

+ + + + + + + + + + + + +
propertytypedescription
distanceNumberThe distance in pixels the draggable element was moved by.
+ + + + + + +

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");
+
+ +

The initialize method is your class's constructor function, meaning that it gets called when you do new MyClass(...).

+ + +

Class Factories

+ +

You may have noticed that Leaflet objects are created without using the new keyword. This is achieved by complementing each class with a lowercase factory method:

+ +
new L.Map('map'); // becomes:
+L.map('map');
+ +

The factories are implemented very easily, and you can do this for your own classes:

+ +
L.map = function (id, options) {
+	return new L.Map(id, options);
+};
+ + +

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(this, "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 = MyClass.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 defaults defined 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'
+ + +

Constructor Hooks

+ +

If you're a plugin developer, you often need to add additional initialization code to existing classes (e.g. editing hooks for L.Polyline). Leaflet comes with a way to do it easily using the addInitHook method:

+ +
MyClass.addInitHook(function () {
+	// ... do something in constructor additionally
+	// e.g. add event listeners, set custom properties etc.
+});
+ +

You can also use the following shortcut when you just need to make one additional method call:

+ +
MyClass.addInitHook('methodName', arg1, arg2, …);
+ + +

Browser

+ +

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

+ +
if (L.Browser.ie6) {
+	alert('Upgrade your browser, dude!');
+}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
propertytypedescription
ieBooleantrue for all Internet Explorer versions.
ie6Booleantrue for Internet Explorer 6.
ie7Booleantrue for Internet Explorer 7.
ielt9Booleantrue for Internet Explorer versions less than 9.
webkitBooleantrue for webkit-based browsers like Chrome and Safari (including mobile versions).
webkit3dBooleantrue for webkit-based browsers that support CSS 3D transformations.
androidBooleantrue for Android mobile browser.
android23Booleantrue for old Android stock browsers (2 and 3).
mobileBooleantrue for modern mobile browsers (including iOS Safari and different Android browsers).
mobileWebkitBooleantrue for mobile webkit-based browsers.
mobileOperaBooleantrue for mobile Opera.
touchBooleantrue for all browsers on touch devices.
msTouchBooleantrue for browsers with Microsoft touch model (e.g. IE10).
retinaBooleantrue for devices with Retina screens.
+ + +

Util

+ +

Various utility functions, used by Leaflet internally.

+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
extend( + <Object> dest, + <Object> src?.. ) + ObjectMerges the properties of the src object (or multiple objects) into dest object and returns the latter. Has an L.extend shortcut.
bind( + <Function> fn, + <Object> obj ) + FunctionReturns a function which executes function fn with the given scope obj (so that this keyword refers to obj inside the function code). Has an L.bind shortcut. Not a polyfill for ES 5 bind (compare L.bind to the MDN-recommended polyfill for Function.prototype.bind).
stamp( <Object> obj )StringApplies a unique key to the object and returns that key. Has an L.stamp shortcut.
requestAnimFrame( + <Function> fn, + <Object> context?, + <Boolean> immediate?, + <HTMLElement> element? ) + NumberSchedules fn to be executed when the browser repaints. When immediate is set, fn is called immediately if the browser doesn't have native support for requestAnimationFrame, otherwise it's delayed. Returns an id that can be used to cancel the request.
cancelAnimFrame( + <Number> id ) + -Cancels a previous request to requestAnimFrame.
limitExecByInterval( + <Function> fn, + <Number> time, + <Object> context? ) + FunctionReturns a wrapper around the function fn that makes sure it's called not more often than a certain time interval time, but as fast as possible otherwise (for example, it is used for checking and requesting new tiles while dragging the map), optionally passing the scope (context) in which the function will be called.
falseFn()FunctionAlways returns false.
formatNum( + <Number> num, + <Number> digits ) + NumberReturns the number num rounded to digits decimals.
splitWords( + <String> str ) + String[]Trims and splits the string on whitespace and returns the array of parts.
setOptions( + <Object> obj, + <Object> options ) + ObjectMerges the given properties to the options of the obj object, returning the resulting options. See Class options. Has an L.setOptions shortcut.
getParamString( + <Object> obj ) + StringConverts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} translates to '?a=foo&b=bar'.
template( + <String> str, <Object> data ) + StringSimple templating facility, accepts a template string of the form 'Hello {a}, {b}' and a data object like {a: 'foo', b: 'bar'}, returns evaluated string ('Hello foo, bar'). You can also specify functions instead of strings for data values — they will be evaluated passing data as an argument.
isArray( + <Object> obj ) + BooleanReturns true if the given object is an array.
trim( + <String> str ) + StringTrims the whitespace from both ends of the string and returns the result.
+ +

Properties

+ + + + + + + + + + + + +
PropertyTypeDescription
emptyImageUrlStringData URI string containing a base64-encoded empty GIF image. Used as a hack to free memory from unused images on WebKit-powered mobile devices (by setting image src to this string).
+ + + +

Transformation

+ +

Represents an affine transformation: a set of coefficients a, b, c, d for transforming a point of a form (x, y) into (a*x + b, c*y + d) and doing the reverse. Used by Leaflet in its projections code.

+ +
var transformation = new L.Transformation(2, 5, -1, 10),
+	p = L.point(1, 2),
+	p2 = transformation.transform(p), //  L.point(7, 8)
+	p3 = transformation.untransform(p2); //  L.point(1, 2)
+
+ +

Creation

+ + + + + + + + + + + +
CreationDescription
new L.Transformation( + <Number> a, + <Number> b, + <Number> c, + <Number> d ) + Creates a transformation object with the given coefficients.
+ +

Methods

+ + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
transform( + <Point> point, + <Number> scale? ) + PointReturns a transformed point, optionally multiplied by the given scale. Only accepts real L.Point instances, not arrays.
untransform( + <Point> point, + <Number> scale? ) + PointReturns the reverse transformation of the given point, optionally divided by the given scale. Only accepts real L.Point instances, not arrays.
+ + + + +

LineUtil

+ +

Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.

+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
simplify( + <Point[]> points, + <Number> tolerance ) + Point[]Dramatically reduces the number of points in a polyline while retaining its shape and returns a new array of simplified points. Used for a huge performance boost when processing/displaying Leaflet polylines for each zoom level and also reducing visual noise. tolerance affects the amount of simplification (lesser value means higher quality but slower and with more points). Also released as a separated micro-library Simplify.js.
pointToSegmentDistance( + <Point> p, + <Point> p1, + <Point> p2 ) + NumberReturns the distance between point p and segment p1 to p2.
closestPointOnSegment( + <Point> p, + <Point> p1, + <Point> p2 ) + PointReturns the closest point from a point p on a segment p1 to p2.
clipSegment( + <Point> a, + <Point> b, + <Bounds> bounds ) + Point[]Clips the segment a to b by rectangular bounds. Returns either false or an array of clipped points. Used by Leaflet to only show polyline points that are on the screen or near, increasing performance.
+ + + +

PolyUtil

+ +

Various utility functions for polygon geometries.

+ +

Methods

+ + + + + + + + + + + + + + +
MethodReturnsDescription
clipPolygon( + <Point[]> points, + <Bounds> bounds ) + Point[]Clips the polygon geometry defined by the given points by rectangular bounds. Used by Leaflet to only show polygon points that are on the screen or near, increasing performance. Note that polygon points needs different algorithm for clipping than polyline, so there's a separate method for it.
+ + + + +

DomEvent

+ +

Utility functions to work with the DOM events, used by Leaflet internally.

+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
addListener( + <HTMLElement> el, + <String> type, + <Function> fn, + <Object> context? ) + thisAdds a listener fn to the element's DOM event of the specified type. this keyword inside the listener will point to context, or to the element if not specified.
removeListener( + <HTMLElement> el, + <String> type, + <Function> fn ) + thisRemoves an event listener from the element.
stopPropagation( + <DOMEvent> e ) + thisStop the given event from propagation to parent elements. Used inside the listener functions: +
L.DomEvent.addListener(div, 'click', function (e) {
+	L.DomEvent.stopPropagation(e);
+});
+
preventDefault( + <DOMEvent> e ) + thisPrevents the default action of the event from happening (such as following a link in the href of the a element, or doing a POST request with page reload when form is submitted). Use it inside listener functions. +
stop( + <DOMEvent> e ) + thisDoes stopPropagation and preventDefault at the same time.
disableClickPropagation( + <HTMLElement> el ) + thisAdds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' and 'touchstart' events.
getMousePosition( + <DOMEvent> e, + <HTMLElement> container? ) + PointGets normalized mouse position from a DOM event relative to the container or to the whole page if not specified.
getWheelDelta( + <DOMEvent> e ) + NumberGets normalized wheel delta from a mousewheel DOM event.
+ + + + +

DomUtil

+ +

Utility functions to work with the DOM tree, used by Leaflet internally.

+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
get( + <String or HTMLElement> id ) + HTMLElementReturns an element with the given id if a string was passed, or just returns the element if it was passed directly.
getStyle( + <HTMLElement> el, + <String> style ) + StringReturns the value for a certain style attribute on an element, including computed values or values set through CSS.
getViewportOffset( + <HTMLElement> el ) + PointReturns the offset to the viewport for the requested element.
create( + <String> tagName, + <String> className, + <HTMLElement> container? ) + HTMLElementCreates an element with tagName, sets the className, and optionally appends it to container element.
disableTextSelection()-Makes sure text cannot be selected, for example during dragging.
enableTextSelection()-Makes text selection possible again.
hasClass( + <HTMLElement> el, + <String> name ) + BooleanReturns true if the element class attribute contains name.
addClass( + <HTMLElement> el, + <String> name ) + -Adds name to the element's class attribute.
removeClass( + <HTMLElement> el, + <String> name ) + -Removes name from the element's class attribute.
setOpacity( + <HTMLElement> el, + <Number> value ) + -Set the opacity of an element (including old IE support). Value must be from 0 to 1.
testProp( + <String[]> props ) + String or falseGoes through the array of style names and returns the first name that is a valid style name for an element. If no such name is found, it returns false. Useful for vendor-prefixed styles like transform.
getTranslateString( + <Point> point ) + StringReturns a CSS transform string to move an element by the offset provided in the given point. Uses 3D translate on WebKit for hardware-accelerated transforms and 2D on other browsers.
getScaleString( + <Number> scale, + <Point> origin ) + StringReturns a CSS transform string to scale an element (with the given scale origin).
setPosition( + <HTMLElement> el, + <Point> point, + <Boolean> disable3D? ) + -Sets the position of an element to coordinates specified by point, using CSS translate or top/left positioning depending on the browser (used by Leaflet internally to position its layers). Forces top/left positioning if disable3D is true.
getPosition( + <HTMLElement> el ) + PointReturns the coordinates of an element previously positioned with setPosition.
+ +

Properties

+ + + + + + + + + + + + + + + + + +
PropertyTypeDescription
TRANSITION + StringVendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit).
TRANSFORM + StringVendor-prefixed transform style name.
+ + + +

PosAnimation

+ +

Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.

+ +
var fx = new L.PosAnimation();
+fx.run(el, [300, 500], 0.5);
+ +

Creation

+ + + + + + + + + + + +
CreationDescription
new L.PosAnimation()Creates a PosAnimation object.
+ +

Methods

+ + + + + + + + + + + + + +
MethodReturnsDescription
run( + <HTMLElement> element, + <Point> newPos, + <Number> duration?, + <Number> easeLinearity? ) + thisRuns an animation of a given element to a new position, optionally setting duration in seconds (0.25 by default) and easing linearity factor (3rd argument of the cubic bezier curve, 0.5 by default).
+ +

Events

+ +

You can subscribe to the following events using these methods.

+ + + + + + + + + + + + + + + + + + + + + + +
EventDataDescription
startEventFired when the animation starts.
stepEventFired continuously during the animation.
endEventFired when the animation ends.
+ + + +

Draggable

+ +

A class for making DOM elements draggable (including touch support). Used internally for map and marker dragging. Only works for elements that were positioned with DomUtil#setPosition.

+ +
var draggable = new L.Draggable(elementToDrag);
+draggable.enable();
+
+ +

Creation

+ + + + + + + + + + + +
CreationDescription
new L.Draggable( + <HTMLElement> element, + <HTMLElement> dragHandle? ) + Creates a Draggable object for moving the given element when you start dragging the dragHandle element (equals the element itself by default).
+ +

Events

+ +

You can subscribe to the following events using these methods.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
EventDataDescription
dragstartEventFired when the dragging starts.
predragEventFired continuously during dragging before each corresponding update of the element position.
dragEventFired continuously during dragging.
dragendEventFired when the dragging ends.
+ +

Methods

+ + + + + + + + + + + + + + + + + +
MethodReturnsDescription
enable()-Enables the dragging ability.
disable()-Disables the dragging ability.
+ + + + + +

IHandler

+

An interface implemented by interaction handlers.

+ + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
enable()-Enables the handler.
disable()-Disables the handler.
enabled()BooleanReturns true if the handler is enabled.
+ + +

ILayer

+ +

Represents an object attached to a particular location (or a set of locations) on a map. Implemented by tile layers, markers, popups, image overlays, vector layers and layer groups.

+ +

Methods

+ + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
onAdd( + <Map> map ) + -Should contain code that creates DOM elements for the overlay, adds them to map panes where they should belong and puts listeners on relevant map events. Called on map.addLayer(layer).
onRemove( + <Map> map ) + -Should contain all clean up code that removes the overlay's elements from the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer).
+ +

Implementing Custom Layers

+ +

The most important things know about when implementing custom layers are Map viewreset event and latLngToLayerPoint method. viewreset is fired when the map needs to reposition its layers (e.g. on zoom), and latLngToLayerPoint is used to get coordinates for the layer's new position.

+ +

Another event often used in layer implementations is moveend which fires after any movement of the map (panning, zooming, etc.).

+ +

Another thing to note is that you'll usually need to add leaflet-zoom-hide class to the DOM elements you create for the layer so that it hides during zoom animation. Implementing zoom animation for custom layers is a complex topic and will be documented separately in future, but meanwhile you can take a look at how it's done for Leaflet layers (e.g. ImageOverlay) in the source.

+ +

Custom Layer Example

+ +

Here's how a custom layer implementation usually looks:

+ +
var MyCustomLayer = L.Class.extend({
+
+	initialize: function (latlng) {
+		// save position of the layer or any options from the constructor
+		this._latlng = latlng;
+	},
+
+	onAdd: function (map) {
+		this._map = map;
+
+		// create a DOM element and put it into one of the map panes
+		this._el = L.DomUtil.create('div', 'my-custom-layer leaflet-zoom-hide');
+		map.getPanes().overlayPane.appendChild(this._el);
+
+		// add a viewreset event listener for updating layer's position, do the latter
+		map.on('viewreset', this._reset, this);
+		this._reset();
+	},
+
+	onRemove: function (map) {
+		// remove layer's DOM elements and listeners
+		map.getPanes().overlayPane.removeChild(this._el);
+		map.off('viewreset', this._reset, this);
+	},
+
+	_reset: function () {
+		// update layer's position
+		var pos = this._map.latLngToLayerPoint(this._latlng);
+		L.DomUtil.setPosition(this._el, pos);
+	}
+});
+
+map.addLayer(new MyCustomLayer(latlng));
+
+ + + +

IControl

+ +

Represents a UI element in one of the corners of the map. Implemented by zoom, attribution, scale and layers controls.

+ +

Methods

+ +

Every control in Leaflet should extend from Control class and additionally have the following methods:

+ + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
onAdd( + <Map> map ) + HTMLElementShould contain code that creates all the neccessary DOM elements for the control, adds listeners on relevant map events, and returns the element containing the control. Called on map.addControl(control) or control.addTo(map).
onRemove( + <Map> map ) + -Optional, should contain all clean up code (e.g. removes control's event listeners). Called on map.removeControl(control) or control.removeFrom(map). The control's DOM container is removed automatically.
+ +

Custom Control Example

+ +
var MyControl = L.Control.extend({
+	options: {
+		position: 'topright'
+	},
+
+	onAdd: function (map) {
+		// create the control container with a particular class name
+		var container = L.DomUtil.create('div', 'my-custom-control');
+
+		// ... initialize other DOM elements, add listeners, etc.
+
+		return container;
+	}
+});
+
+map.addControl(new MyControl());
+
+ +

If specify your own constructor for the control, you'll also probably want to process options properly:

+ +
var MyControl = L.Control.extend({
+	initialize: function (foo, options) {
+		// ...
+		L.Util.setOptions(this, options);
+	},
+	// ...
+});
+ +

This will allow you to pass options like position when creating the control instances:

+ +
map.addControl(new MyControl('bar', {position: 'bottomleft'}));
+ + + + +

IProjection

+ +

An object with methods for projecting geographical coordinates of the world onto a flat surface (and back). See Map projection.

+ +

Methods

+ + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
project( + <LatLng> latlng ) + PointProjects geographical coordinates into a 2D point.
unproject( + <Point> point ) + LatLngThe inverse of project. Projects a 2D point into geographical location.
+ +

Defined Projections

+ +

Leaflet comes with a set of already defined projections out of the box:

+ + + + + + + + + + + + + + + + + + + + + +
ProjectionDescription
L.Projection.SphericalMercatorSpherical Mercator projection — the most common projection for online maps, used by almost all free and commercial tile providers. Assumes that Earth is a sphere. Used by the EPSG:3857 CRS.
L.Projection.MercatorElliptical Mercator projection — more complex than Spherical Mercator. Takes into account that Earth is a geoid, not a perfect sphere. Used by the EPSG:3395 CRS.
L.Projection.LonLatEquirectangular, or Plate Carree projection — the most simple projection, mostly used by GIS enthusiasts. Directly maps x as longitude, and y as latitude. Also suitable for flat worlds, e.g. game maps. Used by the EPSG:3395 and Simple CRS.
+ + + + +

ICRS

+ +

Defines coordinate reference systems for projecting geographical points into pixel (screen) coordinates and back (and to coordinates in other units for WMS services). See Spatial reference system.

+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodReturnsDescription
latLngToPoint( + <LatLng> latlng, + <Number> zoom ) + PointProjects geographical coordinates on a given zoom into pixel coordinates.
pointToLatLng( + <Point> point, + <Number> zoom ) + LatLngThe inverse of latLngToPoint. Projects pixel coordinates on a given zoom into geographical coordinates.
project( + <LatLng> latlng ) + PointProjects geographical coordinates into coordinates in units accepted for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
scale( + <Number> zoom ) + NumberReturns the scale used when transforming projected coordinates into pixel coordinates for a particular zoom. For example, it returns 256 * 2^zoom for Mercator-based CRS.
getSize( + <Number> zoom ) + PointReturns the size of the world in pixels for a particular zoom.
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
projectionIProjectionProjection that this CRS uses.
transformationTransformationTransformation that this CRS uses to turn projected coordinates into screen coordinates for a particular tile service.
codeStringStandard code name of the CRS passed into WMS services (e.g. 'EPSG:3857').
+ +

Defined CRS

+ +

Leaflet comes with a set of already defined CRS to use out of the box:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ProjectionDescription
L.CRS.EPSG3857The most common CRS for online maps, used by almost all free and commercial tile providers. Uses Spherical Mercator projection. Set in by default in Map's crs option.
L.CRS.EPSG4326A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
L.CRS.EPSG3395Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
L.CRS.SimpleA simple CRS that maps longitude and latitude into x and y directly. May be used for maps of flat surfaces (e.g. game maps). Note that the y axis should still be inverted (going from bottom to top).
+ +

If you want to use some obscure CRS not listed here, take a look at the Proj4Leaflet plugin.

+ + +

Global Switches

+ +

Global switches are created for rare cases and generally make Leaflet to not detect a particular browser feature even if it's there. You need to set the switch as a global variable to true before including Leaflet on the page, like this:

+ +
<script>L_PREFER_CANVAS = true;</script>
+<script src="leaflet.js"></script>
+ + + + + + + + + + + + + + + + + + +
SwitchDescription
L_PREFER_CANVASForces Leaflet to use the Canvas back-end (if available) for vector layers instead of SVG. This can increase performance considerably in some cases (e.g. many thousands of circle markers on the map).
L_NO_TOUCHForces Leaflet to not use touch events even if it detects them.
L_DISABLE_3DForces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning (which may cause glitches in some rare environments) even if they're supported.
+ +

noConflict

+ +

This method restores the L global variable 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.
+ + +

version

+ +

A constant that represents the Leaflet version in use.

+ +

L.version // contains "0.5" (or whatever version is currently in use)
+ + diff --git a/docs/reference-versions.html b/docs/reference-versions.html index e43f9a70..eaa2e9a0 100644 --- a/docs/reference-versions.html +++ b/docs/reference-versions.html @@ -9,7 +9,7 @@ bodyclass: api-page

This page lists the API references for several Leaflet versions.