Update leaflet to 1.0.0
authorTom Hughes <tom@compton.nu>
Tue, 27 Sep 2016 17:14:32 +0000 (18:14 +0100)
committerTom Hughes <tom@compton.nu>
Thu, 29 Sep 2016 07:29:51 +0000 (08:29 +0100)
Vendorfile
app/assets/javascripts/leaflet.map.js
vendor/assets/leaflet/images/layers-2x.png
vendor/assets/leaflet/images/layers.png
vendor/assets/leaflet/images/marker-icon-2x.png
vendor/assets/leaflet/images/marker-icon.png
vendor/assets/leaflet/images/marker-shadow.png
vendor/assets/leaflet/leaflet.css
vendor/assets/leaflet/leaflet.js
vendor/assets/leaflet/leaflet.locate.js
vendor/assets/leaflet/leaflet.polyline.js

index 30ccee4..75dfe32 100644 (file)
@@ -11,13 +11,13 @@ folder 'vendor/assets' do
   end
 
   folder 'leaflet' do
-    file 'leaflet.js', 'http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet-src.js'
-    file 'leaflet.css', 'http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css'
+    file 'leaflet.js', 'https://unpkg.com/leaflet@1.0.0/dist/leaflet-src.js'
+    file 'leaflet.css', 'https://unpkg.com/leaflet@1.0.0/dist/leaflet.css'
 
     [ 'layers.png', 'layers-2x.png',
       'marker-icon.png', 'marker-icon-2x.png',
       'marker-shadow.png' ].each do |image|
-      file "images/#{image}", "http://cdn.leafletjs.com/leaflet/v0.7.7/images/#{image}"
+      file "images/#{image}", "https://unpkg.com/leaflet@1.0.0/dist/images/#{image}"
     end
 
     from 'git://github.com/kajic/leaflet-locationfilter.git' do
@@ -26,7 +26,7 @@ folder 'vendor/assets' do
       folder 'img', 'src/img'
     end
 
-    from 'git://github.com/domoritz/leaflet-locatecontrol.git' do
+    from 'git://github.com/domoritz/leaflet-locatecontrol.git', :tag => 'v0.54.0' do
       file 'leaflet.locate.js', 'src/L.Control.Locate.js'
     end
 
@@ -34,7 +34,7 @@ folder 'vendor/assets' do
       file 'leaflet.osm.js', 'leaflet-osm.js'
     end
 
-    from 'git://github.com/jieter/Leaflet.encoded.git' do
+    from 'git://github.com/jieter/Leaflet.encoded.git', :tag => '0.0.8' do
       file 'leaflet.polyline.js', 'Polyline.encoded.js'
     end
   end
index 3af81f7..4f3c7bc 100644 (file)
@@ -277,7 +277,7 @@ L.OSM.Map = L.Map.extend({
   }
 });
 
-L.Icon.Default.imagePath = "/images";
+L.Icon.Default.imagePath = "/images/";
 
 L.Icon.Default.imageUrls = {
   "/images/marker-icon.png": OSM.MARKER_ICON,
index a2cf7f9..200c333 100644 (file)
Binary files a/vendor/assets/leaflet/images/layers-2x.png and b/vendor/assets/leaflet/images/layers-2x.png differ
index bca0a0e..1a72e57 100644 (file)
Binary files a/vendor/assets/leaflet/images/layers.png and b/vendor/assets/leaflet/images/layers.png differ
index 0015b64..e4abba3 100644 (file)
Binary files a/vendor/assets/leaflet/images/marker-icon-2x.png and b/vendor/assets/leaflet/images/marker-icon-2x.png differ
index e2e9f75..950edf2 100644 (file)
Binary files a/vendor/assets/leaflet/images/marker-icon.png and b/vendor/assets/leaflet/images/marker-icon.png differ
index d1e773c..9fd2979 100644 (file)
Binary files a/vendor/assets/leaflet/images/marker-shadow.png and b/vendor/assets/leaflet/images/marker-shadow.png differ
index dea175f..6e0789c 100644 (file)
@@ -1,16 +1,12 @@
 /* required styles */
 
-.leaflet-map-pane,
+.leaflet-pane,
 .leaflet-tile,
 .leaflet-marker-icon,
 .leaflet-marker-shadow,
-.leaflet-tile-pane,
 .leaflet-tile-container,
-.leaflet-overlay-pane,
-.leaflet-shadow-pane,
-.leaflet-marker-pane,
-.leaflet-popup-pane,
-.leaflet-overlay-pane svg,
+.leaflet-map-pane svg,
+.leaflet-map-pane canvas,
 .leaflet-zoom-box,
 .leaflet-image-layer,
 .leaflet-layer {
@@ -20,8 +16,6 @@
        }
 .leaflet-container {
        overflow: hidden;
-       -ms-touch-action: none;
-       touch-action: none;
        }
 .leaflet-tile,
 .leaflet-marker-icon,
        -webkit-user-select: none;
           -moz-user-select: none;
                user-select: none;
-       -webkit-user-drag: none;
+         -webkit-user-drag: none;
+       }
+/* Safari renders non-retina tile on retina better with this, but Chrome is worse */
+.leaflet-safari .leaflet-tile {
+       image-rendering: -webkit-optimize-contrast;
+       }
+/* hack that prevents hw layers "stretching" when loading new tiles */
+.leaflet-safari .leaflet-tile-container {
+       width: 1600px;
+       height: 1600px;
+       -webkit-transform-origin: 0 0;
        }
 .leaflet-marker-icon,
 .leaflet-marker-shadow {
        display: block;
        }
