From 560e73bac54624df89d01be45cf0a77bc09f94fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20S=C3=A1nchez=20Ortega?= Date: Wed, 12 Aug 2015 20:51:04 +0200 Subject: [PATCH] Trying out Leafdoc comments in L.Marker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added Leafdoc comments to Layer.js Leafdoc comments for Popup, Layer Leafdoc comments: L.Evented, inheritances, minor tilelayer Leafdoc comments: gridlayer & tilelayer options Leafdoc comments: tilelayer, marker drag Typos Leafdoc: switch to shorthand method params Leafdoc: Switch to shorthands in marker drag, WMS. Leafdoc: Vector layers Leafdoc: Layer group, feature group, geojson Leafdoc: LatLng, Point, Bounds, Icons. Leafdoc: Controls. Leafdoc: DOM & utils. Leafdoc: "jake docs" now builds the documentation Leafdoc: Commit actual templates instead of symlinks Leafdoc: Fix broken build, have jake print out uglifyjs errors Leafdoc: Several L.Map bits. Leafdoc: Map handlers Leafdoc: Map events, L.CRS, misc. fixes Leafdoc: Fixed ordering of classes by using new leafdoc features Leafdoc: Misc bits at the bottom of the docs 🍂doc: Map panes 🍂doc: CRSs, projections and their templates 🍂doc: miniclasses for map methods' options Leafdoc: Cleanup L.Class, mark uninheritable sections, use Leafdoc 0.3.0 🍂doc: miniclasses for event types, bump to Leafdoc 1.0.0 🍂doc: Make linter happy after branch rebase 🍂doc: Tweaked headers for inherited stuff. 🍂doc: Tweaking section headers (white, padding, triangles) Leafdoc: upgrade to 1.2, document SVG&Canvas, and misc bits 🍂doc: minor CSS tweaks, version in filename, typo. Add missing bits - supersedes #4105, #4065, #4031 🍂doc: moved sections around, minor typos & fixes Typo about LocationEvent --- .gitignore | 1 + Jakefile.js | 8 +- build/build.js | 19 +- build/docs-index.leafdoc | 60 +++ build/docs-misc.leafdoc | 51 +++ build/docs.js | 36 ++ build/leafdoc-templates/comments.hbs | 1 + build/leafdoc-templates/crs.hbs | 13 + build/leafdoc-templates/event.hbs | 15 + build/leafdoc-templates/example.hbs | 4 + build/leafdoc-templates/factory.hbs | 17 + build/leafdoc-templates/function.hbs | 19 + build/leafdoc-templates/html.hbs | 316 +++++++++++++++ build/leafdoc-templates/inherited.hbs | 7 + build/leafdoc-templates/method.hbs | 19 + build/leafdoc-templates/namespace.hbs | 7 + build/leafdoc-templates/option.hbs | 17 + build/leafdoc-templates/pane.hbs | 17 + build/leafdoc-templates/projection.hbs | 13 + build/leafdoc-templates/property.hbs | 15 + build/leafdoc-templates/section.hbs | 11 + build/leafdoc-templates/supersection.hbs | 7 + package.json | 1 + src/control/Control.Attribution.js | 24 +- src/control/Control.Layers.js | 66 +++- src/control/Control.Scale.js | 30 +- src/control/Control.Zoom.js | 27 +- src/control/Control.js | 8 + src/core/Browser.js | 82 +++- src/core/Class.js | 25 +- src/core/Class.leafdoc | 191 +++++++++ src/core/Events.js | 73 +++- src/core/Events.leafdoc | 116 ++++++ src/core/Handler.js | 17 + src/core/Util.js | 73 +++- src/dom/DomEvent.js | 57 ++- src/dom/DomUtil.js | 78 +++- src/dom/Draggable.js | 33 +- src/dom/PosAnimation.js | 30 +- src/geo/LatLng.js | 51 ++- src/geo/LatLngBounds.js | 86 +++- src/geo/crs/CRS.EPSG3395.js | 5 +- src/geo/crs/CRS.EPSG3857.js | 7 +- src/geo/crs/CRS.EPSG4326.js | 5 +- src/geo/crs/CRS.Earth.js | 7 +- src/geo/crs/CRS.Simple.js | 7 +- src/geo/crs/CRS.js | 58 ++- src/geo/projection/Projection.LonLat.js | 11 +- src/geo/projection/Projection.Mercator.js | 6 +- .../Projection.SphericalMercator.js | 7 +- src/geo/projection/Projection.leafdoc | 16 + src/geometry/Bounds.js | 61 ++- src/geometry/LineUtil.js | 24 +- src/geometry/Point.js | 60 ++- src/geometry/PolyUtil.js | 11 +- src/geometry/Transformation.js | 25 +- src/layer/FeatureGroup.js | 26 +- src/layer/GeoJSON.js | 102 ++++- src/layer/ImageOverlay.js | 39 +- src/layer/Layer.Popup.js | 32 +- src/layer/Layer.js | 90 +++++ src/layer/LayerGroup.js | 50 ++- src/layer/Popup.js | 163 +++++++- src/layer/marker/DivIcon.js | 43 +- src/layer/marker/Icon.js | 86 +++- src/layer/marker/Marker.Drag.js | 27 ++ src/layer/marker/Marker.js | 108 ++++- src/layer/tile/GridLayer.js | 142 ++++++- src/layer/tile/TileLayer.WMS.js | 48 ++- src/layer/tile/TileLayer.js | 79 +++- src/layer/vector/Canvas.js | 35 +- src/layer/vector/Circle.js | 29 +- src/layer/vector/CircleMarker.js | 20 +- src/layer/vector/Path.js | 74 +++- src/layer/vector/Polygon.js | 46 ++- src/layer/vector/Polyline.js | 67 +++- src/layer/vector/Rectangle.js | 27 ++ src/layer/vector/Renderer.js | 34 +- src/layer/vector/SVG.VML.js | 12 +- src/layer/vector/SVG.js | 53 ++- src/map/Map.js | 372 ++++++++++++++++-- src/map/Map.methodOptions.leafdoc | 108 +++++ src/map/anim/Map.FlyTo.js | 10 +- src/map/anim/Map.ZoomAnimation.js | 8 + src/map/ext/Map.Geolocation.js | 19 + src/map/handler/Map.BoxZoom.js | 12 +- src/map/handler/Map.DoubleClickZoom.js | 20 + src/map/handler/Map.Drag.js | 36 +- src/map/handler/Map.Keyboard.js | 12 + src/map/handler/Map.ScrollWheelZoom.js | 18 + src/map/handler/Map.Tap.js | 13 + src/map/handler/Map.TouchZoom.js | 15 + 92 files changed, 3903 insertions(+), 223 deletions(-) create mode 100644 build/docs-index.leafdoc create mode 100644 build/docs-misc.leafdoc create mode 100644 build/docs.js create mode 100644 build/leafdoc-templates/comments.hbs create mode 100644 build/leafdoc-templates/crs.hbs create mode 100644 build/leafdoc-templates/event.hbs create mode 100644 build/leafdoc-templates/example.hbs create mode 100644 build/leafdoc-templates/factory.hbs create mode 100644 build/leafdoc-templates/function.hbs create mode 100644 build/leafdoc-templates/html.hbs create mode 100644 build/leafdoc-templates/inherited.hbs create mode 100644 build/leafdoc-templates/method.hbs create mode 100644 build/leafdoc-templates/namespace.hbs create mode 100644 build/leafdoc-templates/option.hbs create mode 100644 build/leafdoc-templates/pane.hbs create mode 100644 build/leafdoc-templates/projection.hbs create mode 100644 build/leafdoc-templates/property.hbs create mode 100644 build/leafdoc-templates/section.hbs create mode 100644 build/leafdoc-templates/supersection.hbs create mode 100644 src/core/Class.leafdoc create mode 100644 src/core/Events.leafdoc create mode 100644 src/geo/projection/Projection.leafdoc create mode 100644 src/map/Map.methodOptions.leafdoc diff --git a/.gitignore b/.gitignore index 3e1080a7c..324290c9c 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ tmp/**/* _site dist/*.js dist/*.map +dist/reference.html coverage/ *.js.html index.html diff --git a/Jakefile.js b/Jakefile.js index 62e9ed2dc..b027ad3fb 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -7,12 +7,13 @@ To use, install Node, then run the following commands in the project root: npm install To check the code for errors and build Leaflet from source, run "jake". -To run the tests, run "jake test". +To run the tests, run "jake test". To build the documentation, run "jake docs". For a custom build, open build/build.html in the browser and follow the instructions. */ var build = require('./build/build.js'), + buildDocs = require('./build/docs'), version = require('./src/Leaflet.js').version; function hint(msg, args) { @@ -51,6 +52,11 @@ task('test', ['lint', 'lintspec'], {async: true}, function () { build.test(complete); }); +desc('Build documentation'); +task('docs', {}, function() { + buildDocs(); +}); + task('default', ['test', 'build']); jake.addListener('complete', function () { diff --git a/build/build.js b/build/build.js index dd11b2ef4..d5ddd6edd 100644 --- a/build/build.js +++ b/build/build.js @@ -126,11 +126,20 @@ exports.build = function (callback, version, compsBase32, buildName) { var path = pathPart + '.js', oldCompressed = loadSilently(path), - newCompressed = copy + UglifyJS.minify(newSrc, { - warnings: true, - fromString: true - }).code, - delta = getSizeDelta(newCompressed, oldCompressed); + newCompressed; + + try { + newCompressed = copy + UglifyJS.minify(newSrc, { + warnings: true, + fromString: true + }).code; + } catch(err) { + console.error('UglifyJS failed to minify the files'); + console.error(err); + callback(err); + } + + var delta = getSizeDelta(newCompressed, oldCompressed); console.log('\tCompressed: ' + bytesToKB(newCompressed.length) + delta); diff --git a/build/docs-index.leafdoc b/build/docs-index.leafdoc new file mode 100644 index 000000000..0c802a6fd --- /dev/null +++ b/build/docs-index.leafdoc @@ -0,0 +1,60 @@ +This file just defines the order of the classes in the docs. + + + + +🍂class Map + +🍂class Marker +🍂class Popup + +🍂class TileLayer +🍂class TileLayer.WMS +🍂class ImageOverlay + +🍂class Path +🍂class Polyline +🍂class Polygon +🍂class Rectangle +🍂class Circle +🍂class CircleMarker +🍂class SVG +🍂class Canvas + +🍂class LayerGroup +🍂class FeatureGroup +🍂class GeoJSON +🍂class GridLayer + +🍂class LatLng +🍂class LatLngBounds +🍂class Point +🍂class Bounds +🍂class Icon +🍂class DivIcon + +🍂class Control.Zoom +🍂class Control.Attribution +🍂class Control.Layers +🍂class Control.Scale + +🍂class Browser +🍂class Util +🍂class Transformation +🍂class LineUtil +🍂class PolyUtil + +🍂class DomEvent +🍂class DomUtil +🍂class PosAnimation +🍂class Draggable + +🍂class Class +🍂class Evented +🍂class Layer +🍂class Control +🍂class Handler +🍂class Projection +🍂class CRS +🍂class Renderer +🍂class Event objects diff --git a/build/docs-misc.leafdoc b/build/docs-misc.leafdoc new file mode 100644 index 000000000..2c222cb74 --- /dev/null +++ b/build/docs-misc.leafdoc @@ -0,0 +1,51 @@ +Miscellaneous bits of documentation that don't really fit anywhere else + + + +🍂namespace 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: + +```html + + +``` + +| Switch | Description | +| -------------- | ---------------- | +| `L_NO_TOUCH` | Forces Leaflet to not use touch events even if it detects them. | +| `L_DISABLE_3D` | Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning (which may cause glitches in some rare environments) even if they're supported. | + + +🍂namespace 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: + +```html + +``` + + +🍂namespace version + +A constant that represents the Leaflet version in use. + +```js +L.version; // contains "1.0.0" (or whatever version is currently in use) +``` + + diff --git a/build/docs.js b/build/docs.js new file mode 100644 index 000000000..f24ce904a --- /dev/null +++ b/build/docs.js @@ -0,0 +1,36 @@ + +var packageDef = require('../package.json'); + +function buildDocs() { + + console.log('Building Leaflet documentation with Leafdoc'); + + var LeafDoc = require('leafdoc'); + var doc = new LeafDoc({ + templateDir: 'build/leafdoc-templates', + showInheritancesWhenEmpty: true + }); + + // Note to Vladimir: Iván's never gonna uncomment the following line. He's + // too proud of the little leaves around the code. + //doc.setLeadingChar('@'); + + // Leaflet uses a couple of non-standard documentable things. They are not + // important enough to be classes/namespaces of their own, and should + // just be listed in a table like the rest of documentables: + doc.registerDocumentable('pane', 'Map panes'); + doc.registerDocumentable('projection', 'Defined projections'); + doc.registerDocumentable('crs', 'Defined CRSs'); + + doc.addFile('build/docs-index.leafdoc', false); + doc.addDir('src'); + doc.addFile('build/docs-misc.leafdoc', false); + + var out = doc.outputStr(); + + var fs = require('fs'); + + fs.writeFileSync('dist/reference-' + packageDef.version + '.html', out); +} + +module.exports = buildDocs; \ No newline at end of file diff --git a/build/leafdoc-templates/comments.hbs b/build/leafdoc-templates/comments.hbs new file mode 100644 index 000000000..8faffef07 --- /dev/null +++ b/build/leafdoc-templates/comments.hbs @@ -0,0 +1 @@ +{{{rawmarkdown comments}}} \ No newline at end of file diff --git a/build/leafdoc-templates/crs.hbs b/build/leafdoc-templates/crs.hbs new file mode 100644 index 000000000..e28758703 --- /dev/null +++ b/build/leafdoc-templates/crs.hbs @@ -0,0 +1,13 @@ + + + + + + + {{#each documentables}} + + + + + {{/each}} +
CRSDescription
{{name}}{{{markdown comments}}}
\ No newline at end of file diff --git a/build/leafdoc-templates/event.hbs b/build/leafdoc-templates/event.hbs new file mode 100644 index 000000000..b55c22a14 --- /dev/null +++ b/build/leafdoc-templates/event.hbs @@ -0,0 +1,15 @@ + + + + + + + + {{#each documentables}} + + + + + {{/each}} +
EventDataDescription
{{name}} + {{{type type}}}{{{markdown comments}}}
\ No newline at end of file diff --git a/build/leafdoc-templates/example.hbs b/build/leafdoc-templates/example.hbs new file mode 100644 index 000000000..7b63b4d5f --- /dev/null +++ b/build/leafdoc-templates/example.hbs @@ -0,0 +1,4 @@ + +{{#each documentables}} +{{{rawmarkdown comments}}} +{{/each}} \ No newline at end of file diff --git a/build/leafdoc-templates/factory.hbs b/build/leafdoc-templates/factory.hbs new file mode 100644 index 000000000..e3b4bfeb2 --- /dev/null +++ b/build/leafdoc-templates/factory.hbs @@ -0,0 +1,17 @@ + + + + + + + {{#each documentables}} + + + + + {{/each}} +
FactoryDescription
{{name}}( + {{~#each params~}} + {{#if type}}<{{{type type}}}> {{/if}}{{name}} + {{~#unless @last}}, {{/unless}}{{/each~}} + ){{{markdown comments}}}
\ No newline at end of file diff --git a/build/leafdoc-templates/function.hbs b/build/leafdoc-templates/function.hbs new file mode 100644 index 000000000..d01d5615e --- /dev/null +++ b/build/leafdoc-templates/function.hbs @@ -0,0 +1,19 @@ + + + + + + + + {{#each documentables}} + + + + + + {{/each}} +
FunctionReturnsDescription
{{name}}( + {{~#each params~}} + {{#if type}}<{{{type type}}}> {{/if}}{{name}} + {{~#unless @last}}, {{/unless}}{{/each~}} + ){{{type type}}}{{{markdown comments}}}
\ No newline at end of file diff --git a/build/leafdoc-templates/html.hbs b/build/leafdoc-templates/html.hbs new file mode 100644 index 000000000..afb07bf85 --- /dev/null +++ b/build/leafdoc-templates/html.hbs @@ -0,0 +1,316 @@ + + + + {{ title }} + + + + + + + + + + +
+ +

Leaflet API reference

+
+ +
+

UI Layers

+ +

Raster Layers

+ +

Vector Layers

+ +
+
+

Other Layers

+ +

Basic Types

+ +

Controls

+ +
+
+ + + + + + +

Utility

+ +

DOM Utility

+ +
+
+

Base Classes

+ + +

Misc

+ +
+
+ + {{{ body }}} + + + + + +
+ + + + + \ No newline at end of file diff --git a/build/leafdoc-templates/inherited.hbs b/build/leafdoc-templates/inherited.hbs new file mode 100644 index 000000000..405988829 --- /dev/null +++ b/build/leafdoc-templates/inherited.hbs @@ -0,0 +1,7 @@ + +
+ +
+
{{{inherited}}}
+
+
diff --git a/build/leafdoc-templates/method.hbs b/build/leafdoc-templates/method.hbs new file mode 100644 index 000000000..865af0196 --- /dev/null +++ b/build/leafdoc-templates/method.hbs @@ -0,0 +1,19 @@ + + + + + + + + {{#each documentables}} + + + + + + {{/each}} +
MethodReturnsDescription
{{name}}( + {{~#each params~}} + {{#if type}}<{{{type type}}}> {{/if}}{{name}} + {{~#unless @last}}, {{/unless}}{{/each~}} + ){{{type type}}}{{{rawmarkdown comments}}}
\ No newline at end of file diff --git a/build/leafdoc-templates/namespace.hbs b/build/leafdoc-templates/namespace.hbs new file mode 100644 index 000000000..2a90a7010 --- /dev/null +++ b/build/leafdoc-templates/namespace.hbs @@ -0,0 +1,7 @@ +{{#if name ~}} +

{{name}}

+{{~ else ~}} + +{{/if}} +{{{rawmarkdown comments}}} +{{{supersections}}} \ No newline at end of file diff --git a/build/leafdoc-templates/option.hbs b/build/leafdoc-templates/option.hbs new file mode 100644 index 000000000..61d406591 --- /dev/null +++ b/build/leafdoc-templates/option.hbs @@ -0,0 +1,17 @@ + + + + + + + + + {{#each documentables}} + + + + + + {{/each}} +
OptionTypeDefaultDescription
{{name}}{{{type type}}} + {{defaultValue}}{{{markdown comments}}}
\ No newline at end of file diff --git a/build/leafdoc-templates/pane.hbs b/build/leafdoc-templates/pane.hbs new file mode 100644 index 000000000..1e3ee9971 --- /dev/null +++ b/build/leafdoc-templates/pane.hbs @@ -0,0 +1,17 @@ + + + + + + + + + {{#each documentables}} + + + + + + {{/each}} +
PaneTypeZ-indexDescription
{{name}}{{{type type}}} + {{defaultValue}}{{{markdown comments}}}
\ No newline at end of file diff --git a/build/leafdoc-templates/projection.hbs b/build/leafdoc-templates/projection.hbs new file mode 100644 index 000000000..dc2b9f286 --- /dev/null +++ b/build/leafdoc-templates/projection.hbs @@ -0,0 +1,13 @@ + + + + + + + {{#each documentables}} + + + + + {{/each}} +
ProjectionDescription
{{name}}{{{markdown comments}}}
\ No newline at end of file diff --git a/build/leafdoc-templates/property.hbs b/build/leafdoc-templates/property.hbs new file mode 100644 index 000000000..ee4e9f2e7 --- /dev/null +++ b/build/leafdoc-templates/property.hbs @@ -0,0 +1,15 @@ + + + + + + + + {{#each documentables}} + + + + + {{/each}} +
PropertyTypeDescription
{{name}} + {{{type type}}}{{{markdown comments}}}
\ No newline at end of file diff --git a/build/leafdoc-templates/section.hbs b/build/leafdoc-templates/section.hbs new file mode 100644 index 000000000..4aba7770e --- /dev/null +++ b/build/leafdoc-templates/section.hbs @@ -0,0 +1,11 @@ +
+ +{{#if name}}

{{name}}

{{/if}} + +{{#if comments~}} +
{{{markdown comments}}}
+{{/if}} + +{{{documentables}}} + +
\ No newline at end of file diff --git a/build/leafdoc-templates/supersection.hbs b/build/leafdoc-templates/supersection.hbs new file mode 100644 index 000000000..09026390f --- /dev/null +++ b/build/leafdoc-templates/supersection.hbs @@ -0,0 +1,7 @@ +
+

{{name}}

+{{markdown comments}} +{{{sections}}} + +{{{inheritances}}} +
\ No newline at end of file diff --git a/package.json b/package.json index 76cf19272..7475d1e43 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "karma-mocha": "~0.2.0", "karma-phantomjs-launcher": "^1.0.0", "karma-safari-launcher": "~0.1.1", + "leafdoc": "^1.2.0", "magic-string": "^0.7.0", "mocha": "~2.3.0", "phantomjs-prebuilt": "^2.1.4", diff --git a/src/control/Control.Attribution.js b/src/control/Control.Attribution.js index 95618e874..f6005532a 100644 --- a/src/control/Control.Attribution.js +++ b/src/control/Control.Attribution.js @@ -1,10 +1,19 @@ /* - * L.Control.Attribution is used for displaying attribution on the map (added by default). + * 🍂class Control.Attribution + * 🍂aka L.Control.Attribution + * 🍂inherits Control + * + * 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](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control. */ L.Control.Attribution = L.Control.extend({ + // 🍂section + // 🍂aka Control.Attribution options options: { position: 'bottomright', + + // 🍂option prefix: String = 'Leaflet' + // The HTML text shown before the attributions. Pass `false` to disable. prefix: 'Leaflet' }, @@ -33,12 +42,16 @@ L.Control.Attribution = L.Control.extend({ return this._container; }, + // 🍂method setPrefix(prefix: String): this + // Sets the text before the attributions. setPrefix: function (prefix) { this.options.prefix = prefix; this._update(); return this; }, + // 🍂method addAttribution(text: String): this + // Adds an attribution text (e.g. `'Vector data © Mapbox'`). addAttribution: function (text) { if (!text) { return this; } @@ -52,6 +65,8 @@ L.Control.Attribution = L.Control.extend({ return this; }, + // 🍂method removeAttribution(text: String): this + // Removes an attribution text. removeAttribution: function (text) { if (!text) { return this; } @@ -87,6 +102,10 @@ L.Control.Attribution = L.Control.extend({ } }); +// 🍂namespace Map +// 🍂section Control options +// 🍂option attributionControl: Boolean = true +// Whether a [attribution control](#control-attribution) is added to the map by default. L.Map.mergeOptions({ attributionControl: true }); @@ -97,6 +116,9 @@ L.Map.addInitHook(function () { } }); +// 🍂namespace Control.Attribution +// 🍂factory L.control.attribution(options: Control.Attribution options) +// Creates an attribution control. L.control.attribution = function (options) { return new L.Control.Attribution(options); }; diff --git a/src/control/Control.Layers.js b/src/control/Control.Layers.js index a78e216eb..a3d02bcbd 100644 --- a/src/control/Control.Layers.js +++ b/src/control/Control.Layers.js @@ -1,12 +1,58 @@ /* - * L.Control.Layers is a control to allow users to switch between different layers on the map. + * 🍂class Control.Layers + * 🍂aka L.Control.Layers + * 🍂inherits Control + * + * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control.html)). Extends `Control`. + * + * 🍂example + * + * ```js + * var baseLayers = { + * "Mapbox": mapbox, + * "OpenStreetMap": osm + * }; + * + * var overlays = { + * "Marker": marker, + * "Roads": roadsLayer + * }; + * + * L.control.layers(baseLayers, overlays).addTo(map); + * ``` + * + * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values: + * + * ```js + * { + * "": layer1, + * "": layer2 + * } + * ``` + * + * The layer names can contain HTML, which allows you to add additional styling to the items: + * + * ```js + * {" My Layer": myLayer} + * ``` */ + L.Control.Layers = L.Control.extend({ + // 🍂section + // 🍂aka Control.Layers options options: { + // 🍂option collapsed: Boolean = true + // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch. collapsed: true, position: 'topright', + + // 🍂option autoZIndex: Boolean = true + // If `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. autoZIndex: true, + + // 🍂option hideSingleBase: Boolean = false + // If `true`, the base layers in the control will be hidden when there is only one. hideSingleBase: false }, @@ -44,16 +90,22 @@ L.Control.Layers = L.Control.extend({ } }, + // 🍂method addBaseLayer(layer: Layer, name: String): this + // Adds a base layer (radio button entry) with the given name to the control. addBaseLayer: function (layer, name) { this._addLayer(layer, name); return (this._map) ? this._update() : this; }, + // 🍂method addOverlay(layer: Layer, name: String): this + // Adds an overlay (checkbox entry) with the given name to the control. addOverlay: function (layer, name) { this._addLayer(layer, name, true); return (this._map) ? this._update() : this; }, + // 🍂method removeLayer(layer: Layer): this + // Remove the given layer from the control. removeLayer: function (layer) { layer.off('add remove', this._onLayerChange, this); @@ -164,6 +216,15 @@ L.Control.Layers = L.Control.extend({ var obj = this._layers[L.stamp(e.target)]; + // 🍂namespace Map + // 🍂section Layer events + // 🍂event baselayerchange: LayersControlEvent + // Fired when the base layer is changed through the [layer control](#control-layers). + // 🍂event overlayadd: LayersControlEvent + // Fired when an overlay is selected through the [layer control](#control-layers). + // 🍂event overlayremove: LayersControlEvent + // Fired when an overlay is deselected through the [layer control](#control-layers). + // 🍂namespace Control.Layers var type = obj.overlay ? (e.type === 'add' ? 'overlayadd' : 'overlayremove') : (e.type === 'add' ? 'baselayerchange' : null); @@ -288,6 +349,9 @@ L.Control.Layers = L.Control.extend({ } }); + +// 🍂factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers 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. L.control.layers = function (baseLayers, overlays, options) { return new L.Control.Layers(baseLayers, overlays, options); }; diff --git a/src/control/Control.Scale.js b/src/control/Control.Scale.js index 7e7a4de84..0f68a2900 100644 --- a/src/control/Control.Scale.js +++ b/src/control/Control.Scale.js @@ -1,14 +1,37 @@ /* - * L.Control.Scale is used for displaying metric/imperial scale on the map. + * 🍂class Control.Scale + * 🍂aka L.Control.Scale + * 🍂inherits Control + * + * 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`. + * + * 🍂example + * + * ```js + * L.control.scale().addTo(map); + * ``` */ L.Control.Scale = L.Control.extend({ + // 🍂section + // 🍂aka Control.Scale options options: { position: 'bottomleft', + + // 🍂option maxWidth: Number = 100 + // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500). maxWidth: 100, + + // 🍂option metric: Boolean = True + // Whether to show the metric scale line (m/km). metric: true, + + // 🍂option imperial: Boolean = True + // Whether to show the imperial scale line (mi/ft). imperial: true - // updateWhenIdle: false + + // 🍂option updateWhenIdle: Boolean = false + // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)). }, onAdd: function (map) { @@ -97,6 +120,9 @@ L.Control.Scale = L.Control.extend({ } }); + +// 🍂factory L.control.scale(options?: Control.Scale options) +// Creates an scale control with the given options. L.control.scale = function (options) { return new L.Control.Scale(options); }; diff --git a/src/control/Control.Zoom.js b/src/control/Control.Zoom.js index c972a8568..9ab3c8134 100644 --- a/src/control/Control.Zoom.js +++ b/src/control/Control.Zoom.js @@ -1,13 +1,29 @@ /* - * L.Control.Zoom is used for the default zoom buttons on the map. + * 🍂class Control.Zoom + * 🍂aka L.Control.Zoom + * 🍂inherits Control + * + * 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](#map-zoomcontrol) to `false`. Extends `Control`. */ L.Control.Zoom = L.Control.extend({ + // 🍂section + // 🍂aka Control.Zoom options options: { - position: 'topleft', + // 🍂option zoomInText: String = '+' + // The text set on the 'zoom in' button. zoomInText: '+', + + // 🍂option zoomInTitle: String = 'Zoom in' + // The title set on the 'zoom in' button. zoomInTitle: 'Zoom in', + + // 🍂option zoomOutText: String = '-' + // The text set on the 'zoom out' button. zoomOutText: '-', + + // 🍂option zoomOutTitle: String = 'Zoom out' + // The title set on the 'zoom out' button. zoomOutTitle: 'Zoom out' }, @@ -86,6 +102,10 @@ L.Control.Zoom = L.Control.extend({ } }); +// 🍂namespace Map +// 🍂section Control options +// 🍂option zoomControl: Boolean = true +// Whether a [zoom control](#control-zoom) is added to the map by default. L.Map.mergeOptions({ zoomControl: true }); @@ -97,6 +117,9 @@ L.Map.addInitHook(function () { } }); +// 🍂namespace Control.Zoom +// 🍂factory L.control.zoom(options: Control.Zoom options) +// Creates a zoom control L.control.zoom = function (options) { return new L.Control.Zoom(options); }; diff --git a/src/control/Control.js b/src/control/Control.js index a21b10238..428caa491 100644 --- a/src/control/Control.js +++ b/src/control/Control.js @@ -1,10 +1,18 @@ /* + * 🍂class Control + * 🍂aka L.Control + * * L.Control is a base class for implementing map controls. Handles positioning. * All other controls extend from this class. */ L.Control = L.Class.extend({ + // 🍂section + // 🍂aka Control options options: { + // 🍂option position: String = 'topleft' + // The position of the control (one of the map corners). Possible values are `'topleft'`, + // `'topright'`, `'bottomleft'` or `'bottomright'` position: 'topright' }, diff --git a/src/core/Browser.js b/src/core/Browser.js index 7fb54c7a9..4626471e9 100644 --- a/src/core/Browser.js +++ b/src/core/Browser.js @@ -1,5 +1,16 @@ /* - * L.Browser handles different browser and feature detections for internal Leaflet use. + * 🍂namespace Browser + * 🍂aka L.Browser + * + * A namespace with static properties for browser/feature detection used by Leaflet internally. + * + * 🍂example + * + * ```js + * if (L.Browser.ielt9) { + * alert('Upgrade your browser, dude!'); + * } + * ``` */ (function () { @@ -28,32 +39,101 @@ (window.DocumentTouch && document instanceof window.DocumentTouch)); L.Browser = { + + // 🍂property ie: Boolean + // `true` for all Internet Explorer versions (not Edge). ie: ie, + + // 🍂property ielt9: Boolean + // `true` for Internet Explorer versions less than 9. ielt9: ie && !document.addEventListener, + + // 🍂property edge: Boolean + // `true` for the Edge web browser. edge: 'msLaunchUri' in navigator && !('documentMode' in document), + + // 🍂property webkit: Boolean + // `true` for webkit-based browsers like Chrome and Safari (including mobile versions). webkit: webkit, + + // 🍂property gecko: Boolean + // `true` for gecko-based browsers like Firefox. gecko: gecko, + + // 🍂property android: Boolean + // `true` for any browser running on an Android platform. android: ua.indexOf('android') !== -1, + + // 🍂property android23: Boolean + // `true` for browsers running on Android 2 or Android 3. android23: android23, + + // 🍂property chrome: Boolean + // `true` for the Chrome browser. chrome: chrome, + + // 🍂property safari: Boolean + // `true` for the Safari browser. safari: !chrome && ua.indexOf('safari') !== -1, + + // 🍂property ie3d: Boolean + // `true` for all Internet Explorer versions supporting CSS transforms. ie3d: ie3d, + + // 🍂property webkit3d: Boolean + // `true` for webkit-based browsers supporting CSS transforms. webkit3d: webkit3d, + + // 🍂property gecko3d: Boolean + // `true` for gecko-based browsers supporting CSS transforms. gecko3d: gecko3d, + + // 🍂property opera12: Boolean + // `true` for the Opera browser supporting CSS transforms (version 12 or later). opera12: opera12, + + // 🍂property any3d: Boolean + // `true` for all browsers supporting CSS transforms. any3d: !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantomjs, + + // 🍂property ie: Boolean + // `true` for all browsers running in a mobile devide. mobile: mobile, + + // 🍂property mobileWebkit: Boolean + // `true` for all webkit-based browsers in a mobile device. mobileWebkit: mobile && webkit, + + // 🍂property mobileWebkit3d: Boolean + // `true` for all webkit-based browsers in a mobile device supporting CSS transforms. mobileWebkit3d: mobile && webkit3d, + + // 🍂property mobileOpera: Boolean + // `true` for the Opera browser in a mobile device. mobileOpera: mobile && window.opera, + + // 🍂property mobileGecko: Boolean + // `true` for gecko-based browsers running in a mobile device. mobileGecko: mobile && gecko, + + // 🍂property touch: Boolean + // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events). touch: !!touch, + + // 🍂property msPointer: Boolean + // `true` for browsers implementing the Microsoft touch events model (notably IE10). msPointer: !!msPointer, + + // 🍂property pointer: Boolean + // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx). pointer: !!pointer, + + // 🍂property retina: Boolean + // `true` for browsers on a high-resolution "retina" screen. retina: (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1 }; diff --git a/src/core/Class.js b/src/core/Class.js index c9507c015..994774a31 100644 --- a/src/core/Class.js +++ b/src/core/Class.js @@ -1,13 +1,19 @@ -/* - * L.Class powers the OOP facilities of the library. - * Thanks to John Resig and Dean Edwards for inspiration! - */ + +// 🍂class Class +// 🍂aka L.Class + +// 🍂section +// 🍂uninheritable + +// Thanks to John Resig and Dean Edwards for inspiration! L.Class = function () {}; L.Class.extend = function (props) { - // extended class with the new prototype + // 🍂function extend(props: Object): Function + // [Extends the current class](#class-inheritance) given the properties to be included. + // Returns a Javascript function that is a class constructor (to be called with `new`). var NewClass = function () { // call the constructor @@ -75,19 +81,22 @@ L.Class.extend = function (props) { }; -// method for adding properties to prototype +// 🍂function include(properties: Object) +// [Includes a mixin](#class-includes) into the current class. L.Class.include = function (props) { L.extend(this.prototype, props); return this; }; -// merge new default options to the Class +// 🍂function mergeOptions(options: Object) +// [Merges `options`](#class-options) into the defaults of the class. L.Class.mergeOptions = function (options) { L.extend(this.prototype.options, options); return this; }; -// add a constructor hook +// 🍂function addInitHook(fn: Function) +// Adds a [constructor hook](#class-constructor-hooks) to the class. L.Class.addInitHook = function (fn) { // (Function) || (String, args...) var args = Array.prototype.slice.call(arguments, 1); diff --git a/src/core/Class.leafdoc b/src/core/Class.leafdoc new file mode 100644 index 000000000..667f42a7c --- /dev/null +++ b/src/core/Class.leafdoc @@ -0,0 +1,191 @@ + +🍂class Class +🍂aka L.Class + +L.Class powers the OOP facilities of Leaflet and is used to create almost all of the Leaflet classes documented here. + +In addition to implementing a simple classical inheritance model, it introduces several special properties for convenient code organization — options, includes and statics. + + +🍂example + +```js +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"); +``` + +🍂section Class Factories +🍂example + +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: + +```js +new L.Map('map'); // becomes: +L.map('map'); +``` + +The factories are implemented very easily, and you can do this for your own classes: + +```js +L.map = function (id, options) { + return new L.Map(id, options); +}; +``` +🍂section Inheritance +🍂example + +You use L.Class.extend to define new classes, but you can use the same method on any class to inherit from it: + +```js +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: + +```js +var a = new MyChildClass(); +a instanceof MyChildClass; // true +a instanceof MyClass; // true +``` + +You can call parent methods (including constructor) from corresponding child ones (as you do with super calls in other languages) by accessing parent class prototype and using JavaScript's call or apply: + +``` +var MyChildClass = MyClass.extend({ + initialize: function () { + MyClass.prototype.initialize.call("Yo"); + }, + + greet: function (name) { + MyClass.prototype.greet.call(this, 'bro ' + name + '!'); + } +}); + +var a = new MyChildClass(); +a.greet('Jason'); // alerts "Yo, bro Jason!" +``` + +🍂section Options +🍂example + +`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: + +```js +var MyClass = L.Class.extend({ + options: { + myOption1: 'foo', + myOption2: 'bar' + } +}); + +var MyChildClass = L.Class.extend({ + options: { + myOption1: 'baz', + myOption3: 5 + } +}); + +var a = new MyChildClass(); +a.options.myOption1; // 'baz' +a.options.myOption2; // 'bar' +a.options.myOption3; // 5 +``` + +There's also [`L.Util.setOptions`](#util-setoptions), a method for +conveniently merging options passed to constructor with the defaults +defines in the class: + +```js +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} +``` + +🍂section Includes +🍂example + +`includes` is a special class property that merges all specified objects into the class (such objects are called mixins). + +```js + 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: + +```js +MyClass.include(MyMixin); +``` + +`statics` is just a convenience property that injects specified object properties as the static properties of the class, useful for defining constants: + +```js +var MyClass = L.Class.extend({ + statics: { + FOO: 'bar', + BLA: 5 + } +}); + +MyClass.FOO; // 'bar' +``` + + +🍂section Constructor hooks +🍂example + +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: + +```js +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: + +```js +MyClass.addInitHook('methodName', arg1, arg2, …); +``` diff --git a/src/core/Events.js b/src/core/Events.js index 6702d2ae4..c84726019 100644 --- a/src/core/Events.js +++ b/src/core/Events.js @@ -1,9 +1,38 @@ /* - * L.Evented is a base class that Leaflet classes inherit from to handle custom events. + * 🍂class Evented + * 🍂aka L.Evented + * 🍂inherits Class + * + * A set of methods shared between event-powered classes (like `Map` and `Marker`). 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 to fire `'click'` event). + * + * 🍂example + * + * ```js + * 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: + * + * ```js + * function onClick(e) { ... } + * + * map.on('click', onClick); + * map.off('click', onClick); + * ``` */ + L.Evented = L.Class.extend({ + /* 🍂method on(type: String, fn: Function, context?: Object): 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). You can also pass several space-separated types (e.g. `'click dblclick'`). + * + * 🍂alternative + * 🍂method on(eventMap: Object): this + * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` + */ on: function (types, fn, context) { // types can be a map of types/handlers @@ -26,6 +55,17 @@ L.Evented = L.Class.extend({ return this; }, + /* 🍂method off(type: String, fn?: Function, context?: Object): this + * Removes 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 `on`, you must pass the same context to `off` in order to remove the listener. + * + * 🍂alternative + * 🍂method off(eventMap: Object): this + * Removes a set of type/listener pairs. + * + * 🍂alternative + * 🍂method off: this + * Removes all listeners to all events on the object. + */ off: function (types, fn, context) { if (!types) { @@ -127,6 +167,10 @@ L.Evented = L.Class.extend({ } }, + // 🍂method fire(type: String, data?: Object, propagate?: Boolean): 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. The event might can optionally be propagated to event parents. fire: function (type, data, propagate) { if (!this.listens(type, propagate)) { return this; } @@ -160,6 +204,8 @@ L.Evented = L.Class.extend({ return this; }, + // 🍂method listens(type: String): Boolean + // Returns `true` if a particular event type has any listeners attached to it. listens: function (type, propagate) { var events = this._events; @@ -174,6 +220,8 @@ L.Evented = L.Class.extend({ return false; }, + // 🍂method once(…): this + // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. once: function (types, fn, context) { if (typeof types === 'object') { @@ -195,13 +243,16 @@ L.Evented = L.Class.extend({ .on(types, handler, context); }, - // adds a parent to propagate events to (when you fire with true as a 3rd argument) + // 🍂method addEventParent(obj: Evented): this + // Adds an event parent - an `Evented` that will receive propagated events addEventParent: function (obj) { this._eventParents = this._eventParents || {}; this._eventParents[L.stamp(obj)] = obj; return this; }, + // 🍂method removeEventParent(obj: Evented): this + // Removes an event parent, so it will stop receiving propagated events removeEventParent: function (obj) { if (this._eventParents) { delete this._eventParents[L.stamp(obj)]; @@ -219,10 +270,28 @@ L.Evented = L.Class.extend({ var proto = L.Evented.prototype; // aliases; we should ditch those eventually + +// 🍂method addEventListener(…): this +// Alias to [`on(…)`](#evented-on) proto.addEventListener = proto.on; + +// 🍂method removeEventListener(…): this +// Alias to [`off(…)`](#evented-off) + +// 🍂method clearAllEventListeners(…): this +// Alias to [`off()`](#evented-off) proto.removeEventListener = proto.clearAllEventListeners = proto.off; + +// 🍂method addOneTimeEventListener(…): this +// Alias to [`once(…)`](#evented-once) proto.addOneTimeEventListener = proto.once; + +// 🍂method fireEvent(…): this +// Alias to [`fire(…)`](#evented-fire) proto.fireEvent = proto.fire; + +// 🍂method hasEventListeners(…): this +// Alias to [`listens(…)`](#evented-listens) proto.hasEventListeners = proto.listens; L.Mixin = {Events: proto}; diff --git a/src/core/Events.leafdoc b/src/core/Events.leafdoc new file mode 100644 index 000000000..7a32af290 --- /dev/null +++ b/src/core/Events.leafdoc @@ -0,0 +1,116 @@ + +🍂namespace Event objects + + +Whenever a class inheriting from `Evented` fires an event, a listener function +will be called with an event argument, which is a plain object containing +information about the event. For example: + +```js +map.on('click', function(ev) { + alert(ev.latlng); // ev is an event object (MouseEvent in this case) +}); +``` + +The information available depends on the event type: + + +🍂miniclass Event (Event objects) +🍂section +The base event object. All other event objects contain these properties too. +🍂property type: String +The event type (e.g. `'click'`). +🍂property target: Object +The object that fired the event. + + +🍂miniclass MouseEvent (Event objects) +🍂inherits Event +🍂property latlng: LatLng +The geographical point where the mouse event occured. +🍂property layerPoint: Point +Pixel coordinates of the point where the mouse event occured relative to the map layer. +🍂property containerPoint: Point +Pixel coordinates of the point where the mouse event occured relative to the map сontainer. +🍂property originalEvent: DOMMouseEvent +The original DOM mouse event fired by the browser. + + + +🍂miniclass LocationEvent (Event objects) +🍂inherits Event +🍂property latlng: LatLng +Detected geographical location of the user. +🍂property bounds: LatLngBounds +Geographical bounds of the area user is located in (with respect to the accuracy of location). +🍂property accuracy: Number +Accuracy of location in meters. +🍂property altitude: Number +Height of the position above the WGS84 ellipsoid in meters. +🍂property altitudeAccuracy: Number +Accuracy of altitude in meters. +🍂property heading: Number +The direction of travel in degrees counting clockwise from true North. +🍂property speed: Number +Current velocity in meters per second. +🍂property timestamp: Number +The time when the position was acquired. + +🍂miniclass ErrorEvent (Event objects) +🍂inherits Event +🍂property message: String +Error message. +🍂property code: Number +Error code (if applicable). + +🍂miniclass LayerEvent (Event objects) +🍂inherits Event +🍂property layer: ILayer +The layer that was added or removed. + +🍂miniclass LayersControlEvent (Event objects) +🍂inherits Event +🍂property layer: ILayer +The layer that was added or removed. +🍂property name: String +The name of the layer that was added or removed. + +🍂miniclass TileEvent (Event objects) +🍂inherits Event +🍂property tile: HTMLElement +The tile element (image). + +🍂miniclass TileErrorEvent (Event objects) +🍂inherits Event +🍂property tile: HTMLElement +The tile element (image). + +🍂miniclass ResizeEvent (Event objects) +🍂inherits Event +🍂property oldSize: Point +The old size before resize event. +🍂property newSize: Point +The new size after the resize event. + +🍂miniclass GeoJSON event (Event objects) +🍂inherits Event +🍂property layer: ILayer +The layer for the GeoJSON feature that is being added to the map. +🍂property properties: Object +GeoJSON properties of the feature. +🍂property geometryType: String +GeoJSON geometry type of the feature. +🍂property id: String +GeoJSON ID of the feature (if present). + +🍂miniclass Popup event (Event objects) +🍂inherits Event +🍂property popup: Popup +The popup that was opened or closed. + +🍂miniclass DragEndEvent (Event objects) +🍂inherits Event +🍂property distance: Number +The distance in pixels the draggable element was moved by. + + diff --git a/src/core/Handler.js b/src/core/Handler.js index 9b1211232..771e6502d 100644 --- a/src/core/Handler.js +++ b/src/core/Handler.js @@ -3,11 +3,17 @@ interaction features like dragging to classes like Map and Marker. */ +// 🍂class Handler +// 🍂aka L.Handler +// Abstract class for map interaction handlers + L.Handler = L.Class.extend({ initialize: function (map) { this._map = map; }, + // 🍂method enable() + // Enables the handler enable: function () { if (this._enabled) { return; } @@ -15,6 +21,8 @@ L.Handler = L.Class.extend({ this.addHooks(); }, + // 🍂method disable() + // Disables the handler disable: function () { if (!this._enabled) { return; } @@ -22,7 +30,16 @@ L.Handler = L.Class.extend({ this.removeHooks(); }, + // 🍂method enabled(): Boolean + // Returns `true` if the handler is enabled enabled: function () { return !!this._enabled; } + + // 🍂section Extension methods + // Classes inheriting from `Handler` must implement the two following methods: + // 🍂method addHooks() + // Called when the handler is enabled, should add event hooks. + // 🍂method removeHooks() + // Called when the handler is disabled, should remove the event hooks added previously. }); diff --git a/src/core/Util.js b/src/core/Util.js index f72058b0f..de4108eed 100644 --- a/src/core/Util.js +++ b/src/core/Util.js @@ -1,9 +1,13 @@ /* - * L.Util contains various utility functions used throughout Leaflet code. + * 🍂namespace Util + * + * Various utility functions, used by Leaflet internally. */ L.Util = { - // extend an object with properties of one or more other objects + + // 🍂function extend(dest: Object, src?: Object): Object + // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut. extend: function (dest) { var i, j, len, src; @@ -16,7 +20,8 @@ L.Util = { return dest; }, - // create an object from a given prototype + // 🍂function create(proto: Object, properties?: Object): Object + // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create) create: Object.create || (function () { function F() {} return function (proto) { @@ -25,7 +30,9 @@ L.Util = { }; })(), - // bind a function to be called with a given context + // 🍂function bind(fn: Function, …): Function + // Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). + // Has a `L.bind()` shortcut. bind: function (fn, obj) { var slice = Array.prototype.slice; @@ -40,7 +47,8 @@ L.Util = { }; }, - // return unique ID of an object + // 🍂function stamp(obj: Object): Number + // Returns the unique ID of an object, assiging it one if it doesn't have it. stamp: function (obj) { /*eslint-disable */ obj._leaflet_id = obj._leaflet_id || ++L.Util.lastId; @@ -48,9 +56,13 @@ L.Util = { /*eslint-enable */ }, + // 🍂property lastId: Number + // Last unique ID used by [`stamp()`](#util-stamp) lastId: 0, - // return a function that won't be called more often than the given interval + // 🍂function throttle(fn: Function, time: Number, context: Object): Function + // Returns a function which executes function `fn` with the given scope `context` + // (so that the `this` keyword refers to `context` inside `fn`'s code). The arguments received by the bound function will be any arguments passed when binding the function, followed by any arguments passed when invoking the bound function. Has an `L.bind` shortcut. throttle: function (fn, time, context) { var lock, args, wrapperFn, later; @@ -79,7 +91,10 @@ L.Util = { return wrapperFn; }, - // wrap the given number to lie within a certain range (used for wrapping longitude) + // 🍂function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number + // Returns the number `num` modulo `range` in such a way so it lies within + // `range[0]` and `range[1]`. The returned value will be always smaller than + // `range[1]` unless `includeMax` is set to `true`. wrapNum: function (x, range, includeMax) { var max = range[1], min = range[0], @@ -87,26 +102,31 @@ L.Util = { return x === max && includeMax ? x : ((x - min) % d + d) % d + min; }, - // do nothing (used as a noop throughout the code) + // 🍂function falseFn(): Function + // Returns a function which always returns `false`. falseFn: function () { return false; }, - // round a given number to a given precision + // 🍂function formatNum(num: Number, digits?: Number): Number + // Returns the number `num` rounded to `digits` decimals, or to 5 decimals by default. formatNum: function (num, digits) { var pow = Math.pow(10, digits || 5); return Math.round(num * pow) / pow; }, - // trim whitespace from both sides of a string + // 🍂function trim(str: String): String + // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim) trim: function (str) { return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); }, - // split a string into words + // 🍂function splitWords(str: String): String[] + // Trims and splits the string on whitespace and returns the array of parts. splitWords: function (str) { return L.Util.trim(str).split(/\s+/); }, - // set options to an object, inheriting parent's options as well + // 🍂function setOptions(obj: Object: options: Object): Object + // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut. setOptions: function (obj, options) { if (!obj.hasOwnProperty('options')) { obj.options = obj.options ? L.Util.create(obj.options) : {}; @@ -117,7 +137,11 @@ L.Util = { return obj.options; }, - // make a URL with GET parameters out of a set of properties/values + // 🍂function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String + // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}` + // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will + // be appended at the end. If `uppercase` is `true`, the parameter names will + // be uppercased (e.g. `'?A=foo&B=bar'`) getParamString: function (obj, existingUrl, uppercase) { var params = []; for (var i in obj) { @@ -126,7 +150,11 @@ L.Util = { return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&'); }, - // super-simple templating facility, used for TileLayer URLs + // 🍂template (str: String, data: Object) + // Simple 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. template: function (str, data) { return str.replace(L.Util.templateRe, function (str, key) { var value = data[key]; @@ -143,10 +171,14 @@ L.Util = { templateRe: /\{ *([\w_\-]+) *\}/g, + // 🍂function isArray(obj): Boolean + // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) isArray: Array.isArray || function (obj) { return (Object.prototype.toString.call(obj) === '[object Array]'); }, + // 🍂function indexOf + // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) indexOf: function (array, el) { for (var i = 0; i < array.length; i++) { if (array[i] === el) { return i; } @@ -154,7 +186,10 @@ L.Util = { return -1; }, - // minimal image URI, set to an image when disposing to flush memory + // 🍂property emptyImageUrl: String + // Data 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). emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=' }; @@ -181,6 +216,12 @@ L.Util = { getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); }; + // 🍂function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): requestId: Number + // Schedules `fn` to be executed when the browser repaints. `fn` is bound to + // `context` if given. When `immediate` is set, `fn` is called immediately if + // the browser doesn't have native support for + // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame), + // otherwise it's delayed. Returns an id that can be used to cancel the request. L.Util.requestAnimFrame = function (fn, context, immediate) { if (immediate && requestFn === timeoutDefer) { fn.call(context); @@ -189,6 +230,8 @@ L.Util = { } }; + // 🍂function cancelAnimFrame(id: Number) + // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame). L.Util.cancelAnimFrame = function (id) { if (id) { cancelFn.call(window, id); diff --git a/src/dom/DomEvent.js b/src/dom/DomEvent.js index 3a12e3969..0c24c72f0 100644 --- a/src/dom/DomEvent.js +++ b/src/dom/DomEvent.js @@ -1,12 +1,25 @@ /* - * L.DomEvent contains functions for working with DOM events. - * Inspired by John Resig, Dean Edwards and YUI addEvent implementations. + * 🍂namespace DomEvent + * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally. */ +// Inspired by John Resig, Dean Edwards and YUI addEvent implementations. + + + var eventsKey = '_leaflet_events'; L.DomEvent = { + // 🍂function on(el: HTMLElement, types: String, fn: Function, context?: Object): this + // Adds a listener function (`fn`) to a particular DOM event type of the + // element `el`. 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'`). + + // 🍂alternative + // 🍂function on(el: HTMLElement, eventMap: Object, context?: Object): this + // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` on: function (obj, types, fn, context) { if (typeof types === 'object') { @@ -24,6 +37,14 @@ L.DomEvent = { return this; }, + // 🍂function off(el: HTMLElement, types: String, fn: Function, context?: Object) + // Removes a previously added listener function. If no function is specified, + // it will remove all the listeners of that particular DOM event from the element. + // Note that if you passed a custom context to on, you must pass the same + // context to `off` in order to remove the listener. + + // 🍂alternative + // 🍂function off(el: HTMLElement, types: eventMap: Object, context?: Object): this off: function (obj, types, fn, context) { if (typeof types === 'object') { @@ -124,6 +145,13 @@ L.DomEvent = { return this; }, + // 🍂function stopPropagation(ev: DOMEvent): this + // Stop the given event from propagation to parent elements. Used inside the listener functions: + // ```js + // L.DomEvent.on(div, 'click', function (ev) { + // L.DomEvent.stopPropagation(ev); + // }); + // ``` stopPropagation: function (e) { if (e.stopPropagation) { @@ -138,10 +166,15 @@ L.DomEvent = { return this; }, + // 🍂function disableScrollPropagation(el: HTMLElement): this + // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants). disableScrollPropagation: function (el) { return L.DomEvent.on(el, 'mousewheel', L.DomEvent.stopPropagation); }, + // 🍂function disableClickPropagation(el: HTMLElement): this + // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`, + // `'mousedown'` and `'touchstart'` events (plus browser variants). disableClickPropagation: function (el) { var stop = L.DomEvent.stopPropagation; @@ -153,6 +186,11 @@ L.DomEvent = { }); }, + // 🍂function preventDefault(ev: DOMEvent): this + // Prevents the default action of the DOM Event `ev` from happening (such as + // following a link in the href of the a element, or doing a POST request + // with page reload when a `
` is submitted). + // Use it inside listener functions. preventDefault: function (e) { if (e.preventDefault) { @@ -163,12 +201,17 @@ L.DomEvent = { return this; }, + // 🍂function stop(ev): this + // Does `stopPropagation` and `preventDefault` at the same time. stop: function (e) { return L.DomEvent .preventDefault(e) .stopPropagation(e); }, + // 🍂function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point + // Gets normalized mouse position from a DOM event relative to the + // `container` or to the whole page if not specified. getMousePosition: function (e, container) { if (!container) { return new L.Point(e.clientX, e.clientY); @@ -181,6 +224,11 @@ L.DomEvent = { e.clientY - rect.top - container.clientTop); }, + // 🍂function getWheelDelta(ev: DOMEvent): Number + // Gets normalized wheel delta from a mousewheel DOM event, in vertical + // pixels scrolled (negative if scrolling down). + // Events from pointing devices without precise scrolling are mapped to + // a best guess of between 50-60 pixels. getWheelDelta: function (e) { return (e.deltaY && e.deltaMode === 0) ? -e.deltaY : // Pixels (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 18 : // Lines @@ -243,5 +291,10 @@ L.DomEvent = { } }; +// 🍂function addListener(…): this +// Alias to [`L.DomEvent.on`](#domevent-on) L.DomEvent.addListener = L.DomEvent.on; + +// 🍂function removeListener(…): this +// Alias to [`L.DomEvent.off`](#domevent-off) L.DomEvent.removeListener = L.DomEvent.off; diff --git a/src/dom/DomUtil.js b/src/dom/DomUtil.js index 8ed7c71ce..ad5ca5703 100644 --- a/src/dom/DomUtil.js +++ b/src/dom/DomUtil.js @@ -1,12 +1,26 @@ /* - * L.DomUtil contains various utility functions for working with DOM. + * 🍂namespace DomUtil + * + * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model) + * tree, used by Leaflet internally. + * + * Most functions expecting or returning a `HTMLElement` also work for + * SVG elements. The only difference is that classes refer to CSS classes + * in HTML and SVG classes in SVG. */ L.DomUtil = { + + // 🍂function get(id: String|HTMLElement): HTMLElement + // Returns an element given its DOM id, or returns the element itself + // if it was passed directly. get: function (id) { return typeof id === 'string' ? document.getElementById(id) : id; }, + // 🍂function getStyle(el: HTMLElement, styleAttrib: String): String + // Returns the value for a certain style attribute on an element, + // including computed values or values set through CSS. getStyle: function (el, style) { var value = el.style[style] || (el.currentStyle && el.currentStyle[style]); @@ -19,6 +33,8 @@ L.DomUtil = { return value === 'auto' ? null : value; }, + // 🍂function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement + // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element. create: function (tagName, className, container) { var el = document.createElement(tagName); @@ -31,6 +47,8 @@ L.DomUtil = { return el; }, + // 🍂function remove(el: HTMLElement) + // Removes `el` from its parent element remove: function (el) { var parent = el.parentNode; if (parent) { @@ -38,21 +56,29 @@ L.DomUtil = { } }, + // 🍂function empty(el: HTMLElement) + // Removes all of `el`'s children elements from `el` empty: function (el) { while (el.firstChild) { el.removeChild(el.firstChild); } }, + // 🍂function toFront(el: HTMLElement) + // Makes `el` the last children of its parent, so it renders in front of the other children. toFront: function (el) { el.parentNode.appendChild(el); }, + // 🍂function toBack(el: HTMLElement) + // Makes `el` the first children of its parent, so it renders back from the other children. toBack: function (el) { var parent = el.parentNode; parent.insertBefore(el, parent.firstChild); }, + // 🍂function hasClass(el: HTMLElement, name: String): Boolean + // Returns `true` if the element's class attribute contains `name`. hasClass: function (el, name) { if (el.classList !== undefined) { return el.classList.contains(name); @@ -61,6 +87,8 @@ L.DomUtil = { return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className); }, + // 🍂function addClass(el: HTMLElement, name: String) + // Adds `name` to the element's class attribute. addClass: function (el, name) { if (el.classList !== undefined) { var classes = L.Util.splitWords(name); @@ -73,6 +101,8 @@ L.DomUtil = { } }, + // 🍂function removeClass(el: HTMLElement, name: String) + // Removes `name` from the element's class attribute. removeClass: function (el, name) { if (el.classList !== undefined) { el.classList.remove(name); @@ -81,6 +111,8 @@ L.DomUtil = { } }, + // 🍂function setClass(el: HTMLElement, name: String) + // Sets the element's class. setClass: function (el, name) { if (el.className.baseVal === undefined) { el.className = name; @@ -90,10 +122,15 @@ L.DomUtil = { } }, + // 🍂function setClass(el: HTMLElement, name: String) + // Sets the element's class. getClass: function (el) { return el.className.baseVal === undefined ? el.className : el.className.baseVal; }, + // 🍂function setOpacity(el: HTMLElement, opacity: Number) + // Set the opacity of an element (including old IE support). + // `opacity` must be a number from `0` to `1`. setOpacity: function (el, value) { if ('opacity' in el.style) { @@ -127,6 +164,10 @@ L.DomUtil = { } }, + // 🍂function testProp(props: String[]): String|false + // Goes 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`. testProp: function (props) { var style = document.documentElement.style; @@ -139,6 +180,10 @@ L.DomUtil = { return false; }, + // 🍂function setTransform(el: HTMLElement, offset: Point, scale?: Number) + // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels + // and optionally scaled by `scale`. Does not have an effect if the + // browser doesn't support 3D CSS transforms. setTransform: function (el, offset, scale) { var pos = offset || new L.Point(0, 0); @@ -149,6 +194,10 @@ L.DomUtil = { (scale ? ' scale(' + scale + ')' : ''); }, + // 🍂function setPosition(el: HTMLElement, position: Point) + // Sets the position of `el` to coordinates specified by `position`, + // using CSS translate or top/left positioning depending on the browser + // (used by Leaflet internally to position its layers). setPosition: function (el, point) { // (HTMLElement, Point[, Boolean]) /*eslint-disable */ @@ -163,6 +212,8 @@ L.DomUtil = { } }, + // 🍂function getPosition(el: HTMLElement): Point + // Returns the coordinates of an element previously positioned with setPosition. getPosition: function (el) { // this method is only used for elements previously positioned using setPosition, // so it's safe to cache the position for performance @@ -175,6 +226,8 @@ L.DomUtil = { (function () { // prefix style property names + // 🍂property TRANSFORM: String + // Vendor-prefixed fransform style name (e.g. `'webkitTransform'` for WebKit). L.DomUtil.TRANSFORM = L.DomUtil.testProp( ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']); @@ -182,13 +235,22 @@ L.DomUtil = { // webkitTransition comes first because some browser versions that drop vendor prefix don't do // the same for the transitionend event, in particular the Android 4.1 stock browser + // 🍂property TRANSITION: String + // Vendor-prefixed transform style name. var transition = L.DomUtil.TRANSITION = L.DomUtil.testProp( ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']); L.DomUtil.TRANSITION_END = transition === 'webkitTransition' || transition === 'OTransition' ? transition + 'End' : 'transitionend'; + // 🍂function disableTextSelection() + // Prevents the user from generating `selectstart` DOM events, usually generated + // when the user drags the mouse through a page with text. Used internally + // by Leaflet to override the behaviour of any click-and-drag interaction on + // the map. Affects drag interactions on the whole document. + // 🍂function enableTextSelection() + // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection). if ('onselectstart' in document) { L.DomUtil.disableTextSelection = function () { L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault); @@ -216,13 +278,24 @@ L.DomUtil = { }; } + // 🍂function disableImageDrag() + // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but + // for `dragstart` DOM events, usually generated when the user drags an image. L.DomUtil.disableImageDrag = function () { L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault); }; + + // 🍂function enableImageDrag() + // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection). L.DomUtil.enableImageDrag = function () { L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault); }; + // 🍂function preventOutline(el: HTMLElement) + // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline) + // of the element `el` invisible. Used internally by Leaflet to prevent + // focusable elements from displaying an outline when the user performs a + // drag interaction on them. L.DomUtil.preventOutline = function (element) { while (element.tabIndex === -1) { element = element.parentNode; @@ -234,6 +307,9 @@ L.DomUtil = { element.style.outline = 'none'; L.DomEvent.on(window, 'keydown', L.DomUtil.restoreOutline, this); }; + + // 🍂function restoreOutline() + // Cancels the effects of a previous [`L.DomUtil.preventOutline`](). L.DomUtil.restoreOutline = function () { if (!this._outlineElement) { return; } this._outlineElement.style.outline = this._outlineStyle; diff --git a/src/dom/Draggable.js b/src/dom/Draggable.js index 0056e8d02..163caeeb1 100644 --- a/src/dom/Draggable.js +++ b/src/dom/Draggable.js @@ -1,5 +1,17 @@ /* - * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too. + * 🍂class Draggable + * 🍂aka L.Draggable + * 🍂inherits Evented + * + * 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 [`L.DomUtil.setPosition`](#domutil-setposition). + * + * 🍂example + * ```js + * var draggable = new L.Draggable(elementToDrag); + * draggable.enable(); + * ``` */ L.Draggable = L.Evented.extend({ @@ -20,12 +32,16 @@ L.Draggable = L.Evented.extend({ } }, + // 🍂constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline: Boolean) + // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default). initialize: function (element, dragStartTarget, preventOutline) { this._element = element; this._dragStartTarget = dragStartTarget || element; this._preventOutline = preventOutline; }, + // 🍂method enable() + // Enables the dragging ability enable: function () { if (this._enabled) { return; } @@ -34,6 +50,8 @@ L.Draggable = L.Evented.extend({ this._enabled = true; }, + // 🍂method disable() + // Disables the dragging ability disable: function () { if (!this._enabled) { return; } @@ -60,6 +78,8 @@ L.Draggable = L.Evented.extend({ if (this._moving) { return; } + // 🍂event down: Event + // Fired when a drag is about to start. this.fire('down'); var first = e.touches ? e.touches[0] : e; @@ -88,6 +108,8 @@ L.Draggable = L.Evented.extend({ L.DomEvent.preventDefault(e); if (!this._moved) { + // 🍂event dragstart: Event + // Fired when a drag starts this.fire('dragstart'); this._moved = true; @@ -109,8 +131,15 @@ L.Draggable = L.Evented.extend({ _updatePosition: function () { var e = {originalEvent: this._lastEvent}; + + // 🍂event predrag: Event + // Fired continuously during dragging *before* each corresponding + // update of the element's position. this.fire('predrag', e); L.DomUtil.setPosition(this._element, this._newPos); + + // 🍂event predrag: Event + // Fired continuously during dragging. this.fire('drag', e); }, @@ -135,6 +164,8 @@ L.Draggable = L.Evented.extend({ // ensure drag is not fired after dragend L.Util.cancelAnimFrame(this._animRequest); + // 🍂event dragend: Event + // Fired when the drag ends. this.fire('dragend', { distance: this._newPos.distanceTo(this._startPos) }); diff --git a/src/dom/PosAnimation.js b/src/dom/PosAnimation.js index 70294d3ed..cf19656bf 100644 --- a/src/dom/PosAnimation.js +++ b/src/dom/PosAnimation.js @@ -1,10 +1,28 @@ /* - * L.PosAnimation powers Leaflet pan animations internally. + * 🍂class PosAnimation + * 🍂aka L.PosAnimation + * 🍂inherits Evented + * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9. + * + * 🍂example + * ```js + * var fx = new L.PosAnimation(); + f x.run(el, [300, 500], 0.5);* + * ``` + * + * 🍂constructor L.PosAnimation() + * Creates a `PosAnimation` object. + * */ L.PosAnimation = L.Evented.extend({ - run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number]) + // 🍂method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number) + // Run 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](http://cubic-bezier.com/#0,0,.5,1), + // `0.5` by default). + run: function (el, newPos, duration, easeLinearity) { this.stop(); this._el = el; @@ -16,11 +34,15 @@ L.PosAnimation = L.Evented.extend({ this._offset = newPos.subtract(this._startPos); this._startTime = +new Date(); + // 🍂event start: Event + // Fired when the animation starts this.fire('start'); this._animate(); }, + // 🍂method stop() + // Stops the animation (if currently running). stop: function () { if (!this._inProgress) { return; } @@ -53,6 +75,8 @@ L.PosAnimation = L.Evented.extend({ } L.DomUtil.setPosition(this._el, pos); + // 🍂event step: Event + // Fired continuously during the animation. this.fire('step'); }, @@ -60,6 +84,8 @@ L.PosAnimation = L.Evented.extend({ L.Util.cancelAnimFrame(this._animId); this._inProgress = false; + // 🍂event end: Event + // Fired when the animation ends. this.fire('end'); }, diff --git a/src/geo/LatLng.js b/src/geo/LatLng.js index 8bfdf2563..eae22762f 100644 --- a/src/geo/LatLng.js +++ b/src/geo/LatLng.js @@ -1,5 +1,22 @@ -/* - * L.LatLng represents a geographical point with latitude and longitude coordinates. +/* 🍂class LatLng + * 🍂aka L.LatLng + * + * Represents a geographical point with a certain latitude and longitude. + * + * 🍂example + * + * ``` + * 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)); + * ``` */ L.LatLng = function (lat, lng, alt) { @@ -7,15 +24,24 @@ L.LatLng = function (lat, lng, alt) { throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')'); } + // 🍂property lat: Number + // Latitude in degrees this.lat = +lat; + + // 🍂property lng: Number + // Longitude in degrees this.lng = +lng; + // 🍂property alt: Number + // Altitude in meters (optional) if (alt !== undefined) { this.alt = +alt; } }; L.LatLng.prototype = { + // 🍂method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean + // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overriden by setting `maxMargin` to a small number. equals: function (obj, maxMargin) { if (!obj) { return false; } @@ -28,20 +54,28 @@ L.LatLng.prototype = { return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin); }, + // 🍂method toString(): String + // Returns a string representation of the point (for debugging purposes). toString: function (precision) { return 'LatLng(' + L.Util.formatNum(this.lat, precision) + ', ' + L.Util.formatNum(this.lng, precision) + ')'; }, + // 🍂method distanceTo(otherLatLng: LatLng): Number + // Returns the distance (in meters) to the given `LatLng` calculated using the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula). distanceTo: function (other) { return L.CRS.Earth.distance(this, L.latLng(other)); }, + // 🍂method wrap(): LatLng + // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees. wrap: function () { return L.CRS.Earth.wrapLatLng(this); }, + // 🍂method toBounds(sizeInMeters: Number): LatLngBounds + // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters` meters apart from the `LatLng`. toBounds: function (sizeInMeters) { var latAccuracy = 180 * sizeInMeters / 40075017, lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat); @@ -57,8 +91,17 @@ L.LatLng.prototype = { }; -// constructs LatLng with different signatures -// (LatLng) or ([Number, Number]) or (Number, Number) or (Object) + +// 🍂factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng +// Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude). + +// 🍂alternative +// 🍂factory L.latLng(coords: Array): LatLng +// Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead. + +// 🍂alternative +// 🍂factory L.latLng(coords: Object): LatLng +// Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead. L.latLng = function (a, b, c) { if (a instanceof L.LatLng) { diff --git a/src/geo/LatLngBounds.js b/src/geo/LatLngBounds.js index a54be5fb8..207640110 100644 --- a/src/geo/LatLngBounds.js +++ b/src/geo/LatLngBounds.js @@ -1,5 +1,25 @@ /* - * L.LatLngBounds represents a rectangular area on the map in geographical coordinates. + * 🍂class LatLngBounds + * 🍂aka L.LatLngBounds + * + * Represents a rectangular geographical area on a map. + * + * 🍂example + * + * ```js + * 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: + * + * ```js + * map.fitBounds([ + * [40.712, -74.227], + * [40.774, -74.125] + * ]); + * ``` */ L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[]) @@ -14,8 +34,13 @@ L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLn L.LatLngBounds.prototype = { - // extend the bounds to contain the given point or bounds - extend: function (obj) { // (LatLng) or (LatLngBounds) + // 🍂method extend(latlng: LatLng) + // Extend the bounds to contain the given point + + // 🍂alternative + // 🍂method extend(otherBounds: LatLngBounds) + // Extend the bounds to contain the given bounds + extend: function (obj) { var sw = this._southWest, ne = this._northEast, sw2, ne2; @@ -47,8 +72,9 @@ L.LatLngBounds.prototype = { return this; }, - // extend the bounds by a percentage - pad: function (bufferRatio) { // (Number) -> LatLngBounds + // 🍂method pad(bufferRatio: Number): LatLngBounds + // Returns bigger bounds created by extending the current bounds by a given percentage in each direction. + pad: function (bufferRatio) { var sw = this._southWest, ne = this._northEast, heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio, @@ -59,44 +85,68 @@ L.LatLngBounds.prototype = { new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer)); }, - getCenter: function () { // -> LatLng + // 🍂method getCenter(): LatLng + // Returns the center point of the bounds. + getCenter: function () { return new L.LatLng( (this._southWest.lat + this._northEast.lat) / 2, (this._southWest.lng + this._northEast.lng) / 2); }, + // 🍂method getSouthWest(): LatLng + // Returns the south-west point of the bounds. getSouthWest: function () { return this._southWest; }, + // 🍂method getNorthEast(): LatLng + // Returns the north-east point of the bounds. getNorthEast: function () { return this._northEast; }, + // 🍂method getNorthWest(): LatLng + // Returns the north-west point of the bounds. getNorthWest: function () { return new L.LatLng(this.getNorth(), this.getWest()); }, + // 🍂method getSouthEast(): LatLng + // Returns the south-east point of the bounds. getSouthEast: function () { return new L.LatLng(this.getSouth(), this.getEast()); }, + // 🍂method getWest(): Number + // Returns the west longitude of the bounds getWest: function () { return this._southWest.lng; }, + // 🍂method getSouth(): Number + // Returns the south latitude of the bounds getSouth: function () { return this._southWest.lat; }, + // 🍂method getEast(): Number + // Returns the east longitude of the bounds getEast: function () { return this._northEast.lng; }, + // 🍂method getNorth(): Number + // Returns the north latitude of the bounds getNorth: function () { return this._northEast.lat; }, + // 🍂method contains(otherBounds: LatLngBounds): Boolean + // Returns `true` if the rectangle contains the given one. + + // 🍂alternative + // 🍂method contains (latlng: LatLng): Boolean + // Returns `true` if the rectangle contains the given point. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean if (typeof obj[0] === 'number' || obj instanceof L.LatLng) { obj = L.latLng(obj); @@ -119,7 +169,9 @@ L.LatLngBounds.prototype = { (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng); }, - intersects: function (bounds) { // (LatLngBounds) -> Boolean + // 🍂method intersects(otherBounds: LatLngBounds): Boolean + // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common. + intersects: function (bounds) { bounds = L.latLngBounds(bounds); var sw = this._southWest, @@ -133,7 +185,9 @@ L.LatLngBounds.prototype = { return latIntersects && lngIntersects; }, - overlaps: function (bounds) { // (LatLngBounds) -> Boolean + // 🍂method overlaps(otherBounds: Bounds): Boolean + // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area. + overlaps: function (bounds) { bounds = L.latLngBounds(bounds); var sw = this._southWest, @@ -147,11 +201,15 @@ L.LatLngBounds.prototype = { return latOverlaps && lngOverlaps; }, + // 🍂method toBBoxString(): String + // Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data. toBBoxString: function () { return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(','); }, - equals: function (bounds) { // (LatLngBounds) + // 🍂method equals(otherBounds: LatLngBounds): Boolean + // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. + equals: function (bounds) { if (!bounds) { return false; } bounds = L.latLngBounds(bounds); @@ -160,6 +218,8 @@ L.LatLngBounds.prototype = { this._northEast.equals(bounds.getNorthEast()); }, + // 🍂method isValid(): Boolean + // Returns `true` if the bounds are properly initialized. isValid: function () { return !!(this._southWest && this._northEast); } @@ -167,7 +227,13 @@ L.LatLngBounds.prototype = { // TODO International date line? -L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng) +// 🍂factory L.latLngBounds(southWest: LatLng, northEast: LatLng) +// Creates a `LatLngBounds` object by defining south-west and north-east corners of the rectangle. + +// 🍂alternative +// 🍂factory L.latLngBounds(latlngs: LatLng[]) +// 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`](#map-fitbounds). +L.latLngBounds = function (a, b) { if (a instanceof L.LatLngBounds) { return a; } diff --git a/src/geo/crs/CRS.EPSG3395.js b/src/geo/crs/CRS.EPSG3395.js index 6c17909ba..c79f75a31 100644 --- a/src/geo/crs/CRS.EPSG3395.js +++ b/src/geo/crs/CRS.EPSG3395.js @@ -1,5 +1,8 @@ /* - * L.CRS.EPSG3857 (World Mercator) CRS implementation. + * 🍂namespace CRS + * 🍂crs L.CRS.EPSG3395 + * + * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection. */ L.CRS.EPSG3395 = L.extend({}, L.CRS.Earth, { diff --git a/src/geo/crs/CRS.EPSG3857.js b/src/geo/crs/CRS.EPSG3857.js index 1601b7d7c..147336ef4 100644 --- a/src/geo/crs/CRS.EPSG3857.js +++ b/src/geo/crs/CRS.EPSG3857.js @@ -1,5 +1,10 @@ /* - * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping and is used by Leaflet by default. + * 🍂namespace CRS + * 🍂crs L.CRS.EPSG3857 + * + * The 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.EPSG3857 = L.extend({}, L.CRS.Earth, { diff --git a/src/geo/crs/CRS.EPSG4326.js b/src/geo/crs/CRS.EPSG4326.js index 0420679f1..50ed6f3c5 100644 --- a/src/geo/crs/CRS.EPSG4326.js +++ b/src/geo/crs/CRS.EPSG4326.js @@ -1,5 +1,8 @@ /* - * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists. + * 🍂namespace CRS + * 🍂crs L.CRS.EPSG4326 + * + * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. */ L.CRS.EPSG4326 = L.extend({}, L.CRS.Earth, { diff --git a/src/geo/crs/CRS.Earth.js b/src/geo/crs/CRS.Earth.js index d6947501f..b3aae258f 100644 --- a/src/geo/crs/CRS.Earth.js +++ b/src/geo/crs/CRS.Earth.js @@ -1,5 +1,10 @@ /* - * L.CRS.Earth is the base class for all CRS representing Earth. + * 🍂namespace CRS + * 🍂crs L.CRS.Earth + * + * Serves as the base for CRS that are global such that they cover the earth. + * Can only be used as the base for other CRS and cannot be used directly, + * since it does not have a `code`, `projection` or `transformation`. */ L.CRS.Earth = L.extend({}, L.CRS, { diff --git a/src/geo/crs/CRS.Simple.js b/src/geo/crs/CRS.Simple.js index ea89e5a83..4d2524b28 100644 --- a/src/geo/crs/CRS.Simple.js +++ b/src/geo/crs/CRS.Simple.js @@ -1,5 +1,10 @@ /* - * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps. + * 🍂namespace CRS + * 🍂crs L.CRS.Simple + * + * A 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). */ L.CRS.Simple = L.extend({}, L.CRS, { diff --git a/src/geo/crs/CRS.js b/src/geo/crs/CRS.js index a82e8f056..45597e956 100644 --- a/src/geo/crs/CRS.js +++ b/src/geo/crs/CRS.js @@ -1,9 +1,19 @@ /* - * L.CRS is the base object for all defined CRS (Coordinate Reference Systems) in Leaflet. + * 🍂class CRS + * 🍂aka L.CRS + * Abstract class that 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](http://en.wikipedia.org/wiki/Coordinate_reference_system). + * + * Leaflet defines the most usual CRSs by default. If you want to use a + * CRS not defined by default, take a look at the + * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin. */ L.CRS = { - // converts geo coords to pixel ones + // 🍂method latLngToPoint(latlng: LatLng, zoom: Number): Point + // Projects geographical coordinates into pixel coordinates for a given zoom. latLngToPoint: function (latlng, zoom) { var projectedPoint = this.projection.project(latlng), scale = this.scale(zoom); @@ -11,7 +21,9 @@ L.CRS = { return this.transformation._transform(projectedPoint, scale); }, - // converts pixel coords to geo coords + // 🍂method pointToLatLng(point: Point, zoom: Number): LatLng + // The inverse of `latLngToPoint`. Projects pixel coordinates on a given + // zoom into geographical coordinates. pointToLatLng: function (point, zoom) { var scale = this.scale(zoom), untransformedPoint = this.transformation.untransform(point, scale); @@ -19,26 +31,37 @@ L.CRS = { return this.projection.unproject(untransformedPoint); }, - // converts geo coords to projection-specific coords (e.g. in meters) + // 🍂method project(latlng: LatLng): Point + // Projects geographical coordinates into coordinates in units accepted for + // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). project: function (latlng) { return this.projection.project(latlng); }, - // converts projected coords to geo coords + // 🍂method unproject(point: Point): LatLng + // Given a projected coordinate returns the corresponding LatLng. + // The inverse of `project`. unproject: function (point) { return this.projection.unproject(point); }, - // defines how the world scales with zoom + // 🍂method scale(zoom: Number): Number + // Returns 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. scale: function (zoom) { return 256 * Math.pow(2, zoom); }, + // 🍂method zoom(scale: Number): Number + // Inverse of `scale()`, returns the zoom level correspondingto a scale + // factor of `scale`. zoom: function (scale) { return Math.log(scale / 256) / Math.LN2; }, - // returns the bounds of the world in projected coords if applicable + // 🍂method getProjectedBounds(zoom): Bounds + // Returns the projection's bounds scaled and transformed for the provided `zoom`. getProjectedBounds: function (zoom) { if (this.infinite) { return null; } @@ -50,14 +73,27 @@ L.CRS = { return L.bounds(min, max); }, - // whether a coordinate axis wraps in a given range (e.g. longitude from -180 to 180); depends on CRS + // 🍂property code: String + // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`) + // + // 🍂property wrapLng: Number[] + // An array of two numbers defining whether the longitude coordinate axis + // wraps around a given range and how. Defaults to `[-180, 180]` in most + // geographical CRSs. + // + // 🍂property wrapLat: Number[] + // Like `wrapLng`, but for the latitude axis. + // wrapLng: [min, max], // wrapLat: [min, max], - // if true, the coordinate space will be unbounded (infinite in all directions) - // infinite: false, + // 🍂property infinite: Boolean = false + // If true, the coordinate space will be unbounded (infinite in both axes) + infinite: false, - // wraps geo coords in certain ranges if applicable + // 🍂method wrapLatLng(latlng: LatLng): LatLng + // Returns a `LatLng` where lat and lng has been wrapped according to the + // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds. wrapLatLng: function (latlng) { var lng = this.wrapLng ? L.Util.wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng, lat = this.wrapLat ? L.Util.wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat, diff --git a/src/geo/projection/Projection.LonLat.js b/src/geo/projection/Projection.LonLat.js index 06b1415b7..4dc7e8911 100644 --- a/src/geo/projection/Projection.LonLat.js +++ b/src/geo/projection/Projection.LonLat.js @@ -1,5 +1,14 @@ /* - * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple. + * 🍂namespace Projection + * 🍂section + * Leaflet comes with a set of already defined Projections out of the box: + * + * 🍂projection L.Projection.LonLat + * + * Equirectangular, 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. */ L.Projection = {}; diff --git a/src/geo/projection/Projection.Mercator.js b/src/geo/projection/Projection.Mercator.js index b23e81697..1012b0a7e 100644 --- a/src/geo/projection/Projection.Mercator.js +++ b/src/geo/projection/Projection.Mercator.js @@ -1,6 +1,8 @@ /* - * Mercator projection that takes into account that the Earth is not a perfect sphere. - * Less popular than spherical mercator; used by projections like EPSG:3395. + * 🍂namespace Projection + * 🍂projection L.Projection.Mercator + * + * Elliptical 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.Mercator = { diff --git a/src/geo/projection/Projection.SphericalMercator.js b/src/geo/projection/Projection.SphericalMercator.js index 278e15290..64118f113 100644 --- a/src/geo/projection/Projection.SphericalMercator.js +++ b/src/geo/projection/Projection.SphericalMercator.js @@ -1,5 +1,10 @@ /* - * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default. + * 🍂namespace Projection + * 🍂projection L.Projection.SphericalMercator + * + * Spherical 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.SphericalMercator = { diff --git a/src/geo/projection/Projection.leafdoc b/src/geo/projection/Projection.leafdoc new file mode 100644 index 000000000..f759b468f --- /dev/null +++ b/src/geo/projection/Projection.leafdoc @@ -0,0 +1,16 @@ + +🍂class Projection + +An object with methods for projecting geographical coordinates of the world onto +a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection). + +🍂property bounds: LatLngBounds +The bounds where the projection is valid + +🍂method project(latlng: LatLng): Point +Projects geographical coordinates into a 2D point. + +🍂method unproject(point: Point): LatLng +The inverse of `project`. Projects a 2D point into a geographical location. + + diff --git a/src/geometry/Bounds.js b/src/geometry/Bounds.js index 884c7bf8e..bdd33d2c5 100644 --- a/src/geometry/Bounds.js +++ b/src/geometry/Bounds.js @@ -1,8 +1,25 @@ /* - * L.Bounds represents a rectangular area on the screen in pixel coordinates. + * 🍂class Bounds + * 🍂aka L.Bounds + * + * Represents a rectangular area in pixel coordinates. + * + * 🍂example + * + * ```js + * 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: + * + * ```js + * otherBounds.intersects([[10, 10], [40, 60]]); + * ``` */ -L.Bounds = function (a, b) { // (Point, Point) or Point[] +L.Bounds = function (a, b) { if (!a) { return; } var points = b ? [a, b] : a; @@ -13,10 +30,15 @@ L.Bounds = function (a, b) { // (Point, Point) or Point[] }; L.Bounds.prototype = { - // extend the bounds to contain the given point + // 🍂method extend(point: Point): this + // Extends the bounds to contain the given point. extend: function (point) { // (Point) point = L.point(point); + // 🍂property min: Point + // The top left corner of the rectangle. + // 🍂property max: Point + // The bottom right corner of the rectangle. if (!this.min && !this.max) { this.min = point.clone(); this.max = point.clone(); @@ -29,25 +51,38 @@ L.Bounds.prototype = { return this; }, - getCenter: function (round) { // (Boolean) -> Point + // 🍂method getCenter(): Point + // Returns the center point of the bounds. + getCenter: function (round) { return new L.Point( (this.min.x + this.max.x) / 2, (this.min.y + this.max.y) / 2, round); }, - getBottomLeft: function () { // -> Point + // 🍂method getBottomLeft(): Point + // Returns the bottom-left point of the bounds. + getBottomLeft: function () { return new L.Point(this.min.x, this.max.y); }, + // 🍂method getTopRight(): Point + // Returns the top-right point of the bounds. getTopRight: function () { // -> Point return new L.Point(this.max.x, this.min.y); }, + // 🍂method getSize(): Point + // Returns the size of the given bounds getSize: function () { return this.max.subtract(this.min); }, - contains: function (obj) { // (Bounds) or (Point) -> Boolean + // 🍂method contains(otherBounds: Bounds): Boolean + // Returns `true` if the rectangle contains the given one. + // 🍂alternative + // 🍂method contains(point: Point): Boolean + // Returns `true` if the rectangle contains the given poing. + contains: function (obj) { var min, max; if (typeof obj[0] === 'number' || obj instanceof L.Point) { @@ -69,6 +104,9 @@ L.Bounds.prototype = { (max.y <= this.max.y); }, + // 🍂method intersects(otherBounds: Bounds): Boolean + // Returns `true` if the rectangle intersects the given bounds. Two bounds + // intersect if they have at least one point in common. intersects: function (bounds) { // (Bounds) -> Boolean bounds = L.bounds(bounds); @@ -82,6 +120,9 @@ L.Bounds.prototype = { return xIntersects && yIntersects; }, + // 🍂method overlaps(otherBounds: Bounds): Boolean + // Returns `true` if the rectangle overlaps the given bounds. Two bounds + // overlap if their intersection is an area. overlaps: function (bounds) { // (Bounds) -> Boolean bounds = L.bounds(bounds); @@ -100,7 +141,13 @@ L.Bounds.prototype = { } }; -L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[]) + +// 🍂factory L.bounds(topLeft: Point, bottomRight: Point) +// Creates a Bounds object from two coordinates (usually top-left and bottom-right corners). +// 🍂alternative +// 🍂factory L.bounds(points: Point[]) +// Creates a Bounds object from the points it contains +L.bounds = function (a, b) { if (!a || a instanceof L.Bounds) { return a; } diff --git a/src/geometry/LineUtil.js b/src/geometry/LineUtil.js index 8c0897c86..89021ab55 100644 --- a/src/geometry/LineUtil.js +++ b/src/geometry/LineUtil.js @@ -1,6 +1,7 @@ /* - * L.LineUtil contains different utility functions for line segments - * and polylines (clipping, simplification, distances, etc.) + * 🍂namespace LineUtil + * + * Various utility functions for polyine points processing, used by Leaflet internally to make polylines lightning-fast. */ L.LineUtil = { @@ -8,6 +9,14 @@ L.LineUtil = { // Simplify polyline with vertex reduction and Douglas-Peucker simplification. // Improves rendering performance dramatically by lessening the number of points to draw. + // 🍂function simplify(points: Point[], tolerance: Number): Point[] + // Dramatically reduces the number of points in a polyline while retaining + // its shape and returns a new array of simplified points, using the + // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm). + // 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](http://mourner.github.com/simplify-js/). simplify: function (points, tolerance) { if (!tolerance || !points.length) { return points.slice(); @@ -24,11 +33,14 @@ L.LineUtil = { return points; }, - // distance from a point to a segment between two points + // 🍂function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number + // Returns the distance between point `p` and segment `p1` to `p2`. pointToSegmentDistance: function (p, p1, p2) { return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true)); }, + // 🍂function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number + // Returns the closest point from a point `p` on a segment `p1` to `p2`. closestPointOnSegment: function (p, p1, p2) { return this._sqClosestPointOnSegment(p, p1, p2); }, @@ -94,9 +106,11 @@ L.LineUtil = { return reducedPoints; }, - // Cohen-Sutherland line clipping algorithm. - // Used to avoid rendering parts of a polyline that are not currently visible. + // Clips the segment a to b by rectangular bounds with the + // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm) + // (modifying the segment points directly!). Used by Leaflet to only show polyline + // points that are on the screen or near, increasing performance. clipSegment: function (a, b, bounds, useLastCode, round) { var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds), codeB = this._getBitCode(b, bounds), diff --git a/src/geometry/Point.js b/src/geometry/Point.js index 43ec06c4e..b2c32b083 100644 --- a/src/geometry/Point.js +++ b/src/geometry/Point.js @@ -1,5 +1,21 @@ /* - * L.Point represents a point with x and y coordinates. + * 🍂class Point + * 🍂aka L.Point + * + * Represents a point with `x` and `y` coordinates in pixels. + * + * 🍂example + * + * ```js + * 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: + * + * ```js + * map.panBy([200, 300]); + * map.panBy(L.point(200, 300)); + * ``` */ L.Point = function (x, y, round) { @@ -9,22 +25,28 @@ L.Point = function (x, y, round) { L.Point.prototype = { + // 🍂method clone(): Point + // Returns a copy of the current point. clone: function () { return new L.Point(this.x, this.y); }, - // non-destructive, returns a new point + // 🍂method add(otherPoint: Point): Point + // Returns the result of addition of the current and the given points. add: function (point) { + // non-destructive, returns a new point return this.clone()._add(L.point(point)); }, - // destructive, used directly for performance in situations where it's safe to modify existing point _add: function (point) { + // destructive, used directly for performance in situations where it's safe to modify existing point this.x += point.x; this.y += point.y; return this; }, + // 🍂method subtract(otherPoint: Point): Point + // Returns the result of subtraction of the given point from the current. subtract: function (point) { return this.clone()._subtract(L.point(point)); }, @@ -35,6 +57,8 @@ L.Point.prototype = { return this; }, + // 🍂method divideBy(num: Number): Point + // Returns the result of division of the current point by the given number. divideBy: function (num) { return this.clone()._divideBy(num); }, @@ -45,6 +69,8 @@ L.Point.prototype = { return this; }, + // 🍂method multiplyBy(num: Number): Point + // Returns the result of multiplication of the current point by the given number. multiplyBy: function (num) { return this.clone()._multiplyBy(num); }, @@ -55,14 +81,24 @@ L.Point.prototype = { return this; }, + // 🍂method scaleBy(scale: Point): Point + // Multiply each coordinate of the current point by each coordinate of + // `scale`. In linear algebra terms, multiply the point by the + // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation) + // defined by `scale`. scaleBy: function (point) { return new L.Point(this.x * point.x, this.y * point.y); }, + // 🍂method unscaleBy(scale: Point) + // Inverse of `scaleBy`. Divide each coordinate of the current point by + // each coordinate of `scale`. unscaleBy: function (point) { return new L.Point(this.x / point.x, this.y / point.y); }, + // 🍂method round(): Point + // Returns a copy of the current point with rounded coordinates. round: function () { return this.clone()._round(); }, @@ -73,6 +109,8 @@ L.Point.prototype = { return this; }, + // 🍂method floor(): Point + // Returns a copy of the current point with floored coordinates (rounded down). floor: function () { return this.clone()._floor(); }, @@ -83,6 +121,8 @@ L.Point.prototype = { return this; }, + // 🍂method ceil(): Point + // Returns a copy of the current point with ceiled coordinates (rounded up). ceil: function () { return this.clone()._ceil(); }, @@ -93,6 +133,8 @@ L.Point.prototype = { return this; }, + // 🍂method distanceTo(otherPoint: Point): Number + // Returns the cartesian distance between the current and the given points. distanceTo: function (point) { point = L.point(point); @@ -102,6 +144,8 @@ L.Point.prototype = { return Math.sqrt(x * x + y * y); }, + // 🍂method equals(otherPoint: Point): Boolean + // Returns `true` if the given point has the same coordinates. equals: function (point) { point = L.point(point); @@ -109,6 +153,8 @@ L.Point.prototype = { point.y === this.y; }, + // 🍂method contains(otherPoint: Point): Boolean + // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values). contains: function (point) { point = L.point(point); @@ -116,6 +162,8 @@ L.Point.prototype = { Math.abs(point.y) <= Math.abs(this.y); }, + // 🍂method toString(): String + // Returns a string representation of the point for debugging purposes. toString: function () { return 'Point(' + L.Util.formatNum(this.x) + ', ' + @@ -123,6 +171,12 @@ L.Point.prototype = { } }; +// 🍂factory L.point(x: Number, y: Number, round?: Boolean) +// Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values. + +// 🍂alternative +// 🍂factory L.point(coords: Number[]) +// Expects an array of the form `[x, y]` instead. L.point = function (x, y, round) { if (x instanceof L.Point) { return x; diff --git a/src/geometry/PolyUtil.js b/src/geometry/PolyUtil.js index 97723f3a0..1b1192fba 100644 --- a/src/geometry/PolyUtil.js +++ b/src/geometry/PolyUtil.js @@ -1,12 +1,15 @@ /* - * L.PolyUtil contains utility functions for polygons (clipping, etc.). + * 🍂namespace PolyUtil + * Various utility functions for polygon geometries. */ L.PolyUtil = {}; -/* - * Sutherland-Hodgeman polygon clipping algorithm. - * Used to avoid rendering parts of a polygon that are not currently visible. +/* 🍂function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[] + * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgeman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)). + * 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 seperate method for it. */ L.PolyUtil.clipPolygon = function (points, bounds, round) { var clippedPoints, diff --git a/src/geometry/Transformation.js b/src/geometry/Transformation.js index df5c6ef57..116b158c4 100644 --- a/src/geometry/Transformation.js +++ b/src/geometry/Transformation.js @@ -1,7 +1,24 @@ /* - * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix. + * 🍂class Transformation + * 🍂aka L.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. + * + * 🍂example + * + * ```js + * 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) + * ``` */ + +// factory new L.Transformation(a: Number, b: Number, c: Number, d: Number) +// Creates a `Transformation` object with the given coefficients. L.Transformation = function (a, b, c, d) { this._a = a; this._b = b; @@ -10,6 +27,9 @@ L.Transformation = function (a, b, c, d) { }; L.Transformation.prototype = { + // 🍂method transform(point: Point, scale?: Number) + // Returns a transformed point, optionally multiplied by the given scale. + // Only accepts real `L.Point` instances, not arrays. transform: function (point, scale) { // (Point, Number) -> Point return this._transform(point.clone(), scale); }, @@ -22,6 +42,9 @@ L.Transformation.prototype = { return point; }, + // 🍂method untransform(point: Point, scale?: Number) + // Returns the reverse transformation of the given point, optionally divided + // by the given scale. Only accepts real `L.Point` instances, not arrays. untransform: function (point, scale) { scale = scale || 1; return new L.Point( diff --git a/src/layer/FeatureGroup.js b/src/layer/FeatureGroup.js index 8d27824cb..6b7b3219b 100644 --- a/src/layer/FeatureGroup.js +++ b/src/layer/FeatureGroup.js @@ -1,6 +1,18 @@ /* - * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods - * shared between a group of interactive layers (like vectors or markers). + * 🍂class FeatureGroup + * 🍂aka L.FeatureGroup + * 🍂inherits LayerGroup + * + * Extended `LayerGroup` that also has mouse events (propagated from members of the group) and a shared bindPopup method. + * + * 🍂example + * + * ```js + * L.featureGroup([marker1, marker2, polyline]) + * .bindPopup('Hello world!') + * .on('click', function() { alert('Clicked on a group!'); }) + * .addTo(map); + * ``` */ L.FeatureGroup = L.LayerGroup.extend({ @@ -32,18 +44,26 @@ L.FeatureGroup = L.LayerGroup.extend({ return this.fire('layerremove', {layer: layer}); }, + // 🍂method setStyle(style: Path options): this + // Sets the given path options to each layer of the group that has a `setStyle` method. setStyle: function (style) { return this.invoke('setStyle', style); }, + // 🍂method bringToFront(): this + // Brings the layer group to the top of all other layers bringToFront: function () { return this.invoke('bringToFront'); }, + // 🍂method bringToBack(): this + // Brings the layer group to the top of all other layers bringToBack: function () { return this.invoke('bringToBack'); }, + // 🍂method getBounds(): LatLngBounds + // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children). getBounds: function () { var bounds = new L.LatLngBounds(); @@ -55,6 +75,8 @@ L.FeatureGroup = L.LayerGroup.extend({ } }); +// 🍂factory L.featureGroup(layers: Layer[]) +// Create a feature group, optionally given an initial set of layers. L.featureGroup = function (layers) { return new L.FeatureGroup(layers); }; diff --git a/src/layer/GeoJSON.js b/src/layer/GeoJSON.js index 32c47429e..48f59d168 100644 --- a/src/layer/GeoJSON.js +++ b/src/layer/GeoJSON.js @@ -1,9 +1,71 @@ /* - * L.GeoJSON turns any GeoJSON data into a Leaflet layer. + * 🍂class GeoJSON + * 🍂aka L.GeoJSON + * 🍂inherits FeatureGroup + * + * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse + * GeoJSON data and display it on the map. Extends `FeatureGroup`. + * + * 🍂example + * + * ```js + * L.geoJson(data, { + * style: function (feature) { + * return {color: feature.properties.color}; + * } + * }).bindPopup(function (layer) { + * return layer.feature.properties.description; + * }).addTo(map); + * ``` */ L.GeoJSON = L.FeatureGroup.extend({ + /* 🍂section + * 🍂aka GeoJSON options + * + * 🍂option pointToLayer: Function = * + * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally + * called when data is added, passing the GeoJSON point feature and its `LatLng`. + * The default is to spawn a default `Marker`: + * ```js + * function(geoJsonPoint, latlng) { + * return L.marker(latlng); + * } + * ``` + * + * 🍂option style: Function = * + * A `Function` defining the `Path options` for styling GeoJSON lines and polygons, + * called internally when data is added. + * The default value is to not override any defaults: + * ```js + * function (geoJsonFeature) { + * return {} + * } + * ``` + * + * 🍂option onEachFeature: Function = * + * A `Function` that will be called once for each created `Layer`, after it has + * been created and styled. Useful for attaching events and popups to features. + * The default is to do nothing with the newly created layers: + * ```js + * function (layer) {} + * ``` + * + * 🍂option filter: Function = * + * A `Function` that will be used to decide whether to show a feature or not. + * The default is to show all features: + * ```js + * function (geoJsonFeature) { + * return true; + * } + * ``` + * + * 🍂option coordsToLatLng: Function = * + * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s. + * The default is the `coordsToLatLng` static method. + */ + initialize: function (geojson, options) { L.setOptions(this, options); @@ -72,7 +134,13 @@ L.GeoJSON = L.FeatureGroup.extend({ } }); +// 🍂section +// There are several static functions which can be called without instantiating L.GeoJSON: L.extend(L.GeoJSON, { + // 🍂function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer + // Creates a `Layer` from a given GeoJSON feature. Can use a custom + // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng) + // functions if provided as options. geometryToLayer: function (geojson, options) { var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson, @@ -127,10 +195,17 @@ L.extend(L.GeoJSON, { } }, + // 🍂function coordsToLatLng(coords: Array): LatLng + // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude) + // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points. coordsToLatLng: function (coords) { return new L.LatLng(coords[1], coords[0], coords[2]); }, + // 🍂function coordsToLatLngs(coords: Array, levelsDeep: Number, coordsToLatLng?: Function): Array + // Creates a multidimensional array of `LatLng`s 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). + // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function. coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { var latlngs = []; @@ -145,12 +220,16 @@ L.extend(L.GeoJSON, { return latlngs; }, + // 🍂function latLngToCoords(latlng: LatLng): Array + // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng) latLngToCoords: function (latlng) { return latlng.alt !== undefined ? [latlng.lng, latlng.lat, latlng.alt] : [latlng.lng, latlng.lat]; }, + // 🍂function latLngsToCoords(latlngs: Array): Array + // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs) latLngsToCoords: function (latlngs, levelsDeep, closed) { var coords = []; @@ -173,6 +252,8 @@ L.extend(L.GeoJSON, { L.GeoJSON.asFeature(newGeometry); }, + // 🍂function asFeature(geojson: Object): Object + // Normalize GeoJSON geometries/features into GeoJSON features. asFeature: function (geojson) { if (geojson.type === 'Feature') { return geojson; @@ -196,9 +277,17 @@ var PointToGeoJSON = { }; L.Marker.include(PointToGeoJSON); + +// 🍂namespace CircleMarker +// 🍂method toGeoJSON(): Object +// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature). L.Circle.include(PointToGeoJSON); L.CircleMarker.include(PointToGeoJSON); + +// 🍂namespace Polyline +// 🍂method toGeoJSON(): Object +// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature). L.Polyline.prototype.toGeoJSON = function () { var multi = !L.Polyline._flat(this._latlngs); @@ -210,6 +299,9 @@ L.Polyline.prototype.toGeoJSON = function () { }); }; +// 🍂namespace Polygon +// 🍂method toGeoJSON(): Object +// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature). L.Polygon.prototype.toGeoJSON = function () { var holes = !L.Polyline._flat(this._latlngs), multi = holes && !L.Polyline._flat(this._latlngs[0]); @@ -227,6 +319,7 @@ L.Polygon.prototype.toGeoJSON = function () { }; +// 🍂namespace LayerGroup L.LayerGroup.include({ toMultiPoint: function () { var coords = []; @@ -241,6 +334,8 @@ L.LayerGroup.include({ }); }, + // 🍂method toGeoJSON(): Object + // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `GeometryCollection`). toGeoJSON: function () { var type = this.feature && this.feature.geometry && this.feature.geometry.type; @@ -273,6 +368,11 @@ L.LayerGroup.include({ } }); +// 🍂namespace GeoJSON +// 🍂factory L.geoJSON(geojson?: Object, options?: GeoJSON options) +// Creates a GeoJSON layer. Optionally accepts an object in +// [GeoJSON format](http://geojson.org/geojson-spec.html) to display on the map +// (you can alternatively add it later with `addData` method) and an `options` object. L.geoJSON = function (geojson, options) { return new L.GeoJSON(geojson, options); }; diff --git a/src/layer/ImageOverlay.js b/src/layer/ImageOverlay.js index 09984df9e..c23ea28a3 100644 --- a/src/layer/ImageOverlay.js +++ b/src/layer/ImageOverlay.js @@ -1,13 +1,37 @@ /* - * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds). + * 🍂class ImageOverlay + * 🍂aka L.ImageOverlay + * 🍂inherits Layer + * + * Used to load and display a single image over specific bounds of the map. Extends `Layer`. + * + * 🍂example + * + * ```js + * 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); + * ``` */ L.ImageOverlay = L.Layer.extend({ options: { + // 🍂option opacity: Number = 1.0 + // The opacity of the image overlay. opacity: 1, + + // 🍂option alt: String = '' + // Text for the `alt` attribute of the image (useful for accessibility). alt: '', - interactive: false + + // 🍂option interactive: Boolean = true + // If `true`, the image overlay will emit mouse events when clicked or hovered. + interactive: false, + + // 🍂option attribution: String = null + // An optional string containing HTML to be shown on the `Attribution control` + attribution: null /* crossOrigin: , @@ -46,6 +70,8 @@ L.ImageOverlay = L.Layer.extend({ } }, + // 🍂method setOpacity(): this + // Sets the opacity of the overlay. setOpacity: function (opacity) { this.options.opacity = opacity; @@ -62,6 +88,8 @@ L.ImageOverlay = L.Layer.extend({ return this; }, + // 🍂method bringToFront(): this + // Brings the layer to the top of all overlays. bringToFront: function () { if (this._map) { L.DomUtil.toFront(this._image); @@ -69,6 +97,8 @@ L.ImageOverlay = L.Layer.extend({ return this; }, + // 🍂method bringToBack(): this + // Brings the layer to the bottom of all overlays. bringToBack: function () { if (this._map) { L.DomUtil.toBack(this._image); @@ -76,6 +106,8 @@ L.ImageOverlay = L.Layer.extend({ return this; }, + // 🍂method setUrl(url: String): this + // Changes the URL of the image. setUrl: function (url) { this._url = url; @@ -161,6 +193,9 @@ L.ImageOverlay = L.Layer.extend({ } }); +// 🍂factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options) +// Instantiates an image overlay object given the URL of the image and the +// geographical bounds it is tied to. L.imageOverlay = function (url, bounds, options) { return new L.ImageOverlay(url, bounds, options); }; diff --git a/src/layer/Layer.Popup.js b/src/layer/Layer.Popup.js index 885684118..aa2856081 100644 --- a/src/layer/Layer.Popup.js +++ b/src/layer/Layer.Popup.js @@ -1,9 +1,25 @@ /* - * Adds popup-related methods to all layers. + * 🍂namespace Layer + * 🍂section Popup methods example + * + * All layers share a set of methods convenient for binding popups to it. + * + * ```js + * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map); + * layer.openPopup(); + * layer.closePopup(); + * ``` + * + * Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened. */ +// 🍂section Popup methods L.Layer.include({ + // 🍂method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this + // Binds a popup to the layer with the passed `content` and sets up the + // neccessary event listeners. If a `Function` is passed it will receive + // the layer as the first argument and should return a `String` or `HTMLElement`. bindPopup: function (content, options) { if (content instanceof L.Popup) { @@ -32,6 +48,8 @@ L.Layer.include({ return this; }, + // 🍂method unbindPopup(): this + // Removes the popup previously bound with `bindPopup`. unbindPopup: function () { if (this._popup) { this.off({ @@ -45,6 +63,8 @@ L.Layer.include({ return this; }, + // 🍂method openPopup(latlng?: LatLng): this + // Opens the bound popup at the specificed `latlng` or at the default popup anchor if no `latlng` is passed. openPopup: function (layer, latlng) { if (!(layer instanceof L.Layer)) { latlng = layer; @@ -79,6 +99,8 @@ L.Layer.include({ return this; }, + // 🍂method closePopup(): this + // Closes the popup bound to this layer if it is open. closePopup: function () { if (this._popup) { this._popup._close(); @@ -86,6 +108,8 @@ L.Layer.include({ return this; }, + // 🍂method closePopup(): this + // Opens or closes the popup bound to this layer depending on its current state. togglePopup: function (target) { if (this._popup) { if (this._popup._map) { @@ -97,10 +121,14 @@ L.Layer.include({ return this; }, + // 🍂method closePopup(): this + // Returns `true` if the popup bound to this layer is currently open. isPopupOpen: function () { return this._popup.isOpen(); }, + // 🍂method setPopupContent(content: String|HTMLElement|Popup, options?: Popup options): this + // Sets the content of the popup bound to this layer. setPopupContent: function (content) { if (this._popup) { this._popup.setContent(content); @@ -108,6 +136,8 @@ L.Layer.include({ return this; }, + // 🍂method getPopup(): Popup + // Returns the popup bound to this layer. getPopup: function () { return this._popup; }, diff --git a/src/layer/Layer.js b/src/layer/Layer.js index a1c2a5270..5fe6cd06a 100644 --- a/src/layer/Layer.js +++ b/src/layer/Layer.js @@ -1,20 +1,58 @@ +/* + * 🍂class Layer + * 🍂inherits Evented + * 🍂aka L.Layer + * 🍂aka ILayer + * + * A set of methods from the Layer base class that all Leaflet layers use. + * Inherits all methods, options and events from `L.Evented`. + * + * 🍂example + * + * ```js + * var layer = L.Marker(latlng).addTo(map); + * layer.addTo(map); + * layer.remove(); + * ``` + * + * 🍂event add: Event + * Fired after the layer is added to a map + * + * 🍂event remove: Event + * Fired after the layer is removed from a map + */ + + L.Layer = L.Evented.extend({ + // Classes extending `L.Layer` will inherit the following options: options: { + // 🍂option pane: String = 'overlayPane' + // By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. pane: 'overlayPane', nonBubblingEvents: [] // Array of events that should not be bubbled to DOM parents (like the map) }, + /* 🍂section + * Classes extending `L.Layer` will inherit the following methods: + * + * 🍂method addTo(map: Map): this + * Adds the layer to the given map + */ addTo: function (map) { map.addLayer(this); return this; }, + // 🍂method remove: this + // Removes the layer from the map it is currently active on. remove: function () { return this.removeFrom(this._map || this._mapToAdd); }, + // 🍂method removeFrom(map: Map): this + // Removes the layer from the given map removeFrom: function (obj) { if (obj) { obj.removeLayer(this); @@ -22,6 +60,8 @@ L.Layer = L.Evented.extend({ return this; }, + // 🍂method getPane(name? : String): HTMLElement + // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. getPane: function (name) { return this._map.getPane(name ? (this.options[name] || name) : this.options.pane); }, @@ -60,8 +100,42 @@ L.Layer = L.Evented.extend({ } }); +/* 🍂section Extension methods + * 🍂uninheritable + * + * Every layer should extend from `L.Layer` and (re-)implement the following methods. + * + * 🍂method onAdd(map: Map): this + * Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer). + * + * 🍂method onRemove(map: Map): this + * Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer). + * + * 🍂method getEvents(): Object + * This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#event-addeventlistener). These events will be automatically added and removed from the map with your layer. + * + * 🍂method getAttribution(): String + * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible. + * + * 🍂method beforeAdd(map: Map): this + * Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only. + */ + +/* 🍂namespace Map + * 🍂section Layer events + * + * 🍂event layeradd: LayerEvent + * Fired when a new layer is added to the map. + * + * 🍂event layerremove: LayerEvent + * Fired when some layer is removed from the map + * + * 🍂section Methods for Layers and Controls + */ L.Map.include({ + // 🍂method addLayer(layer: Layer): this + // Adds the given layer to the map addLayer: function (layer) { var id = L.stamp(layer); if (this._layers[id]) { return layer; } @@ -78,6 +152,8 @@ L.Map.include({ return this; }, + // 🍂method removeLayer(layer: Layer): this + // Removes the given layer from the map. removeLayer: function (layer) { var id = L.stamp(layer); @@ -107,10 +183,20 @@ L.Map.include({ return this; }, + // 🍂method hasLayer(layer: Layer): Boolean + // Returns `true` if the given layer is currently added to the map hasLayer: function (layer) { return !!layer && (L.stamp(layer) in this._layers); }, + /* 🍂method eachLayer(fn: Function, context?: Object): this + * Iterates over the layers of the map, optionally specifying context of the iterator function. + * ``` + * map.eachLayer(function(layer){ + * layer.bindPopup('Hello'); + * }); + * ``` + */ eachLayer: function (method, context) { for (var i in this._layers) { method.call(context, this._layers[i]); @@ -157,6 +243,10 @@ L.Map.include({ this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom; this._layersMinZoom = minZoom === Infinity ? undefined : minZoom; + // 🍂section Map state change events + // 🍂event zoomlevelschange: Event + // Fired when the number of zoomlevels on the map is changed due + // to adding or removing a layer. if (oldZoomSpan !== this._getZoomSpan()) { this.fire('zoomlevelschange'); } diff --git a/src/layer/LayerGroup.js b/src/layer/LayerGroup.js index 1565a377c..fa7c11860 100644 --- a/src/layer/LayerGroup.js +++ b/src/layer/LayerGroup.js @@ -1,6 +1,19 @@ /* - * L.LayerGroup is a class to combine several layers into one so that - * you can manipulate the group (e.g. add/remove it) as one layer. + * 🍂class LayerGroup + * 🍂aka L.LayerGroup + * 🍂inherits Layer + * + * 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. Extends `Layer`. + * + * 🍂example + * + * ```js + * L.layerGroup([marker1, marker2]) + * .addLayer(polyline) + * .addTo(map); + * ``` */ L.LayerGroup = L.Layer.extend({ @@ -17,6 +30,8 @@ L.LayerGroup = L.Layer.extend({ } }, + // 🍂method addLayer(layer: Layer): this + // Adds the given layer to the group. addLayer: function (layer) { var id = this.getLayerId(layer); @@ -29,6 +44,11 @@ L.LayerGroup = L.Layer.extend({ return this; }, + // 🍂method removeLayer(layer: Layer): this + // Removes the given layer from the group. + // 🍂alternative + // 🍂method removeLayer(id: Number): this + // Removes the layer with the given internal ID from the group. removeLayer: function (layer) { var id = layer in this._layers ? layer : this.getLayerId(layer); @@ -41,10 +61,14 @@ L.LayerGroup = L.Layer.extend({ return this; }, + // 🍂method hasLayer(layer: Layer): Boolean + // Returns `true` if the given layer is currently added to the group. hasLayer: function (layer) { return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers); }, + // 🍂method clearLayers(): this + // Removes all the layers from the group. clearLayers: function () { for (var i in this._layers) { this.removeLayer(this._layers[i]); @@ -52,6 +76,10 @@ L.LayerGroup = L.Layer.extend({ return this; }, + // 🍂method invoke(methodName: string, …): this + // Calls `methodName` on every layer contained in this group, passing any + // additional parameters. Has no effect if the layers contained do not + // implement `methodName`. invoke: function (methodName) { var args = Array.prototype.slice.call(arguments, 1), i, layer; @@ -79,6 +107,13 @@ L.LayerGroup = L.Layer.extend({ } }, + // 🍂method eachLayer(fn: Function, context?: Object): this + // Iterates over the layers of the group, optionally specifying context of the iterator function. + // ```js + // group.eachLayer(function (layer) { + // layer.bindPopup('Hello'); + // }); + // ``` eachLayer: function (method, context) { for (var i in this._layers) { method.call(context, this._layers[i]); @@ -86,10 +121,14 @@ L.LayerGroup = L.Layer.extend({ return this; }, + // 🍂method getLayer(id: Number): Layer + // Returns the layer with the given internal ID. getLayer: function (id) { return this._layers[id]; }, + // 🍂method getLayers(): Layer[] + // Returns an array of all the layers added to the group. getLayers: function () { var layers = []; @@ -99,15 +138,22 @@ L.LayerGroup = L.Layer.extend({ return layers; }, + // 🍂method setZIndex(zIndex): this + // Calls `setZIndex` on every layer contained in this group, passing the z-index. setZIndex: function (zIndex) { return this.invoke('setZIndex', zIndex); }, + // 🍂method getLayerId(layer: Layer): Number + // Returns the internal ID for a layer getLayerId: function (layer) { return L.stamp(layer); } }); + +// 🍂factory L.layerGroup(layers: Layer[]) +// Create a layer group, optionally given an initial set of layers. L.layerGroup = function (layers) { return new L.LayerGroup(layers); }; diff --git a/src/layer/Popup.js b/src/layer/Popup.js index e52d8d954..9b259fbff 100644 --- a/src/layer/Popup.js +++ b/src/layer/Popup.js @@ -1,31 +1,109 @@ /* - * L.Popup is used for displaying popups on the map. + * 🍂class Popup + * 🍂inherits Layer + * 🍂aka L.Popup + * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to + * open popups while making sure that only one popup is open at one time + * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want. + * + * 🍂example + * + * If you want to just bind a popup to marker click and then open it, it's really easy: + * + * ```js + * 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: + * + * ```js + * var popup = L.popup() + * .setLatLng(latlng) + * .setContent('

Hello world!
This is a nice popup.

') + * .openOn(map); + * ``` */ + +/* 🍂namespace Map + * 🍂section Interaction Options + * 🍂option closePopupOnClick: Boolean = true + * Set it to `false` if you don't want popups to close when user clicks the map. + */ L.Map.mergeOptions({ closePopupOnClick: true }); +// 🍂namespace Popup L.Popup = L.Layer.extend({ + // 🍂section + // 🍂aka Popup options options: { - pane: 'popupPane', - - minWidth: 50, + // 🍂option maxWidth: Number = 300 + // Max width of the popup, in pixels. maxWidth: 300, - // maxHeight: , + + // 🍂option minWidth: Number = 50 + // Min width of the popup, in pixels. + minWidth: 50, + + // 🍂option maxHeight: Number = null + // If set, creates a scrollable container of the given height + // inside a popup if its content exceeds it. + maxHeight: null, + + // 🍂option autoPan: Boolean = true + // Set it to `false` if you don't want the map to do panning animation + // to fit the opened popup. + autoPan: true, + + // 🍂option autoPanPaddingTopLeft: Point = null + // The margin between the popup and the top left corner of the map + // view after autopanning was performed. + autoPanPaddingTopLeft: null, + + // 🍂option autoPanPaddingTopLeft: Point = null + // The margin between the popup and the bottom right corner of the map + // view after autopanning was performed. + autoPanPaddingBottomRight: null, + + // 🍂option autoPanPadding: Point = Point(5, 5) + // Equivalent of setting both top left and bottom right autopan padding to the same value. + autoPanPadding: [5, 5], + + // 🍂option keepInView: Boolean = false + // Set it to `true` if you want to prevent users from panning the popup + // off of the screen while it is open. + keepInView: false, + + // 🍂option closeButton: Boolean = true + // Controls the presence of a close button in the popup. + closeButton: true, + + // 🍂option offset: Point = Point(0, 7) + // The offset of the popup position. Useful to control the anchor + // of the popup when opening it on some overlays. offset: [0, 7], - autoPan: true, - autoPanPadding: [5, 5], - // autoPanPaddingTopLeft: , - // autoPanPaddingBottomRight: , - - closeButton: true, + // 🍂option autoClose: Boolean = true + // Set 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's [closePopupOnClick](#map-closepopuponclick) option). autoClose: true, - // keepInView: false, - // className: '', - zoomAnimation: true + + // 🍂option zoomAnimation: Boolean = true + // Whether to animate the popup on zoom. Disable it if you have + // problems with Flash content inside popups. + zoomAnimation: true, + + // 🍂option className: String = '' + // A custom CSS class name to assign to the popup. + className: '', + + // 🍂option pane: String = 'popupPane' + // `Map pane` where the popup will be added. + pane: 'popupPane' }, initialize: function (options, source) { @@ -53,14 +131,25 @@ L.Popup = L.Layer.extend({ L.DomUtil.setOpacity(this._container, 1); } + // 🍂namespace Map + // 🍂section Popup events + // 🍂event popupopen: PopupEvent + // Fired when a popup is opened in the map map.fire('popupopen', {popup: this}); if (this._source) { + // 🍂namespace Layer + // 🍂section Popup events + // 🍂event popupopen: PopupEvent + // Fired when a popup bound to this layer is opened this._source.fire('popupopen', {popup: this}, true); this._source.on('preclick', L.DomEvent.stopPropagation); } }, + // 🍂namespace Popup + // 🍂method openOn(map: Map): this + // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`. openOn: function (map) { map.openPopup(this); return this; @@ -74,18 +163,32 @@ L.Popup = L.Layer.extend({ L.DomUtil.remove(this._container); } + // 🍂namespace Map + // 🍂section Popup events + // 🍂event popupclose: PopupEvent + // Fired when a popup in the map is closed map.fire('popupclose', {popup: this}); if (this._source) { + // 🍂namespace Layer + // 🍂section Popup events + // 🍂event popupclose: PopupEvent + // Fired when a popup bound to this layer is closed + // 🍂namespace Popup this._source.fire('popupclose', {popup: this}, true); this._source.off('preclick', L.DomEvent.stopPropagation); } }, + // 🍂namespace Popup + // 🍂method getLatLng: LatLng + // Returns the geographical point of popup. getLatLng: function () { return this._latlng; }, + // 🍂method setLatLng(latlng: LatLng): this + // Sets the geographical point where the popup will open. setLatLng: function (latlng) { this._latlng = L.latLng(latlng); if (this._map) { @@ -95,20 +198,28 @@ L.Popup = L.Layer.extend({ return this; }, + // 🍂method getContent: String|HTMLElement + // Returns the content of the popup. getContent: function () { return this._content; }, + // 🍂method setContent(htmlContent: String|HTMLElement|Function): this + // Sets the HTML content of the popup. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the popup. setContent: function (content) { this._content = content; this.update(); return this; }, + // 🍂method getElement: String|HTMLElement + // Alias for [getContent()](#popup-getcontent) getElement: function () { return this._container; }, + // 🍂method update: null + // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded. update: function () { if (!this._map) { return; } @@ -141,10 +252,14 @@ L.Popup = L.Layer.extend({ return events; }, + // 🍂method isOpen: Boolean + // Returns `true` when the popup is visible on the map. isOpen: function () { return !!this._map && this._map.hasLayer(this); }, + // 🍂method bringToFront: this + // Brings this popup in front of other popups (in the same map pane). bringToFront: function () { if (this._map) { L.DomUtil.toFront(this._container); @@ -152,6 +267,8 @@ L.Popup = L.Layer.extend({ return this; }, + // 🍂method bringToBack: this + // Brings this popup to the back of other popups (in the same map pane). bringToBack: function () { if (this._map) { L.DomUtil.toBack(this._container); @@ -296,6 +413,10 @@ L.Popup = L.Layer.extend({ dy = containerPos.y - paddingTL.y; } + // 🍂namespace Map + // 🍂section Popup events + // 🍂event autopanstart + // Fired when the map starts autopanning when opening a popup. if (dx || dy) { map .fire('autopanstart') @@ -309,13 +430,23 @@ L.Popup = L.Layer.extend({ } }); +// 🍂namespace Popup +// 🍂factory L.popup(options?: Popup options, source?: Layer) +// 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 Layer to which it refers. L.popup = function (options, source) { return new L.Popup(options, source); }; +// 🍂namespace Map +// 🍂section Methods for Layers and Controls L.Map.include({ - openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object]) + // 🍂method openPopup(popup: Popup): this + // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability). + // 🍂alternative + // 🍂method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this + // Creates a popup with the specified content and options and opens it in the given point on a map. + openPopup: function (popup, latlng, options) { if (!(popup instanceof L.Popup)) { popup = new L.Popup(options).setContent(popup); } @@ -336,6 +467,8 @@ L.Map.include({ return this.addLayer(popup); }, + // 🍂method closePopup(popup?: Popup): this + // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one). closePopup: function (popup) { if (!popup || popup === this._popup) { popup = this._popup; diff --git a/src/layer/marker/DivIcon.js b/src/layer/marker/DivIcon.js index 79301d154..b6ab8d1e6 100644 --- a/src/layer/marker/DivIcon.js +++ b/src/layer/marker/DivIcon.js @@ -1,19 +1,40 @@ /* - * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon) - * to use with L.Marker. + * 🍂class DivIcon + * 🍂aka L.DivIcon + * 🍂inherits Icon + * + * Represents a lightweight icon for markers that uses a simple `
` + * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options. + * + * 🍂example + * ```js + * 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' CSS class and is styled as a little white square with a shadow. */ L.DivIcon = L.Icon.extend({ options: { + // 🍂section + // 🍂aka DivIcon options iconSize: [12, 12], // also can be set through CSS - /* - iconAnchor: (Point) - popupAnchor: (Point) - html: (String) - bgPos: (Point) - */ - className: 'leaflet-div-icon', - html: false + + // iconAnchor: (Point), + // popupAnchor: (Point), + + // 🍂option html: String = '' + // Custom HTML code to put inside the div element, empty by default. + html: false, + + // 🍂option bgPos: Point = [0, 0] + // Optional relative position of the background, in pixels + bgPos: null, + + className: 'leaflet-div-icon' }, createIcon: function (oldIcon) { @@ -36,6 +57,8 @@ L.DivIcon = L.Icon.extend({ } }); +// 🍂factory L.divIcon(options: DivIcon options) +// Creates a `DivIcon` instance with the given options. L.divIcon = function (options) { return new L.DivIcon(options); }; diff --git a/src/layer/marker/Icon.js b/src/layer/marker/Icon.js index af6c9cdba..1f9f80986 100644 --- a/src/layer/marker/Icon.js +++ b/src/layer/marker/Icon.js @@ -1,31 +1,84 @@ /* - * L.Icon is an image-based icon class that you can use with L.Marker for custom markers. + * 🍂class Icon + * 🍂aka L.Icon + * 🍂inherits Layer + * + * Represents an icon to provide when creating a marker. + * + * 🍂example + * + * ```js + * 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. + * */ L.Icon = L.Class.extend({ - /* - options: { - iconUrl: (String) (required) - iconRetinaUrl: (String) (optional, used for retina devices if detected) - iconSize: (Point) (can be set through CSS) - iconAnchor: (Point) (centered by default, can be set in CSS with negative margins) - popupAnchor: (Point) (if not specified, popup opens in the anchor point) - shadowUrl: (String) (no shadow by default) - shadowRetinaUrl: (String) (optional, used for retina devices if detected) - shadowSize: (Point) - shadowAnchor: (Point) - className: (String) - }, - */ + + /* 🍂section + * 🍂aka Icon options + * + * 🍂option iconUrl: String = null + * **(required)** The URL to the icon image (absolute or relative to your script path). + * + * 🍂option iconRetinaUrl: String = null + * The URL to a retina sized version of the icon image (absolute or relative to your + * script path). Used for Retina screen devices. + * + * 🍂option iconSize: Point = null + * Size of the icon image in pixels. + * + * 🍂option iconAnchor: Point = null + * The coordinates of the "tip" of the icon (relative to its top left corner). The icon + * will be aligned so that this point is at the marker's geographical location. Centered + * by default if size is specified, also can be set in CSS with negative margins. + * + * 🍂option popupAnchor: Point = null + * The coordinates of the point from which popups will "open", relative to the icon anchor. + * + * 🍂option shadowUrl: String = null + * The URL to the icon shadow image. If not specified, no shadow image will be created. + * + * 🍂option shadowRetinaUrl: String = null + * + * 🍂option shadowSize: Point = null + * Size of the shadow image in pixels. + * + * 🍂option shadowAnchor: Point = null + * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same + * as iconAnchor if not specified). + * + * 🍂option className: String = '' + * A custom class name to assign to both icon and shadow images. Empty by default. + */ initialize: function (options) { L.setOptions(this, options); }, + // 🍂method createIcon(oldIcon: HTMLElement|null): HTMLElement + // Called internally when the icon has to be shown, returns a `` HTML element + // styled according to the options. createIcon: function (oldIcon) { return this._createIcon('icon', oldIcon); }, + // 🍂method createShadow(oldIcon: HTMLElement|null): HTMLElement + // As `createIcon`, but for the shadow beneath it. createShadow: function (oldIcon) { return this._createIcon('shadow', oldIcon); }, @@ -76,6 +129,9 @@ L.Icon = L.Class.extend({ } }); + +// 🍂factory L.icon(options: Icon options) +// Creates an icon instance with the given options. L.icon = function (options) { return new L.Icon(options); }; diff --git a/src/layer/marker/Marker.Drag.js b/src/layer/marker/Marker.Drag.js index 108bcff38..fc2bc2625 100644 --- a/src/layer/marker/Marker.Drag.js +++ b/src/layer/marker/Marker.Drag.js @@ -2,6 +2,20 @@ * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable. */ + +/* 🍂namespace Marker + * 🍂section 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 `Handler` methods). Example: + * + * ```js + * marker.dragging.disable(); + * ``` + * + * 🍂property dragging: Handler + * Marker dragging handler (by both mouse and touch). + */ + L.Handler.MarkerDrag = L.Handler.extend({ initialize: function (marker) { this._marker = marker; @@ -40,6 +54,12 @@ L.Handler.MarkerDrag = L.Handler.extend({ }, _onDragStart: function () { + // 🍂section Dragging events + // 🍂event dragstart: Event + // Fired when the user starts dragging the marker. + + // 🍂event movestart: Event + // Fired when the marker starts moving (because of dragging). this._marker .closePopup() .fire('movestart') @@ -60,12 +80,19 @@ L.Handler.MarkerDrag = L.Handler.extend({ marker._latlng = latlng; e.latlng = latlng; + // 🍂event drag: Event + // Fired repeatedly while the user drags the marker. marker .fire('move', e) .fire('drag', e); }, _onDragEnd: function (e) { + // 🍂event dragend: DragEndEvent + // Fired when the user stops dragging the marker. + + // 🍂event moveend: Event + // Fired when the marker stops moving (because of dragging). this._marker .fire('moveend') .fire('dragend', e); diff --git a/src/layer/marker/Marker.js b/src/layer/marker/Marker.js index e03a1392b..516a1e619 100644 --- a/src/layer/marker/Marker.js +++ b/src/layer/marker/Marker.js @@ -1,25 +1,97 @@ /* - * L.Marker is used to display clickable/draggable icons on the map. + * 🍂class Marker + * 🍂inherits Layer + * 🍂aka L.Marker + * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`. + * + * 🍂example + * + * ```js + * L.marker([50.5, 30.5]).addTo(map); + * ``` */ L.Marker = L.Layer.extend({ options: { - pane: 'markerPane', - nonBubblingEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'], - + // 🍂option icon: L.Icon = * + // Icon class to use for rendering the marker. See [Icon documentation](#L.Icon) for details on how to customize the marker icon. Set to new `L.Icon.Default()` by default. icon: new L.Icon.Default(), - // title: '', - // alt: '', + + // 🍂option interactive: Boolean = true + // If `false`, the marker will not emit mouse events and will act as a part of the underlying map. interactive: true, - // draggable: false, + + // 🍂option draggable: Boolean = false + // Whether the marker is draggable with mouse/touch or not. + draggable: false, + + // 🍂option keyboard: Boolean = true + // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. keyboard: true, + + // 🍂option title: String = '' + // Text for the browser tooltip that appear on marker hover (no tooltip by default). + title: '', + + // 🍂option alt: String = '' + // Text for the `alt` attribute of the icon image (useful for accessibility). + alt: '', + + // 🍂option zIndexOffset: Number = 0 + // By default, marker images zIndex 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). zIndexOffset: 0, + + // 🍂option opacity: Number = 1.0 + // The opacity of the marker. opacity: 1, - // riseOnHover: false, - riseOffset: 250 + + // 🍂option riseOnHover: Boolean = false + // If `true`, the marker will get on top of others when you hover the mouse over it. + riseOnHover: false, + + // 🍂option riseOffset: Number = 250 + // The z-index offset used for the `riseOnHover` feature. + riseOffset: 250, + + // 🍂option pane: String = 'markerPane' + // `Map pane` where the markers icon will be added. + pane: 'markerPane', + + // FIXME: shadowPane is no longer a valid option + nonBubblingEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'] }, + /* 🍂section + * + * You can subscribe to the following events using [these methods](#evented-method). + * + * 🍂event click: MouseEvent + * Fired when the user clicks (or taps) the marker. + * + * 🍂event dblclick: MouseEvent + * Fired when the user double-clicks (or double-taps) the marker. + * + * 🍂event mousedown: MouseEvent + * Fired when the user pushes the mouse button on the marker. + * + * 🍂event mouseover: MouseEvent + * Fired when the mouse enters the marker. + * + * 🍂event mouseout: MouseEvent + * Fired when the mouse leaves the marker. + * + * 🍂event contextmenu: MouseEvent + * Fired when the user right-clicks on the marker. + */ + + + + /* 🍂section + * + * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods: + */ + initialize: function (latlng, options) { L.setOptions(this, options); this._latlng = L.latLng(latlng); @@ -55,22 +127,33 @@ L.Marker = L.Layer.extend({ return events; }, + // 🍂method getLatLng: LatLng + // Returns the current geographical position of the marker. getLatLng: function () { return this._latlng; }, + // 🍂method setLatLng(latlng: LatLng): this + // Changes the marker position to the given point. setLatLng: function (latlng) { var oldLatLng = this._latlng; this._latlng = L.latLng(latlng); this.update(); + + // 🍂event move: Event + // Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng}); }, + // 🍂method setZIndexOffset(offset: Number): this + // Changes the [zIndex offset](#marker-zindexoffset) of the marker. setZIndexOffset: function (offset) { this.options.zIndexOffset = offset; return this.update(); }, + // 🍂method setIcon(icon: Icon): this + // Changes the marker icon. setIcon: function (icon) { this.options.icon = icon; @@ -232,6 +315,8 @@ L.Marker = L.Layer.extend({ } }, + // 🍂method setOpacity(opacity: Number): this + // Changes the opacity of the marker. setOpacity: function (opacity) { this.options.opacity = opacity; if (this._map) { @@ -260,6 +345,11 @@ L.Marker = L.Layer.extend({ } }); + +// factory L.marker(latlng: LatLng, options? : Marker options) + +// 🍂factory L.marker(latlng: LatLng, options? : Marker options) +// Instantiates a Marker object given a geographical point and optionally an options object. L.marker = function (latlng, options) { return new L.Marker(latlng, options); }; diff --git a/src/layer/tile/GridLayer.js b/src/layer/tile/GridLayer.js index 348a60418..2890677b0 100644 --- a/src/layer/tile/GridLayer.js +++ b/src/layer/tile/GridLayer.js @@ -1,25 +1,112 @@ /* - * L.GridLayer is used as base class for grid-like layers like TileLayer. + * 🍂class GridLayer + * 🍂inherits Layer + * 🍂aka L.GridLayer + * + * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`. + * GridLayer can be extended to create a tiled grid of HTML Elements like ``, `` or `
`. GridLayer will handle creating and animating these DOM elements for you. + * + * + * 🍂section Synchronous usage + * 🍂example + * + * To create a custom layer, extend GridLayer and impliment the `createTile()` method, which will be passed a `Point` object with the `x`, `y`, and `z` (zoom level) coordinates to draw your tile. + * + * ```js + * var CanvasLayer = L.GridLayer.extend({ + * createTile: function(coords){ + * // create a element for drawing + * var tile = L.DomUtil.create('canvas', 'leaflet-tile'); + * + * // setup tile width and height according to the options + * var size = this.getTileSize(); + * tile.width = size.x; + * tile.height = size.y; + * + * // get a canvas context and draw something on it using coords.x, coords.y and coords.z + * var ctx = canvas.getContext('2d'); + * + * // return the tile so it can be rendered on screen + * return tile; + * } + * }); + * ``` + * + * 🍂section Asynchrohous usage + * 🍂example + * + * Tile creation can also be asyncronous, this is useful when using a third-party drawing library. Once the tile is finsihed drawing it can be passed to the done() callback. + * + * ```js + * var CanvasLayer = L.GridLayer.extend({ + * createTile: function(coords, done){ + * var error; + * + * // create a element for drawing + * var tile = L.DomUtil.create('canvas', 'leaflet-tile'); + * + * // setup tile width and height according to the options + * var size = this.getTileSize(); + * tile.width = size.x; + * tile.height = size.y; + * + * // draw something and pass the tile to the done() callback + * done(error, tile); + * } + * }); + * ``` + * + * 🍂section */ + L.GridLayer = L.Layer.extend({ options: { - pane: 'tilePane', - + // 🍂option tileSize: Number|Point = 256 + // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise. tileSize: 256, - opacity: 1, - zIndex: 1, + // 🍂option opacity: Number = 1.0 + // Opacity of the tiles. Can be used in the `createTile()` function. + opacity: 1, + + // 🍂option updateWhenIdle: Boolean = depends + // If `false`, new tiles are loaded during panning, otherwise only after it (for better performance). `true` by default on mobile browsers, otherwise `false`. updateWhenIdle: L.Browser.mobile, + + // 🍂option updateInterval: Number = 200 + // Tiles will not update more than once every `updateInterval` milliseconds. updateInterval: 200, + // 🍂option attribution: String = null + // String to be shown in the attribution control, describes the layer data, e.g. "© Mapbox". attribution: null, + + // 🍂option zIndex: Number = 1 + // The explicit zIndex of the tile layer. + zIndex: 1, + + // 🍂option bounds: LatLngBounds = undefined + // If set, tiles will only be loaded inside inside the set `LatLngBounds`. bounds: null, - minZoom: 0 - // maxZoom: - // noWrap: false + // 🍂option minZoom: Number = 0 + // The minimum zoom level that tiles will be loaded at. By default the entire map. + minZoom: 0, + + // 🍂option maxZoom: Number = undefined + // The maximum zoom level that tiles will be loaded at. +// maxZoom: undefined, + + // 🍂option noWrap: Boolean = false + // Whether the layer is wrapped around the antimeridian. If `true`, the + // GridLayer will only be displayed once at low zoom levels. + noWrap: false, + + // 🍂option pane: String = 'tilePane' + // `Map pane` where the grid layer will be added. + pane: 'tilePane' }, initialize: function (options) { @@ -48,6 +135,8 @@ L.GridLayer = L.Layer.extend({ this._tileZoom = null; }, + // 🍂method bringToFront: this + // Brings the tile layer to the top of all tile layers. bringToFront: function () { if (this._map) { L.DomUtil.toFront(this._container); @@ -56,6 +145,8 @@ L.GridLayer = L.Layer.extend({ return this; }, + // 🍂method bringToBack: this + // Brings the tile layer to the bottom of all tile layers. bringToBack: function () { if (this._map) { L.DomUtil.toBack(this._container); @@ -64,20 +155,28 @@ L.GridLayer = L.Layer.extend({ return this; }, + // 🍂method getAttribution: String + // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). getAttribution: function () { return this.options.attribution; }, + // 🍂method getcontainer: String + // Returns the HTML element that contains the tiles for this layer. getContainer: function () { return this._container; }, + // 🍂method setOpacity(opacity: Number): this + // Changes the [opacity](#gridlayer-opacity) of the grid layer. setOpacity: function (opacity) { this.options.opacity = opacity; this._updateOpacity(); return this; }, + // 🍂method setZIndex(zIndex: Number): this + // Changes the [zIndex](#gridlayer-zindex) of the grid layer. setZIndex: function (zIndex) { this.options.zIndex = zIndex; this._updateZIndex(); @@ -85,10 +184,14 @@ L.GridLayer = L.Layer.extend({ return this; }, + // 🍂method isLoading: Boolean + // Returns `true` if any tile in the grid layer has not finished loading. isLoading: function () { return this._loading; }, + // 🍂method redraw: this + // Causes the layer to clear all the tiles and request them again. redraw: function () { if (this._map) { this._removeAllTiles(); @@ -121,10 +224,19 @@ L.GridLayer = L.Layer.extend({ return events; }, + // 🍂section Extension methods + // Layers extending `GridLayer` shall reimplement the following method. + // 🍂method createTile(coords: Object, done?: Function): HTMLElement + // Called only internally, must be overriden by classes extending `GridLayer`. + // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback + // is specified, it must be called when the tile has finished loading and drawing. createTile: function () { return document.createElement('div'); }, + // 🍂section + // 🍂method getTileSize: Point + // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method. getTileSize: function () { var s = this.options.tileSize; return s instanceof L.Point ? s : new L.Point(s, s); @@ -507,6 +619,8 @@ L.GridLayer = L.Layer.extend({ // if its the first batch of tiles to load if (!this._loading) { this._loading = true; + // 🍂event loading: Event + // Fired when the grid layer starts loading tiles this.fire('loading'); } @@ -578,6 +692,8 @@ L.GridLayer = L.Layer.extend({ delete this._tiles[key]; + // 🍂event tileunload: TileEvent + // Fired when a tile is removed (e.g. when a tile goes off the screen). this.fire('tileunload', { tile: tile.el, coords: this._keyToTileCoords(key) @@ -631,6 +747,8 @@ L.GridLayer = L.Layer.extend({ }; container.appendChild(tile); + // 🍂event tileloadstart: TileEvent + // Fired when a tile is requested and starts loading. this.fire('tileloadstart', { tile: tile, coords: coords @@ -641,6 +759,8 @@ L.GridLayer = L.Layer.extend({ if (!this._map) { return; } if (err) { + // 🍂event tileerror: TileEvent + // Fired when there is an error loading a tile. this.fire('tileerror', { error: err, tile: tile, @@ -665,6 +785,8 @@ L.GridLayer = L.Layer.extend({ L.DomUtil.addClass(tile.el, 'leaflet-tile-loaded'); + // 🍂event tileload: TileEvent + // Fired when a tile loads. this.fire('tileload', { tile: tile.el, coords: coords @@ -672,6 +794,8 @@ L.GridLayer = L.Layer.extend({ if (this._noTilesToLoad()) { this._loading = false; + // 🍂event load: TileEvent + // Fired when the grid layer loaded all visible tiles. this.fire('load'); if (L.Browser.ielt9 || !this._map._fadeAnimated) { @@ -711,6 +835,8 @@ L.GridLayer = L.Layer.extend({ } }); +// 🍂factory L.gridLayer(options?: GridLayer options) +// Creates a new instance of GridLayer with the supplied options. L.gridLayer = function (options) { return new L.GridLayer(options); }; diff --git a/src/layer/tile/TileLayer.WMS.js b/src/layer/tile/TileLayer.WMS.js index 407b46ba8..bf5e31802 100644 --- a/src/layer/tile/TileLayer.WMS.js +++ b/src/layer/tile/TileLayer.WMS.js @@ -1,21 +1,58 @@ /* - * L.TileLayer.WMS is used for WMS tile layers. + * 🍂class TileLayer.WMS + * 🍂inherits TileLayer + * 🍂aka L.TileLayer.WMS + * Used to display WMS services as tile layers on the map. Extends `TileLayer`. + * + * 🍂example + * + * ```js + * 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" + * }); + * ``` */ L.TileLayer.WMS = L.TileLayer.extend({ + // 🍂section + // 🍂aka TileLayer.WMS options defaultWmsParams: { service: 'WMS', request: 'GetMap', - version: '1.1.1', + + // 🍂option layers: String = '' + // **(required)** Comma-separated list of WMS layers to show. layers: '', + + // 🍂option styles: String = '' + // Comma-separated list of WMS styles. styles: '', + + // 🍂option format: String = 'image/jpeg' + // WMS image format (use `'image/png'` for layers with transparency). format: 'image/jpeg', - transparent: false + + // 🍂option styles: Boolean = false + // If `true`, the WMS service will return images with transparency. + transparent: false, + + // 🍂option version: String = '1.1.1' + // Version of the WMS service to use + version: '1.1.1' }, options: { + // 🍂option crs: CRS = null + // Coordinate Reference System to use for the WMS requests, defaults to + // map CRS. Don't change this if you're not sure what it means. crs: null, + + // 🍂option uppercase: Boolean = false + // If `true`, WMS request parameter keys will be uppercase. uppercase: false }, @@ -67,6 +104,8 @@ L.TileLayer.WMS = L.TileLayer.extend({ (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox; }, + // 🍂method setParams(params: Object, noRedraw?: Boolean): this + // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true). setParams: function (params, noRedraw) { L.extend(this.wmsParams, params); @@ -79,6 +118,9 @@ L.TileLayer.WMS = L.TileLayer.extend({ } }); + +// 🍂factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options) +// Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object. L.tileLayer.wms = function (url, options) { return new L.TileLayer.WMS(url, options); }; diff --git a/src/layer/tile/TileLayer.js b/src/layer/tile/TileLayer.js index 33c0d7f59..b73f88c3c 100644 --- a/src/layer/tile/TileLayer.js +++ b/src/layer/tile/TileLayer.js @@ -1,20 +1,79 @@ /* - * L.TileLayer is used for standard xyz-numbered tile layers. + * 🍂class TileLayer + * 🍂inherits GridLayer + * 🍂aka L.TileLayer + * Used to load and display tile layers on the map. Extends `GridLayer`. + * + * 🍂example + * + * ```js + * L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map); + * ``` + * + * 🍂section URL template + * 🍂example + * + * A string of the following form: + * + * ``` + * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.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. `{r}` can be used to add @2x to the URL to load retina tiles. + * + * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this: + * + * ``` + * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'}); + * ``` + * + * 🍂section */ + L.TileLayer = L.GridLayer.extend({ options: { + // 🍂option minZoom: Number = 0 + // Minimum zoom number. + minZoom: 0, + + // 🍂option maxZoom: Number = 18 + // Maximum zoom number. maxZoom: 18, + // 🍂option maxNativeZoom: Number = null + // Maximum zoom number the tile 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. + maxNativeZoom: null, + + // 🍂option subdomains: String|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. subdomains: 'abc', + + // 🍂option errorTileUrl: String = '' + // URL to the tile image to show in place of the tile that failed to load. errorTileUrl: '', + + // 🍂option zoomOffset: Number = 0 + // The zoom number used in tile URLs will be offset with this value. zoomOffset: 0, - maxNativeZoom: null, // Number + // 🍂option tms: Boolean = false + // If `true`, inverses Y axis numbering for tiles (turn this on for TMS services). tms: false, + + // 🍂option zoomReverse: Boolean = false + // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`) zoomReverse: false, + + // 🍂option detectRetina: Boolean = false + // If `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. detectRetina: false, + + // 🍂option crossOrigin: Boolean = false + // If true, all tiles will have their crossOrigin attribute set to ''. This is needed if you want to access tile pixel data. crossOrigin: false }, @@ -44,6 +103,8 @@ L.TileLayer = L.GridLayer.extend({ } }, + // 🍂method setUrl(url: String, noRedraw?: Boolean): this + // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`). setUrl: function (url, noRedraw) { this._url = url; @@ -53,6 +114,10 @@ L.TileLayer = L.GridLayer.extend({ return this; }, + // 🍂method createTile(coords: Object, done?: Function): HTMLElement + // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile) + // to return an `` HTML element with the appropiate image URL given `coords`. The `done` + // callback is called when the tile has been loaded. createTile: function (coords, done) { var tile = document.createElement('img'); @@ -74,6 +139,12 @@ L.TileLayer = L.GridLayer.extend({ return tile; }, + // 🍂section Extension methods + // 🍂uninheritable + // Layers extending `TileLayer` might reimplement the following method. + // 🍂method getTileUrl(coords: Object): String + // Called only internally, returns the URL for a tile given its coordinates. + // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes. getTileUrl: function (coords) { var data = { r: L.Browser.retina ? '@2x' : '', @@ -164,6 +235,10 @@ L.TileLayer = L.GridLayer.extend({ } }); + +// 🍂factory L.tilelayer(urlTemplate: String, options? TileLayer options) +// Instantiates a tile layer object given a `URL template` and optionally an options object. + L.tileLayer = function (url, options) { return new L.TileLayer(url, options); }; diff --git a/src/layer/vector/Canvas.js b/src/layer/vector/Canvas.js index f11715cd0..dce97305c 100644 --- a/src/layer/vector/Canvas.js +++ b/src/layer/vector/Canvas.js @@ -1,5 +1,33 @@ /* - * L.Canvas handles Canvas vector layers rendering and mouse events handling. All Canvas-specific code goes here. + * 🍂class Canvas + * 🍂inherits Renderer + * 🍂aka L.Canvas + * + * Allows vector layers to be displayed with [``](https://developer.mozilla.org/docs/Web/API/Canvas_API). + * Inherits `Renderer`. + * + * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not + * available in all web browsers, notably IE8, and overlapping geometries might + * not display properly in some edge cases. + * + * 🍂example + * + * Use Canvas by default for all paths in the map: + * + * ```js + * var map = L.map('map', { + * renderer: L.canvas(); + * }); + * ``` + * + * Use a Canvas renderer with extra padding for specific vector geometries: + * + * ```js + * var map = L.map('map'); + * var myRenderer = L.canvas({ padding: 0.5 }); + * var line = L.polyline( coordinates, { renderer: myRenderer } ); + * var circle = L.circle( center, { renderer: myRenderer } ); + * ``` */ L.Canvas = L.Renderer.extend({ @@ -275,10 +303,15 @@ L.Canvas = L.Renderer.extend({ _bringToBack: L.Util.falseFn }); +// 🍂namespace Browser; 🍂property canvas: Boolean +// `true` when the browser supports [``](https://developer.mozilla.org/docs/Web/API/Canvas_API). L.Browser.canvas = (function () { return !!document.createElement('canvas').getContext; }()); +// 🍂namespace Canvas +// 🍂factory L.canvas(options?: Canvas options) +// Creates a Canvas renderer with the given options. L.canvas = function (options) { return L.Browser.canvas ? new L.Canvas(options) : null; }; diff --git a/src/layer/vector/Circle.js b/src/layer/vector/Circle.js index 5ecd44b9c..cdb397c6e 100644 --- a/src/layer/vector/Circle.js +++ b/src/layer/vector/Circle.js @@ -1,6 +1,17 @@ /* - * L.Circle is a circle overlay (with a certain radius in meters). - * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion) + * 🍂class Circle + * 🍂aka L.Circle + * 🍂inherits CircleMarker + * + * A class for drawing circle overlays on a map. Extends `CircleMarker`. + * + * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion). + * + * 🍂example + * + * ```js + * L.circle([50.5, 30.5], 200).addTo(map); + * ``` */ L.Circle = L.CircleMarker.extend({ @@ -15,18 +26,25 @@ L.Circle = L.CircleMarker.extend({ if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); } + // 🍂option radius: Number; Radius of the circle, in meters. this._mRadius = this.options.radius; }, + // 🍂method setRadius(radius: Number): this + // Sets the radius of a circle. Units are in meters. setRadius: function (radius) { this._mRadius = radius; return this.redraw(); }, + // 🍂method getRadius(): Number + // Returns the current radius of a circle. Units are in meters. getRadius: function () { return this._mRadius; }, + // 🍂method getBounds(): LatLngBounds + // Returns the `LatLngBounds` of the path. getBounds: function () { var half = [this._radius, this._radiusY || this._radius]; @@ -73,6 +91,13 @@ L.Circle = L.CircleMarker.extend({ } }); +// 🍂factory L.circle(latlng: LatLng, options?: Path options) +// Instantiates a circle object given a geographical point, and an options object +// which contains the circle radius. +// 🍂alternative +// 🍂factory L.circle(latlng: LatLng, radius: Number, options?: Path options) +// Obsolete way of instantiating a circle, for compatibility with 0.7.x code. +// Do not use in new applications or plugins. L.circle = function (latlng, options, legacyOptions) { return new L.Circle(latlng, options, legacyOptions); }; diff --git a/src/layer/vector/CircleMarker.js b/src/layer/vector/CircleMarker.js index 7ced11b7c..8d5d38cf7 100644 --- a/src/layer/vector/CircleMarker.js +++ b/src/layer/vector/CircleMarker.js @@ -1,11 +1,18 @@ /* - * L.CircleMarker is a circle overlay with a permanent pixel radius. + * 🍂class CircleMarker + * 🍂aka L.CircleMarker + * 🍂inherits Path + * + * A circle of a fixed size with radius specified in pixels. Extends `Path`. */ L.CircleMarker = L.Path.extend({ options: { fill: true, + + // 🍂option radius: Number = 10 + // Radius of the circle marker, in pixels radius: 10 }, @@ -15,21 +22,29 @@ L.CircleMarker = L.Path.extend({ this._radius = this.options.radius; }, + // 🍂method setLatLng(latLng: LatLng): this + // Sets the position of a circle marker to a new location. setLatLng: function (latlng) { this._latlng = L.latLng(latlng); this.redraw(); return this.fire('move', {latlng: this._latlng}); }, + // 🍂method getLatLng(): LatLng + // Returns the current geographical position of the circle marker getLatLng: function () { return this._latlng; }, + // 🍂method setRadius(radius: Number): this + // Sets the radius of a circle marker. Units are in pixels. setRadius: function (radius) { this.options.radius = this._radius = radius; return this.redraw(); }, + // 🍂method getRadius(): Number + // Returns the current radius of the circle getRadius: function () { return this._radius; }, @@ -69,6 +84,9 @@ L.CircleMarker = L.Path.extend({ } }); + +// 🍂factory L.circleMarker(latlng: LatLng, options? CircleMarker options) +// L.circleMarker = function (latlng, options) { return new L.CircleMarker(latlng, options); }; diff --git a/src/layer/vector/Path.js b/src/layer/vector/Path.js index fa23db71e..1c6bede2c 100644 --- a/src/layer/vector/Path.js +++ b/src/layer/vector/Path.js @@ -1,25 +1,69 @@ /* - * L.Path is the base class for all Leaflet vector layers like polygons and circles. + * 🍂class Path + * 🍂aka L.Path + * 🍂inherits Layer + * + * An abstract class that contains options and constants shared between vector + * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`. */ L.Path = L.Layer.extend({ + // 🍂section + // 🍂aka Path options options: { + // 🍂option stroke: Boolean = true + // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles. stroke: true, - color: '#3388ff', - weight: 3, - opacity: 1, - lineCap: 'round', - lineJoin: 'round', - // dashArray: null - // dashOffset: null - // fill: false - // fillColor: same as color by default + // 🍂option color: String = '#3388ff' + // Stroke color + color: '#3388ff', + + // 🍂option weight: Number = 3 + // Stroke width in pixels + weight: 3, + + // 🍂option opacity: Number = 1.0 + // Stroke opacity + opacity: 1, + + // 🍂option lineCap: String= 'round' + // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke. + lineCap: 'round', + + // 🍂option lineJoin: String = 'round' + // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke. + lineJoin: 'round', + + // 🍂option dashArray: String = null + // A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on canvas-powered layers (e.g. Android 2). + dashArray: null, + + // 🍂option dashOffset: String = null + // A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on canvas-powered layers + dashOffset: null, + + // 🍂option fill: Boolean = depends + // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles. + fill: false, + + // 🍂option fillColor: String = * + // Fill color. Defaults to the value of the [`color`](#path-color) option + fillColor: null, + + // 🍂option fillOpacity: Number = 0.2 + // Fill opacity. fillOpacity: 0.2, + + // 🍂option fillRule: String = 'evenodd' + // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined. fillRule: 'evenodd', - // className: '' + // className: '', + + // 🍂option interactive: Boolean = true + // If `false`, the vector will not emit mouse events and will act as a part of the underlying map. interactive: true }, @@ -47,6 +91,8 @@ L.Path = L.Layer.extend({ }; }, + // 🍂method redraw(): this + // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses. redraw: function () { if (this._map) { this._renderer._updatePath(this); @@ -54,6 +100,8 @@ L.Path = L.Layer.extend({ return this; }, + // 🍂method setStyle(style: Path options): this + // Changes the appearance of a Path based on the options in the `Path options` object. setStyle: function (style) { L.setOptions(this, style); if (this._renderer) { @@ -62,6 +110,8 @@ L.Path = L.Layer.extend({ return this; }, + // 🍂method bringToFront(): this + // Brings the layer to the top of all path layers. bringToFront: function () { if (this._renderer) { this._renderer._bringToFront(this); @@ -69,6 +119,8 @@ L.Path = L.Layer.extend({ return this; }, + // 🍂method bringToBack(): this + // Brings the layer to the bottom of all path layers. bringToBack: function () { if (this._renderer) { this._renderer._bringToBack(this); diff --git a/src/layer/vector/Polygon.js b/src/layer/vector/Polygon.js index b9a50d7fd..fd7fd9e71 100644 --- a/src/layer/vector/Polygon.js +++ b/src/layer/vector/Polygon.js @@ -1,5 +1,47 @@ /* - * L.Polygon implements polygon vector layer (closed polyline with a fill inside). + * 🍂class Polygon + * 🍂aka L.Polygon + * 🍂inherits Polyline + * + * A class for drawing polygon overlays on a map. Extends `Polyline`. + * + * 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. + * + * + * 🍂example + * + * ```js + * // create a red polygon from an array of LatLng points + * var latlngs = [[-111.03, 41],[-111.04, 45],[-104.05, 45],[-104.05, 41]]; + * + * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map); + * + * // zoom the map to the polygon + * map.fitBounds(polygon.getBounds()); + * ``` + * + * You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape: + * + * ```js + * var latlngs = [ + * [[-111.03, 41],[-111.04, 45],[-104.05, 45],[-104.05, 41]], // outer ring + * [[-108.58,37.29],[-108.58,40.71],[-102.50,40.71],[-102.50,37.29]] // hole + * ]; + * ``` + * + * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape. + * + * ```js + * var latlngs = [ + * [ // first polygon + * [[-111.03, 41],[-111.04, 45],[-104.05, 45],[-104.05, 41]], // outer ring + * [[-108.58,37.29],[-108.58,40.71],[-102.50,40.71],[-102.50,37.29]] // hole + * ], + * [ // second polygon + * [[-109.05, 37],[-109.03, 41],[-102.05, 41],[-102.04, 37],[-109.05, 38]] + * ] + * ]; + * ``` */ L.Polygon = L.Polyline.extend({ @@ -97,6 +139,8 @@ L.Polygon = L.Polyline.extend({ } }); + +// 🍂factory L.polygon(latlngs: LatLng[], options?: Path options) L.polygon = function (latlngs, options) { return new L.Polygon(latlngs, options); }; diff --git a/src/layer/vector/Polyline.js b/src/layer/vector/Polyline.js index 43d5ad9cd..8fd651f62 100644 --- a/src/layer/vector/Polyline.js +++ b/src/layer/vector/Polyline.js @@ -1,14 +1,52 @@ /* - * L.Polyline implements polyline vector layer (a set of points connected with lines) + * 🍂class Polyline + * 🍂aka L.Polyline + * 🍂inherits Path + * + * A class for drawing polyline overlays on a map. Extends `Path`. + * + * 🍂example + * + * ```js + * // create a red polyline from an array of LatLng points + * var latlngs = [ + * [-122.68, 45.51], + * [-122.43, 37.77], + * [-118.2, 34.04] + * ]; + * + * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map); + * + * // zoom the map to the polyline + * map.fitBounds(polyline.getBounds()); + * ``` + * + * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape: + * + * ```js + * // create a red polyline from an array of arrays of LatLng points + * var latlngs = [ + * [[-122.68, 45.51], + * [-122.43, 37.77], + * [-118.2, 34.04]], + * [[-73.91, 40.78], + * [-87.62, 41.83], + * [-96.72, 32.76]] + * ]; + * ``` */ L.Polyline = L.Path.extend({ options: { - // how much to simplify the polyline on each zoom level - // more = better performance and smoother look, less = more accurate - smoothFactor: 1.0 - // noClip: false + // 🍂option 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. + smoothFactor: 1.0, + + // 🍂option noClip: Boolean: false + // Disable polyline clipping. + noClip: false }, initialize: function (latlngs, options) { @@ -16,15 +54,21 @@ L.Polyline = L.Path.extend({ this._setLatLngs(latlngs); }, + // 🍂method getLatLngs(): LatLng[] + // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline. getLatLngs: function () { return this._latlngs; }, + // 🍂method setLatLngs(latlngs: LatLng[]): this + // Replaces all the points in the polyline with the given array of geographical points. setLatLngs: function (latlngs) { this._setLatLngs(latlngs); return this.redraw(); }, + // 🍂method isEmpty(): Boolean + // Returns `true` if the Polyline has no LatLngs. isEmpty: function () { return !this._latlngs.length; }, @@ -56,6 +100,8 @@ L.Polyline = L.Path.extend({ return minPoint; }, + // 🍂method getCenter(): LatLng + // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline. getCenter: function () { var i, halfDist, segDist, dist, p1, p2, ratio, points = this._rings[0], @@ -90,10 +136,16 @@ L.Polyline = L.Path.extend({ } }, + // 🍂method getBounds(): LatLngBounds + // Returns the `LatLngBounds` of the path. getBounds: function () { return this._bounds; }, + // 🍂method addLatLng(latlng: LatLng, latlngs? LatLng[]): this + // Adds a given point to the polyline. By default, adds to the first ring of + // the polyline in case of a multi-polyline, but can be overridden by passing + // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)). addLatLng: function (latlng, latlngs) { latlngs = latlngs || this._defaultShape(); latlng = L.latLng(latlng); @@ -223,6 +275,11 @@ L.Polyline = L.Path.extend({ } }); +// 🍂factory L.polyline(latlngs: LatLng[], options?: Path options) +// Instantiates a polyline object given an array of geographical points and +// optionally an options object. You can create a `Polyline` object with +// multiple separate lines (`MultiPolyline`) by passing an array of arrays +// of geographic points. L.polyline = function (latlngs, options) { return new L.Polyline(latlngs, options); }; diff --git a/src/layer/vector/Rectangle.js b/src/layer/vector/Rectangle.js index 4fd9f087e..b87aa3b28 100644 --- a/src/layer/vector/Rectangle.js +++ b/src/layer/vector/Rectangle.js @@ -2,11 +2,36 @@ * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object. */ +/* + * 🍂class Rectangle + * 🍂aka L.Retangle + * 🍂inherits Polygon + * + * A class for drawing rectangle overlays on a map. Extends `Polygon`. + * + * 🍂example + * + * ```js + * // 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); + * ``` + * + */ + + L.Rectangle = L.Polygon.extend({ initialize: function (latLngBounds, options) { L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options); }, + // 🍂method setBounds(latLngBounds: LatLngBounds): this + // Redraws the rectangle with the passed bounds. setBounds: function (latLngBounds) { return this.setLatLngs(this._boundsToLatLngs(latLngBounds)); }, @@ -22,6 +47,8 @@ L.Rectangle = L.Polygon.extend({ } }); + +// 🍂factory L.rectangle(latLngBounds: LatLngBounds, options?: Path options) L.rectangle = function (latLngBounds, options) { return new L.Rectangle(latLngBounds, options); }; diff --git a/src/layer/vector/Renderer.js b/src/layer/vector/Renderer.js index ba400c805..8d74cbcfa 100644 --- a/src/layer/vector/Renderer.js +++ b/src/layer/vector/Renderer.js @@ -1,13 +1,26 @@ /* - * L.Renderer is a base class for renderer implementations (SVG, Canvas); - * handles renderer container, bounds and zoom animation. + * 🍂class Renderer + * 🍂inherits Layer + * 🍂aka L.Renderer + * + * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the + * DOM container of the renderer, its bounds, and its zoom animation. + * + * A `Renderer` works as an implicit layer group for all `Path`s - the renderer + * itself can be added or removed to the map. All paths use a renderer, which can + * be implicit (the map will decide the type of renderer and use it automatically) + * or explicit (using the [`renderer`](#path-renderer) option of the path). + * + * Do not use this class directly, use `SVG` and `Canvas` instead. + * */ L.Renderer = L.Layer.extend({ options: { - // how much to extend the clip area around the map view (relative to its size) - // e.g. 0.1 would be 10% of map view in each direction; defaults to clip with the map view + // 🍂option padding: Number = 0.1 + // How much to extend the clip area around the map view (relative to its size) + // e.g. 0.1 would be 10% of map view in each direction padding: 0.1 }, @@ -90,11 +103,22 @@ L.Renderer = L.Layer.extend({ L.Map.include({ - // used by each vector layer to decide which renderer to use + // 🍂namespace Map; 🍂method getRenderer(layer: Path): Renderer + // Returns the instance of `Renderer` that should be used to render the given + // `Path`. It will ensure that the `renderer` options of the map and paths + // are respected, and that the renderers do exist on the map. getRenderer: function (layer) { + // 🍂namespace Map; 🍂option renderer: Renderer + // Use this specific instance of `Renderer` by default for new `Path`s added to the map + // 🍂namespace Path; 🍂option renderer: Renderer + // Use this specific instance of `Renderer` for this path. Takes + // precedence over the map's [default renderer](#map-renderer). var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer; if (!renderer) { + // 🍂namespace Map; 🍂option preferCanvas: Boolean = false + // Whether `Path`s should be rendered on a `Canvas` renderer. + // By default, all `Path`s are rendered in a `SVG` renderer. renderer = this._renderer = (this.options.preferCanvas && L.canvas()) || L.svg(); } diff --git a/src/layer/vector/SVG.VML.js b/src/layer/vector/SVG.VML.js index 50c72f4f7..87c97f77e 100644 --- a/src/layer/vector/SVG.VML.js +++ b/src/layer/vector/SVG.VML.js @@ -1,8 +1,18 @@ /* - * Vector rendering for IE7-8 through VML. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration! */ +/* + * 🍂class SVG + * + * Although SVG is not available on IE7 and IE8, these browsers support [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language), and the SVG renderer will fall back to VML in this case. + * + * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility + * with old versions of Internet Explorer. + */ + +// 🍂namespace Browser; 🍂property vml: Boolean +// `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language). L.Browser.vml = !L.Browser.svg && (function () { try { var div = document.createElement('div'); diff --git a/src/layer/vector/SVG.js b/src/layer/vector/SVG.js index 3adcb6651..82bd25a5e 100644 --- a/src/layer/vector/SVG.js +++ b/src/layer/vector/SVG.js @@ -1,5 +1,37 @@ /* - * L.SVG renders vector layers with SVG. All SVG-specific code goes here. + * 🍂class SVG + * 🍂inherits Renderer + * 🍂aka L.SVG + * + * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG). + * Inherits `Renderer`. + * + * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not + * available in all web browsers, notably Android 2.x and 3.x. + * + * Although SVG is not available on IE7 and IE8, these browsers support + * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language) + * (a now deprecated technology), and the SVG renderer will fall back to VML in + * this case. + * + * 🍂example + * + * Use SVG by default for all paths in the map: + * + * ```js + * var map = L.map('map', { + * renderer: L.svg(); + * }); + * ``` + * + * Use a SVG renderer with extra padding for specific vector geometries: + * + * ```js + * var map = L.map('map'); + * var myRenderer = L.svg({ padding: 0.5 }); + * var line = L.polyline( coordinates, { renderer: myRenderer } ); + * var circle = L.circle( center, { renderer: myRenderer } ); + * ``` */ L.SVG = L.Renderer.extend({ @@ -53,6 +85,9 @@ L.SVG = L.Renderer.extend({ _initPath: function (layer) { var path = layer._path = L.SVG.create('path'); + // 🍂namespace Path + // 🍂option className: string = null + // Custom class name set on an element. Only for SVG renderer. if (layer.options.className) { L.DomUtil.addClass(path, layer.options.className); } @@ -152,12 +187,20 @@ L.SVG = L.Renderer.extend({ }); +// 🍂namespace SVG; 🍂section +// There are several static functions which can be called without instantiating L.SVG: L.extend(L.SVG, { + // 🍂function create(name: String): SVGElement + // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement), + // corresponding to the class name passed. For example, using 'line' will return + // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement). create: function (name) { return document.createElementNS('http://www.w3.org/2000/svg', name); }, - // generates SVG path string for multiple rings, with each ring turning into "M..L..L.." instructions + // 🍂function pointsToPath(rings: [], closed: Boolean): String + // Generates a SVG path string for multiple rings, with each ring turning + // into "M..L..L.." instructions pointsToPath: function (rings, closed) { var str = '', i, j, len, len2, points, p; @@ -179,8 +222,14 @@ L.extend(L.SVG, { } }); +// 🍂namespace Browser; 🍂property svg: Boolean +// `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG). L.Browser.svg = !!(document.createElementNS && L.SVG.create('svg').createSVGRect); + +// 🍂namespace SVG +// 🍂factory L.svg(options?: SVG options) +// Creates a SVG renderer with the given options. L.svg = function (options) { return L.Browser.svg || L.Browser.vml ? new L.SVG(options) : null; }; diff --git a/src/map/Map.js b/src/map/Map.js index 55ec48ae7..8bc960fc2 100644 --- a/src/map/Map.js +++ b/src/map/Map.js @@ -1,25 +1,109 @@ /* - * L.Map is the central class of the API - it is used to create a map. + * 🍂class Map + * 🍂aka L.Map + * 🍂inherits Evented + * + * The central class of the API — it is used to create a map on a page and manipulate it. + * + * 🍂example + * + * ```js + * // 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 + * }); + * ``` + * */ L.Map = L.Evented.extend({ options: { + // 🍂section Map State Options + // 🍂option crs: CRS = L.CRS.EPSG3857 + // The [Coordinate Reference System](#crs) to use. Don't change this if you're not + // sure what it means. crs: L.CRS.EPSG3857, - /* - center: LatLng, - zoom: Number, - layers: Array, - */ + // 🍂option center: LatLng = undefined + // Initial geographic center of the map + center: undefined, + // 🍂option zoom: Number = undefined + // Initial map zoom level + zoom: undefined, + + // 🍂option minZoom: Number = undefined + // Minimum zoom level of the map. Overrides any `minZoom` option set on map layers. + minZoom: undefined, + + // 🍂option maxZoom: Number = undefined + // Maximum zoom level of the map. Overrides any `maxZoom` option set on map layers. + maxZoom: undefined, + + // 🍂option layers: Layer[] = [] + // Array of layers that will be added to the map initially + layers: [], + + // 🍂option maxBounds: LatLngBounds = null + // When this option is set, the map restricts the view to the given + // geographical bounds, bouncing the user back when he tries to pan + // outside the view. To set the restriction dynamically, use + // [`setMaxBounds`](#map-setmaxbounds) method. + maxBounds: undefined, + + // 🍂option renderer: Renderer = * + // The default method for drawing vector layers on the map. `L.SVG` + // or `L.Canvas` by default depending on browser support. + renderer: undefined, + + + // 🍂section Animation Options + // 🍂option fadeAnimation: Boolean = true + // Whether the tile fade animation is enabled. By default it's enabled + // in all browsers that support CSS3 Transitions except Android. fadeAnimation: true, - trackResize: true, + + // 🍂option markerZoomAnimation: Boolean = true + // Whether markers animate their zoom with the zoom animation, if disabled + // they will disappear for the length of the animation. By default it's + // enabled in all browsers that support CSS3 Transitions except Android. markerZoomAnimation: true, + + // 🍂option maxBoundsViscosity: Number = 0.0 + // If `maxBounds` is set, this options will control how solid the bounds + // are when dragging the map around. The default value of 0.0 allows the + // user to drag outside the bounds at normal speed, higher values will + // slow down map dragging outside bounds, and 1.0 makes the bounds fully + // solid, preventing the user from dragging outside the bounds. maxBoundsViscosity: 0.0, + + // 🍂option transform3DLimit: Number = 2^23 + // Defines the maximum size of a CSS translation transform. The default + // value should not be changed unless a web browser positions layers in + // the wrong place after doing a large `panBy`. transform3DLimit: 8388608, // Precision limit of a 32-bit float + + // 🍂section Interaction Options + // 🍂option zoomSnap: Number = 1 + // Forces the map's zoom level to always be a multiple of this, particularly + // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom. + // By default, the zoom level snaps to the nearest integer; lower values + // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0` + // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom. zoomSnap: 1, - zoomDelta: 1 + + // 🍂option zoomDelta: Number = 1 + // Controls how much the map's zoom level will change after a + // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+` + // or `-` on the keyboard, or using the [zoom controls](#control-zoom). + // Values smaller than `1` (e.g. `0.5`) allow for greater granularity. + zoomDelta: 1, + + // 🍂option trackResize: Boolean = true + // Whether the map automatically handles browser window resize to update itself. + trackResize: true }, initialize: function (id, options) { // (HTMLElement or String, Object) @@ -56,15 +140,20 @@ L.Map = L.Evented.extend({ }, - // public methods that modify map state + // 🍂section Methods for modifying map state - // replaced by animation-powered implementation in Map.PanAnimation.js + // 🍂method setView(center: LatLnt, zoom: Number, options?: Zoom/Pan options): this + // Sets the view of the map (geographical center and zoom) with the given + // animation options. setView: function (center, zoom) { + // replaced by animation-powered implementation in Map.PanAnimation.js zoom = zoom === undefined ? this.getZoom() : zoom; this._resetView(L.latLng(center), zoom); return this; }, + // 🍂method setZoom(zoom: Number, options: Zoom/Pan options): this + // Sets the zoom of the map. setZoom: function (zoom, options) { if (!this._loaded) { this._zoom = zoom; @@ -73,16 +162,26 @@ L.Map = L.Evented.extend({ return this.setView(this.getCenter(), zoom, {zoom: options}); }, + // 🍂method zoomIn(delta?: Number, options?: Zoom options): this + // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default). zoomIn: function (delta, options) { delta = delta || (L.Browser.any3d ? this.options.zoomDelta : 1); return this.setZoom(this._zoom + delta, options); }, + // 🍂method zoomOut(delta?: Number, options?: Zoom options): this + // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default). zoomOut: function (delta, options) { delta = delta || (L.Browser.any3d ? this.options.zoomDelta : 1); return this.setZoom(this._zoom - delta, options); }, + // 🍂method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this + // Zooms the map while keeping a specified geographical point on the map + // stationary (e.g. used internally for scroll zoom and double-click zoom). + // 🍂alternative + // 🍂method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this + // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary. setZoomAround: function (latlng, zoom, options) { var scale = this.getZoomScale(zoom), viewHalf = this.getSize().divideBy(2), @@ -118,6 +217,9 @@ L.Map = L.Evented.extend({ }; }, + // 🍂method fitBounds(bounds: LatLngBounds, options: fitBounds options): this + // Sets a map view that contains the given geographical bounds with the + // maximum zoom level possible. fitBounds: function (bounds, options) { if (!bounds.isValid()) { @@ -128,14 +230,21 @@ L.Map = L.Evented.extend({ return this.setView(target.center, target.zoom, options); }, + // 🍂method fitWorld(options?: fitBounds options): this + // Sets a map view that mostly contains the whole world with the maximum + // zoom level possible. fitWorld: function (options) { return this.fitBounds([[-90, -180], [90, 180]], options); }, + // 🍂method panTo(latlng: LatLng, options?: Pan options): this + // Pans the map to a given center. panTo: function (center, options) { // (LatLng) return this.setView(center, this._zoom, {pan: options}); }, + // 🍂method panBy(offset: Point): this + // Pans the map by a given number of pixels (animated). panBy: function (offset) { // (Point) // replaced with animated panBy in Map.PanAnimation.js this.fire('movestart'); @@ -146,6 +255,8 @@ L.Map = L.Evented.extend({ return this.fire('moveend'); }, + // 🍂method setMaxBounds(bounds: Bounds): this + // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option). setMaxBounds: function (bounds) { bounds = L.latLngBounds(bounds); @@ -164,6 +275,8 @@ L.Map = L.Evented.extend({ return this.on('moveend', this._panInsideMaxBounds); }, + // 🍂method setMinZoom(zoom: Number): this + // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option). setMinZoom: function (zoom) { this.options.minZoom = zoom; @@ -174,6 +287,8 @@ L.Map = L.Evented.extend({ return this; }, + // 🍂method setMaxZoom(zoom: Number): this + // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option). setMaxZoom: function (zoom) { this.options.maxZoom = zoom; @@ -184,6 +299,8 @@ L.Map = L.Evented.extend({ return this; }, + // 🍂method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this + // Pans 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. panInsideBounds: function (bounds, options) { this._enforcingBounds = true; var center = this.getCenter(), @@ -197,6 +314,19 @@ L.Map = L.Evented.extend({ return this; }, + // 🍂method invalidateSize(options: Zoom/Pan options): this + // Checks 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. + + // 🍂alternative + // 🍂method invalidateSize(animate: Boolean): this + // Checks 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: function (options) { if (!this._loaded) { return this; } @@ -234,18 +364,29 @@ L.Map = L.Evented.extend({ } } + // 🍂section Map state change events + // 🍂event resize: Event + // Fired when the map is resized. return this.fire('resize', { oldSize: oldSize, newSize: newSize }); }, + // 🍂section Methods for modifying map state + // 🍂method stop(): this + // Stops the currently running `panTo` or `flyTo` animation, if any. stop: function () { this.setZoom(this._limitZoom(this._zoom)); return this._stop(); }, + // TODO handler.addTo + // TODO Appropiate docs section? + // 🍂section Other Methods + // 🍂method addHandler(name: String, HandlerClass: Function): this + // Adds a new `Handler` to the map, given its name and constructor function. addHandler: function (name, HandlerClass) { if (!HandlerClass) { return this; } @@ -260,6 +401,8 @@ L.Map = L.Evented.extend({ return this; }, + // 🍂method remove(): this + // Destroys the map and clears all related event listeners. remove: function () { this._initEvents(true); @@ -280,6 +423,9 @@ L.Map = L.Evented.extend({ this._clearHandlers(); if (this._loaded) { + // 🍂section Map state change events + // 🍂event unload: Event + // Fired when the map is destroyed with [remove](#map-remove) method. this.fire('unload'); } @@ -290,6 +436,11 @@ L.Map = L.Evented.extend({ return this; }, + // 🍂section Other Methods + // 🍂method createPane(name, container?): HTMLElement + // Creates a new map pane with the given name if it doesn't exist already, + // then returns it. The pane is created as a children of `container`, or + // as a children of the main map pane if not set. createPane: function (name, container) { var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''), pane = L.DomUtil.create('div', className, container || this._mapPane); @@ -300,10 +451,11 @@ L.Map = L.Evented.extend({ return pane; }, + // 🍂section Methods for Getting Map State - // public methods for getting map state - - getCenter: function () { // (Boolean) -> LatLng + // 🍂method getCenter(): LatLng + // Returns the geographical center of the map view + getCenter: function () { this._checkIfLoaded(); if (this._lastCenter && !this._moved()) { @@ -312,10 +464,14 @@ L.Map = L.Evented.extend({ return this.layerPointToLatLng(this._getCenterLayerPoint()); }, + // 🍂method getZoom(): Number + // Returns the current zoom level of the map view getZoom: function () { return this._zoom; }, + // 🍂method getBounds(): LatLngBounds + // Returns the geographical bounds visible in the current map view getBounds: function () { var bounds = this.getPixelBounds(), sw = this.unproject(bounds.getBottomLeft()), @@ -324,16 +480,25 @@ L.Map = L.Evented.extend({ return new L.LatLngBounds(sw, ne); }, + // 🍂method getMinZoom(): Number + // Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default. getMinZoom: function () { return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom; }, + // 🍂method getMinZoom(): Number + // Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers). getMaxZoom: function () { return this.options.maxZoom === undefined ? (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) : this.options.maxZoom; }, + // 🍂method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean): Number + // Returns the maximum zoom level on which the given bounds fit to the map + // view in its entirety. If `inside` (optional) is set to `true`, the method + // instead returns the minimum zoom level on which the map view fits into + // the given bounds in its entirety. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number bounds = L.latLngBounds(bounds); padding = L.point(padding || [0, 0]); @@ -357,6 +522,8 @@ L.Map = L.Evented.extend({ return Math.max(min, Math.min(max, zoom)); }, + // 🍂method getSize(): Point + // Returns the current size of the map container (in pixels). getSize: function () { if (!this._size || this._sizeChanged) { this._size = new L.Point( @@ -368,102 +535,172 @@ L.Map = L.Evented.extend({ return this._size.clone(); }, + // 🍂method getPixelBounds(): Bounds + // Returns the bounds of the current map view in projected pixel + // coordinates (sometimes useful in layer and overlay implementations). getPixelBounds: function (center, zoom) { var topLeftPoint = this._getTopLeftPoint(center, zoom); return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize())); }, + // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to + // the map pane? "left point of the map layer" can be confusing, specially + // since there can be negative offsets. + // 🍂method getPixelOrigin(): Point + // Returns the projected pixel coordinates of the top left point of + // the map layer (useful in custom layer and overlay implementations). getPixelOrigin: function () { this._checkIfLoaded(); return this._pixelOrigin; }, + // 🍂method getPixelWorldBounds(zoom?): Bounds + // Returns the world's bounds in pixel coordinates for zoom level `zoom`. + // If `zoom` is omitted, the map's current zoom level is used. getPixelWorldBounds: function (zoom) { return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom); }, + // 🍂section Other Methods + + // 🍂method getPane(pane: String|HTMLElement): HTMLElement + // Returns a map pane, given its name or its HTML element (its identity). getPane: function (pane) { return typeof pane === 'string' ? this._panes[pane] : pane; }, + // 🍂method getPanes(): Object + // Returns a plain object containing the names of all panes as keys and + // the panes as values. getPanes: function () { return this._panes; }, + // 🍂method getContainer: HTMLElement + // Returns the HTML element that contains the map. getContainer: function () { return this._container; }, - // TODO replace with universal implementation after refactoring projections + // 🍂section Conversion Methods + // 🍂method getZoomScale(toZoom: Number, fromZoom: Number): Number + // Returns the scale factor to be applied to a map transition from zoom level + // `fromZoom` to `toZoom`. Used internally to help with zoom animations. getZoomScale: function (toZoom, fromZoom) { + // TODO replace with universal implementation after refactoring projections var crs = this.options.crs; fromZoom = fromZoom === undefined ? this._zoom : fromZoom; return crs.scale(toZoom) / crs.scale(fromZoom); }, + // 🍂method getScaleZoom(scale: Number, fromZoom: Number): Number + // Returns the zoom level that the map would end up at, if it is at `fromZoom` + // level and everything is scaled by a factor of `scale`. Inverse of + // [`getZoomScale`](#map-getZoomScale). getScaleZoom: function (scale, fromZoom) { var crs = this.options.crs; fromZoom = fromZoom === undefined ? this._zoom : fromZoom; return crs.zoom(scale * crs.scale(fromZoom)); }, - // conversion methods - - project: function (latlng, zoom) { // (LatLng[, Number]) -> Point + // 🍂method project(latlng: LatLng, zoom: Number): Point + // Projects a geographical coordinate `LatLng` according to the projection + // of the map's CRS, then scales it according to `zoom` and the CRS's + // `Transformation`. The result is pixel coordinate relative to + // the CRS origin. + project: function (latlng, zoom) { zoom = zoom === undefined ? this._zoom : zoom; return this.options.crs.latLngToPoint(L.latLng(latlng), zoom); }, - unproject: function (point, zoom) { // (Point[, Number]) -> LatLng + // 🍂method unproject(point: Point, zoom: Number): LatLng + // Inverse of [`project`](#map-project). + unproject: function (point, zoom) { zoom = zoom === undefined ? this._zoom : zoom; return this.options.crs.pointToLatLng(L.point(point), zoom); }, - layerPointToLatLng: function (point) { // (Point) + // 🍂method layerPointToLatLng(point: Point): LatLng + // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin), + // returns the corresponding geographical coordinate (for the current zoom level). + layerPointToLatLng: function (point) { var projectedPoint = L.point(point).add(this.getPixelOrigin()); return this.unproject(projectedPoint); }, - latLngToLayerPoint: function (latlng) { // (LatLng) + // 🍂method latLngToLayerPoint(latlng: LatLng): Point + // Given a geographical coordinate, returns the corresponding pixel coordinate + // relative to the [origin pixel](#map-getpixelorigin). + latLngToLayerPoint: function (latlng) { var projectedPoint = this.project(L.latLng(latlng))._round(); return projectedPoint._subtract(this.getPixelOrigin()); }, + // 🍂method wrapLatLng(latlng: LatLng): LatLng + // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the + // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the + // CRS's bounds. + // By default this means longitude is wrapped around the dateline so its + // value is between -180 and +180 degrees. wrapLatLng: function (latlng) { return this.options.crs.wrapLatLng(L.latLng(latlng)); }, + // 🍂method distance(latlng1: LatLng, latlng2: LatLng): Number + // Returns the distance between two geographical coordinates according to + // the map's CRS. By default this measures distance in meters. distance: function (latlng1, latlng2) { return this.options.crs.distance(L.latLng(latlng1), L.latLng(latlng2)); }, + // 🍂method containerPointToLayerPoint(point: Point): Point + // Given a pixel coordinate relative to the map container, returns the corresponding + // pixel coordinate relative to the [origin pixel](#map-getpixelorigin). containerPointToLayerPoint: function (point) { // (Point) return L.point(point).subtract(this._getMapPanePos()); }, + // 🍂method layerPointToContainerPoint(point: Point): Point + // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin), + // returns the corresponding pixel coordinate relative to the map container. layerPointToContainerPoint: function (point) { // (Point) return L.point(point).add(this._getMapPanePos()); }, + // 🍂method containerPointToLatLng(point: Point): Point + // Given a pixel coordinate relative to the map container, returns + // the corresponding geographical coordinate (for the current zoom level). containerPointToLatLng: function (point) { var layerPoint = this.containerPointToLayerPoint(L.point(point)); return this.layerPointToLatLng(layerPoint); }, + // 🍂method latLngToContainerPoint(latlng: LatLng): Point + // Given a geographical coordinate, returns the corresponding pixel coordinate + // relative to the map container. latLngToContainerPoint: function (latlng) { return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng))); }, - mouseEventToContainerPoint: function (e) { // (MouseEvent) + // 🍂method mouseEventToContainerPoint(ev: MouseEvent): Point + // Given a MouseEvent object, returns the pixel coordinate relative to the + // map container where the event took place. + mouseEventToContainerPoint: function (e) { return L.DomEvent.getMousePosition(e, this._container); }, - mouseEventToLayerPoint: function (e) { // (MouseEvent) + // 🍂method mouseEventToLayerPoint(ev: MouseEvent): Point + // Given a MouseEvent object, returns the pixel coordinate relative to + // the [origin pixel](#map-getpixelorigin) where the event took place. + mouseEventToLayerPoint: function (e) { return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e)); }, + // 🍂method mouseEventToLatLng(ev: MouseEvent): LatLng + // Given a MouseEvent object, returns geographical coordinate where the + // event took place. mouseEventToLatLng: function (e) { // (MouseEvent) return this.layerPointToLatLng(this.mouseEventToLayerPoint(e)); }, @@ -513,13 +750,35 @@ L.Map = L.Evented.extend({ var panes = this._panes = {}; this._paneRenderers = {}; + // 🍂section + // + // Panes are DOM elements used to control the ordering of layers on the map. You + // can access panes with [`map.getPane`](#map-getpane) or + // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the + // [`map.createPane`](#map-createpane) method. + // + // Every map has the following default panes that differ only in zIndex. + // + // 🍂pane mapPane: HTMLElement = 'auto' + // Pane that contains all other map panes + this._mapPane = this.createPane('mapPane', this._container); L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0)); + // 🍂pane tilePane: HTMLElement = 2 + // Pane for tile layers this.createPane('tilePane'); + // 🍂pane overlayPane: HTMLElement = 4 + // Pane for overlays like polylines and polygons this.createPane('shadowPane'); + // 🍂pane shadowPane: HTMLElement = 5 + // Pane for overlay shadows (e.g. marker shadows) this.createPane('overlayPane'); + // 🍂pane markerPane: HTMLElement = 6 + // Pane for marker icons this.createPane('markerPane'); + // 🍂pane popupPane: HTMLElement = 7 + // Pane for popups. this.createPane('popupPane'); if (!this.options.markerZoomAnimation) { @@ -531,6 +790,7 @@ L.Map = L.Evented.extend({ // private methods that modify map state + // 🍂section Map state change events _resetView: function (center, zoom) { L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0)); @@ -546,14 +806,24 @@ L.Map = L.Evented.extend({ ._move(center, zoom) ._moveEnd(zoomChanged); + // 🍂event 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. this.fire('viewreset'); + // 🍂event load: Event + // Fired when the map is initialized (when its center and zoom are set + // for the first time). if (loading) { this.fire('load'); } }, _moveStart: function (zoomChanged) { + // 🍂event zoomstart: Event + // Fired when the map zoom is about to change (e.g. before zoom animation). + // 🍂event movestart: Event + // Fired when the view of the map starts changing (e.g. user starts dragging the map). if (zoomChanged) { this.fire('zoomstart'); } @@ -570,16 +840,29 @@ L.Map = L.Evented.extend({ this._lastCenter = center; this._pixelOrigin = this._getNewPixelOrigin(center); + // 🍂event zoom: Event + // Fired repeteadly during any change in zoom level, including zoom + // and fly animations. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530 this.fire('zoom', data); } + + // 🍂event move: Event + // Fired repeteadly during any movement of the map, including pan and + // fly animations. return this.fire('move', data); }, _moveEnd: function (zoomChanged) { + // 🍂event zoomend: Event + // Fired when the map has changed, after any animations. if (zoomChanged) { this.fire('zoomend'); } + + // 🍂event moveend: Event + // Fired when the center of the map stops changing (e.g. user stopped + // dragging the map). return this.fire('moveend'); }, @@ -613,6 +896,7 @@ L.Map = L.Evented.extend({ // DOM event handling + // 🍂section Interaction events _initEvents: function (remove) { if (!L.DomEvent) { return; } @@ -621,6 +905,27 @@ L.Map = L.Evented.extend({ var onOff = remove ? 'off' : 'on'; + // 🍂event click: MouseEvent + // Fired when the user clicks (or taps) the map. + // 🍂event dblclick: MouseEvent + // Fired when the user double-clicks (or double-taps) the map. + // 🍂event mousedown: MouseEvent + // Fired when the user pushes the mouse button on the map. + // 🍂event mouseup: MouseEvent + // Fired when the user releases the mouse button on the map. + // 🍂event mouseover: MouseEvent + // Fired when the mouse enters the map. + // 🍂event mouseout: MouseEvent + // Fired when the mouse leaves the map. + // 🍂event mousemove: MouseEvent + // Fired while the mouse moves over the map. + // 🍂event contextmenu: MouseEvent + // Fired 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). + // 🍂event keypress: Event + // Fired when the user presses a key from the keyboard while the map is focused. L.DomEvent[onOff](this._container, 'click dblclick mousedown mouseup ' + 'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this); @@ -688,6 +993,10 @@ L.Map = L.Evented.extend({ if (e.type === 'click') { // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups). + // 🍂event preclick: MouseEvent + // Fired before mouse click on the map (sometimes useful when you + // want something to happen on click before any existing click + // handlers start running). var synth = L.Util.extend({}, e); synth.type = 'preclick'; this._handleDOMEvent(synth); @@ -745,6 +1054,12 @@ L.Map = L.Evented.extend({ } }, + // 🍂section Other Methods + + // 🍂method whenReady(fn: Function, context?: Object): this + // Runs the given function `fn` when the map gets initialized with + // a view (center and zoom) and at least one layer, or immediately + // if it's already initialized, optionally passing a function context. whenReady: function (callback, context) { if (this._loaded) { callback.call(context || this, {target: this}); @@ -855,6 +1170,19 @@ L.Map = L.Evented.extend({ } }); +// 🍂section + +// 🍂factory L.map(id: String, options?: Map options) +// Instantiates a map object given the DOM ID of a `
` element +// and optionally an object literal with `Map options`. +// +// 🍂alternative +// 🍂factory L.map(el: HTMLElement, options?: Map options) +// Instantiates a map object given an instance of a `
` HTML element +// and optionally an object literal with `Map options`. L.map = function (id, options) { return new L.Map(id, options); }; + + + diff --git a/src/map/Map.methodOptions.leafdoc b/src/map/Map.methodOptions.leafdoc new file mode 100644 index 000000000..3aead8e68 --- /dev/null +++ b/src/map/Map.methodOptions.leafdoc @@ -0,0 +1,108 @@ + +This file documents the common options passed to several map methods. + + +🍂miniclass Locate options (Map) +🍂aka locate options +🍂section + +Some of the geolocation methods for `Map` take in an `options` parameter. This +is a plain javascript object with the following optional components: + +🍂option watch: Boolean = false +If `true`, starts continous watching of location changes (instead of detecting it +once) using W3C `watchPosition` method. You can later stop watching using +`map.stopLocate()` method. + + +🍂option setView: Boolean = false +If `true`, automatically sets the map view to the user location with respect to +detection accuracy, or to world view if geolocation failed. + +🍂option maxZoom: Number = Infinity +The maximum zoom for automatic view setting when using `setView` option. + +🍂option timeout: Number = 10000 +Number of milliseconds to wait for a response from geolocation before firing a +`locationerror` event. + +🍂option maximumAge: Number = 0 +Maximum age of detected location. If less than this amount of milliseconds +passed since last geolocation response, `locate` will return a cached location. + +🍂option enableHighAccuracy: Boolean = false +Enables high accuracy, see [description in the W3C spec](http://dev.w3.org/geo/api/spec-source.html#high-accuracy). + + + +🍂miniclass Zoom options (Map) +🍂aka zoom options +🍂section + +Some of the `Map` methods which modify the zoom level take in an `options` +parameter. This is a plain javascript object with the following optional +components: + + +🍂option animate: Boolean +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. + + + + +🍂miniclass Pan options (Map) +🍂aka pan options +🍂section + +Some of the `Map` methods which modify the center of the map take in an `options` +parameter. This is a plain javascript object with the following optional +components: + +🍂option animate: Boolean +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). + +🍂option duration: Number = 0.25 +Duration of animated panning, in seconds. + +🍂option easeLinearity: Number = 0.25 +The curvature factor of panning animation easing (third parameter of the +[Cubic Bezier curve](http://cubic-bezier.com/)). 1.0 means linear animation, +the less the more bowed the curve. + +🍂option noMoveStart: Boolean = false +If `true`, panning won't fire `movestart` event on start (used internally for +panning inertia). + + +🍂miniclass Zoom/pan options (Map) +🍂aka zoom/pan options +🍂inherits Zoom options +🍂inherits Pan options + + +🍂miniclass FitBounds options (Map) +🍂aka fitBounds options +🍂inherits Zoom/pan options + +🍂option paddingTopLeft: Point = [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. + +🍂option paddingBottomRight: Point = [0, 0] +The same for the bottom right corner of the map. + +🍂option padding: Point = [0, 0] +Equivalent of setting both top left and bottom right padding to the same value. + +🍂option maxZoom: Number = null +The maximum possible zoom to use. + + diff --git a/src/map/anim/Map.FlyTo.js b/src/map/anim/Map.FlyTo.js index a0077d1fc..2a1f8cec4 100644 --- a/src/map/anim/Map.FlyTo.js +++ b/src/map/anim/Map.FlyTo.js @@ -1,5 +1,10 @@ - +// 🍂namespace Map +// 🍂section Methods for modifying map state L.Map.include({ + + // 🍂method flyTo(latlng: LatLng, zoom?: Number, options? Zoom/Pan options): this + // Sets the view of the map (geographical center and zoom) performing a smooth + // pan-zoom animation. flyTo: function (targetCenter, targetZoom, options) { options = options || {}; @@ -68,6 +73,9 @@ L.Map.include({ return this; }, + // 🍂method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this + // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto), + // but takes a bounds parameter like [`fitBounds`](#map-fitbounds). flyToBounds: function (bounds, options) { var target = this._getBoundsCenterZoom(bounds, options); return this.flyTo(target.center, target.zoom, options); diff --git a/src/map/anim/Map.ZoomAnimation.js b/src/map/anim/Map.ZoomAnimation.js index e707eb72c..672abecc1 100644 --- a/src/map/anim/Map.ZoomAnimation.js +++ b/src/map/anim/Map.ZoomAnimation.js @@ -2,8 +2,16 @@ * Extends L.Map to handle zoom animations. */ +// 🍂namespace Map +// 🍂section Animation Options L.Map.mergeOptions({ + // 🍂option zoomAnimation: Boolean = true + // Whether the map zoom animation is enabled. By default it's enabled + // in all browsers that support CSS3 Transitions except Android. zoomAnimation: true, + + // 🍂option zoomAnimationThreshold: Number = 4 + // Won't animate zoom if the zoom difference exceeds this value. zoomAnimationThreshold: 4 }); diff --git a/src/map/ext/Map.Geolocation.js b/src/map/ext/Map.Geolocation.js index 34834fb2a..6c2350593 100644 --- a/src/map/ext/Map.Geolocation.js +++ b/src/map/ext/Map.Geolocation.js @@ -2,7 +2,10 @@ * Provides L.Map with convenient shortcuts for using browser geolocation features. */ +// 🍂namespace Map + L.Map.include({ + // 🍂section Geolocation methods _defaultLocateOptions: { timeout: 10000, watch: false @@ -12,6 +15,12 @@ L.Map.include({ // enableHighAccuracy: false }, + // 🍂method locate(options?: Locate options): this + // Tries 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. locate: function (options) { options = this._locateOptions = L.extend({}, this._defaultLocateOptions, options); @@ -36,6 +45,10 @@ L.Map.include({ return this; }, + // 🍂method stopLocate(): this + // Stops watching location previously initiated by `map.locate({watch: true})` + // and aborts resetting the map view if map.locate was called with + // `{setView: true}`. stopLocate: function () { if (navigator.geolocation && navigator.geolocation.clearWatch) { navigator.geolocation.clearWatch(this._locationWatchId); @@ -56,6 +69,9 @@ L.Map.include({ this.fitWorld(); } + // 🍂section Location events + // 🍂event locationerror: ErrorEvent + // Fired when geolocation (using the [`locate`](#map-locate) method) failed. this.fire('locationerror', { code: c, message: 'Geolocation error: ' + message + '.' @@ -86,6 +102,9 @@ L.Map.include({ } } + // 🍂event locationfound: LocationEvent + // Fired when geolocation (using the [`locate`](#map-locate) method) + // went successfully. this.fire('locationfound', data); } }); diff --git a/src/map/handler/Map.BoxZoom.js b/src/map/handler/Map.BoxZoom.js index a0d5f06f9..f2a4fc0e4 100644 --- a/src/map/handler/Map.BoxZoom.js +++ b/src/map/handler/Map.BoxZoom.js @@ -1,9 +1,14 @@ /* - * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map - * (zoom to a selected bounding box), enabled by default. + * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map + * (zoom to a selected bounding box), enabled by default. */ +// 🍂namespace Map +// 🍂section Interaction Options L.Map.mergeOptions({ + // 🍂option boxZoom: Boolean = true + // Whether the map can be zoomed to a rectangular area specified by + // dragging the mouse while pressing the shift key. boxZoom: true }); @@ -112,4 +117,7 @@ L.Map.BoxZoom = L.Handler.extend({ } }); +// 🍂section Handlers +// 🍂property boxZoom: Handler +// Box (shift-drag with mouse) zoom handler. L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom); diff --git a/src/map/handler/Map.DoubleClickZoom.js b/src/map/handler/Map.DoubleClickZoom.js index 1af4baae2..e12d03601 100644 --- a/src/map/handler/Map.DoubleClickZoom.js +++ b/src/map/handler/Map.DoubleClickZoom.js @@ -2,7 +2,15 @@ * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default. */ +// 🍂namespace Map +// 🍂section Interaction Options + L.Map.mergeOptions({ + // 🍂option doubleClickZoom: Boolean = true + // Whether 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. doubleClickZoom: true }); @@ -29,4 +37,16 @@ L.Map.DoubleClickZoom = L.Handler.extend({ } }); +// 🍂section Handlers +// +// 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 `Handler` methods). For example: +// +// ```js +// map.doubleClickZoom.disable(); +// ``` +// +// 🍂property doubleClickZoom: Handler +// Double click zoom handler. L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom); diff --git a/src/map/handler/Map.Drag.js b/src/map/handler/Map.Drag.js index 346775d7b..716448178 100644 --- a/src/map/handler/Map.Drag.js +++ b/src/map/handler/Map.Drag.js @@ -2,16 +2,47 @@ * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default. */ +// 🍂namespace Map +// 🍂section Interaction Options L.Map.mergeOptions({ + // 🍂option dragging: Boolean = true + // Whether the map be draggable with mouse/touch or not. dragging: true, + // 🍂section Panning Inertia Options + // 🍂option inertia: Boolean = * + // If 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. Enabled by default unless running on old Android devices. inertia: !L.Browser.android23, + + // 🍂option inertiaDeceleration: Number = 3000 + // The rate with which the inertial movement slows down, in pixels/second². inertiaDeceleration: 3400, // px/s^2 + + // 🍂option inertiaMaxSpeed: Number = Infinity + // Max speed of the inertial movement, in pixels/second. inertiaMaxSpeed: Infinity, // px/s + + // 🍂option easeLinearity: Number = 0.2 easeLinearity: 0.2, // TODO refactor, move to CRS - worldCopyJump: false + // 🍂option worldCopyJump: Boolean = false + // With 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. + worldCopyJump: false, + + // 🍂section Interaction Options + // 🍂option maxBoundsViscosity: Number = 0.0 + // If `maxBounds` is set, this option will control how solid the bounds + // are when dragging the map around. The default value of `0.0` allows the + // user to drag outside the bounds at normal speed, higher values will + // slow down map dragging outside bounds, and `1.0` makes the bounds fully + // solid, preventing the user from dragging outside the bounds. + maxBoundsViscosity: 0.0 }); L.Map.Drag = L.Handler.extend({ @@ -189,4 +220,7 @@ L.Map.Drag = L.Handler.extend({ } }); +// 🍂section Handlers +// 🍂property dragging: Handler +// Map dragging handler (by both mouse and touch). L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag); diff --git a/src/map/handler/Map.Keyboard.js b/src/map/handler/Map.Keyboard.js index d82a152eb..3f58884e3 100644 --- a/src/map/handler/Map.Keyboard.js +++ b/src/map/handler/Map.Keyboard.js @@ -2,8 +2,16 @@ * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default. */ +// 🍂namespace Map +// 🍂section Keyboard Navigation Options L.Map.mergeOptions({ + // 🍂option keyboard: Boolean = true + // Makes the map focusable and allows users to navigate the map with keyboard + // arrows and `+`/`-` keys. keyboard: true, + + // 🍂option keyboardPanDelta: Number = 80 + // Amount of pixels to pan when pressing an arrow key. keyboardPanDelta: 80 }); @@ -159,4 +167,8 @@ L.Map.Keyboard = L.Handler.extend({ } }); +// 🍂section Handlers +// 🍂section Handlers +// 🍂property keyboard: Handler +// Keyboard navigation handler. L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard); diff --git a/src/map/handler/Map.ScrollWheelZoom.js b/src/map/handler/Map.ScrollWheelZoom.js index b216bc12e..14039bcb4 100644 --- a/src/map/handler/Map.ScrollWheelZoom.js +++ b/src/map/handler/Map.ScrollWheelZoom.js @@ -2,9 +2,24 @@ * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map. */ +// 🍂namespace Map +// 🍂section Interaction Options L.Map.mergeOptions({ + // 🍂section Mousewheel options + // 🍂option scrollWheelZoom: Boolean = true + // Whether 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. scrollWheelZoom: true, + + // 🍂option wheelDebounceTime: Number = 40 + // Limits the rate at which a wheel can fire (in milliseconds). By default + // user can't zoom via wheel more often than once per 40 ms. wheelDebounceTime: 40, + + // 🍂option wheelPxPerZoomLevel: Number = 50 + // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta)) + // mean a change of one full zoom level. Smaller values will make wheel-zooming + // faster (and vice versa). wheelPxPerZoomLevel: 50 }); @@ -65,4 +80,7 @@ L.Map.ScrollWheelZoom = L.Handler.extend({ } }); +// 🍂section Handlers +// 🍂property scrollWheelZoom: Handler +// Scroll wheel zoom handler. L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom); diff --git a/src/map/handler/Map.Tap.js b/src/map/handler/Map.Tap.js index 8fac893c6..e7f1502dd 100644 --- a/src/map/handler/Map.Tap.js +++ b/src/map/handler/Map.Tap.js @@ -2,8 +2,18 @@ * L.Map.Tap is used to enable mobile hacks like quick taps and long hold. */ +// 🍂namespace Map +// 🍂section Interaction Options L.Map.mergeOptions({ + // 🍂section Touch interaction options + // 🍂option tap: Boolean = true + // Enables mobile hacks for supporting instant taps (fixing 200ms click + // delay on iOS/Android) and touch holds (fired as `contextmenu` events). tap: true, + + // 🍂option tapTolerance: Number = 15 + // The max number of pixels a user can shift his finger during touch + // for it to be considered a valid tap. tapTolerance: 15 }); @@ -109,6 +119,9 @@ L.Map.Tap = L.Handler.extend({ } }); +// 🍂section Handlers +// 🍂property tap: Handler +// Mobile touch hacks (quick tap and touch hold) handler. if (L.Browser.touch && !L.Browser.pointer) { L.Map.addInitHook('addHandler', 'tap', L.Map.Tap); } diff --git a/src/map/handler/Map.TouchZoom.js b/src/map/handler/Map.TouchZoom.js index edefa9b9a..488742ffb 100644 --- a/src/map/handler/Map.TouchZoom.js +++ b/src/map/handler/Map.TouchZoom.js @@ -2,8 +2,20 @@ * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers. */ +// 🍂namespace Map +// 🍂section Interaction Options L.Map.mergeOptions({ + // 🍂section Touch interaction options + // 🍂option touchZoom: Boolean = * + // Whether the map can be zoomed by touch-dragging with two fingers. If + // passed `'center'`, it will zoom to the center of the view regardless of + // where the touch events (fingers) were. Enabled for touch-capable web + // browsers except for old Androids. touchZoom: L.Browser.touch && !L.Browser.android23, + + // 🍂option bounceAtZoomLimits: Boolean = true + // Set it to false if you don't want the map to zoom beyond min/max zoom + // and then bounce back when pinch-zooming. bounceAtZoomLimits: true }); @@ -106,4 +118,7 @@ L.Map.TouchZoom = L.Handler.extend({ } }); +// 🍂section Handlers +// 🍂property touchZoom: Handler +// Touch zoom handler. L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);