Leaflet

A Modern, Lightweight Open-Source JavaScript Library for Interactive Maps by CloudMade

UI layers

Raster layers

Vector layers


L.Map

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

Usage example

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

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

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

Constructor

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

Options

Option Type Default value Description
center LatLng null Initial geographical center of the map.
zoom Number null Initial map zoom.
layers ILayer[] [] Layers that will be added to the map initially.
dragging Boolean true Whether the map be draggable with mouse/touch or not.
touchZoom Boolean true Whether the map can be zoomed by touch-dragging with two fingers.
scrollWheelZoom Boolean true Whether the map can be zoomed by using the mouse wheel.
doubleClickZoom Boolean true Whether the map can be zoomed in by double clicking on it.
zoomControl Boolean true Whether the zoom control is added to the map by default.
attributionControl Boolean true Whether the attribution control is added to the map by default.
trackResize Boolean true Whether the map automatically handles browser window resize to update itself.
fadeAnimation Boolean depends Whether the tile fade animation is enabled. By default it's enabled in all browsers that support CSS3 Transitions except Android.
zoomAnimation Boolean depends Whether the tile fade animation is enabled. By default it's enabled in all browsers that support CSS3 Transitions except Android.

Properties

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

map.doubleClickZoom.disable();

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

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

Events

You can subscribe to the following events using these methods.

Event Data Description
click MouseEvent Fired when the user clicks (or taps) the map.
dblclick MouseEvent Fired when the user double-clicks (or double-taps) the map.
mousedown MouseEvent Fired when the user pushes the mouse button on the map.
load Event Fired when the map is initialized (when its center and zoom are set for the first time).
viewreset Event Fired when the map needs to redraw its content (this usually happens on map zoom or load). Very useful for creating custom overlays.
movestart Event Fired when the view of the map starts changing (e.g. user starts dragging the map).
move Event Fired on any movement of the map view.
moveend Event Fired when the view of the map ends changed (e.g. user stopped dragging the map).
zoomend Event Fired when the map zoom changes.
layeradd LayerEvent Fired when a new layer is added to the map.
layerremove LayerEvent Fired when some layer is removed from the map.
locationfound LocationEvent Fired when geolocation (using locate or locateAndSetView method) went successfully.

Methods that modify map state

Method Returns Description
setView( <LatLng> center, <Number> zoom, <Boolean> forceReset? ) this Sets the view of the map (geographical center and zoom). If forceReset is set to true, the map is reloaded even if it's eligible for pan or zoom animation (false by default).
setZoom( <Number> zoom ) this Sets the zoom of the map.
zoomIn() this Increases the zoom of the map by 1.
zoomOut() this Decreases the zoom of the map by 1.
fitBounds( <LatLngBounds> bounds ) this Sets a map view that contains the given geographical bounds with the maximum zoom level possible.
panTo( <LatLng> latlng ) this Pans the map to a given center. Makes an animated pan if new center is not more than one screen away from the current one.
panBy( <Point> point ) this Pans the map by a given number of pixels (animated).
invalidateSize() this Checks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically.
locate( <Boolean> noAutoFitBounds? ) this Tries to locate the user using Geolocation API and zooms the map if successful, firing locationfound (with location data) or locationerror event. Set noAutoFitBounds to true if you don't want the map view to be set automatically (false by default).

Methods that get map state

Method Returns Description
getCenter() LatLng Returns the geographical center of the map view.
getZoom() Number Returns the current zoom of the map view.
getMinZoom() Number Returns the minimum zoom level of the map.
getMaxZoom() Number Returns the maximum zoom level of the map.
getBoundsZoom( <LatLngBounds> bounds ) Number Returns the maximum zoom level on which the given bounds fit to the map view in its entirety.
getSize() Point Returns the current size of the map container.
getPixelBounds() Bounds Returns the bounds of the current map view in projected pixel coordinates (sometimes useful in layer and overlay implementations).
getPixelOrigin() Point Returns the projected pixel coordinates of the top left point of the map layer (useful in custom layer and overlay implementations).
getPanes() Panes Returns an object for accessing different panes of the map (tile pane, marker pane, etc.).

