Newer
Older
www-root / lib / leaflet-0.7.3 / leaflet-src.js
@hayashi hayashi on 5 Nov 2017 210 KB leaflet Vector Tile (tileFuel)
  1. /*
  2. Leaflet, a JavaScript library for mobile-friendly interactive maps. http://leafletjs.com
  3. (c) 2010-2013, Vladimir Agafonkin
  4. (c) 2010-2011, CloudMade
  5. */
  6. (function (window, document, undefined) {
  7. var oldL = window.L,
  8. L = {};
  9.  
  10. L.version = '0.7.3';
  11.  
  12. // define Leaflet for Node module pattern loaders, including Browserify
  13. if (typeof module === 'object' && typeof module.exports === 'object') {
  14. module.exports = L;
  15.  
  16. // define Leaflet as an AMD module
  17. } else if (typeof define === 'function' && define.amd) {
  18. define(L);
  19. }
  20.  
  21. // define Leaflet as a global L variable, saving the original L to restore later if needed
  22.  
  23. L.noConflict = function () {
  24. window.L = oldL;
  25. return this;
  26. };
  27.  
  28. window.L = L;
  29.  
  30.  
  31. /*
  32. * L.Util contains various utility functions used throughout Leaflet code.
  33. */
  34.  
  35. L.Util = {
  36. extend: function (dest) { // (Object[, Object, ...]) ->
  37. var sources = Array.prototype.slice.call(arguments, 1),
  38. i, j, len, src;
  39.  
  40. for (j = 0, len = sources.length; j < len; j++) {
  41. src = sources[j] || {};
  42. for (i in src) {
  43. if (src.hasOwnProperty(i)) {
  44. dest[i] = src[i];
  45. }
  46. }
  47. }
  48. return dest;
  49. },
  50.  
  51. bind: function (fn, obj) { // (Function, Object) -> Function
  52. var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
  53. return function () {
  54. return fn.apply(obj, args || arguments);
  55. };
  56. },
  57.  
  58. stamp: (function () {
  59. var lastId = 0,
  60. key = '_leaflet_id';
  61. return function (obj) {
  62. obj[key] = obj[key] || ++lastId;
  63. return obj[key];
  64. };
  65. }()),
  66.  
  67. invokeEach: function (obj, method, context) {
  68. var i, args;
  69.  
  70. if (typeof obj === 'object') {
  71. args = Array.prototype.slice.call(arguments, 3);
  72.  
  73. for (i in obj) {
  74. method.apply(context, [i, obj[i]].concat(args));
  75. }
  76. return true;
  77. }
  78.  
  79. return false;
  80. },
  81.  
  82. limitExecByInterval: function (fn, time, context) {
  83. var lock, execOnUnlock;
  84.  
  85. return function wrapperFn() {
  86. var args = arguments;
  87.  
  88. if (lock) {
  89. execOnUnlock = true;
  90. return;
  91. }
  92.  
  93. lock = true;
  94.  
  95. setTimeout(function () {
  96. lock = false;
  97.  
  98. if (execOnUnlock) {
  99. wrapperFn.apply(context, args);
  100. execOnUnlock = false;
  101. }
  102. }, time);
  103.  
  104. fn.apply(context, args);
  105. };
  106. },
  107.  
  108. falseFn: function () {
  109. return false;
  110. },
  111.  
  112. formatNum: function (num, digits) {
  113. var pow = Math.pow(10, digits || 5);
  114. return Math.round(num * pow) / pow;
  115. },
  116.  
  117. trim: function (str) {
  118. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  119. },
  120.  
  121. splitWords: function (str) {
  122. return L.Util.trim(str).split(/\s+/);
  123. },
  124.  
  125. setOptions: function (obj, options) {
  126. obj.options = L.extend({}, obj.options, options);
  127. return obj.options;
  128. },
  129.  
  130. getParamString: function (obj, existingUrl, uppercase) {
  131. var params = [];
  132. for (var i in obj) {
  133. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  134. }
  135. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  136. },
  137. template: function (str, data) {
  138. return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
  139. var value = data[key];
  140. if (value === undefined) {
  141. throw new Error('No value provided for variable ' + str);
  142. } else if (typeof value === 'function') {
  143. value = value(data);
  144. }
  145. return value;
  146. });
  147. },
  148.  
  149. isArray: Array.isArray || function (obj) {
  150. return (Object.prototype.toString.call(obj) === '[object Array]');
  151. },
  152.  
  153. emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
  154. };
  155.  
  156. (function () {
  157.  
  158. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  159.  
  160. function getPrefixed(name) {
  161. var i, fn,
  162. prefixes = ['webkit', 'moz', 'o', 'ms'];
  163.  
  164. for (i = 0; i < prefixes.length && !fn; i++) {
  165. fn = window[prefixes[i] + name];
  166. }
  167.  
  168. return fn;
  169. }
  170.  
  171. var lastTime = 0;
  172.  
  173. function timeoutDefer(fn) {
  174. var time = +new Date(),
  175. timeToCall = Math.max(0, 16 - (time - lastTime));
  176.  
  177. lastTime = time + timeToCall;
  178. return window.setTimeout(fn, timeToCall);
  179. }
  180.  
  181. var requestFn = window.requestAnimationFrame ||
  182. getPrefixed('RequestAnimationFrame') || timeoutDefer;
  183.  
  184. var cancelFn = window.cancelAnimationFrame ||
  185. getPrefixed('CancelAnimationFrame') ||
  186. getPrefixed('CancelRequestAnimationFrame') ||
  187. function (id) { window.clearTimeout(id); };
  188.  
  189.  
  190. L.Util.requestAnimFrame = function (fn, context, immediate, element) {
  191. fn = L.bind(fn, context);
  192.  
  193. if (immediate && requestFn === timeoutDefer) {
  194. fn();
  195. } else {
  196. return requestFn.call(window, fn, element);
  197. }
  198. };
  199.  
  200. L.Util.cancelAnimFrame = function (id) {
  201. if (id) {
  202. cancelFn.call(window, id);
  203. }
  204. };
  205.  
  206. }());
  207.  
  208. // shortcuts for most used utility functions
  209. L.extend = L.Util.extend;
  210. L.bind = L.Util.bind;
  211. L.stamp = L.Util.stamp;
  212. L.setOptions = L.Util.setOptions;
  213.  
  214.  
  215. /*
  216. * L.Class powers the OOP facilities of the library.
  217. * Thanks to John Resig and Dean Edwards for inspiration!
  218. */
  219.  
  220. L.Class = function () {};
  221.  
  222. L.Class.extend = function (props) {
  223.  
  224. // extended class with the new prototype
  225. var NewClass = function () {
  226.  
  227. // call the constructor
  228. if (this.initialize) {
  229. this.initialize.apply(this, arguments);
  230. }
  231.  
  232. // call all constructor hooks
  233. if (this._initHooks) {
  234. this.callInitHooks();
  235. }
  236. };
  237.  
  238. // instantiate class without calling constructor
  239. var F = function () {};
  240. F.prototype = this.prototype;
  241.  
  242. var proto = new F();
  243. proto.constructor = NewClass;
  244.  
  245. NewClass.prototype = proto;
  246.  
  247. //inherit parent's statics
  248. for (var i in this) {
  249. if (this.hasOwnProperty(i) && i !== 'prototype') {
  250. NewClass[i] = this[i];
  251. }
  252. }
  253.  
  254. // mix static properties into the class
  255. if (props.statics) {
  256. L.extend(NewClass, props.statics);
  257. delete props.statics;
  258. }
  259.  
  260. // mix includes into the prototype
  261. if (props.includes) {
  262. L.Util.extend.apply(null, [proto].concat(props.includes));
  263. delete props.includes;
  264. }
  265.  
  266. // merge options
  267. if (props.options && proto.options) {
  268. props.options = L.extend({}, proto.options, props.options);
  269. }
  270.  
  271. // mix given properties into the prototype
  272. L.extend(proto, props);
  273.  
  274. proto._initHooks = [];
  275.  
  276. var parent = this;
  277. // jshint camelcase: false
  278. NewClass.__super__ = parent.prototype;
  279.  
  280. // add method for calling all hooks
  281. proto.callInitHooks = function () {
  282.  
  283. if (this._initHooksCalled) { return; }
  284.  
  285. if (parent.prototype.callInitHooks) {
  286. parent.prototype.callInitHooks.call(this);
  287. }
  288.  
  289. this._initHooksCalled = true;
  290.  
  291. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  292. proto._initHooks[i].call(this);
  293. }
  294. };
  295.  
  296. return NewClass;
  297. };
  298.  
  299.  
  300. // method for adding properties to prototype
  301. L.Class.include = function (props) {
  302. L.extend(this.prototype, props);
  303. };
  304.  
  305. // merge new default options to the Class
  306. L.Class.mergeOptions = function (options) {
  307. L.extend(this.prototype.options, options);
  308. };
  309.  
  310. // add a constructor hook
  311. L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
  312. var args = Array.prototype.slice.call(arguments, 1);
  313.  
  314. var init = typeof fn === 'function' ? fn : function () {
  315. this[fn].apply(this, args);
  316. };
  317.  
  318. this.prototype._initHooks = this.prototype._initHooks || [];
  319. this.prototype._initHooks.push(init);
  320. };
  321.  
  322.  
  323. /*
  324. * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
  325. */
  326.  
  327. var eventsKey = '_leaflet_events';
  328.  
  329. L.Mixin = {};
  330.  
  331. L.Mixin.Events = {
  332.  
  333. addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
  334.  
  335. // types can be a map of types/handlers
  336. if (L.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; }
  337.  
  338. var events = this[eventsKey] = this[eventsKey] || {},
  339. contextId = context && context !== this && L.stamp(context),
  340. i, len, event, type, indexKey, indexLenKey, typeIndex;
  341.  
  342. // types can be a string of space-separated words
  343. types = L.Util.splitWords(types);
  344.  
  345. for (i = 0, len = types.length; i < len; i++) {
  346. event = {
  347. action: fn,
  348. context: context || this
  349. };
  350. type = types[i];
  351.  
  352. if (contextId) {
  353. // store listeners of a particular context in a separate hash (if it has an id)
  354. // gives a major performance boost when removing thousands of map layers
  355.  
  356. indexKey = type + '_idx';
  357. indexLenKey = indexKey + '_len';
  358.  
  359. typeIndex = events[indexKey] = events[indexKey] || {};
  360.  
  361. if (!typeIndex[contextId]) {
  362. typeIndex[contextId] = [];
  363.  
  364. // keep track of the number of keys in the index to quickly check if it's empty
  365. events[indexLenKey] = (events[indexLenKey] || 0) + 1;
  366. }
  367.  
  368. typeIndex[contextId].push(event);
  369.  
  370.  
  371. } else {
  372. events[type] = events[type] || [];
  373. events[type].push(event);
  374. }
  375. }
  376.  
  377. return this;
  378. },
  379.  
  380. hasEventListeners: function (type) { // (String) -> Boolean
  381. var events = this[eventsKey];
  382. return !!events && ((type in events && events[type].length > 0) ||
  383. (type + '_idx' in events && events[type + '_idx_len'] > 0));
  384. },
  385.  
  386. removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object])
  387.  
  388. if (!this[eventsKey]) {
  389. return this;
  390. }
  391.  
  392. if (!types) {
  393. return this.clearAllEventListeners();
  394. }
  395.  
  396. if (L.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; }
  397.  
  398. var events = this[eventsKey],
  399. contextId = context && context !== this && L.stamp(context),
  400. i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed;
  401.  
  402. types = L.Util.splitWords(types);
  403.  
  404. for (i = 0, len = types.length; i < len; i++) {
  405. type = types[i];
  406. indexKey = type + '_idx';
  407. indexLenKey = indexKey + '_len';
  408.  
  409. typeIndex = events[indexKey];
  410.  
  411. if (!fn) {
  412. // clear all listeners for a type if function isn't specified
  413. delete events[type];
  414. delete events[indexKey];
  415. delete events[indexLenKey];
  416.  
  417. } else {
  418. listeners = contextId && typeIndex ? typeIndex[contextId] : events[type];
  419.  
  420. if (listeners) {
  421. for (j = listeners.length - 1; j >= 0; j--) {
  422. if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) {
  423. removed = listeners.splice(j, 1);
  424. // set the old action to a no-op, because it is possible
  425. // that the listener is being iterated over as part of a dispatch
  426. removed[0].action = L.Util.falseFn;
  427. }
  428. }
  429.  
  430. if (context && typeIndex && (listeners.length === 0)) {
  431. delete typeIndex[contextId];
  432. events[indexLenKey]--;
  433. }
  434. }
  435. }
  436. }
  437.  
  438. return this;
  439. },
  440.  
  441. clearAllEventListeners: function () {
  442. delete this[eventsKey];
  443. return this;
  444. },
  445.  
  446. fireEvent: function (type, data) { // (String[, Object])
  447. if (!this.hasEventListeners(type)) {
  448. return this;
  449. }
  450.  
  451. var event = L.Util.extend({}, data, { type: type, target: this });
  452.  
  453. var events = this[eventsKey],
  454. listeners, i, len, typeIndex, contextId;
  455.  
  456. if (events[type]) {
  457. // make sure adding/removing listeners inside other listeners won't cause infinite loop
  458. listeners = events[type].slice();
  459.  
  460. for (i = 0, len = listeners.length; i < len; i++) {
  461. listeners[i].action.call(listeners[i].context, event);
  462. }
  463. }
  464.  
  465. // fire event for the context-indexed listeners as well
  466. typeIndex = events[type + '_idx'];
  467.  
  468. for (contextId in typeIndex) {
  469. listeners = typeIndex[contextId].slice();
  470.  
  471. if (listeners) {
  472. for (i = 0, len = listeners.length; i < len; i++) {
  473. listeners[i].action.call(listeners[i].context, event);
  474. }
  475. }
  476. }
  477.  
  478. return this;
  479. },
  480.  
  481. addOneTimeEventListener: function (types, fn, context) {
  482.  
  483. if (L.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; }
  484.  
  485. var handler = L.bind(function () {
  486. this
  487. .removeEventListener(types, fn, context)
  488. .removeEventListener(types, handler, context);
  489. }, this);
  490.  
  491. return this
  492. .addEventListener(types, fn, context)
  493. .addEventListener(types, handler, context);
  494. }
  495. };
  496.  
  497. L.Mixin.Events.on = L.Mixin.Events.addEventListener;
  498. L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
  499. L.Mixin.Events.once = L.Mixin.Events.addOneTimeEventListener;
  500. L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
  501.  
  502.  
  503. /*
  504. * L.Browser handles different browser and feature detections for internal Leaflet use.
  505. */
  506.  
  507. (function () {
  508.  
  509. var ie = 'ActiveXObject' in window,
  510. ielt9 = ie && !document.addEventListener,
  511.  
  512. // terrible browser detection to work around Safari / iOS / Android browser bugs
  513. ua = navigator.userAgent.toLowerCase(),
  514. webkit = ua.indexOf('webkit') !== -1,
  515. chrome = ua.indexOf('chrome') !== -1,
  516. phantomjs = ua.indexOf('phantom') !== -1,
  517. android = ua.indexOf('android') !== -1,
  518. android23 = ua.search('android [23]') !== -1,
  519. gecko = ua.indexOf('gecko') !== -1,
  520.  
  521. mobile = typeof orientation !== undefined + '',
  522. msPointer = window.navigator && window.navigator.msPointerEnabled &&
  523. window.navigator.msMaxTouchPoints && !window.PointerEvent,
  524. pointer = (window.PointerEvent && window.navigator.pointerEnabled && window.navigator.maxTouchPoints) ||
  525. msPointer,
  526. retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) ||
  527. ('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') &&
  528. window.matchMedia('(min-resolution:144dpi)').matches),
  529.  
  530. doc = document.documentElement,
  531. ie3d = ie && ('transition' in doc.style),
  532. webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23,
  533. gecko3d = 'MozPerspective' in doc.style,
  534. opera3d = 'OTransition' in doc.style,
  535. any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs;
  536.  
  537.  
  538. // PhantomJS has 'ontouchstart' in document.documentElement, but doesn't actually support touch.
  539. // https://github.com/Leaflet/Leaflet/pull/1434#issuecomment-13843151
  540.  
  541. var touch = !window.L_NO_TOUCH && !phantomjs && (function () {
  542.  
  543. var startName = 'ontouchstart';
  544.  
  545. // IE10+ (We simulate these into touch* events in L.DomEvent and L.DomEvent.Pointer) or WebKit, etc.
  546. if (pointer || (startName in doc)) {
  547. return true;
  548. }
  549.  
  550. // Firefox/Gecko
  551. var div = document.createElement('div'),
  552. supported = false;
  553.  
  554. if (!div.setAttribute) {
  555. return false;
  556. }
  557. div.setAttribute(startName, 'return;');
  558.  
  559. if (typeof div[startName] === 'function') {
  560. supported = true;
  561. }
  562.  
  563. div.removeAttribute(startName);
  564. div = null;
  565.  
  566. return supported;
  567. }());
  568.  
  569.  
  570. L.Browser = {
  571. ie: ie,
  572. ielt9: ielt9,
  573. webkit: webkit,
  574. gecko: gecko && !webkit && !window.opera && !ie,
  575.  
  576. android: android,
  577. android23: android23,
  578.  
  579. chrome: chrome,
  580.  
  581. ie3d: ie3d,
  582. webkit3d: webkit3d,
  583. gecko3d: gecko3d,
  584. opera3d: opera3d,
  585. any3d: any3d,
  586.  
  587. mobile: mobile,
  588. mobileWebkit: mobile && webkit,
  589. mobileWebkit3d: mobile && webkit3d,
  590. mobileOpera: mobile && window.opera,
  591.  
  592. touch: touch,
  593. msPointer: msPointer,
  594. pointer: pointer,
  595.  
  596. retina: retina
  597. };
  598.  
  599. }());
  600.  
  601.  
  602. /*
  603. * L.Point represents a point with x and y coordinates.
  604. */
  605.  
  606. L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
  607. this.x = (round ? Math.round(x) : x);
  608. this.y = (round ? Math.round(y) : y);
  609. };
  610.  
  611. L.Point.prototype = {
  612.  
  613. clone: function () {
  614. return new L.Point(this.x, this.y);
  615. },
  616.  
  617. // non-destructive, returns a new point
  618. add: function (point) {
  619. return this.clone()._add(L.point(point));
  620. },
  621.  
  622. // destructive, used directly for performance in situations where it's safe to modify existing point
  623. _add: function (point) {
  624. this.x += point.x;
  625. this.y += point.y;
  626. return this;
  627. },
  628.  
  629. subtract: function (point) {
  630. return this.clone()._subtract(L.point(point));
  631. },
  632.  
  633. _subtract: function (point) {
  634. this.x -= point.x;
  635. this.y -= point.y;
  636. return this;
  637. },
  638.  
  639. divideBy: function (num) {
  640. return this.clone()._divideBy(num);
  641. },
  642.  
  643. _divideBy: function (num) {
  644. this.x /= num;
  645. this.y /= num;
  646. return this;
  647. },
  648.  
  649. multiplyBy: function (num) {
  650. return this.clone()._multiplyBy(num);
  651. },
  652.  
  653. _multiplyBy: function (num) {
  654. this.x *= num;
  655. this.y *= num;
  656. return this;
  657. },
  658.  
  659. round: function () {
  660. return this.clone()._round();
  661. },
  662.  
  663. _round: function () {
  664. this.x = Math.round(this.x);
  665. this.y = Math.round(this.y);
  666. return this;
  667. },
  668.  
  669. floor: function () {
  670. return this.clone()._floor();
  671. },
  672.  
  673. _floor: function () {
  674. this.x = Math.floor(this.x);
  675. this.y = Math.floor(this.y);
  676. return this;
  677. },
  678.  
  679. distanceTo: function (point) {
  680. point = L.point(point);
  681.  
  682. var x = point.x - this.x,
  683. y = point.y - this.y;
  684.  
  685. return Math.sqrt(x * x + y * y);
  686. },
  687.  
  688. equals: function (point) {
  689. point = L.point(point);
  690.  
  691. return point.x === this.x &&
  692. point.y === this.y;
  693. },
  694.  
  695. contains: function (point) {
  696. point = L.point(point);
  697.  
  698. return Math.abs(point.x) <= Math.abs(this.x) &&
  699. Math.abs(point.y) <= Math.abs(this.y);
  700. },
  701.  
  702. toString: function () {
  703. return 'Point(' +
  704. L.Util.formatNum(this.x) + ', ' +
  705. L.Util.formatNum(this.y) + ')';
  706. }
  707. };
  708.  
  709. L.point = function (x, y, round) {
  710. if (x instanceof L.Point) {
  711. return x;
  712. }
  713. if (L.Util.isArray(x)) {
  714. return new L.Point(x[0], x[1]);
  715. }
  716. if (x === undefined || x === null) {
  717. return x;
  718. }
  719. return new L.Point(x, y, round);
  720. };
  721.  
  722.  
  723. /*
  724. * L.Bounds represents a rectangular area on the screen in pixel coordinates.
  725. */
  726.  
  727. L.Bounds = function (a, b) { //(Point, Point) or Point[]
  728. if (!a) { return; }
  729.  
  730. var points = b ? [a, b] : a;
  731.  
  732. for (var i = 0, len = points.length; i < len; i++) {
  733. this.extend(points[i]);
  734. }
  735. };
  736.  
  737. L.Bounds.prototype = {
  738. // extend the bounds to contain the given point
  739. extend: function (point) { // (Point)
  740. point = L.point(point);
  741.  
  742. if (!this.min && !this.max) {
  743. this.min = point.clone();
  744. this.max = point.clone();
  745. } else {
  746. this.min.x = Math.min(point.x, this.min.x);
  747. this.max.x = Math.max(point.x, this.max.x);
  748. this.min.y = Math.min(point.y, this.min.y);
  749. this.max.y = Math.max(point.y, this.max.y);
  750. }
  751. return this;
  752. },
  753.  
  754. getCenter: function (round) { // (Boolean) -> Point
  755. return new L.Point(
  756. (this.min.x + this.max.x) / 2,
  757. (this.min.y + this.max.y) / 2, round);
  758. },
  759.  
  760. getBottomLeft: function () { // -> Point
  761. return new L.Point(this.min.x, this.max.y);
  762. },
  763.  
  764. getTopRight: function () { // -> Point
  765. return new L.Point(this.max.x, this.min.y);
  766. },
  767.  
  768. getSize: function () {
  769. return this.max.subtract(this.min);
  770. },
  771.  
  772. contains: function (obj) { // (Bounds) or (Point) -> Boolean
  773. var min, max;
  774.  
  775. if (typeof obj[0] === 'number' || obj instanceof L.Point) {
  776. obj = L.point(obj);
  777. } else {
  778. obj = L.bounds(obj);
  779. }
  780.  
  781. if (obj instanceof L.Bounds) {
  782. min = obj.min;
  783. max = obj.max;
  784. } else {
  785. min = max = obj;
  786. }
  787.  
  788. return (min.x >= this.min.x) &&
  789. (max.x <= this.max.x) &&
  790. (min.y >= this.min.y) &&
  791. (max.y <= this.max.y);
  792. },
  793.  
  794. intersects: function (bounds) { // (Bounds) -> Boolean
  795. bounds = L.bounds(bounds);
  796.  
  797. var min = this.min,
  798. max = this.max,
  799. min2 = bounds.min,
  800. max2 = bounds.max,
  801. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  802. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  803.  
  804. return xIntersects && yIntersects;
  805. },
  806.  
  807. isValid: function () {
  808. return !!(this.min && this.max);
  809. }
  810. };
  811.  
  812. L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
  813. if (!a || a instanceof L.Bounds) {
  814. return a;
  815. }
  816. return new L.Bounds(a, b);
  817. };
  818.  
  819.  
  820. /*
  821. * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
  822. */
  823.  
  824. L.Transformation = function (a, b, c, d) {
  825. this._a = a;
  826. this._b = b;
  827. this._c = c;
  828. this._d = d;
  829. };
  830.  
  831. L.Transformation.prototype = {
  832. transform: function (point, scale) { // (Point, Number) -> Point
  833. return this._transform(point.clone(), scale);
  834. },
  835.  
  836. // destructive transform (faster)
  837. _transform: function (point, scale) {
  838. scale = scale || 1;
  839. point.x = scale * (this._a * point.x + this._b);
  840. point.y = scale * (this._c * point.y + this._d);
  841. return point;
  842. },
  843.  
  844. untransform: function (point, scale) {
  845. scale = scale || 1;
  846. return new L.Point(
  847. (point.x / scale - this._b) / this._a,
  848. (point.y / scale - this._d) / this._c);
  849. }
  850. };
  851.  
  852.  
  853. /*
  854. * L.DomUtil contains various utility functions for working with DOM.
  855. */
  856.  
  857. L.DomUtil = {
  858. get: function (id) {
  859. return (typeof id === 'string' ? document.getElementById(id) : id);
  860. },
  861.  
  862. getStyle: function (el, style) {
  863.  
  864. var value = el.style[style];
  865.  
  866. if (!value && el.currentStyle) {
  867. value = el.currentStyle[style];
  868. }
  869.  
  870. if ((!value || value === 'auto') && document.defaultView) {
  871. var css = document.defaultView.getComputedStyle(el, null);
  872. value = css ? css[style] : null;
  873. }
  874.  
  875. return value === 'auto' ? null : value;
  876. },
  877.  
  878. getViewportOffset: function (element) {
  879.  
  880. var top = 0,
  881. left = 0,
  882. el = element,
  883. docBody = document.body,
  884. docEl = document.documentElement,
  885. pos;
  886.  
  887. do {
  888. top += el.offsetTop || 0;
  889. left += el.offsetLeft || 0;
  890.  
  891. //add borders
  892. top += parseInt(L.DomUtil.getStyle(el, 'borderTopWidth'), 10) || 0;
  893. left += parseInt(L.DomUtil.getStyle(el, 'borderLeftWidth'), 10) || 0;
  894.  
  895. pos = L.DomUtil.getStyle(el, 'position');
  896.  
  897. if (el.offsetParent === docBody && pos === 'absolute') { break; }
  898.  
  899. if (pos === 'fixed') {
  900. top += docBody.scrollTop || docEl.scrollTop || 0;
  901. left += docBody.scrollLeft || docEl.scrollLeft || 0;
  902. break;
  903. }
  904.  
  905. if (pos === 'relative' && !el.offsetLeft) {
  906. var width = L.DomUtil.getStyle(el, 'width'),
  907. maxWidth = L.DomUtil.getStyle(el, 'max-width'),
  908. r = el.getBoundingClientRect();
  909.  
  910. if (width !== 'none' || maxWidth !== 'none') {
  911. left += r.left + el.clientLeft;
  912. }
  913.  
  914. //calculate full y offset since we're breaking out of the loop
  915. top += r.top + (docBody.scrollTop || docEl.scrollTop || 0);
  916.  
  917. break;
  918. }
  919.  
  920. el = el.offsetParent;
  921.  
  922. } while (el);
  923.  
  924. el = element;
  925.  
  926. do {
  927. if (el === docBody) { break; }
  928.  
  929. top -= el.scrollTop || 0;
  930. left -= el.scrollLeft || 0;
  931.  
  932. el = el.parentNode;
  933. } while (el);
  934.  
  935. return new L.Point(left, top);
  936. },
  937.  
  938. documentIsLtr: function () {
  939. if (!L.DomUtil._docIsLtrCached) {
  940. L.DomUtil._docIsLtrCached = true;
  941. L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === 'ltr';
  942. }
  943. return L.DomUtil._docIsLtr;
  944. },
  945.  
  946. create: function (tagName, className, container) {
  947.  
  948. var el = document.createElement(tagName);
  949. el.className = className;
  950.  
  951. if (container) {
  952. container.appendChild(el);
  953. }
  954.  
  955. return el;
  956. },
  957.  
  958. hasClass: function (el, name) {
  959. if (el.classList !== undefined) {
  960. return el.classList.contains(name);
  961. }
  962. var className = L.DomUtil._getClass(el);
  963. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  964. },
  965.  
  966. addClass: function (el, name) {
  967. if (el.classList !== undefined) {
  968. var classes = L.Util.splitWords(name);
  969. for (var i = 0, len = classes.length; i < len; i++) {
  970. el.classList.add(classes[i]);
  971. }
  972. } else if (!L.DomUtil.hasClass(el, name)) {
  973. var className = L.DomUtil._getClass(el);
  974. L.DomUtil._setClass(el, (className ? className + ' ' : '') + name);
  975. }
  976. },
  977.  
  978. removeClass: function (el, name) {
  979. if (el.classList !== undefined) {
  980. el.classList.remove(name);
  981. } else {
  982. L.DomUtil._setClass(el, L.Util.trim((' ' + L.DomUtil._getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  983. }
  984. },
  985.  
  986. _setClass: function (el, name) {
  987. if (el.className.baseVal === undefined) {
  988. el.className = name;
  989. } else {
  990. // in case of SVG element
  991. el.className.baseVal = name;
  992. }
  993. },
  994.  
  995. _getClass: function (el) {
  996. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  997. },
  998.  
  999. setOpacity: function (el, value) {
  1000.  
  1001. if ('opacity' in el.style) {
  1002. el.style.opacity = value;
  1003.  
  1004. } else if ('filter' in el.style) {
  1005.  
  1006. var filter = false,
  1007. filterName = 'DXImageTransform.Microsoft.Alpha';
  1008.  
  1009. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  1010. try {
  1011. filter = el.filters.item(filterName);
  1012. } catch (e) {
  1013. // don't set opacity to 1 if we haven't already set an opacity,
  1014. // it isn't needed and breaks transparent pngs.
  1015. if (value === 1) { return; }
  1016. }
  1017.  
  1018. value = Math.round(value * 100);
  1019.  
  1020. if (filter) {
  1021. filter.Enabled = (value !== 100);
  1022. filter.Opacity = value;
  1023. } else {
  1024. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  1025. }
  1026. }
  1027. },
  1028.  
  1029. testProp: function (props) {
  1030.  
  1031. var style = document.documentElement.style;
  1032.  
  1033. for (var i = 0; i < props.length; i++) {
  1034. if (props[i] in style) {
  1035. return props[i];
  1036. }
  1037. }
  1038. return false;
  1039. },
  1040.  
  1041. getTranslateString: function (point) {
  1042. // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
  1043. // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
  1044. // (same speed either way), Opera 12 doesn't support translate3d
  1045.  
  1046. var is3d = L.Browser.webkit3d,
  1047. open = 'translate' + (is3d ? '3d' : '') + '(',
  1048. close = (is3d ? ',0' : '') + ')';
  1049.  
  1050. return open + point.x + 'px,' + point.y + 'px' + close;
  1051. },
  1052.  
  1053. getScaleString: function (scale, origin) {
  1054.  
  1055. var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
  1056. scaleStr = ' scale(' + scale + ') ';
  1057.  
  1058. return preTranslateStr + scaleStr;
  1059. },
  1060.  
  1061. setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
  1062.  
  1063. // jshint camelcase: false
  1064. el._leaflet_pos = point;
  1065.  
  1066. if (!disable3D && L.Browser.any3d) {
  1067. el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point);
  1068. } else {
  1069. el.style.left = point.x + 'px';
  1070. el.style.top = point.y + 'px';
  1071. }
  1072. },
  1073.  
  1074. getPosition: function (el) {
  1075. // this method is only used for elements previously positioned using setPosition,
  1076. // so it's safe to cache the position for performance
  1077.  
  1078. // jshint camelcase: false
  1079. return el._leaflet_pos;
  1080. }
  1081. };
  1082.  
  1083.  
  1084. // prefix style property names
  1085.  
  1086. L.DomUtil.TRANSFORM = L.DomUtil.testProp(
  1087. ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1088.  
  1089. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1090. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1091.  
  1092. L.DomUtil.TRANSITION = L.DomUtil.testProp(
  1093. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1094.  
  1095. L.DomUtil.TRANSITION_END =
  1096. L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
  1097. L.DomUtil.TRANSITION + 'End' : 'transitionend';
  1098.  
  1099. (function () {
  1100. if ('onselectstart' in document) {
  1101. L.extend(L.DomUtil, {
  1102. disableTextSelection: function () {
  1103. L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
  1104. },
  1105.  
  1106. enableTextSelection: function () {
  1107. L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
  1108. }
  1109. });
  1110. } else {
  1111. var userSelectProperty = L.DomUtil.testProp(
  1112. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  1113.  
  1114. L.extend(L.DomUtil, {
  1115. disableTextSelection: function () {
  1116. if (userSelectProperty) {
  1117. var style = document.documentElement.style;
  1118. this._userSelect = style[userSelectProperty];
  1119. style[userSelectProperty] = 'none';
  1120. }
  1121. },
  1122.  
  1123. enableTextSelection: function () {
  1124. if (userSelectProperty) {
  1125. document.documentElement.style[userSelectProperty] = this._userSelect;
  1126. delete this._userSelect;
  1127. }
  1128. }
  1129. });
  1130. }
  1131.  
  1132. L.extend(L.DomUtil, {
  1133. disableImageDrag: function () {
  1134. L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
  1135. },
  1136.  
  1137. enableImageDrag: function () {
  1138. L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
  1139. }
  1140. });
  1141. })();
  1142.  
  1143.  
  1144. /*
  1145. * L.LatLng represents a geographical point with latitude and longitude coordinates.
  1146. */
  1147.  
  1148. L.LatLng = function (lat, lng, alt) { // (Number, Number, Number)
  1149. lat = parseFloat(lat);
  1150. lng = parseFloat(lng);
  1151.  
  1152. if (isNaN(lat) || isNaN(lng)) {
  1153. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1154. }
  1155.  
  1156. this.lat = lat;
  1157. this.lng = lng;
  1158.  
  1159. if (alt !== undefined) {
  1160. this.alt = parseFloat(alt);
  1161. }
  1162. };
  1163.  
  1164. L.extend(L.LatLng, {
  1165. DEG_TO_RAD: Math.PI / 180,
  1166. RAD_TO_DEG: 180 / Math.PI,
  1167. MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
  1168. });
  1169.  
  1170. L.LatLng.prototype = {
  1171. equals: function (obj) { // (LatLng) -> Boolean
  1172. if (!obj) { return false; }
  1173.  
  1174. obj = L.latLng(obj);
  1175.  
  1176. var margin = Math.max(
  1177. Math.abs(this.lat - obj.lat),
  1178. Math.abs(this.lng - obj.lng));
  1179.  
  1180. return margin <= L.LatLng.MAX_MARGIN;
  1181. },
  1182.  
  1183. toString: function (precision) { // (Number) -> String
  1184. return 'LatLng(' +
  1185. L.Util.formatNum(this.lat, precision) + ', ' +
  1186. L.Util.formatNum(this.lng, precision) + ')';
  1187. },
  1188.  
  1189. // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
  1190. // TODO move to projection code, LatLng shouldn't know about Earth
  1191. distanceTo: function (other) { // (LatLng) -> Number
  1192. other = L.latLng(other);
  1193.  
  1194. var R = 6378137, // earth radius in meters
  1195. d2r = L.LatLng.DEG_TO_RAD,
  1196. dLat = (other.lat - this.lat) * d2r,
  1197. dLon = (other.lng - this.lng) * d2r,
  1198. lat1 = this.lat * d2r,
  1199. lat2 = other.lat * d2r,
  1200. sin1 = Math.sin(dLat / 2),
  1201. sin2 = Math.sin(dLon / 2);
  1202.  
  1203. var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
  1204.  
  1205. return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1206. },
  1207.  
  1208. wrap: function (a, b) { // (Number, Number) -> LatLng
  1209. var lng = this.lng;
  1210.  
  1211. a = a || -180;
  1212. b = b || 180;
  1213.  
  1214. lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a);
  1215.  
  1216. return new L.LatLng(this.lat, lng);
  1217. }
  1218. };
  1219.  
  1220. L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number)
  1221. if (a instanceof L.LatLng) {
  1222. return a;
  1223. }
  1224. if (L.Util.isArray(a)) {
  1225. if (typeof a[0] === 'number' || typeof a[0] === 'string') {
  1226. return new L.LatLng(a[0], a[1], a[2]);
  1227. } else {
  1228. return null;
  1229. }
  1230. }
  1231. if (a === undefined || a === null) {
  1232. return a;
  1233. }
  1234. if (typeof a === 'object' && 'lat' in a) {
  1235. return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon);
  1236. }
  1237. if (b === undefined) {
  1238. return null;
  1239. }
  1240. return new L.LatLng(a, b);
  1241. };
  1242.  
  1243.  
  1244.  
  1245. /*
  1246. * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
  1247. */
  1248.  
  1249. L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
  1250. if (!southWest) { return; }
  1251.  
  1252. var latlngs = northEast ? [southWest, northEast] : southWest;
  1253.  
  1254. for (var i = 0, len = latlngs.length; i < len; i++) {
  1255. this.extend(latlngs[i]);
  1256. }
  1257. };
  1258.  
  1259. L.LatLngBounds.prototype = {
  1260. // extend the bounds to contain the given point or bounds
  1261. extend: function (obj) { // (LatLng) or (LatLngBounds)
  1262. if (!obj) { return this; }
  1263.  
  1264. var latLng = L.latLng(obj);
  1265. if (latLng !== null) {
  1266. obj = latLng;
  1267. } else {
  1268. obj = L.latLngBounds(obj);
  1269. }
  1270.  
  1271. if (obj instanceof L.LatLng) {
  1272. if (!this._southWest && !this._northEast) {
  1273. this._southWest = new L.LatLng(obj.lat, obj.lng);
  1274. this._northEast = new L.LatLng(obj.lat, obj.lng);
  1275. } else {
  1276. this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
  1277. this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
  1278.  
  1279. this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
  1280. this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
  1281. }
  1282. } else if (obj instanceof L.LatLngBounds) {
  1283. this.extend(obj._southWest);
  1284. this.extend(obj._northEast);
  1285. }
  1286. return this;
  1287. },
  1288.  
  1289. // extend the bounds by a percentage
  1290. pad: function (bufferRatio) { // (Number) -> LatLngBounds
  1291. var sw = this._southWest,
  1292. ne = this._northEast,
  1293. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  1294. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  1295.  
  1296. return new L.LatLngBounds(
  1297. new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  1298. new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  1299. },
  1300.  
  1301. getCenter: function () { // -> LatLng
  1302. return new L.LatLng(
  1303. (this._southWest.lat + this._northEast.lat) / 2,
  1304. (this._southWest.lng + this._northEast.lng) / 2);
  1305. },
  1306.  
  1307. getSouthWest: function () {
  1308. return this._southWest;
  1309. },
  1310.  
  1311. getNorthEast: function () {
  1312. return this._northEast;
  1313. },
  1314.  
  1315. getNorthWest: function () {
  1316. return new L.LatLng(this.getNorth(), this.getWest());
  1317. },
  1318.  
  1319. getSouthEast: function () {
  1320. return new L.LatLng(this.getSouth(), this.getEast());
  1321. },
  1322.  
  1323. getWest: function () {
  1324. return this._southWest.lng;
  1325. },
  1326.  
  1327. getSouth: function () {
  1328. return this._southWest.lat;
  1329. },
  1330.  
  1331. getEast: function () {
  1332. return this._northEast.lng;
  1333. },
  1334.  
  1335. getNorth: function () {
  1336. return this._northEast.lat;
  1337. },
  1338.  
  1339. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1340. if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
  1341. obj = L.latLng(obj);
  1342. } else {
  1343. obj = L.latLngBounds(obj);
  1344. }
  1345.  
  1346. var sw = this._southWest,
  1347. ne = this._northEast,
  1348. sw2, ne2;
  1349.  
  1350. if (obj instanceof L.LatLngBounds) {
  1351. sw2 = obj.getSouthWest();
  1352. ne2 = obj.getNorthEast();
  1353. } else {
  1354. sw2 = ne2 = obj;
  1355. }
  1356.  
  1357. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1358. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1359. },
  1360.  
  1361. intersects: function (bounds) { // (LatLngBounds)
  1362. bounds = L.latLngBounds(bounds);
  1363.  
  1364. var sw = this._southWest,
  1365. ne = this._northEast,
  1366. sw2 = bounds.getSouthWest(),
  1367. ne2 = bounds.getNorthEast(),
  1368.  
  1369. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1370. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1371.  
  1372. return latIntersects && lngIntersects;
  1373. },
  1374.  
  1375. toBBoxString: function () {
  1376. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1377. },
  1378.  
  1379. equals: function (bounds) { // (LatLngBounds)
  1380. if (!bounds) { return false; }
  1381.  
  1382. bounds = L.latLngBounds(bounds);
  1383.  
  1384. return this._southWest.equals(bounds.getSouthWest()) &&
  1385. this._northEast.equals(bounds.getNorthEast());
  1386. },
  1387.  
  1388. isValid: function () {
  1389. return !!(this._southWest && this._northEast);
  1390. }
  1391. };
  1392.  
  1393. //TODO International date line?
  1394.  
  1395. L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
  1396. if (!a || a instanceof L.LatLngBounds) {
  1397. return a;
  1398. }
  1399. return new L.LatLngBounds(a, b);
  1400. };
  1401.  
  1402.  
  1403. /*
  1404. * L.Projection contains various geographical projections used by CRS classes.
  1405. */
  1406.  
  1407. L.Projection = {};
  1408.  
  1409.  
  1410. /*
  1411. * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default.
  1412. */
  1413.  
  1414. L.Projection.SphericalMercator = {
  1415. MAX_LATITUDE: 85.0511287798,
  1416.  
  1417. project: function (latlng) { // (LatLng) -> Point
  1418. var d = L.LatLng.DEG_TO_RAD,
  1419. max = this.MAX_LATITUDE,
  1420. lat = Math.max(Math.min(max, latlng.lat), -max),
  1421. x = latlng.lng * d,
  1422. y = lat * d;
  1423.  
  1424. y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
  1425.  
  1426. return new L.Point(x, y);
  1427. },
  1428.  
  1429. unproject: function (point) { // (Point, Boolean) -> LatLng
  1430. var d = L.LatLng.RAD_TO_DEG,
  1431. lng = point.x * d,
  1432. lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
  1433.  
  1434. return new L.LatLng(lat, lng);
  1435. }
  1436. };
  1437.  
  1438.  
  1439. /*
  1440. * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple.
  1441. */
  1442.  
  1443. L.Projection.LonLat = {
  1444. project: function (latlng) {
  1445. return new L.Point(latlng.lng, latlng.lat);
  1446. },
  1447.  
  1448. unproject: function (point) {
  1449. return new L.LatLng(point.y, point.x);
  1450. }
  1451. };
  1452.  
  1453.  
  1454. /*
  1455. * L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet.
  1456. */
  1457.  
  1458. L.CRS = {
  1459. latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
  1460. var projectedPoint = this.projection.project(latlng),
  1461. scale = this.scale(zoom);
  1462.  
  1463. return this.transformation._transform(projectedPoint, scale);
  1464. },
  1465.  
  1466. pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
  1467. var scale = this.scale(zoom),
  1468. untransformedPoint = this.transformation.untransform(point, scale);
  1469.  
  1470. return this.projection.unproject(untransformedPoint);
  1471. },
  1472.  
  1473. project: function (latlng) {
  1474. return this.projection.project(latlng);
  1475. },
  1476.  
  1477. scale: function (zoom) {
  1478. return 256 * Math.pow(2, zoom);
  1479. },
  1480.  
  1481. getSize: function (zoom) {
  1482. var s = this.scale(zoom);
  1483. return L.point(s, s);
  1484. }
  1485. };
  1486.  
  1487.  
  1488. /*
  1489. * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps.
  1490. */
  1491.  
  1492. L.CRS.Simple = L.extend({}, L.CRS, {
  1493. projection: L.Projection.LonLat,
  1494. transformation: new L.Transformation(1, 0, -1, 0),
  1495.  
  1496. scale: function (zoom) {
  1497. return Math.pow(2, zoom);
  1498. }
  1499. });
  1500.  
  1501.  
  1502. /*
  1503. * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping
  1504. * and is used by Leaflet by default.
  1505. */
  1506.  
  1507. L.CRS.EPSG3857 = L.extend({}, L.CRS, {
  1508. code: 'EPSG:3857',
  1509.  
  1510. projection: L.Projection.SphericalMercator,
  1511. transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
  1512.  
  1513. project: function (latlng) { // (LatLng) -> Point
  1514. var projectedPoint = this.projection.project(latlng),
  1515. earthRadius = 6378137;
  1516. return projectedPoint.multiplyBy(earthRadius);
  1517. }
  1518. });
  1519.  
  1520. L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
  1521. code: 'EPSG:900913'
  1522. });
  1523.  
  1524.  
  1525. /*
  1526. * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists.
  1527. */
  1528.  
  1529. L.CRS.EPSG4326 = L.extend({}, L.CRS, {
  1530. code: 'EPSG:4326',
  1531.  
  1532. projection: L.Projection.LonLat,
  1533. transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
  1534. });
  1535.  
  1536.  
  1537. /*
  1538. * L.Map is the central class of the API - it is used to create a map.
  1539. */
  1540.  
  1541. L.Map = L.Class.extend({
  1542.  
  1543. includes: L.Mixin.Events,
  1544.  
  1545. options: {
  1546. crs: L.CRS.EPSG3857,
  1547.  
  1548. /*
  1549. center: LatLng,
  1550. zoom: Number,
  1551. layers: Array,
  1552. */
  1553.  
  1554. fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
  1555. trackResize: true,
  1556. markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
  1557. },
  1558.  
  1559. initialize: function (id, options) { // (HTMLElement or String, Object)
  1560. options = L.setOptions(this, options);
  1561.  
  1562.  
  1563. this._initContainer(id);
  1564. this._initLayout();
  1565.  
  1566. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  1567. this._onResize = L.bind(this._onResize, this);
  1568.  
  1569. this._initEvents();
  1570.  
  1571. if (options.maxBounds) {
  1572. this.setMaxBounds(options.maxBounds);
  1573. }
  1574.  
  1575. if (options.center && options.zoom !== undefined) {
  1576. this.setView(L.latLng(options.center), options.zoom, {reset: true});
  1577. }
  1578.  
  1579. this._handlers = [];
  1580.  
  1581. this._layers = {};
  1582. this._zoomBoundLayers = {};
  1583. this._tileLayersNum = 0;
  1584.  
  1585. this.callInitHooks();
  1586.  
  1587. this._addLayers(options.layers);
  1588. },
  1589.  
  1590.  
  1591. // public methods that modify map state
  1592.  
  1593. // replaced by animation-powered implementation in Map.PanAnimation.js
  1594. setView: function (center, zoom) {
  1595. zoom = zoom === undefined ? this.getZoom() : zoom;
  1596. this._resetView(L.latLng(center), this._limitZoom(zoom));
  1597. return this;
  1598. },
  1599.  
  1600. setZoom: function (zoom, options) {
  1601. if (!this._loaded) {
  1602. this._zoom = this._limitZoom(zoom);
  1603. return this;
  1604. }
  1605. return this.setView(this.getCenter(), zoom, {zoom: options});
  1606. },
  1607.  
  1608. zoomIn: function (delta, options) {
  1609. return this.setZoom(this._zoom + (delta || 1), options);
  1610. },
  1611.  
  1612. zoomOut: function (delta, options) {
  1613. return this.setZoom(this._zoom - (delta || 1), options);
  1614. },
  1615.  
  1616. setZoomAround: function (latlng, zoom, options) {
  1617. var scale = this.getZoomScale(zoom),
  1618. viewHalf = this.getSize().divideBy(2),
  1619. containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
  1620.  
  1621. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  1622. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  1623.  
  1624. return this.setView(newCenter, zoom, {zoom: options});
  1625. },
  1626.  
  1627. fitBounds: function (bounds, options) {
  1628.  
  1629. options = options || {};
  1630. bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
  1631.  
  1632. var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
  1633. paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
  1634.  
  1635. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)),
  1636. paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  1637.  
  1638. swPoint = this.project(bounds.getSouthWest(), zoom),
  1639. nePoint = this.project(bounds.getNorthEast(), zoom),
  1640. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  1641.  
  1642. zoom = options && options.maxZoom ? Math.min(options.maxZoom, zoom) : zoom;
  1643.  
  1644. return this.setView(center, zoom, options);
  1645. },
  1646.  
  1647. fitWorld: function (options) {
  1648. return this.fitBounds([[-90, -180], [90, 180]], options);
  1649. },
  1650.  
  1651. panTo: function (center, options) { // (LatLng)
  1652. return this.setView(center, this._zoom, {pan: options});
  1653. },
  1654.  
  1655. panBy: function (offset) { // (Point)
  1656. // replaced with animated panBy in Map.PanAnimation.js
  1657. this.fire('movestart');
  1658.  
  1659. this._rawPanBy(L.point(offset));
  1660.  
  1661. this.fire('move');
  1662. return this.fire('moveend');
  1663. },
  1664.  
  1665. setMaxBounds: function (bounds) {
  1666. bounds = L.latLngBounds(bounds);
  1667.  
  1668. this.options.maxBounds = bounds;
  1669.  
  1670. if (!bounds) {
  1671. return this.off('moveend', this._panInsideMaxBounds, this);
  1672. }
  1673.  
  1674. if (this._loaded) {
  1675. this._panInsideMaxBounds();
  1676. }
  1677.  
  1678. return this.on('moveend', this._panInsideMaxBounds, this);
  1679. },
  1680.  
  1681. panInsideBounds: function (bounds, options) {
  1682. var center = this.getCenter(),
  1683. newCenter = this._limitCenter(center, this._zoom, bounds);
  1684.  
  1685. if (center.equals(newCenter)) { return this; }
  1686.  
  1687. return this.panTo(newCenter, options);
  1688. },
  1689.  
  1690. addLayer: function (layer) {
  1691. // TODO method is too big, refactor
  1692.  
  1693. var id = L.stamp(layer);
  1694.  
  1695. if (this._layers[id]) { return this; }
  1696.  
  1697. this._layers[id] = layer;
  1698.  
  1699. // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
  1700. if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) {
  1701. this._zoomBoundLayers[id] = layer;
  1702. this._updateZoomLevels();
  1703. }
  1704.  
  1705. // TODO looks ugly, refactor!!!
  1706. if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
  1707. this._tileLayersNum++;
  1708. this._tileLayersToLoad++;
  1709. layer.on('load', this._onTileLayerLoad, this);
  1710. }
  1711.  
  1712. if (this._loaded) {
  1713. this._layerAdd(layer);
  1714. }
  1715.  
  1716. return this;
  1717. },
  1718.  
  1719. removeLayer: function (layer) {
  1720. var id = L.stamp(layer);
  1721.  
  1722. if (!this._layers[id]) { return this; }
  1723.  
  1724. if (this._loaded) {
  1725. layer.onRemove(this);
  1726. }
  1727.  
  1728. delete this._layers[id];
  1729.  
  1730. if (this._loaded) {
  1731. this.fire('layerremove', {layer: layer});
  1732. }
  1733.  
  1734. if (this._zoomBoundLayers[id]) {
  1735. delete this._zoomBoundLayers[id];
  1736. this._updateZoomLevels();
  1737. }
  1738.  
  1739. // TODO looks ugly, refactor
  1740. if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
  1741. this._tileLayersNum--;
  1742. this._tileLayersToLoad--;
  1743. layer.off('load', this._onTileLayerLoad, this);
  1744. }
  1745.  
  1746. return this;
  1747. },
  1748.  
  1749. hasLayer: function (layer) {
  1750. if (!layer) { return false; }
  1751.  
  1752. return (L.stamp(layer) in this._layers);
  1753. },
  1754.  
  1755. eachLayer: function (method, context) {
  1756. for (var i in this._layers) {
  1757. method.call(context, this._layers[i]);
  1758. }
  1759. return this;
  1760. },
  1761.  
  1762. invalidateSize: function (options) {
  1763. if (!this._loaded) { return this; }
  1764.  
  1765. options = L.extend({
  1766. animate: false,
  1767. pan: true
  1768. }, options === true ? {animate: true} : options);
  1769.  
  1770. var oldSize = this.getSize();
  1771. this._sizeChanged = true;
  1772. this._initialCenter = null;
  1773.  
  1774. var newSize = this.getSize(),
  1775. oldCenter = oldSize.divideBy(2).round(),
  1776. newCenter = newSize.divideBy(2).round(),
  1777. offset = oldCenter.subtract(newCenter);
  1778.  
  1779. if (!offset.x && !offset.y) { return this; }
  1780.  
  1781. if (options.animate && options.pan) {
  1782. this.panBy(offset);
  1783.  
  1784. } else {
  1785. if (options.pan) {
  1786. this._rawPanBy(offset);
  1787. }
  1788.  
  1789. this.fire('move');
  1790.  
  1791. if (options.debounceMoveend) {
  1792. clearTimeout(this._sizeTimer);
  1793. this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
  1794. } else {
  1795. this.fire('moveend');
  1796. }
  1797. }
  1798.  
  1799. return this.fire('resize', {
  1800. oldSize: oldSize,
  1801. newSize: newSize
  1802. });
  1803. },
  1804.  
  1805. // TODO handler.addTo
  1806. addHandler: function (name, HandlerClass) {
  1807. if (!HandlerClass) { return this; }
  1808.  
  1809. var handler = this[name] = new HandlerClass(this);
  1810.  
  1811. this._handlers.push(handler);
  1812.  
  1813. if (this.options[name]) {
  1814. handler.enable();
  1815. }
  1816.  
  1817. return this;
  1818. },
  1819.  
  1820. remove: function () {
  1821. if (this._loaded) {
  1822. this.fire('unload');
  1823. }
  1824.  
  1825. this._initEvents('off');
  1826.  
  1827. try {
  1828. // throws error in IE6-8
  1829. delete this._container._leaflet;
  1830. } catch (e) {
  1831. this._container._leaflet = undefined;
  1832. }
  1833.  
  1834. this._clearPanes();
  1835. if (this._clearControlPos) {
  1836. this._clearControlPos();
  1837. }
  1838.  
  1839. this._clearHandlers();
  1840.  
  1841. return this;
  1842. },
  1843.  
  1844.  
  1845. // public methods for getting map state
  1846.  
  1847. getCenter: function () { // (Boolean) -> LatLng
  1848. this._checkIfLoaded();
  1849.  
  1850. if (this._initialCenter && !this._moved()) {
  1851. return this._initialCenter;
  1852. }
  1853. return this.layerPointToLatLng(this._getCenterLayerPoint());
  1854. },
  1855.  
  1856. getZoom: function () {
  1857. return this._zoom;
  1858. },
  1859.  
  1860. getBounds: function () {
  1861. var bounds = this.getPixelBounds(),
  1862. sw = this.unproject(bounds.getBottomLeft()),
  1863. ne = this.unproject(bounds.getTopRight());
  1864.  
  1865. return new L.LatLngBounds(sw, ne);
  1866. },
  1867.  
  1868. getMinZoom: function () {
  1869. return this.options.minZoom === undefined ?
  1870. (this._layersMinZoom === undefined ? 0 : this._layersMinZoom) :
  1871. this.options.minZoom;
  1872. },
  1873.  
  1874. getMaxZoom: function () {
  1875. return this.options.maxZoom === undefined ?
  1876. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  1877. this.options.maxZoom;
  1878. },
  1879.  
  1880. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  1881. bounds = L.latLngBounds(bounds);
  1882.  
  1883. var zoom = this.getMinZoom() - (inside ? 1 : 0),
  1884. maxZoom = this.getMaxZoom(),
  1885. size = this.getSize(),
  1886.  
  1887. nw = bounds.getNorthWest(),
  1888. se = bounds.getSouthEast(),
  1889.  
  1890. zoomNotFound = true,
  1891. boundsSize;
  1892.  
  1893. padding = L.point(padding || [0, 0]);
  1894.  
  1895. do {
  1896. zoom++;
  1897. boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
  1898. zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;
  1899.  
  1900. } while (zoomNotFound && zoom <= maxZoom);
  1901.  
  1902. if (zoomNotFound && inside) {
  1903. return null;
  1904. }
  1905.  
  1906. return inside ? zoom : zoom - 1;
  1907. },
  1908.  
  1909. getSize: function () {
  1910. if (!this._size || this._sizeChanged) {
  1911. this._size = new L.Point(
  1912. this._container.clientWidth,
  1913. this._container.clientHeight);
  1914.  
  1915. this._sizeChanged = false;
  1916. }
  1917. return this._size.clone();
  1918. },
  1919.  
  1920. getPixelBounds: function () {
  1921. var topLeftPoint = this._getTopLeftPoint();
  1922. return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  1923. },
  1924.  
  1925. getPixelOrigin: function () {
  1926. this._checkIfLoaded();
  1927. return this._initialTopLeftPoint;
  1928. },
  1929.  
  1930. getPanes: function () {
  1931. return this._panes;
  1932. },
  1933.  
  1934. getContainer: function () {
  1935. return this._container;
  1936. },
  1937.  
  1938.  
  1939. // TODO replace with universal implementation after refactoring projections
  1940.  
  1941. getZoomScale: function (toZoom) {
  1942. var crs = this.options.crs;
  1943. return crs.scale(toZoom) / crs.scale(this._zoom);
  1944. },
  1945.  
  1946. getScaleZoom: function (scale) {
  1947. return this._zoom + (Math.log(scale) / Math.LN2);
  1948. },
  1949.  
  1950.  
  1951. // conversion methods
  1952.  
  1953. project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
  1954. zoom = zoom === undefined ? this._zoom : zoom;
  1955. return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
  1956. },
  1957.  
  1958. unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
  1959. zoom = zoom === undefined ? this._zoom : zoom;
  1960. return this.options.crs.pointToLatLng(L.point(point), zoom);
  1961. },
  1962.  
  1963. layerPointToLatLng: function (point) { // (Point)
  1964. var projectedPoint = L.point(point).add(this.getPixelOrigin());
  1965. return this.unproject(projectedPoint);
  1966. },
  1967.  
  1968. latLngToLayerPoint: function (latlng) { // (LatLng)
  1969. var projectedPoint = this.project(L.latLng(latlng))._round();
  1970. return projectedPoint._subtract(this.getPixelOrigin());
  1971. },
  1972.  
  1973. containerPointToLayerPoint: function (point) { // (Point)
  1974. return L.point(point).subtract(this._getMapPanePos());
  1975. },
  1976.  
  1977. layerPointToContainerPoint: function (point) { // (Point)
  1978. return L.point(point).add(this._getMapPanePos());
  1979. },
  1980.  
  1981. containerPointToLatLng: function (point) {
  1982. var layerPoint = this.containerPointToLayerPoint(L.point(point));
  1983. return this.layerPointToLatLng(layerPoint);
  1984. },
  1985.  
  1986. latLngToContainerPoint: function (latlng) {
  1987. return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
  1988. },
  1989.  
  1990. mouseEventToContainerPoint: function (e) { // (MouseEvent)
  1991. return L.DomEvent.getMousePosition(e, this._container);
  1992. },
  1993.  
  1994. mouseEventToLayerPoint: function (e) { // (MouseEvent)
  1995. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  1996. },
  1997.  
  1998. mouseEventToLatLng: function (e) { // (MouseEvent)
  1999. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  2000. },
  2001.  
  2002.  
  2003. // map initialization methods
  2004.  
  2005. _initContainer: function (id) {
  2006. var container = this._container = L.DomUtil.get(id);
  2007.  
  2008. if (!container) {
  2009. throw new Error('Map container not found.');
  2010. } else if (container._leaflet) {
  2011. throw new Error('Map container is already initialized.');
  2012. }
  2013.  
  2014. container._leaflet = true;
  2015. },
  2016.  
  2017. _initLayout: function () {
  2018. var container = this._container;
  2019.  
  2020. L.DomUtil.addClass(container, 'leaflet-container' +
  2021. (L.Browser.touch ? ' leaflet-touch' : '') +
  2022. (L.Browser.retina ? ' leaflet-retina' : '') +
  2023. (L.Browser.ielt9 ? ' leaflet-oldie' : '') +
  2024. (this.options.fadeAnimation ? ' leaflet-fade-anim' : ''));
  2025.  
  2026. var position = L.DomUtil.getStyle(container, 'position');
  2027.  
  2028. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  2029. container.style.position = 'relative';
  2030. }
  2031.  
  2032. this._initPanes();
  2033.  
  2034. if (this._initControlPos) {
  2035. this._initControlPos();
  2036. }
  2037. },
  2038.  
  2039. _initPanes: function () {
  2040. var panes = this._panes = {};
  2041.  
  2042. this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
  2043.  
  2044. this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
  2045. panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
  2046. panes.shadowPane = this._createPane('leaflet-shadow-pane');
  2047. panes.overlayPane = this._createPane('leaflet-overlay-pane');
  2048. panes.markerPane = this._createPane('leaflet-marker-pane');
  2049. panes.popupPane = this._createPane('leaflet-popup-pane');
  2050.  
  2051. var zoomHide = ' leaflet-zoom-hide';
  2052.  
  2053. if (!this.options.markerZoomAnimation) {
  2054. L.DomUtil.addClass(panes.markerPane, zoomHide);
  2055. L.DomUtil.addClass(panes.shadowPane, zoomHide);
  2056. L.DomUtil.addClass(panes.popupPane, zoomHide);
  2057. }
  2058. },
  2059.  
  2060. _createPane: function (className, container) {
  2061. return L.DomUtil.create('div', className, container || this._panes.objectsPane);
  2062. },
  2063.  
  2064. _clearPanes: function () {
  2065. this._container.removeChild(this._mapPane);
  2066. },
  2067.  
  2068. _addLayers: function (layers) {
  2069. layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
  2070.  
  2071. for (var i = 0, len = layers.length; i < len; i++) {
  2072. this.addLayer(layers[i]);
  2073. }
  2074. },
  2075.  
  2076.  
  2077. // private methods that modify map state
  2078.  
  2079. _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
  2080.  
  2081. var zoomChanged = (this._zoom !== zoom);
  2082.  
  2083. if (!afterZoomAnim) {
  2084. this.fire('movestart');
  2085.  
  2086. if (zoomChanged) {
  2087. this.fire('zoomstart');
  2088. }
  2089. }
  2090.  
  2091. this._zoom = zoom;
  2092. this._initialCenter = center;
  2093.  
  2094. this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
  2095.  
  2096. if (!preserveMapOffset) {
  2097. L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
  2098. } else {
  2099. this._initialTopLeftPoint._add(this._getMapPanePos());
  2100. }
  2101.  
  2102. this._tileLayersToLoad = this._tileLayersNum;
  2103.  
  2104. var loading = !this._loaded;
  2105. this._loaded = true;
  2106.  
  2107. this.fire('viewreset', {hard: !preserveMapOffset});
  2108.  
  2109. if (loading) {
  2110. this.fire('load');
  2111. this.eachLayer(this._layerAdd, this);
  2112. }
  2113.  
  2114. this.fire('move');
  2115.  
  2116. if (zoomChanged || afterZoomAnim) {
  2117. this.fire('zoomend');
  2118. }
  2119.  
  2120. this.fire('moveend', {hard: !preserveMapOffset});
  2121. },
  2122.  
  2123. _rawPanBy: function (offset) {
  2124. L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  2125. },
  2126.  
  2127. _getZoomSpan: function () {
  2128. return this.getMaxZoom() - this.getMinZoom();
  2129. },
  2130.  
  2131. _updateZoomLevels: function () {
  2132. var i,
  2133. minZoom = Infinity,
  2134. maxZoom = -Infinity,
  2135. oldZoomSpan = this._getZoomSpan();
  2136.  
  2137. for (i in this._zoomBoundLayers) {
  2138. var layer = this._zoomBoundLayers[i];
  2139. if (!isNaN(layer.options.minZoom)) {
  2140. minZoom = Math.min(minZoom, layer.options.minZoom);
  2141. }
  2142. if (!isNaN(layer.options.maxZoom)) {
  2143. maxZoom = Math.max(maxZoom, layer.options.maxZoom);
  2144. }
  2145. }
  2146.  
  2147. if (i === undefined) { // we have no tilelayers
  2148. this._layersMaxZoom = this._layersMinZoom = undefined;
  2149. } else {
  2150. this._layersMaxZoom = maxZoom;
  2151. this._layersMinZoom = minZoom;
  2152. }
  2153.  
  2154. if (oldZoomSpan !== this._getZoomSpan()) {
  2155. this.fire('zoomlevelschange');
  2156. }
  2157. },
  2158.  
  2159. _panInsideMaxBounds: function () {
  2160. this.panInsideBounds(this.options.maxBounds);
  2161. },
  2162.  
  2163. _checkIfLoaded: function () {
  2164. if (!this._loaded) {
  2165. throw new Error('Set map center and zoom first.');
  2166. }
  2167. },
  2168.  
  2169. // map events
  2170.  
  2171. _initEvents: function (onOff) {
  2172. if (!L.DomEvent) { return; }
  2173.  
  2174. onOff = onOff || 'on';
  2175.  
  2176. L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this);
  2177.  
  2178. var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
  2179. 'mouseleave', 'mousemove', 'contextmenu'],
  2180. i, len;
  2181.  
  2182. for (i = 0, len = events.length; i < len; i++) {
  2183. L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this);
  2184. }
  2185.  
  2186. if (this.options.trackResize) {
  2187. L.DomEvent[onOff](window, 'resize', this._onResize, this);
  2188. }
  2189. },
  2190.  
  2191. _onResize: function () {
  2192. L.Util.cancelAnimFrame(this._resizeRequest);
  2193. this._resizeRequest = L.Util.requestAnimFrame(
  2194. function () { this.invalidateSize({debounceMoveend: true}); }, this, false, this._container);
  2195. },
  2196.  
  2197. _onMouseClick: function (e) {
  2198. if (!this._loaded || (!e._simulated &&
  2199. ((this.dragging && this.dragging.moved()) ||
  2200. (this.boxZoom && this.boxZoom.moved()))) ||
  2201. L.DomEvent._skipped(e)) { return; }
  2202.  
  2203. this.fire('preclick');
  2204. this._fireMouseEvent(e);
  2205. },
  2206.  
  2207. _fireMouseEvent: function (e) {
  2208. if (!this._loaded || L.DomEvent._skipped(e)) { return; }
  2209.  
  2210. var type = e.type;
  2211.  
  2212. type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
  2213.  
  2214. if (!this.hasEventListeners(type)) { return; }
  2215.  
  2216. if (type === 'contextmenu') {
  2217. L.DomEvent.preventDefault(e);
  2218. }
  2219.  
  2220. var containerPoint = this.mouseEventToContainerPoint(e),
  2221. layerPoint = this.containerPointToLayerPoint(containerPoint),
  2222. latlng = this.layerPointToLatLng(layerPoint);
  2223.  
  2224. this.fire(type, {
  2225. latlng: latlng,
  2226. layerPoint: layerPoint,
  2227. containerPoint: containerPoint,
  2228. originalEvent: e
  2229. });
  2230. },
  2231.  
  2232. _onTileLayerLoad: function () {
  2233. this._tileLayersToLoad--;
  2234. if (this._tileLayersNum && !this._tileLayersToLoad) {
  2235. this.fire('tilelayersload');
  2236. }
  2237. },
  2238.  
  2239. _clearHandlers: function () {
  2240. for (var i = 0, len = this._handlers.length; i < len; i++) {
  2241. this._handlers[i].disable();
  2242. }
  2243. },
  2244.  
  2245. whenReady: function (callback, context) {
  2246. if (this._loaded) {
  2247. callback.call(context || this, this);
  2248. } else {
  2249. this.on('load', callback, context);
  2250. }
  2251. return this;
  2252. },
  2253.  
  2254. _layerAdd: function (layer) {
  2255. layer.onAdd(this);
  2256. this.fire('layeradd', {layer: layer});
  2257. },
  2258.  
  2259.  
  2260. // private methods for getting map state
  2261.  
  2262. _getMapPanePos: function () {
  2263. return L.DomUtil.getPosition(this._mapPane);
  2264. },
  2265.  
  2266. _moved: function () {
  2267. var pos = this._getMapPanePos();
  2268. return pos && !pos.equals([0, 0]);
  2269. },
  2270.  
  2271. _getTopLeftPoint: function () {
  2272. return this.getPixelOrigin().subtract(this._getMapPanePos());
  2273. },
  2274.  
  2275. _getNewTopLeftPoint: function (center, zoom) {
  2276. var viewHalf = this.getSize()._divideBy(2);
  2277. // TODO round on display, not calculation to increase precision?
  2278. return this.project(center, zoom)._subtract(viewHalf)._round();
  2279. },
  2280.  
  2281. _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
  2282. var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
  2283. return this.project(latlng, newZoom)._subtract(topLeft);
  2284. },
  2285.  
  2286. // layer point of the current center
  2287. _getCenterLayerPoint: function () {
  2288. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  2289. },
  2290.  
  2291. // offset of the specified place to the current center in pixels
  2292. _getCenterOffset: function (latlng) {
  2293. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  2294. },
  2295.  
  2296. // adjust center for view to get inside bounds
  2297. _limitCenter: function (center, zoom, bounds) {
  2298.  
  2299. if (!bounds) { return center; }
  2300.  
  2301. var centerPoint = this.project(center, zoom),
  2302. viewHalf = this.getSize().divideBy(2),
  2303. viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  2304. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  2305.  
  2306. return this.unproject(centerPoint.add(offset), zoom);
  2307. },
  2308.  
  2309. // adjust offset for view to get inside bounds
  2310. _limitOffset: function (offset, bounds) {
  2311. if (!bounds) { return offset; }
  2312.  
  2313. var viewBounds = this.getPixelBounds(),
  2314. newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  2315.  
  2316. return offset.add(this._getBoundsOffset(newBounds, bounds));
  2317. },
  2318.  
  2319. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  2320. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  2321. var nwOffset = this.project(maxBounds.getNorthWest(), zoom).subtract(pxBounds.min),
  2322. seOffset = this.project(maxBounds.getSouthEast(), zoom).subtract(pxBounds.max),
  2323.  
  2324. dx = this._rebound(nwOffset.x, -seOffset.x),
  2325. dy = this._rebound(nwOffset.y, -seOffset.y);
  2326.  
  2327. return new L.Point(dx, dy);
  2328. },
  2329.  
  2330. _rebound: function (left, right) {
  2331. return left + right > 0 ?
  2332. Math.round(left - right) / 2 :
  2333. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  2334. },
  2335.  
  2336. _limitZoom: function (zoom) {
  2337. var min = this.getMinZoom(),
  2338. max = this.getMaxZoom();
  2339.  
  2340. return Math.max(min, Math.min(max, zoom));
  2341. }
  2342. });
  2343.  
  2344. L.map = function (id, options) {
  2345. return new L.Map(id, options);
  2346. };
  2347.  
  2348.  
  2349. /*
  2350. * Mercator projection that takes into account that the Earth is not a perfect sphere.
  2351. * Less popular than spherical mercator; used by projections like EPSG:3395.
  2352. */
  2353.  
  2354. L.Projection.Mercator = {
  2355. MAX_LATITUDE: 85.0840591556,
  2356.  
  2357. R_MINOR: 6356752.314245179,
  2358. R_MAJOR: 6378137,
  2359.  
  2360. project: function (latlng) { // (LatLng) -> Point
  2361. var d = L.LatLng.DEG_TO_RAD,
  2362. max = this.MAX_LATITUDE,
  2363. lat = Math.max(Math.min(max, latlng.lat), -max),
  2364. r = this.R_MAJOR,
  2365. r2 = this.R_MINOR,
  2366. x = latlng.lng * d * r,
  2367. y = lat * d,
  2368. tmp = r2 / r,
  2369. eccent = Math.sqrt(1.0 - tmp * tmp),
  2370. con = eccent * Math.sin(y);
  2371.  
  2372. con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
  2373.  
  2374. var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
  2375. y = -r * Math.log(ts);
  2376.  
  2377. return new L.Point(x, y);
  2378. },
  2379.  
  2380. unproject: function (point) { // (Point, Boolean) -> LatLng
  2381. var d = L.LatLng.RAD_TO_DEG,
  2382. r = this.R_MAJOR,
  2383. r2 = this.R_MINOR,
  2384. lng = point.x * d / r,
  2385. tmp = r2 / r,
  2386. eccent = Math.sqrt(1 - (tmp * tmp)),
  2387. ts = Math.exp(- point.y / r),
  2388. phi = (Math.PI / 2) - 2 * Math.atan(ts),
  2389. numIter = 15,
  2390. tol = 1e-7,
  2391. i = numIter,
  2392. dphi = 0.1,
  2393. con;
  2394.  
  2395. while ((Math.abs(dphi) > tol) && (--i > 0)) {
  2396. con = eccent * Math.sin(phi);
  2397. dphi = (Math.PI / 2) - 2 * Math.atan(ts *
  2398. Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
  2399. phi += dphi;
  2400. }
  2401.  
  2402. return new L.LatLng(phi * d, lng);
  2403. }
  2404. };
  2405.  
  2406.  
  2407.  
  2408. L.CRS.EPSG3395 = L.extend({}, L.CRS, {
  2409. code: 'EPSG:3395',
  2410.  
  2411. projection: L.Projection.Mercator,
  2412.  
  2413. transformation: (function () {
  2414. var m = L.Projection.Mercator,
  2415. r = m.R_MAJOR,
  2416. scale = 0.5 / (Math.PI * r);
  2417.  
  2418. return new L.Transformation(scale, 0.5, -scale, 0.5);
  2419. }())
  2420. });
  2421.  
  2422.  
  2423. /*
  2424. * L.TileLayer is used for standard xyz-numbered tile layers.
  2425. */
  2426.  
  2427. L.TileLayer = L.Class.extend({
  2428. includes: L.Mixin.Events,
  2429.  
  2430. options: {
  2431. minZoom: 0,
  2432. maxZoom: 18,
  2433. tileSize: 256,
  2434. subdomains: 'abc',
  2435. errorTileUrl: '',
  2436. attribution: '',
  2437. zoomOffset: 0,
  2438. opacity: 1,
  2439. /*
  2440. maxNativeZoom: null,
  2441. zIndex: null,
  2442. tms: false,
  2443. continuousWorld: false,
  2444. noWrap: false,
  2445. zoomReverse: false,
  2446. detectRetina: false,
  2447. reuseTiles: false,
  2448. bounds: false,
  2449. */
  2450. unloadInvisibleTiles: L.Browser.mobile,
  2451. updateWhenIdle: L.Browser.mobile
  2452. },
  2453.  
  2454. initialize: function (url, options) {
  2455. options = L.setOptions(this, options);
  2456.  
  2457. // detecting retina displays, adjusting tileSize and zoom levels
  2458. if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
  2459.  
  2460. options.tileSize = Math.floor(options.tileSize / 2);
  2461. options.zoomOffset++;
  2462.  
  2463. if (options.minZoom > 0) {
  2464. options.minZoom--;
  2465. }
  2466. this.options.maxZoom--;
  2467. }
  2468.  
  2469. if (options.bounds) {
  2470. options.bounds = L.latLngBounds(options.bounds);
  2471. }
  2472.  
  2473. this._url = url;
  2474.  
  2475. var subdomains = this.options.subdomains;
  2476.  
  2477. if (typeof subdomains === 'string') {
  2478. this.options.subdomains = subdomains.split('');
  2479. }
  2480. },
  2481.  
  2482. onAdd: function (map) {
  2483. this._map = map;
  2484. this._animated = map._zoomAnimated;
  2485.  
  2486. // create a container div for tiles
  2487. this._initContainer();
  2488.  
  2489. // set up events
  2490. map.on({
  2491. 'viewreset': this._reset,
  2492. 'moveend': this._update
  2493. }, this);
  2494.  
  2495. if (this._animated) {
  2496. map.on({
  2497. 'zoomanim': this._animateZoom,
  2498. 'zoomend': this._endZoomAnim
  2499. }, this);
  2500. }
  2501.  
  2502. if (!this.options.updateWhenIdle) {
  2503. this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
  2504. map.on('move', this._limitedUpdate, this);
  2505. }
  2506.  
  2507. this._reset();
  2508. this._update();
  2509. },
  2510.  
  2511. addTo: function (map) {
  2512. map.addLayer(this);
  2513. return this;
  2514. },
  2515.  
  2516. onRemove: function (map) {
  2517. this._container.parentNode.removeChild(this._container);
  2518.  
  2519. map.off({
  2520. 'viewreset': this._reset,
  2521. 'moveend': this._update
  2522. }, this);
  2523.  
  2524. if (this._animated) {
  2525. map.off({
  2526. 'zoomanim': this._animateZoom,
  2527. 'zoomend': this._endZoomAnim
  2528. }, this);
  2529. }
  2530.  
  2531. if (!this.options.updateWhenIdle) {
  2532. map.off('move', this._limitedUpdate, this);
  2533. }
  2534.  
  2535. this._container = null;
  2536. this._map = null;
  2537. },
  2538.  
  2539. bringToFront: function () {
  2540. var pane = this._map._panes.tilePane;
  2541.  
  2542. if (this._container) {
  2543. pane.appendChild(this._container);
  2544. this._setAutoZIndex(pane, Math.max);
  2545. }
  2546.  
  2547. return this;
  2548. },
  2549.  
  2550. bringToBack: function () {
  2551. var pane = this._map._panes.tilePane;
  2552.  
  2553. if (this._container) {
  2554. pane.insertBefore(this._container, pane.firstChild);
  2555. this._setAutoZIndex(pane, Math.min);
  2556. }
  2557.  
  2558. return this;
  2559. },
  2560.  
  2561. getAttribution: function () {
  2562. return this.options.attribution;
  2563. },
  2564.  
  2565. getContainer: function () {
  2566. return this._container;
  2567. },
  2568.  
  2569. setOpacity: function (opacity) {
  2570. this.options.opacity = opacity;
  2571.  
  2572. if (this._map) {
  2573. this._updateOpacity();
  2574. }
  2575.  
  2576. return this;
  2577. },
  2578.  
  2579. setZIndex: function (zIndex) {
  2580. this.options.zIndex = zIndex;
  2581. this._updateZIndex();
  2582.  
  2583. return this;
  2584. },
  2585.  
  2586. setUrl: function (url, noRedraw) {
  2587. this._url = url;
  2588.  
  2589. if (!noRedraw) {
  2590. this.redraw();
  2591. }
  2592.  
  2593. return this;
  2594. },
  2595.  
  2596. redraw: function () {
  2597. if (this._map) {
  2598. this._reset({hard: true});
  2599. this._update();
  2600. }
  2601. return this;
  2602. },
  2603.  
  2604. _updateZIndex: function () {
  2605. if (this._container && this.options.zIndex !== undefined) {
  2606. this._container.style.zIndex = this.options.zIndex;
  2607. }
  2608. },
  2609.  
  2610. _setAutoZIndex: function (pane, compare) {
  2611.  
  2612. var layers = pane.children,
  2613. edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
  2614. zIndex, i, len;
  2615.  
  2616. for (i = 0, len = layers.length; i < len; i++) {
  2617.  
  2618. if (layers[i] !== this._container) {
  2619. zIndex = parseInt(layers[i].style.zIndex, 10);
  2620.  
  2621. if (!isNaN(zIndex)) {
  2622. edgeZIndex = compare(edgeZIndex, zIndex);
  2623. }
  2624. }
  2625. }
  2626.  
  2627. this.options.zIndex = this._container.style.zIndex =
  2628. (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
  2629. },
  2630.  
  2631. _updateOpacity: function () {
  2632. var i,
  2633. tiles = this._tiles;
  2634.  
  2635. if (L.Browser.ielt9) {
  2636. for (i in tiles) {
  2637. L.DomUtil.setOpacity(tiles[i], this.options.opacity);
  2638. }
  2639. } else {
  2640. L.DomUtil.setOpacity(this._container, this.options.opacity);
  2641. }
  2642. },
  2643.  
  2644. _initContainer: function () {
  2645. var tilePane = this._map._panes.tilePane;
  2646.  
  2647. if (!this._container) {
  2648. this._container = L.DomUtil.create('div', 'leaflet-layer');
  2649.  
  2650. this._updateZIndex();
  2651.  
  2652. if (this._animated) {
  2653. var className = 'leaflet-tile-container';
  2654.  
  2655. this._bgBuffer = L.DomUtil.create('div', className, this._container);
  2656. this._tileContainer = L.DomUtil.create('div', className, this._container);
  2657.  
  2658. } else {
  2659. this._tileContainer = this._container;
  2660. }
  2661.  
  2662. tilePane.appendChild(this._container);
  2663.  
  2664. if (this.options.opacity < 1) {
  2665. this._updateOpacity();
  2666. }
  2667. }
  2668. },
  2669.  
  2670. _reset: function (e) {
  2671. for (var key in this._tiles) {
  2672. this.fire('tileunload', {tile: this._tiles[key]});
  2673. }
  2674.  
  2675. this._tiles = {};
  2676. this._tilesToLoad = 0;
  2677.  
  2678. if (this.options.reuseTiles) {
  2679. this._unusedTiles = [];
  2680. }
  2681.  
  2682. this._tileContainer.innerHTML = '';
  2683.  
  2684. if (this._animated && e && e.hard) {
  2685. this._clearBgBuffer();
  2686. }
  2687.  
  2688. this._initContainer();
  2689. },
  2690.  
  2691. _getTileSize: function () {
  2692. var map = this._map,
  2693. zoom = map.getZoom() + this.options.zoomOffset,
  2694. zoomN = this.options.maxNativeZoom,
  2695. tileSize = this.options.tileSize;
  2696.  
  2697. if (zoomN && zoom > zoomN) {
  2698. tileSize = Math.round(map.getZoomScale(zoom) / map.getZoomScale(zoomN) * tileSize);
  2699. }
  2700.  
  2701. return tileSize;
  2702. },
  2703.  
  2704. _update: function () {
  2705.  
  2706. if (!this._map) { return; }
  2707.  
  2708. var map = this._map,
  2709. bounds = map.getPixelBounds(),
  2710. zoom = map.getZoom(),
  2711. tileSize = this._getTileSize();
  2712.  
  2713. if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
  2714. return;
  2715. }
  2716.  
  2717. var tileBounds = L.bounds(
  2718. bounds.min.divideBy(tileSize)._floor(),
  2719. bounds.max.divideBy(tileSize)._floor());
  2720.  
  2721. this._addTilesFromCenterOut(tileBounds);
  2722.  
  2723. if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
  2724. this._removeOtherTiles(tileBounds);
  2725. }
  2726. },
  2727.  
  2728. _addTilesFromCenterOut: function (bounds) {
  2729. var queue = [],
  2730. center = bounds.getCenter();
  2731.  
  2732. var j, i, point;
  2733.  
  2734. for (j = bounds.min.y; j <= bounds.max.y; j++) {
  2735. for (i = bounds.min.x; i <= bounds.max.x; i++) {
  2736. point = new L.Point(i, j);
  2737.  
  2738. if (this._tileShouldBeLoaded(point)) {
  2739. queue.push(point);
  2740. }
  2741. }
  2742. }
  2743.  
  2744. var tilesToLoad = queue.length;
  2745.  
  2746. if (tilesToLoad === 0) { return; }
  2747.  
  2748. // load tiles in order of their distance to center
  2749. queue.sort(function (a, b) {
  2750. return a.distanceTo(center) - b.distanceTo(center);
  2751. });
  2752.  
  2753. var fragment = document.createDocumentFragment();
  2754.  
  2755. // if its the first batch of tiles to load
  2756. if (!this._tilesToLoad) {
  2757. this.fire('loading');
  2758. }
  2759.  
  2760. this._tilesToLoad += tilesToLoad;
  2761.  
  2762. for (i = 0; i < tilesToLoad; i++) {
  2763. this._addTile(queue[i], fragment);
  2764. }
  2765.  
  2766. this._tileContainer.appendChild(fragment);
  2767. },
  2768.  
  2769. _tileShouldBeLoaded: function (tilePoint) {
  2770. if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
  2771. return false; // already loaded
  2772. }
  2773.  
  2774. var options = this.options;
  2775.  
  2776. if (!options.continuousWorld) {
  2777. var limit = this._getWrapTileNum();
  2778.  
  2779. // don't load if exceeds world bounds
  2780. if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit.x)) ||
  2781. tilePoint.y < 0 || tilePoint.y >= limit.y) { return false; }
  2782. }
  2783.  
  2784. if (options.bounds) {
  2785. var tileSize = options.tileSize,
  2786. nwPoint = tilePoint.multiplyBy(tileSize),
  2787. sePoint = nwPoint.add([tileSize, tileSize]),
  2788. nw = this._map.unproject(nwPoint),
  2789. se = this._map.unproject(sePoint);
  2790.  
  2791. // TODO temporary hack, will be removed after refactoring projections
  2792. // https://github.com/Leaflet/Leaflet/issues/1618
  2793. if (!options.continuousWorld && !options.noWrap) {
  2794. nw = nw.wrap();
  2795. se = se.wrap();
  2796. }
  2797.  
  2798. if (!options.bounds.intersects([nw, se])) { return false; }
  2799. }
  2800.  
  2801. return true;
  2802. },
  2803.  
  2804. _removeOtherTiles: function (bounds) {
  2805. var kArr, x, y, key;
  2806.  
  2807. for (key in this._tiles) {
  2808. kArr = key.split(':');
  2809. x = parseInt(kArr[0], 10);
  2810. y = parseInt(kArr[1], 10);
  2811.  
  2812. // remove tile if it's out of bounds
  2813. if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
  2814. this._removeTile(key);
  2815. }
  2816. }
  2817. },
  2818.  
  2819. _removeTile: function (key) {
  2820. var tile = this._tiles[key];
  2821.  
  2822. this.fire('tileunload', {tile: tile, url: tile.src});
  2823.  
  2824. if (this.options.reuseTiles) {
  2825. L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
  2826. this._unusedTiles.push(tile);
  2827.  
  2828. } else if (tile.parentNode === this._tileContainer) {
  2829. this._tileContainer.removeChild(tile);
  2830. }
  2831.  
  2832. // for https://github.com/CloudMade/Leaflet/issues/137
  2833. if (!L.Browser.android) {
  2834. tile.onload = null;
  2835. tile.src = L.Util.emptyImageUrl;
  2836. }
  2837.  
  2838. delete this._tiles[key];
  2839. },
  2840.  
  2841. _addTile: function (tilePoint, container) {
  2842. var tilePos = this._getTilePos(tilePoint);
  2843.  
  2844. // get unused tile - or create a new tile
  2845. var tile = this._getTile();
  2846.  
  2847. /*
  2848. Chrome 20 layouts much faster with top/left (verify with timeline, frames)
  2849. Android 4 browser has display issues with top/left and requires transform instead
  2850. (other browsers don't currently care) - see debug/hacks/jitter.html for an example
  2851. */
  2852. L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome);
  2853.  
  2854. this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
  2855.  
  2856. this._loadTile(tile, tilePoint);
  2857.  
  2858. if (tile.parentNode !== this._tileContainer) {
  2859. container.appendChild(tile);
  2860. }
  2861. },
  2862.  
  2863. _getZoomForUrl: function () {
  2864.  
  2865. var options = this.options,
  2866. zoom = this._map.getZoom();
  2867.  
  2868. if (options.zoomReverse) {
  2869. zoom = options.maxZoom - zoom;
  2870. }
  2871.  
  2872. zoom += options.zoomOffset;
  2873.  
  2874. return options.maxNativeZoom ? Math.min(zoom, options.maxNativeZoom) : zoom;
  2875. },
  2876.  
  2877. _getTilePos: function (tilePoint) {
  2878. var origin = this._map.getPixelOrigin(),
  2879. tileSize = this._getTileSize();
  2880.  
  2881. return tilePoint.multiplyBy(tileSize).subtract(origin);
  2882. },
  2883.  
  2884. // image-specific code (override to implement e.g. Canvas or SVG tile layer)
  2885.  
  2886. getTileUrl: function (tilePoint) {
  2887. return L.Util.template(this._url, L.extend({
  2888. s: this._getSubdomain(tilePoint),
  2889. z: tilePoint.z,
  2890. x: tilePoint.x,
  2891. y: tilePoint.y
  2892. }, this.options));
  2893. },
  2894.  
  2895. _getWrapTileNum: function () {
  2896. var crs = this._map.options.crs,
  2897. size = crs.getSize(this._map.getZoom());
  2898. return size.divideBy(this._getTileSize())._floor();
  2899. },
  2900.  
  2901. _adjustTilePoint: function (tilePoint) {
  2902.  
  2903. var limit = this._getWrapTileNum();
  2904.  
  2905. // wrap tile coordinates
  2906. if (!this.options.continuousWorld && !this.options.noWrap) {
  2907. tilePoint.x = ((tilePoint.x % limit.x) + limit.x) % limit.x;
  2908. }
  2909.  
  2910. if (this.options.tms) {
  2911. tilePoint.y = limit.y - tilePoint.y - 1;
  2912. }
  2913.  
  2914. tilePoint.z = this._getZoomForUrl();
  2915. },
  2916.  
  2917. _getSubdomain: function (tilePoint) {
  2918. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  2919. return this.options.subdomains[index];
  2920. },
  2921.  
  2922. _getTile: function () {
  2923. if (this.options.reuseTiles && this._unusedTiles.length > 0) {
  2924. var tile = this._unusedTiles.pop();
  2925. this._resetTile(tile);
  2926. return tile;
  2927. }
  2928. return this._createTile();
  2929. },
  2930.  
  2931. // Override if data stored on a tile needs to be cleaned up before reuse
  2932. _resetTile: function (/*tile*/) {},
  2933.  
  2934. _createTile: function () {
  2935. var tile = L.DomUtil.create('img', 'leaflet-tile');
  2936. tile.style.width = tile.style.height = this._getTileSize() + 'px';
  2937. tile.galleryimg = 'no';
  2938.  
  2939. tile.onselectstart = tile.onmousemove = L.Util.falseFn;
  2940.  
  2941. if (L.Browser.ielt9 && this.options.opacity !== undefined) {
  2942. L.DomUtil.setOpacity(tile, this.options.opacity);
  2943. }
  2944. // without this hack, tiles disappear after zoom on Chrome for Android
  2945. // https://github.com/Leaflet/Leaflet/issues/2078
  2946. if (L.Browser.mobileWebkit3d) {
  2947. tile.style.WebkitBackfaceVisibility = 'hidden';
  2948. }
  2949. return tile;
  2950. },
  2951.  
  2952. _loadTile: function (tile, tilePoint) {
  2953. tile._layer = this;
  2954. tile.onload = this._tileOnLoad;
  2955. tile.onerror = this._tileOnError;
  2956.  
  2957. this._adjustTilePoint(tilePoint);
  2958. tile.src = this.getTileUrl(tilePoint);
  2959.  
  2960. this.fire('tileloadstart', {
  2961. tile: tile,
  2962. url: tile.src
  2963. });
  2964. },
  2965.  
  2966. _tileLoaded: function () {
  2967. this._tilesToLoad--;
  2968.  
  2969. if (this._animated) {
  2970. L.DomUtil.addClass(this._tileContainer, 'leaflet-zoom-animated');
  2971. }
  2972.  
  2973. if (!this._tilesToLoad) {
  2974. this.fire('load');
  2975.  
  2976. if (this._animated) {
  2977. // clear scaled tiles after all new tiles are loaded (for performance)
  2978. clearTimeout(this._clearBgBufferTimer);
  2979. this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500);
  2980. }
  2981. }
  2982. },
  2983.  
  2984. _tileOnLoad: function () {
  2985. var layer = this._layer;
  2986.  
  2987. //Only if we are loading an actual image
  2988. if (this.src !== L.Util.emptyImageUrl) {
  2989. L.DomUtil.addClass(this, 'leaflet-tile-loaded');
  2990.  
  2991. layer.fire('tileload', {
  2992. tile: this,
  2993. url: this.src
  2994. });
  2995. }
  2996.  
  2997. layer._tileLoaded();
  2998. },
  2999.  
  3000. _tileOnError: function () {
  3001. var layer = this._layer;
  3002.  
  3003. layer.fire('tileerror', {
  3004. tile: this,
  3005. url: this.src
  3006. });
  3007.  
  3008. var newUrl = layer.options.errorTileUrl;
  3009. if (newUrl) {
  3010. this.src = newUrl;
  3011. }
  3012.  
  3013. layer._tileLoaded();
  3014. }
  3015. });
  3016.  
  3017. L.tileLayer = function (url, options) {
  3018. return new L.TileLayer(url, options);
  3019. };
  3020.  
  3021.  
  3022. /*
  3023. * L.TileLayer.WMS is used for putting WMS tile layers on the map.
  3024. */
  3025.  
  3026. L.TileLayer.WMS = L.TileLayer.extend({
  3027.  
  3028. defaultWmsParams: {
  3029. service: 'WMS',
  3030. request: 'GetMap',
  3031. version: '1.1.1',
  3032. layers: '',
  3033. styles: '',
  3034. format: 'image/jpeg',
  3035. transparent: false
  3036. },
  3037.  
  3038. initialize: function (url, options) { // (String, Object)
  3039.  
  3040. this._url = url;
  3041.  
  3042. var wmsParams = L.extend({}, this.defaultWmsParams),
  3043. tileSize = options.tileSize || this.options.tileSize;
  3044.  
  3045. if (options.detectRetina && L.Browser.retina) {
  3046. wmsParams.width = wmsParams.height = tileSize * 2;
  3047. } else {
  3048. wmsParams.width = wmsParams.height = tileSize;
  3049. }
  3050.  
  3051. for (var i in options) {
  3052. // all keys that are not TileLayer options go to WMS params
  3053. if (!this.options.hasOwnProperty(i) && i !== 'crs') {
  3054. wmsParams[i] = options[i];
  3055. }
  3056. }
  3057.  
  3058. this.wmsParams = wmsParams;
  3059.  
  3060. L.setOptions(this, options);
  3061. },
  3062.  
  3063. onAdd: function (map) {
  3064.  
  3065. this._crs = this.options.crs || map.options.crs;
  3066.  
  3067. this._wmsVersion = parseFloat(this.wmsParams.version);
  3068.  
  3069. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  3070. this.wmsParams[projectionKey] = this._crs.code;
  3071.  
  3072. L.TileLayer.prototype.onAdd.call(this, map);
  3073. },
  3074.  
  3075. getTileUrl: function (tilePoint) { // (Point, Number) -> String
  3076.  
  3077. var map = this._map,
  3078. tileSize = this.options.tileSize,
  3079.  
  3080. nwPoint = tilePoint.multiplyBy(tileSize),
  3081. sePoint = nwPoint.add([tileSize, tileSize]),
  3082.  
  3083. nw = this._crs.project(map.unproject(nwPoint, tilePoint.z)),
  3084. se = this._crs.project(map.unproject(sePoint, tilePoint.z)),
  3085. bbox = this._wmsVersion >= 1.3 && this._crs === L.CRS.EPSG4326 ?
  3086. [se.y, nw.x, nw.y, se.x].join(',') :
  3087. [nw.x, se.y, se.x, nw.y].join(','),
  3088.  
  3089. url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
  3090.  
  3091. return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox;
  3092. },
  3093.  
  3094. setParams: function (params, noRedraw) {
  3095.  
  3096. L.extend(this.wmsParams, params);
  3097.  
  3098. if (!noRedraw) {
  3099. this.redraw();
  3100. }
  3101.  
  3102. return this;
  3103. }
  3104. });
  3105.  
  3106. L.tileLayer.wms = function (url, options) {
  3107. return new L.TileLayer.WMS(url, options);
  3108. };
  3109.  
  3110.  
  3111. /*
  3112. * L.TileLayer.Canvas is a class that you can use as a base for creating
  3113. * dynamically drawn Canvas-based tile layers.
  3114. */
  3115.  
  3116. L.TileLayer.Canvas = L.TileLayer.extend({
  3117. options: {
  3118. async: false
  3119. },
  3120.  
  3121. initialize: function (options) {
  3122. L.setOptions(this, options);
  3123. },
  3124.  
  3125. redraw: function () {
  3126. if (this._map) {
  3127. this._reset({hard: true});
  3128. this._update();
  3129. }
  3130.  
  3131. for (var i in this._tiles) {
  3132. this._redrawTile(this._tiles[i]);
  3133. }
  3134. return this;
  3135. },
  3136.  
  3137. _redrawTile: function (tile) {
  3138. this.drawTile(tile, tile._tilePoint, this._map._zoom);
  3139. },
  3140.  
  3141. _createTile: function () {
  3142. var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  3143. tile.width = tile.height = this.options.tileSize;
  3144. tile.onselectstart = tile.onmousemove = L.Util.falseFn;
  3145. return tile;
  3146. },
  3147.  
  3148. _loadTile: function (tile, tilePoint) {
  3149. tile._layer = this;
  3150. tile._tilePoint = tilePoint;
  3151.  
  3152. this._redrawTile(tile);
  3153.  
  3154. if (!this.options.async) {
  3155. this.tileDrawn(tile);
  3156. }
  3157. },
  3158.  
  3159. drawTile: function (/*tile, tilePoint*/) {
  3160. // override with rendering code
  3161. },
  3162.  
  3163. tileDrawn: function (tile) {
  3164. this._tileOnLoad.call(tile);
  3165. }
  3166. });
  3167.  
  3168.  
  3169. L.tileLayer.canvas = function (options) {
  3170. return new L.TileLayer.Canvas(options);
  3171. };
  3172.  
  3173.  
  3174. /*
  3175. * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
  3176. */
  3177.  
  3178. L.ImageOverlay = L.Class.extend({
  3179. includes: L.Mixin.Events,
  3180.  
  3181. options: {
  3182. opacity: 1
  3183. },
  3184.  
  3185. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  3186. this._url = url;
  3187. this._bounds = L.latLngBounds(bounds);
  3188.  
  3189. L.setOptions(this, options);
  3190. },
  3191.  
  3192. onAdd: function (map) {
  3193. this._map = map;
  3194.  
  3195. if (!this._image) {
  3196. this._initImage();
  3197. }
  3198.  
  3199. map._panes.overlayPane.appendChild(this._image);
  3200.  
  3201. map.on('viewreset', this._reset, this);
  3202.  
  3203. if (map.options.zoomAnimation && L.Browser.any3d) {
  3204. map.on('zoomanim', this._animateZoom, this);
  3205. }
  3206.  
  3207. this._reset();
  3208. },
  3209.  
  3210. onRemove: function (map) {
  3211. map.getPanes().overlayPane.removeChild(this._image);
  3212.  
  3213. map.off('viewreset', this._reset, this);
  3214.  
  3215. if (map.options.zoomAnimation) {
  3216. map.off('zoomanim', this._animateZoom, this);
  3217. }
  3218. },
  3219.  
  3220. addTo: function (map) {
  3221. map.addLayer(this);
  3222. return this;
  3223. },
  3224.  
  3225. setOpacity: function (opacity) {
  3226. this.options.opacity = opacity;
  3227. this._updateOpacity();
  3228. return this;
  3229. },
  3230.  
  3231. // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
  3232. bringToFront: function () {
  3233. if (this._image) {
  3234. this._map._panes.overlayPane.appendChild(this._image);
  3235. }
  3236. return this;
  3237. },
  3238.  
  3239. bringToBack: function () {
  3240. var pane = this._map._panes.overlayPane;
  3241. if (this._image) {
  3242. pane.insertBefore(this._image, pane.firstChild);
  3243. }
  3244. return this;
  3245. },
  3246.  
  3247. setUrl: function (url) {
  3248. this._url = url;
  3249. this._image.src = this._url;
  3250. },
  3251.  
  3252. getAttribution: function () {
  3253. return this.options.attribution;
  3254. },
  3255.  
  3256. _initImage: function () {
  3257. this._image = L.DomUtil.create('img', 'leaflet-image-layer');
  3258.  
  3259. if (this._map.options.zoomAnimation && L.Browser.any3d) {
  3260. L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
  3261. } else {
  3262. L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
  3263. }
  3264.  
  3265. this._updateOpacity();
  3266.  
  3267. //TODO createImage util method to remove duplication
  3268. L.extend(this._image, {
  3269. galleryimg: 'no',
  3270. onselectstart: L.Util.falseFn,
  3271. onmousemove: L.Util.falseFn,
  3272. onload: L.bind(this._onImageLoad, this),
  3273. src: this._url
  3274. });
  3275. },
  3276.  
  3277. _animateZoom: function (e) {
  3278. var map = this._map,
  3279. image = this._image,
  3280. scale = map.getZoomScale(e.zoom),
  3281. nw = this._bounds.getNorthWest(),
  3282. se = this._bounds.getSouthEast(),
  3283.  
  3284. topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
  3285. size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
  3286. origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
  3287.  
  3288. image.style[L.DomUtil.TRANSFORM] =
  3289. L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
  3290. },
  3291.  
  3292. _reset: function () {
  3293. var image = this._image,
  3294. topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  3295. size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
  3296.  
  3297. L.DomUtil.setPosition(image, topLeft);
  3298.  
  3299. image.style.width = size.x + 'px';
  3300. image.style.height = size.y + 'px';
  3301. },
  3302.  
  3303. _onImageLoad: function () {
  3304. this.fire('load');
  3305. },
  3306.  
  3307. _updateOpacity: function () {
  3308. L.DomUtil.setOpacity(this._image, this.options.opacity);
  3309. }
  3310. });
  3311.  
  3312. L.imageOverlay = function (url, bounds, options) {
  3313. return new L.ImageOverlay(url, bounds, options);
  3314. };
  3315.  
  3316.  
  3317. /*
  3318. * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
  3319. */
  3320.  
  3321. L.Icon = L.Class.extend({
  3322. options: {
  3323. /*
  3324. iconUrl: (String) (required)
  3325. iconRetinaUrl: (String) (optional, used for retina devices if detected)
  3326. iconSize: (Point) (can be set through CSS)
  3327. iconAnchor: (Point) (centered by default, can be set in CSS with negative margins)
  3328. popupAnchor: (Point) (if not specified, popup opens in the anchor point)
  3329. shadowUrl: (String) (no shadow by default)
  3330. shadowRetinaUrl: (String) (optional, used for retina devices if detected)
  3331. shadowSize: (Point)
  3332. shadowAnchor: (Point)
  3333. */
  3334. className: ''
  3335. },
  3336.  
  3337. initialize: function (options) {
  3338. L.setOptions(this, options);
  3339. },
  3340.  
  3341. createIcon: function (oldIcon) {
  3342. return this._createIcon('icon', oldIcon);
  3343. },
  3344.  
  3345. createShadow: function (oldIcon) {
  3346. return this._createIcon('shadow', oldIcon);
  3347. },
  3348.  
  3349. _createIcon: function (name, oldIcon) {
  3350. var src = this._getIconUrl(name);
  3351.  
  3352. if (!src) {
  3353. if (name === 'icon') {
  3354. throw new Error('iconUrl not set in Icon options (see the docs).');
  3355. }
  3356. return null;
  3357. }
  3358.  
  3359. var img;
  3360. if (!oldIcon || oldIcon.tagName !== 'IMG') {
  3361. img = this._createImg(src);
  3362. } else {
  3363. img = this._createImg(src, oldIcon);
  3364. }
  3365. this._setIconStyles(img, name);
  3366.  
  3367. return img;
  3368. },
  3369.  
  3370. _setIconStyles: function (img, name) {
  3371. var options = this.options,
  3372. size = L.point(options[name + 'Size']),
  3373. anchor;
  3374.  
  3375. if (name === 'shadow') {
  3376. anchor = L.point(options.shadowAnchor || options.iconAnchor);
  3377. } else {
  3378. anchor = L.point(options.iconAnchor);
  3379. }
  3380.  
  3381. if (!anchor && size) {
  3382. anchor = size.divideBy(2, true);
  3383. }
  3384.  
  3385. img.className = 'leaflet-marker-' + name + ' ' + options.className;
  3386.  
  3387. if (anchor) {
  3388. img.style.marginLeft = (-anchor.x) + 'px';
  3389. img.style.marginTop = (-anchor.y) + 'px';
  3390. }
  3391.  
  3392. if (size) {
  3393. img.style.width = size.x + 'px';
  3394. img.style.height = size.y + 'px';
  3395. }
  3396. },
  3397.  
  3398. _createImg: function (src, el) {
  3399. el = el || document.createElement('img');
  3400. el.src = src;
  3401. return el;
  3402. },
  3403.  
  3404. _getIconUrl: function (name) {
  3405. if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
  3406. return this.options[name + 'RetinaUrl'];
  3407. }
  3408. return this.options[name + 'Url'];
  3409. }
  3410. });
  3411.  
  3412. L.icon = function (options) {
  3413. return new L.Icon(options);
  3414. };
  3415.  
  3416.  
  3417. /*
  3418. * L.Icon.Default is the blue marker icon used by default in Leaflet.
  3419. */
  3420.  
  3421. L.Icon.Default = L.Icon.extend({
  3422.  
  3423. options: {
  3424. iconSize: [25, 41],
  3425. iconAnchor: [12, 41],
  3426. popupAnchor: [1, -34],
  3427.  
  3428. shadowSize: [41, 41]
  3429. },
  3430.  
  3431. _getIconUrl: function (name) {
  3432. var key = name + 'Url';
  3433.  
  3434. if (this.options[key]) {
  3435. return this.options[key];
  3436. }
  3437.  
  3438. if (L.Browser.retina && name === 'icon') {
  3439. name += '-2x';
  3440. }
  3441.  
  3442. var path = L.Icon.Default.imagePath;
  3443.  
  3444. if (!path) {
  3445. throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.');
  3446. }
  3447.  
  3448. return path + '/marker-' + name + '.png';
  3449. }
  3450. });
  3451.  
  3452. L.Icon.Default.imagePath = (function () {
  3453. var scripts = document.getElementsByTagName('script'),
  3454. leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
  3455.  
  3456. var i, len, src, matches, path;
  3457.  
  3458. for (i = 0, len = scripts.length; i < len; i++) {
  3459. src = scripts[i].src;
  3460. matches = src.match(leafletRe);
  3461.  
  3462. if (matches) {
  3463. path = src.split(leafletRe)[0];
  3464. return (path ? path + '/' : '') + 'images';
  3465. }
  3466. }
  3467. }());
  3468.  
  3469.  
  3470. /*
  3471. * L.Marker is used to display clickable/draggable icons on the map.
  3472. */
  3473.  
  3474. L.Marker = L.Class.extend({
  3475.  
  3476. includes: L.Mixin.Events,
  3477.  
  3478. options: {
  3479. icon: new L.Icon.Default(),
  3480. title: '',
  3481. alt: '',
  3482. clickable: true,
  3483. draggable: false,
  3484. keyboard: true,
  3485. zIndexOffset: 0,
  3486. opacity: 1,
  3487. riseOnHover: false,
  3488. riseOffset: 250
  3489. },
  3490.  
  3491. initialize: function (latlng, options) {
  3492. L.setOptions(this, options);
  3493. this._latlng = L.latLng(latlng);
  3494. },
  3495.  
  3496. onAdd: function (map) {
  3497. this._map = map;
  3498.  
  3499. map.on('viewreset', this.update, this);
  3500.  
  3501. this._initIcon();
  3502. this.update();
  3503. this.fire('add');
  3504.  
  3505. if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
  3506. map.on('zoomanim', this._animateZoom, this);
  3507. }
  3508. },
  3509.  
  3510. addTo: function (map) {
  3511. map.addLayer(this);
  3512. return this;
  3513. },
  3514.  
  3515. onRemove: function (map) {
  3516. if (this.dragging) {
  3517. this.dragging.disable();
  3518. }
  3519.  
  3520. this._removeIcon();
  3521. this._removeShadow();
  3522.  
  3523. this.fire('remove');
  3524.  
  3525. map.off({
  3526. 'viewreset': this.update,
  3527. 'zoomanim': this._animateZoom
  3528. }, this);
  3529.  
  3530. this._map = null;
  3531. },
  3532.  
  3533. getLatLng: function () {
  3534. return this._latlng;
  3535. },
  3536.  
  3537. setLatLng: function (latlng) {
  3538. this._latlng = L.latLng(latlng);
  3539.  
  3540. this.update();
  3541.  
  3542. return this.fire('move', { latlng: this._latlng });
  3543. },
  3544.  
  3545. setZIndexOffset: function (offset) {
  3546. this.options.zIndexOffset = offset;
  3547. this.update();
  3548.  
  3549. return this;
  3550. },
  3551.  
  3552. setIcon: function (icon) {
  3553.  
  3554. this.options.icon = icon;
  3555.  
  3556. if (this._map) {
  3557. this._initIcon();
  3558. this.update();
  3559. }
  3560.  
  3561. if (this._popup) {
  3562. this.bindPopup(this._popup);
  3563. }
  3564.  
  3565. return this;
  3566. },
  3567.  
  3568. update: function () {
  3569. if (this._icon) {
  3570. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  3571. this._setPos(pos);
  3572. }
  3573.  
  3574. return this;
  3575. },
  3576.  
  3577. _initIcon: function () {
  3578. var options = this.options,
  3579. map = this._map,
  3580. animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
  3581. classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
  3582.  
  3583. var icon = options.icon.createIcon(this._icon),
  3584. addIcon = false;
  3585.  
  3586. // if we're not reusing the icon, remove the old one and init new one
  3587. if (icon !== this._icon) {
  3588. if (this._icon) {
  3589. this._removeIcon();
  3590. }
  3591. addIcon = true;
  3592.  
  3593. if (options.title) {
  3594. icon.title = options.title;
  3595. }
  3596. if (options.alt) {
  3597. icon.alt = options.alt;
  3598. }
  3599. }
  3600.  
  3601. L.DomUtil.addClass(icon, classToAdd);
  3602.  
  3603. if (options.keyboard) {
  3604. icon.tabIndex = '0';
  3605. }
  3606.  
  3607. this._icon = icon;
  3608.  
  3609. this._initInteraction();
  3610.  
  3611. if (options.riseOnHover) {
  3612. L.DomEvent
  3613. .on(icon, 'mouseover', this._bringToFront, this)
  3614. .on(icon, 'mouseout', this._resetZIndex, this);
  3615. }
  3616.  
  3617. var newShadow = options.icon.createShadow(this._shadow),
  3618. addShadow = false;
  3619.  
  3620. if (newShadow !== this._shadow) {
  3621. this._removeShadow();
  3622. addShadow = true;
  3623. }
  3624.  
  3625. if (newShadow) {
  3626. L.DomUtil.addClass(newShadow, classToAdd);
  3627. }
  3628. this._shadow = newShadow;
  3629.  
  3630.  
  3631. if (options.opacity < 1) {
  3632. this._updateOpacity();
  3633. }
  3634.  
  3635.  
  3636. var panes = this._map._panes;
  3637.  
  3638. if (addIcon) {
  3639. panes.markerPane.appendChild(this._icon);
  3640. }
  3641.  
  3642. if (newShadow && addShadow) {
  3643. panes.shadowPane.appendChild(this._shadow);
  3644. }
  3645. },
  3646.  
  3647. _removeIcon: function () {
  3648. if (this.options.riseOnHover) {
  3649. L.DomEvent
  3650. .off(this._icon, 'mouseover', this._bringToFront)
  3651. .off(this._icon, 'mouseout', this._resetZIndex);
  3652. }
  3653.  
  3654. this._map._panes.markerPane.removeChild(this._icon);
  3655.  
  3656. this._icon = null;
  3657. },
  3658.  
  3659. _removeShadow: function () {
  3660. if (this._shadow) {
  3661. this._map._panes.shadowPane.removeChild(this._shadow);
  3662. }
  3663. this._shadow = null;
  3664. },
  3665.  
  3666. _setPos: function (pos) {
  3667. L.DomUtil.setPosition(this._icon, pos);
  3668.  
  3669. if (this._shadow) {
  3670. L.DomUtil.setPosition(this._shadow, pos);
  3671. }
  3672.  
  3673. this._zIndex = pos.y + this.options.zIndexOffset;
  3674.  
  3675. this._resetZIndex();
  3676. },
  3677.  
  3678. _updateZIndex: function (offset) {
  3679. this._icon.style.zIndex = this._zIndex + offset;
  3680. },
  3681.  
  3682. _animateZoom: function (opt) {
  3683. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  3684.  
  3685. this._setPos(pos);
  3686. },
  3687.  
  3688. _initInteraction: function () {
  3689.  
  3690. if (!this.options.clickable) { return; }
  3691.  
  3692. // TODO refactor into something shared with Map/Path/etc. to DRY it up
  3693.  
  3694. var icon = this._icon,
  3695. events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
  3696.  
  3697. L.DomUtil.addClass(icon, 'leaflet-clickable');
  3698. L.DomEvent.on(icon, 'click', this._onMouseClick, this);
  3699. L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
  3700.  
  3701. for (var i = 0; i < events.length; i++) {
  3702. L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
  3703. }
  3704.  
  3705. if (L.Handler.MarkerDrag) {
  3706. this.dragging = new L.Handler.MarkerDrag(this);
  3707.  
  3708. if (this.options.draggable) {
  3709. this.dragging.enable();
  3710. }
  3711. }
  3712. },
  3713.  
  3714. _onMouseClick: function (e) {
  3715. var wasDragged = this.dragging && this.dragging.moved();
  3716.  
  3717. if (this.hasEventListeners(e.type) || wasDragged) {
  3718. L.DomEvent.stopPropagation(e);
  3719. }
  3720.  
  3721. if (wasDragged) { return; }
  3722.  
  3723. if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
  3724.  
  3725. this.fire(e.type, {
  3726. originalEvent: e,
  3727. latlng: this._latlng
  3728. });
  3729. },
  3730.  
  3731. _onKeyPress: function (e) {
  3732. if (e.keyCode === 13) {
  3733. this.fire('click', {
  3734. originalEvent: e,
  3735. latlng: this._latlng
  3736. });
  3737. }
  3738. },
  3739.  
  3740. _fireMouseEvent: function (e) {
  3741.  
  3742. this.fire(e.type, {
  3743. originalEvent: e,
  3744. latlng: this._latlng
  3745. });
  3746.  
  3747. // TODO proper custom event propagation
  3748. // this line will always be called if marker is in a FeatureGroup
  3749. if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
  3750. L.DomEvent.preventDefault(e);
  3751. }
  3752. if (e.type !== 'mousedown') {
  3753. L.DomEvent.stopPropagation(e);
  3754. } else {
  3755. L.DomEvent.preventDefault(e);
  3756. }
  3757. },
  3758.  
  3759. setOpacity: function (opacity) {
  3760. this.options.opacity = opacity;
  3761. if (this._map) {
  3762. this._updateOpacity();
  3763. }
  3764.  
  3765. return this;
  3766. },
  3767.  
  3768. _updateOpacity: function () {
  3769. L.DomUtil.setOpacity(this._icon, this.options.opacity);
  3770. if (this._shadow) {
  3771. L.DomUtil.setOpacity(this._shadow, this.options.opacity);
  3772. }
  3773. },
  3774.  
  3775. _bringToFront: function () {
  3776. this._updateZIndex(this.options.riseOffset);
  3777. },
  3778.  
  3779. _resetZIndex: function () {
  3780. this._updateZIndex(0);
  3781. }
  3782. });
  3783.  
  3784. L.marker = function (latlng, options) {
  3785. return new L.Marker(latlng, options);
  3786. };
  3787.  
  3788.  
  3789. /*
  3790. * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
  3791. * to use with L.Marker.
  3792. */
  3793.  
  3794. L.DivIcon = L.Icon.extend({
  3795. options: {
  3796. iconSize: [12, 12], // also can be set through CSS
  3797. /*
  3798. iconAnchor: (Point)
  3799. popupAnchor: (Point)
  3800. html: (String)
  3801. bgPos: (Point)
  3802. */
  3803. className: 'leaflet-div-icon',
  3804. html: false
  3805. },
  3806.  
  3807. createIcon: function (oldIcon) {
  3808. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  3809. options = this.options;
  3810.  
  3811. if (options.html !== false) {
  3812. div.innerHTML = options.html;
  3813. } else {
  3814. div.innerHTML = '';
  3815. }
  3816.  
  3817. if (options.bgPos) {
  3818. div.style.backgroundPosition =
  3819. (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
  3820. }
  3821.  
  3822. this._setIconStyles(div, 'icon');
  3823. return div;
  3824. },
  3825.  
  3826. createShadow: function () {
  3827. return null;
  3828. }
  3829. });
  3830.  
  3831. L.divIcon = function (options) {
  3832. return new L.DivIcon(options);
  3833. };
  3834.  
  3835.  
  3836. /*
  3837. * L.Popup is used for displaying popups on the map.
  3838. */
  3839.  
  3840. L.Map.mergeOptions({
  3841. closePopupOnClick: true
  3842. });
  3843.  
  3844. L.Popup = L.Class.extend({
  3845. includes: L.Mixin.Events,
  3846.  
  3847. options: {
  3848. minWidth: 50,
  3849. maxWidth: 300,
  3850. // maxHeight: null,
  3851. autoPan: true,
  3852. closeButton: true,
  3853. offset: [0, 7],
  3854. autoPanPadding: [5, 5],
  3855. // autoPanPaddingTopLeft: null,
  3856. // autoPanPaddingBottomRight: null,
  3857. keepInView: false,
  3858. className: '',
  3859. zoomAnimation: true
  3860. },
  3861.  
  3862. initialize: function (options, source) {
  3863. L.setOptions(this, options);
  3864.  
  3865. this._source = source;
  3866. this._animated = L.Browser.any3d && this.options.zoomAnimation;
  3867. this._isOpen = false;
  3868. },
  3869.  
  3870. onAdd: function (map) {
  3871. this._map = map;
  3872.  
  3873. if (!this._container) {
  3874. this._initLayout();
  3875. }
  3876.  
  3877. var animFade = map.options.fadeAnimation;
  3878.  
  3879. if (animFade) {
  3880. L.DomUtil.setOpacity(this._container, 0);
  3881. }
  3882. map._panes.popupPane.appendChild(this._container);
  3883.  
  3884. map.on(this._getEvents(), this);
  3885.  
  3886. this.update();
  3887.  
  3888. if (animFade) {
  3889. L.DomUtil.setOpacity(this._container, 1);
  3890. }
  3891.  
  3892. this.fire('open');
  3893.  
  3894. map.fire('popupopen', {popup: this});
  3895.  
  3896. if (this._source) {
  3897. this._source.fire('popupopen', {popup: this});
  3898. }
  3899. },
  3900.  
  3901. addTo: function (map) {
  3902. map.addLayer(this);
  3903. return this;
  3904. },
  3905.  
  3906. openOn: function (map) {
  3907. map.openPopup(this);
  3908. return this;
  3909. },
  3910.  
  3911. onRemove: function (map) {
  3912. map._panes.popupPane.removeChild(this._container);
  3913.  
  3914. L.Util.falseFn(this._container.offsetWidth); // force reflow
  3915.  
  3916. map.off(this._getEvents(), this);
  3917.  
  3918. if (map.options.fadeAnimation) {
  3919. L.DomUtil.setOpacity(this._container, 0);
  3920. }
  3921.  
  3922. this._map = null;
  3923.  
  3924. this.fire('close');
  3925.  
  3926. map.fire('popupclose', {popup: this});
  3927.  
  3928. if (this._source) {
  3929. this._source.fire('popupclose', {popup: this});
  3930. }
  3931. },
  3932.  
  3933. getLatLng: function () {
  3934. return this._latlng;
  3935. },
  3936.  
  3937. setLatLng: function (latlng) {
  3938. this._latlng = L.latLng(latlng);
  3939. if (this._map) {
  3940. this._updatePosition();
  3941. this._adjustPan();
  3942. }
  3943. return this;
  3944. },
  3945.  
  3946. getContent: function () {
  3947. return this._content;
  3948. },
  3949.  
  3950. setContent: function (content) {
  3951. this._content = content;
  3952. this.update();
  3953. return this;
  3954. },
  3955.  
  3956. update: function () {
  3957. if (!this._map) { return; }
  3958.  
  3959. this._container.style.visibility = 'hidden';
  3960.  
  3961. this._updateContent();
  3962. this._updateLayout();
  3963. this._updatePosition();
  3964.  
  3965. this._container.style.visibility = '';
  3966.  
  3967. this._adjustPan();
  3968. },
  3969.  
  3970. _getEvents: function () {
  3971. var events = {
  3972. viewreset: this._updatePosition
  3973. };
  3974.  
  3975. if (this._animated) {
  3976. events.zoomanim = this._zoomAnimation;
  3977. }
  3978. if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  3979. events.preclick = this._close;
  3980. }
  3981. if (this.options.keepInView) {
  3982. events.moveend = this._adjustPan;
  3983. }
  3984.  
  3985. return events;
  3986. },
  3987.  
  3988. _close: function () {
  3989. if (this._map) {
  3990. this._map.closePopup(this);
  3991. }
  3992. },
  3993.  
  3994. _initLayout: function () {
  3995. var prefix = 'leaflet-popup',
  3996. containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' +
  3997. (this._animated ? 'animated' : 'hide'),
  3998. container = this._container = L.DomUtil.create('div', containerClass),
  3999. closeButton;
  4000.  
  4001. if (this.options.closeButton) {
  4002. closeButton = this._closeButton =
  4003. L.DomUtil.create('a', prefix + '-close-button', container);
  4004. closeButton.href = '#close';
  4005. closeButton.innerHTML = '&#215;';
  4006. L.DomEvent.disableClickPropagation(closeButton);
  4007.  
  4008. L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
  4009. }
  4010.  
  4011. var wrapper = this._wrapper =
  4012. L.DomUtil.create('div', prefix + '-content-wrapper', container);
  4013. L.DomEvent.disableClickPropagation(wrapper);
  4014.  
  4015. this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
  4016.  
  4017. L.DomEvent.disableScrollPropagation(this._contentNode);
  4018. L.DomEvent.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
  4019.  
  4020. this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
  4021. this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
  4022. },
  4023.  
  4024. _updateContent: function () {
  4025. if (!this._content) { return; }
  4026.  
  4027. if (typeof this._content === 'string') {
  4028. this._contentNode.innerHTML = this._content;
  4029. } else {
  4030. while (this._contentNode.hasChildNodes()) {
  4031. this._contentNode.removeChild(this._contentNode.firstChild);
  4032. }
  4033. this._contentNode.appendChild(this._content);
  4034. }
  4035. this.fire('contentupdate');
  4036. },
  4037.  
  4038. _updateLayout: function () {
  4039. var container = this._contentNode,
  4040. style = container.style;
  4041.  
  4042. style.width = '';
  4043. style.whiteSpace = 'nowrap';
  4044.  
  4045. var width = container.offsetWidth;
  4046. width = Math.min(width, this.options.maxWidth);
  4047. width = Math.max(width, this.options.minWidth);
  4048.  
  4049. style.width = (width + 1) + 'px';
  4050. style.whiteSpace = '';
  4051.  
  4052. style.height = '';
  4053.  
  4054. var height = container.offsetHeight,
  4055. maxHeight = this.options.maxHeight,
  4056. scrolledClass = 'leaflet-popup-scrolled';
  4057.  
  4058. if (maxHeight && height > maxHeight) {
  4059. style.height = maxHeight + 'px';
  4060. L.DomUtil.addClass(container, scrolledClass);
  4061. } else {
  4062. L.DomUtil.removeClass(container, scrolledClass);
  4063. }
  4064.  
  4065. this._containerWidth = this._container.offsetWidth;
  4066. },
  4067.  
  4068. _updatePosition: function () {
  4069. if (!this._map) { return; }
  4070.  
  4071. var pos = this._map.latLngToLayerPoint(this._latlng),
  4072. animated = this._animated,
  4073. offset = L.point(this.options.offset);
  4074.  
  4075. if (animated) {
  4076. L.DomUtil.setPosition(this._container, pos);
  4077. }
  4078.  
  4079. this._containerBottom = -offset.y - (animated ? 0 : pos.y);
  4080. this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x);
  4081.  
  4082. // bottom position the popup in case the height of the popup changes (images loading etc)
  4083. this._container.style.bottom = this._containerBottom + 'px';
  4084. this._container.style.left = this._containerLeft + 'px';
  4085. },
  4086.  
  4087. _zoomAnimation: function (opt) {
  4088. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
  4089.  
  4090. L.DomUtil.setPosition(this._container, pos);
  4091. },
  4092.  
  4093. _adjustPan: function () {
  4094. if (!this.options.autoPan) { return; }
  4095.  
  4096. var map = this._map,
  4097. containerHeight = this._container.offsetHeight,
  4098. containerWidth = this._containerWidth,
  4099.  
  4100. layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
  4101.  
  4102. if (this._animated) {
  4103. layerPos._add(L.DomUtil.getPosition(this._container));
  4104. }
  4105.  
  4106. var containerPos = map.layerPointToContainerPoint(layerPos),
  4107. padding = L.point(this.options.autoPanPadding),
  4108. paddingTL = L.point(this.options.autoPanPaddingTopLeft || padding),
  4109. paddingBR = L.point(this.options.autoPanPaddingBottomRight || padding),
  4110. size = map.getSize(),
  4111. dx = 0,
  4112. dy = 0;
  4113.  
  4114. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  4115. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  4116. }
  4117. if (containerPos.x - dx - paddingTL.x < 0) { // left
  4118. dx = containerPos.x - paddingTL.x;
  4119. }
  4120. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  4121. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  4122. }
  4123. if (containerPos.y - dy - paddingTL.y < 0) { // top
  4124. dy = containerPos.y - paddingTL.y;
  4125. }
  4126.  
  4127. if (dx || dy) {
  4128. map
  4129. .fire('autopanstart')
  4130. .panBy([dx, dy]);
  4131. }
  4132. },
  4133.  
  4134. _onCloseButtonClick: function (e) {
  4135. this._close();
  4136. L.DomEvent.stop(e);
  4137. }
  4138. });
  4139.  
  4140. L.popup = function (options, source) {
  4141. return new L.Popup(options, source);
  4142. };
  4143.  
  4144.  
  4145. L.Map.include({
  4146. openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object])
  4147. this.closePopup();
  4148.  
  4149. if (!(popup instanceof L.Popup)) {
  4150. var content = popup;
  4151.  
  4152. popup = new L.Popup(options)
  4153. .setLatLng(latlng)
  4154. .setContent(content);
  4155. }
  4156. popup._isOpen = true;
  4157.  
  4158. this._popup = popup;
  4159. return this.addLayer(popup);
  4160. },
  4161.  
  4162. closePopup: function (popup) {
  4163. if (!popup || popup === this._popup) {
  4164. popup = this._popup;
  4165. this._popup = null;
  4166. }
  4167. if (popup) {
  4168. this.removeLayer(popup);
  4169. popup._isOpen = false;
  4170. }
  4171. return this;
  4172. }
  4173. });
  4174.  
  4175.  
  4176. /*
  4177. * Popup extension to L.Marker, adding popup-related methods.
  4178. */
  4179.  
  4180. L.Marker.include({
  4181. openPopup: function () {
  4182. if (this._popup && this._map && !this._map.hasLayer(this._popup)) {
  4183. this._popup.setLatLng(this._latlng);
  4184. this._map.openPopup(this._popup);
  4185. }
  4186.  
  4187. return this;
  4188. },
  4189.  
  4190. closePopup: function () {
  4191. if (this._popup) {
  4192. this._popup._close();
  4193. }
  4194. return this;
  4195. },
  4196.  
  4197. togglePopup: function () {
  4198. if (this._popup) {
  4199. if (this._popup._isOpen) {
  4200. this.closePopup();
  4201. } else {
  4202. this.openPopup();
  4203. }
  4204. }
  4205. return this;
  4206. },
  4207.  
  4208. bindPopup: function (content, options) {
  4209. var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
  4210.  
  4211. anchor = anchor.add(L.Popup.prototype.options.offset);
  4212.  
  4213. if (options && options.offset) {
  4214. anchor = anchor.add(options.offset);
  4215. }
  4216.  
  4217. options = L.extend({offset: anchor}, options);
  4218.  
  4219. if (!this._popupHandlersAdded) {
  4220. this
  4221. .on('click', this.togglePopup, this)
  4222. .on('remove', this.closePopup, this)
  4223. .on('move', this._movePopup, this);
  4224. this._popupHandlersAdded = true;
  4225. }
  4226.  
  4227. if (content instanceof L.Popup) {
  4228. L.setOptions(content, options);
  4229. this._popup = content;
  4230. } else {
  4231. this._popup = new L.Popup(options, this)
  4232. .setContent(content);
  4233. }
  4234.  
  4235. return this;
  4236. },
  4237.  
  4238. setPopupContent: function (content) {
  4239. if (this._popup) {
  4240. this._popup.setContent(content);
  4241. }
  4242. return this;
  4243. },
  4244.  
  4245. unbindPopup: function () {
  4246. if (this._popup) {
  4247. this._popup = null;
  4248. this
  4249. .off('click', this.togglePopup, this)
  4250. .off('remove', this.closePopup, this)
  4251. .off('move', this._movePopup, this);
  4252. this._popupHandlersAdded = false;
  4253. }
  4254. return this;
  4255. },
  4256.  
  4257. getPopup: function () {
  4258. return this._popup;
  4259. },
  4260.  
  4261. _movePopup: function (e) {
  4262. this._popup.setLatLng(e.latlng);
  4263. }
  4264. });
  4265.  
  4266.  
  4267. /*
  4268. * L.LayerGroup is a class to combine several layers into one so that
  4269. * you can manipulate the group (e.g. add/remove it) as one layer.
  4270. */
  4271.  
  4272. L.LayerGroup = L.Class.extend({
  4273. initialize: function (layers) {
  4274. this._layers = {};
  4275.  
  4276. var i, len;
  4277.  
  4278. if (layers) {
  4279. for (i = 0, len = layers.length; i < len; i++) {
  4280. this.addLayer(layers[i]);
  4281. }
  4282. }
  4283. },
  4284.  
  4285. addLayer: function (layer) {
  4286. var id = this.getLayerId(layer);
  4287.  
  4288. this._layers[id] = layer;
  4289.  
  4290. if (this._map) {
  4291. this._map.addLayer(layer);
  4292. }
  4293.  
  4294. return this;
  4295. },
  4296.  
  4297. removeLayer: function (layer) {
  4298. var id = layer in this._layers ? layer : this.getLayerId(layer);
  4299.  
  4300. if (this._map && this._layers[id]) {
  4301. this._map.removeLayer(this._layers[id]);
  4302. }
  4303.  
  4304. delete this._layers[id];
  4305.  
  4306. return this;
  4307. },
  4308.  
  4309. hasLayer: function (layer) {
  4310. if (!layer) { return false; }
  4311.  
  4312. return (layer in this._layers || this.getLayerId(layer) in this._layers);
  4313. },
  4314.  
  4315. clearLayers: function () {
  4316. this.eachLayer(this.removeLayer, this);
  4317. return this;
  4318. },
  4319.  
  4320. invoke: function (methodName) {
  4321. var args = Array.prototype.slice.call(arguments, 1),
  4322. i, layer;
  4323.  
  4324. for (i in this._layers) {
  4325. layer = this._layers[i];
  4326.  
  4327. if (layer[methodName]) {
  4328. layer[methodName].apply(layer, args);
  4329. }
  4330. }
  4331.  
  4332. return this;
  4333. },
  4334.  
  4335. onAdd: function (map) {
  4336. this._map = map;
  4337. this.eachLayer(map.addLayer, map);
  4338. },
  4339.  
  4340. onRemove: function (map) {
  4341. this.eachLayer(map.removeLayer, map);
  4342. this._map = null;
  4343. },
  4344.  
  4345. addTo: function (map) {
  4346. map.addLayer(this);
  4347. return this;
  4348. },
  4349.  
  4350. eachLayer: function (method, context) {
  4351. for (var i in this._layers) {
  4352. method.call(context, this._layers[i]);
  4353. }
  4354. return this;
  4355. },
  4356.  
  4357. getLayer: function (id) {
  4358. return this._layers[id];
  4359. },
  4360.  
  4361. getLayers: function () {
  4362. var layers = [];
  4363.  
  4364. for (var i in this._layers) {
  4365. layers.push(this._layers[i]);
  4366. }
  4367. return layers;
  4368. },
  4369.  
  4370. setZIndex: function (zIndex) {
  4371. return this.invoke('setZIndex', zIndex);
  4372. },
  4373.  
  4374. getLayerId: function (layer) {
  4375. return L.stamp(layer);
  4376. }
  4377. });
  4378.  
  4379. L.layerGroup = function (layers) {
  4380. return new L.LayerGroup(layers);
  4381. };
  4382.  
  4383.  
  4384. /*
  4385. * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods
  4386. * shared between a group of interactive layers (like vectors or markers).
  4387. */
  4388.  
  4389. L.FeatureGroup = L.LayerGroup.extend({
  4390. includes: L.Mixin.Events,
  4391.  
  4392. statics: {
  4393. EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
  4394. },
  4395.  
  4396. addLayer: function (layer) {
  4397. if (this.hasLayer(layer)) {
  4398. return this;
  4399. }
  4400.  
  4401. if ('on' in layer) {
  4402. layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
  4403. }
  4404.  
  4405. L.LayerGroup.prototype.addLayer.call(this, layer);
  4406.  
  4407. if (this._popupContent && layer.bindPopup) {
  4408. layer.bindPopup(this._popupContent, this._popupOptions);
  4409. }
  4410.  
  4411. return this.fire('layeradd', {layer: layer});
  4412. },
  4413.  
  4414. removeLayer: function (layer) {
  4415. if (!this.hasLayer(layer)) {
  4416. return this;
  4417. }
  4418. if (layer in this._layers) {
  4419. layer = this._layers[layer];
  4420. }
  4421.  
  4422. layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this);
  4423.  
  4424. L.LayerGroup.prototype.removeLayer.call(this, layer);
  4425.  
  4426. if (this._popupContent) {
  4427. this.invoke('unbindPopup');
  4428. }
  4429.  
  4430. return this.fire('layerremove', {layer: layer});
  4431. },
  4432.  
  4433. bindPopup: function (content, options) {
  4434. this._popupContent = content;
  4435. this._popupOptions = options;
  4436. return this.invoke('bindPopup', content, options);
  4437. },
  4438.  
  4439. openPopup: function (latlng) {
  4440. // open popup on the first layer
  4441. for (var id in this._layers) {
  4442. this._layers[id].openPopup(latlng);
  4443. break;
  4444. }
  4445. return this;
  4446. },
  4447.  
  4448. setStyle: function (style) {
  4449. return this.invoke('setStyle', style);
  4450. },
  4451.  
  4452. bringToFront: function () {
  4453. return this.invoke('bringToFront');
  4454. },
  4455.  
  4456. bringToBack: function () {
  4457. return this.invoke('bringToBack');
  4458. },
  4459.  
  4460. getBounds: function () {
  4461. var bounds = new L.LatLngBounds();
  4462.  
  4463. this.eachLayer(function (layer) {
  4464. bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
  4465. });
  4466.  
  4467. return bounds;
  4468. },
  4469.  
  4470. _propagateEvent: function (e) {
  4471. e = L.extend({
  4472. layer: e.target,
  4473. target: this
  4474. }, e);
  4475. this.fire(e.type, e);
  4476. }
  4477. });
  4478.  
  4479. L.featureGroup = function (layers) {
  4480. return new L.FeatureGroup(layers);
  4481. };
  4482.  
  4483.  
  4484. /*
  4485. * L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc.
  4486. */
  4487.  
  4488. L.Path = L.Class.extend({
  4489. includes: [L.Mixin.Events],
  4490.  
  4491. statics: {
  4492. // how much to extend the clip area around the map view
  4493. // (relative to its size, e.g. 0.5 is half the screen in each direction)
  4494. // set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is)
  4495. CLIP_PADDING: (function () {
  4496. var max = L.Browser.mobile ? 1280 : 2000,
  4497. target = (max / Math.max(window.outerWidth, window.outerHeight) - 1) / 2;
  4498. return Math.max(0, Math.min(0.5, target));
  4499. })()
  4500. },
  4501.  
  4502. options: {
  4503. stroke: true,
  4504. color: '#0033ff',
  4505. dashArray: null,
  4506. lineCap: null,
  4507. lineJoin: null,
  4508. weight: 5,
  4509. opacity: 0.5,
  4510.  
  4511. fill: false,
  4512. fillColor: null, //same as color by default
  4513. fillOpacity: 0.2,
  4514.  
  4515. clickable: true
  4516. },
  4517.  
  4518. initialize: function (options) {
  4519. L.setOptions(this, options);
  4520. },
  4521.  
  4522. onAdd: function (map) {
  4523. this._map = map;
  4524.  
  4525. if (!this._container) {
  4526. this._initElements();
  4527. this._initEvents();
  4528. }
  4529.  
  4530. this.projectLatlngs();
  4531. this._updatePath();
  4532.  
  4533. if (this._container) {
  4534. this._map._pathRoot.appendChild(this._container);
  4535. }
  4536.  
  4537. this.fire('add');
  4538.  
  4539. map.on({
  4540. 'viewreset': this.projectLatlngs,
  4541. 'moveend': this._updatePath
  4542. }, this);
  4543. },
  4544.  
  4545. addTo: function (map) {
  4546. map.addLayer(this);
  4547. return this;
  4548. },
  4549.  
  4550. onRemove: function (map) {
  4551. map._pathRoot.removeChild(this._container);
  4552.  
  4553. // Need to fire remove event before we set _map to null as the event hooks might need the object
  4554. this.fire('remove');
  4555. this._map = null;
  4556.  
  4557. if (L.Browser.vml) {
  4558. this._container = null;
  4559. this._stroke = null;
  4560. this._fill = null;
  4561. }
  4562.  
  4563. map.off({
  4564. 'viewreset': this.projectLatlngs,
  4565. 'moveend': this._updatePath
  4566. }, this);
  4567. },
  4568.  
  4569. projectLatlngs: function () {
  4570. // do all projection stuff here
  4571. },
  4572.  
  4573. setStyle: function (style) {
  4574. L.setOptions(this, style);
  4575.  
  4576. if (this._container) {
  4577. this._updateStyle();
  4578. }
  4579.  
  4580. return this;
  4581. },
  4582.  
  4583. redraw: function () {
  4584. if (this._map) {
  4585. this.projectLatlngs();
  4586. this._updatePath();
  4587. }
  4588. return this;
  4589. }
  4590. });
  4591.  
  4592. L.Map.include({
  4593. _updatePathViewport: function () {
  4594. var p = L.Path.CLIP_PADDING,
  4595. size = this.getSize(),
  4596. panePos = L.DomUtil.getPosition(this._mapPane),
  4597. min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
  4598. max = min.add(size.multiplyBy(1 + p * 2)._round());
  4599.  
  4600. this._pathViewport = new L.Bounds(min, max);
  4601. }
  4602. });
  4603.  
  4604.  
  4605. /*
  4606. * Extends L.Path with SVG-specific rendering code.
  4607. */
  4608.  
  4609. L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
  4610.  
  4611. L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
  4612.  
  4613. L.Path = L.Path.extend({
  4614. statics: {
  4615. SVG: L.Browser.svg
  4616. },
  4617.  
  4618. bringToFront: function () {
  4619. var root = this._map._pathRoot,
  4620. path = this._container;
  4621.  
  4622. if (path && root.lastChild !== path) {
  4623. root.appendChild(path);
  4624. }
  4625. return this;
  4626. },
  4627.  
  4628. bringToBack: function () {
  4629. var root = this._map._pathRoot,
  4630. path = this._container,
  4631. first = root.firstChild;
  4632.  
  4633. if (path && first !== path) {
  4634. root.insertBefore(path, first);
  4635. }
  4636. return this;
  4637. },
  4638.  
  4639. getPathString: function () {
  4640. // form path string here
  4641. },
  4642.  
  4643. _createElement: function (name) {
  4644. return document.createElementNS(L.Path.SVG_NS, name);
  4645. },
  4646.  
  4647. _initElements: function () {
  4648. this._map._initPathRoot();
  4649. this._initPath();
  4650. this._initStyle();
  4651. },
  4652.  
  4653. _initPath: function () {
  4654. this._container = this._createElement('g');
  4655.  
  4656. this._path = this._createElement('path');
  4657.  
  4658. if (this.options.className) {
  4659. L.DomUtil.addClass(this._path, this.options.className);
  4660. }
  4661.  
  4662. this._container.appendChild(this._path);
  4663. },
  4664.  
  4665. _initStyle: function () {
  4666. if (this.options.stroke) {
  4667. this._path.setAttribute('stroke-linejoin', 'round');
  4668. this._path.setAttribute('stroke-linecap', 'round');
  4669. }
  4670. if (this.options.fill) {
  4671. this._path.setAttribute('fill-rule', 'evenodd');
  4672. }
  4673. if (this.options.pointerEvents) {
  4674. this._path.setAttribute('pointer-events', this.options.pointerEvents);
  4675. }
  4676. if (!this.options.clickable && !this.options.pointerEvents) {
  4677. this._path.setAttribute('pointer-events', 'none');
  4678. }
  4679. this._updateStyle();
  4680. },
  4681.  
  4682. _updateStyle: function () {
  4683. if (this.options.stroke) {
  4684. this._path.setAttribute('stroke', this.options.color);
  4685. this._path.setAttribute('stroke-opacity', this.options.opacity);
  4686. this._path.setAttribute('stroke-width', this.options.weight);
  4687. if (this.options.dashArray) {
  4688. this._path.setAttribute('stroke-dasharray', this.options.dashArray);
  4689. } else {
  4690. this._path.removeAttribute('stroke-dasharray');
  4691. }
  4692. if (this.options.lineCap) {
  4693. this._path.setAttribute('stroke-linecap', this.options.lineCap);
  4694. }
  4695. if (this.options.lineJoin) {
  4696. this._path.setAttribute('stroke-linejoin', this.options.lineJoin);
  4697. }
  4698. } else {
  4699. this._path.setAttribute('stroke', 'none');
  4700. }
  4701. if (this.options.fill) {
  4702. this._path.setAttribute('fill', this.options.fillColor || this.options.color);
  4703. this._path.setAttribute('fill-opacity', this.options.fillOpacity);
  4704. } else {
  4705. this._path.setAttribute('fill', 'none');
  4706. }
  4707. },
  4708.  
  4709. _updatePath: function () {
  4710. var str = this.getPathString();
  4711. if (!str) {
  4712. // fix webkit empty string parsing bug
  4713. str = 'M0 0';
  4714. }
  4715. this._path.setAttribute('d', str);
  4716. },
  4717.  
  4718. // TODO remove duplication with L.Map
  4719. _initEvents: function () {
  4720. if (this.options.clickable) {
  4721. if (L.Browser.svg || !L.Browser.vml) {
  4722. L.DomUtil.addClass(this._path, 'leaflet-clickable');
  4723. }
  4724.  
  4725. L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
  4726.  
  4727. var events = ['dblclick', 'mousedown', 'mouseover',
  4728. 'mouseout', 'mousemove', 'contextmenu'];
  4729. for (var i = 0; i < events.length; i++) {
  4730. L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
  4731. }
  4732. }
  4733. },
  4734.  
  4735. _onMouseClick: function (e) {
  4736. if (this._map.dragging && this._map.dragging.moved()) { return; }
  4737.  
  4738. this._fireMouseEvent(e);
  4739. },
  4740.  
  4741. _fireMouseEvent: function (e) {
  4742. if (!this.hasEventListeners(e.type)) { return; }
  4743.  
  4744. var map = this._map,
  4745. containerPoint = map.mouseEventToContainerPoint(e),
  4746. layerPoint = map.containerPointToLayerPoint(containerPoint),
  4747. latlng = map.layerPointToLatLng(layerPoint);
  4748.  
  4749. this.fire(e.type, {
  4750. latlng: latlng,
  4751. layerPoint: layerPoint,
  4752. containerPoint: containerPoint,
  4753. originalEvent: e
  4754. });
  4755.  
  4756. if (e.type === 'contextmenu') {
  4757. L.DomEvent.preventDefault(e);
  4758. }
  4759. if (e.type !== 'mousemove') {
  4760. L.DomEvent.stopPropagation(e);
  4761. }
  4762. }
  4763. });
  4764.  
  4765. L.Map.include({
  4766. _initPathRoot: function () {
  4767. if (!this._pathRoot) {
  4768. this._pathRoot = L.Path.prototype._createElement('svg');
  4769. this._panes.overlayPane.appendChild(this._pathRoot);
  4770.  
  4771. if (this.options.zoomAnimation && L.Browser.any3d) {
  4772. L.DomUtil.addClass(this._pathRoot, 'leaflet-zoom-animated');
  4773.  
  4774. this.on({
  4775. 'zoomanim': this._animatePathZoom,
  4776. 'zoomend': this._endPathZoom
  4777. });
  4778. } else {
  4779. L.DomUtil.addClass(this._pathRoot, 'leaflet-zoom-hide');
  4780. }
  4781.  
  4782. this.on('moveend', this._updateSvgViewport);
  4783. this._updateSvgViewport();
  4784. }
  4785. },
  4786.  
  4787. _animatePathZoom: function (e) {
  4788. var scale = this.getZoomScale(e.zoom),
  4789. offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min);
  4790.  
  4791. this._pathRoot.style[L.DomUtil.TRANSFORM] =
  4792. L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') ';
  4793.  
  4794. this._pathZooming = true;
  4795. },
  4796.  
  4797. _endPathZoom: function () {
  4798. this._pathZooming = false;
  4799. },
  4800.  
  4801. _updateSvgViewport: function () {
  4802.  
  4803. if (this._pathZooming) {
  4804. // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
  4805. // When the zoom animation ends we will be updated again anyway
  4806. // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
  4807. return;
  4808. }
  4809.  
  4810. this._updatePathViewport();
  4811.  
  4812. var vp = this._pathViewport,
  4813. min = vp.min,
  4814. max = vp.max,
  4815. width = max.x - min.x,
  4816. height = max.y - min.y,
  4817. root = this._pathRoot,
  4818. pane = this._panes.overlayPane;
  4819.  
  4820. // Hack to make flicker on drag end on mobile webkit less irritating
  4821. if (L.Browser.mobileWebkit) {
  4822. pane.removeChild(root);
  4823. }
  4824.  
  4825. L.DomUtil.setPosition(root, min);
  4826. root.setAttribute('width', width);
  4827. root.setAttribute('height', height);
  4828. root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
  4829.  
  4830. if (L.Browser.mobileWebkit) {
  4831. pane.appendChild(root);
  4832. }
  4833. }
  4834. });
  4835.  
  4836.  
  4837. /*
  4838. * Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods.
  4839. */
  4840.  
  4841. L.Path.include({
  4842.  
  4843. bindPopup: function (content, options) {
  4844.  
  4845. if (content instanceof L.Popup) {
  4846. this._popup = content;
  4847. } else {
  4848. if (!this._popup || options) {
  4849. this._popup = new L.Popup(options, this);
  4850. }
  4851. this._popup.setContent(content);
  4852. }
  4853.  
  4854. if (!this._popupHandlersAdded) {
  4855. this
  4856. .on('click', this._openPopup, this)
  4857. .on('remove', this.closePopup, this);
  4858.  
  4859. this._popupHandlersAdded = true;
  4860. }
  4861.  
  4862. return this;
  4863. },
  4864.  
  4865. unbindPopup: function () {
  4866. if (this._popup) {
  4867. this._popup = null;
  4868. this
  4869. .off('click', this._openPopup)
  4870. .off('remove', this.closePopup);
  4871.  
  4872. this._popupHandlersAdded = false;
  4873. }
  4874. return this;
  4875. },
  4876.  
  4877. openPopup: function (latlng) {
  4878.  
  4879. if (this._popup) {
  4880. // open the popup from one of the path's points if not specified
  4881. latlng = latlng || this._latlng ||
  4882. this._latlngs[Math.floor(this._latlngs.length / 2)];
  4883.  
  4884. this._openPopup({latlng: latlng});
  4885. }
  4886.  
  4887. return this;
  4888. },
  4889.  
  4890. closePopup: function () {
  4891. if (this._popup) {
  4892. this._popup._close();
  4893. }
  4894. return this;
  4895. },
  4896.  
  4897. _openPopup: function (e) {
  4898. this._popup.setLatLng(e.latlng);
  4899. this._map.openPopup(this._popup);
  4900. }
  4901. });
  4902.  
  4903.  
  4904. /*
  4905. * Vector rendering for IE6-8 through VML.
  4906. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  4907. */
  4908.  
  4909. L.Browser.vml = !L.Browser.svg && (function () {
  4910. try {
  4911. var div = document.createElement('div');
  4912. div.innerHTML = '<v:shape adj="1"/>';
  4913.  
  4914. var shape = div.firstChild;
  4915. shape.style.behavior = 'url(#default#VML)';
  4916.  
  4917. return shape && (typeof shape.adj === 'object');
  4918.  
  4919. } catch (e) {
  4920. return false;
  4921. }
  4922. }());
  4923.  
  4924. L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
  4925. statics: {
  4926. VML: true,
  4927. CLIP_PADDING: 0.02
  4928. },
  4929.  
  4930. _createElement: (function () {
  4931. try {
  4932. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  4933. return function (name) {
  4934. return document.createElement('<lvml:' + name + ' class="lvml">');
  4935. };
  4936. } catch (e) {
  4937. return function (name) {
  4938. return document.createElement(
  4939. '<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  4940. };
  4941. }
  4942. }()),
  4943.  
  4944. _initPath: function () {
  4945. var container = this._container = this._createElement('shape');
  4946.  
  4947. L.DomUtil.addClass(container, 'leaflet-vml-shape' +
  4948. (this.options.className ? ' ' + this.options.className : ''));
  4949.  
  4950. if (this.options.clickable) {
  4951. L.DomUtil.addClass(container, 'leaflet-clickable');
  4952. }
  4953.  
  4954. container.coordsize = '1 1';
  4955.  
  4956. this._path = this._createElement('path');
  4957. container.appendChild(this._path);
  4958.  
  4959. this._map._pathRoot.appendChild(container);
  4960. },
  4961.  
  4962. _initStyle: function () {
  4963. this._updateStyle();
  4964. },
  4965.  
  4966. _updateStyle: function () {
  4967. var stroke = this._stroke,
  4968. fill = this._fill,
  4969. options = this.options,
  4970. container = this._container;
  4971.  
  4972. container.stroked = options.stroke;
  4973. container.filled = options.fill;
  4974.  
  4975. if (options.stroke) {
  4976. if (!stroke) {
  4977. stroke = this._stroke = this._createElement('stroke');
  4978. stroke.endcap = 'round';
  4979. container.appendChild(stroke);
  4980. }
  4981. stroke.weight = options.weight + 'px';
  4982. stroke.color = options.color;
  4983. stroke.opacity = options.opacity;
  4984.  
  4985. if (options.dashArray) {
  4986. stroke.dashStyle = L.Util.isArray(options.dashArray) ?
  4987. options.dashArray.join(' ') :
  4988. options.dashArray.replace(/( *, *)/g, ' ');
  4989. } else {
  4990. stroke.dashStyle = '';
  4991. }
  4992. if (options.lineCap) {
  4993. stroke.endcap = options.lineCap.replace('butt', 'flat');
  4994. }
  4995. if (options.lineJoin) {
  4996. stroke.joinstyle = options.lineJoin;
  4997. }
  4998.  
  4999. } else if (stroke) {
  5000. container.removeChild(stroke);
  5001. this._stroke = null;
  5002. }
  5003.  
  5004. if (options.fill) {
  5005. if (!fill) {
  5006. fill = this._fill = this._createElement('fill');
  5007. container.appendChild(fill);
  5008. }
  5009. fill.color = options.fillColor || options.color;
  5010. fill.opacity = options.fillOpacity;
  5011.  
  5012. } else if (fill) {
  5013. container.removeChild(fill);
  5014. this._fill = null;
  5015. }
  5016. },
  5017.  
  5018. _updatePath: function () {
  5019. var style = this._container.style;
  5020.  
  5021. style.display = 'none';
  5022. this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
  5023. style.display = '';
  5024. }
  5025. });
  5026.  
  5027. L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
  5028. _initPathRoot: function () {
  5029. if (this._pathRoot) { return; }
  5030.  
  5031. var root = this._pathRoot = document.createElement('div');
  5032. root.className = 'leaflet-vml-container';
  5033. this._panes.overlayPane.appendChild(root);
  5034.  
  5035. this.on('moveend', this._updatePathViewport);
  5036. this._updatePathViewport();
  5037. }
  5038. });
  5039.  
  5040.  
  5041. /*
  5042. * Vector rendering for all browsers that support canvas.
  5043. */
  5044.  
  5045. L.Browser.canvas = (function () {
  5046. return !!document.createElement('canvas').getContext;
  5047. }());
  5048.  
  5049. L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
  5050. statics: {
  5051. //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
  5052. CANVAS: true,
  5053. SVG: false
  5054. },
  5055.  
  5056. redraw: function () {
  5057. if (this._map) {
  5058. this.projectLatlngs();
  5059. this._requestUpdate();
  5060. }
  5061. return this;
  5062. },
  5063.  
  5064. setStyle: function (style) {
  5065. L.setOptions(this, style);
  5066.  
  5067. if (this._map) {
  5068. this._updateStyle();
  5069. this._requestUpdate();
  5070. }
  5071. return this;
  5072. },
  5073.  
  5074. onRemove: function (map) {
  5075. map
  5076. .off('viewreset', this.projectLatlngs, this)
  5077. .off('moveend', this._updatePath, this);
  5078.  
  5079. if (this.options.clickable) {
  5080. this._map.off('click', this._onClick, this);
  5081. this._map.off('mousemove', this._onMouseMove, this);
  5082. }
  5083.  
  5084. this._requestUpdate();
  5085. this.fire('remove');
  5086. this._map = null;
  5087. },
  5088.  
  5089. _requestUpdate: function () {
  5090. if (this._map && !L.Path._updateRequest) {
  5091. L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
  5092. }
  5093. },
  5094.  
  5095. _fireMapMoveEnd: function () {
  5096. L.Path._updateRequest = null;
  5097. this.fire('moveend');
  5098. },
  5099.  
  5100. _initElements: function () {
  5101. this._map._initPathRoot();
  5102. this._ctx = this._map._canvasCtx;
  5103. },
  5104.  
  5105. _updateStyle: function () {
  5106. var options = this.options;
  5107.  
  5108. if (options.stroke) {
  5109. this._ctx.lineWidth = options.weight;
  5110. this._ctx.strokeStyle = options.color;
  5111. }
  5112. if (options.fill) {
  5113. this._ctx.fillStyle = options.fillColor || options.color;
  5114. }
  5115. },
  5116.  
  5117. _drawPath: function () {
  5118. var i, j, len, len2, point, drawMethod;
  5119.  
  5120. this._ctx.beginPath();
  5121.  
  5122. for (i = 0, len = this._parts.length; i < len; i++) {
  5123. for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
  5124. point = this._parts[i][j];
  5125. drawMethod = (j === 0 ? 'move' : 'line') + 'To';
  5126.  
  5127. this._ctx[drawMethod](point.x, point.y);
  5128. }
  5129. // TODO refactor ugly hack
  5130. if (this instanceof L.Polygon) {
  5131. this._ctx.closePath();
  5132. }
  5133. }
  5134. },
  5135.  
  5136. _checkIfEmpty: function () {
  5137. return !this._parts.length;
  5138. },
  5139.  
  5140. _updatePath: function () {
  5141. if (this._checkIfEmpty()) { return; }
  5142.  
  5143. var ctx = this._ctx,
  5144. options = this.options;
  5145.  
  5146. this._drawPath();
  5147. ctx.save();
  5148. this._updateStyle();
  5149.  
  5150. if (options.fill) {
  5151. ctx.globalAlpha = options.fillOpacity;
  5152. ctx.fill();
  5153. }
  5154.  
  5155. if (options.stroke) {
  5156. ctx.globalAlpha = options.opacity;
  5157. ctx.stroke();
  5158. }
  5159.  
  5160. ctx.restore();
  5161.  
  5162. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  5163. },
  5164.  
  5165. _initEvents: function () {
  5166. if (this.options.clickable) {
  5167. // TODO dblclick
  5168. this._map.on('mousemove', this._onMouseMove, this);
  5169. this._map.on('click', this._onClick, this);
  5170. }
  5171. },
  5172.  
  5173. _onClick: function (e) {
  5174. if (this._containsPoint(e.layerPoint)) {
  5175. this.fire('click', e);
  5176. }
  5177. },
  5178.  
  5179. _onMouseMove: function (e) {
  5180. if (!this._map || this._map._animatingZoom) { return; }
  5181.  
  5182. // TODO don't do on each move
  5183. if (this._containsPoint(e.layerPoint)) {
  5184. this._ctx.canvas.style.cursor = 'pointer';
  5185. this._mouseInside = true;
  5186. this.fire('mouseover', e);
  5187.  
  5188. } else if (this._mouseInside) {
  5189. this._ctx.canvas.style.cursor = '';
  5190. this._mouseInside = false;
  5191. this.fire('mouseout', e);
  5192. }
  5193. }
  5194. });
  5195.  
  5196. L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
  5197. _initPathRoot: function () {
  5198. var root = this._pathRoot,
  5199. ctx;
  5200.  
  5201. if (!root) {
  5202. root = this._pathRoot = document.createElement('canvas');
  5203. root.style.position = 'absolute';
  5204. ctx = this._canvasCtx = root.getContext('2d');
  5205.  
  5206. ctx.lineCap = 'round';
  5207. ctx.lineJoin = 'round';
  5208.  
  5209. this._panes.overlayPane.appendChild(root);
  5210.  
  5211. if (this.options.zoomAnimation) {
  5212. this._pathRoot.className = 'leaflet-zoom-animated';
  5213. this.on('zoomanim', this._animatePathZoom);
  5214. this.on('zoomend', this._endPathZoom);
  5215. }
  5216. this.on('moveend', this._updateCanvasViewport);
  5217. this._updateCanvasViewport();
  5218. }
  5219. },
  5220.  
  5221. _updateCanvasViewport: function () {
  5222. // don't redraw while zooming. See _updateSvgViewport for more details
  5223. if (this._pathZooming) { return; }
  5224. this._updatePathViewport();
  5225.  
  5226. var vp = this._pathViewport,
  5227. min = vp.min,
  5228. size = vp.max.subtract(min),
  5229. root = this._pathRoot;
  5230.  
  5231. //TODO check if this works properly on mobile webkit
  5232. L.DomUtil.setPosition(root, min);
  5233. root.width = size.x;
  5234. root.height = size.y;
  5235. root.getContext('2d').translate(-min.x, -min.y);
  5236. }
  5237. });
  5238.  
  5239.  
  5240. /*
  5241. * L.LineUtil contains different utility functions for line segments
  5242. * and polylines (clipping, simplification, distances, etc.)
  5243. */
  5244.  
  5245. /*jshint bitwise:false */ // allow bitwise operations for this file
  5246.  
  5247. L.LineUtil = {
  5248.  
  5249. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  5250. // Improves rendering performance dramatically by lessening the number of points to draw.
  5251.  
  5252. simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
  5253. if (!tolerance || !points.length) {
  5254. return points.slice();
  5255. }
  5256.  
  5257. var sqTolerance = tolerance * tolerance;
  5258.  
  5259. // stage 1: vertex reduction
  5260. points = this._reducePoints(points, sqTolerance);
  5261.  
  5262. // stage 2: Douglas-Peucker simplification
  5263. points = this._simplifyDP(points, sqTolerance);
  5264.  
  5265. return points;
  5266. },
  5267.  
  5268. // distance from a point to a segment between two points
  5269. pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
  5270. return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
  5271. },
  5272.  
  5273. closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
  5274. return this._sqClosestPointOnSegment(p, p1, p2);
  5275. },
  5276.  
  5277. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  5278. _simplifyDP: function (points, sqTolerance) {
  5279.  
  5280. var len = points.length,
  5281. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  5282. markers = new ArrayConstructor(len);
  5283.  
  5284. markers[0] = markers[len - 1] = 1;
  5285.  
  5286. this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  5287.  
  5288. var i,
  5289. newPoints = [];
  5290.  
  5291. for (i = 0; i < len; i++) {
  5292. if (markers[i]) {
  5293. newPoints.push(points[i]);
  5294. }
  5295. }
  5296.  
  5297. return newPoints;
  5298. },
  5299.  
  5300. _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
  5301.  
  5302. var maxSqDist = 0,
  5303. index, i, sqDist;
  5304.  
  5305. for (i = first + 1; i <= last - 1; i++) {
  5306. sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
  5307.  
  5308. if (sqDist > maxSqDist) {
  5309. index = i;
  5310. maxSqDist = sqDist;
  5311. }
  5312. }
  5313.  
  5314. if (maxSqDist > sqTolerance) {
  5315. markers[index] = 1;
  5316.  
  5317. this._simplifyDPStep(points, markers, sqTolerance, first, index);
  5318. this._simplifyDPStep(points, markers, sqTolerance, index, last);
  5319. }
  5320. },
  5321.  
  5322. // reduce points that are too close to each other to a single point
  5323. _reducePoints: function (points, sqTolerance) {
  5324. var reducedPoints = [points[0]];
  5325.  
  5326. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  5327. if (this._sqDist(points[i], points[prev]) > sqTolerance) {
  5328. reducedPoints.push(points[i]);
  5329. prev = i;
  5330. }
  5331. }
  5332. if (prev < len - 1) {
  5333. reducedPoints.push(points[len - 1]);
  5334. }
  5335. return reducedPoints;
  5336. },
  5337.  
  5338. // Cohen-Sutherland line clipping algorithm.
  5339. // Used to avoid rendering parts of a polyline that are not currently visible.
  5340.  
  5341. clipSegment: function (a, b, bounds, useLastCode) {
  5342. var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
  5343. codeB = this._getBitCode(b, bounds),
  5344.  
  5345. codeOut, p, newCode;
  5346.  
  5347. // save 2nd code to avoid calculating it on the next segment
  5348. this._lastCode = codeB;
  5349.  
  5350. while (true) {
  5351. // if a,b is inside the clip window (trivial accept)
  5352. if (!(codeA | codeB)) {
  5353. return [a, b];
  5354. // if a,b is outside the clip window (trivial reject)
  5355. } else if (codeA & codeB) {
  5356. return false;
  5357. // other cases
  5358. } else {
  5359. codeOut = codeA || codeB;
  5360. p = this._getEdgeIntersection(a, b, codeOut, bounds);
  5361. newCode = this._getBitCode(p, bounds);
  5362.  
  5363. if (codeOut === codeA) {
  5364. a = p;
  5365. codeA = newCode;
  5366. } else {
  5367. b = p;
  5368. codeB = newCode;
  5369. }
  5370. }
  5371. }
  5372. },
  5373.  
  5374. _getEdgeIntersection: function (a, b, code, bounds) {
  5375. var dx = b.x - a.x,
  5376. dy = b.y - a.y,
  5377. min = bounds.min,
  5378. max = bounds.max;
  5379.  
  5380. if (code & 8) { // top
  5381. return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
  5382. } else if (code & 4) { // bottom
  5383. return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
  5384. } else if (code & 2) { // right
  5385. return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
  5386. } else if (code & 1) { // left
  5387. return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
  5388. }
  5389. },
  5390.  
  5391. _getBitCode: function (/*Point*/ p, bounds) {
  5392. var code = 0;
  5393.  
  5394. if (p.x < bounds.min.x) { // left
  5395. code |= 1;
  5396. } else if (p.x > bounds.max.x) { // right
  5397. code |= 2;
  5398. }
  5399. if (p.y < bounds.min.y) { // bottom
  5400. code |= 4;
  5401. } else if (p.y > bounds.max.y) { // top
  5402. code |= 8;
  5403. }
  5404.  
  5405. return code;
  5406. },
  5407.  
  5408. // square distance (to avoid unnecessary Math.sqrt calls)
  5409. _sqDist: function (p1, p2) {
  5410. var dx = p2.x - p1.x,
  5411. dy = p2.y - p1.y;
  5412. return dx * dx + dy * dy;
  5413. },
  5414.  
  5415. // return closest point on segment or distance to that point
  5416. _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
  5417. var x = p1.x,
  5418. y = p1.y,
  5419. dx = p2.x - x,
  5420. dy = p2.y - y,
  5421. dot = dx * dx + dy * dy,
  5422. t;
  5423.  
  5424. if (dot > 0) {
  5425. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  5426.  
  5427. if (t > 1) {
  5428. x = p2.x;
  5429. y = p2.y;
  5430. } else if (t > 0) {
  5431. x += dx * t;
  5432. y += dy * t;
  5433. }
  5434. }
  5435.  
  5436. dx = p.x - x;
  5437. dy = p.y - y;
  5438.  
  5439. return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
  5440. }
  5441. };
  5442.  
  5443.  
  5444. /*
  5445. * L.Polyline is used to display polylines on a map.
  5446. */
  5447.  
  5448. L.Polyline = L.Path.extend({
  5449. initialize: function (latlngs, options) {
  5450. L.Path.prototype.initialize.call(this, options);
  5451.  
  5452. this._latlngs = this._convertLatLngs(latlngs);
  5453. },
  5454.  
  5455. options: {
  5456. // how much to simplify the polyline on each zoom level
  5457. // more = better performance and smoother look, less = more accurate
  5458. smoothFactor: 1.0,
  5459. noClip: false
  5460. },
  5461.  
  5462. projectLatlngs: function () {
  5463. this._originalPoints = [];
  5464.  
  5465. for (var i = 0, len = this._latlngs.length; i < len; i++) {
  5466. this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
  5467. }
  5468. },
  5469.  
  5470. getPathString: function () {
  5471. for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
  5472. str += this._getPathPartStr(this._parts[i]);
  5473. }
  5474. return str;
  5475. },
  5476.  
  5477. getLatLngs: function () {
  5478. return this._latlngs;
  5479. },
  5480.  
  5481. setLatLngs: function (latlngs) {
  5482. this._latlngs = this._convertLatLngs(latlngs);
  5483. return this.redraw();
  5484. },
  5485.  
  5486. addLatLng: function (latlng) {
  5487. this._latlngs.push(L.latLng(latlng));
  5488. return this.redraw();
  5489. },
  5490.  
  5491. spliceLatLngs: function () { // (Number index, Number howMany)
  5492. var removed = [].splice.apply(this._latlngs, arguments);
  5493. this._convertLatLngs(this._latlngs, true);
  5494. this.redraw();
  5495. return removed;
  5496. },
  5497.  
  5498. closestLayerPoint: function (p) {
  5499. var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
  5500.  
  5501. for (var j = 0, jLen = parts.length; j < jLen; j++) {
  5502. var points = parts[j];
  5503. for (var i = 1, len = points.length; i < len; i++) {
  5504. p1 = points[i - 1];
  5505. p2 = points[i];
  5506. var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
  5507. if (sqDist < minDistance) {
  5508. minDistance = sqDist;
  5509. minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
  5510. }
  5511. }
  5512. }
  5513. if (minPoint) {
  5514. minPoint.distance = Math.sqrt(minDistance);
  5515. }
  5516. return minPoint;
  5517. },
  5518.  
  5519. getBounds: function () {
  5520. return new L.LatLngBounds(this.getLatLngs());
  5521. },
  5522.  
  5523. _convertLatLngs: function (latlngs, overwrite) {
  5524. var i, len, target = overwrite ? latlngs : [];
  5525.  
  5526. for (i = 0, len = latlngs.length; i < len; i++) {
  5527. if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') {
  5528. return;
  5529. }
  5530. target[i] = L.latLng(latlngs[i]);
  5531. }
  5532. return target;
  5533. },
  5534.  
  5535. _initEvents: function () {
  5536. L.Path.prototype._initEvents.call(this);
  5537. },
  5538.  
  5539. _getPathPartStr: function (points) {
  5540. var round = L.Path.VML;
  5541.  
  5542. for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
  5543. p = points[j];
  5544. if (round) {
  5545. p._round();
  5546. }
  5547. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  5548. }
  5549. return str;
  5550. },
  5551.  
  5552. _clipPoints: function () {
  5553. var points = this._originalPoints,
  5554. len = points.length,
  5555. i, k, segment;
  5556.  
  5557. if (this.options.noClip) {
  5558. this._parts = [points];
  5559. return;
  5560. }
  5561.  
  5562. this._parts = [];
  5563.  
  5564. var parts = this._parts,
  5565. vp = this._map._pathViewport,
  5566. lu = L.LineUtil;
  5567.  
  5568. for (i = 0, k = 0; i < len - 1; i++) {
  5569. segment = lu.clipSegment(points[i], points[i + 1], vp, i);
  5570. if (!segment) {
  5571. continue;
  5572. }
  5573.  
  5574. parts[k] = parts[k] || [];
  5575. parts[k].push(segment[0]);
  5576.  
  5577. // if segment goes out of screen, or it's the last one, it's the end of the line part
  5578. if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
  5579. parts[k].push(segment[1]);
  5580. k++;
  5581. }
  5582. }
  5583. },
  5584.  
  5585. // simplify each clipped part of the polyline
  5586. _simplifyPoints: function () {
  5587. var parts = this._parts,
  5588. lu = L.LineUtil;
  5589.  
  5590. for (var i = 0, len = parts.length; i < len; i++) {
  5591. parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
  5592. }
  5593. },
  5594.  
  5595. _updatePath: function () {
  5596. if (!this._map) { return; }
  5597.  
  5598. this._clipPoints();
  5599. this._simplifyPoints();
  5600.  
  5601. L.Path.prototype._updatePath.call(this);
  5602. }
  5603. });
  5604.  
  5605. L.polyline = function (latlngs, options) {
  5606. return new L.Polyline(latlngs, options);
  5607. };
  5608.  
  5609.  
  5610. /*
  5611. * L.PolyUtil contains utility functions for polygons (clipping, etc.).
  5612. */
  5613.  
  5614. /*jshint bitwise:false */ // allow bitwise operations here
  5615.  
  5616. L.PolyUtil = {};
  5617.  
  5618. /*
  5619. * Sutherland-Hodgeman polygon clipping algorithm.
  5620. * Used to avoid rendering parts of a polygon that are not currently visible.
  5621. */
  5622. L.PolyUtil.clipPolygon = function (points, bounds) {
  5623. var clippedPoints,
  5624. edges = [1, 4, 2, 8],
  5625. i, j, k,
  5626. a, b,
  5627. len, edge, p,
  5628. lu = L.LineUtil;
  5629.  
  5630. for (i = 0, len = points.length; i < len; i++) {
  5631. points[i]._code = lu._getBitCode(points[i], bounds);
  5632. }
  5633.  
  5634. // for each edge (left, bottom, right, top)
  5635. for (k = 0; k < 4; k++) {
  5636. edge = edges[k];
  5637. clippedPoints = [];
  5638.  
  5639. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5640. a = points[i];
  5641. b = points[j];
  5642.  
  5643. // if a is inside the clip window
  5644. if (!(a._code & edge)) {
  5645. // if b is outside the clip window (a->b goes out of screen)
  5646. if (b._code & edge) {
  5647. p = lu._getEdgeIntersection(b, a, edge, bounds);
  5648. p._code = lu._getBitCode(p, bounds);
  5649. clippedPoints.push(p);
  5650. }
  5651. clippedPoints.push(a);
  5652.  
  5653. // else if b is inside the clip window (a->b enters the screen)
  5654. } else if (!(b._code & edge)) {
  5655. p = lu._getEdgeIntersection(b, a, edge, bounds);
  5656. p._code = lu._getBitCode(p, bounds);
  5657. clippedPoints.push(p);
  5658. }
  5659. }
  5660. points = clippedPoints;
  5661. }
  5662.  
  5663. return points;
  5664. };
  5665.  
  5666.  
  5667. /*
  5668. * L.Polygon is used to display polygons on a map.
  5669. */
  5670.  
  5671. L.Polygon = L.Polyline.extend({
  5672. options: {
  5673. fill: true
  5674. },
  5675.  
  5676. initialize: function (latlngs, options) {
  5677. L.Polyline.prototype.initialize.call(this, latlngs, options);
  5678. this._initWithHoles(latlngs);
  5679. },
  5680.  
  5681. _initWithHoles: function (latlngs) {
  5682. var i, len, hole;
  5683. if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
  5684. this._latlngs = this._convertLatLngs(latlngs[0]);
  5685. this._holes = latlngs.slice(1);
  5686.  
  5687. for (i = 0, len = this._holes.length; i < len; i++) {
  5688. hole = this._holes[i] = this._convertLatLngs(this._holes[i]);
  5689. if (hole[0].equals(hole[hole.length - 1])) {
  5690. hole.pop();
  5691. }
  5692. }
  5693. }
  5694.  
  5695. // filter out last point if its equal to the first one
  5696. latlngs = this._latlngs;
  5697.  
  5698. if (latlngs.length >= 2 && latlngs[0].equals(latlngs[latlngs.length - 1])) {
  5699. latlngs.pop();
  5700. }
  5701. },
  5702.  
  5703. projectLatlngs: function () {
  5704. L.Polyline.prototype.projectLatlngs.call(this);
  5705.  
  5706. // project polygon holes points
  5707. // TODO move this logic to Polyline to get rid of duplication
  5708. this._holePoints = [];
  5709.  
  5710. if (!this._holes) { return; }
  5711.  
  5712. var i, j, len, len2;
  5713.  
  5714. for (i = 0, len = this._holes.length; i < len; i++) {
  5715. this._holePoints[i] = [];
  5716.  
  5717. for (j = 0, len2 = this._holes[i].length; j < len2; j++) {
  5718. this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
  5719. }
  5720. }
  5721. },
  5722.  
  5723. setLatLngs: function (latlngs) {
  5724. if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
  5725. this._initWithHoles(latlngs);
  5726. return this.redraw();
  5727. } else {
  5728. return L.Polyline.prototype.setLatLngs.call(this, latlngs);
  5729. }
  5730. },
  5731.  
  5732. _clipPoints: function () {
  5733. var points = this._originalPoints,
  5734. newParts = [];
  5735.  
  5736. this._parts = [points].concat(this._holePoints);
  5737.  
  5738. if (this.options.noClip) { return; }
  5739.  
  5740. for (var i = 0, len = this._parts.length; i < len; i++) {
  5741. var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
  5742. if (clipped.length) {
  5743. newParts.push(clipped);
  5744. }
  5745. }
  5746.  
  5747. this._parts = newParts;
  5748. },
  5749.  
  5750. _getPathPartStr: function (points) {
  5751. var str = L.Polyline.prototype._getPathPartStr.call(this, points);
  5752. return str + (L.Browser.svg ? 'z' : 'x');
  5753. }
  5754. });
  5755.  
  5756. L.polygon = function (latlngs, options) {
  5757. return new L.Polygon(latlngs, options);
  5758. };
  5759.  
  5760.  
  5761. /*
  5762. * Contains L.MultiPolyline and L.MultiPolygon layers.
  5763. */
  5764.  
  5765. (function () {
  5766. function createMulti(Klass) {
  5767.  
  5768. return L.FeatureGroup.extend({
  5769.  
  5770. initialize: function (latlngs, options) {
  5771. this._layers = {};
  5772. this._options = options;
  5773. this.setLatLngs(latlngs);
  5774. },
  5775.  
  5776. setLatLngs: function (latlngs) {
  5777. var i = 0,
  5778. len = latlngs.length;
  5779.  
  5780. this.eachLayer(function (layer) {
  5781. if (i < len) {
  5782. layer.setLatLngs(latlngs[i++]);
  5783. } else {
  5784. this.removeLayer(layer);
  5785. }
  5786. }, this);
  5787.  
  5788. while (i < len) {
  5789. this.addLayer(new Klass(latlngs[i++], this._options));
  5790. }
  5791.  
  5792. return this;
  5793. },
  5794.  
  5795. getLatLngs: function () {
  5796. var latlngs = [];
  5797.  
  5798. this.eachLayer(function (layer) {
  5799. latlngs.push(layer.getLatLngs());
  5800. });
  5801.  
  5802. return latlngs;
  5803. }
  5804. });
  5805. }
  5806.  
  5807. L.MultiPolyline = createMulti(L.Polyline);
  5808. L.MultiPolygon = createMulti(L.Polygon);
  5809.  
  5810. L.multiPolyline = function (latlngs, options) {
  5811. return new L.MultiPolyline(latlngs, options);
  5812. };
  5813.  
  5814. L.multiPolygon = function (latlngs, options) {
  5815. return new L.MultiPolygon(latlngs, options);
  5816. };
  5817. }());
  5818.  
  5819.  
  5820. /*
  5821. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  5822. */
  5823.  
  5824. L.Rectangle = L.Polygon.extend({
  5825. initialize: function (latLngBounds, options) {
  5826. L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  5827. },
  5828.  
  5829. setBounds: function (latLngBounds) {
  5830. this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  5831. },
  5832.  
  5833. _boundsToLatLngs: function (latLngBounds) {
  5834. latLngBounds = L.latLngBounds(latLngBounds);
  5835. return [
  5836. latLngBounds.getSouthWest(),
  5837. latLngBounds.getNorthWest(),
  5838. latLngBounds.getNorthEast(),
  5839. latLngBounds.getSouthEast()
  5840. ];
  5841. }
  5842. });
  5843.  
  5844. L.rectangle = function (latLngBounds, options) {
  5845. return new L.Rectangle(latLngBounds, options);
  5846. };
  5847.  
  5848.  
  5849. /*
  5850. * L.Circle is a circle overlay (with a certain radius in meters).
  5851. */
  5852.  
  5853. L.Circle = L.Path.extend({
  5854. initialize: function (latlng, radius, options) {
  5855. L.Path.prototype.initialize.call(this, options);
  5856.  
  5857. this._latlng = L.latLng(latlng);
  5858. this._mRadius = radius;
  5859. },
  5860.  
  5861. options: {
  5862. fill: true
  5863. },
  5864.  
  5865. setLatLng: function (latlng) {
  5866. this._latlng = L.latLng(latlng);
  5867. return this.redraw();
  5868. },
  5869.  
  5870. setRadius: function (radius) {
  5871. this._mRadius = radius;
  5872. return this.redraw();
  5873. },
  5874.  
  5875. projectLatlngs: function () {
  5876. var lngRadius = this._getLngRadius(),
  5877. latlng = this._latlng,
  5878. pointLeft = this._map.latLngToLayerPoint([latlng.lat, latlng.lng - lngRadius]);
  5879.  
  5880. this._point = this._map.latLngToLayerPoint(latlng);
  5881. this._radius = Math.max(this._point.x - pointLeft.x, 1);
  5882. },
  5883.  
  5884. getBounds: function () {
  5885. var lngRadius = this._getLngRadius(),
  5886. latRadius = (this._mRadius / 40075017) * 360,
  5887. latlng = this._latlng;
  5888.  
  5889. return new L.LatLngBounds(
  5890. [latlng.lat - latRadius, latlng.lng - lngRadius],
  5891. [latlng.lat + latRadius, latlng.lng + lngRadius]);
  5892. },
  5893.  
  5894. getLatLng: function () {
  5895. return this._latlng;
  5896. },
  5897.  
  5898. getPathString: function () {
  5899. var p = this._point,
  5900. r = this._radius;
  5901.  
  5902. if (this._checkIfEmpty()) {
  5903. return '';
  5904. }
  5905.  
  5906. if (L.Browser.svg) {
  5907. return 'M' + p.x + ',' + (p.y - r) +
  5908. 'A' + r + ',' + r + ',0,1,1,' +
  5909. (p.x - 0.1) + ',' + (p.y - r) + ' z';
  5910. } else {
  5911. p._round();
  5912. r = Math.round(r);
  5913. return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360);
  5914. }
  5915. },
  5916.  
  5917. getRadius: function () {
  5918. return this._mRadius;
  5919. },
  5920.  
  5921. // TODO Earth hardcoded, move into projection code!
  5922.  
  5923. _getLatRadius: function () {
  5924. return (this._mRadius / 40075017) * 360;
  5925. },
  5926.  
  5927. _getLngRadius: function () {
  5928. return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
  5929. },
  5930.  
  5931. _checkIfEmpty: function () {
  5932. if (!this._map) {
  5933. return false;
  5934. }
  5935. var vp = this._map._pathViewport,
  5936. r = this._radius,
  5937. p = this._point;
  5938.  
  5939. return p.x - r > vp.max.x || p.y - r > vp.max.y ||
  5940. p.x + r < vp.min.x || p.y + r < vp.min.y;
  5941. }
  5942. });
  5943.  
  5944. L.circle = function (latlng, radius, options) {
  5945. return new L.Circle(latlng, radius, options);
  5946. };
  5947.  
  5948.  
  5949. /*
  5950. * L.CircleMarker is a circle overlay with a permanent pixel radius.
  5951. */
  5952.  
  5953. L.CircleMarker = L.Circle.extend({
  5954. options: {
  5955. radius: 10,
  5956. weight: 2
  5957. },
  5958.  
  5959. initialize: function (latlng, options) {
  5960. L.Circle.prototype.initialize.call(this, latlng, null, options);
  5961. this._radius = this.options.radius;
  5962. },
  5963.  
  5964. projectLatlngs: function () {
  5965. this._point = this._map.latLngToLayerPoint(this._latlng);
  5966. },
  5967.  
  5968. _updateStyle : function () {
  5969. L.Circle.prototype._updateStyle.call(this);
  5970. this.setRadius(this.options.radius);
  5971. },
  5972.  
  5973. setLatLng: function (latlng) {
  5974. L.Circle.prototype.setLatLng.call(this, latlng);
  5975. if (this._popup && this._popup._isOpen) {
  5976. this._popup.setLatLng(latlng);
  5977. }
  5978. return this;
  5979. },
  5980.  
  5981. setRadius: function (radius) {
  5982. this.options.radius = this._radius = radius;
  5983. return this.redraw();
  5984. },
  5985.  
  5986. getRadius: function () {
  5987. return this._radius;
  5988. }
  5989. });
  5990.  
  5991. L.circleMarker = function (latlng, options) {
  5992. return new L.CircleMarker(latlng, options);
  5993. };
  5994.  
  5995.  
  5996. /*
  5997. * Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines.
  5998. */
  5999.  
  6000. L.Polyline.include(!L.Path.CANVAS ? {} : {
  6001. _containsPoint: function (p, closed) {
  6002. var i, j, k, len, len2, dist, part,
  6003. w = this.options.weight / 2;
  6004.  
  6005. if (L.Browser.touch) {
  6006. w += 10; // polyline click tolerance on touch devices
  6007. }
  6008.  
  6009. for (i = 0, len = this._parts.length; i < len; i++) {
  6010. part = this._parts[i];
  6011. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6012. if (!closed && (j === 0)) {
  6013. continue;
  6014. }
  6015.  
  6016. dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
  6017.  
  6018. if (dist <= w) {
  6019. return true;
  6020. }
  6021. }
  6022. }
  6023. return false;
  6024. }
  6025. });
  6026.  
  6027.  
  6028. /*
  6029. * Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons.
  6030. */
  6031.  
  6032. L.Polygon.include(!L.Path.CANVAS ? {} : {
  6033. _containsPoint: function (p) {
  6034. var inside = false,
  6035. part, p1, p2,
  6036. i, j, k,
  6037. len, len2;
  6038.  
  6039. // TODO optimization: check if within bounds first
  6040.  
  6041. if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
  6042. // click on polygon border
  6043. return true;
  6044. }
  6045.  
  6046. // ray casting algorithm for detecting if point is in polygon
  6047.  
  6048. for (i = 0, len = this._parts.length; i < len; i++) {
  6049. part = this._parts[i];
  6050.  
  6051. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6052. p1 = part[j];
  6053. p2 = part[k];
  6054.  
  6055. if (((p1.y > p.y) !== (p2.y > p.y)) &&
  6056. (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
  6057. inside = !inside;
  6058. }
  6059. }
  6060. }
  6061.  
  6062. return inside;
  6063. }
  6064. });
  6065.  
  6066.  
  6067. /*
  6068. * Extends L.Circle with Canvas-specific code.
  6069. */
  6070.  
  6071. L.Circle.include(!L.Path.CANVAS ? {} : {
  6072. _drawPath: function () {
  6073. var p = this._point;
  6074. this._ctx.beginPath();
  6075. this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
  6076. },
  6077.  
  6078. _containsPoint: function (p) {
  6079. var center = this._point,
  6080. w2 = this.options.stroke ? this.options.weight / 2 : 0;
  6081.  
  6082. return (p.distanceTo(center) <= this._radius + w2);
  6083. }
  6084. });
  6085.  
  6086.  
  6087. /*
  6088. * CircleMarker canvas specific drawing parts.
  6089. */
  6090.  
  6091. L.CircleMarker.include(!L.Path.CANVAS ? {} : {
  6092. _updateStyle: function () {
  6093. L.Path.prototype._updateStyle.call(this);
  6094. }
  6095. });
  6096.  
  6097.  
  6098. /*
  6099. * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
  6100. */
  6101.  
  6102. L.GeoJSON = L.FeatureGroup.extend({
  6103.  
  6104. initialize: function (geojson, options) {
  6105. L.setOptions(this, options);
  6106.  
  6107. this._layers = {};
  6108.  
  6109. if (geojson) {
  6110. this.addData(geojson);
  6111. }
  6112. },
  6113.  
  6114. addData: function (geojson) {
  6115. var features = L.Util.isArray(geojson) ? geojson : geojson.features,
  6116. i, len, feature;
  6117.  
  6118. if (features) {
  6119. for (i = 0, len = features.length; i < len; i++) {
  6120. // Only add this if geometry or geometries are set and not null
  6121. feature = features[i];
  6122. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  6123. this.addData(features[i]);
  6124. }
  6125. }
  6126. return this;
  6127. }
  6128.  
  6129. var options = this.options;
  6130.  
  6131. if (options.filter && !options.filter(geojson)) { return; }
  6132.  
  6133. var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer, options.coordsToLatLng, options);
  6134. layer.feature = L.GeoJSON.asFeature(geojson);
  6135.  
  6136. layer.defaultOptions = layer.options;
  6137. this.resetStyle(layer);
  6138.  
  6139. if (options.onEachFeature) {
  6140. options.onEachFeature(geojson, layer);
  6141. }
  6142.  
  6143. return this.addLayer(layer);
  6144. },
  6145.  
  6146. resetStyle: function (layer) {
  6147. var style = this.options.style;
  6148. if (style) {
  6149. // reset any custom styles
  6150. L.Util.extend(layer.options, layer.defaultOptions);
  6151.  
  6152. this._setLayerStyle(layer, style);
  6153. }
  6154. },
  6155.  
  6156. setStyle: function (style) {
  6157. this.eachLayer(function (layer) {
  6158. this._setLayerStyle(layer, style);
  6159. }, this);
  6160. },
  6161.  
  6162. _setLayerStyle: function (layer, style) {
  6163. if (typeof style === 'function') {
  6164. style = style(layer.feature);
  6165. }
  6166. if (layer.setStyle) {
  6167. layer.setStyle(style);
  6168. }
  6169. }
  6170. });
  6171.  
  6172. L.extend(L.GeoJSON, {
  6173. geometryToLayer: function (geojson, pointToLayer, coordsToLatLng, vectorOptions) {
  6174. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  6175. coords = geometry.coordinates,
  6176. layers = [],
  6177. latlng, latlngs, i, len;
  6178.  
  6179. coordsToLatLng = coordsToLatLng || this.coordsToLatLng;
  6180.  
  6181. switch (geometry.type) {
  6182. case 'Point':
  6183. latlng = coordsToLatLng(coords);
  6184. return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
  6185.  
  6186. case 'MultiPoint':
  6187. for (i = 0, len = coords.length; i < len; i++) {
  6188. latlng = coordsToLatLng(coords[i]);
  6189. layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng));
  6190. }
  6191. return new L.FeatureGroup(layers);
  6192.  
  6193. case 'LineString':
  6194. latlngs = this.coordsToLatLngs(coords, 0, coordsToLatLng);
  6195. return new L.Polyline(latlngs, vectorOptions);
  6196.  
  6197. case 'Polygon':
  6198. if (coords.length === 2 && !coords[1].length) {
  6199. throw new Error('Invalid GeoJSON object.');
  6200. }
  6201. latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
  6202. return new L.Polygon(latlngs, vectorOptions);
  6203.  
  6204. case 'MultiLineString':
  6205. latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
  6206. return new L.MultiPolyline(latlngs, vectorOptions);
  6207.  
  6208. case 'MultiPolygon':
  6209. latlngs = this.coordsToLatLngs(coords, 2, coordsToLatLng);
  6210. return new L.MultiPolygon(latlngs, vectorOptions);
  6211.  
  6212. case 'GeometryCollection':
  6213. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  6214.  
  6215. layers.push(this.geometryToLayer({
  6216. geometry: geometry.geometries[i],
  6217. type: 'Feature',
  6218. properties: geojson.properties
  6219. }, pointToLayer, coordsToLatLng, vectorOptions));
  6220. }
  6221. return new L.FeatureGroup(layers);
  6222.  
  6223. default:
  6224. throw new Error('Invalid GeoJSON object.');
  6225. }
  6226. },
  6227.  
  6228. coordsToLatLng: function (coords) { // (Array[, Boolean]) -> LatLng
  6229. return new L.LatLng(coords[1], coords[0], coords[2]);
  6230. },
  6231.  
  6232. coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { // (Array[, Number, Function]) -> Array
  6233. var latlng, i, len,
  6234. latlngs = [];
  6235.  
  6236. for (i = 0, len = coords.length; i < len; i++) {
  6237. latlng = levelsDeep ?
  6238. this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
  6239. (coordsToLatLng || this.coordsToLatLng)(coords[i]);
  6240.  
  6241. latlngs.push(latlng);
  6242. }
  6243.  
  6244. return latlngs;
  6245. },
  6246.  
  6247. latLngToCoords: function (latlng) {
  6248. var coords = [latlng.lng, latlng.lat];
  6249.  
  6250. if (latlng.alt !== undefined) {
  6251. coords.push(latlng.alt);
  6252. }
  6253. return coords;
  6254. },
  6255.  
  6256. latLngsToCoords: function (latLngs) {
  6257. var coords = [];
  6258.  
  6259. for (var i = 0, len = latLngs.length; i < len; i++) {
  6260. coords.push(L.GeoJSON.latLngToCoords(latLngs[i]));
  6261. }
  6262.  
  6263. return coords;
  6264. },
  6265.  
  6266. getFeature: function (layer, newGeometry) {
  6267. return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry);
  6268. },
  6269.  
  6270. asFeature: function (geoJSON) {
  6271. if (geoJSON.type === 'Feature') {
  6272. return geoJSON;
  6273. }
  6274.  
  6275. return {
  6276. type: 'Feature',
  6277. properties: {},
  6278. geometry: geoJSON
  6279. };
  6280. }
  6281. });
  6282.  
  6283. var PointToGeoJSON = {
  6284. toGeoJSON: function () {
  6285. return L.GeoJSON.getFeature(this, {
  6286. type: 'Point',
  6287. coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
  6288. });
  6289. }
  6290. };
  6291.  
  6292. L.Marker.include(PointToGeoJSON);
  6293. L.Circle.include(PointToGeoJSON);
  6294. L.CircleMarker.include(PointToGeoJSON);
  6295.  
  6296. L.Polyline.include({
  6297. toGeoJSON: function () {
  6298. return L.GeoJSON.getFeature(this, {
  6299. type: 'LineString',
  6300. coordinates: L.GeoJSON.latLngsToCoords(this.getLatLngs())
  6301. });
  6302. }
  6303. });
  6304.  
  6305. L.Polygon.include({
  6306. toGeoJSON: function () {
  6307. var coords = [L.GeoJSON.latLngsToCoords(this.getLatLngs())],
  6308. i, len, hole;
  6309.  
  6310. coords[0].push(coords[0][0]);
  6311.  
  6312. if (this._holes) {
  6313. for (i = 0, len = this._holes.length; i < len; i++) {
  6314. hole = L.GeoJSON.latLngsToCoords(this._holes[i]);
  6315. hole.push(hole[0]);
  6316. coords.push(hole);
  6317. }
  6318. }
  6319.  
  6320. return L.GeoJSON.getFeature(this, {
  6321. type: 'Polygon',
  6322. coordinates: coords
  6323. });
  6324. }
  6325. });
  6326.  
  6327. (function () {
  6328. function multiToGeoJSON(type) {
  6329. return function () {
  6330. var coords = [];
  6331.  
  6332. this.eachLayer(function (layer) {
  6333. coords.push(layer.toGeoJSON().geometry.coordinates);
  6334. });
  6335.  
  6336. return L.GeoJSON.getFeature(this, {
  6337. type: type,
  6338. coordinates: coords
  6339. });
  6340. };
  6341. }
  6342.  
  6343. L.MultiPolyline.include({toGeoJSON: multiToGeoJSON('MultiLineString')});
  6344. L.MultiPolygon.include({toGeoJSON: multiToGeoJSON('MultiPolygon')});
  6345.  
  6346. L.LayerGroup.include({
  6347. toGeoJSON: function () {
  6348.  
  6349. var geometry = this.feature && this.feature.geometry,
  6350. jsons = [],
  6351. json;
  6352.  
  6353. if (geometry && geometry.type === 'MultiPoint') {
  6354. return multiToGeoJSON('MultiPoint').call(this);
  6355. }
  6356.  
  6357. var isGeometryCollection = geometry && geometry.type === 'GeometryCollection';
  6358.  
  6359. this.eachLayer(function (layer) {
  6360. if (layer.toGeoJSON) {
  6361. json = layer.toGeoJSON();
  6362. jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json));
  6363. }
  6364. });
  6365.  
  6366. if (isGeometryCollection) {
  6367. return L.GeoJSON.getFeature(this, {
  6368. geometries: jsons,
  6369. type: 'GeometryCollection'
  6370. });
  6371. }
  6372.  
  6373. return {
  6374. type: 'FeatureCollection',
  6375. features: jsons
  6376. };
  6377. }
  6378. });
  6379. }());
  6380.  
  6381. L.geoJson = function (geojson, options) {
  6382. return new L.GeoJSON(geojson, options);
  6383. };
  6384.  
  6385.  
  6386. /*
  6387. * L.DomEvent contains functions for working with DOM events.
  6388. */
  6389.  
  6390. L.DomEvent = {
  6391. /* inspired by John Resig, Dean Edwards and YUI addEvent implementations */
  6392. addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
  6393.  
  6394. var id = L.stamp(fn),
  6395. key = '_leaflet_' + type + id,
  6396. handler, originalHandler, newType;
  6397.  
  6398. if (obj[key]) { return this; }
  6399.  
  6400. handler = function (e) {
  6401. return fn.call(context || obj, e || L.DomEvent._getEvent());
  6402. };
  6403.  
  6404. if (L.Browser.pointer && type.indexOf('touch') === 0) {
  6405. return this.addPointerListener(obj, type, handler, id);
  6406. }
  6407. if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
  6408. this.addDoubleTapListener(obj, handler, id);
  6409. }
  6410.  
  6411. if ('addEventListener' in obj) {
  6412.  
  6413. if (type === 'mousewheel') {
  6414. obj.addEventListener('DOMMouseScroll', handler, false);
  6415. obj.addEventListener(type, handler, false);
  6416.  
  6417. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  6418.  
  6419. originalHandler = handler;
  6420. newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
  6421.  
  6422. handler = function (e) {
  6423. if (!L.DomEvent._checkMouse(obj, e)) { return; }
  6424. return originalHandler(e);
  6425. };
  6426.  
  6427. obj.addEventListener(newType, handler, false);
  6428.  
  6429. } else if (type === 'click' && L.Browser.android) {
  6430. originalHandler = handler;
  6431. handler = function (e) {
  6432. return L.DomEvent._filterClick(e, originalHandler);
  6433. };
  6434.  
  6435. obj.addEventListener(type, handler, false);
  6436. } else {
  6437. obj.addEventListener(type, handler, false);
  6438. }
  6439.  
  6440. } else if ('attachEvent' in obj) {
  6441. obj.attachEvent('on' + type, handler);
  6442. }
  6443.  
  6444. obj[key] = handler;
  6445.  
  6446. return this;
  6447. },
  6448.  
  6449. removeListener: function (obj, type, fn) { // (HTMLElement, String, Function)
  6450.  
  6451. var id = L.stamp(fn),
  6452. key = '_leaflet_' + type + id,
  6453. handler = obj[key];
  6454.  
  6455. if (!handler) { return this; }
  6456.  
  6457. if (L.Browser.pointer && type.indexOf('touch') === 0) {
  6458. this.removePointerListener(obj, type, id);
  6459. } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
  6460. this.removeDoubleTapListener(obj, id);
  6461.  
  6462. } else if ('removeEventListener' in obj) {
  6463.  
  6464. if (type === 'mousewheel') {
  6465. obj.removeEventListener('DOMMouseScroll', handler, false);
  6466. obj.removeEventListener(type, handler, false);
  6467.  
  6468. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  6469. obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
  6470. } else {
  6471. obj.removeEventListener(type, handler, false);
  6472. }
  6473. } else if ('detachEvent' in obj) {
  6474. obj.detachEvent('on' + type, handler);
  6475. }
  6476.  
  6477. obj[key] = null;
  6478.  
  6479. return this;
  6480. },
  6481.  
  6482. stopPropagation: function (e) {
  6483.  
  6484. if (e.stopPropagation) {
  6485. e.stopPropagation();
  6486. } else {
  6487. e.cancelBubble = true;
  6488. }
  6489. L.DomEvent._skipped(e);
  6490.  
  6491. return this;
  6492. },
  6493.  
  6494. disableScrollPropagation: function (el) {
  6495. var stop = L.DomEvent.stopPropagation;
  6496.  
  6497. return L.DomEvent
  6498. .on(el, 'mousewheel', stop)
  6499. .on(el, 'MozMousePixelScroll', stop);
  6500. },
  6501.  
  6502. disableClickPropagation: function (el) {
  6503. var stop = L.DomEvent.stopPropagation;
  6504.  
  6505. for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
  6506. L.DomEvent.on(el, L.Draggable.START[i], stop);
  6507. }
  6508.  
  6509. return L.DomEvent
  6510. .on(el, 'click', L.DomEvent._fakeStop)
  6511. .on(el, 'dblclick', stop);
  6512. },
  6513.  
  6514. preventDefault: function (e) {
  6515.  
  6516. if (e.preventDefault) {
  6517. e.preventDefault();
  6518. } else {
  6519. e.returnValue = false;
  6520. }
  6521. return this;
  6522. },
  6523.  
  6524. stop: function (e) {
  6525. return L.DomEvent
  6526. .preventDefault(e)
  6527. .stopPropagation(e);
  6528. },
  6529.  
  6530. getMousePosition: function (e, container) {
  6531. if (!container) {
  6532. return new L.Point(e.clientX, e.clientY);
  6533. }
  6534.  
  6535. var rect = container.getBoundingClientRect();
  6536.  
  6537. return new L.Point(
  6538. e.clientX - rect.left - container.clientLeft,
  6539. e.clientY - rect.top - container.clientTop);
  6540. },
  6541.  
  6542. getWheelDelta: function (e) {
  6543.  
  6544. var delta = 0;
  6545.  
  6546. if (e.wheelDelta) {
  6547. delta = e.wheelDelta / 120;
  6548. }
  6549. if (e.detail) {
  6550. delta = -e.detail / 3;
  6551. }
  6552. return delta;
  6553. },
  6554.  
  6555. _skipEvents: {},
  6556.  
  6557. _fakeStop: function (e) {
  6558. // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e)
  6559. L.DomEvent._skipEvents[e.type] = true;
  6560. },
  6561.  
  6562. _skipped: function (e) {
  6563. var skipped = this._skipEvents[e.type];
  6564. // reset when checking, as it's only used in map container and propagates outside of the map
  6565. this._skipEvents[e.type] = false;
  6566. return skipped;
  6567. },
  6568.  
  6569. // check if element really left/entered the event target (for mouseenter/mouseleave)
  6570. _checkMouse: function (el, e) {
  6571.  
  6572. var related = e.relatedTarget;
  6573.  
  6574. if (!related) { return true; }
  6575.  
  6576. try {
  6577. while (related && (related !== el)) {
  6578. related = related.parentNode;
  6579. }
  6580. } catch (err) {
  6581. return false;
  6582. }
  6583. return (related !== el);
  6584. },
  6585.  
  6586. _getEvent: function () { // evil magic for IE
  6587. /*jshint noarg:false */
  6588. var e = window.event;
  6589. if (!e) {
  6590. var caller = arguments.callee.caller;
  6591. while (caller) {
  6592. e = caller['arguments'][0];
  6593. if (e && window.Event === e.constructor) {
  6594. break;
  6595. }
  6596. caller = caller.caller;
  6597. }
  6598. }
  6599. return e;
  6600. },
  6601.  
  6602. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  6603. _filterClick: function (e, handler) {
  6604. var timeStamp = (e.timeStamp || e.originalEvent.timeStamp),
  6605. elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
  6606.  
  6607. // are they closer together than 500ms yet more than 100ms?
  6608. // Android typically triggers them ~300ms apart while multiple listeners
  6609. // on the same event should be triggered far faster;
  6610. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  6611.  
  6612. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  6613. L.DomEvent.stop(e);
  6614. return;
  6615. }
  6616. L.DomEvent._lastClick = timeStamp;
  6617.  
  6618. return handler(e);
  6619. }
  6620. };
  6621.  
  6622. L.DomEvent.on = L.DomEvent.addListener;
  6623. L.DomEvent.off = L.DomEvent.removeListener;
  6624.  
  6625.  
  6626. /*
  6627. * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
  6628. */
  6629.  
  6630. L.Draggable = L.Class.extend({
  6631. includes: L.Mixin.Events,
  6632.  
  6633. statics: {
  6634. START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
  6635. END: {
  6636. mousedown: 'mouseup',
  6637. touchstart: 'touchend',
  6638. pointerdown: 'touchend',
  6639. MSPointerDown: 'touchend'
  6640. },
  6641. MOVE: {
  6642. mousedown: 'mousemove',
  6643. touchstart: 'touchmove',
  6644. pointerdown: 'touchmove',
  6645. MSPointerDown: 'touchmove'
  6646. }
  6647. },
  6648.  
  6649. initialize: function (element, dragStartTarget) {
  6650. this._element = element;
  6651. this._dragStartTarget = dragStartTarget || element;
  6652. },
  6653.  
  6654. enable: function () {
  6655. if (this._enabled) { return; }
  6656.  
  6657. for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
  6658. L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
  6659. }
  6660.  
  6661. this._enabled = true;
  6662. },
  6663.  
  6664. disable: function () {
  6665. if (!this._enabled) { return; }
  6666.  
  6667. for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
  6668. L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
  6669. }
  6670.  
  6671. this._enabled = false;
  6672. this._moved = false;
  6673. },
  6674.  
  6675. _onDown: function (e) {
  6676. this._moved = false;
  6677.  
  6678. if (e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  6679.  
  6680. L.DomEvent.stopPropagation(e);
  6681.  
  6682. if (L.Draggable._disabled) { return; }
  6683.  
  6684. L.DomUtil.disableImageDrag();
  6685. L.DomUtil.disableTextSelection();
  6686.  
  6687. if (this._moving) { return; }
  6688.  
  6689. var first = e.touches ? e.touches[0] : e;
  6690.  
  6691. this._startPoint = new L.Point(first.clientX, first.clientY);
  6692. this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
  6693.  
  6694. L.DomEvent
  6695. .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
  6696. .on(document, L.Draggable.END[e.type], this._onUp, this);
  6697. },
  6698.  
  6699. _onMove: function (e) {
  6700. if (e.touches && e.touches.length > 1) {
  6701. this._moved = true;
  6702. return;
  6703. }
  6704.  
  6705. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  6706. newPoint = new L.Point(first.clientX, first.clientY),
  6707. offset = newPoint.subtract(this._startPoint);
  6708.  
  6709. if (!offset.x && !offset.y) { return; }
  6710. if (L.Browser.touch && Math.abs(offset.x) + Math.abs(offset.y) < 3) { return; }
  6711.  
  6712. L.DomEvent.preventDefault(e);
  6713.  
  6714. if (!this._moved) {
  6715. this.fire('dragstart');
  6716.  
  6717. this._moved = true;
  6718. this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
  6719.  
  6720. L.DomUtil.addClass(document.body, 'leaflet-dragging');
  6721. this._lastTarget = e.target || e.srcElement;
  6722. L.DomUtil.addClass(this._lastTarget, 'leaflet-drag-target');
  6723. }
  6724.  
  6725. this._newPos = this._startPos.add(offset);
  6726. this._moving = true;
  6727.  
  6728. L.Util.cancelAnimFrame(this._animRequest);
  6729. this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
  6730. },
  6731.  
  6732. _updatePosition: function () {
  6733. this.fire('predrag');
  6734. L.DomUtil.setPosition(this._element, this._newPos);
  6735. this.fire('drag');
  6736. },
  6737.  
  6738. _onUp: function () {
  6739. L.DomUtil.removeClass(document.body, 'leaflet-dragging');
  6740.  
  6741. if (this._lastTarget) {
  6742. L.DomUtil.removeClass(this._lastTarget, 'leaflet-drag-target');
  6743. this._lastTarget = null;
  6744. }
  6745.  
  6746. for (var i in L.Draggable.MOVE) {
  6747. L.DomEvent
  6748. .off(document, L.Draggable.MOVE[i], this._onMove)
  6749. .off(document, L.Draggable.END[i], this._onUp);
  6750. }
  6751.  
  6752. L.DomUtil.enableImageDrag();
  6753. L.DomUtil.enableTextSelection();
  6754.  
  6755. if (this._moved && this._moving) {
  6756. // ensure drag is not fired after dragend
  6757. L.Util.cancelAnimFrame(this._animRequest);
  6758.  
  6759. this.fire('dragend', {
  6760. distance: this._newPos.distanceTo(this._startPos)
  6761. });
  6762. }
  6763.  
  6764. this._moving = false;
  6765. }
  6766. });
  6767.  
  6768.  
  6769. /*
  6770. L.Handler is a base class for handler classes that are used internally to inject
  6771. interaction features like dragging to classes like Map and Marker.
  6772. */
  6773.  
  6774. L.Handler = L.Class.extend({
  6775. initialize: function (map) {
  6776. this._map = map;
  6777. },
  6778.  
  6779. enable: function () {
  6780. if (this._enabled) { return; }
  6781.  
  6782. this._enabled = true;
  6783. this.addHooks();
  6784. },
  6785.  
  6786. disable: function () {
  6787. if (!this._enabled) { return; }
  6788.  
  6789. this._enabled = false;
  6790. this.removeHooks();
  6791. },
  6792.  
  6793. enabled: function () {
  6794. return !!this._enabled;
  6795. }
  6796. });
  6797.  
  6798.  
  6799. /*
  6800. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  6801. */
  6802.  
  6803. L.Map.mergeOptions({
  6804. dragging: true,
  6805.  
  6806. inertia: !L.Browser.android23,
  6807. inertiaDeceleration: 3400, // px/s^2
  6808. inertiaMaxSpeed: Infinity, // px/s
  6809. inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
  6810. easeLinearity: 0.25,
  6811.  
  6812. // TODO refactor, move to CRS
  6813. worldCopyJump: false
  6814. });
  6815.  
  6816. L.Map.Drag = L.Handler.extend({
  6817. addHooks: function () {
  6818. if (!this._draggable) {
  6819. var map = this._map;
  6820.  
  6821. this._draggable = new L.Draggable(map._mapPane, map._container);
  6822.  
  6823. this._draggable.on({
  6824. 'dragstart': this._onDragStart,
  6825. 'drag': this._onDrag,
  6826. 'dragend': this._onDragEnd
  6827. }, this);
  6828.  
  6829. if (map.options.worldCopyJump) {
  6830. this._draggable.on('predrag', this._onPreDrag, this);
  6831. map.on('viewreset', this._onViewReset, this);
  6832.  
  6833. map.whenReady(this._onViewReset, this);
  6834. }
  6835. }
  6836. this._draggable.enable();
  6837. },
  6838.  
  6839. removeHooks: function () {
  6840. this._draggable.disable();
  6841. },
  6842.  
  6843. moved: function () {
  6844. return this._draggable && this._draggable._moved;
  6845. },
  6846.  
  6847. _onDragStart: function () {
  6848. var map = this._map;
  6849.  
  6850. if (map._panAnim) {
  6851. map._panAnim.stop();
  6852. }
  6853.  
  6854. map
  6855. .fire('movestart')
  6856. .fire('dragstart');
  6857.  
  6858. if (map.options.inertia) {
  6859. this._positions = [];
  6860. this._times = [];
  6861. }
  6862. },
  6863.  
  6864. _onDrag: function () {
  6865. if (this._map.options.inertia) {
  6866. var time = this._lastTime = +new Date(),
  6867. pos = this._lastPos = this._draggable._newPos;
  6868.  
  6869. this._positions.push(pos);
  6870. this._times.push(time);
  6871.  
  6872. if (time - this._times[0] > 200) {
  6873. this._positions.shift();
  6874. this._times.shift();
  6875. }
  6876. }
  6877.  
  6878. this._map
  6879. .fire('move')
  6880. .fire('drag');
  6881. },
  6882.  
  6883. _onViewReset: function () {
  6884. // TODO fix hardcoded Earth values
  6885. var pxCenter = this._map.getSize()._divideBy(2),
  6886. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  6887.  
  6888. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  6889. this._worldWidth = this._map.project([0, 180]).x;
  6890. },
  6891.  
  6892. _onPreDrag: function () {
  6893. // TODO refactor to be able to adjust map pane position after zoom
  6894. var worldWidth = this._worldWidth,
  6895. halfWidth = Math.round(worldWidth / 2),
  6896. dx = this._initialWorldOffset,
  6897. x = this._draggable._newPos.x,
  6898. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  6899. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  6900. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  6901.  
  6902. this._draggable._newPos.x = newX;
  6903. },
  6904.  
  6905. _onDragEnd: function (e) {
  6906. var map = this._map,
  6907. options = map.options,
  6908. delay = +new Date() - this._lastTime,
  6909.  
  6910. noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];
  6911.  
  6912. map.fire('dragend', e);
  6913.  
  6914. if (noInertia) {
  6915. map.fire('moveend');
  6916.  
  6917. } else {
  6918.  
  6919. var direction = this._lastPos.subtract(this._positions[0]),
  6920. duration = (this._lastTime + delay - this._times[0]) / 1000,
  6921. ease = options.easeLinearity,
  6922.  
  6923. speedVector = direction.multiplyBy(ease / duration),
  6924. speed = speedVector.distanceTo([0, 0]),
  6925.  
  6926. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  6927. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  6928.  
  6929. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  6930. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  6931.  
  6932. if (!offset.x || !offset.y) {
  6933. map.fire('moveend');
  6934.  
  6935. } else {
  6936. offset = map._limitOffset(offset, map.options.maxBounds);
  6937.  
  6938. L.Util.requestAnimFrame(function () {
  6939. map.panBy(offset, {
  6940. duration: decelerationDuration,
  6941. easeLinearity: ease,
  6942. noMoveStart: true
  6943. });
  6944. });
  6945. }
  6946. }
  6947. }
  6948. });
  6949.  
  6950. L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
  6951.  
  6952.  
  6953. /*
  6954. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  6955. */
  6956.  
  6957. L.Map.mergeOptions({
  6958. doubleClickZoom: true
  6959. });
  6960.  
  6961. L.Map.DoubleClickZoom = L.Handler.extend({
  6962. addHooks: function () {
  6963. this._map.on('dblclick', this._onDoubleClick, this);
  6964. },
  6965.  
  6966. removeHooks: function () {
  6967. this._map.off('dblclick', this._onDoubleClick, this);
  6968. },
  6969.  
  6970. _onDoubleClick: function (e) {
  6971. var map = this._map,
  6972. zoom = map.getZoom() + (e.originalEvent.shiftKey ? -1 : 1);
  6973.  
  6974. if (map.options.doubleClickZoom === 'center') {
  6975. map.setZoom(zoom);
  6976. } else {
  6977. map.setZoomAround(e.containerPoint, zoom);
  6978. }
  6979. }
  6980. });
  6981.  
  6982. L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
  6983.  
  6984.  
  6985. /*
  6986. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  6987. */
  6988.  
  6989. L.Map.mergeOptions({
  6990. scrollWheelZoom: true
  6991. });
  6992.  
  6993. L.Map.ScrollWheelZoom = L.Handler.extend({
  6994. addHooks: function () {
  6995. L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  6996. L.DomEvent.on(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
  6997. this._delta = 0;
  6998. },
  6999.  
  7000. removeHooks: function () {
  7001. L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
  7002. L.DomEvent.off(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
  7003. },
  7004.  
  7005. _onWheelScroll: function (e) {
  7006. var delta = L.DomEvent.getWheelDelta(e);
  7007.  
  7008. this._delta += delta;
  7009. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  7010.  
  7011. if (!this._startTime) {
  7012. this._startTime = +new Date();
  7013. }
  7014.  
  7015. var left = Math.max(40 - (+new Date() - this._startTime), 0);
  7016.  
  7017. clearTimeout(this._timer);
  7018. this._timer = setTimeout(L.bind(this._performZoom, this), left);
  7019.  
  7020. L.DomEvent.preventDefault(e);
  7021. L.DomEvent.stopPropagation(e);
  7022. },
  7023.  
  7024. _performZoom: function () {
  7025. var map = this._map,
  7026. delta = this._delta,
  7027. zoom = map.getZoom();
  7028.  
  7029. delta = delta > 0 ? Math.ceil(delta) : Math.floor(delta);
  7030. delta = Math.max(Math.min(delta, 4), -4);
  7031. delta = map._limitZoom(zoom + delta) - zoom;
  7032.  
  7033. this._delta = 0;
  7034. this._startTime = null;
  7035.  
  7036. if (!delta) { return; }
  7037.  
  7038. if (map.options.scrollWheelZoom === 'center') {
  7039. map.setZoom(zoom + delta);
  7040. } else {
  7041. map.setZoomAround(this._lastMousePos, zoom + delta);
  7042. }
  7043. }
  7044. });
  7045.  
  7046. L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
  7047.  
  7048.  
  7049. /*
  7050. * Extends the event handling code with double tap support for mobile browsers.
  7051. */
  7052.  
  7053. L.extend(L.DomEvent, {
  7054.  
  7055. _touchstart: L.Browser.msPointer ? 'MSPointerDown' : L.Browser.pointer ? 'pointerdown' : 'touchstart',
  7056. _touchend: L.Browser.msPointer ? 'MSPointerUp' : L.Browser.pointer ? 'pointerup' : 'touchend',
  7057.  
  7058. // inspired by Zepto touch code by Thomas Fuchs
  7059. addDoubleTapListener: function (obj, handler, id) {
  7060. var last,
  7061. doubleTap = false,
  7062. delay = 250,
  7063. touch,
  7064. pre = '_leaflet_',
  7065. touchstart = this._touchstart,
  7066. touchend = this._touchend,
  7067. trackedTouches = [];
  7068.  
  7069. function onTouchStart(e) {
  7070. var count;
  7071.  
  7072. if (L.Browser.pointer) {
  7073. trackedTouches.push(e.pointerId);
  7074. count = trackedTouches.length;
  7075. } else {
  7076. count = e.touches.length;
  7077. }
  7078. if (count > 1) {
  7079. return;
  7080. }
  7081.  
  7082. var now = Date.now(),
  7083. delta = now - (last || now);
  7084.  
  7085. touch = e.touches ? e.touches[0] : e;
  7086. doubleTap = (delta > 0 && delta <= delay);
  7087. last = now;
  7088. }
  7089.  
  7090. function onTouchEnd(e) {
  7091. if (L.Browser.pointer) {
  7092. var idx = trackedTouches.indexOf(e.pointerId);
  7093. if (idx === -1) {
  7094. return;
  7095. }
  7096. trackedTouches.splice(idx, 1);
  7097. }
  7098.  
  7099. if (doubleTap) {
  7100. if (L.Browser.pointer) {
  7101. // work around .type being readonly with MSPointer* events
  7102. var newTouch = { },
  7103. prop;
  7104.  
  7105. // jshint forin:false
  7106. for (var i in touch) {
  7107. prop = touch[i];
  7108. if (typeof prop === 'function') {
  7109. newTouch[i] = prop.bind(touch);
  7110. } else {
  7111. newTouch[i] = prop;
  7112. }
  7113. }
  7114. touch = newTouch;
  7115. }
  7116. touch.type = 'dblclick';
  7117. handler(touch);
  7118. last = null;
  7119. }
  7120. }
  7121. obj[pre + touchstart + id] = onTouchStart;
  7122. obj[pre + touchend + id] = onTouchEnd;
  7123.  
  7124. // on pointer we need to listen on the document, otherwise a drag starting on the map and moving off screen
  7125. // will not come through to us, so we will lose track of how many touches are ongoing
  7126. var endElement = L.Browser.pointer ? document.documentElement : obj;
  7127.  
  7128. obj.addEventListener(touchstart, onTouchStart, false);
  7129. endElement.addEventListener(touchend, onTouchEnd, false);
  7130.  
  7131. if (L.Browser.pointer) {
  7132. endElement.addEventListener(L.DomEvent.POINTER_CANCEL, onTouchEnd, false);
  7133. }
  7134.  
  7135. return this;
  7136. },
  7137.  
  7138. removeDoubleTapListener: function (obj, id) {
  7139. var pre = '_leaflet_';
  7140.  
  7141. obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false);
  7142. (L.Browser.pointer ? document.documentElement : obj).removeEventListener(
  7143. this._touchend, obj[pre + this._touchend + id], false);
  7144.  
  7145. if (L.Browser.pointer) {
  7146. document.documentElement.removeEventListener(L.DomEvent.POINTER_CANCEL, obj[pre + this._touchend + id],
  7147. false);
  7148. }
  7149.  
  7150. return this;
  7151. }
  7152. });
  7153.  
  7154.  
  7155. /*
  7156. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  7157. */
  7158.  
  7159. L.extend(L.DomEvent, {
  7160.  
  7161. //static
  7162. POINTER_DOWN: L.Browser.msPointer ? 'MSPointerDown' : 'pointerdown',
  7163. POINTER_MOVE: L.Browser.msPointer ? 'MSPointerMove' : 'pointermove',
  7164. POINTER_UP: L.Browser.msPointer ? 'MSPointerUp' : 'pointerup',
  7165. POINTER_CANCEL: L.Browser.msPointer ? 'MSPointerCancel' : 'pointercancel',
  7166.  
  7167. _pointers: [],
  7168. _pointerDocumentListener: false,
  7169.  
  7170. // Provides a touch events wrapper for (ms)pointer events.
  7171. // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019
  7172. //ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  7173.  
  7174. addPointerListener: function (obj, type, handler, id) {
  7175.  
  7176. switch (type) {
  7177. case 'touchstart':
  7178. return this.addPointerListenerStart(obj, type, handler, id);
  7179. case 'touchend':
  7180. return this.addPointerListenerEnd(obj, type, handler, id);
  7181. case 'touchmove':
  7182. return this.addPointerListenerMove(obj, type, handler, id);
  7183. default:
  7184. throw 'Unknown touch event type';
  7185. }
  7186. },
  7187.  
  7188. addPointerListenerStart: function (obj, type, handler, id) {
  7189. var pre = '_leaflet_',
  7190. pointers = this._pointers;
  7191.  
  7192. var cb = function (e) {
  7193.  
  7194. L.DomEvent.preventDefault(e);
  7195.  
  7196. var alreadyInArray = false;
  7197. for (var i = 0; i < pointers.length; i++) {
  7198. if (pointers[i].pointerId === e.pointerId) {
  7199. alreadyInArray = true;
  7200. break;
  7201. }
  7202. }
  7203. if (!alreadyInArray) {
  7204. pointers.push(e);
  7205. }
  7206.  
  7207. e.touches = pointers.slice();
  7208. e.changedTouches = [e];
  7209.  
  7210. handler(e);
  7211. };
  7212.  
  7213. obj[pre + 'touchstart' + id] = cb;
  7214. obj.addEventListener(this.POINTER_DOWN, cb, false);
  7215.  
  7216. // need to also listen for end events to keep the _pointers list accurate
  7217. // this needs to be on the body and never go away
  7218. if (!this._pointerDocumentListener) {
  7219. var internalCb = function (e) {
  7220. for (var i = 0; i < pointers.length; i++) {
  7221. if (pointers[i].pointerId === e.pointerId) {
  7222. pointers.splice(i, 1);
  7223. break;
  7224. }
  7225. }
  7226. };
  7227. //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there
  7228. document.documentElement.addEventListener(this.POINTER_UP, internalCb, false);
  7229. document.documentElement.addEventListener(this.POINTER_CANCEL, internalCb, false);
  7230.  
  7231. this._pointerDocumentListener = true;
  7232. }
  7233.  
  7234. return this;
  7235. },
  7236.  
  7237. addPointerListenerMove: function (obj, type, handler, id) {
  7238. var pre = '_leaflet_',
  7239. touches = this._pointers;
  7240.  
  7241. function cb(e) {
  7242.  
  7243. // don't fire touch moves when mouse isn't down
  7244. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
  7245.  
  7246. for (var i = 0; i < touches.length; i++) {
  7247. if (touches[i].pointerId === e.pointerId) {
  7248. touches[i] = e;
  7249. break;
  7250. }
  7251. }
  7252.  
  7253. e.touches = touches.slice();
  7254. e.changedTouches = [e];
  7255.  
  7256. handler(e);
  7257. }
  7258.  
  7259. obj[pre + 'touchmove' + id] = cb;
  7260. obj.addEventListener(this.POINTER_MOVE, cb, false);
  7261.  
  7262. return this;
  7263. },
  7264.  
  7265. addPointerListenerEnd: function (obj, type, handler, id) {
  7266. var pre = '_leaflet_',
  7267. touches = this._pointers;
  7268.  
  7269. var cb = function (e) {
  7270. for (var i = 0; i < touches.length; i++) {
  7271. if (touches[i].pointerId === e.pointerId) {
  7272. touches.splice(i, 1);
  7273. break;
  7274. }
  7275. }
  7276.  
  7277. e.touches = touches.slice();
  7278. e.changedTouches = [e];
  7279.  
  7280. handler(e);
  7281. };
  7282.  
  7283. obj[pre + 'touchend' + id] = cb;
  7284. obj.addEventListener(this.POINTER_UP, cb, false);
  7285. obj.addEventListener(this.POINTER_CANCEL, cb, false);
  7286.  
  7287. return this;
  7288. },
  7289.  
  7290. removePointerListener: function (obj, type, id) {
  7291. var pre = '_leaflet_',
  7292. cb = obj[pre + type + id];
  7293.  
  7294. switch (type) {
  7295. case 'touchstart':
  7296. obj.removeEventListener(this.POINTER_DOWN, cb, false);
  7297. break;
  7298. case 'touchmove':
  7299. obj.removeEventListener(this.POINTER_MOVE, cb, false);
  7300. break;
  7301. case 'touchend':
  7302. obj.removeEventListener(this.POINTER_UP, cb, false);
  7303. obj.removeEventListener(this.POINTER_CANCEL, cb, false);
  7304. break;
  7305. }
  7306.  
  7307. return this;
  7308. }
  7309. });
  7310.  
  7311.  
  7312. /*
  7313. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  7314. */
  7315.  
  7316. L.Map.mergeOptions({
  7317. touchZoom: L.Browser.touch && !L.Browser.android23,
  7318. bounceAtZoomLimits: true
  7319. });
  7320.  
  7321. L.Map.TouchZoom = L.Handler.extend({
  7322. addHooks: function () {
  7323. L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
  7324. },
  7325.  
  7326. removeHooks: function () {
  7327. L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
  7328. },
  7329.  
  7330. _onTouchStart: function (e) {
  7331. var map = this._map;
  7332.  
  7333. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  7334.  
  7335. var p1 = map.mouseEventToLayerPoint(e.touches[0]),
  7336. p2 = map.mouseEventToLayerPoint(e.touches[1]),
  7337. viewCenter = map._getCenterLayerPoint();
  7338.  
  7339. this._startCenter = p1.add(p2)._divideBy(2);
  7340. this._startDist = p1.distanceTo(p2);
  7341.  
  7342. this._moved = false;
  7343. this._zooming = true;
  7344.  
  7345. this._centerOffset = viewCenter.subtract(this._startCenter);
  7346.  
  7347. if (map._panAnim) {
  7348. map._panAnim.stop();
  7349. }
  7350.  
  7351. L.DomEvent
  7352. .on(document, 'touchmove', this._onTouchMove, this)
  7353. .on(document, 'touchend', this._onTouchEnd, this);
  7354.  
  7355. L.DomEvent.preventDefault(e);
  7356. },
  7357.  
  7358. _onTouchMove: function (e) {
  7359. var map = this._map;
  7360.  
  7361. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  7362.  
  7363. var p1 = map.mouseEventToLayerPoint(e.touches[0]),
  7364. p2 = map.mouseEventToLayerPoint(e.touches[1]);
  7365.  
  7366. this._scale = p1.distanceTo(p2) / this._startDist;
  7367. this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
  7368.  
  7369. if (this._scale === 1) { return; }
  7370.  
  7371. if (!map.options.bounceAtZoomLimits) {
  7372. if ((map.getZoom() === map.getMinZoom() && this._scale < 1) ||
  7373. (map.getZoom() === map.getMaxZoom() && this._scale > 1)) { return; }
  7374. }
  7375.  
  7376. if (!this._moved) {
  7377. L.DomUtil.addClass(map._mapPane, 'leaflet-touching');
  7378.  
  7379. map
  7380. .fire('movestart')
  7381. .fire('zoomstart');
  7382.  
  7383. this._moved = true;
  7384. }
  7385.  
  7386. L.Util.cancelAnimFrame(this._animRequest);
  7387. this._animRequest = L.Util.requestAnimFrame(
  7388. this._updateOnMove, this, true, this._map._container);
  7389.  
  7390. L.DomEvent.preventDefault(e);
  7391. },
  7392.  
  7393. _updateOnMove: function () {
  7394. var map = this._map,
  7395. origin = this._getScaleOrigin(),
  7396. center = map.layerPointToLatLng(origin),
  7397. zoom = map.getScaleZoom(this._scale);
  7398.  
  7399. map._animateZoom(center, zoom, this._startCenter, this._scale, this._delta, false, true);
  7400. },
  7401.  
  7402. _onTouchEnd: function () {
  7403. if (!this._moved || !this._zooming) {
  7404. this._zooming = false;
  7405. return;
  7406. }
  7407.  
  7408. var map = this._map;
  7409.  
  7410. this._zooming = false;
  7411. L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
  7412. L.Util.cancelAnimFrame(this._animRequest);
  7413.  
  7414. L.DomEvent
  7415. .off(document, 'touchmove', this._onTouchMove)
  7416. .off(document, 'touchend', this._onTouchEnd);
  7417.  
  7418. var origin = this._getScaleOrigin(),
  7419. center = map.layerPointToLatLng(origin),
  7420.  
  7421. oldZoom = map.getZoom(),
  7422. floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
  7423. roundZoomDelta = (floatZoomDelta > 0 ?
  7424. Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
  7425.  
  7426. zoom = map._limitZoom(oldZoom + roundZoomDelta),
  7427. scale = map.getZoomScale(zoom) / this._scale;
  7428.  
  7429. map._animateZoom(center, zoom, origin, scale);
  7430. },
  7431.  
  7432. _getScaleOrigin: function () {
  7433. var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
  7434. return this._startCenter.add(centerOffset);
  7435. }
  7436. });
  7437.  
  7438. L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
  7439.  
  7440.  
  7441. /*
  7442. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  7443. */
  7444.  
  7445. L.Map.mergeOptions({
  7446. tap: true,
  7447. tapTolerance: 15
  7448. });
  7449.  
  7450. L.Map.Tap = L.Handler.extend({
  7451. addHooks: function () {
  7452. L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
  7453. },
  7454.  
  7455. removeHooks: function () {
  7456. L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
  7457. },
  7458.  
  7459. _onDown: function (e) {
  7460. if (!e.touches) { return; }
  7461.  
  7462. L.DomEvent.preventDefault(e);
  7463.  
  7464. this._fireClick = true;
  7465.  
  7466. // don't simulate click or track longpress if more than 1 touch
  7467. if (e.touches.length > 1) {
  7468. this._fireClick = false;
  7469. clearTimeout(this._holdTimeout);
  7470. return;
  7471. }
  7472.  
  7473. var first = e.touches[0],
  7474. el = first.target;
  7475.  
  7476. this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
  7477.  
  7478. // if touching a link, highlight it
  7479. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  7480. L.DomUtil.addClass(el, 'leaflet-active');
  7481. }
  7482.  
  7483. // simulate long hold but setting a timeout
  7484. this._holdTimeout = setTimeout(L.bind(function () {
  7485. if (this._isTapValid()) {
  7486. this._fireClick = false;
  7487. this._onUp();
  7488. this._simulateEvent('contextmenu', first);
  7489. }
  7490. }, this), 1000);
  7491.  
  7492. L.DomEvent
  7493. .on(document, 'touchmove', this._onMove, this)
  7494. .on(document, 'touchend', this._onUp, this);
  7495. },
  7496.  
  7497. _onUp: function (e) {
  7498. clearTimeout(this._holdTimeout);
  7499.  
  7500. L.DomEvent
  7501. .off(document, 'touchmove', this._onMove, this)
  7502. .off(document, 'touchend', this._onUp, this);
  7503.  
  7504. if (this._fireClick && e && e.changedTouches) {
  7505.  
  7506. var first = e.changedTouches[0],
  7507. el = first.target;
  7508.  
  7509. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  7510. L.DomUtil.removeClass(el, 'leaflet-active');
  7511. }
  7512.  
  7513. // simulate click if the touch didn't move too much
  7514. if (this._isTapValid()) {
  7515. this._simulateEvent('click', first);
  7516. }
  7517. }
  7518. },
  7519.  
  7520. _isTapValid: function () {
  7521. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  7522. },
  7523.  
  7524. _onMove: function (e) {
  7525. var first = e.touches[0];
  7526. this._newPos = new L.Point(first.clientX, first.clientY);
  7527. },
  7528.  
  7529. _simulateEvent: function (type, e) {
  7530. var simulatedEvent = document.createEvent('MouseEvents');
  7531.  
  7532. simulatedEvent._simulated = true;
  7533. e.target._simulatedClick = true;
  7534.  
  7535. simulatedEvent.initMouseEvent(
  7536. type, true, true, window, 1,
  7537. e.screenX, e.screenY,
  7538. e.clientX, e.clientY,
  7539. false, false, false, false, 0, null);
  7540.  
  7541. e.target.dispatchEvent(simulatedEvent);
  7542. }
  7543. });
  7544.  
  7545. if (L.Browser.touch && !L.Browser.pointer) {
  7546. L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
  7547. }
  7548.  
  7549.  
  7550. /*
  7551. * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map
  7552. * (zoom to a selected bounding box), enabled by default.
  7553. */
  7554.  
  7555. L.Map.mergeOptions({
  7556. boxZoom: true
  7557. });
  7558.  
  7559. L.Map.BoxZoom = L.Handler.extend({
  7560. initialize: function (map) {
  7561. this._map = map;
  7562. this._container = map._container;
  7563. this._pane = map._panes.overlayPane;
  7564. this._moved = false;
  7565. },
  7566.  
  7567. addHooks: function () {
  7568. L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
  7569. },
  7570.  
  7571. removeHooks: function () {
  7572. L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
  7573. this._moved = false;
  7574. },
  7575.  
  7576. moved: function () {
  7577. return this._moved;
  7578. },
  7579.  
  7580. _onMouseDown: function (e) {
  7581. this._moved = false;
  7582.  
  7583. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  7584.  
  7585. L.DomUtil.disableTextSelection();
  7586. L.DomUtil.disableImageDrag();
  7587.  
  7588. this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
  7589.  
  7590. L.DomEvent
  7591. .on(document, 'mousemove', this._onMouseMove, this)
  7592. .on(document, 'mouseup', this._onMouseUp, this)
  7593. .on(document, 'keydown', this._onKeyDown, this);
  7594. },
  7595.  
  7596. _onMouseMove: function (e) {
  7597. if (!this._moved) {
  7598. this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
  7599. L.DomUtil.setPosition(this._box, this._startLayerPoint);
  7600.  
  7601. //TODO refactor: move cursor to styles
  7602. this._container.style.cursor = 'crosshair';
  7603. this._map.fire('boxzoomstart');
  7604. }
  7605.  
  7606. var startPoint = this._startLayerPoint,
  7607. box = this._box,
  7608.  
  7609. layerPoint = this._map.mouseEventToLayerPoint(e),
  7610. offset = layerPoint.subtract(startPoint),
  7611.  
  7612. newPos = new L.Point(
  7613. Math.min(layerPoint.x, startPoint.x),
  7614. Math.min(layerPoint.y, startPoint.y));
  7615.  
  7616. L.DomUtil.setPosition(box, newPos);
  7617.  
  7618. this._moved = true;
  7619.  
  7620. // TODO refactor: remove hardcoded 4 pixels
  7621. box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px';
  7622. box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px';
  7623. },
  7624.  
  7625. _finish: function () {
  7626. if (this._moved) {
  7627. this._pane.removeChild(this._box);
  7628. this._container.style.cursor = '';
  7629. }
  7630.  
  7631. L.DomUtil.enableTextSelection();
  7632. L.DomUtil.enableImageDrag();
  7633.  
  7634. L.DomEvent
  7635. .off(document, 'mousemove', this._onMouseMove)
  7636. .off(document, 'mouseup', this._onMouseUp)
  7637. .off(document, 'keydown', this._onKeyDown);
  7638. },
  7639.  
  7640. _onMouseUp: function (e) {
  7641.  
  7642. this._finish();
  7643.  
  7644. var map = this._map,
  7645. layerPoint = map.mouseEventToLayerPoint(e);
  7646.  
  7647. if (this._startLayerPoint.equals(layerPoint)) { return; }
  7648.  
  7649. var bounds = new L.LatLngBounds(
  7650. map.layerPointToLatLng(this._startLayerPoint),
  7651. map.layerPointToLatLng(layerPoint));
  7652.  
  7653. map.fitBounds(bounds);
  7654.  
  7655. map.fire('boxzoomend', {
  7656. boxZoomBounds: bounds
  7657. });
  7658. },
  7659.  
  7660. _onKeyDown: function (e) {
  7661. if (e.keyCode === 27) {
  7662. this._finish();
  7663. }
  7664. }
  7665. });
  7666.  
  7667. L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
  7668.  
  7669.  
  7670. /*
  7671. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  7672. */
  7673.  
  7674. L.Map.mergeOptions({
  7675. keyboard: true,
  7676. keyboardPanOffset: 80,
  7677. keyboardZoomOffset: 1
  7678. });
  7679.  
  7680. L.Map.Keyboard = L.Handler.extend({
  7681.  
  7682. keyCodes: {
  7683. left: [37],
  7684. right: [39],
  7685. down: [40],
  7686. up: [38],
  7687. zoomIn: [187, 107, 61, 171],
  7688. zoomOut: [189, 109, 173]
  7689. },
  7690.  
  7691. initialize: function (map) {
  7692. this._map = map;
  7693.  
  7694. this._setPanOffset(map.options.keyboardPanOffset);
  7695. this._setZoomOffset(map.options.keyboardZoomOffset);
  7696. },
  7697.  
  7698. addHooks: function () {
  7699. var container = this._map._container;
  7700.  
  7701. // make the container focusable by tabbing
  7702. if (container.tabIndex === -1) {
  7703. container.tabIndex = '0';
  7704. }
  7705.  
  7706. L.DomEvent
  7707. .on(container, 'focus', this._onFocus, this)
  7708. .on(container, 'blur', this._onBlur, this)
  7709. .on(container, 'mousedown', this._onMouseDown, this);
  7710.  
  7711. this._map
  7712. .on('focus', this._addHooks, this)
  7713. .on('blur', this._removeHooks, this);
  7714. },
  7715.  
  7716. removeHooks: function () {
  7717. this._removeHooks();
  7718.  
  7719. var container = this._map._container;
  7720.  
  7721. L.DomEvent
  7722. .off(container, 'focus', this._onFocus, this)
  7723. .off(container, 'blur', this._onBlur, this)
  7724. .off(container, 'mousedown', this._onMouseDown, this);
  7725.  
  7726. this._map
  7727. .off('focus', this._addHooks, this)
  7728. .off('blur', this._removeHooks, this);
  7729. },
  7730.  
  7731. _onMouseDown: function () {
  7732. if (this._focused) { return; }
  7733.  
  7734. var body = document.body,
  7735. docEl = document.documentElement,
  7736. top = body.scrollTop || docEl.scrollTop,
  7737. left = body.scrollLeft || docEl.scrollLeft;
  7738.  
  7739. this._map._container.focus();
  7740.  
  7741. window.scrollTo(left, top);
  7742. },
  7743.  
  7744. _onFocus: function () {
  7745. this._focused = true;
  7746. this._map.fire('focus');
  7747. },
  7748.  
  7749. _onBlur: function () {
  7750. this._focused = false;
  7751. this._map.fire('blur');
  7752. },
  7753.  
  7754. _setPanOffset: function (pan) {
  7755. var keys = this._panKeys = {},
  7756. codes = this.keyCodes,
  7757. i, len;
  7758.  
  7759. for (i = 0, len = codes.left.length; i < len; i++) {
  7760. keys[codes.left[i]] = [-1 * pan, 0];
  7761. }
  7762. for (i = 0, len = codes.right.length; i < len; i++) {
  7763. keys[codes.right[i]] = [pan, 0];
  7764. }
  7765. for (i = 0, len = codes.down.length; i < len; i++) {
  7766. keys[codes.down[i]] = [0, pan];
  7767. }
  7768. for (i = 0, len = codes.up.length; i < len; i++) {
  7769. keys[codes.up[i]] = [0, -1 * pan];
  7770. }
  7771. },
  7772.  
  7773. _setZoomOffset: function (zoom) {
  7774. var keys = this._zoomKeys = {},
  7775. codes = this.keyCodes,
  7776. i, len;
  7777.  
  7778. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  7779. keys[codes.zoomIn[i]] = zoom;
  7780. }
  7781. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  7782. keys[codes.zoomOut[i]] = -zoom;
  7783. }
  7784. },
  7785.  
  7786. _addHooks: function () {
  7787. L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
  7788. },
  7789.  
  7790. _removeHooks: function () {
  7791. L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
  7792. },
  7793.  
  7794. _onKeyDown: function (e) {
  7795. var key = e.keyCode,
  7796. map = this._map;
  7797.  
  7798. if (key in this._panKeys) {
  7799.  
  7800. if (map._panAnim && map._panAnim._inProgress) { return; }
  7801.  
  7802. map.panBy(this._panKeys[key]);
  7803.  
  7804. if (map.options.maxBounds) {
  7805. map.panInsideBounds(map.options.maxBounds);
  7806. }
  7807.  
  7808. } else if (key in this._zoomKeys) {
  7809. map.setZoom(map.getZoom() + this._zoomKeys[key]);
  7810.  
  7811. } else {
  7812. return;
  7813. }
  7814.  
  7815. L.DomEvent.stop(e);
  7816. }
  7817. });
  7818.  
  7819. L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
  7820.  
  7821.  
  7822. /*
  7823. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  7824. */
  7825.  
  7826. L.Handler.MarkerDrag = L.Handler.extend({
  7827. initialize: function (marker) {
  7828. this._marker = marker;
  7829. },
  7830.  
  7831. addHooks: function () {
  7832. var icon = this._marker._icon;
  7833. if (!this._draggable) {
  7834. this._draggable = new L.Draggable(icon, icon);
  7835. }
  7836.  
  7837. this._draggable
  7838. .on('dragstart', this._onDragStart, this)
  7839. .on('drag', this._onDrag, this)
  7840. .on('dragend', this._onDragEnd, this);
  7841. this._draggable.enable();
  7842. L.DomUtil.addClass(this._marker._icon, 'leaflet-marker-draggable');
  7843. },
  7844.  
  7845. removeHooks: function () {
  7846. this._draggable
  7847. .off('dragstart', this._onDragStart, this)
  7848. .off('drag', this._onDrag, this)
  7849. .off('dragend', this._onDragEnd, this);
  7850.  
  7851. this._draggable.disable();
  7852. L.DomUtil.removeClass(this._marker._icon, 'leaflet-marker-draggable');
  7853. },
  7854.  
  7855. moved: function () {
  7856. return this._draggable && this._draggable._moved;
  7857. },
  7858.  
  7859. _onDragStart: function () {
  7860. this._marker
  7861. .closePopup()
  7862. .fire('movestart')
  7863. .fire('dragstart');
  7864. },
  7865.  
  7866. _onDrag: function () {
  7867. var marker = this._marker,
  7868. shadow = marker._shadow,
  7869. iconPos = L.DomUtil.getPosition(marker._icon),
  7870. latlng = marker._map.layerPointToLatLng(iconPos);
  7871.  
  7872. // update shadow position
  7873. if (shadow) {
  7874. L.DomUtil.setPosition(shadow, iconPos);
  7875. }
  7876.  
  7877. marker._latlng = latlng;
  7878.  
  7879. marker
  7880. .fire('move', {latlng: latlng})
  7881. .fire('drag');
  7882. },
  7883.  
  7884. _onDragEnd: function (e) {
  7885. this._marker
  7886. .fire('moveend')
  7887. .fire('dragend', e);
  7888. }
  7889. });
  7890.  
  7891.  
  7892. /*
  7893. * L.Control is a base class for implementing map controls. Handles positioning.
  7894. * All other controls extend from this class.
  7895. */
  7896.  
  7897. L.Control = L.Class.extend({
  7898. options: {
  7899. position: 'topright'
  7900. },
  7901.  
  7902. initialize: function (options) {
  7903. L.setOptions(this, options);
  7904. },
  7905.  
  7906. getPosition: function () {
  7907. return this.options.position;
  7908. },
  7909.  
  7910. setPosition: function (position) {
  7911. var map = this._map;
  7912.  
  7913. if (map) {
  7914. map.removeControl(this);
  7915. }
  7916.  
  7917. this.options.position = position;
  7918.  
  7919. if (map) {
  7920. map.addControl(this);
  7921. }
  7922.  
  7923. return this;
  7924. },
  7925.  
  7926. getContainer: function () {
  7927. return this._container;
  7928. },
  7929.  
  7930. addTo: function (map) {
  7931. this._map = map;
  7932.  
  7933. var container = this._container = this.onAdd(map),
  7934. pos = this.getPosition(),
  7935. corner = map._controlCorners[pos];
  7936.  
  7937. L.DomUtil.addClass(container, 'leaflet-control');
  7938.  
  7939. if (pos.indexOf('bottom') !== -1) {
  7940. corner.insertBefore(container, corner.firstChild);
  7941. } else {
  7942. corner.appendChild(container);
  7943. }
  7944.  
  7945. return this;
  7946. },
  7947.  
  7948. removeFrom: function (map) {
  7949. var pos = this.getPosition(),
  7950. corner = map._controlCorners[pos];
  7951.  
  7952. corner.removeChild(this._container);
  7953. this._map = null;
  7954.  
  7955. if (this.onRemove) {
  7956. this.onRemove(map);
  7957. }
  7958.  
  7959. return this;
  7960. },
  7961.  
  7962. _refocusOnMap: function () {
  7963. if (this._map) {
  7964. this._map.getContainer().focus();
  7965. }
  7966. }
  7967. });
  7968.  
  7969. L.control = function (options) {
  7970. return new L.Control(options);
  7971. };
  7972.  
  7973.  
  7974. // adds control-related methods to L.Map
  7975.  
  7976. L.Map.include({
  7977. addControl: function (control) {
  7978. control.addTo(this);
  7979. return this;
  7980. },
  7981.  
  7982. removeControl: function (control) {
  7983. control.removeFrom(this);
  7984. return this;
  7985. },
  7986.  
  7987. _initControlPos: function () {
  7988. var corners = this._controlCorners = {},
  7989. l = 'leaflet-',
  7990. container = this._controlContainer =
  7991. L.DomUtil.create('div', l + 'control-container', this._container);
  7992.  
  7993. function createCorner(vSide, hSide) {
  7994. var className = l + vSide + ' ' + l + hSide;
  7995.  
  7996. corners[vSide + hSide] = L.DomUtil.create('div', className, container);
  7997. }
  7998.  
  7999. createCorner('top', 'left');
  8000. createCorner('top', 'right');
  8001. createCorner('bottom', 'left');
  8002. createCorner('bottom', 'right');
  8003. },
  8004.  
  8005. _clearControlPos: function () {
  8006. this._container.removeChild(this._controlContainer);
  8007. }
  8008. });
  8009.  
  8010.  
  8011. /*
  8012. * L.Control.Zoom is used for the default zoom buttons on the map.
  8013. */
  8014.  
  8015. L.Control.Zoom = L.Control.extend({
  8016. options: {
  8017. position: 'topleft',
  8018. zoomInText: '+',
  8019. zoomInTitle: 'Zoom in',
  8020. zoomOutText: '-',
  8021. zoomOutTitle: 'Zoom out'
  8022. },
  8023.  
  8024. onAdd: function (map) {
  8025. var zoomName = 'leaflet-control-zoom',
  8026. container = L.DomUtil.create('div', zoomName + ' leaflet-bar');
  8027.  
  8028. this._map = map;
  8029.  
  8030. this._zoomInButton = this._createButton(
  8031. this.options.zoomInText, this.options.zoomInTitle,
  8032. zoomName + '-in', container, this._zoomIn, this);
  8033. this._zoomOutButton = this._createButton(
  8034. this.options.zoomOutText, this.options.zoomOutTitle,
  8035. zoomName + '-out', container, this._zoomOut, this);
  8036.  
  8037. this._updateDisabled();
  8038. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  8039.  
  8040. return container;
  8041. },
  8042.  
  8043. onRemove: function (map) {
  8044. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  8045. },
  8046.  
  8047. _zoomIn: function (e) {
  8048. this._map.zoomIn(e.shiftKey ? 3 : 1);
  8049. },
  8050.  
  8051. _zoomOut: function (e) {
  8052. this._map.zoomOut(e.shiftKey ? 3 : 1);
  8053. },
  8054.  
  8055. _createButton: function (html, title, className, container, fn, context) {
  8056. var link = L.DomUtil.create('a', className, container);
  8057. link.innerHTML = html;
  8058. link.href = '#';
  8059. link.title = title;
  8060.  
  8061. var stop = L.DomEvent.stopPropagation;
  8062.  
  8063. L.DomEvent
  8064. .on(link, 'click', stop)
  8065. .on(link, 'mousedown', stop)
  8066. .on(link, 'dblclick', stop)
  8067. .on(link, 'click', L.DomEvent.preventDefault)
  8068. .on(link, 'click', fn, context)
  8069. .on(link, 'click', this._refocusOnMap, context);
  8070.  
  8071. return link;
  8072. },
  8073.  
  8074. _updateDisabled: function () {
  8075. var map = this._map,
  8076. className = 'leaflet-disabled';
  8077.  
  8078. L.DomUtil.removeClass(this._zoomInButton, className);
  8079. L.DomUtil.removeClass(this._zoomOutButton, className);
  8080.  
  8081. if (map._zoom === map.getMinZoom()) {
  8082. L.DomUtil.addClass(this._zoomOutButton, className);
  8083. }
  8084. if (map._zoom === map.getMaxZoom()) {
  8085. L.DomUtil.addClass(this._zoomInButton, className);
  8086. }
  8087. }
  8088. });
  8089.  
  8090. L.Map.mergeOptions({
  8091. zoomControl: true
  8092. });
  8093.  
  8094. L.Map.addInitHook(function () {
  8095. if (this.options.zoomControl) {
  8096. this.zoomControl = new L.Control.Zoom();
  8097. this.addControl(this.zoomControl);
  8098. }
  8099. });
  8100.  
  8101. L.control.zoom = function (options) {
  8102. return new L.Control.Zoom(options);
  8103. };
  8104.  
  8105.  
  8106.  
  8107. /*
  8108. * L.Control.Attribution is used for displaying attribution on the map (added by default).
  8109. */
  8110.  
  8111. L.Control.Attribution = L.Control.extend({
  8112. options: {
  8113. position: 'bottomright',
  8114. prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  8115. },
  8116.  
  8117. initialize: function (options) {
  8118. L.setOptions(this, options);
  8119.  
  8120. this._attributions = {};
  8121. },
  8122.  
  8123. onAdd: function (map) {
  8124. this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
  8125. L.DomEvent.disableClickPropagation(this._container);
  8126.  
  8127. for (var i in map._layers) {
  8128. if (map._layers[i].getAttribution) {
  8129. this.addAttribution(map._layers[i].getAttribution());
  8130. }
  8131. }
  8132. map
  8133. .on('layeradd', this._onLayerAdd, this)
  8134. .on('layerremove', this._onLayerRemove, this);
  8135.  
  8136. this._update();
  8137.  
  8138. return this._container;
  8139. },
  8140.  
  8141. onRemove: function (map) {
  8142. map
  8143. .off('layeradd', this._onLayerAdd)
  8144. .off('layerremove', this._onLayerRemove);
  8145.  
  8146. },
  8147.  
  8148. setPrefix: function (prefix) {
  8149. this.options.prefix = prefix;
  8150. this._update();
  8151. return this;
  8152. },
  8153.  
  8154. addAttribution: function (text) {
  8155. if (!text) { return; }
  8156.  
  8157. if (!this._attributions[text]) {
  8158. this._attributions[text] = 0;
  8159. }
  8160. this._attributions[text]++;
  8161.  
  8162. this._update();
  8163.  
  8164. return this;
  8165. },
  8166.  
  8167. removeAttribution: function (text) {
  8168. if (!text) { return; }
  8169.  
  8170. if (this._attributions[text]) {
  8171. this._attributions[text]--;
  8172. this._update();
  8173. }
  8174.  
  8175. return this;
  8176. },
  8177.  
  8178. _update: function () {
  8179. if (!this._map) { return; }
  8180.  
  8181. var attribs = [];
  8182.  
  8183. for (var i in this._attributions) {
  8184. if (this._attributions[i]) {
  8185. attribs.push(i);
  8186. }
  8187. }
  8188.  
  8189. var prefixAndAttribs = [];
  8190.  
  8191. if (this.options.prefix) {
  8192. prefixAndAttribs.push(this.options.prefix);
  8193. }
  8194. if (attribs.length) {
  8195. prefixAndAttribs.push(attribs.join(', '));
  8196. }
  8197.  
  8198. this._container.innerHTML = prefixAndAttribs.join(' | ');
  8199. },
  8200.  
  8201. _onLayerAdd: function (e) {
  8202. if (e.layer.getAttribution) {
  8203. this.addAttribution(e.layer.getAttribution());
  8204. }
  8205. },
  8206.  
  8207. _onLayerRemove: function (e) {
  8208. if (e.layer.getAttribution) {
  8209. this.removeAttribution(e.layer.getAttribution());
  8210. }
  8211. }
  8212. });
  8213.  
  8214. L.Map.mergeOptions({
  8215. attributionControl: true
  8216. });
  8217.  
  8218. L.Map.addInitHook(function () {
  8219. if (this.options.attributionControl) {
  8220. this.attributionControl = (new L.Control.Attribution()).addTo(this);
  8221. }
  8222. });
  8223.  
  8224. L.control.attribution = function (options) {
  8225. return new L.Control.Attribution(options);
  8226. };
  8227.  
  8228.  
  8229. /*
  8230. * L.Control.Scale is used for displaying metric/imperial scale on the map.
  8231. */
  8232.  
  8233. L.Control.Scale = L.Control.extend({
  8234. options: {
  8235. position: 'bottomleft',
  8236. maxWidth: 100,
  8237. metric: true,
  8238. imperial: true,
  8239. updateWhenIdle: false
  8240. },
  8241.  
  8242. onAdd: function (map) {
  8243. this._map = map;
  8244.  
  8245. var className = 'leaflet-control-scale',
  8246. container = L.DomUtil.create('div', className),
  8247. options = this.options;
  8248.  
  8249. this._addScales(options, className, container);
  8250.  
  8251. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  8252. map.whenReady(this._update, this);
  8253.  
  8254. return container;
  8255. },
  8256.  
  8257. onRemove: function (map) {
  8258. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  8259. },
  8260.  
  8261. _addScales: function (options, className, container) {
  8262. if (options.metric) {
  8263. this._mScale = L.DomUtil.create('div', className + '-line', container);
  8264. }
  8265. if (options.imperial) {
  8266. this._iScale = L.DomUtil.create('div', className + '-line', container);
  8267. }
  8268. },
  8269.  
  8270. _update: function () {
  8271. var bounds = this._map.getBounds(),
  8272. centerLat = bounds.getCenter().lat,
  8273. halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
  8274. dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
  8275.  
  8276. size = this._map.getSize(),
  8277. options = this.options,
  8278. maxMeters = 0;
  8279.  
  8280. if (size.x > 0) {
  8281. maxMeters = dist * (options.maxWidth / size.x);
  8282. }
  8283.  
  8284. this._updateScales(options, maxMeters);
  8285. },
  8286.  
  8287. _updateScales: function (options, maxMeters) {
  8288. if (options.metric && maxMeters) {
  8289. this._updateMetric(maxMeters);
  8290. }
  8291.  
  8292. if (options.imperial && maxMeters) {
  8293. this._updateImperial(maxMeters);
  8294. }
  8295. },
  8296.  
  8297. _updateMetric: function (maxMeters) {
  8298. var meters = this._getRoundNum(maxMeters);
  8299.  
  8300. this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
  8301. this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  8302. },
  8303.  
  8304. _updateImperial: function (maxMeters) {
  8305. var maxFeet = maxMeters * 3.2808399,
  8306. scale = this._iScale,
  8307. maxMiles, miles, feet;
  8308.  
  8309. if (maxFeet > 5280) {
  8310. maxMiles = maxFeet / 5280;
  8311. miles = this._getRoundNum(maxMiles);
  8312.  
  8313. scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
  8314. scale.innerHTML = miles + ' mi';
  8315.  
  8316. } else {
  8317. feet = this._getRoundNum(maxFeet);
  8318.  
  8319. scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
  8320. scale.innerHTML = feet + ' ft';
  8321. }
  8322. },
  8323.  
  8324. _getScaleWidth: function (ratio) {
  8325. return Math.round(this.options.maxWidth * ratio) - 10;
  8326. },
  8327.  
  8328. _getRoundNum: function (num) {
  8329. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  8330. d = num / pow10;
  8331.  
  8332. d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
  8333.  
  8334. return pow10 * d;
  8335. }
  8336. });
  8337.  
  8338. L.control.scale = function (options) {
  8339. return new L.Control.Scale(options);
  8340. };
  8341.  
  8342.  
  8343. /*
  8344. * L.Control.Layers is a control to allow users to switch between different layers on the map.
  8345. */
  8346.  
  8347. L.Control.Layers = L.Control.extend({
  8348. options: {
  8349. collapsed: true,
  8350. position: 'topright',
  8351. autoZIndex: true
  8352. },
  8353.  
  8354. initialize: function (baseLayers, overlays, options) {
  8355. L.setOptions(this, options);
  8356.  
  8357. this._layers = {};
  8358. this._lastZIndex = 0;
  8359. this._handlingClick = false;
  8360.  
  8361. for (var i in baseLayers) {
  8362. this._addLayer(baseLayers[i], i);
  8363. }
  8364.  
  8365. for (i in overlays) {
  8366. this._addLayer(overlays[i], i, true);
  8367. }
  8368. },
  8369.  
  8370. onAdd: function (map) {
  8371. this._initLayout();
  8372. this._update();
  8373.  
  8374. map
  8375. .on('layeradd', this._onLayerChange, this)
  8376. .on('layerremove', this._onLayerChange, this);
  8377.  
  8378. return this._container;
  8379. },
  8380.  
  8381. onRemove: function (map) {
  8382. map
  8383. .off('layeradd', this._onLayerChange, this)
  8384. .off('layerremove', this._onLayerChange, this);
  8385. },
  8386.  
  8387. addBaseLayer: function (layer, name) {
  8388. this._addLayer(layer, name);
  8389. this._update();
  8390. return this;
  8391. },
  8392.  
  8393. addOverlay: function (layer, name) {
  8394. this._addLayer(layer, name, true);
  8395. this._update();
  8396. return this;
  8397. },
  8398.  
  8399. removeLayer: function (layer) {
  8400. var id = L.stamp(layer);
  8401. delete this._layers[id];
  8402. this._update();
  8403. return this;
  8404. },
  8405.  
  8406. _initLayout: function () {
  8407. var className = 'leaflet-control-layers',
  8408. container = this._container = L.DomUtil.create('div', className);
  8409.  
  8410. //Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
  8411. container.setAttribute('aria-haspopup', true);
  8412.  
  8413. if (!L.Browser.touch) {
  8414. L.DomEvent
  8415. .disableClickPropagation(container)
  8416. .disableScrollPropagation(container);
  8417. } else {
  8418. L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
  8419. }
  8420.  
  8421. var form = this._form = L.DomUtil.create('form', className + '-list');
  8422.  
  8423. if (this.options.collapsed) {
  8424. if (!L.Browser.android) {
  8425. L.DomEvent
  8426. .on(container, 'mouseover', this._expand, this)
  8427. .on(container, 'mouseout', this._collapse, this);
  8428. }
  8429. var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
  8430. link.href = '#';
  8431. link.title = 'Layers';
  8432.  
  8433. if (L.Browser.touch) {
  8434. L.DomEvent
  8435. .on(link, 'click', L.DomEvent.stop)
  8436. .on(link, 'click', this._expand, this);
  8437. }
  8438. else {
  8439. L.DomEvent.on(link, 'focus', this._expand, this);
  8440. }
  8441. //Work around for Firefox android issue https://github.com/Leaflet/Leaflet/issues/2033
  8442. L.DomEvent.on(form, 'click', function () {
  8443. setTimeout(L.bind(this._onInputClick, this), 0);
  8444. }, this);
  8445.  
  8446. this._map.on('click', this._collapse, this);
  8447. // TODO keyboard accessibility
  8448. } else {
  8449. this._expand();
  8450. }
  8451.  
  8452. this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
  8453. this._separator = L.DomUtil.create('div', className + '-separator', form);
  8454. this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
  8455.  
  8456. container.appendChild(form);
  8457. },
  8458.  
  8459. _addLayer: function (layer, name, overlay) {
  8460. var id = L.stamp(layer);
  8461.  
  8462. this._layers[id] = {
  8463. layer: layer,
  8464. name: name,
  8465. overlay: overlay
  8466. };
  8467.  
  8468. if (this.options.autoZIndex && layer.setZIndex) {
  8469. this._lastZIndex++;
  8470. layer.setZIndex(this._lastZIndex);
  8471. }
  8472. },
  8473.  
  8474. _update: function () {
  8475. if (!this._container) {
  8476. return;
  8477. }
  8478.  
  8479. this._baseLayersList.innerHTML = '';
  8480. this._overlaysList.innerHTML = '';
  8481.  
  8482. var baseLayersPresent = false,
  8483. overlaysPresent = false,
  8484. i, obj;
  8485.  
  8486. for (i in this._layers) {
  8487. obj = this._layers[i];
  8488. this._addItem(obj);
  8489. overlaysPresent = overlaysPresent || obj.overlay;
  8490. baseLayersPresent = baseLayersPresent || !obj.overlay;
  8491. }
  8492.  
  8493. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  8494. },
  8495.  
  8496. _onLayerChange: function (e) {
  8497. var obj = this._layers[L.stamp(e.layer)];
  8498.  
  8499. if (!obj) { return; }
  8500.  
  8501. if (!this._handlingClick) {
  8502. this._update();
  8503. }
  8504.  
  8505. var type = obj.overlay ?
  8506. (e.type === 'layeradd' ? 'overlayadd' : 'overlayremove') :
  8507. (e.type === 'layeradd' ? 'baselayerchange' : null);
  8508.  
  8509. if (type) {
  8510. this._map.fire(type, obj);
  8511. }
  8512. },
  8513.  
  8514. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  8515. _createRadioElement: function (name, checked) {
  8516.  
  8517. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
  8518. if (checked) {
  8519. radioHtml += ' checked="checked"';
  8520. }
  8521. radioHtml += '/>';
  8522.  
  8523. var radioFragment = document.createElement('div');
  8524. radioFragment.innerHTML = radioHtml;
  8525.  
  8526. return radioFragment.firstChild;
  8527. },
  8528.  
  8529. _addItem: function (obj) {
  8530. var label = document.createElement('label'),
  8531. input,
  8532. checked = this._map.hasLayer(obj.layer);
  8533.  
  8534. if (obj.overlay) {
  8535. input = document.createElement('input');
  8536. input.type = 'checkbox';
  8537. input.className = 'leaflet-control-layers-selector';
  8538. input.defaultChecked = checked;
  8539. } else {
  8540. input = this._createRadioElement('leaflet-base-layers', checked);
  8541. }
  8542.  
  8543. input.layerId = L.stamp(obj.layer);
  8544.  
  8545. L.DomEvent.on(input, 'click', this._onInputClick, this);
  8546.  
  8547. var name = document.createElement('span');
  8548. name.innerHTML = ' ' + obj.name;
  8549.  
  8550. label.appendChild(input);
  8551. label.appendChild(name);
  8552.  
  8553. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  8554. container.appendChild(label);
  8555.  
  8556. return label;
  8557. },
  8558.  
  8559. _onInputClick: function () {
  8560. var i, input, obj,
  8561. inputs = this._form.getElementsByTagName('input'),
  8562. inputsLen = inputs.length;
  8563.  
  8564. this._handlingClick = true;
  8565.  
  8566. for (i = 0; i < inputsLen; i++) {
  8567. input = inputs[i];
  8568. obj = this._layers[input.layerId];
  8569.  
  8570. if (input.checked && !this._map.hasLayer(obj.layer)) {
  8571. this._map.addLayer(obj.layer);
  8572.  
  8573. } else if (!input.checked && this._map.hasLayer(obj.layer)) {
  8574. this._map.removeLayer(obj.layer);
  8575. }
  8576. }
  8577.  
  8578. this._handlingClick = false;
  8579.  
  8580. this._refocusOnMap();
  8581. },
  8582.  
  8583. _expand: function () {
  8584. L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
  8585. },
  8586.  
  8587. _collapse: function () {
  8588. this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
  8589. }
  8590. });
  8591.  
  8592. L.control.layers = function (baseLayers, overlays, options) {
  8593. return new L.Control.Layers(baseLayers, overlays, options);
  8594. };
  8595.  
  8596.  
  8597. /*
  8598. * L.PosAnimation is used by Leaflet internally for pan animations.
  8599. */
  8600.  
  8601. L.PosAnimation = L.Class.extend({
  8602. includes: L.Mixin.Events,
  8603.  
  8604. run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
  8605. this.stop();
  8606.  
  8607. this._el = el;
  8608. this._inProgress = true;
  8609. this._newPos = newPos;
  8610.  
  8611. this.fire('start');
  8612.  
  8613. el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) +
  8614. 's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)';
  8615.  
  8616. L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
  8617. L.DomUtil.setPosition(el, newPos);
  8618.  
  8619. // toggle reflow, Chrome flickers for some reason if you don't do this
  8620. L.Util.falseFn(el.offsetWidth);
  8621.  
  8622. // there's no native way to track value updates of transitioned properties, so we imitate this
  8623. this._stepTimer = setInterval(L.bind(this._onStep, this), 50);
  8624. },
  8625.  
  8626. stop: function () {
  8627. if (!this._inProgress) { return; }
  8628.  
  8629. // if we just removed the transition property, the element would jump to its final position,
  8630. // so we need to make it stay at the current position
  8631.  
  8632. L.DomUtil.setPosition(this._el, this._getPos());
  8633. this._onTransitionEnd();
  8634. L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation
  8635. },
  8636.  
  8637. _onStep: function () {
  8638. var stepPos = this._getPos();
  8639. if (!stepPos) {
  8640. this._onTransitionEnd();
  8641. return;
  8642. }
  8643. // jshint camelcase: false
  8644. // make L.DomUtil.getPosition return intermediate position value during animation
  8645. this._el._leaflet_pos = stepPos;
  8646.  
  8647. this.fire('step');
  8648. },
  8649.  
  8650. // you can't easily get intermediate values of properties animated with CSS3 Transitions,
  8651. // we need to parse computed style (in case of transform it returns matrix string)
  8652.  
  8653. _transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,
  8654.  
  8655. _getPos: function () {
  8656. var left, top, matches,
  8657. el = this._el,
  8658. style = window.getComputedStyle(el);
  8659.  
  8660. if (L.Browser.any3d) {
  8661. matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
  8662. if (!matches) { return; }
  8663. left = parseFloat(matches[1]);
  8664. top = parseFloat(matches[2]);
  8665. } else {
  8666. left = parseFloat(style.left);
  8667. top = parseFloat(style.top);
  8668. }
  8669.  
  8670. return new L.Point(left, top, true);
  8671. },
  8672.  
  8673. _onTransitionEnd: function () {
  8674. L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
  8675.  
  8676. if (!this._inProgress) { return; }
  8677. this._inProgress = false;
  8678.  
  8679. this._el.style[L.DomUtil.TRANSITION] = '';
  8680.  
  8681. // jshint camelcase: false
  8682. // make sure L.DomUtil.getPosition returns the final position value after animation
  8683. this._el._leaflet_pos = this._newPos;
  8684.  
  8685. clearInterval(this._stepTimer);
  8686.  
  8687. this.fire('step').fire('end');
  8688. }
  8689.  
  8690. });
  8691.  
  8692.  
  8693. /*
  8694. * Extends L.Map to handle panning animations.
  8695. */
  8696.  
  8697. L.Map.include({
  8698.  
  8699. setView: function (center, zoom, options) {
  8700.  
  8701. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  8702. center = this._limitCenter(L.latLng(center), zoom, this.options.maxBounds);
  8703. options = options || {};
  8704.  
  8705. if (this._panAnim) {
  8706. this._panAnim.stop();
  8707. }
  8708.  
  8709. if (this._loaded && !options.reset && options !== true) {
  8710.  
  8711. if (options.animate !== undefined) {
  8712. options.zoom = L.extend({animate: options.animate}, options.zoom);
  8713. options.pan = L.extend({animate: options.animate}, options.pan);
  8714. }
  8715.  
  8716. // try animating pan or zoom
  8717. var animated = (this._zoom !== zoom) ?
  8718. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  8719. this._tryAnimatedPan(center, options.pan);
  8720.  
  8721. if (animated) {
  8722. // prevent resize handler call, the view will refresh after animation anyway
  8723. clearTimeout(this._sizeTimer);
  8724. return this;
  8725. }
  8726. }
  8727.  
  8728. // animation didn't start, just reset the map view
  8729. this._resetView(center, zoom);
  8730.  
  8731. return this;
  8732. },
  8733.  
  8734. panBy: function (offset, options) {
  8735. offset = L.point(offset).round();
  8736. options = options || {};
  8737.  
  8738. if (!offset.x && !offset.y) {
  8739. return this;
  8740. }
  8741.  
  8742. if (!this._panAnim) {
  8743. this._panAnim = new L.PosAnimation();
  8744.  
  8745. this._panAnim.on({
  8746. 'step': this._onPanTransitionStep,
  8747. 'end': this._onPanTransitionEnd
  8748. }, this);
  8749. }
  8750.  
  8751. // don't fire movestart if animating inertia
  8752. if (!options.noMoveStart) {
  8753. this.fire('movestart');
  8754. }
  8755.  
  8756. // animate pan unless animate: false specified
  8757. if (options.animate !== false) {
  8758. L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
  8759.  
  8760. var newPos = this._getMapPanePos().subtract(offset);
  8761. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  8762. } else {
  8763. this._rawPanBy(offset);
  8764. this.fire('move').fire('moveend');
  8765. }
  8766.  
  8767. return this;
  8768. },
  8769.  
  8770. _onPanTransitionStep: function () {
  8771. this.fire('move');
  8772. },
  8773.  
  8774. _onPanTransitionEnd: function () {
  8775. L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
  8776. this.fire('moveend');
  8777. },
  8778.  
  8779. _tryAnimatedPan: function (center, options) {
  8780. // difference between the new and current centers in pixels
  8781. var offset = this._getCenterOffset(center)._floor();
  8782.  
  8783. // don't animate too far unless animate: true specified in options
  8784. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  8785.  
  8786. this.panBy(offset, options);
  8787.  
  8788. return true;
  8789. }
  8790. });
  8791.  
  8792.  
  8793. /*
  8794. * L.PosAnimation fallback implementation that powers Leaflet pan animations
  8795. * in browsers that don't support CSS3 Transitions.
  8796. */
  8797.  
  8798. L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
  8799.  
  8800. run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
  8801. this.stop();
  8802.  
  8803. this._el = el;
  8804. this._inProgress = true;
  8805. this._duration = duration || 0.25;
  8806. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  8807.  
  8808. this._startPos = L.DomUtil.getPosition(el);
  8809. this._offset = newPos.subtract(this._startPos);
  8810. this._startTime = +new Date();
  8811.  
  8812. this.fire('start');
  8813.  
  8814. this._animate();
  8815. },
  8816.  
  8817. stop: function () {
  8818. if (!this._inProgress) { return; }
  8819.  
  8820. this._step();
  8821. this._complete();
  8822. },
  8823.  
  8824. _animate: function () {
  8825. // animation loop
  8826. this._animId = L.Util.requestAnimFrame(this._animate, this);
  8827. this._step();
  8828. },
  8829.  
  8830. _step: function () {
  8831. var elapsed = (+new Date()) - this._startTime,
  8832. duration = this._duration * 1000;
  8833.  
  8834. if (elapsed < duration) {
  8835. this._runFrame(this._easeOut(elapsed / duration));
  8836. } else {
  8837. this._runFrame(1);
  8838. this._complete();
  8839. }
  8840. },
  8841.  
  8842. _runFrame: function (progress) {
  8843. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  8844. L.DomUtil.setPosition(this._el, pos);
  8845.  
  8846. this.fire('step');
  8847. },
  8848.  
  8849. _complete: function () {
  8850. L.Util.cancelAnimFrame(this._animId);
  8851.  
  8852. this._inProgress = false;
  8853. this.fire('end');
  8854. },
  8855.  
  8856. _easeOut: function (t) {
  8857. return 1 - Math.pow(1 - t, this._easeOutPower);
  8858. }
  8859. });
  8860.  
  8861.  
  8862. /*
  8863. * Extends L.Map to handle zoom animations.
  8864. */
  8865.  
  8866. L.Map.mergeOptions({
  8867. zoomAnimation: true,
  8868. zoomAnimationThreshold: 4
  8869. });
  8870.  
  8871. if (L.DomUtil.TRANSITION) {
  8872.  
  8873. L.Map.addInitHook(function () {
  8874. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  8875. this._zoomAnimated = this.options.zoomAnimation && L.DomUtil.TRANSITION &&
  8876. L.Browser.any3d && !L.Browser.android23 && !L.Browser.mobileOpera;
  8877.  
  8878. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  8879. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  8880. if (this._zoomAnimated) {
  8881. L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
  8882. }
  8883. });
  8884. }
  8885.  
  8886. L.Map.include(!L.DomUtil.TRANSITION ? {} : {
  8887.  
  8888. _catchTransitionEnd: function (e) {
  8889. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  8890. this._onZoomTransitionEnd();
  8891. }
  8892. },
  8893.  
  8894. _nothingToAnimate: function () {
  8895. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  8896. },
  8897.  
  8898. _tryAnimatedZoom: function (center, zoom, options) {
  8899.  
  8900. if (this._animatingZoom) { return true; }
  8901.  
  8902. options = options || {};
  8903.  
  8904. // don't animate if disabled, not supported or zoom difference is too large
  8905. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  8906. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  8907.  
  8908. // offset is the pixel coords of the zoom origin relative to the current center
  8909. var scale = this.getZoomScale(zoom),
  8910. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale),
  8911. origin = this._getCenterLayerPoint()._add(offset);
  8912.  
  8913. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  8914. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  8915.  
  8916. this
  8917. .fire('movestart')
  8918. .fire('zoomstart');
  8919.  
  8920. this._animateZoom(center, zoom, origin, scale, null, true);
  8921.  
  8922. return true;
  8923. },
  8924.  
  8925. _animateZoom: function (center, zoom, origin, scale, delta, backwards, forTouchZoom) {
  8926.  
  8927. if (!forTouchZoom) {
  8928. this._animatingZoom = true;
  8929. }
  8930.  
  8931. // put transform transition on all layers with leaflet-zoom-animated class
  8932. L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
  8933.  
  8934. // remember what center/zoom to set after animation
  8935. this._animateToCenter = center;
  8936. this._animateToZoom = zoom;
  8937.  
  8938. // disable any dragging during animation
  8939. if (L.Draggable) {
  8940. L.Draggable._disabled = true;
  8941. }
  8942.  
  8943. L.Util.requestAnimFrame(function () {
  8944. this.fire('zoomanim', {
  8945. center: center,
  8946. zoom: zoom,
  8947. origin: origin,
  8948. scale: scale,
  8949. delta: delta,
  8950. backwards: backwards
  8951. });
  8952. }, this);
  8953. },
  8954.  
  8955. _onZoomTransitionEnd: function () {
  8956.  
  8957. this._animatingZoom = false;
  8958.  
  8959. L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
  8960.  
  8961. this._resetView(this._animateToCenter, this._animateToZoom, true, true);
  8962.  
  8963. if (L.Draggable) {
  8964. L.Draggable._disabled = false;
  8965. }
  8966. }
  8967. });
  8968.  
  8969.  
  8970. /*
  8971. Zoom animation logic for L.TileLayer.
  8972. */
  8973.  
  8974. L.TileLayer.include({
  8975. _animateZoom: function (e) {
  8976. if (!this._animating) {
  8977. this._animating = true;
  8978. this._prepareBgBuffer();
  8979. }
  8980.  
  8981. var bg = this._bgBuffer,
  8982. transform = L.DomUtil.TRANSFORM,
  8983. initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform],
  8984. scaleStr = L.DomUtil.getScaleString(e.scale, e.origin);
  8985.  
  8986. bg.style[transform] = e.backwards ?
  8987. scaleStr + ' ' + initialTransform :
  8988. initialTransform + ' ' + scaleStr;
  8989. },
  8990.  
  8991. _endZoomAnim: function () {
  8992. var front = this._tileContainer,
  8993. bg = this._bgBuffer;
  8994.  
  8995. front.style.visibility = '';
  8996. front.parentNode.appendChild(front); // Bring to fore
  8997.  
  8998. // force reflow
  8999. L.Util.falseFn(bg.offsetWidth);
  9000.  
  9001. this._animating = false;
  9002. },
  9003.  
  9004. _clearBgBuffer: function () {
  9005. var map = this._map;
  9006.  
  9007. if (map && !map._animatingZoom && !map.touchZoom._zooming) {
  9008. this._bgBuffer.innerHTML = '';
  9009. this._bgBuffer.style[L.DomUtil.TRANSFORM] = '';
  9010. }
  9011. },
  9012.  
  9013. _prepareBgBuffer: function () {
  9014.  
  9015. var front = this._tileContainer,
  9016. bg = this._bgBuffer;
  9017.  
  9018. // if foreground layer doesn't have many tiles but bg layer does,
  9019. // keep the existing bg layer and just zoom it some more
  9020.  
  9021. var bgLoaded = this._getLoadedTilesPercentage(bg),
  9022. frontLoaded = this._getLoadedTilesPercentage(front);
  9023.  
  9024. if (bg && bgLoaded > 0.5 && frontLoaded < 0.5) {
  9025.  
  9026. front.style.visibility = 'hidden';
  9027. this._stopLoadingImages(front);
  9028. return;
  9029. }
  9030.  
  9031. // prepare the buffer to become the front tile pane
  9032. bg.style.visibility = 'hidden';
  9033. bg.style[L.DomUtil.TRANSFORM] = '';
  9034.  
  9035. // switch out the current layer to be the new bg layer (and vice-versa)
  9036. this._tileContainer = bg;
  9037. bg = this._bgBuffer = front;
  9038.  
  9039. this._stopLoadingImages(bg);
  9040.  
  9041. //prevent bg buffer from clearing right after zoom
  9042. clearTimeout(this._clearBgBufferTimer);
  9043. },
  9044.  
  9045. _getLoadedTilesPercentage: function (container) {
  9046. var tiles = container.getElementsByTagName('img'),
  9047. i, len, count = 0;
  9048.  
  9049. for (i = 0, len = tiles.length; i < len; i++) {
  9050. if (tiles[i].complete) {
  9051. count++;
  9052. }
  9053. }
  9054. return count / len;
  9055. },
  9056.  
  9057. // stops loading all tiles in the background layer
  9058. _stopLoadingImages: function (container) {
  9059. var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
  9060. i, len, tile;
  9061.  
  9062. for (i = 0, len = tiles.length; i < len; i++) {
  9063. tile = tiles[i];
  9064.  
  9065. if (!tile.complete) {
  9066. tile.onload = L.Util.falseFn;
  9067. tile.onerror = L.Util.falseFn;
  9068. tile.src = L.Util.emptyImageUrl;
  9069.  
  9070. tile.parentNode.removeChild(tile);
  9071. }
  9072. }
  9073. }
  9074. });
  9075.  
  9076.  
  9077. /*
  9078. * Provides L.Map with convenient shortcuts for using browser geolocation features.
  9079. */
  9080.  
  9081. L.Map.include({
  9082. _defaultLocateOptions: {
  9083. watch: false,
  9084. setView: false,
  9085. maxZoom: Infinity,
  9086. timeout: 10000,
  9087. maximumAge: 0,
  9088. enableHighAccuracy: false
  9089. },
  9090.  
  9091. locate: function (/*Object*/ options) {
  9092.  
  9093. options = this._locateOptions = L.extend(this._defaultLocateOptions, options);
  9094.  
  9095. if (!navigator.geolocation) {
  9096. this._handleGeolocationError({
  9097. code: 0,
  9098. message: 'Geolocation not supported.'
  9099. });
  9100. return this;
  9101. }
  9102.  
  9103. var onResponse = L.bind(this._handleGeolocationResponse, this),
  9104. onError = L.bind(this._handleGeolocationError, this);
  9105.  
  9106. if (options.watch) {
  9107. this._locationWatchId =
  9108. navigator.geolocation.watchPosition(onResponse, onError, options);
  9109. } else {
  9110. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  9111. }
  9112. return this;
  9113. },
  9114.  
  9115. stopLocate: function () {
  9116. if (navigator.geolocation) {
  9117. navigator.geolocation.clearWatch(this._locationWatchId);
  9118. }
  9119. if (this._locateOptions) {
  9120. this._locateOptions.setView = false;
  9121. }
  9122. return this;
  9123. },
  9124.  
  9125. _handleGeolocationError: function (error) {
  9126. var c = error.code,
  9127. message = error.message ||
  9128. (c === 1 ? 'permission denied' :
  9129. (c === 2 ? 'position unavailable' : 'timeout'));
  9130.  
  9131. if (this._locateOptions.setView && !this._loaded) {
  9132. this.fitWorld();
  9133. }
  9134.  
  9135. this.fire('locationerror', {
  9136. code: c,
  9137. message: 'Geolocation error: ' + message + '.'
  9138. });
  9139. },
  9140.  
  9141. _handleGeolocationResponse: function (pos) {
  9142. var lat = pos.coords.latitude,
  9143. lng = pos.coords.longitude,
  9144. latlng = new L.LatLng(lat, lng),
  9145.  
  9146. latAccuracy = 180 * pos.coords.accuracy / 40075017,
  9147. lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat),
  9148.  
  9149. bounds = L.latLngBounds(
  9150. [lat - latAccuracy, lng - lngAccuracy],
  9151. [lat + latAccuracy, lng + lngAccuracy]),
  9152.  
  9153. options = this._locateOptions;
  9154.  
  9155. if (options.setView) {
  9156. var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
  9157. this.setView(latlng, zoom);
  9158. }
  9159.  
  9160. var data = {
  9161. latlng: latlng,
  9162. bounds: bounds,
  9163. timestamp: pos.timestamp
  9164. };
  9165.  
  9166. for (var i in pos.coords) {
  9167. if (typeof pos.coords[i] === 'number') {
  9168. data[i] = pos.coords[i];
  9169. }
  9170. }
  9171.  
  9172. this.fire('locationfound', data);
  9173. }
  9174. });
  9175.  
  9176.  
  9177. }(window, document));