Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

9168 lines
210KB

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