Methods for layers and controls

addLayer( <ILayer> layer ) this Adds the given layer to the map.
removeLayer( <ILayer> layer ) this Removes the given layer from the map.
openPopup( <Popuppopup ) this Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
closePopup() this Closes the popup opened with openPopup.
addControl( <IControlcontrol ) this Adds the given control to the map.
removeControl( <IControlcontrol ) this Removes the given control from the map.

Conversion methods

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

Other methods

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

Map panes

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

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

L.Marker

Used to put markers on the map.

Usage example

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

Constructor

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

Options

Option Type Default value Description
icon Class
(L.Icon or its child)
L.Icon Icon class to use for rendering the marker. See Icon documentation for details on how to customize the marker icon.
clickable Boolean true If false, the marker will not emit mouse events and will act as a part of the underlying map.
draggable Boolean false Whether the marker is draggable with mouse/touch or not.

Events

You can subscribe to the following events using these methods.

Event Data Description
click Event Fired when the user clicks (or taps) the marker.
dblclick Event Fired when the user double-clicks (or double-taps) the marker.

Methods

Method Returns Description
getLatLng() LatLng Returns the current geographical position of the marker.
bindPopup( <String> htmlContent, <Popup optionsoptions? ) this Binds a popup with a particular HTML content to a click on this marker. You can also open the bound popup with the Marker openPopup method.
openPopup() this Opens the popup previously bound by the bindPopup method.

Interaction handlers

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

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

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

Usage example

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

marker.bindPopup(popupContent).openPopup();

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

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

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

map.openPopup(popup);

Constructor

Constructor Description
L.Popup( <Popup optionsoptions? ) Instantiates a Popup object given the geographical point where it will open, the HTML content it will have and optionally an options object.
Option Type Default value Description
maxWidth Number 300 Max width of the popup.
autoPan Boolean true Set it to false if you don't want the map to do panning animation to fit the opened popup.'
closeButton Boolean true Controls the presense of a close button in the popup.
closeMapOnClick Boolean true Set it to false if you don't want the popup to close when user clicks the map.
offset Point Point(0, 0) The offset of the popup position. Useful to control the anchor of the popup when opening it on some overlays.

Methods

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

L.TileLayer

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

Usage example

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

Constructor

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

URL template

A string of the following form:

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

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

Options

Option Type Default value Description
minZoom Number 0 Minimum zoom number.
maxZoom Number 18 Maximum zoom number.
tileSize Number 256 Tile size (width and height in pixels, assuming tiles are square).
subdomains String or String[] 'abc' Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.
errorTileUrl String '' URL to the tile image to show in place of the tile that failed to load.
attribution String '' e.g. "© CloudMade" — the string used by the attribution control, describes the layer data.
unloadInvisibleTiles Boolean depends If true, all the tiles that are not visible after panning are removed (for better performance). true by default on mobile WebKit, otherwise false.
updateWhenIdle Boolean depends If false, new tiles are loaded during panning, otherwise only after it (for better performance). true by default on mobile WebKit, otherwise false.

L.ImageOverlay

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

Usage example

var imageBounds = new L.LatLngBounds(
		new L.LatLng(40.712216,-74.22655),
		new L.LatLng(40.773941,-74.12544));
		
var image = new L.ImageOverlay(
		"http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg", imageBounds);

Constructor

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

L.Path

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

Options

Option Type Default value Description
stroke Boolean true Whether to draw stroke along the path. Set it to false to disable borders on polygons or circles.
color String '#03f' Stroke color.
weight Number 5 Stroke width in pixels.
opacity Number 0.5 Stroke opacity.
fill Boolean depends Whether to fill the path with color. Set it to false to disable filling on polygons or circles.
fillColor String same as color Fill color.
fillOpacity Number 0.2 Fill opacity.

