Leaflet参考书API-Reference-0.7.7

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

Map

Map Methods

Map Misc

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 optionsoptions? )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.
baselayerchangeLayerEventFired when the base layer is changed through the layer control.
overlayaddLayerEventFired when an overlay is selected through the layer control.
overlayremoveLayerEventFired when an overlay is deselected through the layer control.
locationfoundLocationEventFired when geolocation (using the locate method) went successfully.
locationerrorErrorEventFired 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( <LatLngcenter, <Number> zoom?, <zoom/pan optionsoptions? )thisSets the view of the map (geographical center and zoom) with the given animation options.
setZoom( <Number> zoom, <zoom optionsoptions? )thisSets the zoom of the map.
zoomIn( <Number> delta?, <zoom optionsoptions? )thisIncreases the zoom of the map by delta (1 by default).
zoomOut( <Number> delta?, <zoom optionsoptions? )thisDecreases the zoom of the map by delta (1 by default).
setZoomAround( <LatLnglatlng, <Number> zoom, <zoom optionsoptions? )thisZooms the map while keeping a specified point on the map stationary (e.g. used internally for scroll zoom and double-click zoom).
fitBounds( <LatLngBoundsbounds, <fitBounds optionsoptions? )thisSets a map view that contains the given geographical bounds with the maximum zoom level possible.
fitWorld( <fitBounds optionsoptions? )thisSets a map view that mostly contains the whole world with the maximum zoom level possible.
panTo( <LatLnglatlng, <pan optionsoptions? )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( <LatLngBoundsbounds, <pan optionsoptions? )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( <Pointpoint, <pan optionsoptions? )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 optionsoptions )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( <LatLngBoundsboundsthisRestricts the map view to the given bounds (see map maxBounds option).
locate( <Locate optionsoptions? )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( <LatLngBoundsbounds, <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( <ILayerlayer )thisAdds the given layer to the map.
removeLayer( <ILayerlayer )thisRemoves the given layer from the map.
hasLayer( <ILayerlayer )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( <Popuppopup )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, <LatLnglatlng, <Popup optionsoptions? )thisCreates a popup with the specified options and opens it in the given point on a map.
closePopup( <Popuppopup? )thisCloses the popup previously opened with openPopup (or the given one).
addControl( <IControlcontrol )thisAdds the given control to the map.
removeControl( <IControlcontrol )thisRemoves the given control from the map.

Conversion Methods

MethodReturnsDescription
latLngToLayerPoint( <LatLnglatlng )PointReturns the map layer point that corresponds to the given geographical coordinates (useful for placing overlays on the map).
layerPointToLatLng( <Pointpoint )LatLngReturns the geographical coordinates of a given map layer point.
containerPointToLayerPoint( <Pointpoint )PointConverts the point relative to the map container to a point relative to the map layer.
layerPointToContainerPoint( <Pointpoint )PointConverts the point relative to the map layer to a point relative to the map container.
latLngToContainerPoint( <LatLnglatlng )PointReturns the map container point that corresponds to the given geographical coordinates.
containerPointToLatLng( <Pointpoint )LatLngReturns the geographical coordinates of a given map container point.
project( <LatLnglatlng, <Number> zoom? )PointProjects the given geographical coordinates to absolute pixel coordinates for the given zoom level (current zoom level by default).
unproject( <Pointpoint, <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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值