-/* map is broken in FF if you have max-width: 100% on tiles */
-.leaflet-container img {
+/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */
+/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */
+.leaflet-container .leaflet-overlay-pane svg,
+.leaflet-container .leaflet-marker-pane img,
+.leaflet-container .leaflet-tile-pane img,
+.leaflet-container img.leaflet-image-layer {
        max-width: none !important;
        }
-/* stupid Android 2 doesn't understand "max-width: none" properly */
-.leaflet-container img.leaflet-image-layer {
-       max-width: 15000px !important;
+
+.leaflet-container.leaflet-touch-zoom {
+       -ms-touch-action: pan-x pan-y;
+       touch-action: pan-x pan-y;
        }
+.leaflet-container.leaflet-touch-drag {
+       -ms-touch-action: pinch-zoom;
+       }
+.leaflet-container.leaflet-touch-drag.leaflet-touch-drag {
+       -ms-touch-action: none;
+       touch-action: none;
+}
 .leaflet-tile {
        filter: inherit;
        visibility: hidden;
 .leaflet-zoom-box {
        width: 0;
        height: 0;
+       -moz-box-sizing: border-box;
+            box-sizing: border-box;
+       z-index: 800;
        }
 /* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
 .leaflet-overlay-pane svg {
        -moz-user-select: none;
        }
 
-.leaflet-tile-pane    { z-index: 2; }
-.leaflet-objects-pane { z-index: 3; }
-.leaflet-overlay-pane { z-index: 4; }
-.leaflet-shadow-pane  { z-index: 5; }
-.leaflet-marker-pane  { z-index: 6; }
-.leaflet-popup-pane   { z-index: 7; }
+.leaflet-pane         { z-index: 400; }
+
+.leaflet-tile-pane    { z-index: 200; }
+.leaflet-overlay-pane { z-index: 400; }
+.leaflet-shadow-pane  { z-index: 500; }
+.leaflet-marker-pane  { z-index: 600; }
+.leaflet-tooltip-pane   { z-index: 650; }
+.leaflet-popup-pane   { z-index: 700; }
+
+.leaflet-map-pane canvas { z-index: 100; }
+.leaflet-map-pane svg    { z-index: 200; }
 
 .leaflet-vml-shape {
        width: 1px;
 
 .leaflet-control {
        position: relative;
-       z-index: 7;
+       z-index: 800;
+       pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
        pointer-events: auto;
        }
 .leaflet-top,
 
 /* zoom and fade animations */
 
-.leaflet-fade-anim .leaflet-tile,
+.leaflet-fade-anim .leaflet-tile {
+       will-change: opacity;
+       }
 .leaflet-fade-anim .leaflet-popup {
        opacity: 0;
        -webkit-transition: opacity 0.2s linear;
             -o-transition: opacity 0.2s linear;
                transition: opacity 0.2s linear;
        }
-.leaflet-fade-anim .leaflet-tile-loaded,
 .leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
        opacity: 1;
        }
-
+.leaflet-zoom-animated {
+       -webkit-transform-origin: 0 0;
+           -ms-transform-origin: 0 0;
+               transform-origin: 0 0;
+       }
+.leaflet-zoom-anim .leaflet-zoom-animated {
+       will-change: transform;
+       }
 .leaflet-zoom-anim .leaflet-zoom-animated {
        -webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
           -moz-transition:    -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
                transition:         transform 0.25s cubic-bezier(0,0,0.25,1);
        }
 .leaflet-zoom-anim .leaflet-tile,
-.leaflet-pan-anim .leaflet-tile,
-.leaflet-touching .leaflet-zoom-animated {
+.leaflet-pan-anim .leaflet-tile {
        -webkit-transition: none;
           -moz-transition: none;
             -o-transition: none;
 
 /* cursors */
 
-.leaflet-clickable {
+.leaflet-interactive {
        cursor: pointer;
        }
-.leaflet-container {
+.leaflet-grab {
        cursor: -webkit-grab;
        cursor:    -moz-grab;
        }
+.leaflet-crosshair,
+.leaflet-crosshair .leaflet-interactive {
+       cursor: crosshair;
+       }
 .leaflet-popup-pane,
 .leaflet-control {
        cursor: auto;
        }
-.leaflet-dragging .leaflet-container,
-.leaflet-dragging .leaflet-clickable {
+.leaflet-dragging .leaflet-grab,
+.leaflet-dragging .leaflet-grab .leaflet-interactive,
+.leaflet-dragging .leaflet-marker-draggable {
        cursor: move;
        cursor: -webkit-grabbing;
        cursor:    -moz-grabbing;
        }
 
+/* marker & overlays interactivity */
+.leaflet-marker-icon,
+.leaflet-marker-shadow,
+.leaflet-image-layer,
+.leaflet-pane > svg path,
+.leaflet-tile-container {
+       pointer-events: none;
+       }
+
+.leaflet-marker-icon.leaflet-interactive,
+.leaflet-image-layer.leaflet-interactive,
+.leaflet-pane > svg path.leaflet-interactive {
+       pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
+       pointer-events: auto;
+       }
 
 /* visual tweaks */
 
        color: #333;
        background: #fff;
        }
+.leaflet-control-layers-scrollbar {
+       overflow-y: scroll;
+       padding-right: 5px;
+       }
 .leaflet-control-layers-selector {
        margin-top: 2px;
        position: relative;
        margin: 5px -10px 5px -6px;
        }
 
+/* Default icon URLs */
+.leaflet-default-icon-path {
+       background-image: url(images/);
+       }
+
 
 /* attribution and scale controls */
 
        font-size: 11px;
        white-space: nowrap;
        overflow: hidden;
-       -moz-box-sizing: content-box;
-            box-sizing: content-box;
+       -moz-box-sizing: border-box;
+            box-sizing: border-box;
 
        background: #fff;
        background: rgba(255, 255, 255, 0.5);
 .leaflet-popup {
        position: absolute;
        text-align: center;
+       margin-bottom: 20px;
        }
 .leaflet-popup-content-wrapper {
        padding: 1px;
        margin: 18px 0;
        }
 .leaflet-popup-tip-container {
-       margin: 0 auto;
        width: 40px;
        height: 20px;
-       position: relative;
+       position: absolute;
+       left: 50%;
+       margin-left: -20px;
        overflow: hidden;
+       pointer-events: none;
        }
 .leaflet-popup-tip {
        width: 17px;
 .leaflet-popup-content-wrapper,
 .leaflet-popup-tip {
        background: white;
-
+       color: #333;
        box-shadow: 0 3px 14px rgba(0,0,0,0.4);
        }
 .leaflet-container a.leaflet-popup-close-button {
        top: 0;
        right: 0;
        padding: 4px 4px 0 0;
+       border: none;
        text-align: center;
        width: 18px;
        height: 14px;
        background: #fff;
        border: 1px solid #666;
        }
+
+
+/* Tooltip */
+/* Base styles for the element that has a tooltip */
+.leaflet-tooltip {
+       position: absolute;
+       padding: 6px;
+       background-color: #fff;
+       border: 1px solid #fff;
+       border-radius: 3px;
+       color: #222;
+       white-space: nowrap;
+       -webkit-user-select: none;
+       -moz-user-select: none;
+       -ms-user-select: none;
+       user-select: none;
+       pointer-events: none;
+       box-shadow: 0 1px 3px rgba(0,0,0,0.4);
+       }
+.leaflet-tooltip.leaflet-clickable {
+       cursor: pointer;
+       pointer-events: auto;
+       }
+.leaflet-tooltip-top:before,
+.leaflet-tooltip-bottom:before,
+.leaflet-tooltip-left:before,
+.leaflet-tooltip-right:before {
+       position: absolute;
+       pointer-events: none;
+       border: 6px solid transparent;
+       background: transparent;
+       content: "";
+       }
+
+/* Directions */
+
+.leaflet-tooltip-bottom {
+       margin-top: 6px;
+}
+.leaflet-tooltip-top {
+       margin-top: -6px;
+}
+.leaflet-tooltip-bottom:before,
+.leaflet-tooltip-top:before {
+       left: 50%;
+       margin-left: -6px;
+       }
+.leaflet-tooltip-top:before {
+       bottom: 0;
+       margin-bottom: -12px;
+       border-top-color: #fff;
+       }
+.leaflet-tooltip-bottom:before {
+       top: 0;
+       margin-top: -12px;
+       margin-left: -6px;
+       border-bottom-color: #fff;
+       }
+.leaflet-tooltip-left {
+       margin-left: -6px;
+}
+.leaflet-tooltip-right {
+       margin-left: 6px;
+}
+.leaflet-tooltip-left:before,
+.leaflet-tooltip-right:before {
+       top: 50%;
+       margin-top: -6px;
+       }
+.leaflet-tooltip-left:before {
+       right: 0;
+       margin-right: -12px;
+       border-left-color: #fff;
+       }
+.leaflet-tooltip-right:before {
+       left: 0;
+       margin-left: -12px;
+       border-right-color: #fff;
+       }
index d3d5635..045b307 100644 (file)
@@ -1,13 +1,22 @@
 /*
- Leaflet, a JavaScript library for mobile-friendly interactive maps. http://leafletjs.com
- (c) 2010-2013, Vladimir Agafonkin
- (c) 2010-2011, CloudMade
+ Leaflet 1.0.0, a JS library for interactive maps. http://leafletjs.com
+ (c) 2010-2016 Vladimir Agafonkin, (c) 2010-2011 CloudMade
 */
 (function (window, document, undefined) {
-var oldL = window.L,
-    L = {};
+var L = {
+       version: "1.0.0"
+};
+
+function expose() {
+       var oldL = window.L;
+
+       L.noConflict = function () {
+               window.L = oldL;
+               return this;
+       };
 
-L.version = '0.7.7';
+       window.L = L;
+}
 
 // define Leaflet for Node module pattern loaders, including Browserify
 if (typeof module === 'object' && typeof module.exports === 'object') {
@@ -19,114 +28,160 @@ if (typeof module === 'object' && typeof module.exports === 'object') {
 }
 
 // define Leaflet as a global L variable, saving the original L to restore later if needed
+if (typeof window !== 'undefined') {
+       expose();
+}
 
-L.noConflict = function () {
-       window.L = oldL;
-       return this;
-};
-
-window.L = L;
 
 
 /*
- * L.Util contains various utility functions used throughout Leaflet code.
+ * @namespace Util
+ *
+ * Various utility functions, used by Leaflet internally.
  */
 
 L.Util = {
-       extend: function (dest) { // (Object[, Object, ...]) ->
-               var sources = Array.prototype.slice.call(arguments, 1),
-                   i, j, len, src;
 
-               for (j = 0, len = sources.length; j < len; j++) {
-                       src = sources[j] || {};
+       // @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;
+
+               for (j = 1, len = arguments.length; j < len; j++) {
+                       src = arguments[j];
                        for (i in src) {
-                               if (src.hasOwnProperty(i)) {
-                                       dest[i] = src[i];
-                               }
+                               dest[i] = src[i];
                        }
                }
                return dest;
        },
 
-       bind: function (fn, obj) { // (Function, Object) -> Function
-               var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
-               return function () {
-                       return fn.apply(obj, args || arguments);
-               };
-       },
-
-       stamp: (function () {
-               var lastId = 0,
-                   key = '_leaflet_id';
-               return function (obj) {
-                       obj[key] = obj[key] || ++lastId;
-                       return obj[key];
+       // @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) {
+                       F.prototype = proto;
+                       return new F();
                };
-       }()),
+       })(),
 
-       invokeEach: function (obj, method, context) {
-               var i, args;
+       // @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;
 
-               if (typeof obj === 'object') {
-                       args = Array.prototype.slice.call(arguments, 3);
-
-                       for (i in obj) {
-                               method.apply(context, [i, obj[i]].concat(args));
-                       }
-                       return true;
+               if (fn.bind) {
+                       return fn.bind.apply(fn, slice.call(arguments, 1));
                }
 
-               return false;
-       },
-
-       limitExecByInterval: function (fn, time, context) {
-               var lock, execOnUnlock;
+               var args = slice.call(arguments, 2);
 
-               return function wrapperFn() {
-                       var args = arguments;
+               return function () {
+                       return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
+               };
+       },
 
-                       if (lock) {
-                               execOnUnlock = true;
-                               return;
+       // @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;
+               return obj._leaflet_id;
+               /*eslint-enable */
+       },
+
+       // @property lastId: Number
+       // Last unique ID used by [`stamp()`](#util-stamp)
+       lastId: 0,
+
+       // @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 function
+       // `fn` will be called no more than one time per given amount of `time`. 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;
+
+               later = function () {
+                       // reset lock and call if queued
+                       lock = false;
+                       if (args) {
+                               wrapperFn.apply(context, args);
+                               args = false;
                        }
+               };
 
-                       lock = true;
-
-                       setTimeout(function () {
-                               lock = false;
-
-                               if (execOnUnlock) {
-                                       wrapperFn.apply(context, args);
-                                       execOnUnlock = false;
-                               }
-                       }, time);
+               wrapperFn = function () {
+                       if (lock) {
+                               // called too soon, queue to call later
+                               args = arguments;
 
-                       fn.apply(context, args);
+                       } else {
+                               // call and lock until later
+                               fn.apply(context, arguments);
+                               setTimeout(later, time);
+                               lock = true;
+                       }
                };
+
+               return wrapperFn;
        },
 
-       falseFn: function () {
-               return false;
+       // @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],
+                   d = max - min;
+               return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
        },
 
+       // @function falseFn(): Function
+       // Returns a function which always returns `false`.
+       falseFn: function () { return false; },
+
+       // @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;
        },
 
+       // @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, '');
        },
 
+       // @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+/);
        },
 
+       // @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) {
-               obj.options = L.extend({}, obj.options, options);
+               if (!obj.hasOwnProperty('options')) {
+                       obj.options = obj.options ? L.Util.create(obj.options) : {};
+               }
+               for (var i in options) {
+                       obj.options[i] = options[i];
+               }
                return obj.options;
        },
 
+       // @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) {
@@ -134,11 +189,19 @@ L.Util = {
                }
                return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
        },
+
+       // @function template(str: String, data: Object): String
+       // 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(/\{ *([\w_]+) *\}/g, function (str, key) {
+               return str.replace(L.Util.templateRe, function (str, key) {
                        var value = data[key];
+
                        if (value === undefined) {
                                throw new Error('No value provided for variable ' + str);
+
                        } else if (typeof value === 'function') {
                                value = value(data);
                        }
@@ -146,30 +209,40 @@ 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(array: Array, el: Object): Number
+       // 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; }
+               }
+               return -1;
+       },
+
+       // @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='
 };
 
 (function () {
-
        // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
 
        function getPrefixed(name) {
-               var i, fn,
-                   prefixes = ['webkit', 'moz', 'o', 'ms'];
-
-               for (i = 0; i < prefixes.length && !fn; i++) {
-                       fn = window[prefixes[i] + name];
-               }
-
-               return fn;
+               return window['webkit' + name] || window['moz' + name] || window['ms' + name];
        }
 
        var lastTime = 0;
 
+       // fallback for IE 7-8
        function timeoutDefer(fn) {
                var time = +new Date(),
                    timeToCall = Math.max(0, 16 - (time - lastTime));
@@ -178,32 +251,33 @@ L.Util = {
                return window.setTimeout(fn, timeToCall);
        }
 
-       var requestFn = window.requestAnimationFrame ||
-               getPrefixed('RequestAnimationFrame') || timeoutDefer;
-
-       var cancelFn = window.cancelAnimationFrame ||
-               getPrefixed('CancelAnimationFrame') ||
-               getPrefixed('CancelRequestAnimationFrame') ||
-               function (id) { window.clearTimeout(id); };
+       var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer,
+           cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
+                      getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
 
 
-       L.Util.requestAnimFrame = function (fn, context, immediate, element) {
-               fn = L.bind(fn, context);
-
+       // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): 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 a request ID that can be used to cancel the request.
+       L.Util.requestAnimFrame = function (fn, context, immediate) {
                if (immediate && requestFn === timeoutDefer) {
-                       fn();
+                       fn.call(context);
                } else {
-                       return requestFn.call(window, fn, element);
+                       return requestFn.call(window, L.bind(fn, context));
                }
        };
 
+       // @function cancelAnimFrame(id: Number): undefined
+       // 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);
                }
        };
-
-}());
+})();
 
 // shortcuts for most used utility functions
 L.extend = L.Util.extend;
@@ -212,16 +286,23 @@ L.stamp = L.Util.stamp;
 L.setOptions = L.Util.setOptions;
 
 
-/*
- * 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
@@ -230,21 +311,17 @@ L.Class.extend = function (props) {
                }
 
                // call all constructor hooks
-               if (this._initHooks) {
-                       this.callInitHooks();
-               }
+               this.callInitHooks();
        };
 
-       // instantiate class without calling constructor
-       var F = function () {};
-       F.prototype = this.prototype;
+       var parentProto = NewClass.__super__ = this.prototype;
 
-       var proto = new F();
+       var proto = L.Util.create(parentProto);
        proto.constructor = NewClass;
 
        NewClass.prototype = proto;
 
-       //inherit parent's statics
+       // inherit parent's statics
        for (var i in this) {
                if (this.hasOwnProperty(i) && i !== 'prototype') {
                        NewClass[i] = this[i];
@@ -264,8 +341,8 @@ L.Class.extend = function (props) {
        }
 
        // merge options
-       if (props.options && proto.options) {
-               props.options = L.extend({}, proto.options, props.options);
+       if (proto.options) {
+               props.options = L.Util.extend(L.Util.create(proto.options), props.options);
        }
 
        // mix given properties into the prototype
@@ -273,17 +350,13 @@ L.Class.extend = function (props) {
 
        proto._initHooks = [];
 
-       var parent = this;
-       // jshint camelcase: false
-       NewClass.__super__ = parent.prototype;
-
        // add method for calling all hooks
        proto.callInitHooks = function () {
 
                if (this._initHooksCalled) { return; }
 
-               if (parent.prototype.callInitHooks) {
-                       parent.prototype.callInitHooks.call(this);
+               if (parentProto.callInitHooks) {
+                       parentProto.callInitHooks.call(this);
                }
 
                this._initHooksCalled = true;
@@ -297,17 +370,22 @@ L.Class.extend = function (props) {
 };
 
 
-// method for adding properties to prototype
+// @function include(properties: Object): this
+// [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): this
+// [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): this
+// 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);
 
@@ -317,284 +395,504 @@ L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
 
        this.prototype._initHooks = this.prototype._initHooks || [];
        this.prototype._initHooks.push(init);
+       return this;
 };
 
 
+
 /*
- * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
+ * @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);
+ * ```
  */
 
-var eventsKey = '_leaflet_events';
-
-L.Mixin = {};
 
-L.Mixin.Events = {
+L.Evented = L.Class.extend({
 
-       addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
+       /* @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
-               if (L.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; }
-
-               var events = this[eventsKey] = this[eventsKey] || {},
-                   contextId = context && context !== this && L.stamp(context),
-                   i, len, event, type, indexKey, indexLenKey, typeIndex;
-
-               // types can be a string of space-separated words
-               types = L.Util.splitWords(types);
-
-               for (i = 0, len = types.length; i < len; i++) {
-                       event = {
-                               action: fn,
-                               context: context || this
-                       };
-                       type = types[i];
+               if (typeof types === 'object') {
+                       for (var type in types) {
+                               // we don't process space-separated events here for performance;
+                               // it's a hot path since Layer uses the on(obj) syntax
+                               this._on(type, types[type], fn);
+                       }
 
-                       if (contextId) {
-                               // store listeners of a particular context in a separate hash (if it has an id)
-                               // gives a major performance boost when removing thousands of map layers
+               } else {
+                       // types can be a string of space-separated words
+                       types = L.Util.splitWords(types);
 
-                               indexKey = type + '_idx';
-                               indexLenKey = indexKey + '_len';
+                       for (var i = 0, len = types.length; i < len; i++) {
+                               this._on(types[i], fn, context);
+                       }
+               }
 
-                               typeIndex = events[indexKey] = events[indexKey] || {};
+               return this;
+       },
 
-                               if (!typeIndex[contextId]) {
-                                       typeIndex[contextId] = [];
+       /* @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) {
 
-                                       // keep track of the number of keys in the index to quickly check if it's empty
-                                       events[indexLenKey] = (events[indexLenKey] || 0) + 1;
-                               }
+               if (!types) {
+                       // clear all listeners if called without arguments
+                       delete this._events;
 
-                               typeIndex[contextId].push(event);
+               } else if (typeof types === 'object') {
+                       for (var type in types) {
+                               this._off(type, types[type], fn);
+                       }
 
+               } else {
+                       types = L.Util.splitWords(types);
 
-                       } else {
-                               events[type] = events[type] || [];
-                               events[type].push(event);
+                       for (var i = 0, len = types.length; i < len; i++) {
+                               this._off(types[i], fn, context);
                        }
                }
 
                return this;
        },
 
-       hasEventListeners: function (type) { // (String) -> Boolean
-               var events = this[eventsKey];
-               return !!events && ((type in events && events[type].length > 0) ||
-                                   (type + '_idx' in events && events[type + '_idx_len'] > 0));
-       },
-
-       removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object])
+       // attach listener (without syntactic sugar now)
+       _on: function (type, fn, context) {
+               this._events = this._events || {};
 
-               if (!this[eventsKey]) {
-                       return this;
+               /* get/init listeners for type */
+               var typeListeners = this._events[type];
+               if (!typeListeners) {
+                       typeListeners = [];
+                       this._events[type] = typeListeners;
                }
 
-               if (!types) {
-                       return this.clearAllEventListeners();
+               if (context === this) {
+                       // Less memory footprint.
+                       context = undefined;
                }
+               var newListener = {fn: fn, ctx: context},
+                   listeners = typeListeners;
 
-               if (L.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; }
-
-               var events = this[eventsKey],
-                   contextId = context && context !== this && L.stamp(context),
-                   i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed;
+               // check if fn already there
+               for (var i = 0, len = listeners.length; i < len; i++) {
+                       if (listeners[i].fn === fn && listeners[i].ctx === context) {
+                               return;
+                       }
+               }
 
-               types = L.Util.splitWords(types);
+               listeners.push(newListener);
+               typeListeners.count++;
+       },
 
-               for (i = 0, len = types.length; i < len; i++) {
-                       type = types[i];
-                       indexKey = type + '_idx';
-                       indexLenKey = indexKey + '_len';
+       _off: function (type, fn, context) {
+               var listeners,
+                   i,
+                   len;
 
-                       typeIndex = events[indexKey];
+               if (!this._events) { return; }
 
-                       if (!fn) {
-                               // clear all listeners for a type if function isn't specified
-                               delete events[type];
-                               delete events[indexKey];
-                               delete events[indexLenKey];
+               listeners = this._events[type];
 
-                       } else {
-                               listeners = contextId && typeIndex ? typeIndex[contextId] : events[type];
-
-                               if (listeners) {
-                                       for (j = listeners.length - 1; j >= 0; j--) {
-                                               if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) {
-                                                       removed = listeners.splice(j, 1);
-                                                       // set the old action to a no-op, because it is possible
-                                                       // that the listener is being iterated over as part of a dispatch
-                                                       removed[0].action = L.Util.falseFn;
-                                               }
-                                       }
+               if (!listeners) {
+                       return;
+               }
 
-                                       if (context && typeIndex && (listeners.length === 0)) {
-                                               delete typeIndex[contextId];
-                                               events[indexLenKey]--;
-                                       }
-                               }
+               if (!fn) {
+                       // Set all removed listeners to noop so they are not called if remove happens in fire
+                       for (i = 0, len = listeners.length; i < len; i++) {
+                               listeners[i].fn = L.Util.falseFn;
                        }
+                       // clear all listeners for a type if function isn't specified
+                       delete this._events[type];
+                       return;
                }
 
-               return this;
-       },
-
-       clearAllEventListeners: function () {
-               delete this[eventsKey];
-               return this;
-       },
-
-       fireEvent: function (type, data) { // (String[, Object])
-               if (!this.hasEventListeners(type)) {
-                       return this;
+               if (context === this) {
+                       context = undefined;
                }
 
-               var event = L.Util.extend({}, data, { type: type, target: this });
+               if (listeners) {
 
-               var events = this[eventsKey],
-                   listeners, i, len, typeIndex, contextId;
+                       // find fn and remove it
+                       for (i = 0, len = listeners.length; i < len; i++) {
+                               var l = listeners[i];
+                               if (l.ctx !== context) { continue; }
+                               if (l.fn === fn) {
 
-               if (events[type]) {
-                       // make sure adding/removing listeners inside other listeners won't cause infinite loop
-                       listeners = events[type].slice();
+                                       // set the removed listener to noop so that's not called if remove happens in fire
+                                       l.fn = L.Util.falseFn;
 
-                       for (i = 0, len = listeners.length; i < len; i++) {
-                               listeners[i].action.call(listeners[i].context, event);
+                                       if (this._firingCount) {
+                                               /* copy array in case events are being fired */
+                                               this._events[type] = listeners = listeners.slice();
+                                       }
+                                       listeners.splice(i, 1);
+
+                                       return;
+                               }
                        }
                }
+       },
+
+       // @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; }
 
-               // fire event for the context-indexed listeners as well
-               typeIndex = events[type + '_idx'];
+               var event = L.Util.extend({}, data, {type: type, target: this});
 
-               for (contextId in typeIndex) {
-                       listeners = typeIndex[contextId].slice();
+               if (this._events) {
+                       var listeners = this._events[type];
 
                        if (listeners) {
-                               for (i = 0, len = listeners.length; i < len; i++) {
-                                       listeners[i].action.call(listeners[i].context, event);
+                               this._firingCount = (this._firingCount + 1) || 1;
+                               for (var i = 0, len = listeners.length; i < len; i++) {
+                                       var l = listeners[i];
+                                       l.fn.call(l.ctx || this, event);
                                }
+
+                               this._firingCount--;
                        }
                }
 
+               if (propagate) {
+                       // propagate the event to parents (set with addEventParent)
+                       this._propagateEvent(event);
+               }
+
                return this;
        },
 
-       addOneTimeEventListener: function (types, fn, context) {
+       // @method listens(type: String): Boolean
+       // Returns `true` if a particular event type has any listeners attached to it.
+       listens: function (type, propagate) {
+               var listeners = this._events && this._events[type];
+               if (listeners && listeners.length) { return true; }
+
+               if (propagate) {
+                       // also check parents for listeners if event propagates
+                       for (var id in this._eventParents) {
+                               if (this._eventParents[id].listens(type, propagate)) { return true; }
+                       }
+               }
+               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 (L.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; }
+               if (typeof types === 'object') {
+                       for (var type in types) {
+                               this.once(type, types[type], fn);
+                       }
+                       return this;
+               }
 
                var handler = L.bind(function () {
                        this
-                           .removeEventListener(types, fn, context)
-                           .removeEventListener(types, handler, context);
+                           .off(types, fn, context)
+                           .off(types, handler, context);
                }, this);
 
+               // add a listener that's executed once and removed after that
                return this
-                   .addEventListener(types, fn, context)
-                   .addEventListener(types, handler, context);
+                   .on(types, fn, context)
+                   .on(types, handler, context);
+       },
+
+       // @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)];
+               }
+               return this;
+       },
+
+       _propagateEvent: function (e) {
+               for (var id in this._eventParents) {
+                       this._eventParents[id].fire(e.type, L.extend({layer: e.target}, e), true);
+               }
        }
-};
+});
+
+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(…): Boolean
+// Alias to [`listens(…)`](#evented-listens)
+proto.hasEventListeners = proto.listens;
+
+L.Mixin = {Events: proto};
 
-L.Mixin.Events.on = L.Mixin.Events.addEventListener;
-L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
-L.Mixin.Events.once = L.Mixin.Events.addOneTimeEventListener;
-L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
 
 
 /*
- * 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 () {
 
-       var ie = 'ActiveXObject' in window,
-               ielt9 = ie && !document.addEventListener,
+       var ua = navigator.userAgent.toLowerCase(),
+           doc = document.documentElement,
+
+           ie = 'ActiveXObject' in window,
 
-           // terrible browser detection to work around Safari / iOS / Android browser bugs
-           ua = navigator.userAgent.toLowerCase(),
-           webkit = ua.indexOf('webkit') !== -1,
-           chrome = ua.indexOf('chrome') !== -1,
+           webkit    = ua.indexOf('webkit') !== -1,
            phantomjs = ua.indexOf('phantom') !== -1,
-           android = ua.indexOf('android') !== -1,
            android23 = ua.search('android [23]') !== -1,
-               gecko = ua.indexOf('gecko') !== -1,
+           chrome    = ua.indexOf('chrome') !== -1,
+           gecko     = ua.indexOf('gecko') !== -1  && !webkit && !window.opera && !ie,
 
-           mobile = typeof orientation !== undefined + '',
+           win = navigator.platform.indexOf('Win') === 0,
+
+           mobile = typeof orientation !== 'undefined' || ua.indexOf('mobile') !== -1,
            msPointer = !window.PointerEvent && window.MSPointerEvent,
-               pointer = (window.PointerEvent && window.navigator.pointerEnabled) ||
-                                 msPointer,
-           retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) ||
-                    ('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') &&
-                     window.matchMedia('(min-resolution:144dpi)').matches),
+           pointer = window.PointerEvent || msPointer,
 
-           doc = document.documentElement,
            ie3d = ie && ('transition' in doc.style),
            webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23,
            gecko3d = 'MozPerspective' in doc.style,
-           opera3d = 'OTransition' in doc.style,
-           any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs;
+           opera12 = 'OTransition' in doc.style;
 
-       var touch = !window.L_NO_TOUCH && !phantomjs && (pointer || 'ontouchstart' in window ||
-               (window.DocumentTouch && document instanceof window.DocumentTouch));
+
+       var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
+                       (window.DocumentTouch && document instanceof window.DocumentTouch));
 
        L.Browser = {
+
+               // @property ie: Boolean
+               // `true` for all Internet Explorer versions (not Edge).
                ie: ie,
-               ielt9: ielt9,
+
+               // @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,
-               gecko: gecko && !webkit && !window.opera && !ie,
 
-               android: android,
+               // @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 win: Boolean
+               // `true` when the browser is running in a Windows platform
+               win: win,
+
+
+               // @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,
-               opera3d: opera3d,
-               any3d: any3d,
 
+               // @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 mobile: Boolean
+               // `true` for all browsers running in a mobile device.
                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,
 
-               touch: touch,
-               msPointer: msPointer,
-               pointer: pointer,
+               // @property mobileGecko: Boolean
+               // `true` for gecko-based browsers running in a mobile device.
+               mobileGecko: mobile && gecko,
+
 
-               retina: retina
+               // @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
        };
 
 }());
 
 
+
 /*
- * 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 (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
+L.Point = function (x, y, round) {
        this.x = (round ? Math.round(x) : x);
        this.y = (round ? Math.round(y) : y);
 };
 
 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));
        },
@@ -605,6 +903,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);
        },
@@ -615,6 +915,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);
        },
@@ -625,6 +927,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): 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();
        },
@@ -635,6 +955,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();
        },
@@ -645,6 +967,20 @@ 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();
+       },
+
+       _ceil: function () {
+               this.x = Math.ceil(this.x);
+               this.y = Math.ceil(this.y);
+               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);
 
@@ -654,6 +990,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);
 
@@ -661,6 +999,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);
 
@@ -668,6 +1008,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) + ', ' +
@@ -675,6 +1017,16 @@ 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.
+
+// @alternative
+// @factory L.point(coords: Object)
+// Expects a plain object of the form `{x: Number, y: Number}` instead.
 L.point = function (x, y, round) {
        if (x instanceof L.Point) {
                return x;
@@ -685,15 +1037,36 @@ L.point = function (x, y, round) {
        if (x === undefined || x === null) {
                return x;
        }
+       if (typeof x === 'object' && 'x' in x && 'y' in x) {
+               return new L.Point(x.x, x.y);
+       }
        return new L.Point(x, y, round);
 };
 
 
+
 /*
- * 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;
@@ -704,10 +1077,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();
@@ -720,25 +1098,38 @@ L.Bounds.prototype = {
                return this;
        },
 
-       getCenter: function (round) { // (Boolean) -> Point
+       // @method getCenter(round?: Boolean): 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 point.
+       contains: function (obj) {
                var min, max;
 
                if (typeof obj[0] === 'number' || obj instanceof L.Point) {
@@ -760,6 +1151,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);
 
@@ -773,12 +1167,34 @@ 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);
+
+               var min = this.min,
+                   max = this.max,
+                   min2 = bounds.min,
+                   max2 = bounds.max,
+                   xOverlaps = (max2.x > min.x) && (min2.x < max.x),
+                   yOverlaps = (max2.y > min.y) && (min2.y < max.y);
+
+               return xOverlaps && yOverlaps;
+       },
+
        isValid: function () {
                return !!(this.min && this.max);
        }
 };
 
-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;
        }
@@ -786,10 +1202,28 @@ L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
 };
 
 
+
 /*
- * 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;
@@ -798,6 +1232,9 @@ L.Transformation = function (a, b, c, d) {
 };
 
 L.Transformation.prototype = {
+       // @method transform(point: Point, scale?: Number): Point
+       // 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);
        },
@@ -810,6 +1247,9 @@ L.Transformation.prototype = {
                return point;
        },
 
+       // @method untransform(point: Point, scale?: Number): Point
+       // 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(
@@ -819,22 +1259,33 @@ L.Transformation.prototype = {
 };
 
 
+
 /*
- * 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);
+               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];
-
-               if (!value && el.currentStyle) {
-                       value = el.currentStyle[style];
-               }
+               var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
 
                if ((!value || value === 'auto') && document.defaultView) {
                        var css = document.defaultView.getComputedStyle(el, null);
@@ -844,94 +1295,62 @@ L.DomUtil = {
                return value === 'auto' ? null : value;
        },
 
-       getViewportOffset: function (element) {
-
-               var top = 0,
-                   left = 0,
-                   el = element,
-                   docBody = document.body,
-                   docEl = document.documentElement,
-                   pos;
-
-               do {
-                       top  += el.offsetTop  || 0;
-                       left += el.offsetLeft || 0;
-
-                       //add borders
-                       top += parseInt(L.DomUtil.getStyle(el, 'borderTopWidth'), 10) || 0;
-                       left += parseInt(L.DomUtil.getStyle(el, 'borderLeftWidth'), 10) || 0;
-
-                       pos = L.DomUtil.getStyle(el, 'position');
-
-                       if (el.offsetParent === docBody && pos === 'absolute') { break; }
-
-                       if (pos === 'fixed') {
-                               top  += docBody.scrollTop  || docEl.scrollTop  || 0;
-                               left += docBody.scrollLeft || docEl.scrollLeft || 0;
-                               break;
-                       }
-
-                       if (pos === 'relative' && !el.offsetLeft) {
-                               var width = L.DomUtil.getStyle(el, 'width'),
-                                   maxWidth = L.DomUtil.getStyle(el, 'max-width'),
-                                   r = el.getBoundingClientRect();
-
-                               if (width !== 'none' || maxWidth !== 'none') {
-                                       left += r.left + el.clientLeft;
-                               }
-
-                               //calculate full y offset since we're breaking out of the loop
-                               top += r.top + (docBody.scrollTop  || docEl.scrollTop  || 0);
-
-                               break;
-                       }
-
-                       el = el.offsetParent;
-
-               } while (el);
-
-               el = element;
-
-               do {
-                       if (el === docBody) { break; }
+       // @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) {
 
-                       top  -= el.scrollTop  || 0;
-                       left -= el.scrollLeft || 0;
+               var el = document.createElement(tagName);
+               el.className = className || '';
 
-                       el = el.parentNode;
-               } while (el);
+               if (container) {
+                       container.appendChild(el);
+               }
 
-               return new L.Point(left, top);
+               return el;
        },
 
-       documentIsLtr: function () {
-               if (!L.DomUtil._docIsLtrCached) {
-                       L.DomUtil._docIsLtrCached = true;
-                       L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === 'ltr';
+       // @function remove(el: HTMLElement)
+       // Removes `el` from its parent element
+       remove: function (el) {
+               var parent = el.parentNode;
+               if (parent) {
+                       parent.removeChild(el);
                }
-               return L.DomUtil._docIsLtr;
        },
 
-       create: function (tagName, className, container) {
-
-               var el = document.createElement(tagName);
-               el.className = className;
-
-               if (container) {
-                       container.appendChild(el);
+       // @function empty(el: HTMLElement)
+       // Removes all of `el`'s children elements from `el`
+       empty: function (el) {
+               while (el.firstChild) {
+                       el.removeChild(el.firstChild);
                }
+       },
 
-               return el;
+       // @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);
                }
-               var className = L.DomUtil._getClass(el);
+               var className = L.DomUtil.getClass(el);
                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);
@@ -939,20 +1358,24 @@ L.DomUtil = {
                                el.classList.add(classes[i]);
                        }
                } else if (!L.DomUtil.hasClass(el, name)) {
-                       var className = L.DomUtil._getClass(el);
-                       L.DomUtil._setClass(el, (className ? className + ' ' : '') + name);
+                       var className = L.DomUtil.getClass(el);
+                       L.DomUtil.setClass(el, (className ? className + ' ' : '') + name);
                }
        },
 
+       // @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);
                } else {
-                       L.DomUtil._setClass(el, L.Util.trim((' ' + L.DomUtil._getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
+                       L.DomUtil.setClass(el, L.Util.trim((' ' + L.DomUtil.getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
                }
        },
 
-       _setClass: function (el, name) {
+       // @function setClass(el: HTMLElement, name: String)
+       // Sets the element's class.
+       setClass: function (el, name) {
                if (el.className.baseVal === undefined) {
                        el.className = name;
                } else {
@@ -961,40 +1384,52 @@ L.DomUtil = {
                }
        },
 
-       _getClass: function (el) {
+       // @function getClass(el: HTMLElement): String
+       // Returns 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) {
                        el.style.opacity = value;
 
                } else if ('filter' in el.style) {
+                       L.DomUtil._setOpacityIE(el, value);
+               }
+       },
 
-                       var filter = false,
-                           filterName = 'DXImageTransform.Microsoft.Alpha';
+       _setOpacityIE: function (el, value) {
+               var filter = false,
+                   filterName = 'DXImageTransform.Microsoft.Alpha';
 
-                       // filters collection throws an error if we try to retrieve a filter that doesn't exist
-                       try {
-                               filter = el.filters.item(filterName);
-                       } catch (e) {
-                               // don't set opacity to 1 if we haven't already set an opacity,
-                               // it isn't needed and breaks transparent pngs.
-                               if (value === 1) { return; }
-                       }
+               // filters collection throws an error if we try to retrieve a filter that doesn't exist
+               try {
+                       filter = el.filters.item(filterName);
+               } catch (e) {
+                       // don't set opacity to 1 if we haven't already set an opacity,
+                       // it isn't needed and breaks transparent pngs.
+                       if (value === 1) { return; }
+               }
 
-                       value = Math.round(value * 100);
+               value = Math.round(value * 100);
 
-                       if (filter) {
-                               filter.Enabled = (value !== 100);
-                               filter.Opacity = value;
-                       } else {
-                               el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
-                       }
+               if (filter) {
+                       filter.Enabled = (value !== 100);
+                       filter.Opacity = value;
+               } else {
+                       el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
                }
        },
 
+       // @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;
@@ -1007,137 +1442,192 @@ L.DomUtil = {
                return false;
        },
 
-       getTranslateString: function (point) {
-               // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
-               // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
-               // (same speed either way), Opera 12 doesn't support translate3d
-
-               var is3d = L.Browser.webkit3d,
-                   open = 'translate' + (is3d ? '3d' : '') + '(',
-                   close = (is3d ? ',0' : '') + ')';
+       // @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);
 
-               return open + point.x + 'px,' + point.y + 'px' + close;
+               el.style[L.DomUtil.TRANSFORM] =
+                       (L.Browser.ie3d ?
+                               'translate(' + pos.x + 'px,' + pos.y + 'px)' :
+                               'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
+                       (scale ? ' scale(' + scale + ')' : '');
        },
 
-       getScaleString: function (scale, origin) {
+       // @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])
 
-               var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
-                   scaleStr = ' scale(' + scale + ') ';
-
-               return preTranslateStr + scaleStr;
-       },
-
-       setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
-
-               // jshint camelcase: false
+               /*eslint-disable */
                el._leaflet_pos = point;
+               /*eslint-enable */
 
-               if (!disable3D && L.Browser.any3d) {
-                       el.style[L.DomUtil.TRANSFORM] =  L.DomUtil.getTranslateString(point);
+               if (L.Browser.any3d) {
+                       L.DomUtil.setTransform(el, point);
                } else {
                        el.style.left = point.x + 'px';
                        el.style.top = point.y + 'px';
                }
        },
 
+       // @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
 
-               // jshint camelcase: false
-               return el._leaflet_pos;
+               return el._leaflet_pos || new L.Point(0, 0);
        }
 };
 
 
-// prefix style property names
+(function () {
+       // prefix style property names
 
-L.DomUtil.TRANSFORM = L.DomUtil.testProp(
-        ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
+       // @property TRANSFORM: String
+       // Vendor-prefixed fransform style name (e.g. `'webkitTransform'` for WebKit).
+       L.DomUtil.TRANSFORM = L.DomUtil.testProp(
+                       ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
 
-// 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
 
-L.DomUtil.TRANSITION = L.DomUtil.testProp(
-        ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
+       // 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
 
-L.DomUtil.TRANSITION_END =
-        L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
-        L.DomUtil.TRANSITION + 'End' : 'transitionend';
+       // @property TRANSITION: String
+       // Vendor-prefixed transform style name.
+       var transition = L.DomUtil.TRANSITION = L.DomUtil.testProp(
+                       ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
 
-(function () {
-    if ('onselectstart' in document) {
-        L.extend(L.DomUtil, {
-            disableTextSelection: function () {
-                L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
-            },
-
-            enableTextSelection: function () {
-                L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
-            }
-        });
-    } else {
-        var userSelectProperty = L.DomUtil.testProp(
-            ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
-
-        L.extend(L.DomUtil, {
-            disableTextSelection: function () {
-                if (userSelectProperty) {
-                    var style = document.documentElement.style;
-                    this._userSelect = style[userSelectProperty];
-                    style[userSelectProperty] = 'none';
-                }
-            },
-
-            enableTextSelection: function () {
-                if (userSelectProperty) {
-                    document.documentElement.style[userSelectProperty] = this._userSelect;
-                    delete this._userSelect;
-                }
-            }
-        });
-    }
-
-       L.extend(L.DomUtil, {
-               disableImageDrag: function () {
-                       L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
-               },
+       L.DomUtil.TRANSITION_END =
+                       transition === 'webkitTransition' || transition === 'OTransition' ? transition + 'End' : 'transitionend';
 
-               enableImageDrag: function () {
-                       L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
-               }
-       });
+       // @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);
+               };
+               L.DomUtil.enableTextSelection = function () {
+                       L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
+               };
+
+       } else {
+               var userSelectProperty = L.DomUtil.testProp(
+                       ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
+
+               L.DomUtil.disableTextSelection = function () {
+                       if (userSelectProperty) {
+                               var style = document.documentElement.style;
+                               this._userSelect = style[userSelectProperty];
+                               style[userSelectProperty] = 'none';
+                       }
+               };
+               L.DomUtil.enableTextSelection = function () {
+                       if (userSelectProperty) {
+                               document.documentElement.style[userSelectProperty] = this._userSelect;
+                               delete this._userSelect;
+                       }
+               };
+       }
+
+       // @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;
+               }
+               if (!element || !element.style) { return; }
+               L.DomUtil.restoreOutline();
+               this._outlineElement = element;
+               this._outlineStyle = element.style.outline;
+               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;
+               delete this._outlineElement;
+               delete this._outlineStyle;
+               L.DomEvent.off(window, 'keydown', L.DomUtil.restoreOutline, this);
+       };
 })();
 
 
-/*
- * L.LatLng represents a geographical point with latitude and longitude coordinates.
- */
 
-L.LatLng = function (lat, lng, alt) { // (Number, Number, Number)
-       lat = parseFloat(lat);
-       lng = parseFloat(lng);
+/* @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) {
        if (isNaN(lat) || isNaN(lng)) {
                throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
        }
 
-       this.lat = lat;
-       this.lng = 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 = parseFloat(alt);
+               this.alt = +alt;
        }
 };
 
-L.extend(L.LatLng, {
-       DEG_TO_RAD: Math.PI / 180,
-       RAD_TO_DEG: 180 / Math.PI,
-       MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
-});
-
 L.LatLng.prototype = {
-       equals: function (obj) { // (LatLng) -> Boolean
+       // @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; }
 
                obj = L.latLng(obj);
@@ -1146,73 +1636,107 @@ L.LatLng.prototype = {
                        Math.abs(this.lat - obj.lat),
                        Math.abs(this.lng - obj.lng));
 
-               return margin <= L.LatLng.MAX_MARGIN;
+               return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
        },
 
-       toString: function (precision) { // (Number) -> String
+       // @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) + ')';
        },
 
-       // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
-       // TODO move to projection code, LatLng shouldn't know about Earth
-       distanceTo: function (other) { // (LatLng) -> Number
-               other = L.latLng(other);
+       // @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));
+       },
 
-               var R = 6378137, // earth radius in meters
-                   d2r = L.LatLng.DEG_TO_RAD,
-                   dLat = (other.lat - this.lat) * d2r,
-                   dLon = (other.lng - this.lng) * d2r,
-                   lat1 = this.lat * d2r,
-                   lat2 = other.lat * d2r,
-                   sin1 = Math.sin(dLat / 2),
-                   sin2 = Math.sin(dLon / 2);
+       // @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);
+       },
 
-               var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
+       // @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);
 
-               return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
+               return L.latLngBounds(
+                       [this.lat - latAccuracy, this.lng - lngAccuracy],
+                       [this.lat + latAccuracy, this.lng + lngAccuracy]);
        },
 
-       wrap: function (a, b) { // (Number, Number) -> LatLng
-               var lng = this.lng;
+       clone: function () {
+               return new L.LatLng(this.lat, this.lng, this.alt);
+       }
+};
 
-               a = a || -180;
-               b = b ||  180;
 
-               lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a);
 
-               return new L.LatLng(this.lat, lng);
-       }
-};
+// @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.
 
-L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number)
+// @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) {
                return a;
        }
-       if (L.Util.isArray(a)) {
-               if (typeof a[0] === 'number' || typeof a[0] === 'string') {
+       if (L.Util.isArray(a) && typeof a[0] !== 'object') {
+               if (a.length === 3) {
                        return new L.LatLng(a[0], a[1], a[2]);
-               } else {
-                       return null;
                }
+               if (a.length === 2) {
+                       return new L.LatLng(a[0], a[1]);
+               }
+               return null;
        }
        if (a === undefined || a === null) {
                return a;
        }
        if (typeof a === 'object' && 'lat' in a) {
-               return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon);
+               return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
        }
        if (b === undefined) {
                return null;
        }
-       return new L.LatLng(a, b);
+       return new L.LatLng(a, b, c);
 };
 
 
 
 /*
- * 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[])
@@ -1226,37 +1750,48 @@ 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)
-               if (!obj) { return this; }
 
-               var latLng = L.latLng(obj);
-               if (latLng !== null) {
-                       obj = latLng;
-               } else {
-                       obj = L.latLngBounds(obj);
-               }
+       // @method extend(latlng: LatLng): this
+       // Extend the bounds to contain the given point
+
+       // @alternative
+       // @method extend(otherBounds: LatLngBounds): this
+       // Extend the bounds to contain the given bounds
+       extend: function (obj) {
+               var sw = this._southWest,
+                   ne = this._northEast,
+                   sw2, ne2;
 
                if (obj instanceof L.LatLng) {
-                       if (!this._southWest && !this._northEast) {
-                               this._southWest = new L.LatLng(obj.lat, obj.lng);
-                               this._northEast = new L.LatLng(obj.lat, obj.lng);
-                       } else {
-                               this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
-                               this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
+                       sw2 = obj;
+                       ne2 = obj;
 
-                               this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
-                               this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
-                       }
                } else if (obj instanceof L.LatLngBounds) {
-                       this.extend(obj._southWest);
-                       this.extend(obj._northEast);
+                       sw2 = obj._southWest;
+                       ne2 = obj._northEast;
+
+                       if (!sw2 || !ne2) { return this; }
+
+               } else {
+                       return obj ? this.extend(L.latLng(obj) || L.latLngBounds(obj)) : this;
+               }
+
+               if (!sw && !ne) {
+                       this._southWest = new L.LatLng(sw2.lat, sw2.lng);
+                       this._northEast = new L.LatLng(ne2.lat, ne2.lng);
+               } else {
+                       sw.lat = Math.min(sw2.lat, sw.lat);
+                       sw.lng = Math.min(sw2.lng, sw.lng);
+                       ne.lat = Math.max(ne2.lat, ne.lat);
+                       ne.lng = Math.max(ne2.lng, ne.lng);
                }
+
                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,
@@ -1267,44 +1802,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);
@@ -1327,7 +1886,9 @@ L.LatLngBounds.prototype = {
                       (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
        },
 
-       intersects: function (bounds) { // (LatLngBounds)
+       // @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,
@@ -1341,11 +1902,31 @@ L.LatLngBounds.prototype = {
                return latIntersects && lngIntersects;
        },
 
+       // @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,
+                   ne = this._northEast,
+                   sw2 = bounds.getSouthWest(),
+                   ne2 = bounds.getNorthEast(),
+
+                   latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
+                   lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
+
+               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);
@@ -1354,108 +1935,218 @@ 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);
        }
 };
 
-//TODO International date line?
+// TODO International date line?
 
-L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
-       if (!a || a instanceof L.LatLngBounds) {
+// @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;
        }
        return new L.LatLngBounds(a, b);
 };
 
 
+
 /*
- * L.Projection contains various geographical projections used by CRS classes.
+ * @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 = {};
 
+L.Projection.LonLat = {
+       project: function (latlng) {
+               return new L.Point(latlng.lng, latlng.lat);
+       },
+
+       unproject: function (point) {
+               return new L.LatLng(point.y, point.x);
+       },
+
+       bounds: L.bounds([-180, -90], [180, 90])
+};
+
+
 
 /*
- * 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 = {
+
+       R: 6378137,
        MAX_LATITUDE: 85.0511287798,
 
-       project: function (latlng) { // (LatLng) -> Point
-               var d = L.LatLng.DEG_TO_RAD,
+       project: function (latlng) {
+               var d = Math.PI / 180,
                    max = this.MAX_LATITUDE,
                    lat = Math.max(Math.min(max, latlng.lat), -max),
-                   x = latlng.lng * d,
-                   y = lat * d;
+                   sin = Math.sin(lat * d);
 
-               y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
-
-               return new L.Point(x, y);
+               return new L.Point(
+                               this.R * latlng.lng * d,
+                               this.R * Math.log((1 + sin) / (1 - sin)) / 2);
        },
 
-       unproject: function (point) { // (Point, Boolean) -> LatLng
-               var d = L.LatLng.RAD_TO_DEG,
-                   lng = point.x * d,
-                   lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
-
-               return new L.LatLng(lat, lng);
-       }
-};
-
-
-/*
- * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple.
- */
+       unproject: function (point) {
+               var d = 180 / Math.PI;
 
-L.Projection.LonLat = {
-       project: function (latlng) {
-               return new L.Point(latlng.lng, latlng.lat);
+               return new L.LatLng(
+                       (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
+                       point.x * d / this.R);
        },
 
-       unproject: function (point) {
-               return new L.LatLng(point.y, point.x);
-       }
+       bounds: (function () {
+               var d = 6378137 * Math.PI;
+               return L.bounds([-d, -d], [d, d]);
+       })()
 };
 
 
+
 /*
- * L.CRS is a 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](https://en.wikipedia.org/wiki/Web_Map_Service) 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 = {
-       latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
+       // @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);
 
                return this.transformation._transform(projectedPoint, scale);
        },
 
-       pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
+       // @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);
 
                return this.projection.unproject(untransformedPoint);
        },
 
+       // @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);
        },
 
+       // @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);
+       },
+
+       // @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);
        },
 
-       getSize: function (zoom) {
-               var s = this.scale(zoom);
-               return L.point(s, s);
+       // @method zoom(scale: Number): Number
+       // Inverse of `scale()`, returns the zoom level corresponding to a scale
+       // factor of `scale`.
+       zoom: function (scale) {
+               return Math.log(scale / 256) / Math.LN2;
+       },
+
+       // @method getProjectedBounds(zoom: Number): Bounds
+       // Returns the projection's bounds scaled and transformed for the provided `zoom`.
+       getProjectedBounds: function (zoom) {
+               if (this.infinite) { return null; }
+
+               var b = this.projection.bounds,
+                   s = this.scale(zoom),
+                   min = this.transformation.transform(b.min, s),
+                   max = this.transformation.transform(b.max, s);
+
+               return L.bounds(min, max);
+       },
+
+       // @method distance(latlng1: LatLng, latlng2: LatLng): Number
+       // Returns the distance between two geographical coordinates.
+
+       // @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 (horizontal) coordinate
+       // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
+       // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
+       //
+       // @property wrapLat: Number[]
+       // Like `wrapLng`, but for the latitude (vertical) axis.
+
+       // wrapLng: [min, max],
+       // wrapLat: [min, max],
+
+       // @property infinite: Boolean
+       // If true, the coordinate space will be unbounded (infinite in both axes)
+       infinite: false,
+
+       // @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,
+                   alt = latlng.alt;
+
+               return L.latLng(lat, lng, alt);
        }
 };
 
 
+
 /*
- * 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). `distance()` returns
+ * simple euclidean distance.
  */
 
 L.CRS.Simple = L.extend({}, L.CRS, {
@@ -1464,26 +2155,73 @@ L.CRS.Simple = L.extend({}, L.CRS, {
 
        scale: function (zoom) {
                return Math.pow(2, zoom);
+       },
+
+       zoom: function (scale) {
+               return Math.log(scale) / Math.LN2;
+       },
+
+       distance: function (latlng1, latlng2) {
+               var dx = latlng2.lng - latlng1.lng,
+                   dy = latlng2.lat - latlng1.lat;
+
+               return Math.sqrt(dx * dx + dy * dy);
+       },
+
+       infinite: true
+});
+
+
+
+/*
+ * @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`. `distance()` returns
+ * meters.
+ */
+
+L.CRS.Earth = L.extend({}, L.CRS, {
+       wrapLng: [-180, 180],
+
+       // Mean Earth Radius, as recommended for use by
+       // the International Union of Geodesy and Geophysics,
+       // see http://rosettacode.org/wiki/Haversine_formula
+       R: 6371000,
+
+       // distance between two geographical points using spherical law of cosines approximation
+       distance: function (latlng1, latlng2) {
+               var rad = Math.PI / 180,
+                   lat1 = latlng1.lat * rad,
+                   lat2 = latlng2.lat * rad,
+                   a = Math.sin(lat1) * Math.sin(lat2) +
+                       Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad);
+
+               return this.R * Math.acos(Math.min(a, 1));
        }
 });
 
 
+
 /*
- * 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, {
+L.CRS.EPSG3857 = L.extend({}, L.CRS.Earth, {
        code: 'EPSG:3857',
-
        projection: L.Projection.SphericalMercator,
-       transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
 
-       project: function (latlng) { // (LatLng) -> Point
-               var projectedPoint = this.projection.project(latlng),
-                   earthRadius = 6378137;
-               return projectedPoint.multiplyBy(earthRadius);
-       }
+       transformation: (function () {
+               var scale = 0.5 / (Math.PI * L.Projection.SphericalMercator.R);
+               return new L.Transformation(scale, 0.5, -scale, 0.5);
+       }())
 });
 
 L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
@@ -1491,44 +2229,125 @@ L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
 });
 
 
+
 /*
- * 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, {
+L.CRS.EPSG4326 = L.extend({}, L.CRS.Earth, {
        code: 'EPSG:4326',
-
        projection: L.Projection.LonLat,
-       transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
+       transformation: new L.Transformation(1 / 180, 1, -1 / 180, 0.5)
 });
 
 
+
 /*
- * 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.Class.extend({
-
-       includes: L.Mixin.Events,
+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,
-               */
-
-               fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
-               trackResize: true,
-               markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
+               // @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,
+
+               // @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 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,
+
+               // @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)
                options = L.setOptions(this, options);
 
-
                this._initContainer(id);
                this._initLayout();
 
@@ -1541,47 +2360,67 @@ L.Map = L.Class.extend({
                        this.setMaxBounds(options.maxBounds);
                }
 
+               if (options.zoom !== undefined) {
+                       this._zoom = this._limitZoom(options.zoom);
+               }
+
                if (options.center && options.zoom !== undefined) {
                        this.setView(L.latLng(options.center), options.zoom, {reset: true});
                }
 
                this._handlers = [];
-
                this._layers = {};
                this._zoomBoundLayers = {};
-               this._tileLayersNum = 0;
+               this._sizeChanged = true;
 
                this.callInitHooks();
 
-               this._addLayers(options.layers);
+               this._addLayers(this.options.layers);
        },
 
 
-       // public methods that modify map state
+       // @section Methods for modifying map state
 
-       // replaced by animation-powered implementation in Map.PanAnimation.js
+       // @method setView(center: LatLng, 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), this._limitZoom(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 = this._limitZoom(zoom);
+                       this._zoom = zoom;
                        return this;
                }
                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) {
-               return this.setZoom(this._zoom + (delta || 1), 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) {
-               return this.setZoom(this._zoom - (delta || 1), 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),
@@ -1593,7 +2432,7 @@ L.Map = L.Class.extend({
                return this.setView(newCenter, zoom, {zoom: options});
        },
 
-       fitBounds: function (bounds, options) {
+       _getBoundsCenterZoom: function (bounds, options) {
 
                options = options || {};
                bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
@@ -1603,7 +2442,7 @@ L.Map = L.Class.extend({
 
                    zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
 
-               zoom = (options.maxZoom) ? Math.min(options.maxZoom, zoom) : zoom;
+               zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
 
                var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
 
@@ -1611,17 +2450,42 @@ L.Map = L.Class.extend({
                    nePoint = this.project(bounds.getNorthEast(), zoom),
                    center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
 
-               return this.setView(center, zoom, options);
+               return {
+                       center: center,
+                       zoom: zoom
+               };
+       },
+
+       // @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) {
+
+               bounds = L.latLngBounds(bounds);
+
+               if (!bounds.isValid()) {
+                       throw new Error('Bounds are not valid.');
+               }
+
+               var target = this._getBoundsCenterZoom(bounds, options);
+               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');
@@ -1632,103 +2496,79 @@ L.Map = L.Class.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);
 
-               this.options.maxBounds = bounds;
-
-               if (!bounds) {
-                       return this.off('moveend', this._panInsideMaxBounds, this);
+               if (!bounds.isValid()) {
+                       this.options.maxBounds = null;
+                       return this.off('moveend', this._panInsideMaxBounds);
+               } else if (this.options.maxBounds) {
+                       this.off('moveend', this._panInsideMaxBounds);
                }
 
+               this.options.maxBounds = bounds;
+
                if (this._loaded) {
                        this._panInsideMaxBounds();
                }
 
-               return this.on('moveend', this._panInsideMaxBounds, this);
-       },
-
-       panInsideBounds: function (bounds, options) {
-               var center = this.getCenter(),
-                       newCenter = this._limitCenter(center, this._zoom, bounds);
-
-               if (center.equals(newCenter)) { return this; }
-
-               return this.panTo(newCenter, options);
+               return this.on('moveend', this._panInsideMaxBounds);
        },
 
-       addLayer: function (layer) {
-               // TODO method is too big, refactor
-
-               var id = L.stamp(layer);
-
-               if (this._layers[id]) { return this; }
-
-               this._layers[id] = layer;
-
-               // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
-               if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) {
-                       this._zoomBoundLayers[id] = layer;
-                       this._updateZoomLevels();
-               }
-
-               // TODO looks ugly, refactor!!!
-               if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
-                       this._tileLayersNum++;
-                       this._tileLayersToLoad++;
-                       layer.on('load', this._onTileLayerLoad, this);
-               }
+       // @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;
 
-               if (this._loaded) {
-                       this._layerAdd(layer);
+               if (this._loaded && this.getZoom() < this.options.minZoom) {
+                       return this.setZoom(zoom);
                }
 
                return this;
        },
 
-       removeLayer: function (layer) {
-               var id = L.stamp(layer);
-
-               if (!this._layers[id]) { return this; }
-
-               if (this._loaded) {
-                       layer.onRemove(this);
-               }
-
-               delete this._layers[id];
-
-               if (this._loaded) {
-                       this.fire('layerremove', {layer: layer});
-               }
-
-               if (this._zoomBoundLayers[id]) {
-                       delete this._zoomBoundLayers[id];
-                       this._updateZoomLevels();
-               }
+       // @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;
 
-               // TODO looks ugly, refactor
-               if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
-                       this._tileLayersNum--;
-                       this._tileLayersToLoad--;
-                       layer.off('load', this._onTileLayerLoad, this);
+               if (this._loaded && (this.getZoom() > this.options.maxZoom)) {
+                       return this.setZoom(zoom);
                }
 
                return this;
        },
 
-       hasLayer: function (layer) {
-               if (!layer) { return false; }
-
-               return (L.stamp(layer) in this._layers);
-       },
+       // @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(),
+                   newCenter = this._limitCenter(center, this._zoom, L.latLngBounds(bounds));
 
-       eachLayer: function (method, context) {
-               for (var i in this._layers) {
-                       method.call(context, this._layers[i]);
+               if (!center.equals(newCenter)) {
+                       this.panTo(newCenter, options);
                }
+
+               this._enforcingBounds = false;
                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; }
 
@@ -1739,7 +2579,7 @@ L.Map = L.Class.extend({
 
                var oldSize = this.getSize();
                this._sizeChanged = true;
-               this._initialCenter = null;
+               this._lastCenter = null;
 
                var newSize = this.getSize(),
                    oldCenter = oldSize.divideBy(2).round(),
@@ -1766,13 +2606,32 @@ L.Map = L.Class.extend({
                        }
                }
 
+               // @section Map state change events
+               // @event resize: ResizeEvent
+               // 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));
+               if (!this.options.zoomSnap) {
+                       this.fire('viewreset');
+               }
+               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; }
 
@@ -1787,46 +2646,85 @@ L.Map = L.Class.extend({
                return this;
        },
 
+       // @method remove(): this
+       // Destroys the map and clears all related event listeners.
        remove: function () {
-               if (this._loaded) {
-                       this.fire('unload');
-               }
 
-               this._initEvents('off');
+               this._initEvents(true);
+
+               if (this._containerId !== this._container._leaflet_id) {
+                       throw new Error('Map container is being reused by another instance');
+               }
 
                try {
                        // throws error in IE6-8
-                       delete this._container._leaflet;
+                       delete this._container._leaflet_id;
+                       delete this._containerId;
                } catch (e) {
-                       this._container._leaflet = undefined;
+                       /*eslint-disable */
+                       this._container._leaflet_id = undefined;
+                       /*eslint-enable */
+                       this._containerId = undefined;
                }
 
-               this._clearPanes();
+               L.DomUtil.remove(this._mapPane);
+
                if (this._clearControlPos) {
                        this._clearControlPos();
                }
 
                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');
+               }
+
+               for (var i in this._layers) {
+                       this._layers[i].remove();
+               }
+
                return this;
        },
 
+       // @section Other Methods
+       // @method createPane(name: String, container?: HTMLElement): HTMLElement
+       // Creates a new [map pane](#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);
 
-       // public methods for getting map state
+               if (name) {
+                       this._panes[name] = pane;
+               }
+               return pane;
+       },
 
-       getCenter: function () { // (Boolean) -> LatLng
+       // @section Methods for Getting Map State
+
+       // @method getCenter(): LatLng
+       // Returns the geographical center of the map view
+       getCenter: function () {
                this._checkIfLoaded();
 
-               if (this._initialCenter && !this._moved()) {
-                       return this._initialCenter;
+               if (this._lastCenter && !this._moved()) {
+                       return this._lastCenter;
                }
                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()),
@@ -1835,47 +2733,51 @@ L.Map = L.Class.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 === undefined ? 0 : this._layersMinZoom) :
-                       this.options.minZoom;
+               return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
        },
 
+       // @method getMaxZoom(): Number
+       // Returns the maximum zoom level of the map (if set in the `maxZoom` 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]);
 
-               var zoom = this.getMinZoom() - (inside ? 1 : 0),
-                   maxZoom = this.getMaxZoom(),
-                   size = this.getSize(),
-
+               var zoom = this.getZoom() || 0,
+                   min = this.getMinZoom(),
+                   max = this.getMaxZoom(),
                    nw = bounds.getNorthWest(),
                    se = bounds.getSouthEast(),
+                   size = this.getSize().subtract(padding),
+                   boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)),
+                   snap = L.Browser.any3d ? this.options.zoomSnap : 1;
 
-                   zoomNotFound = true,
-                   boundsSize;
-
-               padding = L.point(padding || [0, 0]);
-
-               do {
-                       zoom++;
-                       boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
-                       zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;
-
-               } while (zoomNotFound && zoom <= maxZoom);
+               var scale = Math.min(size.x / boundsSize.x, size.y / boundsSize.y);
+               zoom = this.getScaleZoom(scale, zoom);
 
-               if (zoomNotFound && inside) {
-                       return null;
+               if (snap) {
+                       zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
+                       zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
                }
 
-               return inside ? zoom : zoom - 1;
+               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(
@@ -1887,84 +2789,173 @@ L.Map = L.Class.extend({
                return this._size.clone();
        },
 
-       getPixelBounds: function () {
-               var topLeftPoint = this._getTopLeftPoint();
+       // @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._initialTopLeftPoint;
+               return this._pixelOrigin;
        },
 
-       getPanes: function () {
-               return this._panes;
+       // @method getPixelWorldBounds(zoom?: Number): 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);
        },
 
-       getContainer: function () {
-               return this._container;
+       // @section Other Methods
+
+       // @method getPane(pane: String|HTMLElement): HTMLElement
+       // Returns a [map pane](#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](#map-pane) 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
 
-       getZoomScale: function (toZoom) {
+       // @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;
-               return crs.scale(toZoom) / crs.scale(this._zoom);
+               fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
+               return crs.scale(toZoom) / crs.scale(fromZoom);
        },
 
-       getScaleZoom: function (scale) {
-               return this._zoom + (Math.log(scale) / Math.LN2);
+       // @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;
+               var zoom = crs.zoom(scale * crs.scale(fromZoom));
+               return isNaN(zoom) ? Infinity : zoom;
        },
 
-
-       // 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));
        },
@@ -1977,21 +2968,25 @@ L.Map = L.Class.extend({
 
                if (!container) {
                        throw new Error('Map container not found.');
-               } else if (container._leaflet) {
+               } else if (container._leaflet_id) {
                        throw new Error('Map container is already initialized.');
                }
 
-               container._leaflet = true;
+               L.DomEvent.addListener(container, 'scroll', this._onScroll, this);
+               this._containerId = L.Util.stamp(container);
        },
 
        _initLayout: function () {
                var container = this._container;
 
+               this._fadeAnimated = this.options.fadeAnimation && L.Browser.any3d;
+
                L.DomUtil.addClass(container, 'leaflet-container' +
                        (L.Browser.touch ? ' leaflet-touch' : '') +
                        (L.Browser.retina ? ' leaflet-retina' : '') +
                        (L.Browser.ielt9 ? ' leaflet-oldie' : '') +
-                       (this.options.fadeAnimation ? ' leaflet-fade-anim' : ''));
+                       (L.Browser.safari ? ' leaflet-safari' : '') +
+                       (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
 
                var position = L.DomUtil.getStyle(container, 'position');
 
@@ -2008,86 +3003,133 @@ L.Map = L.Class.extend({
 
        _initPanes: function () {
                var panes = this._panes = {};
-
-               this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
-
-               this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
-               panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
-               panes.shadowPane = this._createPane('leaflet-shadow-pane');
-               panes.overlayPane = this._createPane('leaflet-overlay-pane');
-               panes.markerPane = this._createPane('leaflet-marker-pane');
-               panes.popupPane = this._createPane('leaflet-popup-pane');
-
-               var zoomHide = ' leaflet-zoom-hide';
+               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 = 200
+               // Pane for `GridLayer`s and `TileLayer`s
+               this.createPane('tilePane');
+               // @pane overlayPane: HTMLElement = 400
+               // Pane for vector overlays (`Path`s), like `Polyline`s and `Polygon`s
+               this.createPane('shadowPane');
+               // @pane shadowPane: HTMLElement = 500
+               // Pane for overlay shadows (e.g. `Marker` shadows)
+               this.createPane('overlayPane');
+               // @pane markerPane: HTMLElement = 600
+               // Pane for `Icon`s of `Marker`s
+               this.createPane('markerPane');
+               // @pane tooltipPane: HTMLElement = 650
+               // Pane for tooltip.
+               this.createPane('tooltipPane');
+               // @pane popupPane: HTMLElement = 700
+               // Pane for `Popup`s.
+               this.createPane('popupPane');
 
                if (!this.options.markerZoomAnimation) {
-                       L.DomUtil.addClass(panes.markerPane, zoomHide);
-                       L.DomUtil.addClass(panes.shadowPane, zoomHide);
-                       L.DomUtil.addClass(panes.popupPane, zoomHide);
-               }
-       },
-
-       _createPane: function (className, container) {
-               return L.DomUtil.create('div', className, container || this._panes.objectsPane);
-       },
-
-       _clearPanes: function () {
-               this._container.removeChild(this._mapPane);
-       },
-
-       _addLayers: function (layers) {
-               layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
-
-               for (var i = 0, len = layers.length; i < len; i++) {
-                       this.addLayer(layers[i]);
+                       L.DomUtil.addClass(panes.markerPane, 'leaflet-zoom-hide');
+                       L.DomUtil.addClass(panes.shadowPane, 'leaflet-zoom-hide');
                }
        },
 
 
        // private methods that modify map state
 
-       _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
+       // @section Map state change events
+       _resetView: function (center, zoom) {
+               L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
 
-               var zoomChanged = (this._zoom !== zoom);
+               var loading = !this._loaded;
+               this._loaded = true;
+               zoom = this._limitZoom(zoom);
 
-               if (!afterZoomAnim) {
-                       this.fire('movestart');
+               this.fire('viewprereset');
 
-                       if (zoomChanged) {
-                               this.fire('zoomstart');
-                       }
+               var zoomChanged = this._zoom !== zoom;
+               this
+                       ._moveStart(zoomChanged)
+                       ._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');
                }
+       },
 
-               this._zoom = zoom;
-               this._initialCenter = center;
-
-               this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
-
-               if (!preserveMapOffset) {
-                       L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
-               } else {
-                       this._initialTopLeftPoint._add(this._getMapPanePos());
+       _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');
                }
+               return this.fire('movestart');
+       },
 
-               this._tileLayersToLoad = this._tileLayersNum;
-
-               var loading = !this._loaded;
-               this._loaded = true;
+       _move: function (center, zoom, data) {
+               if (zoom === undefined) {
+                       zoom = this._zoom;
+               }
+               var zoomChanged = this._zoom !== zoom;
 
-               this.fire('viewreset', {hard: !preserveMapOffset});
+               this._zoom = zoom;
+               this._lastCenter = center;
+               this._pixelOrigin = this._getNewPixelOrigin(center);
 
-               if (loading) {
-                       this.fire('load');
-                       this.eachLayer(this._layerAdd, this);
+               // @event zoom: Event
+               // Fired repeatedly 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);
                }
 
-               this.fire('move');
+               // @event move: Event
+               // Fired repeatedly during any movement of the map, including pan and
+               // fly animations.
+               return this.fire('move', data);
+       },
 
-               if (zoomChanged || afterZoomAnim) {
+       _moveEnd: function (zoomChanged) {
+               // @event zoomend: Event
+               // Fired when the map has changed, after any animations.
+               if (zoomChanged) {
                        this.fire('zoomend');
                }
 
-               this.fire('moveend', {hard: !preserveMapOffset});
+               // @event moveend: Event
+               // Fired when the center of the map stops changing (e.g. user stopped
+               // dragging the map).
+               return this.fire('moveend');
+       },
+
+       _stop: function () {
+               L.Util.cancelAnimFrame(this._flyToFrame);
+               if (this._panAnim) {
+                       this._panAnim.stop();
+               }
+               return this;
        },
 
        _rawPanBy: function (offset) {
@@ -2098,36 +3140,10 @@ L.Map = L.Class.extend({
                return this.getMaxZoom() - this.getMinZoom();
        },
 
-       _updateZoomLevels: function () {
-               var i,
-                       minZoom = Infinity,
-                       maxZoom = -Infinity,
-                       oldZoomSpan = this._getZoomSpan();
-
-               for (i in this._zoomBoundLayers) {
-                       var layer = this._zoomBoundLayers[i];
-                       if (!isNaN(layer.options.minZoom)) {
-                               minZoom = Math.min(minZoom, layer.options.minZoom);
-                       }
-                       if (!isNaN(layer.options.maxZoom)) {
-                               maxZoom = Math.max(maxZoom, layer.options.maxZoom);
-                       }
-               }
-
-               if (i === undefined) { // we have no tilelayers
-                       this._layersMaxZoom = this._layersMinZoom = undefined;
-               } else {
-                       this._layersMaxZoom = maxZoom;
-                       this._layersMinZoom = minZoom;
-               }
-
-               if (oldZoomSpan !== this._getZoomSpan()) {
-                       this.fire('zoomlevelschange');
-               }
-       },
-
        _panInsideMaxBounds: function () {
-               this.panInsideBounds(this.options.maxBounds);
+               if (!this._enforcingBounds) {
+                       this.panInsideBounds(this.options.maxBounds);
+               }
        },
 
        _checkIfLoaded: function () {
@@ -2136,101 +3152,186 @@ L.Map = L.Class.extend({
                }
        },
 
-       // map events
+       // DOM event handling
 
-       _initEvents: function (onOff) {
+       // @section Interaction events
+       _initEvents: function (remove) {
                if (!L.DomEvent) { return; }
 
-               onOff = onOff || 'on';
-
-               L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this);
-
-               var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
-                             'mouseleave', 'mousemove', 'contextmenu'],
-                   i, len;
-
-               for (i = 0, len = events.length; i < len; i++) {
-                       L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this);
-               }
+               this._targets = {};
+               this._targets[L.stamp(this._container)] = this;
+
+               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: KeyboardEvent
+               // 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);
 
                if (this.options.trackResize) {
                        L.DomEvent[onOff](window, 'resize', this._onResize, this);
                }
+
+               if (L.Browser.any3d && this.options.transform3DLimit) {
+                       this[onOff]('moveend', this._onMoveEnd);
+               }
        },
 
        _onResize: function () {
                L.Util.cancelAnimFrame(this._resizeRequest);
                this._resizeRequest = L.Util.requestAnimFrame(
-                       function () { this.invalidateSize({debounceMoveend: true}); }, this, false, this._container);
+                       function () { this.invalidateSize({debounceMoveend: true}); }, this);
+       },
+
+       _onScroll: function () {
+               this._container.scrollTop  = 0;
+               this._container.scrollLeft = 0;
+       },
+
+       _onMoveEnd: function () {
+               var pos = this._getMapPanePos();
+               if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
+                       // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
+                       // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
+                       this._resetView(this.getCenter(), this.getZoom());
+               }
        },
 
-       _onMouseClick: function (e) {
-               if (!this._loaded || (!e._simulated &&
-                       ((this.dragging && this.dragging.moved()) ||
-                        (this.boxZoom  && this.boxZoom.moved()))) ||
-                           L.DomEvent._skipped(e)) { return; }
+       _findEventTargets: function (e, type) {
+               var targets = [],
+                   target,
+                   isHover = type === 'mouseout' || type === 'mouseover',
+                   src = e.target || e.srcElement,
+                   dragging = false;
 
-               this.fire('preclick');
-               this._fireMouseEvent(e);
+               while (src) {
+                       target = this._targets[L.stamp(src)];
+                       if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
+                               // Prevent firing click after you just dragged an object.
+                               dragging = true;
+                               break;
+                       }
+                       if (target && target.listens(type, true)) {
+                               if (isHover && !L.DomEvent._isExternalTarget(src, e)) { break; }
+                               targets.push(target);
+                               if (isHover) { break; }
+                       }
+                       if (src === this._container) { break; }
+                       src = src.parentNode;
+               }
+               if (!targets.length && !dragging && !isHover && L.DomEvent._isExternalTarget(src, e)) {
+                       targets = [this];
+               }
+               return targets;
        },
 
-       _fireMouseEvent: function (e) {
+       _handleDOMEvent: function (e) {
                if (!this._loaded || L.DomEvent._skipped(e)) { return; }
 
-               var type = e.type;
+               var type = e.type === 'keypress' && e.keyCode === 13 ? 'click' : e.type;
+
+               if (type === 'mousedown') {
+                       // prevents outline when clicking on keyboard-focusable element
+                       L.DomUtil.preventOutline(e.target || e.srcElement);
+               }
 
-               type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
+               this._fireDOMEvent(e, type);
+       },
 
-               if (!this.hasEventListeners(type)) { return; }
+       _fireDOMEvent: function (e, type, targets) {
 
-               if (type === 'contextmenu') {
-                       L.DomEvent.preventDefault(e);
+               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._fireDOMEvent(synth, synth.type, targets);
                }
 
-               var containerPoint = this.mouseEventToContainerPoint(e),
-                   layerPoint = this.containerPointToLayerPoint(containerPoint),
-                   latlng = this.layerPointToLatLng(layerPoint);
+               if (e._stopped) { return; }
 
-               this.fire(type, {
-                       latlng: latlng,
-                       layerPoint: layerPoint,
-                       containerPoint: containerPoint,
+               // Find the layer the event is propagating from and its parents.
+               targets = (targets || []).concat(this._findEventTargets(e, type));
+
+               if (!targets.length) { return; }
+
+               var target = targets[0];
+               if (type === 'contextmenu' && target.listens(type, true)) {
+                       L.DomEvent.preventDefault(e);
+               }
+
+               var data = {
                        originalEvent: e
-               });
-       },
+               };
+
+               if (e.type !== 'keypress') {
+                       var isMarker = target instanceof L.Marker;
+                       data.containerPoint = isMarker ?
+                                       this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
+                       data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
+                       data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
+               }
 
-       _onTileLayerLoad: function () {
-               this._tileLayersToLoad--;
-               if (this._tileLayersNum && !this._tileLayersToLoad) {
-                       this.fire('tilelayersload');
+               for (var i = 0; i < targets.length; i++) {
+                       targets[i].fire(type, data, true);
+                       if (data.originalEvent._stopped ||
+                               (targets[i].options.nonBubblingEvents && L.Util.indexOf(targets[i].options.nonBubblingEvents, type) !== -1)) { return; }
                }
        },
 
+       _draggableMoved: function (obj) {
+               obj = obj.dragging && obj.dragging.enabled() ? obj : this;
+               return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
+       },
+
        _clearHandlers: function () {
                for (var i = 0, len = this._handlers.length; i < len; i++) {
                        this._handlers[i].disable();
                }
        },
 
+       // @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, this);
+                       callback.call(context || this, {target: this});
                } else {
                        this.on('load', callback, context);
                }
                return this;
        },
 
-       _layerAdd: function (layer) {
-               layer.onAdd(this);
-               this.fire('layeradd', {layer: layer});
-       },
-
 
        // private methods for getting map state
 
        _getMapPanePos: function () {
-               return L.DomUtil.getPosition(this._mapPane);
+               return L.DomUtil.getPosition(this._mapPane) || new L.Point(0, 0);
        },
 
        _moved: function () {
@@ -2238,19 +3339,21 @@ L.Map = L.Class.extend({
                return pos && !pos.equals([0, 0]);
        },
 
-       _getTopLeftPoint: function () {
-               return this.getPixelOrigin().subtract(this._getMapPanePos());
+       _getTopLeftPoint: function (center, zoom) {
+               var pixelOrigin = center && zoom !== undefined ?
+                       this._getNewPixelOrigin(center, zoom) :
+                       this.getPixelOrigin();
+               return pixelOrigin.subtract(this._getMapPanePos());
        },
 
-       _getNewTopLeftPoint: function (center, zoom) {
+       _getNewPixelOrigin: function (center, zoom) {
                var viewHalf = this.getSize()._divideBy(2);
-               // TODO round on display, not calculation to increase precision?
-               return this.project(center, zoom)._subtract(viewHalf)._round();
+               return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
        },
 
-       _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
-               var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
-               return this.project(latlng, newZoom)._subtract(topLeft);
+       _latLngToNewLayerPoint: function (latlng, zoom, center) {
+               var topLeft = this._getNewPixelOrigin(center, zoom);
+               return this.project(latlng, zoom)._subtract(topLeft);
        },
 
        // layer point of the current center
@@ -2273,6 +3376,13 @@ L.Map = L.Class.extend({
                    viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
                    offset = this._getBoundsOffset(viewBounds, bounds, zoom);
 
+               // If offset is less than a pixel, ignore.
+               // This prevents unstable projections from getting into
+               // an infinite loop of tiny offsets.
+               if (offset.round().equals([0, 0])) {
+                       return center;
+               }
+
                return this.unproject(centerPoint.add(offset), zoom);
        },
 
@@ -2288,11 +3398,15 @@ L.Map = L.Class.extend({
 
        // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
        _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
-               var nwOffset = this.project(maxBounds.getNorthWest(), zoom).subtract(pxBounds.min),
-                   seOffset = this.project(maxBounds.getSouthEast(), zoom).subtract(pxBounds.max),
+               var projectedMaxBounds = L.bounds(
+                       this.project(maxBounds.getNorthEast(), zoom),
+                       this.project(maxBounds.getSouthWest(), zoom)
+                   ),
+                   minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
+                   maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
 
-                   dx = this._rebound(nwOffset.x, -seOffset.x),
-                   dy = this._rebound(nwOffset.y, -seOffset.y);
+                   dx = this._rebound(minOffset.x, -maxOffset.x),
+                   dy = this._rebound(minOffset.y, -maxOffset.y);
 
                return new L.Point(dx, dy);
        },
@@ -2305,1941 +3419,3589 @@ L.Map = L.Class.extend({
 
        _limitZoom: function (zoom) {
                var min = this.getMinZoom(),
-                   max = this.getMaxZoom();
-
+                   max = this.getMaxZoom(),
+                   snap = L.Browser.any3d ? this.options.zoomSnap : 1;
+               if (snap) {
+                       zoom = Math.round(zoom / snap) * snap;
+               }
                return Math.max(min, Math.min(max, zoom));
        }
 });
 
+// @section
+
+// @factory L.map(id: String, options?: Map options)
+// Instantiates a map object given the DOM ID of a `<div>` 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 `<div>` HTML element
+// and optionally an object literal with `Map options`.
 L.map = function (id, options) {
        return new L.Map(id, options);
 };
 
 
-/*
- * 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.
- */
-
-L.Projection.Mercator = {
-       MAX_LATITUDE: 85.0840591556,
-
-       R_MINOR: 6356752.314245179,
-       R_MAJOR: 6378137,
-
-       project: function (latlng) { // (LatLng) -> Point
-               var d = L.LatLng.DEG_TO_RAD,
-                   max = this.MAX_LATITUDE,
-                   lat = Math.max(Math.min(max, latlng.lat), -max),
-                   r = this.R_MAJOR,
-                   r2 = this.R_MINOR,
-                   x = latlng.lng * d * r,
-                   y = lat * d,
-                   tmp = r2 / r,
-                   eccent = Math.sqrt(1.0 - tmp * tmp),
-                   con = eccent * Math.sin(y);
-
-               con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
-
-               var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
-               y = -r * Math.log(ts);
-
-               return new L.Point(x, y);
-       },
-
-       unproject: function (point) { // (Point, Boolean) -> LatLng
-               var d = L.LatLng.RAD_TO_DEG,
-                   r = this.R_MAJOR,
-                   r2 = this.R_MINOR,
-                   lng = point.x * d / r,
-                   tmp = r2 / r,
-                   eccent = Math.sqrt(1 - (tmp * tmp)),
-                   ts = Math.exp(- point.y / r),
-                   phi = (Math.PI / 2) - 2 * Math.atan(ts),
-                   numIter = 15,
-                   tol = 1e-7,
-                   i = numIter,
-                   dphi = 0.1,
-                   con;
-
-               while ((Math.abs(dphi) > tol) && (--i > 0)) {
-                       con = eccent * Math.sin(phi);
-                       dphi = (Math.PI / 2) - 2 * Math.atan(ts *
-                                   Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
-                       phi += dphi;
-               }
-
-               return new L.LatLng(phi * d, lng);
-       }
-};
-
 
 
-L.CRS.EPSG3395 = L.extend({}, L.CRS, {
-       code: 'EPSG:3395',
+/*
+ * @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
+ */
 
-       projection: L.Projection.Mercator,
 
-       transformation: (function () {
-               var m = L.Projection.Mercator,
-                   r = m.R_MAJOR,
-                   scale = 0.5 / (Math.PI * r);
+L.Layer = L.Evented.extend({
 
-               return new L.Transformation(scale, 0.5, -scale, 0.5);
-       }())
-});
+       // 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);
+       },
 
-/*
- * L.TileLayer is used for standard xyz-numbered tile layers.
- */
+       // @method removeFrom(map: Map): this
+       // Removes the layer from the given map
+       removeFrom: function (obj) {
+               if (obj) {
+                       obj.removeLayer(this);
+               }
+               return this;
+       },
 
-L.TileLayer = L.Class.extend({
-       includes: L.Mixin.Events,
+       // @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);
+       },
 
-       options: {
-               minZoom: 0,
-               maxZoom: 18,
-               tileSize: 256,
-               subdomains: 'abc',
-               errorTileUrl: '',
-               attribution: '',
-               zoomOffset: 0,
-               opacity: 1,
-               /*
-               maxNativeZoom: null,
-               zIndex: null,
-               tms: false,
-               continuousWorld: false,
-               noWrap: false,
-               zoomReverse: false,
-               detectRetina: false,
-               reuseTiles: false,
-               bounds: false,
-               */
-               unloadInvisibleTiles: L.Browser.mobile,
-               updateWhenIdle: L.Browser.mobile
+       addInteractiveTarget: function (targetEl) {
+               this._map._targets[L.stamp(targetEl)] = this;
+               return this;
        },
 
-       initialize: function (url, options) {
-               options = L.setOptions(this, options);
+       removeInteractiveTarget: function (targetEl) {
+               delete this._map._targets[L.stamp(targetEl)];
+               return this;
+       },
 
-               // detecting retina displays, adjusting tileSize and zoom levels
-               if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
+       _layerAdd: function (e) {
+               var map = e.target;
 
-                       options.tileSize = Math.floor(options.tileSize / 2);
-                       options.zoomOffset++;
+               // check in case layer gets added and then removed before the map is ready
+               if (!map.hasLayer(this)) { return; }
 
-                       if (options.minZoom > 0) {
-                               options.minZoom--;
-                       }
-                       this.options.maxZoom--;
-               }
+               this._map = map;
+               this._zoomAnimated = map._zoomAnimated;
 
-               if (options.bounds) {
-                       options.bounds = L.latLngBounds(options.bounds);
+               if (this.getEvents) {
+                       var events = this.getEvents();
+                       map.on(events, this);
+                       this.once('remove', function () {
+                               map.off(events, this);
+                       }, this);
                }
 
-               this._url = url;
-
-               var subdomains = this.options.subdomains;
+               this.onAdd(map);
 
-               if (typeof subdomains === 'string') {
-                       this.options.subdomains = subdomains.split('');
+               if (this.getAttribution && this._map.attributionControl) {
+                       this._map.attributionControl.addAttribution(this.getAttribution());
                }
-       },
 
-       onAdd: function (map) {
-               this._map = map;
-               this._animated = map._zoomAnimated;
+               this.fire('add');
+               map.fire('layeradd', {layer: this});
+       }
+});
 
-               // create a container div for tiles
-               this._initContainer();
+/* @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`](#evented-addeventlistener). The event handlers in this object 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.
+ */
 
-               // set up events
-               map.on({
-                       'viewreset': this._reset,
-                       'moveend': this._update
-               }, this);
 
-               if (this._animated) {
-                       map.on({
-                               'zoomanim': this._animateZoom,
-                               'zoomend': this._endZoomAnim
-                       }, this);
-               }
+/* @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 this; }
+               this._layers[id] = layer;
 
-               if (!this.options.updateWhenIdle) {
-                       this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
-                       map.on('move', this._limitedUpdate, this);
+               layer._mapToAdd = this;
+
+               if (layer.beforeAdd) {
+                       layer.beforeAdd(this);
                }
 
-               this._reset();
-               this._update();
-       },
+               this.whenReady(layer._layerAdd, layer);
 
-       addTo: function (map) {
-               map.addLayer(this);
                return this;
        },
 
-       onRemove: function (map) {
-               this._container.parentNode.removeChild(this._container);
+       // @method removeLayer(layer: Layer): this
+       // Removes the given layer from the map.
+       removeLayer: function (layer) {
+               var id = L.stamp(layer);
 
-               map.off({
-                       'viewreset': this._reset,
-                       'moveend': this._update
-               }, this);
+               if (!this._layers[id]) { return this; }
 
-               if (this._animated) {
-                       map.off({
-                               'zoomanim': this._animateZoom,
-                               'zoomend': this._endZoomAnim
-                       }, this);
+               if (this._loaded) {
+                       layer.onRemove(this);
                }
 
-               if (!this.options.updateWhenIdle) {
-                       map.off('move', this._limitedUpdate, this);
+               if (layer.getAttribution && this.attributionControl) {
+                       this.attributionControl.removeAttribution(layer.getAttribution());
                }
 
-               this._container = null;
-               this._map = null;
-       },
-
-       bringToFront: function () {
-               var pane = this._map._panes.tilePane;
+               delete this._layers[id];
 
-               if (this._container) {
-                       pane.appendChild(this._container);
-                       this._setAutoZIndex(pane, Math.max);
+               if (this._loaded) {
+                       this.fire('layerremove', {layer: layer});
+                       layer.fire('remove');
                }
 
+               layer._map = layer._mapToAdd = null;
+
                return this;
        },
 
-       bringToBack: function () {
-               var pane = this._map._panes.tilePane;
+       // @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);
+       },
 
-               if (this._container) {
-                       pane.insertBefore(this._container, pane.firstChild);
-                       this._setAutoZIndex(pane, Math.min);
+       /* @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]);
                }
-
                return this;
        },
 
-       getAttribution: function () {
-               return this.options.attribution;
-       },
+       _addLayers: function (layers) {
+               layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
 
-       getContainer: function () {
-               return this._container;
+               for (var i = 0, len = layers.length; i < len; i++) {
+                       this.addLayer(layers[i]);
+               }
        },
 
-       setOpacity: function (opacity) {
-               this.options.opacity = opacity;
-
-               if (this._map) {
-                       this._updateOpacity();
+       _addZoomLimit: function (layer) {
+               if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
+                       this._zoomBoundLayers[L.stamp(layer)] = layer;
+                       this._updateZoomLevels();
                }
-
-               return this;
        },
 
-       setZIndex: function (zIndex) {
-               this.options.zIndex = zIndex;
-               this._updateZIndex();
+       _removeZoomLimit: function (layer) {
+               var id = L.stamp(layer);
 
-               return this;
+               if (this._zoomBoundLayers[id]) {
+                       delete this._zoomBoundLayers[id];
+                       this._updateZoomLevels();
+               }
        },
 
-       setUrl: function (url, noRedraw) {
-               this._url = url;
+       _updateZoomLevels: function () {
+               var minZoom = Infinity,
+                   maxZoom = -Infinity,
+                   oldZoomSpan = this._getZoomSpan();
 
-               if (!noRedraw) {
-                       this.redraw();
+               for (var i in this._zoomBoundLayers) {
+                       var options = this._zoomBoundLayers[i].options;
+
+                       minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
+                       maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
                }
 
-               return this;
-       },
+               this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
+               this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
 
-       redraw: function () {
-               if (this._map) {
-                       this._reset({hard: true});
-                       this._update();
+               // @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');
                }
-               return this;
-       },
+       }
+});
+
 
-       _updateZIndex: function () {
-               if (this._container && this.options.zIndex !== undefined) {
-                       this._container.style.zIndex = this.options.zIndex;
-               }
-       },
 
-       _setAutoZIndex: function (pane, compare) {
+/*
+ * @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.
+ */
 
-               var layers = pane.children,
-                   edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
-                   zIndex, i, len;
+L.Projection.Mercator = {
+       R: 6378137,
+       R_MINOR: 6356752.314245179,
 
-               for (i = 0, len = layers.length; i < len; i++) {
+       bounds: L.bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
 
-                       if (layers[i] !== this._container) {
-                               zIndex = parseInt(layers[i].style.zIndex, 10);
+       project: function (latlng) {
+               var d = Math.PI / 180,
+                   r = this.R,
+                   y = latlng.lat * d,
+                   tmp = this.R_MINOR / r,
+                   e = Math.sqrt(1 - tmp * tmp),
+                   con = e * Math.sin(y);
 
-                               if (!isNaN(zIndex)) {
-                                       edgeZIndex = compare(edgeZIndex, zIndex);
-                               }
-                       }
-               }
+               var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
+               y = -r * Math.log(Math.max(ts, 1E-10));
 
-               this.options.zIndex = this._container.style.zIndex =
-                       (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
+               return new L.Point(latlng.lng * d * r, y);
        },
 
-       _updateOpacity: function () {
-               var i,
-                   tiles = this._tiles;
-
-               if (L.Browser.ielt9) {
-                       for (i in tiles) {
-                               L.DomUtil.setOpacity(tiles[i], this.options.opacity);
-                       }
-               } else {
-                       L.DomUtil.setOpacity(this._container, this.options.opacity);
+       unproject: function (point) {
+               var d = 180 / Math.PI,
+                   r = this.R,
+                   tmp = this.R_MINOR / r,
+                   e = Math.sqrt(1 - tmp * tmp),
+                   ts = Math.exp(-point.y / r),
+                   phi = Math.PI / 2 - 2 * Math.atan(ts);
+
+               for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
+                       con = e * Math.sin(phi);
+                       con = Math.pow((1 - con) / (1 + con), e / 2);
+                       dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
+                       phi += dphi;
                }
-       },
 
-       _initContainer: function () {
-               var tilePane = this._map._panes.tilePane;
+               return new L.LatLng(phi * d, point.x * d / r);
+       }
+};
 
-               if (!this._container) {
-                       this._container = L.DomUtil.create('div', 'leaflet-layer');
 
-                       this._updateZIndex();
 
-                       if (this._animated) {
-                               var className = 'leaflet-tile-container';
+/*
+ * @namespace CRS
+ * @crs L.CRS.EPSG3395
+ *
+ * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
+ */
 
-                               this._bgBuffer = L.DomUtil.create('div', className, this._container);
-                               this._tileContainer = L.DomUtil.create('div', className, this._container);
+L.CRS.EPSG3395 = L.extend({}, L.CRS.Earth, {
+       code: 'EPSG:3395',
+       projection: L.Projection.Mercator,
 
-                       } else {
-                               this._tileContainer = this._container;
-                       }
+       transformation: (function () {
+               var scale = 0.5 / (Math.PI * L.Projection.Mercator.R);
+               return new L.Transformation(scale, 0.5, -scale, 0.5);
+       }())
+});
 
-                       tilePane.appendChild(this._container);
 
-                       if (this.options.opacity < 1) {
-                               this._updateOpacity();
-                       }
-               }
-       },
 
-       _reset: function (e) {
-               for (var key in this._tiles) {
-                       this.fire('tileunload', {tile: this._tiles[key]});
-               }
+/*
+ * @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 `<canvas>`, `<img>` or `<div>`. GridLayer will handle creating and animating these DOM elements for you.
+ *
+ *
+ * @section Synchronous usage
+ * @example
+ *
+ * To create a custom layer, extend GridLayer and implement 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 <canvas> 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 = tile.getContext('2d');
+ *
+ *         // return the tile so it can be rendered on screen
+ *         return tile;
+ *     }
+ * });
+ * ```
+ *
+ * @section Asynchronous usage
+ * @example
+ *
+ * Tile creation can also be asynchronous, this is useful when using a third-party drawing library. Once the tile is finished drawing it can be passed to the `done()` callback.
+ *
+ * ```js
+ * var CanvasLayer = L.GridLayer.extend({
+ *     createTile: function(coords, done){
+ *         var error;
+ *
+ *         // create a <canvas> 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 asynchronously and pass the tile to the done() callback
+ *         setTimeout(function() {
+ *             done(error, tile);
+ *         }, 1000);
+ *
+ *         return tile;
+ *     }
+ * });
+ * ```
+ *
+ * @section
+ */
 
-               this._tiles = {};
-               this._tilesToLoad = 0;
 
-               if (this.options.reuseTiles) {
-                       this._unusedTiles = [];
-               }
+L.GridLayer = L.Layer.extend({
 
-               this._tileContainer.innerHTML = '';
+       // @section
+       // @aka GridLayer options
+       options: {
+               // @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,
 
-               if (this._animated && e && e.hard) {
-                       this._clearBgBuffer();
-               }
+               // @option opacity: Number = 1.0
+               // Opacity of the tiles. Can be used in the `createTile()` function.
+               opacity: 1,
 
-               this._initContainer();
-       },
+               // @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,
 
-       _getTileSize: function () {
-               var map = this._map,
-                   zoom = map.getZoom() + this.options.zoomOffset,
-                   zoomN = this.options.maxNativeZoom,
-                   tileSize = this.options.tileSize;
+               // @option updateWhenZooming: Boolean = true
+               // By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends.
+               updateWhenZooming: true,
 
-               if (zoomN && zoom > zoomN) {
-                       tileSize = Math.round(map.getZoomScale(zoom) / map.getZoomScale(zoomN) * tileSize);
-               }
+               // @option updateInterval: Number = 200
+               // Tiles will not update more than once every `updateInterval` milliseconds when panning.
+               updateInterval: 200,
 
-               return tileSize;
-       },
+               // @option attribution: String = null
+               // String to be shown in the attribution control, describes the layer data, e.g. "© Mapbox".
+               attribution: null,
 
-       _update: function () {
+               // @option zIndex: Number = 1
+               // The explicit zIndex of the tile layer.
+               zIndex: 1,
 
-               if (!this._map) { return; }
+               // @option bounds: LatLngBounds = undefined
+               // If set, tiles will only be loaded inside the set `LatLngBounds`.
+               bounds: null,
 
-               var map = this._map,
-                   bounds = map.getPixelBounds(),
-                   zoom = map.getZoom(),
-                   tileSize = this._getTileSize();
+               // @option minZoom: Number = 0
+               // The minimum zoom level that tiles will be loaded at. By default the entire map.
+               minZoom: 0,
 
-               if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
-                       return;
-               }
+               // @option maxZoom: Number = undefined
+               // The maximum zoom level that tiles will be loaded at.
+               maxZoom: undefined,
 
-               var tileBounds = L.bounds(
-                       bounds.min.divideBy(tileSize)._floor(),
-                       bounds.max.divideBy(tileSize)._floor());
+               // @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. Has no
+               // effect when the [map CRS](#map-crs) doesn't wrap around.
+               noWrap: false,
 
-               this._addTilesFromCenterOut(tileBounds);
+               // @option pane: String = 'tilePane'
+               // `Map pane` where the grid layer will be added.
+               pane: 'tilePane',
 
-               if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
-                       this._removeOtherTiles(tileBounds);
-               }
-       },
+               // @option className: String = ''
+               // A custom class name to assign to the tile layer. Empty by default.
+               className: '',
 
-       _addTilesFromCenterOut: function (bounds) {
-               var queue = [],
-                   center = bounds.getCenter();
+               // @option keepBuffer: Number = 2
+               // When panning the map, keep this many rows and columns of tiles before unloading them.
+               keepBuffer: 2
+       },
 
-               var j, i, point;
+       initialize: function (options) {
+               L.setOptions(this, options);
+       },
 
-               for (j = bounds.min.y; j <= bounds.max.y; j++) {
-                       for (i = bounds.min.x; i <= bounds.max.x; i++) {
-                               point = new L.Point(i, j);
+       onAdd: function () {
+               this._initContainer();
 
-                               if (this._tileShouldBeLoaded(point)) {
-                                       queue.push(point);
-                               }
-                       }
-               }
+               this._levels = {};
+               this._tiles = {};
 
-               var tilesToLoad = queue.length;
+               this._resetView();
+               this._update();
+       },
 
-               if (tilesToLoad === 0) { return; }
+       beforeAdd: function (map) {
+               map._addZoomLimit(this);
+       },
 
-               // load tiles in order of their distance to center
-               queue.sort(function (a, b) {
-                       return a.distanceTo(center) - b.distanceTo(center);
-               });
+       onRemove: function (map) {
+               this._removeAllTiles();
+               L.DomUtil.remove(this._container);
+               map._removeZoomLimit(this);
+               this._container = null;
+               this._tileZoom = null;
+       },
 
-               var fragment = document.createDocumentFragment();
+       // @method bringToFront: this
+       // Brings the tile layer to the top of all tile layers.
+       bringToFront: function () {
+               if (this._map) {
+                       L.DomUtil.toFront(this._container);
+                       this._setAutoZIndex(Math.max);
+               }
+               return this;
+       },
 
-               // if its the first batch of tiles to load
-               if (!this._tilesToLoad) {
-                       this.fire('loading');
+       // @method bringToBack: this
+       // Brings the tile layer to the bottom of all tile layers.
+       bringToBack: function () {
+               if (this._map) {
+                       L.DomUtil.toBack(this._container);
+                       this._setAutoZIndex(Math.min);
                }
+               return this;
+       },
 
-               this._tilesToLoad += tilesToLoad;
+       // @method getAttribution: String
+       // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
+       getAttribution: function () {
+               return this.options.attribution;
+       },
 
-               for (i = 0; i < tilesToLoad; i++) {
-                       this._addTile(queue[i], fragment);
-               }
+       // @method getContainer: HTMLElement
+       // Returns the HTML element that contains the tiles for this layer.
+       getContainer: function () {
+               return this._container;
+       },
 
-               this._tileContainer.appendChild(fragment);
+       // @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;
        },
 
-       _tileShouldBeLoaded: function (tilePoint) {
-               if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
-                       return false; // already loaded
-               }
+       // @method setZIndex(zIndex: Number): this
+       // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
+       setZIndex: function (zIndex) {
+               this.options.zIndex = zIndex;
+               this._updateZIndex();
 
-               var options = this.options;
+               return this;
+       },
 
-               if (!options.continuousWorld) {
-                       var limit = this._getWrapTileNum();
+       // @method isLoading: Boolean
+       // Returns `true` if any tile in the grid layer has not finished loading.
+       isLoading: function () {
+               return this._loading;
+       },
 
-                       // don't load if exceeds world bounds
-                       if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit.x)) ||
-                               tilePoint.y < 0 || tilePoint.y >= limit.y) { return false; }
+       // @method redraw: this
+       // Causes the layer to clear all the tiles and request them again.
+       redraw: function () {
+               if (this._map) {
+                       this._removeAllTiles();
+                       this._update();
                }
+               return this;
+       },
 
-               if (options.bounds) {
-                       var tileSize = this._getTileSize(),
-                           nwPoint = tilePoint.multiplyBy(tileSize),
-                           sePoint = nwPoint.add([tileSize, tileSize]),
-                           nw = this._map.unproject(nwPoint),
-                           se = this._map.unproject(sePoint);
+       getEvents: function () {
+               var events = {
+                       viewprereset: this._invalidateAll,
+                       viewreset: this._resetView,
+                       zoom: this._resetView,
+                       moveend: this._onMoveEnd
+               };
 
-                       // TODO temporary hack, will be removed after refactoring projections
-                       // https://github.com/Leaflet/Leaflet/issues/1618
-                       if (!options.continuousWorld && !options.noWrap) {
-                               nw = nw.wrap();
-                               se = se.wrap();
+               if (!this.options.updateWhenIdle) {
+                       // update tiles on move, but not more often than once per given interval
+                       if (!this._onMove) {
+                               this._onMove = L.Util.throttle(this._onMoveEnd, this.options.updateInterval, this);
                        }
 
-                       if (!options.bounds.intersects([nw, se])) { return false; }
+                       events.move = this._onMove;
                }
 
-               return true;
+               if (this._zoomAnimated) {
+                       events.zoomanim = this._animateZoom;
+               }
+
+               return events;
        },
 
-       _removeOtherTiles: function (bounds) {
-               var kArr, x, y, key;
+       // @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');
+       },
 
-               for (key in this._tiles) {
-                       kArr = key.split(':');
-                       x = parseInt(kArr[0], 10);
-                       y = parseInt(kArr[1], 10);
+       // @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);
+       },
 
-                       // remove tile if it's out of bounds
-                       if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
-                               this._removeTile(key);
-                       }
+       _updateZIndex: function () {
+               if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
+                       this._container.style.zIndex = this.options.zIndex;
                }
        },
 
-       _removeTile: function (key) {
-               var tile = this._tiles[key];
+       _setAutoZIndex: function (compare) {
+               // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
 
-               this.fire('tileunload', {tile: tile, url: tile.src});
+               var layers = this.getPane().children,
+                   edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
 
-               if (this.options.reuseTiles) {
-                       L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
-                       this._unusedTiles.push(tile);
+               for (var i = 0, len = layers.length, zIndex; i < len; i++) {
 
-               } else if (tile.parentNode === this._tileContainer) {
-                       this._tileContainer.removeChild(tile);
-               }
+                       zIndex = layers[i].style.zIndex;
 
-               // for https://github.com/CloudMade/Leaflet/issues/137
-               if (!L.Browser.android) {
-                       tile.onload = null;
-                       tile.src = L.Util.emptyImageUrl;
+                       if (layers[i] !== this._container && zIndex) {
+                               edgeZIndex = compare(edgeZIndex, +zIndex);
+                       }
                }
 
-               delete this._tiles[key];
+               if (isFinite(edgeZIndex)) {
+                       this.options.zIndex = edgeZIndex + compare(-1, 1);
+                       this._updateZIndex();
+               }
        },
 
-       _addTile: function (tilePoint, container) {
-               var tilePos = this._getTilePos(tilePoint);
+       _updateOpacity: function () {
+               if (!this._map) { return; }
+
+               // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
+               if (L.Browser.ielt9) { return; }
 
-               // get unused tile - or create a new tile
-               var tile = this._getTile();
+               L.DomUtil.setOpacity(this._container, this.options.opacity);
 
-               /*
-               Chrome 20 layouts much faster with top/left (verify with timeline, frames)
-               Android 4 browser has display issues with top/left and requires transform instead
-               (other browsers don't currently care) - see debug/hacks/jitter.html for an example
-               */
-               L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome);
+               var now = +new Date(),
+                   nextFrame = false,
+                   willPrune = false;
+
+               for (var key in this._tiles) {
+                       var tile = this._tiles[key];
+                       if (!tile.current || !tile.loaded) { continue; }
+
+                       var fade = Math.min(1, (now - tile.loaded) / 200);
 
-               this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
+                       L.DomUtil.setOpacity(tile.el, fade);
+                       if (fade < 1) {
+                               nextFrame = true;
+                       } else {
+                               if (tile.active) { willPrune = true; }
+                               tile.active = true;
+                       }
+               }
 
-               this._loadTile(tile, tilePoint);
+               if (willPrune && !this._noPrune) { this._pruneTiles(); }
 
-               if (tile.parentNode !== this._tileContainer) {
-                       container.appendChild(tile);
+               if (nextFrame) {
+                       L.Util.cancelAnimFrame(this._fadeFrame);
+                       this._fadeFrame = L.Util.requestAnimFrame(this._updateOpacity, this);
                }
        },
 
-       _getZoomForUrl: function () {
+       _initContainer: function () {
+               if (this._container) { return; }
 
-               var options = this.options,
-                   zoom = this._map.getZoom();
+               this._container = L.DomUtil.create('div', 'leaflet-layer ' + (this.options.className || ''));
+               this._updateZIndex();
 
-               if (options.zoomReverse) {
-                       zoom = options.maxZoom - zoom;
+               if (this.options.opacity < 1) {
+                       this._updateOpacity();
                }
 
-               zoom += options.zoomOffset;
-
-               return options.maxNativeZoom ? Math.min(zoom, options.maxNativeZoom) : zoom;
+               this.getPane().appendChild(this._container);
        },
 
-       _getTilePos: function (tilePoint) {
-               var origin = this._map.getPixelOrigin(),
-                   tileSize = this._getTileSize();
+       _updateLevels: function () {
 
-               return tilePoint.multiplyBy(tileSize).subtract(origin);
-       },
+               var zoom = this._tileZoom,
+                   maxZoom = this.options.maxZoom;
 
-       // image-specific code (override to implement e.g. Canvas or SVG tile layer)
+               if (zoom === undefined) { return undefined; }
 
-       getTileUrl: function (tilePoint) {
-               return L.Util.template(this._url, L.extend({
-                       s: this._getSubdomain(tilePoint),
-                       z: tilePoint.z,
-                       x: tilePoint.x,
-                       y: tilePoint.y
-               }, this.options));
-       },
+               for (var z in this._levels) {
+                       if (this._levels[z].el.children.length || z === zoom) {
+                               this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
+                       } else {
+                               L.DomUtil.remove(this._levels[z].el);
+                               this._removeTilesAtZoom(z);
+                               delete this._levels[z];
+                       }
+               }
 
-       _getWrapTileNum: function () {
-               var crs = this._map.options.crs,
-                   size = crs.getSize(this._map.getZoom());
-               return size.divideBy(this._getTileSize())._floor();
+               var level = this._levels[zoom],
+                   map = this._map;
+
+               if (!level) {
+                       level = this._levels[zoom] = {};
+
+                       level.el = L.DomUtil.create('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
+                       level.el.style.zIndex = maxZoom;
+
+                       level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
+                       level.zoom = zoom;
+
+                       this._setZoomTransform(level, map.getCenter(), map.getZoom());
+
+                       // force the browser to consider the newly added element for transition
+                       L.Util.falseFn(level.el.offsetWidth);
+               }
+
+               this._level = level;
+
+               return level;
        },
 
-       _adjustTilePoint: function (tilePoint) {
+       _pruneTiles: function () {
+               if (!this._map) {
+                       return;
+               }
+
+               var key, tile;
 
-               var limit = this._getWrapTileNum();
+               var zoom = this._map.getZoom();
+               if (zoom > this.options.maxZoom ||
+                       zoom < this.options.minZoom) {
+                       this._removeAllTiles();
+                       return;
+               }
 
-               // wrap tile coordinates
-               if (!this.options.continuousWorld && !this.options.noWrap) {
-                       tilePoint.x = ((tilePoint.x % limit.x) + limit.x) % limit.x;
+               for (key in this._tiles) {
+                       tile = this._tiles[key];
+                       tile.retain = tile.current;
                }
 
-               if (this.options.tms) {
-                       tilePoint.y = limit.y - tilePoint.y - 1;
+               for (key in this._tiles) {
+                       tile = this._tiles[key];
+                       if (tile.current && !tile.active) {
+                               var coords = tile.coords;
+                               if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
+                                       this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
+                               }
+                       }
                }
 
-               tilePoint.z = this._getZoomForUrl();
+               for (key in this._tiles) {
+                       if (!this._tiles[key].retain) {
+                               this._removeTile(key);
+                       }
+               }
        },
 
-       _getSubdomain: function (tilePoint) {
-               var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
-               return this.options.subdomains[index];
+       _removeTilesAtZoom: function (zoom) {
+               for (var key in this._tiles) {
+                       if (this._tiles[key].coords.z !== zoom) {
+                               continue;
+                       }
+                       this._removeTile(key);
+               }
+       },
+
+       _removeAllTiles: function () {
+               for (var key in this._tiles) {
+                       this._removeTile(key);
+               }
        },
 
-       _getTile: function () {
-               if (this.options.reuseTiles && this._unusedTiles.length > 0) {
-                       var tile = this._unusedTiles.pop();
-                       this._resetTile(tile);
-                       return tile;
+       _invalidateAll: function () {
+               for (var z in this._levels) {
+                       L.DomUtil.remove(this._levels[z].el);
+                       delete this._levels[z];
                }
-               return this._createTile();
+               this._removeAllTiles();
+
+               this._tileZoom = null;
        },
 
-       // Override if data stored on a tile needs to be cleaned up before reuse
-       _resetTile: function (/*tile*/) {},
+       _retainParent: function (x, y, z, minZoom) {
+               var x2 = Math.floor(x / 2),
+                   y2 = Math.floor(y / 2),
+                   z2 = z - 1,
+                   coords2 = new L.Point(+x2, +y2);
+               coords2.z = +z2;
 
-       _createTile: function () {
-               var tile = L.DomUtil.create('img', 'leaflet-tile');
-               tile.style.width = tile.style.height = this._getTileSize() + 'px';
-               tile.galleryimg = 'no';
+               var key = this._tileCoordsToKey(coords2),
+                   tile = this._tiles[key];
 
-               tile.onselectstart = tile.onmousemove = L.Util.falseFn;
+               if (tile && tile.active) {
+                       tile.retain = true;
+                       return true;
 
-               if (L.Browser.ielt9 && this.options.opacity !== undefined) {
-                       L.DomUtil.setOpacity(tile, this.options.opacity);
+               } else if (tile && tile.loaded) {
+                       tile.retain = true;
                }
-               // without this hack, tiles disappear after zoom on Chrome for Android
-               // https://github.com/Leaflet/Leaflet/issues/2078
-               if (L.Browser.mobileWebkit3d) {
-                       tile.style.WebkitBackfaceVisibility = 'hidden';
+
+               if (z2 > minZoom) {
+                       return this._retainParent(x2, y2, z2, minZoom);
                }
-               return tile;
+
+               return false;
        },
 
-       _loadTile: function (tile, tilePoint) {
-               tile._layer  = this;
-               tile.onload  = this._tileOnLoad;
-               tile.onerror = this._tileOnError;
+       _retainChildren: function (x, y, z, maxZoom) {
 
-               this._adjustTilePoint(tilePoint);
-               tile.src     = this.getTileUrl(tilePoint);
+               for (var i = 2 * x; i < 2 * x + 2; i++) {
+                       for (var j = 2 * y; j < 2 * y + 2; j++) {
 
-               this.fire('tileloadstart', {
-                       tile: tile,
-                       url: tile.src
-               });
-       },
+                               var coords = new L.Point(i, j);
+                               coords.z = z + 1;
 
-       _tileLoaded: function () {
-               this._tilesToLoad--;
+                               var key = this._tileCoordsToKey(coords),
+                                   tile = this._tiles[key];
 
-               if (this._animated) {
-                       L.DomUtil.addClass(this._tileContainer, 'leaflet-zoom-animated');
-               }
+                               if (tile && tile.active) {
+                                       tile.retain = true;
+                                       continue;
 
-               if (!this._tilesToLoad) {
-                       this.fire('load');
+                               } else if (tile && tile.loaded) {
+                                       tile.retain = true;
+                               }
 
-                       if (this._animated) {
-                               // clear scaled tiles after all new tiles are loaded (for performance)
-                               clearTimeout(this._clearBgBufferTimer);
-                               this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500);
+                               if (z + 1 < maxZoom) {
+                                       this._retainChildren(i, j, z + 1, maxZoom);
+                               }
                        }
                }
        },
 
-       _tileOnLoad: function () {
-               var layer = this._layer;
+       _resetView: function (e) {
+               var animating = e && (e.pinch || e.flyTo);
+               this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
+       },
 
-               //Only if we are loading an actual image
-               if (this.src !== L.Util.emptyImageUrl) {
-                       L.DomUtil.addClass(this, 'leaflet-tile-loaded');
+       _animateZoom: function (e) {
+               this._setView(e.center, e.zoom, true, e.noUpdate);
+       },
 
-                       layer.fire('tileload', {
-                               tile: this,
-                               url: this.src
-                       });
+       _setView: function (center, zoom, noPrune, noUpdate) {
+               var tileZoom = Math.round(zoom);
+               if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
+                   (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
+                       tileZoom = undefined;
                }
 
-               layer._tileLoaded();
-       },
+               var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
 
-       _tileOnError: function () {
-               var layer = this._layer;
+               if (!noUpdate || tileZoomChanged) {
 
-               layer.fire('tileerror', {
-                       tile: this,
-                       url: this.src
-               });
+                       this._tileZoom = tileZoom;
 
-               var newUrl = layer.options.errorTileUrl;
-               if (newUrl) {
-                       this.src = newUrl;
-               }
+                       if (this._abortLoading) {
+                               this._abortLoading();
+                       }
 
-               layer._tileLoaded();
-       }
-});
-
-L.tileLayer = function (url, options) {
-       return new L.TileLayer(url, options);
-};
+                       this._updateLevels();
+                       this._resetGrid();
 
+                       if (tileZoom !== undefined) {
+                               this._update(center);
+                       }
 
-/*
- * L.TileLayer.WMS is used for putting WMS tile layers on the map.
- */
+                       if (!noPrune) {
+                               this._pruneTiles();
+                       }
 
-L.TileLayer.WMS = L.TileLayer.extend({
+                       // Flag to prevent _updateOpacity from pruning tiles during
+                       // a zoom anim or a pinch gesture
+                       this._noPrune = !!noPrune;
+               }
 
-       defaultWmsParams: {
-               service: 'WMS',
-               request: 'GetMap',
-               version: '1.1.1',
-               layers: '',
-               styles: '',
-               format: 'image/jpeg',
-               transparent: false
+               this._setZoomTransforms(center, zoom);
        },
 
-       initialize: function (url, options) { // (String, Object)
-
-               this._url = url;
+       _setZoomTransforms: function (center, zoom) {
+               for (var i in this._levels) {
+                       this._setZoomTransform(this._levels[i], center, zoom);
+               }
+       },
 
-               var wmsParams = L.extend({}, this.defaultWmsParams),
-                   tileSize = options.tileSize || this.options.tileSize;
+       _setZoomTransform: function (level, center, zoom) {
+               var scale = this._map.getZoomScale(zoom, level.zoom),
+                   translate = level.origin.multiplyBy(scale)
+                       .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
 
-               if (options.detectRetina && L.Browser.retina) {
-                       wmsParams.width = wmsParams.height = tileSize * 2;
+               if (L.Browser.any3d) {
+                       L.DomUtil.setTransform(level.el, translate, scale);
                } else {
-                       wmsParams.width = wmsParams.height = tileSize;
+                       L.DomUtil.setPosition(level.el, translate);
                }
+       },
 
-               for (var i in options) {
-                       // all keys that are not TileLayer options go to WMS params
-                       if (!this.options.hasOwnProperty(i) && i !== 'crs') {
-                               wmsParams[i] = options[i];
-                       }
-               }
+       _resetGrid: function () {
+               var map = this._map,
+                   crs = map.options.crs,
+                   tileSize = this._tileSize = this.getTileSize(),
+                   tileZoom = this._tileZoom;
 
-               this.wmsParams = wmsParams;
+               var bounds = this._map.getPixelWorldBounds(this._tileZoom);
+               if (bounds) {
+                       this._globalTileRange = this._pxBoundsToTileRange(bounds);
+               }
 
-               L.setOptions(this, options);
+               this._wrapX = crs.wrapLng && !this.options.noWrap && [
+                       Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
+                       Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
+               ];
+               this._wrapY = crs.wrapLat && !this.options.noWrap && [
+                       Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
+                       Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
+               ];
        },
 
-       onAdd: function (map) {
-
-               this._crs = this.options.crs || map.options.crs;
+       _onMoveEnd: function () {
+               if (!this._map || this._map._animatingZoom) { return; }
 
-               this._wmsVersion = parseFloat(this.wmsParams.version);
+               this._update();
+       },
 
-               var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
-               this.wmsParams[projectionKey] = this._crs.code;
+       _getTiledPixelBounds: function (center) {
+               var map = this._map,
+                   mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
+                   scale = map.getZoomScale(mapZoom, this._tileZoom),
+                   pixelCenter = map.project(center, this._tileZoom).floor(),
+                   halfSize = map.getSize().divideBy(scale * 2);
 
-               L.TileLayer.prototype.onAdd.call(this, map);
+               return new L.Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
        },
 
-       getTileUrl: function (tilePoint) { // (Point, Number) -> String
-
-               var map = this._map,
-                   tileSize = this.options.tileSize,
+       // Private method to load tiles in the grid's active zoom level according to map bounds
+       _update: function (center) {
+               var map = this._map;
+               if (!map) { return; }
+               var zoom = map.getZoom();
 
-                   nwPoint = tilePoint.multiplyBy(tileSize),
-                   sePoint = nwPoint.add([tileSize, tileSize]),
+               if (center === undefined) { center = map.getCenter(); }
+               if (this._tileZoom === undefined) { return; }   // if out of minzoom/maxzoom
 
-                   nw = this._crs.project(map.unproject(nwPoint, tilePoint.z)),
-                   se = this._crs.project(map.unproject(sePoint, tilePoint.z)),
-                   bbox = this._wmsVersion >= 1.3 && this._crs === L.CRS.EPSG4326 ?
-                       [se.y, nw.x, nw.y, se.x].join(',') :
-                       [nw.x, se.y, se.x, nw.y].join(','),
+               var pixelBounds = this._getTiledPixelBounds(center),
+                   tileRange = this._pxBoundsToTileRange(pixelBounds),
+                   tileCenter = tileRange.getCenter(),
+                   queue = [],
+                   margin = this.options.keepBuffer,
+                   noPruneRange = new L.Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
+                                             tileRange.getTopRight().add([margin, -margin]));
 
-                   url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
+               for (var key in this._tiles) {
+                       var c = this._tiles[key].coords;
+                       if (c.z !== this._tileZoom || !noPruneRange.contains(L.point(c.x, c.y))) {
+                               this._tiles[key].current = false;
+                       }
+               }
 
-               return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox;
-       },
+               // _update just loads more tiles. If the tile zoom level differs too much
+               // from the map's, let _setView reset levels and prune old tiles.
+               if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
 
-       setParams: function (params, noRedraw) {
+               // create a queue of coordinates to load tiles from
+               for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
+                       for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
+                               var coords = new L.Point(i, j);
+                               coords.z = this._tileZoom;
 
-               L.extend(this.wmsParams, params);
+                               if (!this._isValidTile(coords)) { continue; }
 
-               if (!noRedraw) {
-                       this.redraw();
+                               var tile = this._tiles[this._tileCoordsToKey(coords)];
+                               if (tile) {
+                                       tile.current = true;
+                               } else {
+                                       queue.push(coords);
+                               }
+                       }
                }
 
-               return this;
-       }
-});
+               // sort tile queue to load tiles in order of their distance to center
+               queue.sort(function (a, b) {
+                       return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
+               });
 
-L.tileLayer.wms = function (url, options) {
-       return new L.TileLayer.WMS(url, options);
-};
+               if (queue.length !== 0) {
+                       // 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');
+                       }
 
+                       // create DOM fragment to append tiles in one batch
+                       var fragment = document.createDocumentFragment();
 
-/*
- * L.TileLayer.Canvas is a class that you can use as a base for creating
- * dynamically drawn Canvas-based tile layers.
- */
+                       for (i = 0; i < queue.length; i++) {
+                               this._addTile(queue[i], fragment);
+                       }
 
-L.TileLayer.Canvas = L.TileLayer.extend({
-       options: {
-               async: false
+                       this._level.el.appendChild(fragment);
+               }
        },
 
-       initialize: function (options) {
-               L.setOptions(this, options);
-       },
+       _isValidTile: function (coords) {
+               var crs = this._map.options.crs;
 
-       redraw: function () {
-               if (this._map) {
-                       this._reset({hard: true});
-                       this._update();
+               if (!crs.infinite) {
+                       // don't load tile if it's out of bounds and not wrapped
+                       var bounds = this._globalTileRange;
+                       if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
+                           (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
                }
 
-               for (var i in this._tiles) {
-                       this._redrawTile(this._tiles[i]);
-               }
-               return this;
-       },
+               if (!this.options.bounds) { return true; }
 
-       _redrawTile: function (tile) {
-               this.drawTile(tile, tile._tilePoint, this._map._zoom);
+               // don't load tile if it doesn't intersect the bounds in options
+               var tileBounds = this._tileCoordsToBounds(coords);
+               return L.latLngBounds(this.options.bounds).overlaps(tileBounds);
        },
 
-       _createTile: function () {
-               var tile = L.DomUtil.create('canvas', 'leaflet-tile');
-               tile.width = tile.height = this.options.tileSize;
-               tile.onselectstart = tile.onmousemove = L.Util.falseFn;
-               return tile;
+       _keyToBounds: function (key) {
+               return this._tileCoordsToBounds(this._keyToTileCoords(key));
        },
 
-       _loadTile: function (tile, tilePoint) {
-               tile._layer = this;
-               tile._tilePoint = tilePoint;
+       // converts tile coordinates to its geographical bounds
+       _tileCoordsToBounds: function (coords) {
+
+               var map = this._map,
+                   tileSize = this.getTileSize(),
+
+                   nwPoint = coords.scaleBy(tileSize),
+                   sePoint = nwPoint.add(tileSize),
 
-               this._redrawTile(tile);
+                   nw = map.unproject(nwPoint, coords.z),
+                   se = map.unproject(sePoint, coords.z);
 
-               if (!this.options.async) {
-                       this.tileDrawn(tile);
+               if (!this.options.noWrap) {
+                       nw = map.wrapLatLng(nw);
+                       se = map.wrapLatLng(se);
                }
-       },
 
-       drawTile: function (/*tile, tilePoint*/) {
-               // override with rendering code
+               return new L.LatLngBounds(nw, se);
        },
 
-       tileDrawn: function (tile) {
-               this._tileOnLoad.call(tile);
-       }
-});
-
+       // converts tile coordinates to key for the tile cache
+       _tileCoordsToKey: function (coords) {
+               return coords.x + ':' + coords.y + ':' + coords.z;
+       },
 
-L.tileLayer.canvas = function (options) {
-       return new L.TileLayer.Canvas(options);
-};
+       // converts tile cache key to coordinates
+       _keyToTileCoords: function (key) {
+               var k = key.split(':'),
+                   coords = new L.Point(+k[0], +k[1]);
+               coords.z = +k[2];
+               return coords;
+       },
 
+       _removeTile: function (key) {
+               var tile = this._tiles[key];
+               if (!tile) { return; }
 
-/*
- * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
- */
+               L.DomUtil.remove(tile.el);
 
-L.ImageOverlay = L.Class.extend({
-       includes: L.Mixin.Events,
+               delete this._tiles[key];
 
-       options: {
-               opacity: 1
+               // @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)
+               });
        },
 
-       initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
-               this._url = url;
-               this._bounds = L.latLngBounds(bounds);
+       _initTile: function (tile) {
+               L.DomUtil.addClass(tile, 'leaflet-tile');
 
-               L.setOptions(this, options);
-       },
+               var tileSize = this.getTileSize();
+               tile.style.width = tileSize.x + 'px';
+               tile.style.height = tileSize.y + 'px';
 
-       onAdd: function (map) {
-               this._map = map;
+               tile.onselectstart = L.Util.falseFn;
+               tile.onmousemove = L.Util.falseFn;
 
-               if (!this._image) {
-                       this._initImage();
+               // update opacity on tiles in IE7-8 because of filter inheritance problems
+               if (L.Browser.ielt9 && this.options.opacity < 1) {
+                       L.DomUtil.setOpacity(tile, this.options.opacity);
                }
 
-               map._panes.overlayPane.appendChild(this._image);
-
-               map.on('viewreset', this._reset, this);
-
-               if (map.options.zoomAnimation && L.Browser.any3d) {
-                       map.on('zoomanim', this._animateZoom, this);
+               // without this hack, tiles disappear after zoom on Chrome for Android
+               // https://github.com/Leaflet/Leaflet/issues/2078
+               if (L.Browser.android && !L.Browser.android23) {
+                       tile.style.WebkitBackfaceVisibility = 'hidden';
                }
-
-               this._reset();
        },
 
-       onRemove: function (map) {
-               map.getPanes().overlayPane.removeChild(this._image);
+       _addTile: function (coords, container) {
+               var tilePos = this._getTilePos(coords),
+                   key = this._tileCoordsToKey(coords);
 
-               map.off('viewreset', this._reset, this);
+               var tile = this.createTile(this._wrapCoords(coords), L.bind(this._tileReady, this, coords));
 
-               if (map.options.zoomAnimation) {
-                       map.off('zoomanim', this._animateZoom, this);
+               this._initTile(tile);
+
+               // if createTile is defined with a second argument ("done" callback),
+               // we know that tile is async and will be ready later; otherwise
+               if (this.createTile.length < 2) {
+                       // mark tile as ready, but delay one frame for opacity animation to happen
+                       L.Util.requestAnimFrame(L.bind(this._tileReady, this, coords, null, tile));
                }
-       },
 
-       addTo: function (map) {
-               map.addLayer(this);
-               return this;
-       },
+               L.DomUtil.setPosition(tile, tilePos);
 
-       setOpacity: function (opacity) {
-               this.options.opacity = opacity;
-               this._updateOpacity();
-               return this;
-       },
+               // save tile in cache
+               this._tiles[key] = {
+                       el: tile,
+                       coords: coords,
+                       current: true
+               };
 
-       // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
-       bringToFront: function () {
-               if (this._image) {
-                       this._map._panes.overlayPane.appendChild(this._image);
-               }
-               return this;
+               container.appendChild(tile);
+               // @event tileloadstart: TileEvent
+               // Fired when a tile is requested and starts loading.
+               this.fire('tileloadstart', {
+                       tile: tile,
+                       coords: coords
+               });
        },
 
-       bringToBack: function () {
-               var pane = this._map._panes.overlayPane;
-               if (this._image) {
-                       pane.insertBefore(this._image, pane.firstChild);
-               }
-               return this;
-       },
+       _tileReady: function (coords, err, tile) {
+               if (!this._map) { return; }
 
-       setUrl: function (url) {
-               this._url = url;
-               this._image.src = this._url;
-       },
+               if (err) {
+                       // @event tileerror: TileErrorEvent
+                       // Fired when there is an error loading a tile.
+                       this.fire('tileerror', {
+                               error: err,
+                               tile: tile,
+                               coords: coords
+                       });
+               }
 
-       getAttribution: function () {
-               return this.options.attribution;
-       },
+               var key = this._tileCoordsToKey(coords);
 
-       _initImage: function () {
-               this._image = L.DomUtil.create('img', 'leaflet-image-layer');
+               tile = this._tiles[key];
+               if (!tile) { return; }
 
-               if (this._map.options.zoomAnimation && L.Browser.any3d) {
-                       L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
+               tile.loaded = +new Date();
+               if (this._map._fadeAnimated) {
+                       L.DomUtil.setOpacity(tile.el, 0);
+                       L.Util.cancelAnimFrame(this._fadeFrame);
+                       this._fadeFrame = L.Util.requestAnimFrame(this._updateOpacity, this);
                } else {
-                       L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
+                       tile.active = true;
+                       this._pruneTiles();
                }
 
-               this._updateOpacity();
+               L.DomUtil.addClass(tile.el, 'leaflet-tile-loaded');
 
-               //TODO createImage util method to remove duplication
-               L.extend(this._image, {
-                       galleryimg: 'no',
-                       onselectstart: L.Util.falseFn,
-                       onmousemove: L.Util.falseFn,
-                       onload: L.bind(this._onImageLoad, this),
-                       src: this._url
+               // @event tileload: TileEvent
+               // Fired when a tile loads.
+               this.fire('tileload', {
+                       tile: tile.el,
+                       coords: coords
                });
-       },
-
-       _animateZoom: function (e) {
-               var map = this._map,
-                   image = this._image,
-                   scale = map.getZoomScale(e.zoom),
-                   nw = this._bounds.getNorthWest(),
-                   se = this._bounds.getSouthEast(),
 
-                   topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
-                   size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
-                   origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
+               if (this._noTilesToLoad()) {
+                       this._loading = false;
+                       // @event load: Event
+                       // Fired when the grid layer loaded all visible tiles.
+                       this.fire('load');
 
-               image.style[L.DomUtil.TRANSFORM] =
-                       L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
+                       if (L.Browser.ielt9 || !this._map._fadeAnimated) {
+                               L.Util.requestAnimFrame(this._pruneTiles, this);
+                       } else {
+                               // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
+                               // to trigger a pruning.
+                               setTimeout(L.bind(this._pruneTiles, this), 250);
+                       }
+               }
        },
 
-       _reset: function () {
-               var image   = this._image,
-                   topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
-                   size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
-
-               L.DomUtil.setPosition(image, topLeft);
+       _getTilePos: function (coords) {
+               return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
+       },
 
-               image.style.width  = size.x + 'px';
-               image.style.height = size.y + 'px';
+       _wrapCoords: function (coords) {
+               var newCoords = new L.Point(
+                       this._wrapX ? L.Util.wrapNum(coords.x, this._wrapX) : coords.x,
+                       this._wrapY ? L.Util.wrapNum(coords.y, this._wrapY) : coords.y);
+               newCoords.z = coords.z;
+               return newCoords;
        },
 
-       _onImageLoad: function () {
-               this.fire('load');
+       _pxBoundsToTileRange: function (bounds) {
+               var tileSize = this.getTileSize();
+               return new L.Bounds(
+                       bounds.min.unscaleBy(tileSize).floor(),
+                       bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
        },
 
-       _updateOpacity: function () {
-               L.DomUtil.setOpacity(this._image, this.options.opacity);
+       _noTilesToLoad: function () {
+               for (var key in this._tiles) {
+                       if (!this._tiles[key].loaded) { return false; }
+               }
+               return true;
        }
 });
 
-L.imageOverlay = function (url, bounds, options) {
-       return new L.ImageOverlay(url, bounds, options);
+// @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);
 };
 
 
+
 /*
- * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
+ * @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'});
+ * ```
  */
 
-L.Icon = L.Class.extend({
+
+L.TileLayer = L.GridLayer.extend({
+
+       // @section
+       // @aka TileLayer options
        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: ''
-       },
+               // @option minZoom: Number = 0
+               // Minimum zoom number.
+               minZoom: 0,
 
-       initialize: function (options) {
-               L.setOptions(this, options);
-       },
+               // @option maxZoom: Number = 18
+               // Maximum zoom number.
+               maxZoom: 18,
 
-       createIcon: function (oldIcon) {
-               return this._createIcon('icon', oldIcon);
-       },
+               // @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,
 
-       createShadow: function (oldIcon) {
-               return this._createIcon('shadow', oldIcon);
-       },
+               // @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',
 
-       _createIcon: function (name, oldIcon) {
-               var src = this._getIconUrl(name);
+               // @option errorTileUrl: String = ''
+               // URL to the tile image to show in place of the tile that failed to load.
+               errorTileUrl: '',
 
-               if (!src) {
-                       if (name === 'icon') {
-                               throw new Error('iconUrl not set in Icon options (see the docs).');
-                       }
-                       return null;
-               }
+               // @option zoomOffset: Number = 0
+               // The zoom number used in tile URLs will be offset with this value.
+               zoomOffset: 0,
 
-               var img;
-               if (!oldIcon || oldIcon.tagName !== 'IMG') {
-                       img = this._createImg(src);
-               } else {
-                       img = this._createImg(src, oldIcon);
-               }
-               this._setIconStyles(img, name);
+               // @option tms: Boolean = false
+               // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
+               tms: false,
 
-               return img;
+               // @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
        },
 
-       _setIconStyles: function (img, name) {
-               var options = this.options,
-                   size = L.point(options[name + 'Size']),
-                   anchor;
+       initialize: function (url, options) {
 
-               if (name === 'shadow') {
-                       anchor = L.point(options.shadowAnchor || options.iconAnchor);
-               } else {
-                       anchor = L.point(options.iconAnchor);
-               }
+               this._url = url;
 
-               if (!anchor && size) {
-                       anchor = size.divideBy(2, true);
-               }
+               options = L.setOptions(this, options);
+
+               // detecting retina displays, adjusting tileSize and zoom levels
+               if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
 
-               img.className = 'leaflet-marker-' + name + ' ' + options.className;
+                       options.tileSize = Math.floor(options.tileSize / 2);
 
-               if (anchor) {
-                       img.style.marginLeft = (-anchor.x) + 'px';
-                       img.style.marginTop  = (-anchor.y) + 'px';
+                       if (!options.zoomReverse) {
+                               options.zoomOffset++;
+                               options.maxZoom--;
+                       } else {
+                               options.zoomOffset--;
+                               options.minZoom++;
+                       }
+
+                       options.minZoom = Math.max(0, options.minZoom);
                }
 
-               if (size) {
-                       img.style.width  = size.x + 'px';
-                       img.style.height = size.y + 'px';
+               if (typeof options.subdomains === 'string') {
+                       options.subdomains = options.subdomains.split('');
                }
-       },
 
-       _createImg: function (src, el) {
-               el = el || document.createElement('img');
-               el.src = src;
-               return el;
+               // for https://github.com/Leaflet/Leaflet/issues/137
+               if (!L.Browser.android) {
+                       this.on('tileunload', this._onTileRemove);
+               }
        },
 
-       _getIconUrl: function (name) {
-               if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
-                       return this.options[name + 'RetinaUrl'];
+       // @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;
+
+               if (!noRedraw) {
+                       this.redraw();
                }
-               return this.options[name + 'Url'];
-       }
-});
+               return this;
+       },
 
-L.icon = function (options) {
-       return new L.Icon(options);
-};
+       // @method createTile(coords: Object, done?: Function): HTMLElement
+       // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
+       // to return an `<img>` 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');
 
+               L.DomEvent.on(tile, 'load', L.bind(this._tileOnLoad, this, done, tile));
+               L.DomEvent.on(tile, 'error', L.bind(this._tileOnError, this, done, tile));
 
-/*
- * L.Icon.Default is the blue marker icon used by default in Leaflet.
- */
+               if (this.options.crossOrigin) {
+                       tile.crossOrigin = '';
+               }
 
-L.Icon.Default = L.Icon.extend({
+               /*
+                Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
+                http://www.w3.org/TR/WCAG20-TECHS/H67
+               */
+               tile.alt = '';
 
-       options: {
-               iconSize: [25, 41],
-               iconAnchor: [12, 41],
-               popupAnchor: [1, -34],
+               tile.src = this.getTileUrl(coords);
 
-               shadowSize: [41, 41]
+               return tile;
        },
 
-       _getIconUrl: function (name) {
-               var key = name + 'Url';
+       // @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' : '',
+                       s: this._getSubdomain(coords),
+                       x: coords.x,
+                       y: coords.y,
+                       z: this._getZoomForUrl()
+               };
+               if (this._map && !this._map.options.crs.infinite) {
+                       var invertedY = this._globalTileRange.max.y - coords.y;
+                       if (this.options.tms) {
+                               data['y'] = invertedY;
+                       }
+                       data['-y'] = invertedY;
+               }
+
+               return L.Util.template(this._url, L.extend(data, this.options));
+       },
 
-               if (this.options[key]) {
-                       return this.options[key];
+       _tileOnLoad: function (done, tile) {
+               // For https://github.com/Leaflet/Leaflet/issues/3332
+               if (L.Browser.ielt9) {
+                       setTimeout(L.bind(done, this, null, tile), 0);
+               } else {
+                       done(null, tile);
                }
+       },
 
-               if (L.Browser.retina && name === 'icon') {
-                       name += '-2x';
+       _tileOnError: function (done, tile, e) {
+               var errorUrl = this.options.errorTileUrl;
+               if (errorUrl) {
+                       tile.src = errorUrl;
                }
+               done(e, tile);
+       },
+
+       getTileSize: function () {
+               var map = this._map,
+                   tileSize = L.GridLayer.prototype.getTileSize.call(this),
+                   zoom = this._tileZoom + this.options.zoomOffset,
+                   zoomN = this.options.maxNativeZoom;
+
+               // increase tile size when overscaling
+               return zoomN !== null && zoom > zoomN ?
+                               tileSize.divideBy(map.getZoomScale(zoomN, zoom)).round() :
+                               tileSize;
+       },
+
+       _onTileRemove: function (e) {
+               e.tile.onload = null;
+       },
+
+       _getZoomForUrl: function () {
 
-               var path = L.Icon.Default.imagePath;
+               var options = this.options,
+                   zoom = this._tileZoom;
 
-               if (!path) {
-                       throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.');
+               if (options.zoomReverse) {
+                       zoom = options.maxZoom - zoom;
                }
 
-               return path + '/marker-' + name + '.png';
-       }
-});
+               zoom += options.zoomOffset;
+
+               return options.maxNativeZoom !== null ? Math.min(zoom, options.maxNativeZoom) : zoom;
+       },
 
-L.Icon.Default.imagePath = (function () {
-       var scripts = document.getElementsByTagName('script'),
-           leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
+       _getSubdomain: function (tilePoint) {
+               var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
+               return this.options.subdomains[index];
+       },
 
-       var i, len, src, matches, path;
+       // stops loading all tiles in the background layer
+       _abortLoading: function () {
+               var i, tile;
+               for (i in this._tiles) {
+                       if (this._tiles[i].coords.z !== this._tileZoom) {
+                               tile = this._tiles[i].el;
 
-       for (i = 0, len = scripts.length; i < len; i++) {
-               src = scripts[i].src;
-               matches = src.match(leafletRe);
+                               tile.onload = L.Util.falseFn;
+                               tile.onerror = L.Util.falseFn;
 
-               if (matches) {
-                       path = src.split(leafletRe)[0];
-                       return (path ? path + '/' : '') + 'images';
+                               if (!tile.complete) {
+                                       tile.src = L.Util.emptyImageUrl;
+                                       L.DomUtil.remove(tile);
+                               }
+                       }
                }
        }
-}());
+});
+
+
+// @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);
+};
+
 
 
 /*
- * L.Marker is used to display clickable/draggable icons on the map.
+ * @class TileLayer.WMS
+ * @inherits TileLayer
+ * @aka L.TileLayer.WMS
+ * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) 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.Marker = L.Class.extend({
+L.TileLayer.WMS = L.TileLayer.extend({
 
-       includes: L.Mixin.Events,
+       // @section
+       // @aka TileLayer.WMS options
+       // If any custom options not documented here are used, they will be sent to the
+       // WMS server as extra parameters in each request URL. This can be useful for
+       // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
+       defaultWmsParams: {
+               service: 'WMS',
+               request: 'GetMap',
 
-       options: {
-               icon: new L.Icon.Default(),
-               title: '',
-               alt: '',
-               clickable: true,
-               draggable: false,
-               keyboard: true,
-               zIndexOffset: 0,
-               opacity: 1,
-               riseOnHover: false,
-               riseOffset: 250
+               // @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',
+
+               // @option transparent: 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'
        },
 
-       initialize: function (latlng, options) {
-               L.setOptions(this, options);
-               this._latlng = L.latLng(latlng);
+       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
        },
 
-       onAdd: function (map) {
-               this._map = map;
+       initialize: function (url, options) {
 
-               map.on('viewreset', this.update, this);
+               this._url = url;
 
-               this._initIcon();
-               this.update();
-               this.fire('add');
+               var wmsParams = L.extend({}, this.defaultWmsParams);
 
-               if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
-                       map.on('zoomanim', this._animateZoom, this);
+               // all keys that are not TileLayer options go to WMS params
+               for (var i in options) {
+                       if (!(i in this.options)) {
+                               wmsParams[i] = options[i];
+                       }
                }
-       },
 
-       addTo: function (map) {
-               map.addLayer(this);
-               return this;
-       },
+               options = L.setOptions(this, options);
 
-       onRemove: function (map) {
-               if (this.dragging) {
-                       this.dragging.disable();
-               }
+               wmsParams.width = wmsParams.height = options.tileSize * (options.detectRetina && L.Browser.retina ? 2 : 1);
 
-               this._removeIcon();
-               this._removeShadow();
+               this.wmsParams = wmsParams;
+       },
 
-               this.fire('remove');
+       onAdd: function (map) {
 
-               map.off({
-                       'viewreset': this.update,
-                       'zoomanim': this._animateZoom
-               }, this);
+               this._crs = this.options.crs || map.options.crs;
+               this._wmsVersion = parseFloat(this.wmsParams.version);
 
-               this._map = null;
-       },
+               var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
+               this.wmsParams[projectionKey] = this._crs.code;
 
-       getLatLng: function () {
-               return this._latlng;
+               L.TileLayer.prototype.onAdd.call(this, map);
        },
 
-       setLatLng: function (latlng) {
-               this._latlng = L.latLng(latlng);
+       getTileUrl: function (coords) {
 
-               this.update();
+               var tileBounds = this._tileCoordsToBounds(coords),
+                   nw = this._crs.project(tileBounds.getNorthWest()),
+                   se = this._crs.project(tileBounds.getSouthEast()),
 
-               return this.fire('move', { latlng: this._latlng });
-       },
+                   bbox = (this._wmsVersion >= 1.3 && this._crs === L.CRS.EPSG4326 ?
+                           [se.y, nw.x, nw.y, se.x] :
+                           [nw.x, se.y, se.x, nw.y]).join(','),
 
-       setZIndexOffset: function (offset) {
-               this.options.zIndexOffset = offset;
-               this.update();
+                   url = L.TileLayer.prototype.getTileUrl.call(this, coords);
 
-               return this;
+               return url +
+                       L.Util.getParamString(this.wmsParams, url, this.options.uppercase) +
+                       (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
        },
 
-       setIcon: function (icon) {
-
-               this.options.icon = icon;
+       // @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) {
 
-               if (this._map) {
-                       this._initIcon();
-                       this.update();
-               }
+               L.extend(this.wmsParams, params);
 
-               if (this._popup) {
-                       this.bindPopup(this._popup);
+               if (!noRedraw) {
+                       this.redraw();
                }
 
                return this;
-       },
+       }
+});
 
-       update: function () {
-               if (this._icon) {
-                       this._setPos(this._map.latLngToLayerPoint(this._latlng).round());
-               }
-               return this;
-       },
 
-       _initIcon: function () {
-               var options = this.options,
-                   map = this._map,
-                   animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
-                   classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
+// @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);
+};
 
-               var icon = options.icon.createIcon(this._icon),
-                       addIcon = false;
 
-               // if we're not reusing the icon, remove the old one and init new one
-               if (icon !== this._icon) {
-                       if (this._icon) {
-                               this._removeIcon();
-                       }
-                       addIcon = true;
 
-                       if (options.title) {
-                               icon.title = options.title;
-                       }
+/*
+ * @class ImageOverlay
+ * @aka L.ImageOverlay
+ * @inherits Interactive 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);
+ * ```
+ */
 
-                       if (options.alt) {
-                               icon.alt = options.alt;
-                       }
-               }
+L.ImageOverlay = L.Layer.extend({
 
-               L.DomUtil.addClass(icon, classToAdd);
+       // @section
+       // @aka ImageOverlay options
+       options: {
+               // @option opacity: Number = 1.0
+               // The opacity of the image overlay.
+               opacity: 1,
 
-               if (options.keyboard) {
-                       icon.tabIndex = '0';
-               }
+               // @option alt: String = ''
+               // Text for the `alt` attribute of the image (useful for accessibility).
+               alt: '',
 
-               this._icon = icon;
+               // @option interactive: Boolean = false
+               // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
+               interactive: false,
 
-               this._initInteraction();
+               // @option attribution: String = null
+               // An optional string containing HTML to be shown on the `Attribution control`
+               attribution: null,
 
-               if (options.riseOnHover) {
-                       L.DomEvent
-                               .on(icon, 'mouseover', this._bringToFront, this)
-                               .on(icon, 'mouseout', this._resetZIndex, this);
-               }
+               // @option crossOrigin: Boolean = false
+               // If true, the image will have its crossOrigin attribute set to ''. This is needed if you want to access image pixel data.
+               crossOrigin: false
+       },
 
-               var newShadow = options.icon.createShadow(this._shadow),
-                       addShadow = false;
+       initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
+               this._url = url;
+               this._bounds = L.latLngBounds(bounds);
 
-               if (newShadow !== this._shadow) {
-                       this._removeShadow();
-                       addShadow = true;
+               L.setOptions(this, options);
+       },
+
+       onAdd: function () {
+               if (!this._image) {
+                       this._initImage();
+
+                       if (this.options.opacity < 1) {
+                               this._updateOpacity();
+                       }
                }
 
-               if (newShadow) {
-                       L.DomUtil.addClass(newShadow, classToAdd);
+               if (this.options.interactive) {
+                       L.DomUtil.addClass(this._image, 'leaflet-interactive');
+                       this.addInteractiveTarget(this._image);
                }
-               this._shadow = newShadow;
 
+               this.getPane().appendChild(this._image);
+               this._reset();
+       },
 
-               if (options.opacity < 1) {
-                       this._updateOpacity();
+       onRemove: function () {
+               L.DomUtil.remove(this._image);
+               if (this.options.interactive) {
+                       this.removeInteractiveTarget(this._image);
                }
+       },
 
+       // @method setOpacity(opacity: Number): this
+       // Sets the opacity of the overlay.
+       setOpacity: function (opacity) {
+               this.options.opacity = opacity;
 
-               var panes = this._map._panes;
-
-               if (addIcon) {
-                       panes.markerPane.appendChild(this._icon);
+               if (this._image) {
+                       this._updateOpacity();
                }
+               return this;
+       },
 
-               if (newShadow && addShadow) {
-                       panes.shadowPane.appendChild(this._shadow);
+       setStyle: function (styleOpts) {
+               if (styleOpts.opacity) {
+                       this.setOpacity(styleOpts.opacity);
                }
+               return this;
        },
 
-       _removeIcon: function () {
-               if (this.options.riseOnHover) {
-                       L.DomEvent
-                           .off(this._icon, 'mouseover', this._bringToFront)
-                           .off(this._icon, 'mouseout', this._resetZIndex);
+       // @method bringToFront(): this
+       // Brings the layer to the top of all overlays.
+       bringToFront: function () {
+               if (this._map) {
+                       L.DomUtil.toFront(this._image);
                }
-
-               this._map._panes.markerPane.removeChild(this._icon);
-
-               this._icon = null;
+               return this;
        },
 
-       _removeShadow: function () {
-               if (this._shadow) {
-                       this._map._panes.shadowPane.removeChild(this._shadow);
+       // @method bringToBack(): this
+       // Brings the layer to the bottom of all overlays.
+       bringToBack: function () {
+               if (this._map) {
+                       L.DomUtil.toBack(this._image);
                }
-               this._shadow = null;
+               return this;
        },
 
-       _setPos: function (pos) {
-               L.DomUtil.setPosition(this._icon, pos);
+       // @method setUrl(url: String): this
+       // Changes the URL of the image.
+       setUrl: function (url) {
+               this._url = url;
 
-               if (this._shadow) {
-                       L.DomUtil.setPosition(this._shadow, pos);
+               if (this._image) {
+                       this._image.src = url;
                }
+               return this;
+       },
 
-               this._zIndex = pos.y + this.options.zIndexOffset;
+       setBounds: function (bounds) {
+               this._bounds = bounds;
 
-               this._resetZIndex();
+               if (this._map) {
+                       this._reset();
+               }
+               return this;
        },
 
-       _updateZIndex: function (offset) {
-               this._icon.style.zIndex = this._zIndex + offset;
+       getAttribution: function () {
+               return this.options.attribution;
        },
 
-       _animateZoom: function (opt) {
-               var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
+       getEvents: function () {
+               var events = {
+                       zoom: this._reset,
+                       viewreset: this._reset
+               };
 
-               this._setPos(pos);
+               if (this._zoomAnimated) {
+                       events.zoomanim = this._animateZoom;
+               }
+
+               return events;
        },
 
-       _initInteraction: function () {
+       getBounds: function () {
+               return this._bounds;
+       },
 
-               if (!this.options.clickable) { return; }
+       getElement: function () {
+               return this._image;
+       },
 
-               // TODO refactor into something shared with Map/Path/etc. to DRY it up
+       _initImage: function () {
+               var img = this._image = L.DomUtil.create('img',
+                               'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated' : ''));
 
-               var icon = this._icon,
-                   events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
+               img.onselectstart = L.Util.falseFn;
+               img.onmousemove = L.Util.falseFn;
 
-               L.DomUtil.addClass(icon, 'leaflet-clickable');
-               L.DomEvent.on(icon, 'click', this._onMouseClick, this);
-               L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
+               img.onload = L.bind(this.fire, this, 'load');
 
-               for (var i = 0; i < events.length; i++) {
-                       L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
+               if (this.options.crossOrigin) {
+                       img.crossOrigin = '';
                }
 
-               if (L.Handler.MarkerDrag) {
-                       this.dragging = new L.Handler.MarkerDrag(this);
+               img.src = this._url;
+               img.alt = this.options.alt;
+       },
 
-                       if (this.options.draggable) {
-                               this.dragging.enable();
-                       }
-               }
+       _animateZoom: function (e) {
+               var scale = this._map.getZoomScale(e.zoom),
+                   offset = this._map._latLngToNewLayerPoint(this._bounds.getNorthWest(), e.zoom, e.center);
+
+               L.DomUtil.setTransform(this._image, offset, scale);
        },
 
-       _onMouseClick: function (e) {
-               var wasDragged = this.dragging && this.dragging.moved();
+       _reset: function () {
+               var image = this._image,
+                   bounds = new L.Bounds(
+                       this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
+                       this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
+                   size = bounds.getSize();
 
-               if (this.hasEventListeners(e.type) || wasDragged) {
-                       L.DomEvent.stopPropagation(e);
-               }
+               L.DomUtil.setPosition(image, bounds.min);
+
+               image.style.width  = size.x + 'px';
+               image.style.height = size.y + 'px';
+       },
+
+       _updateOpacity: function () {
+               L.DomUtil.setOpacity(this._image, this.options.opacity);
+       }
+});
+
+// @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);
+};
 
-               if (wasDragged) { return; }
 
-               if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
 
-               this.fire(e.type, {
-                       originalEvent: e,
-                       latlng: this._latlng
-               });
+/*
+ * @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({
+
+       /* @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