Events

You can subscribe to the following events using these methods.

Event Data Description
click Event Fired when the user clicks (or taps) the object.
dblclick Event Fired when the user double-clicks (or double-taps) the object.

Constants

Constant Type Value Description
L.Path.SVG Boolean depends True if SVG is used for vector rendering (true for most modern browsers).
L.Path.VML Boolean depends True if VML is used for vector rendering (IE 6-8).
L.Path.CLIP_PADDING Number 0.5 for SVG
0.02 for VML
How much to extend the clip area around the map view (relative to its size, e.g. 0.5 is half the screen in each direction). Smaller values mean that you will see clipped ends of paths while you're dragging the map, and bigger values decrease drawing performance.

L.Polyline

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

Usage example

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

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

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

Constructor

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

Options

You can use Path options and additionally the following options:

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

L.Polygon

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

Constructor

Constructor Description
L.Polygon( <LatLng[]> latlngs, <Polyline optionsoptions? ) Instantiates a polygon object given an array of geographical points and optionally an options object (the same as for Polyline).

L.Circle

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

Constructor

Constructor Description
L.Circle( <LatLnglatlng, <Number> radius, <Path optionsoptions? ) Instantiates a polygon object given an geographical point, a radius in pixels and optionally an options object.

L.LatLng

Represents a geographical point with a certain latitude and longitude.

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

Constructor

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

Properties

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

Methods

Method Returns Description
equals( <LatLngotherLatlng ) Boolean Returns true if the given LatLng point is at the same position (within a small margin of error).
toString() String Returns a string representation of the point (for debugging purposes).

Constants

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

L.LatLngBounds

Represents a rectangular geographical area on a map.

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

Constructor

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

Methods

Method Returns Description
extend( <LatLnglatlng ) - Extends the bounds to contain the given LatLng point.
getSouthWest() LatLng Returns the south-west point of the bounds.
getNorthEast() LatLng Returns the north-east point of the bounds.
getNorthWest() LatLng Returns the north-west point of the bounds.
getSouthEast() LatLng Returns the south-east point of the bounds.
getCenter() LatLng Returns the center point of the bounds.
contains( <LatLngBoundsotherBounds ) Boolean Returns true if the rectangle contains the given one.

L.Point

Represents a point with x and y coordinates in pixels.

Constructor

Constructor Description
L.Point( <Number> x, <Number> y ) Creates a Point object with the given x and y coordinates.

Properties

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

Methods

Method Returns Description
add( <PointotherPoint ) Point Returns the result of addition of the current and the given points.
subtract( <PointotherPoint ) Point Returns the result of subtraction of the given point from the current.
multiplyBy( <Number> number ) Point Returns the result of multiplication of the current point by the given number.
divideBy( <Number> number ) Point Returns the result of division of the current point by the given number.
distanceTo( <PointotherPoint ) Number Returns the distance between the current and the given points.
clone() Point Returns a copy of the current point.
round() Point Returns a copy of the current point with rounded coordinates.
toString() String Returns a string representation of the point for debugging purposes.

L.Bounds

Represents a rectangular area in pixel coordinates.

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

Constructor

Constructor Description
L.Bounds( <PointtopLeft, <PointbottomRight ) Creates a Bounds object by defining top-left and bottom-right coordinates of the rectangle.
L.LatLngBounds( <Point[]>points ) Creates a Bounds object defined by the points it contains.

Properties

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

Methods

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

L.Control.Zoom

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

Constructor

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

L.Control.Attribution

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

Constructor

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

Methods

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

Events methods

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

Example

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

Methods

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

Event objects

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

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

Event

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

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

MouseEvent

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

LocationEvent

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

LayerEvent

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

IHandler

An interface implemented by interaction handlers.

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

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

Fork me on GitHub