Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

13251 Zeilen
373KB

  1. /*
  2. Leaflet 1.0.3, a JS library for interactive maps. http://leafletjs.com
  3. (c) 2010-2016 Vladimir Agafonkin, (c) 2010-2011 CloudMade
  4. */
  5. (function (window, document, undefined) {
  6. var L = {
  7. version: "1.0.3"
  8. };
  9. function expose() {
  10. var oldL = window.L;
  11. L.noConflict = function () {
  12. window.L = oldL;
  13. return this;
  14. };
  15. window.L = L;
  16. }
  17. // define Leaflet for Node module pattern loaders, including Browserify
  18. if (typeof module === 'object' && typeof module.exports === 'object') {
  19. module.exports = L;
  20. // define Leaflet as an AMD module
  21. } else if (typeof define === 'function' && define.amd) {
  22. define(L);
  23. }
  24. // define Leaflet as a global L variable, saving the original L to restore later if needed
  25. if (typeof window !== 'undefined') {
  26. expose();
  27. }
  28. /*
  29. * @namespace Util
  30. *
  31. * Various utility functions, used by Leaflet internally.
  32. */
  33. L.Util = {
  34. // @function extend(dest: Object, src?: Object): Object
  35. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  36. extend: function (dest) {
  37. var i, j, len, src;
  38. for (j = 1, len = arguments.length; j < len; j++) {
  39. src = arguments[j];
  40. for (i in src) {
  41. dest[i] = src[i];
  42. }
  43. }
  44. return dest;
  45. },
  46. // @function create(proto: Object, properties?: Object): Object
  47. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  48. create: Object.create || (function () {
  49. function F() {}
  50. return function (proto) {
  51. F.prototype = proto;
  52. return new F();
  53. };
  54. })(),
  55. // @function bind(fn: Function, …): Function
  56. // Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
  57. // Has a `L.bind()` shortcut.
  58. bind: function (fn, obj) {
  59. var slice = Array.prototype.slice;
  60. if (fn.bind) {
  61. return fn.bind.apply(fn, slice.call(arguments, 1));
  62. }
  63. var args = slice.call(arguments, 2);
  64. return function () {
  65. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  66. };
  67. },
  68. // @function stamp(obj: Object): Number
  69. // Returns the unique ID of an object, assiging it one if it doesn't have it.
  70. stamp: function (obj) {
  71. /*eslint-disable */
  72. obj._leaflet_id = obj._leaflet_id || ++L.Util.lastId;
  73. return obj._leaflet_id;
  74. /*eslint-enable */
  75. },
  76. // @property lastId: Number
  77. // Last unique ID used by [`stamp()`](#util-stamp)
  78. lastId: 0,
  79. // @function throttle(fn: Function, time: Number, context: Object): Function
  80. // Returns a function which executes function `fn` with the given scope `context`
  81. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  82. // `fn` will be called no more than one time per given amount of `time`. The arguments
  83. // received by the bound function will be any arguments passed when binding the
  84. // function, followed by any arguments passed when invoking the bound function.
  85. // Has an `L.bind` shortcut.
  86. throttle: function (fn, time, context) {
  87. var lock, args, wrapperFn, later;
  88. later = function () {
  89. // reset lock and call if queued
  90. lock = false;
  91. if (args) {
  92. wrapperFn.apply(context, args);
  93. args = false;
  94. }
  95. };
  96. wrapperFn = function () {
  97. if (lock) {
  98. // called too soon, queue to call later
  99. args = arguments;
  100. } else {
  101. // call and lock until later
  102. fn.apply(context, arguments);
  103. setTimeout(later, time);
  104. lock = true;
  105. }
  106. };
  107. return wrapperFn;
  108. },
  109. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  110. // Returns the number `num` modulo `range` in such a way so it lies within
  111. // `range[0]` and `range[1]`. The returned value will be always smaller than
  112. // `range[1]` unless `includeMax` is set to `true`.
  113. wrapNum: function (x, range, includeMax) {
  114. var max = range[1],
  115. min = range[0],
  116. d = max - min;
  117. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  118. },
  119. // @function falseFn(): Function
  120. // Returns a function which always returns `false`.
  121. falseFn: function () { return false; },
  122. // @function formatNum(num: Number, digits?: Number): Number
  123. // Returns the number `num` rounded to `digits` decimals, or to 5 decimals by default.
  124. formatNum: function (num, digits) {
  125. var pow = Math.pow(10, digits || 5);
  126. return Math.round(num * pow) / pow;
  127. },
  128. // @function trim(str: String): String
  129. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  130. trim: function (str) {
  131. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  132. },
  133. // @function splitWords(str: String): String[]
  134. // Trims and splits the string on whitespace and returns the array of parts.
  135. splitWords: function (str) {
  136. return L.Util.trim(str).split(/\s+/);
  137. },
  138. // @function setOptions(obj: Object, options: Object): Object
  139. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  140. setOptions: function (obj, options) {
  141. if (!obj.hasOwnProperty('options')) {
  142. obj.options = obj.options ? L.Util.create(obj.options) : {};
  143. }
  144. for (var i in options) {
  145. obj.options[i] = options[i];
  146. }
  147. return obj.options;
  148. },
  149. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  150. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  151. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  152. // be appended at the end. If `uppercase` is `true`, the parameter names will
  153. // be uppercased (e.g. `'?A=foo&B=bar'`)
  154. getParamString: function (obj, existingUrl, uppercase) {
  155. var params = [];
  156. for (var i in obj) {
  157. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  158. }
  159. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  160. },
  161. // @function template(str: String, data: Object): String
  162. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  163. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  164. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  165. // data values — they will be evaluated passing `data` as an argument.
  166. template: function (str, data) {
  167. return str.replace(L.Util.templateRe, function (str, key) {
  168. var value = data[key];
  169. if (value === undefined) {
  170. throw new Error('No value provided for variable ' + str);
  171. } else if (typeof value === 'function') {
  172. value = value(data);
  173. }
  174. return value;
  175. });
  176. },
  177. templateRe: /\{ *([\w_\-]+) *\}/g,
  178. // @function isArray(obj): Boolean
  179. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  180. isArray: Array.isArray || function (obj) {
  181. return (Object.prototype.toString.call(obj) === '[object Array]');
  182. },
  183. // @function indexOf(array: Array, el: Object): Number
  184. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  185. indexOf: function (array, el) {
  186. for (var i = 0; i < array.length; i++) {
  187. if (array[i] === el) { return i; }
  188. }
  189. return -1;
  190. },
  191. // @property emptyImageUrl: String
  192. // Data URI string containing a base64-encoded empty GIF image.
  193. // Used as a hack to free memory from unused images on WebKit-powered
  194. // mobile devices (by setting image `src` to this string).
  195. emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
  196. };
  197. (function () {
  198. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  199. function getPrefixed(name) {
  200. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  201. }
  202. var lastTime = 0;
  203. // fallback for IE 7-8
  204. function timeoutDefer(fn) {
  205. var time = +new Date(),
  206. timeToCall = Math.max(0, 16 - (time - lastTime));
  207. lastTime = time + timeToCall;
  208. return window.setTimeout(fn, timeToCall);
  209. }
  210. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer,
  211. cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  212. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  213. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  214. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  215. // `context` if given. When `immediate` is set, `fn` is called immediately if
  216. // the browser doesn't have native support for
  217. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  218. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  219. L.Util.requestAnimFrame = function (fn, context, immediate) {
  220. if (immediate && requestFn === timeoutDefer) {
  221. fn.call(context);
  222. } else {
  223. return requestFn.call(window, L.bind(fn, context));
  224. }
  225. };
  226. // @function cancelAnimFrame(id: Number): undefined
  227. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  228. L.Util.cancelAnimFrame = function (id) {
  229. if (id) {
  230. cancelFn.call(window, id);
  231. }
  232. };
  233. })();
  234. // shortcuts for most used utility functions
  235. L.extend = L.Util.extend;
  236. L.bind = L.Util.bind;
  237. L.stamp = L.Util.stamp;
  238. L.setOptions = L.Util.setOptions;
  239. // @class Class
  240. // @aka L.Class
  241. // @section
  242. // @uninheritable
  243. // Thanks to John Resig and Dean Edwards for inspiration!
  244. L.Class = function () {};
  245. L.Class.extend = function (props) {
  246. // @function extend(props: Object): Function
  247. // [Extends the current class](#class-inheritance) given the properties to be included.
  248. // Returns a Javascript function that is a class constructor (to be called with `new`).
  249. var NewClass = function () {
  250. // call the constructor
  251. if (this.initialize) {
  252. this.initialize.apply(this, arguments);
  253. }
  254. // call all constructor hooks
  255. this.callInitHooks();
  256. };
  257. var parentProto = NewClass.__super__ = this.prototype;
  258. var proto = L.Util.create(parentProto);
  259. proto.constructor = NewClass;
  260. NewClass.prototype = proto;
  261. // inherit parent's statics
  262. for (var i in this) {
  263. if (this.hasOwnProperty(i) && i !== 'prototype') {
  264. NewClass[i] = this[i];
  265. }
  266. }
  267. // mix static properties into the class
  268. if (props.statics) {
  269. L.extend(NewClass, props.statics);
  270. delete props.statics;
  271. }
  272. // mix includes into the prototype
  273. if (props.includes) {
  274. L.Util.extend.apply(null, [proto].concat(props.includes));
  275. delete props.includes;
  276. }
  277. // merge options
  278. if (proto.options) {
  279. props.options = L.Util.extend(L.Util.create(proto.options), props.options);
  280. }
  281. // mix given properties into the prototype
  282. L.extend(proto, props);
  283. proto._initHooks = [];
  284. // add method for calling all hooks
  285. proto.callInitHooks = function () {
  286. if (this._initHooksCalled) { return; }
  287. if (parentProto.callInitHooks) {
  288. parentProto.callInitHooks.call(this);
  289. }
  290. this._initHooksCalled = true;
  291. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  292. proto._initHooks[i].call(this);
  293. }
  294. };
  295. return NewClass;
  296. };
  297. // @function include(properties: Object): this
  298. // [Includes a mixin](#class-includes) into the current class.
  299. L.Class.include = function (props) {
  300. L.extend(this.prototype, props);
  301. return this;
  302. };
  303. // @function mergeOptions(options: Object): this
  304. // [Merges `options`](#class-options) into the defaults of the class.
  305. L.Class.mergeOptions = function (options) {
  306. L.extend(this.prototype.options, options);
  307. return this;
  308. };
  309. // @function addInitHook(fn: Function): this
  310. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  311. L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
  312. var args = Array.prototype.slice.call(arguments, 1);
  313. var init = typeof fn === 'function' ? fn : function () {
  314. this[fn].apply(this, args);
  315. };
  316. this.prototype._initHooks = this.prototype._initHooks || [];
  317. this.prototype._initHooks.push(init);
  318. return this;
  319. };
  320. /*
  321. * @class Evented
  322. * @aka L.Evented
  323. * @inherits Class
  324. *
  325. * A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event).
  326. *
  327. * @example
  328. *
  329. * ```js
  330. * map.on('click', function(e) {
  331. * alert(e.latlng);
  332. * } );
  333. * ```
  334. *
  335. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  336. *
  337. * ```js
  338. * function onClick(e) { ... }
  339. *
  340. * map.on('click', onClick);
  341. * map.off('click', onClick);
  342. * ```
  343. */
  344. L.Evented = L.Class.extend({
  345. /* @method on(type: String, fn: Function, context?: Object): this
  346. * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).
  347. *
  348. * @alternative
  349. * @method on(eventMap: Object): this
  350. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  351. */
  352. on: function (types, fn, context) {
  353. // types can be a map of types/handlers
  354. if (typeof types === 'object') {
  355. for (var type in types) {
  356. // we don't process space-separated events here for performance;
  357. // it's a hot path since Layer uses the on(obj) syntax
  358. this._on(type, types[type], fn);
  359. }
  360. } else {
  361. // types can be a string of space-separated words
  362. types = L.Util.splitWords(types);
  363. for (var i = 0, len = types.length; i < len; i++) {
  364. this._on(types[i], fn, context);
  365. }
  366. }
  367. return this;
  368. },
  369. /* @method off(type: String, fn?: Function, context?: Object): this
  370. * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.
  371. *
  372. * @alternative
  373. * @method off(eventMap: Object): this
  374. * Removes a set of type/listener pairs.
  375. *
  376. * @alternative
  377. * @method off: this
  378. * Removes all listeners to all events on the object.
  379. */
  380. off: function (types, fn, context) {
  381. if (!types) {
  382. // clear all listeners if called without arguments
  383. delete this._events;
  384. } else if (typeof types === 'object') {
  385. for (var type in types) {
  386. this._off(type, types[type], fn);
  387. }
  388. } else {
  389. types = L.Util.splitWords(types);
  390. for (var i = 0, len = types.length; i < len; i++) {
  391. this._off(types[i], fn, context);
  392. }
  393. }
  394. return this;
  395. },
  396. // attach listener (without syntactic sugar now)
  397. _on: function (type, fn, context) {
  398. this._events = this._events || {};
  399. /* get/init listeners for type */
  400. var typeListeners = this._events[type];
  401. if (!typeListeners) {
  402. typeListeners = [];
  403. this._events[type] = typeListeners;
  404. }
  405. if (context === this) {
  406. // Less memory footprint.
  407. context = undefined;
  408. }
  409. var newListener = {fn: fn, ctx: context},
  410. listeners = typeListeners;
  411. // check if fn already there
  412. for (var i = 0, len = listeners.length; i < len; i++) {
  413. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  414. return;
  415. }
  416. }
  417. listeners.push(newListener);
  418. },
  419. _off: function (type, fn, context) {
  420. var listeners,
  421. i,
  422. len;
  423. if (!this._events) { return; }
  424. listeners = this._events[type];
  425. if (!listeners) {
  426. return;
  427. }
  428. if (!fn) {
  429. // Set all removed listeners to noop so they are not called if remove happens in fire
  430. for (i = 0, len = listeners.length; i < len; i++) {
  431. listeners[i].fn = L.Util.falseFn;
  432. }
  433. // clear all listeners for a type if function isn't specified
  434. delete this._events[type];
  435. return;
  436. }
  437. if (context === this) {
  438. context = undefined;
  439. }
  440. if (listeners) {
  441. // find fn and remove it
  442. for (i = 0, len = listeners.length; i < len; i++) {
  443. var l = listeners[i];
  444. if (l.ctx !== context) { continue; }
  445. if (l.fn === fn) {
  446. // set the removed listener to noop so that's not called if remove happens in fire
  447. l.fn = L.Util.falseFn;
  448. if (this._firingCount) {
  449. /* copy array in case events are being fired */
  450. this._events[type] = listeners = listeners.slice();
  451. }
  452. listeners.splice(i, 1);
  453. return;
  454. }
  455. }
  456. }
  457. },
  458. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  459. // Fires an event of the specified type. You can optionally provide an data
  460. // object — the first argument of the listener function will contain its
  461. // properties. The event can optionally be propagated to event parents.
  462. fire: function (type, data, propagate) {
  463. if (!this.listens(type, propagate)) { return this; }
  464. var event = L.Util.extend({}, data, {type: type, target: this});
  465. if (this._events) {
  466. var listeners = this._events[type];
  467. if (listeners) {
  468. this._firingCount = (this._firingCount + 1) || 1;
  469. for (var i = 0, len = listeners.length; i < len; i++) {
  470. var l = listeners[i];
  471. l.fn.call(l.ctx || this, event);
  472. }
  473. this._firingCount--;
  474. }
  475. }
  476. if (propagate) {
  477. // propagate the event to parents (set with addEventParent)
  478. this._propagateEvent(event);
  479. }
  480. return this;
  481. },
  482. // @method listens(type: String): Boolean
  483. // Returns `true` if a particular event type has any listeners attached to it.
  484. listens: function (type, propagate) {
  485. var listeners = this._events && this._events[type];
  486. if (listeners && listeners.length) { return true; }
  487. if (propagate) {
  488. // also check parents for listeners if event propagates
  489. for (var id in this._eventParents) {
  490. if (this._eventParents[id].listens(type, propagate)) { return true; }
  491. }
  492. }
  493. return false;
  494. },
  495. // @method once(…): this
  496. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  497. once: function (types, fn, context) {
  498. if (typeof types === 'object') {
  499. for (var type in types) {
  500. this.once(type, types[type], fn);
  501. }
  502. return this;
  503. }
  504. var handler = L.bind(function () {
  505. this
  506. .off(types, fn, context)
  507. .off(types, handler, context);
  508. }, this);
  509. // add a listener that's executed once and removed after that
  510. return this
  511. .on(types, fn, context)
  512. .on(types, handler, context);
  513. },
  514. // @method addEventParent(obj: Evented): this
  515. // Adds an event parent - an `Evented` that will receive propagated events
  516. addEventParent: function (obj) {
  517. this._eventParents = this._eventParents || {};
  518. this._eventParents[L.stamp(obj)] = obj;
  519. return this;
  520. },
  521. // @method removeEventParent(obj: Evented): this
  522. // Removes an event parent, so it will stop receiving propagated events
  523. removeEventParent: function (obj) {
  524. if (this._eventParents) {
  525. delete this._eventParents[L.stamp(obj)];
  526. }
  527. return this;
  528. },
  529. _propagateEvent: function (e) {
  530. for (var id in this._eventParents) {
  531. this._eventParents[id].fire(e.type, L.extend({layer: e.target}, e), true);
  532. }
  533. }
  534. });
  535. var proto = L.Evented.prototype;
  536. // aliases; we should ditch those eventually
  537. // @method addEventListener(…): this
  538. // Alias to [`on(…)`](#evented-on)
  539. proto.addEventListener = proto.on;
  540. // @method removeEventListener(…): this
  541. // Alias to [`off(…)`](#evented-off)
  542. // @method clearAllEventListeners(…): this
  543. // Alias to [`off()`](#evented-off)
  544. proto.removeEventListener = proto.clearAllEventListeners = proto.off;
  545. // @method addOneTimeEventListener(…): this
  546. // Alias to [`once(…)`](#evented-once)
  547. proto.addOneTimeEventListener = proto.once;
  548. // @method fireEvent(…): this
  549. // Alias to [`fire(…)`](#evented-fire)
  550. proto.fireEvent = proto.fire;
  551. // @method hasEventListeners(…): Boolean
  552. // Alias to [`listens(…)`](#evented-listens)
  553. proto.hasEventListeners = proto.listens;
  554. L.Mixin = {Events: proto};
  555. /*
  556. * @namespace Browser
  557. * @aka L.Browser
  558. *
  559. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  560. *
  561. * @example
  562. *
  563. * ```js
  564. * if (L.Browser.ielt9) {
  565. * alert('Upgrade your browser, dude!');
  566. * }
  567. * ```
  568. */
  569. (function () {
  570. var ua = navigator.userAgent.toLowerCase(),
  571. doc = document.documentElement,
  572. ie = 'ActiveXObject' in window,
  573. webkit = ua.indexOf('webkit') !== -1,
  574. phantomjs = ua.indexOf('phantom') !== -1,
  575. android23 = ua.search('android [23]') !== -1,
  576. chrome = ua.indexOf('chrome') !== -1,
  577. gecko = ua.indexOf('gecko') !== -1 && !webkit && !window.opera && !ie,
  578. win = navigator.platform.indexOf('Win') === 0,
  579. mobile = typeof orientation !== 'undefined' || ua.indexOf('mobile') !== -1,
  580. msPointer = !window.PointerEvent && window.MSPointerEvent,
  581. pointer = window.PointerEvent || msPointer,
  582. ie3d = ie && ('transition' in doc.style),
  583. webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23,
  584. gecko3d = 'MozPerspective' in doc.style,
  585. opera12 = 'OTransition' in doc.style;
  586. var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
  587. (window.DocumentTouch && document instanceof window.DocumentTouch));
  588. L.Browser = {
  589. // @property ie: Boolean
  590. // `true` for all Internet Explorer versions (not Edge).
  591. ie: ie,
  592. // @property ielt9: Boolean
  593. // `true` for Internet Explorer versions less than 9.
  594. ielt9: ie && !document.addEventListener,
  595. // @property edge: Boolean
  596. // `true` for the Edge web browser.
  597. edge: 'msLaunchUri' in navigator && !('documentMode' in document),
  598. // @property webkit: Boolean
  599. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  600. webkit: webkit,
  601. // @property gecko: Boolean
  602. // `true` for gecko-based browsers like Firefox.
  603. gecko: gecko,
  604. // @property android: Boolean
  605. // `true` for any browser running on an Android platform.
  606. android: ua.indexOf('android') !== -1,
  607. // @property android23: Boolean
  608. // `true` for browsers running on Android 2 or Android 3.
  609. android23: android23,
  610. // @property chrome: Boolean
  611. // `true` for the Chrome browser.
  612. chrome: chrome,
  613. // @property safari: Boolean
  614. // `true` for the Safari browser.
  615. safari: !chrome && ua.indexOf('safari') !== -1,
  616. // @property win: Boolean
  617. // `true` when the browser is running in a Windows platform
  618. win: win,
  619. // @property ie3d: Boolean
  620. // `true` for all Internet Explorer versions supporting CSS transforms.
  621. ie3d: ie3d,
  622. // @property webkit3d: Boolean
  623. // `true` for webkit-based browsers supporting CSS transforms.
  624. webkit3d: webkit3d,
  625. // @property gecko3d: Boolean
  626. // `true` for gecko-based browsers supporting CSS transforms.
  627. gecko3d: gecko3d,
  628. // @property opera12: Boolean
  629. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  630. opera12: opera12,
  631. // @property any3d: Boolean
  632. // `true` for all browsers supporting CSS transforms.
  633. any3d: !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantomjs,
  634. // @property mobile: Boolean
  635. // `true` for all browsers running in a mobile device.
  636. mobile: mobile,
  637. // @property mobileWebkit: Boolean
  638. // `true` for all webkit-based browsers in a mobile device.
  639. mobileWebkit: mobile && webkit,
  640. // @property mobileWebkit3d: Boolean
  641. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  642. mobileWebkit3d: mobile && webkit3d,
  643. // @property mobileOpera: Boolean
  644. // `true` for the Opera browser in a mobile device.
  645. mobileOpera: mobile && window.opera,
  646. // @property mobileGecko: Boolean
  647. // `true` for gecko-based browsers running in a mobile device.
  648. mobileGecko: mobile && gecko,
  649. // @property touch: Boolean
  650. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  651. // This does not necessarily mean that the browser is running in a computer with
  652. // a touchscreen, it only means that the browser is capable of understanding
  653. // touch events.
  654. touch: !!touch,
  655. // @property msPointer: Boolean
  656. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  657. msPointer: !!msPointer,
  658. // @property pointer: Boolean
  659. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  660. pointer: !!pointer,
  661. // @property retina: Boolean
  662. // `true` for browsers on a high-resolution "retina" screen.
  663. retina: (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1
  664. };
  665. }());
  666. /*
  667. * @class Point
  668. * @aka L.Point
  669. *
  670. * Represents a point with `x` and `y` coordinates in pixels.
  671. *
  672. * @example
  673. *
  674. * ```js
  675. * var point = L.point(200, 300);
  676. * ```
  677. *
  678. * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:
  679. *
  680. * ```js
  681. * map.panBy([200, 300]);
  682. * map.panBy(L.point(200, 300));
  683. * ```
  684. */
  685. L.Point = function (x, y, round) {
  686. // @property x: Number; The `x` coordinate of the point
  687. this.x = (round ? Math.round(x) : x);
  688. // @property y: Number; The `y` coordinate of the point
  689. this.y = (round ? Math.round(y) : y);
  690. };
  691. L.Point.prototype = {
  692. // @method clone(): Point
  693. // Returns a copy of the current point.
  694. clone: function () {
  695. return new L.Point(this.x, this.y);
  696. },
  697. // @method add(otherPoint: Point): Point
  698. // Returns the result of addition of the current and the given points.
  699. add: function (point) {
  700. // non-destructive, returns a new point
  701. return this.clone()._add(L.point(point));
  702. },
  703. _add: function (point) {
  704. // destructive, used directly for performance in situations where it's safe to modify existing point
  705. this.x += point.x;
  706. this.y += point.y;
  707. return this;
  708. },
  709. // @method subtract(otherPoint: Point): Point
  710. // Returns the result of subtraction of the given point from the current.
  711. subtract: function (point) {
  712. return this.clone()._subtract(L.point(point));
  713. },
  714. _subtract: function (point) {
  715. this.x -= point.x;
  716. this.y -= point.y;
  717. return this;
  718. },
  719. // @method divideBy(num: Number): Point
  720. // Returns the result of division of the current point by the given number.
  721. divideBy: function (num) {
  722. return this.clone()._divideBy(num);
  723. },
  724. _divideBy: function (num) {
  725. this.x /= num;
  726. this.y /= num;
  727. return this;
  728. },
  729. // @method multiplyBy(num: Number): Point
  730. // Returns the result of multiplication of the current point by the given number.
  731. multiplyBy: function (num) {
  732. return this.clone()._multiplyBy(num);
  733. },
  734. _multiplyBy: function (num) {
  735. this.x *= num;
  736. this.y *= num;
  737. return this;
  738. },
  739. // @method scaleBy(scale: Point): Point
  740. // Multiply each coordinate of the current point by each coordinate of
  741. // `scale`. In linear algebra terms, multiply the point by the
  742. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  743. // defined by `scale`.
  744. scaleBy: function (point) {
  745. return new L.Point(this.x * point.x, this.y * point.y);
  746. },
  747. // @method unscaleBy(scale: Point): Point
  748. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  749. // each coordinate of `scale`.
  750. unscaleBy: function (point) {
  751. return new L.Point(this.x / point.x, this.y / point.y);
  752. },
  753. // @method round(): Point
  754. // Returns a copy of the current point with rounded coordinates.
  755. round: function () {
  756. return this.clone()._round();
  757. },
  758. _round: function () {
  759. this.x = Math.round(this.x);
  760. this.y = Math.round(this.y);
  761. return this;
  762. },
  763. // @method floor(): Point
  764. // Returns a copy of the current point with floored coordinates (rounded down).
  765. floor: function () {
  766. return this.clone()._floor();
  767. },
  768. _floor: function () {
  769. this.x = Math.floor(this.x);
  770. this.y = Math.floor(this.y);
  771. return this;
  772. },
  773. // @method ceil(): Point
  774. // Returns a copy of the current point with ceiled coordinates (rounded up).
  775. ceil: function () {
  776. return this.clone()._ceil();
  777. },
  778. _ceil: function () {
  779. this.x = Math.ceil(this.x);
  780. this.y = Math.ceil(this.y);
  781. return this;
  782. },
  783. // @method distanceTo(otherPoint: Point): Number
  784. // Returns the cartesian distance between the current and the given points.
  785. distanceTo: function (point) {
  786. point = L.point(point);
  787. var x = point.x - this.x,
  788. y = point.y - this.y;
  789. return Math.sqrt(x * x + y * y);
  790. },
  791. // @method equals(otherPoint: Point): Boolean
  792. // Returns `true` if the given point has the same coordinates.
  793. equals: function (point) {
  794. point = L.point(point);
  795. return point.x === this.x &&
  796. point.y === this.y;
  797. },
  798. // @method contains(otherPoint: Point): Boolean
  799. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  800. contains: function (point) {
  801. point = L.point(point);
  802. return Math.abs(point.x) <= Math.abs(this.x) &&
  803. Math.abs(point.y) <= Math.abs(this.y);
  804. },
  805. // @method toString(): String
  806. // Returns a string representation of the point for debugging purposes.
  807. toString: function () {
  808. return 'Point(' +
  809. L.Util.formatNum(this.x) + ', ' +
  810. L.Util.formatNum(this.y) + ')';
  811. }
  812. };
  813. // @factory L.point(x: Number, y: Number, round?: Boolean)
  814. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  815. // @alternative
  816. // @factory L.point(coords: Number[])
  817. // Expects an array of the form `[x, y]` instead.
  818. // @alternative
  819. // @factory L.point(coords: Object)
  820. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  821. L.point = function (x, y, round) {
  822. if (x instanceof L.Point) {
  823. return x;
  824. }
  825. if (L.Util.isArray(x)) {
  826. return new L.Point(x[0], x[1]);
  827. }
  828. if (x === undefined || x === null) {
  829. return x;
  830. }
  831. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  832. return new L.Point(x.x, x.y);
  833. }
  834. return new L.Point(x, y, round);
  835. };
  836. /*
  837. * @class Bounds
  838. * @aka L.Bounds
  839. *
  840. * Represents a rectangular area in pixel coordinates.
  841. *
  842. * @example
  843. *
  844. * ```js
  845. * var p1 = L.point(10, 10),
  846. * p2 = L.point(40, 60),
  847. * bounds = L.bounds(p1, p2);
  848. * ```
  849. *
  850. * All Leaflet methods that accept `Bounds` objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:
  851. *
  852. * ```js
  853. * otherBounds.intersects([[10, 10], [40, 60]]);
  854. * ```
  855. */
  856. L.Bounds = function (a, b) {
  857. if (!a) { return; }
  858. var points = b ? [a, b] : a;
  859. for (var i = 0, len = points.length; i < len; i++) {
  860. this.extend(points[i]);
  861. }
  862. };
  863. L.Bounds.prototype = {
  864. // @method extend(point: Point): this
  865. // Extends the bounds to contain the given point.
  866. extend: function (point) { // (Point)
  867. point = L.point(point);
  868. // @property min: Point
  869. // The top left corner of the rectangle.
  870. // @property max: Point
  871. // The bottom right corner of the rectangle.
  872. if (!this.min && !this.max) {
  873. this.min = point.clone();
  874. this.max = point.clone();
  875. } else {
  876. this.min.x = Math.min(point.x, this.min.x);
  877. this.max.x = Math.max(point.x, this.max.x);
  878. this.min.y = Math.min(point.y, this.min.y);
  879. this.max.y = Math.max(point.y, this.max.y);
  880. }
  881. return this;
  882. },
  883. // @method getCenter(round?: Boolean): Point
  884. // Returns the center point of the bounds.
  885. getCenter: function (round) {
  886. return new L.Point(
  887. (this.min.x + this.max.x) / 2,
  888. (this.min.y + this.max.y) / 2, round);
  889. },
  890. // @method getBottomLeft(): Point
  891. // Returns the bottom-left point of the bounds.
  892. getBottomLeft: function () {
  893. return new L.Point(this.min.x, this.max.y);
  894. },
  895. // @method getTopRight(): Point
  896. // Returns the top-right point of the bounds.
  897. getTopRight: function () { // -> Point
  898. return new L.Point(this.max.x, this.min.y);
  899. },
  900. // @method getSize(): Point
  901. // Returns the size of the given bounds
  902. getSize: function () {
  903. return this.max.subtract(this.min);
  904. },
  905. // @method contains(otherBounds: Bounds): Boolean
  906. // Returns `true` if the rectangle contains the given one.
  907. // @alternative
  908. // @method contains(point: Point): Boolean
  909. // Returns `true` if the rectangle contains the given point.
  910. contains: function (obj) {
  911. var min, max;
  912. if (typeof obj[0] === 'number' || obj instanceof L.Point) {
  913. obj = L.point(obj);
  914. } else {
  915. obj = L.bounds(obj);
  916. }
  917. if (obj instanceof L.Bounds) {
  918. min = obj.min;
  919. max = obj.max;
  920. } else {
  921. min = max = obj;
  922. }
  923. return (min.x >= this.min.x) &&
  924. (max.x <= this.max.x) &&
  925. (min.y >= this.min.y) &&
  926. (max.y <= this.max.y);
  927. },
  928. // @method intersects(otherBounds: Bounds): Boolean
  929. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  930. // intersect if they have at least one point in common.
  931. intersects: function (bounds) { // (Bounds) -> Boolean
  932. bounds = L.bounds(bounds);
  933. var min = this.min,
  934. max = this.max,
  935. min2 = bounds.min,
  936. max2 = bounds.max,
  937. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  938. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  939. return xIntersects && yIntersects;
  940. },
  941. // @method overlaps(otherBounds: Bounds): Boolean
  942. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  943. // overlap if their intersection is an area.
  944. overlaps: function (bounds) { // (Bounds) -> Boolean
  945. bounds = L.bounds(bounds);
  946. var min = this.min,
  947. max = this.max,
  948. min2 = bounds.min,
  949. max2 = bounds.max,
  950. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  951. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  952. return xOverlaps && yOverlaps;
  953. },
  954. isValid: function () {
  955. return !!(this.min && this.max);
  956. }
  957. };
  958. // @factory L.bounds(topLeft: Point, bottomRight: Point)
  959. // Creates a Bounds object from two coordinates (usually top-left and bottom-right corners).
  960. // @alternative
  961. // @factory L.bounds(points: Point[])
  962. // Creates a Bounds object from the points it contains
  963. L.bounds = function (a, b) {
  964. if (!a || a instanceof L.Bounds) {
  965. return a;
  966. }
  967. return new L.Bounds(a, b);
  968. };
  969. /*
  970. * @class Transformation
  971. * @aka L.Transformation
  972. *
  973. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  974. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  975. * the reverse. Used by Leaflet in its projections code.
  976. *
  977. * @example
  978. *
  979. * ```js
  980. * var transformation = new L.Transformation(2, 5, -1, 10),
  981. * p = L.point(1, 2),
  982. * p2 = transformation.transform(p), // L.point(7, 8)
  983. * p3 = transformation.untransform(p2); // L.point(1, 2)
  984. * ```
  985. */
  986. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  987. // Creates a `Transformation` object with the given coefficients.
  988. L.Transformation = function (a, b, c, d) {
  989. this._a = a;
  990. this._b = b;
  991. this._c = c;
  992. this._d = d;
  993. };
  994. L.Transformation.prototype = {
  995. // @method transform(point: Point, scale?: Number): Point
  996. // Returns a transformed point, optionally multiplied by the given scale.
  997. // Only accepts actual `L.Point` instances, not arrays.
  998. transform: function (point, scale) { // (Point, Number) -> Point
  999. return this._transform(point.clone(), scale);
  1000. },
  1001. // destructive transform (faster)
  1002. _transform: function (point, scale) {
  1003. scale = scale || 1;
  1004. point.x = scale * (this._a * point.x + this._b);
  1005. point.y = scale * (this._c * point.y + this._d);
  1006. return point;
  1007. },
  1008. // @method untransform(point: Point, scale?: Number): Point
  1009. // Returns the reverse transformation of the given point, optionally divided
  1010. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1011. untransform: function (point, scale) {
  1012. scale = scale || 1;
  1013. return new L.Point(
  1014. (point.x / scale - this._b) / this._a,
  1015. (point.y / scale - this._d) / this._c);
  1016. }
  1017. };
  1018. /*
  1019. * @namespace DomUtil
  1020. *
  1021. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1022. * tree, used by Leaflet internally.
  1023. *
  1024. * Most functions expecting or returning a `HTMLElement` also work for
  1025. * SVG elements. The only difference is that classes refer to CSS classes
  1026. * in HTML and SVG classes in SVG.
  1027. */
  1028. L.DomUtil = {
  1029. // @function get(id: String|HTMLElement): HTMLElement
  1030. // Returns an element given its DOM id, or returns the element itself
  1031. // if it was passed directly.
  1032. get: function (id) {
  1033. return typeof id === 'string' ? document.getElementById(id) : id;
  1034. },
  1035. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1036. // Returns the value for a certain style attribute on an element,
  1037. // including computed values or values set through CSS.
  1038. getStyle: function (el, style) {
  1039. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1040. if ((!value || value === 'auto') && document.defaultView) {
  1041. var css = document.defaultView.getComputedStyle(el, null);
  1042. value = css ? css[style] : null;
  1043. }
  1044. return value === 'auto' ? null : value;
  1045. },
  1046. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1047. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1048. create: function (tagName, className, container) {
  1049. var el = document.createElement(tagName);
  1050. el.className = className || '';
  1051. if (container) {
  1052. container.appendChild(el);
  1053. }
  1054. return el;
  1055. },
  1056. // @function remove(el: HTMLElement)
  1057. // Removes `el` from its parent element
  1058. remove: function (el) {
  1059. var parent = el.parentNode;
  1060. if (parent) {
  1061. parent.removeChild(el);
  1062. }
  1063. },
  1064. // @function empty(el: HTMLElement)
  1065. // Removes all of `el`'s children elements from `el`
  1066. empty: function (el) {
  1067. while (el.firstChild) {
  1068. el.removeChild(el.firstChild);
  1069. }
  1070. },
  1071. // @function toFront(el: HTMLElement)
  1072. // Makes `el` the last children of its parent, so it renders in front of the other children.
  1073. toFront: function (el) {
  1074. el.parentNode.appendChild(el);
  1075. },
  1076. // @function toBack(el: HTMLElement)
  1077. // Makes `el` the first children of its parent, so it renders back from the other children.
  1078. toBack: function (el) {
  1079. var parent = el.parentNode;
  1080. parent.insertBefore(el, parent.firstChild);
  1081. },
  1082. // @function hasClass(el: HTMLElement, name: String): Boolean
  1083. // Returns `true` if the element's class attribute contains `name`.
  1084. hasClass: function (el, name) {
  1085. if (el.classList !== undefined) {
  1086. return el.classList.contains(name);
  1087. }
  1088. var className = L.DomUtil.getClass(el);
  1089. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  1090. },
  1091. // @function addClass(el: HTMLElement, name: String)
  1092. // Adds `name` to the element's class attribute.
  1093. addClass: function (el, name) {
  1094. if (el.classList !== undefined) {
  1095. var classes = L.Util.splitWords(name);
  1096. for (var i = 0, len = classes.length; i < len; i++) {
  1097. el.classList.add(classes[i]);
  1098. }
  1099. } else if (!L.DomUtil.hasClass(el, name)) {
  1100. var className = L.DomUtil.getClass(el);
  1101. L.DomUtil.setClass(el, (className ? className + ' ' : '') + name);
  1102. }
  1103. },
  1104. // @function removeClass(el: HTMLElement, name: String)
  1105. // Removes `name` from the element's class attribute.
  1106. removeClass: function (el, name) {
  1107. if (el.classList !== undefined) {
  1108. el.classList.remove(name);
  1109. } else {
  1110. L.DomUtil.setClass(el, L.Util.trim((' ' + L.DomUtil.getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  1111. }
  1112. },
  1113. // @function setClass(el: HTMLElement, name: String)
  1114. // Sets the element's class.
  1115. setClass: function (el, name) {
  1116. if (el.className.baseVal === undefined) {
  1117. el.className = name;
  1118. } else {
  1119. // in case of SVG element
  1120. el.className.baseVal = name;
  1121. }
  1122. },
  1123. // @function getClass(el: HTMLElement): String
  1124. // Returns the element's class.
  1125. getClass: function (el) {
  1126. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  1127. },
  1128. // @function setOpacity(el: HTMLElement, opacity: Number)
  1129. // Set the opacity of an element (including old IE support).
  1130. // `opacity` must be a number from `0` to `1`.
  1131. setOpacity: function (el, value) {
  1132. if ('opacity' in el.style) {
  1133. el.style.opacity = value;
  1134. } else if ('filter' in el.style) {
  1135. L.DomUtil._setOpacityIE(el, value);
  1136. }
  1137. },
  1138. _setOpacityIE: function (el, value) {
  1139. var filter = false,
  1140. filterName = 'DXImageTransform.Microsoft.Alpha';
  1141. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  1142. try {
  1143. filter = el.filters.item(filterName);
  1144. } catch (e) {
  1145. // don't set opacity to 1 if we haven't already set an opacity,
  1146. // it isn't needed and breaks transparent pngs.
  1147. if (value === 1) { return; }
  1148. }
  1149. value = Math.round(value * 100);
  1150. if (filter) {
  1151. filter.Enabled = (value !== 100);
  1152. filter.Opacity = value;
  1153. } else {
  1154. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  1155. }
  1156. },
  1157. // @function testProp(props: String[]): String|false
  1158. // Goes through the array of style names and returns the first name
  1159. // that is a valid style name for an element. If no such name is found,
  1160. // it returns false. Useful for vendor-prefixed styles like `transform`.
  1161. testProp: function (props) {
  1162. var style = document.documentElement.style;
  1163. for (var i = 0; i < props.length; i++) {
  1164. if (props[i] in style) {
  1165. return props[i];
  1166. }
  1167. }
  1168. return false;
  1169. },
  1170. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  1171. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  1172. // and optionally scaled by `scale`. Does not have an effect if the
  1173. // browser doesn't support 3D CSS transforms.
  1174. setTransform: function (el, offset, scale) {
  1175. var pos = offset || new L.Point(0, 0);
  1176. el.style[L.DomUtil.TRANSFORM] =
  1177. (L.Browser.ie3d ?
  1178. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  1179. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  1180. (scale ? ' scale(' + scale + ')' : '');
  1181. },
  1182. // @function setPosition(el: HTMLElement, position: Point)
  1183. // Sets the position of `el` to coordinates specified by `position`,
  1184. // using CSS translate or top/left positioning depending on the browser
  1185. // (used by Leaflet internally to position its layers).
  1186. setPosition: function (el, point) { // (HTMLElement, Point[, Boolean])
  1187. /*eslint-disable */
  1188. el._leaflet_pos = point;
  1189. /*eslint-enable */
  1190. if (L.Browser.any3d) {
  1191. L.DomUtil.setTransform(el, point);
  1192. } else {
  1193. el.style.left = point.x + 'px';
  1194. el.style.top = point.y + 'px';
  1195. }
  1196. },
  1197. // @function getPosition(el: HTMLElement): Point
  1198. // Returns the coordinates of an element previously positioned with setPosition.
  1199. getPosition: function (el) {
  1200. // this method is only used for elements previously positioned using setPosition,
  1201. // so it's safe to cache the position for performance
  1202. return el._leaflet_pos || new L.Point(0, 0);
  1203. }
  1204. };
  1205. (function () {
  1206. // prefix style property names
  1207. // @property TRANSFORM: String
  1208. // Vendor-prefixed fransform style name (e.g. `'webkitTransform'` for WebKit).
  1209. L.DomUtil.TRANSFORM = L.DomUtil.testProp(
  1210. ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1211. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1212. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1213. // @property TRANSITION: String
  1214. // Vendor-prefixed transform style name.
  1215. var transition = L.DomUtil.TRANSITION = L.DomUtil.testProp(
  1216. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1217. L.DomUtil.TRANSITION_END =
  1218. transition === 'webkitTransition' || transition === 'OTransition' ? transition + 'End' : 'transitionend';
  1219. // @function disableTextSelection()
  1220. // Prevents the user from generating `selectstart` DOM events, usually generated
  1221. // when the user drags the mouse through a page with text. Used internally
  1222. // by Leaflet to override the behaviour of any click-and-drag interaction on
  1223. // the map. Affects drag interactions on the whole document.
  1224. // @function enableTextSelection()
  1225. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  1226. if ('onselectstart' in document) {
  1227. L.DomUtil.disableTextSelection = function () {
  1228. L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
  1229. };
  1230. L.DomUtil.enableTextSelection = function () {
  1231. L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
  1232. };
  1233. } else {
  1234. var userSelectProperty = L.DomUtil.testProp(
  1235. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  1236. L.DomUtil.disableTextSelection = function () {
  1237. if (userSelectProperty) {
  1238. var style = document.documentElement.style;
  1239. this._userSelect = style[userSelectProperty];
  1240. style[userSelectProperty] = 'none';
  1241. }
  1242. };
  1243. L.DomUtil.enableTextSelection = function () {
  1244. if (userSelectProperty) {
  1245. document.documentElement.style[userSelectProperty] = this._userSelect;
  1246. delete this._userSelect;
  1247. }
  1248. };
  1249. }
  1250. // @function disableImageDrag()
  1251. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  1252. // for `dragstart` DOM events, usually generated when the user drags an image.
  1253. L.DomUtil.disableImageDrag = function () {
  1254. L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
  1255. };
  1256. // @function enableImageDrag()
  1257. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  1258. L.DomUtil.enableImageDrag = function () {
  1259. L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
  1260. };
  1261. // @function preventOutline(el: HTMLElement)
  1262. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  1263. // of the element `el` invisible. Used internally by Leaflet to prevent
  1264. // focusable elements from displaying an outline when the user performs a
  1265. // drag interaction on them.
  1266. L.DomUtil.preventOutline = function (element) {
  1267. while (element.tabIndex === -1) {
  1268. element = element.parentNode;
  1269. }
  1270. if (!element || !element.style) { return; }
  1271. L.DomUtil.restoreOutline();
  1272. this._outlineElement = element;
  1273. this._outlineStyle = element.style.outline;
  1274. element.style.outline = 'none';
  1275. L.DomEvent.on(window, 'keydown', L.DomUtil.restoreOutline, this);
  1276. };
  1277. // @function restoreOutline()
  1278. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  1279. L.DomUtil.restoreOutline = function () {
  1280. if (!this._outlineElement) { return; }
  1281. this._outlineElement.style.outline = this._outlineStyle;
  1282. delete this._outlineElement;
  1283. delete this._outlineStyle;
  1284. L.DomEvent.off(window, 'keydown', L.DomUtil.restoreOutline, this);
  1285. };
  1286. })();
  1287. /* @class LatLng
  1288. * @aka L.LatLng
  1289. *
  1290. * Represents a geographical point with a certain latitude and longitude.
  1291. *
  1292. * @example
  1293. *
  1294. * ```
  1295. * var latlng = L.latLng(50.5, 30.5);
  1296. * ```
  1297. *
  1298. * All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent:
  1299. *
  1300. * ```
  1301. * map.panTo([50, 30]);
  1302. * map.panTo({lon: 30, lat: 50});
  1303. * map.panTo({lat: 50, lng: 30});
  1304. * map.panTo(L.latLng(50, 30));
  1305. * ```
  1306. */
  1307. L.LatLng = function (lat, lng, alt) {
  1308. if (isNaN(lat) || isNaN(lng)) {
  1309. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1310. }
  1311. // @property lat: Number
  1312. // Latitude in degrees
  1313. this.lat = +lat;
  1314. // @property lng: Number
  1315. // Longitude in degrees
  1316. this.lng = +lng;
  1317. // @property alt: Number
  1318. // Altitude in meters (optional)
  1319. if (alt !== undefined) {
  1320. this.alt = +alt;
  1321. }
  1322. };
  1323. L.LatLng.prototype = {
  1324. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1325. // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overriden by setting `maxMargin` to a small number.
  1326. equals: function (obj, maxMargin) {
  1327. if (!obj) { return false; }
  1328. obj = L.latLng(obj);
  1329. var margin = Math.max(
  1330. Math.abs(this.lat - obj.lat),
  1331. Math.abs(this.lng - obj.lng));
  1332. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1333. },
  1334. // @method toString(): String
  1335. // Returns a string representation of the point (for debugging purposes).
  1336. toString: function (precision) {
  1337. return 'LatLng(' +
  1338. L.Util.formatNum(this.lat, precision) + ', ' +
  1339. L.Util.formatNum(this.lng, precision) + ')';
  1340. },
  1341. // @method distanceTo(otherLatLng: LatLng): Number
  1342. // Returns the distance (in meters) to the given `LatLng` calculated using the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula).
  1343. distanceTo: function (other) {
  1344. return L.CRS.Earth.distance(this, L.latLng(other));
  1345. },
  1346. // @method wrap(): LatLng
  1347. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1348. wrap: function () {
  1349. return L.CRS.Earth.wrapLatLng(this);
  1350. },
  1351. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1352. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1353. toBounds: function (sizeInMeters) {
  1354. var latAccuracy = 180 * sizeInMeters / 40075017,
  1355. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1356. return L.latLngBounds(
  1357. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1358. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1359. },
  1360. clone: function () {
  1361. return new L.LatLng(this.lat, this.lng, this.alt);
  1362. }
  1363. };
  1364. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1365. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1366. // @alternative
  1367. // @factory L.latLng(coords: Array): LatLng
  1368. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1369. // @alternative
  1370. // @factory L.latLng(coords: Object): LatLng
  1371. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1372. L.latLng = function (a, b, c) {
  1373. if (a instanceof L.LatLng) {
  1374. return a;
  1375. }
  1376. if (L.Util.isArray(a) && typeof a[0] !== 'object') {
  1377. if (a.length === 3) {
  1378. return new L.LatLng(a[0], a[1], a[2]);
  1379. }
  1380. if (a.length === 2) {
  1381. return new L.LatLng(a[0], a[1]);
  1382. }
  1383. return null;
  1384. }
  1385. if (a === undefined || a === null) {
  1386. return a;
  1387. }
  1388. if (typeof a === 'object' && 'lat' in a) {
  1389. return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1390. }
  1391. if (b === undefined) {
  1392. return null;
  1393. }
  1394. return new L.LatLng(a, b, c);
  1395. };
  1396. /*
  1397. * @class LatLngBounds
  1398. * @aka L.LatLngBounds
  1399. *
  1400. * Represents a rectangular geographical area on a map.
  1401. *
  1402. * @example
  1403. *
  1404. * ```js
  1405. * var corner1 = L.latLng(40.712, -74.227),
  1406. * corner2 = L.latLng(40.774, -74.125),
  1407. * bounds = L.latLngBounds(corner1, corner2);
  1408. * ```
  1409. *
  1410. * All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:
  1411. *
  1412. * ```js
  1413. * map.fitBounds([
  1414. * [40.712, -74.227],
  1415. * [40.774, -74.125]
  1416. * ]);
  1417. * ```
  1418. *
  1419. * Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range.
  1420. */
  1421. L.LatLngBounds = function (corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  1422. if (!corner1) { return; }
  1423. var latlngs = corner2 ? [corner1, corner2] : corner1;
  1424. for (var i = 0, len = latlngs.length; i < len; i++) {
  1425. this.extend(latlngs[i]);
  1426. }
  1427. };
  1428. L.LatLngBounds.prototype = {
  1429. // @method extend(latlng: LatLng): this
  1430. // Extend the bounds to contain the given point
  1431. // @alternative
  1432. // @method extend(otherBounds: LatLngBounds): this
  1433. // Extend the bounds to contain the given bounds
  1434. extend: function (obj) {
  1435. var sw = this._southWest,
  1436. ne = this._northEast,
  1437. sw2, ne2;
  1438. if (obj instanceof L.LatLng) {
  1439. sw2 = obj;
  1440. ne2 = obj;
  1441. } else if (obj instanceof L.LatLngBounds) {
  1442. sw2 = obj._southWest;
  1443. ne2 = obj._northEast;
  1444. if (!sw2 || !ne2) { return this; }
  1445. } else {
  1446. return obj ? this.extend(L.latLng(obj) || L.latLngBounds(obj)) : this;
  1447. }
  1448. if (!sw && !ne) {
  1449. this._southWest = new L.LatLng(sw2.lat, sw2.lng);
  1450. this._northEast = new L.LatLng(ne2.lat, ne2.lng);
  1451. } else {
  1452. sw.lat = Math.min(sw2.lat, sw.lat);
  1453. sw.lng = Math.min(sw2.lng, sw.lng);
  1454. ne.lat = Math.max(ne2.lat, ne.lat);
  1455. ne.lng = Math.max(ne2.lng, ne.lng);
  1456. }
  1457. return this;
  1458. },
  1459. // @method pad(bufferRatio: Number): LatLngBounds
  1460. // Returns bigger bounds created by extending the current bounds by a given percentage in each direction.
  1461. pad: function (bufferRatio) {
  1462. var sw = this._southWest,
  1463. ne = this._northEast,
  1464. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  1465. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  1466. return new L.LatLngBounds(
  1467. new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  1468. new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  1469. },
  1470. // @method getCenter(): LatLng
  1471. // Returns the center point of the bounds.
  1472. getCenter: function () {
  1473. return new L.LatLng(
  1474. (this._southWest.lat + this._northEast.lat) / 2,
  1475. (this._southWest.lng + this._northEast.lng) / 2);
  1476. },
  1477. // @method getSouthWest(): LatLng
  1478. // Returns the south-west point of the bounds.
  1479. getSouthWest: function () {
  1480. return this._southWest;
  1481. },
  1482. // @method getNorthEast(): LatLng
  1483. // Returns the north-east point of the bounds.
  1484. getNorthEast: function () {
  1485. return this._northEast;
  1486. },
  1487. // @method getNorthWest(): LatLng
  1488. // Returns the north-west point of the bounds.
  1489. getNorthWest: function () {
  1490. return new L.LatLng(this.getNorth(), this.getWest());
  1491. },
  1492. // @method getSouthEast(): LatLng
  1493. // Returns the south-east point of the bounds.
  1494. getSouthEast: function () {
  1495. return new L.LatLng(this.getSouth(), this.getEast());
  1496. },
  1497. // @method getWest(): Number
  1498. // Returns the west longitude of the bounds
  1499. getWest: function () {
  1500. return this._southWest.lng;
  1501. },
  1502. // @method getSouth(): Number
  1503. // Returns the south latitude of the bounds
  1504. getSouth: function () {
  1505. return this._southWest.lat;
  1506. },
  1507. // @method getEast(): Number
  1508. // Returns the east longitude of the bounds
  1509. getEast: function () {
  1510. return this._northEast.lng;
  1511. },
  1512. // @method getNorth(): Number
  1513. // Returns the north latitude of the bounds
  1514. getNorth: function () {
  1515. return this._northEast.lat;
  1516. },
  1517. // @method contains(otherBounds: LatLngBounds): Boolean
  1518. // Returns `true` if the rectangle contains the given one.
  1519. // @alternative
  1520. // @method contains (latlng: LatLng): Boolean
  1521. // Returns `true` if the rectangle contains the given point.
  1522. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1523. if (typeof obj[0] === 'number' || obj instanceof L.LatLng || 'lat' in obj) {
  1524. obj = L.latLng(obj);
  1525. } else {
  1526. obj = L.latLngBounds(obj);
  1527. }
  1528. var sw = this._southWest,
  1529. ne = this._northEast,
  1530. sw2, ne2;
  1531. if (obj instanceof L.LatLngBounds) {
  1532. sw2 = obj.getSouthWest();
  1533. ne2 = obj.getNorthEast();
  1534. } else {
  1535. sw2 = ne2 = obj;
  1536. }
  1537. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1538. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1539. },
  1540. // @method intersects(otherBounds: LatLngBounds): Boolean
  1541. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1542. intersects: function (bounds) {
  1543. bounds = L.latLngBounds(bounds);
  1544. var sw = this._southWest,
  1545. ne = this._northEast,
  1546. sw2 = bounds.getSouthWest(),
  1547. ne2 = bounds.getNorthEast(),
  1548. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1549. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1550. return latIntersects && lngIntersects;
  1551. },
  1552. // @method overlaps(otherBounds: Bounds): Boolean
  1553. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1554. overlaps: function (bounds) {
  1555. bounds = L.latLngBounds(bounds);
  1556. var sw = this._southWest,
  1557. ne = this._northEast,
  1558. sw2 = bounds.getSouthWest(),
  1559. ne2 = bounds.getNorthEast(),
  1560. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1561. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1562. return latOverlaps && lngOverlaps;
  1563. },
  1564. // @method toBBoxString(): String
  1565. // Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.
  1566. toBBoxString: function () {
  1567. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1568. },
  1569. // @method equals(otherBounds: LatLngBounds): Boolean
  1570. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds.
  1571. equals: function (bounds) {
  1572. if (!bounds) { return false; }
  1573. bounds = L.latLngBounds(bounds);
  1574. return this._southWest.equals(bounds.getSouthWest()) &&
  1575. this._northEast.equals(bounds.getNorthEast());
  1576. },
  1577. // @method isValid(): Boolean
  1578. // Returns `true` if the bounds are properly initialized.
  1579. isValid: function () {
  1580. return !!(this._southWest && this._northEast);
  1581. }
  1582. };
  1583. // TODO International date line?
  1584. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1585. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1586. // @alternative
  1587. // @factory L.latLngBounds(latlngs: LatLng[])
  1588. // Creates a `LatLngBounds` object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds).
  1589. L.latLngBounds = function (a, b) {
  1590. if (a instanceof L.LatLngBounds) {
  1591. return a;
  1592. }
  1593. return new L.LatLngBounds(a, b);
  1594. };
  1595. /*
  1596. * @namespace Projection
  1597. * @section
  1598. * Leaflet comes with a set of already defined Projections out of the box:
  1599. *
  1600. * @projection L.Projection.LonLat
  1601. *
  1602. * Equirectangular, or Plate Carree projection — the most simple projection,
  1603. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  1604. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  1605. * `EPSG:3395` and `Simple` CRS.
  1606. */
  1607. L.Projection = {};
  1608. L.Projection.LonLat = {
  1609. project: function (latlng) {
  1610. return new L.Point(latlng.lng, latlng.lat);
  1611. },
  1612. unproject: function (point) {
  1613. return new L.LatLng(point.y, point.x);
  1614. },
  1615. bounds: L.bounds([-180, -90], [180, 90])
  1616. };
  1617. /*
  1618. * @namespace Projection
  1619. * @projection L.Projection.SphericalMercator
  1620. *
  1621. * Spherical Mercator projection — the most common projection for online maps,
  1622. * used by almost all free and commercial tile providers. Assumes that Earth is
  1623. * a sphere. Used by the `EPSG:3857` CRS.
  1624. */
  1625. L.Projection.SphericalMercator = {
  1626. R: 6378137,
  1627. MAX_LATITUDE: 85.0511287798,
  1628. project: function (latlng) {
  1629. var d = Math.PI / 180,
  1630. max = this.MAX_LATITUDE,
  1631. lat = Math.max(Math.min(max, latlng.lat), -max),
  1632. sin = Math.sin(lat * d);
  1633. return new L.Point(
  1634. this.R * latlng.lng * d,
  1635. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1636. },
  1637. unproject: function (point) {
  1638. var d = 180 / Math.PI;
  1639. return new L.LatLng(
  1640. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1641. point.x * d / this.R);
  1642. },
  1643. bounds: (function () {
  1644. var d = 6378137 * Math.PI;
  1645. return L.bounds([-d, -d], [d, d]);
  1646. })()
  1647. };
  1648. /*
  1649. * @class CRS
  1650. * @aka L.CRS
  1651. * Abstract class that defines coordinate reference systems for projecting
  1652. * geographical points into pixel (screen) coordinates and back (and to
  1653. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1654. * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
  1655. *
  1656. * Leaflet defines the most usual CRSs by default. If you want to use a
  1657. * CRS not defined by default, take a look at the
  1658. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1659. */
  1660. L.CRS = {
  1661. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1662. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1663. latLngToPoint: function (latlng, zoom) {
  1664. var projectedPoint = this.projection.project(latlng),
  1665. scale = this.scale(zoom);
  1666. return this.transformation._transform(projectedPoint, scale);
  1667. },
  1668. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1669. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1670. // zoom into geographical coordinates.
  1671. pointToLatLng: function (point, zoom) {
  1672. var scale = this.scale(zoom),
  1673. untransformedPoint = this.transformation.untransform(point, scale);
  1674. return this.projection.unproject(untransformedPoint);
  1675. },
  1676. // @method project(latlng: LatLng): Point
  1677. // Projects geographical coordinates into coordinates in units accepted for
  1678. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1679. project: function (latlng) {
  1680. return this.projection.project(latlng);
  1681. },
  1682. // @method unproject(point: Point): LatLng
  1683. // Given a projected coordinate returns the corresponding LatLng.
  1684. // The inverse of `project`.
  1685. unproject: function (point) {
  1686. return this.projection.unproject(point);
  1687. },
  1688. // @method scale(zoom: Number): Number
  1689. // Returns the scale used when transforming projected coordinates into
  1690. // pixel coordinates for a particular zoom. For example, it returns
  1691. // `256 * 2^zoom` for Mercator-based CRS.
  1692. scale: function (zoom) {
  1693. return 256 * Math.pow(2, zoom);
  1694. },
  1695. // @method zoom(scale: Number): Number
  1696. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1697. // factor of `scale`.
  1698. zoom: function (scale) {
  1699. return Math.log(scale / 256) / Math.LN2;
  1700. },
  1701. // @method getProjectedBounds(zoom: Number): Bounds
  1702. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1703. getProjectedBounds: function (zoom) {
  1704. if (this.infinite) { return null; }
  1705. var b = this.projection.bounds,
  1706. s = this.scale(zoom),
  1707. min = this.transformation.transform(b.min, s),
  1708. max = this.transformation.transform(b.max, s);
  1709. return L.bounds(min, max);
  1710. },
  1711. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1712. // Returns the distance between two geographical coordinates.
  1713. // @property code: String
  1714. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1715. //
  1716. // @property wrapLng: Number[]
  1717. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1718. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1719. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1720. //
  1721. // @property wrapLat: Number[]
  1722. // Like `wrapLng`, but for the latitude (vertical) axis.
  1723. // wrapLng: [min, max],
  1724. // wrapLat: [min, max],
  1725. // @property infinite: Boolean
  1726. // If true, the coordinate space will be unbounded (infinite in both axes)
  1727. infinite: false,
  1728. // @method wrapLatLng(latlng: LatLng): LatLng
  1729. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1730. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1731. // Only accepts actual `L.LatLng` instances, not arrays.
  1732. wrapLatLng: function (latlng) {
  1733. var lng = this.wrapLng ? L.Util.wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1734. lat = this.wrapLat ? L.Util.wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1735. alt = latlng.alt;
  1736. return L.latLng(lat, lng, alt);
  1737. },
  1738. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1739. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1740. // that its center is within the CRS's bounds.
  1741. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1742. wrapLatLngBounds: function (bounds) {
  1743. var center = bounds.getCenter(),
  1744. newCenter = this.wrapLatLng(center),
  1745. latShift = center.lat - newCenter.lat,
  1746. lngShift = center.lng - newCenter.lng;
  1747. if (latShift === 0 && lngShift === 0) {
  1748. return bounds;
  1749. }
  1750. var sw = bounds.getSouthWest(),
  1751. ne = bounds.getNorthEast(),
  1752. newSw = L.latLng({lat: sw.lat - latShift, lng: sw.lng - lngShift}),
  1753. newNe = L.latLng({lat: ne.lat - latShift, lng: ne.lng - lngShift});
  1754. return new L.LatLngBounds(newSw, newNe);
  1755. }
  1756. };
  1757. /*
  1758. * @namespace CRS
  1759. * @crs L.CRS.Simple
  1760. *
  1761. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  1762. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  1763. * axis should still be inverted (going from bottom to top). `distance()` returns
  1764. * simple euclidean distance.
  1765. */
  1766. L.CRS.Simple = L.extend({}, L.CRS, {
  1767. projection: L.Projection.LonLat,
  1768. transformation: new L.Transformation(1, 0, -1, 0),
  1769. scale: function (zoom) {
  1770. return Math.pow(2, zoom);
  1771. },
  1772. zoom: function (scale) {
  1773. return Math.log(scale) / Math.LN2;
  1774. },
  1775. distance: function (latlng1, latlng2) {
  1776. var dx = latlng2.lng - latlng1.lng,
  1777. dy = latlng2.lat - latlng1.lat;
  1778. return Math.sqrt(dx * dx + dy * dy);
  1779. },
  1780. infinite: true
  1781. });
  1782. /*
  1783. * @namespace CRS
  1784. * @crs L.CRS.Earth
  1785. *
  1786. * Serves as the base for CRS that are global such that they cover the earth.
  1787. * Can only be used as the base for other CRS and cannot be used directly,
  1788. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1789. * meters.
  1790. */
  1791. L.CRS.Earth = L.extend({}, L.CRS, {
  1792. wrapLng: [-180, 180],
  1793. // Mean Earth Radius, as recommended for use by
  1794. // the International Union of Geodesy and Geophysics,
  1795. // see http://rosettacode.org/wiki/Haversine_formula
  1796. R: 6371000,
  1797. // distance between two geographical points using spherical law of cosines approximation
  1798. distance: function (latlng1, latlng2) {
  1799. var rad = Math.PI / 180,
  1800. lat1 = latlng1.lat * rad,
  1801. lat2 = latlng2.lat * rad,
  1802. a = Math.sin(lat1) * Math.sin(lat2) +
  1803. Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad);
  1804. return this.R * Math.acos(Math.min(a, 1));
  1805. }
  1806. });
  1807. /*
  1808. * @namespace CRS
  1809. * @crs L.CRS.EPSG3857
  1810. *
  1811. * The most common CRS for online maps, used by almost all free and commercial
  1812. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1813. * Map's `crs` option.
  1814. */
  1815. L.CRS.EPSG3857 = L.extend({}, L.CRS.Earth, {
  1816. code: 'EPSG:3857',
  1817. projection: L.Projection.SphericalMercator,
  1818. transformation: (function () {
  1819. var scale = 0.5 / (Math.PI * L.Projection.SphericalMercator.R);
  1820. return new L.Transformation(scale, 0.5, -scale, 0.5);
  1821. }())
  1822. });
  1823. L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
  1824. code: 'EPSG:900913'
  1825. });
  1826. /*
  1827. * @namespace CRS
  1828. * @crs L.CRS.EPSG4326
  1829. *
  1830. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  1831. *
  1832. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  1833. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  1834. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  1835. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  1836. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  1837. */
  1838. L.CRS.EPSG4326 = L.extend({}, L.CRS.Earth, {
  1839. code: 'EPSG:4326',
  1840. projection: L.Projection.LonLat,
  1841. transformation: new L.Transformation(1 / 180, 1, -1 / 180, 0.5)
  1842. });
  1843. /*
  1844. * @class Map
  1845. * @aka L.Map
  1846. * @inherits Evented
  1847. *
  1848. * The central class of the API — it is used to create a map on a page and manipulate it.
  1849. *
  1850. * @example
  1851. *
  1852. * ```js
  1853. * // initialize the map on the "map" div with a given center and zoom
  1854. * var map = L.map('map', {
  1855. * center: [51.505, -0.09],
  1856. * zoom: 13
  1857. * });
  1858. * ```
  1859. *
  1860. */
  1861. L.Map = L.Evented.extend({
  1862. options: {
  1863. // @section Map State Options
  1864. // @option crs: CRS = L.CRS.EPSG3857
  1865. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  1866. // sure what it means.
  1867. crs: L.CRS.EPSG3857,
  1868. // @option center: LatLng = undefined
  1869. // Initial geographic center of the map
  1870. center: undefined,
  1871. // @option zoom: Number = undefined
  1872. // Initial map zoom level
  1873. zoom: undefined,
  1874. // @option minZoom: Number = undefined
  1875. // Minimum zoom level of the map. Overrides any `minZoom` option set on map layers.
  1876. minZoom: undefined,
  1877. // @option maxZoom: Number = undefined
  1878. // Maximum zoom level of the map. Overrides any `maxZoom` option set on map layers.
  1879. maxZoom: undefined,
  1880. // @option layers: Layer[] = []
  1881. // Array of layers that will be added to the map initially
  1882. layers: [],
  1883. // @option maxBounds: LatLngBounds = null
  1884. // When this option is set, the map restricts the view to the given
  1885. // geographical bounds, bouncing the user back if the user tries to pan
  1886. // outside the view. To set the restriction dynamically, use
  1887. // [`setMaxBounds`](#map-setmaxbounds) method.
  1888. maxBounds: undefined,
  1889. // @option renderer: Renderer = *
  1890. // The default method for drawing vector layers on the map. `L.SVG`
  1891. // or `L.Canvas` by default depending on browser support.
  1892. renderer: undefined,
  1893. // @section Animation Options
  1894. // @option zoomAnimation: Boolean = true
  1895. // Whether the map zoom animation is enabled. By default it's enabled
  1896. // in all browsers that support CSS3 Transitions except Android.
  1897. zoomAnimation: true,
  1898. // @option zoomAnimationThreshold: Number = 4
  1899. // Won't animate zoom if the zoom difference exceeds this value.
  1900. zoomAnimationThreshold: 4,
  1901. // @option fadeAnimation: Boolean = true
  1902. // Whether the tile fade animation is enabled. By default it's enabled
  1903. // in all browsers that support CSS3 Transitions except Android.
  1904. fadeAnimation: true,
  1905. // @option markerZoomAnimation: Boolean = true
  1906. // Whether markers animate their zoom with the zoom animation, if disabled
  1907. // they will disappear for the length of the animation. By default it's
  1908. // enabled in all browsers that support CSS3 Transitions except Android.
  1909. markerZoomAnimation: true,
  1910. // @option transform3DLimit: Number = 2^23
  1911. // Defines the maximum size of a CSS translation transform. The default
  1912. // value should not be changed unless a web browser positions layers in
  1913. // the wrong place after doing a large `panBy`.
  1914. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  1915. // @section Interaction Options
  1916. // @option zoomSnap: Number = 1
  1917. // Forces the map's zoom level to always be a multiple of this, particularly
  1918. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  1919. // By default, the zoom level snaps to the nearest integer; lower values
  1920. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  1921. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  1922. zoomSnap: 1,
  1923. // @option zoomDelta: Number = 1
  1924. // Controls how much the map's zoom level will change after a
  1925. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  1926. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  1927. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  1928. zoomDelta: 1,
  1929. // @option trackResize: Boolean = true
  1930. // Whether the map automatically handles browser window resize to update itself.
  1931. trackResize: true
  1932. },
  1933. initialize: function (id, options) { // (HTMLElement or String, Object)
  1934. options = L.setOptions(this, options);
  1935. this._initContainer(id);
  1936. this._initLayout();
  1937. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  1938. this._onResize = L.bind(this._onResize, this);
  1939. this._initEvents();
  1940. if (options.maxBounds) {
  1941. this.setMaxBounds(options.maxBounds);
  1942. }
  1943. if (options.zoom !== undefined) {
  1944. this._zoom = this._limitZoom(options.zoom);
  1945. }
  1946. if (options.center && options.zoom !== undefined) {
  1947. this.setView(L.latLng(options.center), options.zoom, {reset: true});
  1948. }
  1949. this._handlers = [];
  1950. this._layers = {};
  1951. this._zoomBoundLayers = {};
  1952. this._sizeChanged = true;
  1953. this.callInitHooks();
  1954. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  1955. this._zoomAnimated = L.DomUtil.TRANSITION && L.Browser.any3d && !L.Browser.mobileOpera &&
  1956. this.options.zoomAnimation;
  1957. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  1958. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  1959. if (this._zoomAnimated) {
  1960. this._createAnimProxy();
  1961. L.DomEvent.on(this._proxy, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
  1962. }
  1963. this._addLayers(this.options.layers);
  1964. },
  1965. // @section Methods for modifying map state
  1966. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  1967. // Sets the view of the map (geographical center and zoom) with the given
  1968. // animation options.
  1969. setView: function (center, zoom, options) {
  1970. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  1971. center = this._limitCenter(L.latLng(center), zoom, this.options.maxBounds);
  1972. options = options || {};
  1973. this._stop();
  1974. if (this._loaded && !options.reset && options !== true) {
  1975. if (options.animate !== undefined) {
  1976. options.zoom = L.extend({animate: options.animate}, options.zoom);
  1977. options.pan = L.extend({animate: options.animate, duration: options.duration}, options.pan);
  1978. }
  1979. // try animating pan or zoom
  1980. var moved = (this._zoom !== zoom) ?
  1981. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  1982. this._tryAnimatedPan(center, options.pan);
  1983. if (moved) {
  1984. // prevent resize handler call, the view will refresh after animation anyway
  1985. clearTimeout(this._sizeTimer);
  1986. return this;
  1987. }
  1988. }
  1989. // animation didn't start, just reset the map view
  1990. this._resetView(center, zoom);
  1991. return this;
  1992. },
  1993. // @method setZoom(zoom: Number, options: Zoom/pan options): this
  1994. // Sets the zoom of the map.
  1995. setZoom: function (zoom, options) {
  1996. if (!this._loaded) {
  1997. this._zoom = zoom;
  1998. return this;
  1999. }
  2000. return this.setView(this.getCenter(), zoom, {zoom: options});
  2001. },
  2002. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2003. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2004. zoomIn: function (delta, options) {
  2005. delta = delta || (L.Browser.any3d ? this.options.zoomDelta : 1);
  2006. return this.setZoom(this._zoom + delta, options);
  2007. },
  2008. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2009. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2010. zoomOut: function (delta, options) {
  2011. delta = delta || (L.Browser.any3d ? this.options.zoomDelta : 1);
  2012. return this.setZoom(this._zoom - delta, options);
  2013. },
  2014. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2015. // Zooms the map while keeping a specified geographical point on the map
  2016. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2017. // @alternative
  2018. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2019. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2020. setZoomAround: function (latlng, zoom, options) {
  2021. var scale = this.getZoomScale(zoom),
  2022. viewHalf = this.getSize().divideBy(2),
  2023. containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
  2024. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2025. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2026. return this.setView(newCenter, zoom, {zoom: options});
  2027. },
  2028. _getBoundsCenterZoom: function (bounds, options) {
  2029. options = options || {};
  2030. bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
  2031. var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
  2032. paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
  2033. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2034. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2035. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2036. swPoint = this.project(bounds.getSouthWest(), zoom),
  2037. nePoint = this.project(bounds.getNorthEast(), zoom),
  2038. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2039. return {
  2040. center: center,
  2041. zoom: zoom
  2042. };
  2043. },
  2044. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2045. // Sets a map view that contains the given geographical bounds with the
  2046. // maximum zoom level possible.
  2047. fitBounds: function (bounds, options) {
  2048. bounds = L.latLngBounds(bounds);
  2049. if (!bounds.isValid()) {
  2050. throw new Error('Bounds are not valid.');
  2051. }
  2052. var target = this._getBoundsCenterZoom(bounds, options);
  2053. return this.setView(target.center, target.zoom, options);
  2054. },
  2055. // @method fitWorld(options?: fitBounds options): this
  2056. // Sets a map view that mostly contains the whole world with the maximum
  2057. // zoom level possible.
  2058. fitWorld: function (options) {
  2059. return this.fitBounds([[-90, -180], [90, 180]], options);
  2060. },
  2061. // @method panTo(latlng: LatLng, options?: Pan options): this
  2062. // Pans the map to a given center.
  2063. panTo: function (center, options) { // (LatLng)
  2064. return this.setView(center, this._zoom, {pan: options});
  2065. },
  2066. // @method panBy(offset: Point): this
  2067. // Pans the map by a given number of pixels (animated).
  2068. panBy: function (offset, options) {
  2069. offset = L.point(offset).round();
  2070. options = options || {};
  2071. if (!offset.x && !offset.y) {
  2072. return this.fire('moveend');
  2073. }
  2074. // If we pan too far, Chrome gets issues with tiles
  2075. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2076. if (options.animate !== true && !this.getSize().contains(offset)) {
  2077. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2078. return this;
  2079. }
  2080. if (!this._panAnim) {
  2081. this._panAnim = new L.PosAnimation();
  2082. this._panAnim.on({
  2083. 'step': this._onPanTransitionStep,
  2084. 'end': this._onPanTransitionEnd
  2085. }, this);
  2086. }
  2087. // don't fire movestart if animating inertia
  2088. if (!options.noMoveStart) {
  2089. this.fire('movestart');
  2090. }
  2091. // animate pan unless animate: false specified
  2092. if (options.animate !== false) {
  2093. L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
  2094. var newPos = this._getMapPanePos().subtract(offset).round();
  2095. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2096. } else {
  2097. this._rawPanBy(offset);
  2098. this.fire('move').fire('moveend');
  2099. }
  2100. return this;
  2101. },
  2102. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2103. // Sets the view of the map (geographical center and zoom) performing a smooth
  2104. // pan-zoom animation.
  2105. flyTo: function (targetCenter, targetZoom, options) {
  2106. options = options || {};
  2107. if (options.animate === false || !L.Browser.any3d) {
  2108. return this.setView(targetCenter, targetZoom, options);
  2109. }
  2110. this._stop();
  2111. var from = this.project(this.getCenter()),
  2112. to = this.project(targetCenter),
  2113. size = this.getSize(),
  2114. startZoom = this._zoom;
  2115. targetCenter = L.latLng(targetCenter);
  2116. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2117. var w0 = Math.max(size.x, size.y),
  2118. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2119. u1 = (to.distanceTo(from)) || 1,
  2120. rho = 1.42,
  2121. rho2 = rho * rho;
  2122. function r(i) {
  2123. var s1 = i ? -1 : 1,
  2124. s2 = i ? w1 : w0,
  2125. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2126. b1 = 2 * s2 * rho2 * u1,
  2127. b = t1 / b1,
  2128. sq = Math.sqrt(b * b + 1) - b;
  2129. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2130. // thus triggering an infinite loop in flyTo
  2131. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2132. return log;
  2133. }
  2134. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2135. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2136. function tanh(n) { return sinh(n) / cosh(n); }
  2137. var r0 = r(0);
  2138. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2139. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2140. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2141. var start = Date.now(),
  2142. S = (r(1) - r0) / rho,
  2143. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2144. function frame() {
  2145. var t = (Date.now() - start) / duration,
  2146. s = easeOut(t) * S;
  2147. if (t <= 1) {
  2148. this._flyToFrame = L.Util.requestAnimFrame(frame, this);
  2149. this._move(
  2150. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2151. this.getScaleZoom(w0 / w(s), startZoom),
  2152. {flyTo: true});
  2153. } else {
  2154. this
  2155. ._move(targetCenter, targetZoom)
  2156. ._moveEnd(true);
  2157. }
  2158. }
  2159. this._moveStart(true);
  2160. frame.call(this);
  2161. return this;
  2162. },
  2163. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2164. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2165. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2166. flyToBounds: function (bounds, options) {
  2167. var target = this._getBoundsCenterZoom(bounds, options);
  2168. return this.flyTo(target.center, target.zoom, options);
  2169. },
  2170. // @method setMaxBounds(bounds: Bounds): this
  2171. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2172. setMaxBounds: function (bounds) {
  2173. bounds = L.latLngBounds(bounds);
  2174. if (!bounds.isValid()) {
  2175. this.options.maxBounds = null;
  2176. return this.off('moveend', this._panInsideMaxBounds);
  2177. } else if (this.options.maxBounds) {
  2178. this.off('moveend', this._panInsideMaxBounds);
  2179. }
  2180. this.options.maxBounds = bounds;
  2181. if (this._loaded) {
  2182. this._panInsideMaxBounds();
  2183. }
  2184. return this.on('moveend', this._panInsideMaxBounds);
  2185. },
  2186. // @method setMinZoom(zoom: Number): this
  2187. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2188. setMinZoom: function (zoom) {
  2189. this.options.minZoom = zoom;
  2190. if (this._loaded && this.getZoom() < this.options.minZoom) {
  2191. return this.setZoom(zoom);
  2192. }
  2193. return this;
  2194. },
  2195. // @method setMaxZoom(zoom: Number): this
  2196. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2197. setMaxZoom: function (zoom) {
  2198. this.options.maxZoom = zoom;
  2199. if (this._loaded && (this.getZoom() > this.options.maxZoom)) {
  2200. return this.setZoom(zoom);
  2201. }
  2202. return this;
  2203. },
  2204. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2205. // Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.
  2206. panInsideBounds: function (bounds, options) {
  2207. this._enforcingBounds = true;
  2208. var center = this.getCenter(),
  2209. newCenter = this._limitCenter(center, this._zoom, L.latLngBounds(bounds));
  2210. if (!center.equals(newCenter)) {
  2211. this.panTo(newCenter, options);
  2212. }
  2213. this._enforcingBounds = false;
  2214. return this;
  2215. },
  2216. // @method invalidateSize(options: Zoom/Pan options): this
  2217. // Checks if the map container size changed and updates the map if so —
  2218. // call it after you've changed the map size dynamically, also animating
  2219. // pan by default. If `options.pan` is `false`, panning will not occur.
  2220. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2221. // that it doesn't happen often even if the method is called many
  2222. // times in a row.
  2223. // @alternative
  2224. // @method invalidateSize(animate: Boolean): this
  2225. // Checks if the map container size changed and updates the map if so —
  2226. // call it after you've changed the map size dynamically, also animating
  2227. // pan by default.
  2228. invalidateSize: function (options) {
  2229. if (!this._loaded) { return this; }
  2230. options = L.extend({
  2231. animate: false,
  2232. pan: true
  2233. }, options === true ? {animate: true} : options);
  2234. var oldSize = this.getSize();
  2235. this._sizeChanged = true;
  2236. this._lastCenter = null;
  2237. var newSize = this.getSize(),
  2238. oldCenter = oldSize.divideBy(2).round(),
  2239. newCenter = newSize.divideBy(2).round(),
  2240. offset = oldCenter.subtract(newCenter);
  2241. if (!offset.x && !offset.y) { return this; }
  2242. if (options.animate && options.pan) {
  2243. this.panBy(offset);
  2244. } else {
  2245. if (options.pan) {
  2246. this._rawPanBy(offset);
  2247. }
  2248. this.fire('move');
  2249. if (options.debounceMoveend) {
  2250. clearTimeout(this._sizeTimer);
  2251. this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
  2252. } else {
  2253. this.fire('moveend');
  2254. }
  2255. }
  2256. // @section Map state change events
  2257. // @event resize: ResizeEvent
  2258. // Fired when the map is resized.
  2259. return this.fire('resize', {
  2260. oldSize: oldSize,
  2261. newSize: newSize
  2262. });
  2263. },
  2264. // @section Methods for modifying map state
  2265. // @method stop(): this
  2266. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2267. stop: function () {
  2268. this.setZoom(this._limitZoom(this._zoom));
  2269. if (!this.options.zoomSnap) {
  2270. this.fire('viewreset');
  2271. }
  2272. return this._stop();
  2273. },
  2274. // @section Geolocation methods
  2275. // @method locate(options?: Locate options): this
  2276. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  2277. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  2278. // and optionally sets the map view to the user's location with respect to
  2279. // detection accuracy (or to the world view if geolocation failed).
  2280. // Note that, if your page doesn't use HTTPS, this method will fail in
  2281. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  2282. // See `Locate options` for more details.
  2283. locate: function (options) {
  2284. options = this._locateOptions = L.extend({
  2285. timeout: 10000,
  2286. watch: false
  2287. // setView: false
  2288. // maxZoom: <Number>
  2289. // maximumAge: 0
  2290. // enableHighAccuracy: false
  2291. }, options);
  2292. if (!('geolocation' in navigator)) {
  2293. this._handleGeolocationError({
  2294. code: 0,
  2295. message: 'Geolocation not supported.'
  2296. });
  2297. return this;
  2298. }
  2299. var onResponse = L.bind(this._handleGeolocationResponse, this),
  2300. onError = L.bind(this._handleGeolocationError, this);
  2301. if (options.watch) {
  2302. this._locationWatchId =
  2303. navigator.geolocation.watchPosition(onResponse, onError, options);
  2304. } else {
  2305. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  2306. }
  2307. return this;
  2308. },
  2309. // @method stopLocate(): this
  2310. // Stops watching location previously initiated by `map.locate({watch: true})`
  2311. // and aborts resetting the map view if map.locate was called with
  2312. // `{setView: true}`.
  2313. stopLocate: function () {
  2314. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  2315. navigator.geolocation.clearWatch(this._locationWatchId);
  2316. }
  2317. if (this._locateOptions) {
  2318. this._locateOptions.setView = false;
  2319. }
  2320. return this;
  2321. },
  2322. _handleGeolocationError: function (error) {
  2323. var c = error.code,
  2324. message = error.message ||
  2325. (c === 1 ? 'permission denied' :
  2326. (c === 2 ? 'position unavailable' : 'timeout'));
  2327. if (this._locateOptions.setView && !this._loaded) {
  2328. this.fitWorld();
  2329. }
  2330. // @section Location events
  2331. // @event locationerror: ErrorEvent
  2332. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  2333. this.fire('locationerror', {
  2334. code: c,
  2335. message: 'Geolocation error: ' + message + '.'
  2336. });
  2337. },
  2338. _handleGeolocationResponse: function (pos) {
  2339. var lat = pos.coords.latitude,
  2340. lng = pos.coords.longitude,
  2341. latlng = new L.LatLng(lat, lng),
  2342. bounds = latlng.toBounds(pos.coords.accuracy),
  2343. options = this._locateOptions;
  2344. if (options.setView) {
  2345. var zoom = this.getBoundsZoom(bounds);
  2346. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  2347. }
  2348. var data = {
  2349. latlng: latlng,
  2350. bounds: bounds,
  2351. timestamp: pos.timestamp
  2352. };
  2353. for (var i in pos.coords) {
  2354. if (typeof pos.coords[i] === 'number') {
  2355. data[i] = pos.coords[i];
  2356. }
  2357. }
  2358. // @event locationfound: LocationEvent
  2359. // Fired when geolocation (using the [`locate`](#map-locate) method)
  2360. // went successfully.
  2361. this.fire('locationfound', data);
  2362. },
  2363. // TODO handler.addTo
  2364. // TODO Appropiate docs section?
  2365. // @section Other Methods
  2366. // @method addHandler(name: String, HandlerClass: Function): this
  2367. // Adds a new `Handler` to the map, given its name and constructor function.
  2368. addHandler: function (name, HandlerClass) {
  2369. if (!HandlerClass) { return this; }
  2370. var handler = this[name] = new HandlerClass(this);
  2371. this._handlers.push(handler);
  2372. if (this.options[name]) {
  2373. handler.enable();
  2374. }
  2375. return this;
  2376. },
  2377. // @method remove(): this
  2378. // Destroys the map and clears all related event listeners.
  2379. remove: function () {
  2380. this._initEvents(true);
  2381. if (this._containerId !== this._container._leaflet_id) {
  2382. throw new Error('Map container is being reused by another instance');
  2383. }
  2384. try {
  2385. // throws error in IE6-8
  2386. delete this._container._leaflet_id;
  2387. delete this._containerId;
  2388. } catch (e) {
  2389. /*eslint-disable */
  2390. this._container._leaflet_id = undefined;
  2391. /*eslint-enable */
  2392. this._containerId = undefined;
  2393. }
  2394. L.DomUtil.remove(this._mapPane);
  2395. if (this._clearControlPos) {
  2396. this._clearControlPos();
  2397. }
  2398. this._clearHandlers();
  2399. if (this._loaded) {
  2400. // @section Map state change events
  2401. // @event unload: Event
  2402. // Fired when the map is destroyed with [remove](#map-remove) method.
  2403. this.fire('unload');
  2404. }
  2405. for (var i in this._layers) {
  2406. this._layers[i].remove();
  2407. }
  2408. return this;
  2409. },
  2410. // @section Other Methods
  2411. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  2412. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  2413. // then returns it. The pane is created as a children of `container`, or
  2414. // as a children of the main map pane if not set.
  2415. createPane: function (name, container) {
  2416. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  2417. pane = L.DomUtil.create('div', className, container || this._mapPane);
  2418. if (name) {
  2419. this._panes[name] = pane;
  2420. }
  2421. return pane;
  2422. },
  2423. // @section Methods for Getting Map State
  2424. // @method getCenter(): LatLng
  2425. // Returns the geographical center of the map view
  2426. getCenter: function () {
  2427. this._checkIfLoaded();
  2428. if (this._lastCenter && !this._moved()) {
  2429. return this._lastCenter;
  2430. }
  2431. return this.layerPointToLatLng(this._getCenterLayerPoint());
  2432. },
  2433. // @method getZoom(): Number
  2434. // Returns the current zoom level of the map view
  2435. getZoom: function () {
  2436. return this._zoom;
  2437. },
  2438. // @method getBounds(): LatLngBounds
  2439. // Returns the geographical bounds visible in the current map view
  2440. getBounds: function () {
  2441. var bounds = this.getPixelBounds(),
  2442. sw = this.unproject(bounds.getBottomLeft()),
  2443. ne = this.unproject(bounds.getTopRight());
  2444. return new L.LatLngBounds(sw, ne);
  2445. },
  2446. // @method getMinZoom(): Number
  2447. // Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default.
  2448. getMinZoom: function () {
  2449. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  2450. },
  2451. // @method getMaxZoom(): Number
  2452. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  2453. getMaxZoom: function () {
  2454. return this.options.maxZoom === undefined ?
  2455. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  2456. this.options.maxZoom;
  2457. },
  2458. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean): Number
  2459. // Returns the maximum zoom level on which the given bounds fit to the map
  2460. // view in its entirety. If `inside` (optional) is set to `true`, the method
  2461. // instead returns the minimum zoom level on which the map view fits into
  2462. // the given bounds in its entirety.
  2463. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  2464. bounds = L.latLngBounds(bounds);
  2465. padding = L.point(padding || [0, 0]);
  2466. var zoom = this.getZoom() || 0,
  2467. min = this.getMinZoom(),
  2468. max = this.getMaxZoom(),
  2469. nw = bounds.getNorthWest(),
  2470. se = bounds.getSouthEast(),
  2471. size = this.getSize().subtract(padding),
  2472. boundsSize = L.bounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  2473. snap = L.Browser.any3d ? this.options.zoomSnap : 1;
  2474. var scale = Math.min(size.x / boundsSize.x, size.y / boundsSize.y);
  2475. zoom = this.getScaleZoom(scale, zoom);
  2476. if (snap) {
  2477. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  2478. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  2479. }
  2480. return Math.max(min, Math.min(max, zoom));
  2481. },
  2482. // @method getSize(): Point
  2483. // Returns the current size of the map container (in pixels).
  2484. getSize: function () {
  2485. if (!this._size || this._sizeChanged) {
  2486. this._size = new L.Point(
  2487. this._container.clientWidth || 0,
  2488. this._container.clientHeight || 0);
  2489. this._sizeChanged = false;
  2490. }
  2491. return this._size.clone();
  2492. },
  2493. // @method getPixelBounds(): Bounds
  2494. // Returns the bounds of the current map view in projected pixel
  2495. // coordinates (sometimes useful in layer and overlay implementations).
  2496. getPixelBounds: function (center, zoom) {
  2497. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  2498. return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  2499. },
  2500. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  2501. // the map pane? "left point of the map layer" can be confusing, specially
  2502. // since there can be negative offsets.
  2503. // @method getPixelOrigin(): Point
  2504. // Returns the projected pixel coordinates of the top left point of
  2505. // the map layer (useful in custom layer and overlay implementations).
  2506. getPixelOrigin: function () {
  2507. this._checkIfLoaded();
  2508. return this._pixelOrigin;
  2509. },
  2510. // @method getPixelWorldBounds(zoom?: Number): Bounds
  2511. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  2512. // If `zoom` is omitted, the map's current zoom level is used.
  2513. getPixelWorldBounds: function (zoom) {
  2514. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  2515. },
  2516. // @section Other Methods
  2517. // @method getPane(pane: String|HTMLElement): HTMLElement
  2518. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  2519. getPane: function (pane) {
  2520. return typeof pane === 'string' ? this._panes[pane] : pane;
  2521. },
  2522. // @method getPanes(): Object
  2523. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  2524. // the panes as values.
  2525. getPanes: function () {
  2526. return this._panes;
  2527. },
  2528. // @method getContainer: HTMLElement
  2529. // Returns the HTML element that contains the map.
  2530. getContainer: function () {
  2531. return this._container;
  2532. },
  2533. // @section Conversion Methods
  2534. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  2535. // Returns the scale factor to be applied to a map transition from zoom level
  2536. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  2537. getZoomScale: function (toZoom, fromZoom) {
  2538. // TODO replace with universal implementation after refactoring projections
  2539. var crs = this.options.crs;
  2540. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  2541. return crs.scale(toZoom) / crs.scale(fromZoom);
  2542. },
  2543. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  2544. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  2545. // level and everything is scaled by a factor of `scale`. Inverse of
  2546. // [`getZoomScale`](#map-getZoomScale).
  2547. getScaleZoom: function (scale, fromZoom) {
  2548. var crs = this.options.crs;
  2549. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  2550. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  2551. return isNaN(zoom) ? Infinity : zoom;
  2552. },
  2553. // @method project(latlng: LatLng, zoom: Number): Point
  2554. // Projects a geographical coordinate `LatLng` according to the projection
  2555. // of the map's CRS, then scales it according to `zoom` and the CRS's
  2556. // `Transformation`. The result is pixel coordinate relative to
  2557. // the CRS origin.
  2558. project: function (latlng, zoom) {
  2559. zoom = zoom === undefined ? this._zoom : zoom;
  2560. return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
  2561. },
  2562. // @method unproject(point: Point, zoom: Number): LatLng
  2563. // Inverse of [`project`](#map-project).
  2564. unproject: function (point, zoom) {
  2565. zoom = zoom === undefined ? this._zoom : zoom;
  2566. return this.options.crs.pointToLatLng(L.point(point), zoom);
  2567. },
  2568. // @method layerPointToLatLng(point: Point): LatLng
  2569. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  2570. // returns the corresponding geographical coordinate (for the current zoom level).
  2571. layerPointToLatLng: function (point) {
  2572. var projectedPoint = L.point(point).add(this.getPixelOrigin());
  2573. return this.unproject(projectedPoint);
  2574. },
  2575. // @method latLngToLayerPoint(latlng: LatLng): Point
  2576. // Given a geographical coordinate, returns the corresponding pixel coordinate
  2577. // relative to the [origin pixel](#map-getpixelorigin).
  2578. latLngToLayerPoint: function (latlng) {
  2579. var projectedPoint = this.project(L.latLng(latlng))._round();
  2580. return projectedPoint._subtract(this.getPixelOrigin());
  2581. },
  2582. // @method wrapLatLng(latlng: LatLng): LatLng
  2583. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  2584. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  2585. // CRS's bounds.
  2586. // By default this means longitude is wrapped around the dateline so its
  2587. // value is between -180 and +180 degrees.
  2588. wrapLatLng: function (latlng) {
  2589. return this.options.crs.wrapLatLng(L.latLng(latlng));
  2590. },
  2591. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  2592. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  2593. // its center is within the CRS's bounds.
  2594. // By default this means the center longitude is wrapped around the dateline so its
  2595. // value is between -180 and +180 degrees, and the majority of the bounds
  2596. // overlaps the CRS's bounds.
  2597. wrapLatLngBounds: function (latlng) {
  2598. return this.options.crs.wrapLatLngBounds(L.latLngBounds(latlng));
  2599. },
  2600. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  2601. // Returns the distance between two geographical coordinates according to
  2602. // the map's CRS. By default this measures distance in meters.
  2603. distance: function (latlng1, latlng2) {
  2604. return this.options.crs.distance(L.latLng(latlng1), L.latLng(latlng2));
  2605. },
  2606. // @method containerPointToLayerPoint(point: Point): Point
  2607. // Given a pixel coordinate relative to the map container, returns the corresponding
  2608. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  2609. containerPointToLayerPoint: function (point) { // (Point)
  2610. return L.point(point).subtract(this._getMapPanePos());
  2611. },
  2612. // @method layerPointToContainerPoint(point: Point): Point
  2613. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  2614. // returns the corresponding pixel coordinate relative to the map container.
  2615. layerPointToContainerPoint: function (point) { // (Point)
  2616. return L.point(point).add(this._getMapPanePos());
  2617. },
  2618. // @method containerPointToLatLng(point: Point): LatLng
  2619. // Given a pixel coordinate relative to the map container, returns
  2620. // the corresponding geographical coordinate (for the current zoom level).
  2621. containerPointToLatLng: function (point) {
  2622. var layerPoint = this.containerPointToLayerPoint(L.point(point));
  2623. return this.layerPointToLatLng(layerPoint);
  2624. },
  2625. // @method latLngToContainerPoint(latlng: LatLng): Point
  2626. // Given a geographical coordinate, returns the corresponding pixel coordinate
  2627. // relative to the map container.
  2628. latLngToContainerPoint: function (latlng) {
  2629. return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
  2630. },
  2631. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  2632. // Given a MouseEvent object, returns the pixel coordinate relative to the
  2633. // map container where the event took place.
  2634. mouseEventToContainerPoint: function (e) {
  2635. return L.DomEvent.getMousePosition(e, this._container);
  2636. },
  2637. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  2638. // Given a MouseEvent object, returns the pixel coordinate relative to
  2639. // the [origin pixel](#map-getpixelorigin) where the event took place.
  2640. mouseEventToLayerPoint: function (e) {
  2641. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  2642. },
  2643. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  2644. // Given a MouseEvent object, returns geographical coordinate where the
  2645. // event took place.
  2646. mouseEventToLatLng: function (e) { // (MouseEvent)
  2647. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  2648. },
  2649. // map initialization methods
  2650. _initContainer: function (id) {
  2651. var container = this._container = L.DomUtil.get(id);
  2652. if (!container) {
  2653. throw new Error('Map container not found.');
  2654. } else if (container._leaflet_id) {
  2655. throw new Error('Map container is already initialized.');
  2656. }
  2657. L.DomEvent.addListener(container, 'scroll', this._onScroll, this);
  2658. this._containerId = L.Util.stamp(container);
  2659. },
  2660. _initLayout: function () {
  2661. var container = this._container;
  2662. this._fadeAnimated = this.options.fadeAnimation && L.Browser.any3d;
  2663. L.DomUtil.addClass(container, 'leaflet-container' +
  2664. (L.Browser.touch ? ' leaflet-touch' : '') +
  2665. (L.Browser.retina ? ' leaflet-retina' : '') +
  2666. (L.Browser.ielt9 ? ' leaflet-oldie' : '') +
  2667. (L.Browser.safari ? ' leaflet-safari' : '') +
  2668. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  2669. var position = L.DomUtil.getStyle(container, 'position');
  2670. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  2671. container.style.position = 'relative';
  2672. }
  2673. this._initPanes();
  2674. if (this._initControlPos) {
  2675. this._initControlPos();
  2676. }
  2677. },
  2678. _initPanes: function () {
  2679. var panes = this._panes = {};
  2680. this._paneRenderers = {};
  2681. // @section
  2682. //
  2683. // Panes are DOM elements used to control the ordering of layers on the map. You
  2684. // can access panes with [`map.getPane`](#map-getpane) or
  2685. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  2686. // [`map.createPane`](#map-createpane) method.
  2687. //
  2688. // Every map has the following default panes that differ only in zIndex.
  2689. //
  2690. // @pane mapPane: HTMLElement = 'auto'
  2691. // Pane that contains all other map panes
  2692. this._mapPane = this.createPane('mapPane', this._container);
  2693. L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
  2694. // @pane tilePane: HTMLElement = 200
  2695. // Pane for `GridLayer`s and `TileLayer`s
  2696. this.createPane('tilePane');
  2697. // @pane overlayPane: HTMLElement = 400
  2698. // Pane for vector overlays (`Path`s), like `Polyline`s and `Polygon`s
  2699. this.createPane('shadowPane');
  2700. // @pane shadowPane: HTMLElement = 500
  2701. // Pane for overlay shadows (e.g. `Marker` shadows)
  2702. this.createPane('overlayPane');
  2703. // @pane markerPane: HTMLElement = 600
  2704. // Pane for `Icon`s of `Marker`s
  2705. this.createPane('markerPane');
  2706. // @pane tooltipPane: HTMLElement = 650
  2707. // Pane for tooltip.
  2708. this.createPane('tooltipPane');
  2709. // @pane popupPane: HTMLElement = 700
  2710. // Pane for `Popup`s.
  2711. this.createPane('popupPane');
  2712. if (!this.options.markerZoomAnimation) {
  2713. L.DomUtil.addClass(panes.markerPane, 'leaflet-zoom-hide');
  2714. L.DomUtil.addClass(panes.shadowPane, 'leaflet-zoom-hide');
  2715. }
  2716. },
  2717. // private methods that modify map state
  2718. // @section Map state change events
  2719. _resetView: function (center, zoom) {
  2720. L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
  2721. var loading = !this._loaded;
  2722. this._loaded = true;
  2723. zoom = this._limitZoom(zoom);
  2724. this.fire('viewprereset');
  2725. var zoomChanged = this._zoom !== zoom;
  2726. this
  2727. ._moveStart(zoomChanged)
  2728. ._move(center, zoom)
  2729. ._moveEnd(zoomChanged);
  2730. // @event viewreset: Event
  2731. // Fired when the map needs to redraw its content (this usually happens
  2732. // on map zoom or load). Very useful for creating custom overlays.
  2733. this.fire('viewreset');
  2734. // @event load: Event
  2735. // Fired when the map is initialized (when its center and zoom are set
  2736. // for the first time).
  2737. if (loading) {
  2738. this.fire('load');
  2739. }
  2740. },
  2741. _moveStart: function (zoomChanged) {
  2742. // @event zoomstart: Event
  2743. // Fired when the map zoom is about to change (e.g. before zoom animation).
  2744. // @event movestart: Event
  2745. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  2746. if (zoomChanged) {
  2747. this.fire('zoomstart');
  2748. }
  2749. return this.fire('movestart');
  2750. },
  2751. _move: function (center, zoom, data) {
  2752. if (zoom === undefined) {
  2753. zoom = this._zoom;
  2754. }
  2755. var zoomChanged = this._zoom !== zoom;
  2756. this._zoom = zoom;
  2757. this._lastCenter = center;
  2758. this._pixelOrigin = this._getNewPixelOrigin(center);
  2759. // @event zoom: Event
  2760. // Fired repeatedly during any change in zoom level, including zoom
  2761. // and fly animations.
  2762. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  2763. this.fire('zoom', data);
  2764. }
  2765. // @event move: Event
  2766. // Fired repeatedly during any movement of the map, including pan and
  2767. // fly animations.
  2768. return this.fire('move', data);
  2769. },
  2770. _moveEnd: function (zoomChanged) {
  2771. // @event zoomend: Event
  2772. // Fired when the map has changed, after any animations.
  2773. if (zoomChanged) {
  2774. this.fire('zoomend');
  2775. }
  2776. // @event moveend: Event
  2777. // Fired when the center of the map stops changing (e.g. user stopped
  2778. // dragging the map).
  2779. return this.fire('moveend');
  2780. },
  2781. _stop: function () {
  2782. L.Util.cancelAnimFrame(this._flyToFrame);
  2783. if (this._panAnim) {
  2784. this._panAnim.stop();
  2785. }
  2786. return this;
  2787. },
  2788. _rawPanBy: function (offset) {
  2789. L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  2790. },
  2791. _getZoomSpan: function () {
  2792. return this.getMaxZoom() - this.getMinZoom();
  2793. },
  2794. _panInsideMaxBounds: function () {
  2795. if (!this._enforcingBounds) {
  2796. this.panInsideBounds(this.options.maxBounds);
  2797. }
  2798. },
  2799. _checkIfLoaded: function () {
  2800. if (!this._loaded) {
  2801. throw new Error('Set map center and zoom first.');
  2802. }
  2803. },
  2804. // DOM event handling
  2805. // @section Interaction events
  2806. _initEvents: function (remove) {
  2807. if (!L.DomEvent) { return; }
  2808. this._targets = {};
  2809. this._targets[L.stamp(this._container)] = this;
  2810. var onOff = remove ? 'off' : 'on';
  2811. // @event click: MouseEvent
  2812. // Fired when the user clicks (or taps) the map.
  2813. // @event dblclick: MouseEvent
  2814. // Fired when the user double-clicks (or double-taps) the map.
  2815. // @event mousedown: MouseEvent
  2816. // Fired when the user pushes the mouse button on the map.
  2817. // @event mouseup: MouseEvent
  2818. // Fired when the user releases the mouse button on the map.
  2819. // @event mouseover: MouseEvent
  2820. // Fired when the mouse enters the map.
  2821. // @event mouseout: MouseEvent
  2822. // Fired when the mouse leaves the map.
  2823. // @event mousemove: MouseEvent
  2824. // Fired while the mouse moves over the map.
  2825. // @event contextmenu: MouseEvent
  2826. // Fired when the user pushes the right mouse button on the map, prevents
  2827. // default browser context menu from showing if there are listeners on
  2828. // this event. Also fired on mobile when the user holds a single touch
  2829. // for a second (also called long press).
  2830. // @event keypress: KeyboardEvent
  2831. // Fired when the user presses a key from the keyboard while the map is focused.
  2832. L.DomEvent[onOff](this._container, 'click dblclick mousedown mouseup ' +
  2833. 'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this);
  2834. if (this.options.trackResize) {
  2835. L.DomEvent[onOff](window, 'resize', this._onResize, this);
  2836. }
  2837. if (L.Browser.any3d && this.options.transform3DLimit) {
  2838. this[onOff]('moveend', this._onMoveEnd);
  2839. }
  2840. },
  2841. _onResize: function () {
  2842. L.Util.cancelAnimFrame(this._resizeRequest);
  2843. this._resizeRequest = L.Util.requestAnimFrame(
  2844. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  2845. },
  2846. _onScroll: function () {
  2847. this._container.scrollTop = 0;
  2848. this._container.scrollLeft = 0;
  2849. },
  2850. _onMoveEnd: function () {
  2851. var pos = this._getMapPanePos();
  2852. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  2853. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  2854. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  2855. this._resetView(this.getCenter(), this.getZoom());
  2856. }
  2857. },
  2858. _findEventTargets: function (e, type) {
  2859. var targets = [],
  2860. target,
  2861. isHover = type === 'mouseout' || type === 'mouseover',
  2862. src = e.target || e.srcElement,
  2863. dragging = false;
  2864. while (src) {
  2865. target = this._targets[L.stamp(src)];
  2866. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  2867. // Prevent firing click after you just dragged an object.
  2868. dragging = true;
  2869. break;
  2870. }
  2871. if (target && target.listens(type, true)) {
  2872. if (isHover && !L.DomEvent._isExternalTarget(src, e)) { break; }
  2873. targets.push(target);
  2874. if (isHover) { break; }
  2875. }
  2876. if (src === this._container) { break; }
  2877. src = src.parentNode;
  2878. }
  2879. if (!targets.length && !dragging && !isHover && L.DomEvent._isExternalTarget(src, e)) {
  2880. targets = [this];
  2881. }
  2882. return targets;
  2883. },
  2884. _handleDOMEvent: function (e) {
  2885. if (!this._loaded || L.DomEvent._skipped(e)) { return; }
  2886. var type = e.type === 'keypress' && e.keyCode === 13 ? 'click' : e.type;
  2887. if (type === 'mousedown') {
  2888. // prevents outline when clicking on keyboard-focusable element
  2889. L.DomUtil.preventOutline(e.target || e.srcElement);
  2890. }
  2891. this._fireDOMEvent(e, type);
  2892. },
  2893. _fireDOMEvent: function (e, type, targets) {
  2894. if (e.type === 'click') {
  2895. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  2896. // @event preclick: MouseEvent
  2897. // Fired before mouse click on the map (sometimes useful when you
  2898. // want something to happen on click before any existing click
  2899. // handlers start running).
  2900. var synth = L.Util.extend({}, e);
  2901. synth.type = 'preclick';
  2902. this._fireDOMEvent(synth, synth.type, targets);
  2903. }
  2904. if (e._stopped) { return; }
  2905. // Find the layer the event is propagating from and its parents.
  2906. targets = (targets || []).concat(this._findEventTargets(e, type));
  2907. if (!targets.length) { return; }
  2908. var target = targets[0];
  2909. if (type === 'contextmenu' && target.listens(type, true)) {
  2910. L.DomEvent.preventDefault(e);
  2911. }
  2912. var data = {
  2913. originalEvent: e
  2914. };
  2915. if (e.type !== 'keypress') {
  2916. var isMarker = target instanceof L.Marker;
  2917. data.containerPoint = isMarker ?
  2918. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  2919. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  2920. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  2921. }
  2922. for (var i = 0; i < targets.length; i++) {
  2923. targets[i].fire(type, data, true);
  2924. if (data.originalEvent._stopped ||
  2925. (targets[i].options.nonBubblingEvents && L.Util.indexOf(targets[i].options.nonBubblingEvents, type) !== -1)) { return; }
  2926. }
  2927. },
  2928. _draggableMoved: function (obj) {
  2929. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  2930. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  2931. },
  2932. _clearHandlers: function () {
  2933. for (var i = 0, len = this._handlers.length; i < len; i++) {
  2934. this._handlers[i].disable();
  2935. }
  2936. },
  2937. // @section Other Methods
  2938. // @method whenReady(fn: Function, context?: Object): this
  2939. // Runs the given function `fn` when the map gets initialized with
  2940. // a view (center and zoom) and at least one layer, or immediately
  2941. // if it's already initialized, optionally passing a function context.
  2942. whenReady: function (callback, context) {
  2943. if (this._loaded) {
  2944. callback.call(context || this, {target: this});
  2945. } else {
  2946. this.on('load', callback, context);
  2947. }
  2948. return this;
  2949. },
  2950. // private methods for getting map state
  2951. _getMapPanePos: function () {
  2952. return L.DomUtil.getPosition(this._mapPane) || new L.Point(0, 0);
  2953. },
  2954. _moved: function () {
  2955. var pos = this._getMapPanePos();
  2956. return pos && !pos.equals([0, 0]);
  2957. },
  2958. _getTopLeftPoint: function (center, zoom) {
  2959. var pixelOrigin = center && zoom !== undefined ?
  2960. this._getNewPixelOrigin(center, zoom) :
  2961. this.getPixelOrigin();
  2962. return pixelOrigin.subtract(this._getMapPanePos());
  2963. },
  2964. _getNewPixelOrigin: function (center, zoom) {
  2965. var viewHalf = this.getSize()._divideBy(2);
  2966. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  2967. },
  2968. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  2969. var topLeft = this._getNewPixelOrigin(center, zoom);
  2970. return this.project(latlng, zoom)._subtract(topLeft);
  2971. },
  2972. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  2973. var topLeft = this._getNewPixelOrigin(center, zoom);
  2974. return L.bounds([
  2975. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  2976. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  2977. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  2978. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  2979. ]);
  2980. },
  2981. // layer point of the current center
  2982. _getCenterLayerPoint: function () {
  2983. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  2984. },
  2985. // offset of the specified place to the current center in pixels
  2986. _getCenterOffset: function (latlng) {
  2987. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  2988. },
  2989. // adjust center for view to get inside bounds
  2990. _limitCenter: function (center, zoom, bounds) {
  2991. if (!bounds) { return center; }
  2992. var centerPoint = this.project(center, zoom),
  2993. viewHalf = this.getSize().divideBy(2),
  2994. viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  2995. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  2996. // If offset is less than a pixel, ignore.
  2997. // This prevents unstable projections from getting into
  2998. // an infinite loop of tiny offsets.
  2999. if (offset.round().equals([0, 0])) {
  3000. return center;
  3001. }
  3002. return this.unproject(centerPoint.add(offset), zoom);
  3003. },
  3004. // adjust offset for view to get inside bounds
  3005. _limitOffset: function (offset, bounds) {
  3006. if (!bounds) { return offset; }
  3007. var viewBounds = this.getPixelBounds(),
  3008. newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3009. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3010. },
  3011. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3012. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3013. var projectedMaxBounds = L.bounds(
  3014. this.project(maxBounds.getNorthEast(), zoom),
  3015. this.project(maxBounds.getSouthWest(), zoom)
  3016. ),
  3017. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3018. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3019. dx = this._rebound(minOffset.x, -maxOffset.x),
  3020. dy = this._rebound(minOffset.y, -maxOffset.y);
  3021. return new L.Point(dx, dy);
  3022. },
  3023. _rebound: function (left, right) {
  3024. return left + right > 0 ?
  3025. Math.round(left - right) / 2 :
  3026. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3027. },
  3028. _limitZoom: function (zoom) {
  3029. var min = this.getMinZoom(),
  3030. max = this.getMaxZoom(),
  3031. snap = L.Browser.any3d ? this.options.zoomSnap : 1;
  3032. if (snap) {
  3033. zoom = Math.round(zoom / snap) * snap;
  3034. }
  3035. return Math.max(min, Math.min(max, zoom));
  3036. },
  3037. _onPanTransitionStep: function () {
  3038. this.fire('move');
  3039. },
  3040. _onPanTransitionEnd: function () {
  3041. L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
  3042. this.fire('moveend');
  3043. },
  3044. _tryAnimatedPan: function (center, options) {
  3045. // difference between the new and current centers in pixels
  3046. var offset = this._getCenterOffset(center)._floor();
  3047. // don't animate too far unless animate: true specified in options
  3048. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3049. this.panBy(offset, options);
  3050. return true;
  3051. },
  3052. _createAnimProxy: function () {
  3053. var proxy = this._proxy = L.DomUtil.create('div', 'leaflet-proxy leaflet-zoom-animated');
  3054. this._panes.mapPane.appendChild(proxy);
  3055. this.on('zoomanim', function (e) {
  3056. var prop = L.DomUtil.TRANSFORM,
  3057. transform = proxy.style[prop];
  3058. L.DomUtil.setTransform(proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3059. // workaround for case when transform is the same and so transitionend event is not fired
  3060. if (transform === proxy.style[prop] && this._animatingZoom) {
  3061. this._onZoomTransitionEnd();
  3062. }
  3063. }, this);
  3064. this.on('load moveend', function () {
  3065. var c = this.getCenter(),
  3066. z = this.getZoom();
  3067. L.DomUtil.setTransform(proxy, this.project(c, z), this.getZoomScale(z, 1));
  3068. }, this);
  3069. },
  3070. _catchTransitionEnd: function (e) {
  3071. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3072. this._onZoomTransitionEnd();
  3073. }
  3074. },
  3075. _nothingToAnimate: function () {
  3076. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3077. },
  3078. _tryAnimatedZoom: function (center, zoom, options) {
  3079. if (this._animatingZoom) { return true; }
  3080. options = options || {};
  3081. // don't animate if disabled, not supported or zoom difference is too large
  3082. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3083. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3084. // offset is the pixel coords of the zoom origin relative to the current center
  3085. var scale = this.getZoomScale(zoom),
  3086. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3087. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3088. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3089. L.Util.requestAnimFrame(function () {
  3090. this
  3091. ._moveStart(true)
  3092. ._animateZoom(center, zoom, true);
  3093. }, this);
  3094. return true;
  3095. },
  3096. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3097. if (startAnim) {
  3098. this._animatingZoom = true;
  3099. // remember what center/zoom to set after animation
  3100. this._animateToCenter = center;
  3101. this._animateToZoom = zoom;
  3102. L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
  3103. }
  3104. // @event zoomanim: ZoomAnimEvent
  3105. // Fired on every frame of a zoom animation
  3106. this.fire('zoomanim', {
  3107. center: center,
  3108. zoom: zoom,
  3109. noUpdate: noUpdate
  3110. });
  3111. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3112. setTimeout(L.bind(this._onZoomTransitionEnd, this), 250);
  3113. },
  3114. _onZoomTransitionEnd: function () {
  3115. if (!this._animatingZoom) { return; }
  3116. L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
  3117. this._animatingZoom = false;
  3118. this._move(this._animateToCenter, this._animateToZoom);
  3119. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  3120. L.Util.requestAnimFrame(function () {
  3121. this._moveEnd(true);
  3122. }, this);
  3123. }
  3124. });
  3125. // @section
  3126. // @factory L.map(id: String, options?: Map options)
  3127. // Instantiates a map object given the DOM ID of a `<div>` element
  3128. // and optionally an object literal with `Map options`.
  3129. //
  3130. // @alternative
  3131. // @factory L.map(el: HTMLElement, options?: Map options)
  3132. // Instantiates a map object given an instance of a `<div>` HTML element
  3133. // and optionally an object literal with `Map options`.
  3134. L.map = function (id, options) {
  3135. return new L.Map(id, options);
  3136. };
  3137. /*
  3138. * @class Layer
  3139. * @inherits Evented
  3140. * @aka L.Layer
  3141. * @aka ILayer
  3142. *
  3143. * A set of methods from the Layer base class that all Leaflet layers use.
  3144. * Inherits all methods, options and events from `L.Evented`.
  3145. *
  3146. * @example
  3147. *
  3148. * ```js
  3149. * var layer = L.Marker(latlng).addTo(map);
  3150. * layer.addTo(map);
  3151. * layer.remove();
  3152. * ```
  3153. *
  3154. * @event add: Event
  3155. * Fired after the layer is added to a map
  3156. *
  3157. * @event remove: Event
  3158. * Fired after the layer is removed from a map
  3159. */
  3160. L.Layer = L.Evented.extend({
  3161. // Classes extending `L.Layer` will inherit the following options:
  3162. options: {
  3163. // @option pane: String = 'overlayPane'
  3164. // By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default.
  3165. pane: 'overlayPane',
  3166. nonBubblingEvents: [], // Array of events that should not be bubbled to DOM parents (like the map),
  3167. // @option attribution: String = null
  3168. // String to be shown in the attribution control, describes the layer data, e.g. "© Mapbox".
  3169. attribution: null
  3170. },
  3171. /* @section
  3172. * Classes extending `L.Layer` will inherit the following methods:
  3173. *
  3174. * @method addTo(map: Map): this
  3175. * Adds the layer to the given map
  3176. */
  3177. addTo: function (map) {
  3178. map.addLayer(this);
  3179. return this;
  3180. },
  3181. // @method remove: this
  3182. // Removes the layer from the map it is currently active on.
  3183. remove: function () {
  3184. return this.removeFrom(this._map || this._mapToAdd);
  3185. },
  3186. // @method removeFrom(map: Map): this
  3187. // Removes the layer from the given map
  3188. removeFrom: function (obj) {
  3189. if (obj) {
  3190. obj.removeLayer(this);
  3191. }
  3192. return this;
  3193. },
  3194. // @method getPane(name? : String): HTMLElement
  3195. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  3196. getPane: function (name) {
  3197. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  3198. },
  3199. addInteractiveTarget: function (targetEl) {
  3200. this._map._targets[L.stamp(targetEl)] = this;
  3201. return this;
  3202. },
  3203. removeInteractiveTarget: function (targetEl) {
  3204. delete this._map._targets[L.stamp(targetEl)];
  3205. return this;
  3206. },
  3207. // @method getAttribution: String
  3208. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  3209. getAttribution: function () {
  3210. return this.options.attribution;
  3211. },
  3212. _layerAdd: function (e) {
  3213. var map = e.target;
  3214. // check in case layer gets added and then removed before the map is ready
  3215. if (!map.hasLayer(this)) { return; }
  3216. this._map = map;
  3217. this._zoomAnimated = map._zoomAnimated;
  3218. if (this.getEvents) {
  3219. var events = this.getEvents();
  3220. map.on(events, this);
  3221. this.once('remove', function () {
  3222. map.off(events, this);
  3223. }, this);
  3224. }
  3225. this.onAdd(map);
  3226. if (this.getAttribution && map.attributionControl) {
  3227. map.attributionControl.addAttribution(this.getAttribution());
  3228. }
  3229. this.fire('add');
  3230. map.fire('layeradd', {layer: this});
  3231. }
  3232. });
  3233. /* @section Extension methods
  3234. * @uninheritable
  3235. *
  3236. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  3237. *
  3238. * @method onAdd(map: Map): this
  3239. * Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer).
  3240. *
  3241. * @method onRemove(map: Map): this
  3242. * Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer).
  3243. *
  3244. * @method getEvents(): Object
  3245. * This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#evented-addeventlistener). The event handlers in this object will be automatically added and removed from the map with your layer.
  3246. *
  3247. * @method getAttribution(): String
  3248. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  3249. *
  3250. * @method beforeAdd(map: Map): this
  3251. * Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only.
  3252. */
  3253. /* @namespace Map
  3254. * @section Layer events
  3255. *
  3256. * @event layeradd: LayerEvent
  3257. * Fired when a new layer is added to the map.
  3258. *
  3259. * @event layerremove: LayerEvent
  3260. * Fired when some layer is removed from the map
  3261. *
  3262. * @section Methods for Layers and Controls
  3263. */
  3264. L.Map.include({
  3265. // @method addLayer(layer: Layer): this
  3266. // Adds the given layer to the map
  3267. addLayer: function (layer) {
  3268. var id = L.stamp(layer);
  3269. if (this._layers[id]) { return this; }
  3270. this._layers[id] = layer;
  3271. layer._mapToAdd = this;
  3272. if (layer.beforeAdd) {
  3273. layer.beforeAdd(this);
  3274. }
  3275. this.whenReady(layer._layerAdd, layer);
  3276. return this;
  3277. },
  3278. // @method removeLayer(layer: Layer): this
  3279. // Removes the given layer from the map.
  3280. removeLayer: function (layer) {
  3281. var id = L.stamp(layer);
  3282. if (!this._layers[id]) { return this; }
  3283. if (this._loaded) {
  3284. layer.onRemove(this);
  3285. }
  3286. if (layer.getAttribution && this.attributionControl) {
  3287. this.attributionControl.removeAttribution(layer.getAttribution());
  3288. }
  3289. delete this._layers[id];
  3290. if (this._loaded) {
  3291. this.fire('layerremove', {layer: layer});
  3292. layer.fire('remove');
  3293. }
  3294. layer._map = layer._mapToAdd = null;
  3295. return this;
  3296. },
  3297. // @method hasLayer(layer: Layer): Boolean
  3298. // Returns `true` if the given layer is currently added to the map
  3299. hasLayer: function (layer) {
  3300. return !!layer && (L.stamp(layer) in this._layers);
  3301. },
  3302. /* @method eachLayer(fn: Function, context?: Object): this
  3303. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  3304. * ```
  3305. * map.eachLayer(function(layer){
  3306. * layer.bindPopup('Hello');
  3307. * });
  3308. * ```
  3309. */
  3310. eachLayer: function (method, context) {
  3311. for (var i in this._layers) {
  3312. method.call(context, this._layers[i]);
  3313. }
  3314. return this;
  3315. },
  3316. _addLayers: function (layers) {
  3317. layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
  3318. for (var i = 0, len = layers.length; i < len; i++) {
  3319. this.addLayer(layers[i]);
  3320. }
  3321. },
  3322. _addZoomLimit: function (layer) {
  3323. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  3324. this._zoomBoundLayers[L.stamp(layer)] = layer;
  3325. this._updateZoomLevels();
  3326. }
  3327. },
  3328. _removeZoomLimit: function (layer) {
  3329. var id = L.stamp(layer);
  3330. if (this._zoomBoundLayers[id]) {
  3331. delete this._zoomBoundLayers[id];
  3332. this._updateZoomLevels();
  3333. }
  3334. },
  3335. _updateZoomLevels: function () {
  3336. var minZoom = Infinity,
  3337. maxZoom = -Infinity,
  3338. oldZoomSpan = this._getZoomSpan();
  3339. for (var i in this._zoomBoundLayers) {
  3340. var options = this._zoomBoundLayers[i].options;
  3341. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  3342. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  3343. }
  3344. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  3345. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  3346. // @section Map state change events
  3347. // @event zoomlevelschange: Event
  3348. // Fired when the number of zoomlevels on the map is changed due
  3349. // to adding or removing a layer.
  3350. if (oldZoomSpan !== this._getZoomSpan()) {
  3351. this.fire('zoomlevelschange');
  3352. }
  3353. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  3354. this.setZoom(this._layersMaxZoom);
  3355. }
  3356. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  3357. this.setZoom(this._layersMinZoom);
  3358. }
  3359. }
  3360. });
  3361. /*
  3362. * @namespace DomEvent
  3363. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  3364. */
  3365. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  3366. var eventsKey = '_leaflet_events';
  3367. L.DomEvent = {
  3368. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  3369. // Adds a listener function (`fn`) to a particular DOM event type of the
  3370. // element `el`. You can optionally specify the context of the listener
  3371. // (object the `this` keyword will point to). You can also pass several
  3372. // space-separated types (e.g. `'click dblclick'`).
  3373. // @alternative
  3374. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  3375. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  3376. on: function (obj, types, fn, context) {
  3377. if (typeof types === 'object') {
  3378. for (var type in types) {
  3379. this._on(obj, type, types[type], fn);
  3380. }
  3381. } else {
  3382. types = L.Util.splitWords(types);
  3383. for (var i = 0, len = types.length; i < len; i++) {
  3384. this._on(obj, types[i], fn, context);
  3385. }
  3386. }
  3387. return this;
  3388. },
  3389. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  3390. // Removes a previously added listener function. If no function is specified,
  3391. // it will remove all the listeners of that particular DOM event from the element.
  3392. // Note that if you passed a custom context to on, you must pass the same
  3393. // context to `off` in order to remove the listener.
  3394. // @alternative
  3395. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  3396. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  3397. off: function (obj, types, fn, context) {
  3398. if (typeof types === 'object') {
  3399. for (var type in types) {
  3400. this._off(obj, type, types[type], fn);
  3401. }
  3402. } else {
  3403. types = L.Util.splitWords(types);
  3404. for (var i = 0, len = types.length; i < len; i++) {
  3405. this._off(obj, types[i], fn, context);
  3406. }
  3407. }
  3408. return this;
  3409. },
  3410. _on: function (obj, type, fn, context) {
  3411. var id = type + L.stamp(fn) + (context ? '_' + L.stamp(context) : '');
  3412. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  3413. var handler = function (e) {
  3414. return fn.call(context || obj, e || window.event);
  3415. };
  3416. var originalHandler = handler;
  3417. if (L.Browser.pointer && type.indexOf('touch') === 0) {
  3418. this.addPointerListener(obj, type, handler, id);
  3419. } else if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener &&
  3420. !(L.Browser.pointer && L.Browser.chrome)) {
  3421. // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener
  3422. // See #5180
  3423. this.addDoubleTapListener(obj, handler, id);
  3424. } else if ('addEventListener' in obj) {
  3425. if (type === 'mousewheel') {
  3426. obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  3427. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  3428. handler = function (e) {
  3429. e = e || window.event;
  3430. if (L.DomEvent._isExternalTarget(obj, e)) {
  3431. originalHandler(e);
  3432. }
  3433. };
  3434. obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
  3435. } else {
  3436. if (type === 'click' && L.Browser.android) {
  3437. handler = function (e) {
  3438. return L.DomEvent._filterClick(e, originalHandler);
  3439. };
  3440. }
  3441. obj.addEventListener(type, handler, false);
  3442. }
  3443. } else if ('attachEvent' in obj) {
  3444. obj.attachEvent('on' + type, handler);
  3445. }
  3446. obj[eventsKey] = obj[eventsKey] || {};
  3447. obj[eventsKey][id] = handler;
  3448. return this;
  3449. },
  3450. _off: function (obj, type, fn, context) {
  3451. var id = type + L.stamp(fn) + (context ? '_' + L.stamp(context) : ''),
  3452. handler = obj[eventsKey] && obj[eventsKey][id];
  3453. if (!handler) { return this; }
  3454. if (L.Browser.pointer && type.indexOf('touch') === 0) {
  3455. this.removePointerListener(obj, type, id);
  3456. } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
  3457. this.removeDoubleTapListener(obj, id);
  3458. } else if ('removeEventListener' in obj) {
  3459. if (type === 'mousewheel') {
  3460. obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  3461. } else {
  3462. obj.removeEventListener(
  3463. type === 'mouseenter' ? 'mouseover' :
  3464. type === 'mouseleave' ? 'mouseout' : type, handler, false);
  3465. }
  3466. } else if ('detachEvent' in obj) {
  3467. obj.detachEvent('on' + type, handler);
  3468. }
  3469. obj[eventsKey][id] = null;
  3470. return this;
  3471. },
  3472. // @function stopPropagation(ev: DOMEvent): this
  3473. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  3474. // ```js
  3475. // L.DomEvent.on(div, 'click', function (ev) {
  3476. // L.DomEvent.stopPropagation(ev);
  3477. // });
  3478. // ```
  3479. stopPropagation: function (e) {
  3480. if (e.stopPropagation) {
  3481. e.stopPropagation();
  3482. } else if (e.originalEvent) { // In case of Leaflet event.
  3483. e.originalEvent._stopped = true;
  3484. } else {
  3485. e.cancelBubble = true;
  3486. }
  3487. L.DomEvent._skipped(e);
  3488. return this;
  3489. },
  3490. // @function disableScrollPropagation(el: HTMLElement): this
  3491. // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
  3492. disableScrollPropagation: function (el) {
  3493. return L.DomEvent.on(el, 'mousewheel', L.DomEvent.stopPropagation);
  3494. },
  3495. // @function disableClickPropagation(el: HTMLElement): this
  3496. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  3497. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  3498. disableClickPropagation: function (el) {
  3499. var stop = L.DomEvent.stopPropagation;
  3500. L.DomEvent.on(el, L.Draggable.START.join(' '), stop);
  3501. return L.DomEvent.on(el, {
  3502. click: L.DomEvent._fakeStop,
  3503. dblclick: stop
  3504. });
  3505. },
  3506. // @function preventDefault(ev: DOMEvent): this
  3507. // Prevents the default action of the DOM Event `ev` from happening (such as
  3508. // following a link in the href of the a element, or doing a POST request
  3509. // with page reload when a `<form>` is submitted).
  3510. // Use it inside listener functions.
  3511. preventDefault: function (e) {
  3512. if (e.preventDefault) {
  3513. e.preventDefault();
  3514. } else {
  3515. e.returnValue = false;
  3516. }
  3517. return this;
  3518. },
  3519. // @function stop(ev): this
  3520. // Does `stopPropagation` and `preventDefault` at the same time.
  3521. stop: function (e) {
  3522. return L.DomEvent
  3523. .preventDefault(e)
  3524. .stopPropagation(e);
  3525. },
  3526. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  3527. // Gets normalized mouse position from a DOM event relative to the
  3528. // `container` or to the whole page if not specified.
  3529. getMousePosition: function (e, container) {
  3530. if (!container) {
  3531. return new L.Point(e.clientX, e.clientY);
  3532. }
  3533. var rect = container.getBoundingClientRect();
  3534. return new L.Point(
  3535. e.clientX - rect.left - container.clientLeft,
  3536. e.clientY - rect.top - container.clientTop);
  3537. },
  3538. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  3539. // and Firefox scrolls device pixels, not CSS pixels
  3540. _wheelPxFactor: (L.Browser.win && L.Browser.chrome) ? 2 :
  3541. L.Browser.gecko ? window.devicePixelRatio :
  3542. 1,
  3543. // @function getWheelDelta(ev: DOMEvent): Number
  3544. // Gets normalized wheel delta from a mousewheel DOM event, in vertical
  3545. // pixels scrolled (negative if scrolling down).
  3546. // Events from pointing devices without precise scrolling are mapped to
  3547. // a best guess of 60 pixels.
  3548. getWheelDelta: function (e) {
  3549. return (L.Browser.edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  3550. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / L.DomEvent._wheelPxFactor : // Pixels
  3551. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  3552. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  3553. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  3554. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  3555. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  3556. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  3557. 0;
  3558. },
  3559. _skipEvents: {},
  3560. _fakeStop: function (e) {
  3561. // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e)
  3562. L.DomEvent._skipEvents[e.type] = true;
  3563. },
  3564. _skipped: function (e) {
  3565. var skipped = this._skipEvents[e.type];
  3566. // reset when checking, as it's only used in map container and propagates outside of the map
  3567. this._skipEvents[e.type] = false;
  3568. return skipped;
  3569. },
  3570. // check if element really left/entered the event target (for mouseenter/mouseleave)
  3571. _isExternalTarget: function (el, e) {
  3572. var related = e.relatedTarget;
  3573. if (!related) { return true; }
  3574. try {
  3575. while (related && (related !== el)) {
  3576. related = related.parentNode;
  3577. }
  3578. } catch (err) {
  3579. return false;
  3580. }
  3581. return (related !== el);
  3582. },
  3583. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  3584. _filterClick: function (e, handler) {
  3585. var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
  3586. elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
  3587. // are they closer together than 500ms yet more than 100ms?
  3588. // Android typically triggers them ~300ms apart while multiple listeners
  3589. // on the same event should be triggered far faster;
  3590. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  3591. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  3592. L.DomEvent.stop(e);
  3593. return;
  3594. }
  3595. L.DomEvent._lastClick = timeStamp;
  3596. handler(e);
  3597. }
  3598. };
  3599. // @function addListener(…): this
  3600. // Alias to [`L.DomEvent.on`](#domevent-on)
  3601. L.DomEvent.addListener = L.DomEvent.on;
  3602. // @function removeListener(…): this
  3603. // Alias to [`L.DomEvent.off`](#domevent-off)
  3604. L.DomEvent.removeListener = L.DomEvent.off;
  3605. /*
  3606. * @class PosAnimation
  3607. * @aka L.PosAnimation
  3608. * @inherits Evented
  3609. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  3610. *
  3611. * @example
  3612. * ```js
  3613. * var fx = new L.PosAnimation();
  3614. * fx.run(el, [300, 500], 0.5);
  3615. * ```
  3616. *
  3617. * @constructor L.PosAnimation()
  3618. * Creates a `PosAnimation` object.
  3619. *
  3620. */
  3621. L.PosAnimation = L.Evented.extend({
  3622. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  3623. // Run an animation of a given element to a new position, optionally setting
  3624. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  3625. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  3626. // `0.5` by default).
  3627. run: function (el, newPos, duration, easeLinearity) {
  3628. this.stop();
  3629. this._el = el;
  3630. this._inProgress = true;
  3631. this._duration = duration || 0.25;
  3632. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  3633. this._startPos = L.DomUtil.getPosition(el);
  3634. this._offset = newPos.subtract(this._startPos);
  3635. this._startTime = +new Date();
  3636. // @event start: Event
  3637. // Fired when the animation starts
  3638. this.fire('start');
  3639. this._animate();
  3640. },
  3641. // @method stop()
  3642. // Stops the animation (if currently running).
  3643. stop: function () {
  3644. if (!this._inProgress) { return; }
  3645. this._step(true);
  3646. this._complete();
  3647. },
  3648. _animate: function () {
  3649. // animation loop
  3650. this._animId = L.Util.requestAnimFrame(this._animate, this);
  3651. this._step();
  3652. },
  3653. _step: function (round) {
  3654. var elapsed = (+new Date()) - this._startTime,
  3655. duration = this._duration * 1000;
  3656. if (elapsed < duration) {
  3657. this._runFrame(this._easeOut(elapsed / duration), round);
  3658. } else {
  3659. this._runFrame(1);
  3660. this._complete();
  3661. }
  3662. },
  3663. _runFrame: function (progress, round) {
  3664. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  3665. if (round) {
  3666. pos._round();
  3667. }
  3668. L.DomUtil.setPosition(this._el, pos);
  3669. // @event step: Event
  3670. // Fired continuously during the animation.
  3671. this.fire('step');
  3672. },
  3673. _complete: function () {
  3674. L.Util.cancelAnimFrame(this._animId);
  3675. this._inProgress = false;
  3676. // @event end: Event
  3677. // Fired when the animation ends.
  3678. this.fire('end');
  3679. },
  3680. _easeOut: function (t) {
  3681. return 1 - Math.pow(1 - t, this._easeOutPower);
  3682. }
  3683. });
  3684. /*
  3685. * @namespace Projection
  3686. * @projection L.Projection.Mercator
  3687. *
  3688. * Elliptical Mercator projection — more complex than Spherical Mercator. Takes into account that Earth is a geoid, not a perfect sphere. Used by the EPSG:3395 CRS.
  3689. */
  3690. L.Projection.Mercator = {
  3691. R: 6378137,
  3692. R_MINOR: 6356752.314245179,
  3693. bounds: L.bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  3694. project: function (latlng) {
  3695. var d = Math.PI / 180,
  3696. r = this.R,
  3697. y = latlng.lat * d,
  3698. tmp = this.R_MINOR / r,
  3699. e = Math.sqrt(1 - tmp * tmp),
  3700. con = e * Math.sin(y);
  3701. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  3702. y = -r * Math.log(Math.max(ts, 1E-10));
  3703. return new L.Point(latlng.lng * d * r, y);
  3704. },
  3705. unproject: function (point) {
  3706. var d = 180 / Math.PI,
  3707. r = this.R,
  3708. tmp = this.R_MINOR / r,
  3709. e = Math.sqrt(1 - tmp * tmp),
  3710. ts = Math.exp(-point.y / r),
  3711. phi = Math.PI / 2 - 2 * Math.atan(ts);
  3712. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  3713. con = e * Math.sin(phi);
  3714. con = Math.pow((1 - con) / (1 + con), e / 2);
  3715. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  3716. phi += dphi;
  3717. }
  3718. return new L.LatLng(phi * d, point.x * d / r);
  3719. }
  3720. };
  3721. /*
  3722. * @namespace CRS
  3723. * @crs L.CRS.EPSG3395
  3724. *
  3725. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  3726. */
  3727. L.CRS.EPSG3395 = L.extend({}, L.CRS.Earth, {
  3728. code: 'EPSG:3395',
  3729. projection: L.Projection.Mercator,
  3730. transformation: (function () {
  3731. var scale = 0.5 / (Math.PI * L.Projection.Mercator.R);
  3732. return new L.Transformation(scale, 0.5, -scale, 0.5);
  3733. }())
  3734. });
  3735. /*
  3736. * @class GridLayer
  3737. * @inherits Layer
  3738. * @aka L.GridLayer
  3739. *
  3740. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  3741. * GridLayer can be extended to create a tiled grid of HTML elements like `<canvas>`, `<img>` or `<div>`. GridLayer will handle creating and animating these DOM elements for you.
  3742. *
  3743. *
  3744. * @section Synchronous usage
  3745. * @example
  3746. *
  3747. * To create a custom layer, extend GridLayer and implement the `createTile()` method, which will be passed a `Point` object with the `x`, `y`, and `z` (zoom level) coordinates to draw your tile.
  3748. *
  3749. * ```js
  3750. * var CanvasLayer = L.GridLayer.extend({
  3751. * createTile: function(coords){
  3752. * // create a <canvas> element for drawing
  3753. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  3754. *
  3755. * // setup tile width and height according to the options
  3756. * var size = this.getTileSize();
  3757. * tile.width = size.x;
  3758. * tile.height = size.y;
  3759. *
  3760. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  3761. * var ctx = tile.getContext('2d');
  3762. *
  3763. * // return the tile so it can be rendered on screen
  3764. * return tile;
  3765. * }
  3766. * });
  3767. * ```
  3768. *
  3769. * @section Asynchronous usage
  3770. * @example
  3771. *
  3772. * Tile creation can also be asynchronous, this is useful when using a third-party drawing library. Once the tile is finished drawing it can be passed to the `done()` callback.
  3773. *
  3774. * ```js
  3775. * var CanvasLayer = L.GridLayer.extend({
  3776. * createTile: function(coords, done){
  3777. * var error;
  3778. *
  3779. * // create a <canvas> element for drawing
  3780. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  3781. *
  3782. * // setup tile width and height according to the options
  3783. * var size = this.getTileSize();
  3784. * tile.width = size.x;
  3785. * tile.height = size.y;
  3786. *
  3787. * // draw something asynchronously and pass the tile to the done() callback
  3788. * setTimeout(function() {
  3789. * done(error, tile);
  3790. * }, 1000);
  3791. *
  3792. * return tile;
  3793. * }
  3794. * });
  3795. * ```
  3796. *
  3797. * @section
  3798. */
  3799. L.GridLayer = L.Layer.extend({
  3800. // @section
  3801. // @aka GridLayer options
  3802. options: {
  3803. // @option tileSize: Number|Point = 256
  3804. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  3805. tileSize: 256,
  3806. // @option opacity: Number = 1.0
  3807. // Opacity of the tiles. Can be used in the `createTile()` function.
  3808. opacity: 1,
  3809. // @option updateWhenIdle: Boolean = depends
  3810. // If `false`, new tiles are loaded during panning, otherwise only after it (for better performance). `true` by default on mobile browsers, otherwise `false`.
  3811. updateWhenIdle: L.Browser.mobile,
  3812. // @option updateWhenZooming: Boolean = true
  3813. // By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends.
  3814. updateWhenZooming: true,
  3815. // @option updateInterval: Number = 200
  3816. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  3817. updateInterval: 200,
  3818. // @option zIndex: Number = 1
  3819. // The explicit zIndex of the tile layer.
  3820. zIndex: 1,
  3821. // @option bounds: LatLngBounds = undefined
  3822. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  3823. bounds: null,
  3824. // @option minZoom: Number = 0
  3825. // The minimum zoom level that tiles will be loaded at. By default the entire map.
  3826. minZoom: 0,
  3827. // @option maxZoom: Number = undefined
  3828. // The maximum zoom level that tiles will be loaded at.
  3829. maxZoom: undefined,
  3830. // @option noWrap: Boolean = false
  3831. // Whether the layer is wrapped around the antimeridian. If `true`, the
  3832. // GridLayer will only be displayed once at low zoom levels. Has no
  3833. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  3834. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  3835. // tiles outside the CRS limits.
  3836. noWrap: false,
  3837. // @option pane: String = 'tilePane'
  3838. // `Map pane` where the grid layer will be added.
  3839. pane: 'tilePane',
  3840. // @option className: String = ''
  3841. // A custom class name to assign to the tile layer. Empty by default.
  3842. className: '',
  3843. // @option keepBuffer: Number = 2
  3844. // When panning the map, keep this many rows and columns of tiles before unloading them.
  3845. keepBuffer: 2
  3846. },
  3847. initialize: function (options) {
  3848. L.setOptions(this, options);
  3849. },
  3850. onAdd: function () {
  3851. this._initContainer();
  3852. this._levels = {};
  3853. this._tiles = {};
  3854. this._resetView();
  3855. this._update();
  3856. },
  3857. beforeAdd: function (map) {
  3858. map._addZoomLimit(this);
  3859. },
  3860. onRemove: function (map) {
  3861. this._removeAllTiles();
  3862. L.DomUtil.remove(this._container);
  3863. map._removeZoomLimit(this);
  3864. this._container = null;
  3865. this._tileZoom = null;
  3866. },
  3867. // @method bringToFront: this
  3868. // Brings the tile layer to the top of all tile layers.
  3869. bringToFront: function () {
  3870. if (this._map) {
  3871. L.DomUtil.toFront(this._container);
  3872. this._setAutoZIndex(Math.max);
  3873. }
  3874. return this;
  3875. },
  3876. // @method bringToBack: this
  3877. // Brings the tile layer to the bottom of all tile layers.
  3878. bringToBack: function () {
  3879. if (this._map) {
  3880. L.DomUtil.toBack(this._container);
  3881. this._setAutoZIndex(Math.min);
  3882. }
  3883. return this;
  3884. },
  3885. // @method getContainer: HTMLElement
  3886. // Returns the HTML element that contains the tiles for this layer.
  3887. getContainer: function () {
  3888. return this._container;
  3889. },
  3890. // @method setOpacity(opacity: Number): this
  3891. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  3892. setOpacity: function (opacity) {
  3893. this.options.opacity = opacity;
  3894. this._updateOpacity();
  3895. return this;
  3896. },
  3897. // @method setZIndex(zIndex: Number): this
  3898. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  3899. setZIndex: function (zIndex) {
  3900. this.options.zIndex = zIndex;
  3901. this._updateZIndex();
  3902. return this;
  3903. },
  3904. // @method isLoading: Boolean
  3905. // Returns `true` if any tile in the grid layer has not finished loading.
  3906. isLoading: function () {
  3907. return this._loading;
  3908. },
  3909. // @method redraw: this
  3910. // Causes the layer to clear all the tiles and request them again.
  3911. redraw: function () {
  3912. if (this._map) {
  3913. this._removeAllTiles();
  3914. this._update();
  3915. }
  3916. return this;
  3917. },
  3918. getEvents: function () {
  3919. var events = {
  3920. viewprereset: this._invalidateAll,
  3921. viewreset: this._resetView,
  3922. zoom: this._resetView,
  3923. moveend: this._onMoveEnd
  3924. };
  3925. if (!this.options.updateWhenIdle) {
  3926. // update tiles on move, but not more often than once per given interval
  3927. if (!this._onMove) {
  3928. this._onMove = L.Util.throttle(this._onMoveEnd, this.options.updateInterval, this);
  3929. }
  3930. events.move = this._onMove;
  3931. }
  3932. if (this._zoomAnimated) {
  3933. events.zoomanim = this._animateZoom;
  3934. }
  3935. return events;
  3936. },
  3937. // @section Extension methods
  3938. // Layers extending `GridLayer` shall reimplement the following method.
  3939. // @method createTile(coords: Object, done?: Function): HTMLElement
  3940. // Called only internally, must be overriden by classes extending `GridLayer`.
  3941. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  3942. // is specified, it must be called when the tile has finished loading and drawing.
  3943. createTile: function () {
  3944. return document.createElement('div');
  3945. },
  3946. // @section
  3947. // @method getTileSize: Point
  3948. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  3949. getTileSize: function () {
  3950. var s = this.options.tileSize;
  3951. return s instanceof L.Point ? s : new L.Point(s, s);
  3952. },
  3953. _updateZIndex: function () {
  3954. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  3955. this._container.style.zIndex = this.options.zIndex;
  3956. }
  3957. },
  3958. _setAutoZIndex: function (compare) {
  3959. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  3960. var layers = this.getPane().children,
  3961. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  3962. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  3963. zIndex = layers[i].style.zIndex;
  3964. if (layers[i] !== this._container && zIndex) {
  3965. edgeZIndex = compare(edgeZIndex, +zIndex);
  3966. }
  3967. }
  3968. if (isFinite(edgeZIndex)) {
  3969. this.options.zIndex = edgeZIndex + compare(-1, 1);
  3970. this._updateZIndex();
  3971. }
  3972. },
  3973. _updateOpacity: function () {
  3974. if (!this._map) { return; }
  3975. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  3976. if (L.Browser.ielt9) { return; }
  3977. L.DomUtil.setOpacity(this._container, this.options.opacity);
  3978. var now = +new Date(),
  3979. nextFrame = false,
  3980. willPrune = false;
  3981. for (var key in this._tiles) {
  3982. var tile = this._tiles[key];
  3983. if (!tile.current || !tile.loaded) { continue; }
  3984. var fade = Math.min(1, (now - tile.loaded) / 200);
  3985. L.DomUtil.setOpacity(tile.el, fade);
  3986. if (fade < 1) {
  3987. nextFrame = true;
  3988. } else {
  3989. if (tile.active) { willPrune = true; }
  3990. tile.active = true;
  3991. }
  3992. }
  3993. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  3994. if (nextFrame) {
  3995. L.Util.cancelAnimFrame(this._fadeFrame);
  3996. this._fadeFrame = L.Util.requestAnimFrame(this._updateOpacity, this);
  3997. }
  3998. },
  3999. _initContainer: function () {
  4000. if (this._container) { return; }
  4001. this._container = L.DomUtil.create('div', 'leaflet-layer ' + (this.options.className || ''));
  4002. this._updateZIndex();
  4003. if (this.options.opacity < 1) {
  4004. this._updateOpacity();
  4005. }
  4006. this.getPane().appendChild(this._container);
  4007. },
  4008. _updateLevels: function () {
  4009. var zoom = this._tileZoom,
  4010. maxZoom = this.options.maxZoom;
  4011. if (zoom === undefined) { return undefined; }
  4012. for (var z in this._levels) {
  4013. if (this._levels[z].el.children.length || z === zoom) {
  4014. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  4015. } else {
  4016. L.DomUtil.remove(this._levels[z].el);
  4017. this._removeTilesAtZoom(z);
  4018. delete this._levels[z];
  4019. }
  4020. }
  4021. var level = this._levels[zoom],
  4022. map = this._map;
  4023. if (!level) {
  4024. level = this._levels[zoom] = {};
  4025. level.el = L.DomUtil.create('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  4026. level.el.style.zIndex = maxZoom;
  4027. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  4028. level.zoom = zoom;
  4029. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  4030. // force the browser to consider the newly added element for transition
  4031. L.Util.falseFn(level.el.offsetWidth);
  4032. }
  4033. this._level = level;
  4034. return level;
  4035. },
  4036. _pruneTiles: function () {
  4037. if (!this._map) {
  4038. return;
  4039. }
  4040. var key, tile;
  4041. var zoom = this._map.getZoom();
  4042. if (zoom > this.options.maxZoom ||
  4043. zoom < this.options.minZoom) {
  4044. this._removeAllTiles();
  4045. return;
  4046. }
  4047. for (key in this._tiles) {
  4048. tile = this._tiles[key];
  4049. tile.retain = tile.current;
  4050. }
  4051. for (key in this._tiles) {
  4052. tile = this._tiles[key];
  4053. if (tile.current && !tile.active) {
  4054. var coords = tile.coords;
  4055. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  4056. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  4057. }
  4058. }
  4059. }
  4060. for (key in this._tiles) {
  4061. if (!this._tiles[key].retain) {
  4062. this._removeTile(key);
  4063. }
  4064. }
  4065. },
  4066. _removeTilesAtZoom: function (zoom) {
  4067. for (var key in this._tiles) {
  4068. if (this._tiles[key].coords.z !== zoom) {
  4069. continue;
  4070. }
  4071. this._removeTile(key);
  4072. }
  4073. },
  4074. _removeAllTiles: function () {
  4075. for (var key in this._tiles) {
  4076. this._removeTile(key);
  4077. }
  4078. },
  4079. _invalidateAll: function () {
  4080. for (var z in this._levels) {
  4081. L.DomUtil.remove(this._levels[z].el);
  4082. delete this._levels[z];
  4083. }
  4084. this._removeAllTiles();
  4085. this._tileZoom = null;
  4086. },
  4087. _retainParent: function (x, y, z, minZoom) {
  4088. var x2 = Math.floor(x / 2),
  4089. y2 = Math.floor(y / 2),
  4090. z2 = z - 1,
  4091. coords2 = new L.Point(+x2, +y2);
  4092. coords2.z = +z2;
  4093. var key = this._tileCoordsToKey(coords2),
  4094. tile = this._tiles[key];
  4095. if (tile && tile.active) {
  4096. tile.retain = true;
  4097. return true;
  4098. } else if (tile && tile.loaded) {
  4099. tile.retain = true;
  4100. }
  4101. if (z2 > minZoom) {
  4102. return this._retainParent(x2, y2, z2, minZoom);
  4103. }
  4104. return false;
  4105. },
  4106. _retainChildren: function (x, y, z, maxZoom) {
  4107. for (var i = 2 * x; i < 2 * x + 2; i++) {
  4108. for (var j = 2 * y; j < 2 * y + 2; j++) {
  4109. var coords = new L.Point(i, j);
  4110. coords.z = z + 1;
  4111. var key = this._tileCoordsToKey(coords),
  4112. tile = this._tiles[key];
  4113. if (tile && tile.active) {
  4114. tile.retain = true;
  4115. continue;
  4116. } else if (tile && tile.loaded) {
  4117. tile.retain = true;
  4118. }
  4119. if (z + 1 < maxZoom) {
  4120. this._retainChildren(i, j, z + 1, maxZoom);
  4121. }
  4122. }
  4123. }
  4124. },
  4125. _resetView: function (e) {
  4126. var animating = e && (e.pinch || e.flyTo);
  4127. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  4128. },
  4129. _animateZoom: function (e) {
  4130. this._setView(e.center, e.zoom, true, e.noUpdate);
  4131. },
  4132. _setView: function (center, zoom, noPrune, noUpdate) {
  4133. var tileZoom = Math.round(zoom);
  4134. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  4135. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  4136. tileZoom = undefined;
  4137. }
  4138. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  4139. if (!noUpdate || tileZoomChanged) {
  4140. this._tileZoom = tileZoom;
  4141. if (this._abortLoading) {
  4142. this._abortLoading();
  4143. }
  4144. this._updateLevels();
  4145. this._resetGrid();
  4146. if (tileZoom !== undefined) {
  4147. this._update(center);
  4148. }
  4149. if (!noPrune) {
  4150. this._pruneTiles();
  4151. }
  4152. // Flag to prevent _updateOpacity from pruning tiles during
  4153. // a zoom anim or a pinch gesture
  4154. this._noPrune = !!noPrune;
  4155. }
  4156. this._setZoomTransforms(center, zoom);
  4157. },
  4158. _setZoomTransforms: function (center, zoom) {
  4159. for (var i in this._levels) {
  4160. this._setZoomTransform(this._levels[i], center, zoom);
  4161. }
  4162. },
  4163. _setZoomTransform: function (level, center, zoom) {
  4164. var scale = this._map.getZoomScale(zoom, level.zoom),
  4165. translate = level.origin.multiplyBy(scale)
  4166. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  4167. if (L.Browser.any3d) {
  4168. L.DomUtil.setTransform(level.el, translate, scale);
  4169. } else {
  4170. L.DomUtil.setPosition(level.el, translate);
  4171. }
  4172. },
  4173. _resetGrid: function () {
  4174. var map = this._map,
  4175. crs = map.options.crs,
  4176. tileSize = this._tileSize = this.getTileSize(),
  4177. tileZoom = this._tileZoom;
  4178. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  4179. if (bounds) {
  4180. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  4181. }
  4182. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  4183. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  4184. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  4185. ];
  4186. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  4187. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  4188. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  4189. ];
  4190. },
  4191. _onMoveEnd: function () {
  4192. if (!this._map || this._map._animatingZoom) { return; }
  4193. this._update();
  4194. },
  4195. _getTiledPixelBounds: function (center) {
  4196. var map = this._map,
  4197. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  4198. scale = map.getZoomScale(mapZoom, this._tileZoom),
  4199. pixelCenter = map.project(center, this._tileZoom).floor(),
  4200. halfSize = map.getSize().divideBy(scale * 2);
  4201. return new L.Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  4202. },
  4203. // Private method to load tiles in the grid's active zoom level according to map bounds
  4204. _update: function (center) {
  4205. var map = this._map;
  4206. if (!map) { return; }
  4207. var zoom = map.getZoom();
  4208. if (center === undefined) { center = map.getCenter(); }
  4209. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  4210. var pixelBounds = this._getTiledPixelBounds(center),
  4211. tileRange = this._pxBoundsToTileRange(pixelBounds),
  4212. tileCenter = tileRange.getCenter(),
  4213. queue = [],
  4214. margin = this.options.keepBuffer,
  4215. noPruneRange = new L.Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  4216. tileRange.getTopRight().add([margin, -margin]));
  4217. for (var key in this._tiles) {
  4218. var c = this._tiles[key].coords;
  4219. if (c.z !== this._tileZoom || !noPruneRange.contains(L.point(c.x, c.y))) {
  4220. this._tiles[key].current = false;
  4221. }
  4222. }
  4223. // _update just loads more tiles. If the tile zoom level differs too much
  4224. // from the map's, let _setView reset levels and prune old tiles.
  4225. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  4226. // create a queue of coordinates to load tiles from
  4227. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  4228. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  4229. var coords = new L.Point(i, j);
  4230. coords.z = this._tileZoom;
  4231. if (!this._isValidTile(coords)) { continue; }
  4232. var tile = this._tiles[this._tileCoordsToKey(coords)];
  4233. if (tile) {
  4234. tile.current = true;
  4235. } else {
  4236. queue.push(coords);
  4237. }
  4238. }
  4239. }
  4240. // sort tile queue to load tiles in order of their distance to center
  4241. queue.sort(function (a, b) {
  4242. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  4243. });
  4244. if (queue.length !== 0) {
  4245. // if it's the first batch of tiles to load
  4246. if (!this._loading) {
  4247. this._loading = true;
  4248. // @event loading: Event
  4249. // Fired when the grid layer starts loading tiles.
  4250. this.fire('loading');
  4251. }
  4252. // create DOM fragment to append tiles in one batch
  4253. var fragment = document.createDocumentFragment();
  4254. for (i = 0; i < queue.length; i++) {
  4255. this._addTile(queue[i], fragment);
  4256. }
  4257. this._level.el.appendChild(fragment);
  4258. }
  4259. },
  4260. _isValidTile: function (coords) {
  4261. var crs = this._map.options.crs;
  4262. if (!crs.infinite) {
  4263. // don't load tile if it's out of bounds and not wrapped
  4264. var bounds = this._globalTileRange;
  4265. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  4266. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  4267. }
  4268. if (!this.options.bounds) { return true; }
  4269. // don't load tile if it doesn't intersect the bounds in options
  4270. var tileBounds = this._tileCoordsToBounds(coords);
  4271. return L.latLngBounds(this.options.bounds).overlaps(tileBounds);
  4272. },
  4273. _keyToBounds: function (key) {
  4274. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  4275. },
  4276. // converts tile coordinates to its geographical bounds
  4277. _tileCoordsToBounds: function (coords) {
  4278. var map = this._map,
  4279. tileSize = this.getTileSize(),
  4280. nwPoint = coords.scaleBy(tileSize),
  4281. sePoint = nwPoint.add(tileSize),
  4282. nw = map.unproject(nwPoint, coords.z),
  4283. se = map.unproject(sePoint, coords.z),
  4284. bounds = new L.LatLngBounds(nw, se);
  4285. if (!this.options.noWrap) {
  4286. map.wrapLatLngBounds(bounds);
  4287. }
  4288. return bounds;
  4289. },
  4290. // converts tile coordinates to key for the tile cache
  4291. _tileCoordsToKey: function (coords) {
  4292. return coords.x + ':' + coords.y + ':' + coords.z;
  4293. },
  4294. // converts tile cache key to coordinates
  4295. _keyToTileCoords: function (key) {
  4296. var k = key.split(':'),
  4297. coords = new L.Point(+k[0], +k[1]);
  4298. coords.z = +k[2];
  4299. return coords;
  4300. },
  4301. _removeTile: function (key) {
  4302. var tile = this._tiles[key];
  4303. if (!tile) { return; }
  4304. L.DomUtil.remove(tile.el);
  4305. delete this._tiles[key];
  4306. // @event tileunload: TileEvent
  4307. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  4308. this.fire('tileunload', {
  4309. tile: tile.el,
  4310. coords: this._keyToTileCoords(key)
  4311. });
  4312. },
  4313. _initTile: function (tile) {
  4314. L.DomUtil.addClass(tile, 'leaflet-tile');
  4315. var tileSize = this.getTileSize();
  4316. tile.style.width = tileSize.x + 'px';
  4317. tile.style.height = tileSize.y + 'px';
  4318. tile.onselectstart = L.Util.falseFn;
  4319. tile.onmousemove = L.Util.falseFn;
  4320. // update opacity on tiles in IE7-8 because of filter inheritance problems
  4321. if (L.Browser.ielt9 && this.options.opacity < 1) {
  4322. L.DomUtil.setOpacity(tile, this.options.opacity);
  4323. }
  4324. // without this hack, tiles disappear after zoom on Chrome for Android
  4325. // https://github.com/Leaflet/Leaflet/issues/2078
  4326. if (L.Browser.android && !L.Browser.android23) {
  4327. tile.style.WebkitBackfaceVisibility = 'hidden';
  4328. }
  4329. },
  4330. _addTile: function (coords, container) {
  4331. var tilePos = this._getTilePos(coords),
  4332. key = this._tileCoordsToKey(coords);
  4333. var tile = this.createTile(this._wrapCoords(coords), L.bind(this._tileReady, this, coords));
  4334. this._initTile(tile);
  4335. // if createTile is defined with a second argument ("done" callback),
  4336. // we know that tile is async and will be ready later; otherwise
  4337. if (this.createTile.length < 2) {
  4338. // mark tile as ready, but delay one frame for opacity animation to happen
  4339. L.Util.requestAnimFrame(L.bind(this._tileReady, this, coords, null, tile));
  4340. }
  4341. L.DomUtil.setPosition(tile, tilePos);
  4342. // save tile in cache
  4343. this._tiles[key] = {
  4344. el: tile,
  4345. coords: coords,
  4346. current: true
  4347. };
  4348. container.appendChild(tile);
  4349. // @event tileloadstart: TileEvent
  4350. // Fired when a tile is requested and starts loading.
  4351. this.fire('tileloadstart', {
  4352. tile: tile,
  4353. coords: coords
  4354. });
  4355. },
  4356. _tileReady: function (coords, err, tile) {
  4357. if (!this._map) { return; }
  4358. if (err) {
  4359. // @event tileerror: TileErrorEvent
  4360. // Fired when there is an error loading a tile.
  4361. this.fire('tileerror', {
  4362. error: err,
  4363. tile: tile,
  4364. coords: coords
  4365. });
  4366. }
  4367. var key = this._tileCoordsToKey(coords);
  4368. tile = this._tiles[key];
  4369. if (!tile) { return; }
  4370. tile.loaded = +new Date();
  4371. if (this._map._fadeAnimated) {
  4372. L.DomUtil.setOpacity(tile.el, 0);
  4373. L.Util.cancelAnimFrame(this._fadeFrame);
  4374. this._fadeFrame = L.Util.requestAnimFrame(this._updateOpacity, this);
  4375. } else {
  4376. tile.active = true;
  4377. this._pruneTiles();
  4378. }
  4379. if (!err) {
  4380. L.DomUtil.addClass(tile.el, 'leaflet-tile-loaded');
  4381. // @event tileload: TileEvent
  4382. // Fired when a tile loads.
  4383. this.fire('tileload', {
  4384. tile: tile.el,
  4385. coords: coords
  4386. });
  4387. }
  4388. if (this._noTilesToLoad()) {
  4389. this._loading = false;
  4390. // @event load: Event
  4391. // Fired when the grid layer loaded all visible tiles.
  4392. this.fire('load');
  4393. if (L.Browser.ielt9 || !this._map._fadeAnimated) {
  4394. L.Util.requestAnimFrame(this._pruneTiles, this);
  4395. } else {
  4396. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  4397. // to trigger a pruning.
  4398. setTimeout(L.bind(this._pruneTiles, this), 250);
  4399. }
  4400. }
  4401. },
  4402. _getTilePos: function (coords) {
  4403. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  4404. },
  4405. _wrapCoords: function (coords) {
  4406. var newCoords = new L.Point(
  4407. this._wrapX ? L.Util.wrapNum(coords.x, this._wrapX) : coords.x,
  4408. this._wrapY ? L.Util.wrapNum(coords.y, this._wrapY) : coords.y);
  4409. newCoords.z = coords.z;
  4410. return newCoords;
  4411. },
  4412. _pxBoundsToTileRange: function (bounds) {
  4413. var tileSize = this.getTileSize();
  4414. return new L.Bounds(
  4415. bounds.min.unscaleBy(tileSize).floor(),
  4416. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  4417. },
  4418. _noTilesToLoad: function () {
  4419. for (var key in this._tiles) {
  4420. if (!this._tiles[key].loaded) { return false; }
  4421. }
  4422. return true;
  4423. }
  4424. });
  4425. // @factory L.gridLayer(options?: GridLayer options)
  4426. // Creates a new instance of GridLayer with the supplied options.
  4427. L.gridLayer = function (options) {
  4428. return new L.GridLayer(options);
  4429. };
  4430. /*
  4431. * @class TileLayer
  4432. * @inherits GridLayer
  4433. * @aka L.TileLayer
  4434. * Used to load and display tile layers on the map. Extends `GridLayer`.
  4435. *
  4436. * @example
  4437. *
  4438. * ```js
  4439. * L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map);
  4440. * ```
  4441. *
  4442. * @section URL template
  4443. * @example
  4444. *
  4445. * A string of the following form:
  4446. *
  4447. * ```
  4448. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  4449. * ```
  4450. *
  4451. * `{s}` means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; `a`, `b` or `c` by default, can be omitted), `{z}` — zoom level, `{x}` and `{y}` — tile coordinates. `{r}` can be used to add @2x to the URL to load retina tiles.
  4452. *
  4453. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  4454. *
  4455. * ```
  4456. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  4457. * ```
  4458. */
  4459. L.TileLayer = L.GridLayer.extend({
  4460. // @section
  4461. // @aka TileLayer options
  4462. options: {
  4463. // @option minZoom: Number = 0
  4464. // Minimum zoom number.
  4465. minZoom: 0,
  4466. // @option maxZoom: Number = 18
  4467. // Maximum zoom number.
  4468. maxZoom: 18,
  4469. // @option maxNativeZoom: Number = null
  4470. // Maximum zoom number the tile source has available. If it is specified,
  4471. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  4472. // from `maxNativeZoom` level and auto-scaled.
  4473. maxNativeZoom: null,
  4474. // @option minNativeZoom: Number = null
  4475. // Minimum zoom number the tile source has available. If it is specified,
  4476. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  4477. // from `minNativeZoom` level and auto-scaled.
  4478. minNativeZoom: null,
  4479. // @option subdomains: String|String[] = 'abc'
  4480. // Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.
  4481. subdomains: 'abc',
  4482. // @option errorTileUrl: String = ''
  4483. // URL to the tile image to show in place of the tile that failed to load.
  4484. errorTileUrl: '',
  4485. // @option zoomOffset: Number = 0
  4486. // The zoom number used in tile URLs will be offset with this value.
  4487. zoomOffset: 0,
  4488. // @option tms: Boolean = false
  4489. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  4490. tms: false,
  4491. // @option zoomReverse: Boolean = false
  4492. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  4493. zoomReverse: false,
  4494. // @option detectRetina: Boolean = false
  4495. // If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.
  4496. detectRetina: false,
  4497. // @option crossOrigin: Boolean = false
  4498. // If true, all tiles will have their crossOrigin attribute set to ''. This is needed if you want to access tile pixel data.
  4499. crossOrigin: false
  4500. },
  4501. initialize: function (url, options) {
  4502. this._url = url;
  4503. options = L.setOptions(this, options);
  4504. // detecting retina displays, adjusting tileSize and zoom levels
  4505. if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
  4506. options.tileSize = Math.floor(options.tileSize / 2);
  4507. if (!options.zoomReverse) {
  4508. options.zoomOffset++;
  4509. options.maxZoom--;
  4510. } else {
  4511. options.zoomOffset--;
  4512. options.minZoom++;
  4513. }
  4514. options.minZoom = Math.max(0, options.minZoom);
  4515. }
  4516. if (typeof options.subdomains === 'string') {
  4517. options.subdomains = options.subdomains.split('');
  4518. }
  4519. // for https://github.com/Leaflet/Leaflet/issues/137
  4520. if (!L.Browser.android) {
  4521. this.on('tileunload', this._onTileRemove);
  4522. }
  4523. },
  4524. // @method setUrl(url: String, noRedraw?: Boolean): this
  4525. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  4526. setUrl: function (url, noRedraw) {
  4527. this._url = url;
  4528. if (!noRedraw) {
  4529. this.redraw();
  4530. }
  4531. return this;
  4532. },
  4533. // @method createTile(coords: Object, done?: Function): HTMLElement
  4534. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  4535. // to return an `<img>` HTML element with the appropiate image URL given `coords`. The `done`
  4536. // callback is called when the tile has been loaded.
  4537. createTile: function (coords, done) {
  4538. var tile = document.createElement('img');
  4539. L.DomEvent.on(tile, 'load', L.bind(this._tileOnLoad, this, done, tile));
  4540. L.DomEvent.on(tile, 'error', L.bind(this._tileOnError, this, done, tile));
  4541. if (this.options.crossOrigin) {
  4542. tile.crossOrigin = '';
  4543. }
  4544. /*
  4545. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  4546. http://www.w3.org/TR/WCAG20-TECHS/H67
  4547. */
  4548. tile.alt = '';
  4549. /*
  4550. Set role="presentation" to force screen readers to ignore this
  4551. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  4552. */
  4553. tile.setAttribute('role', 'presentation');
  4554. tile.src = this.getTileUrl(coords);
  4555. return tile;
  4556. },
  4557. // @section Extension methods
  4558. // @uninheritable
  4559. // Layers extending `TileLayer` might reimplement the following method.
  4560. // @method getTileUrl(coords: Object): String
  4561. // Called only internally, returns the URL for a tile given its coordinates.
  4562. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  4563. getTileUrl: function (coords) {
  4564. var data = {
  4565. r: L.Browser.retina ? '@2x' : '',
  4566. s: this._getSubdomain(coords),
  4567. x: coords.x,
  4568. y: coords.y,
  4569. z: this._getZoomForUrl()
  4570. };
  4571. if (this._map && !this._map.options.crs.infinite) {
  4572. var invertedY = this._globalTileRange.max.y - coords.y;
  4573. if (this.options.tms) {
  4574. data['y'] = invertedY;
  4575. }
  4576. data['-y'] = invertedY;
  4577. }
  4578. return L.Util.template(this._url, L.extend(data, this.options));
  4579. },
  4580. _tileOnLoad: function (done, tile) {
  4581. // For https://github.com/Leaflet/Leaflet/issues/3332
  4582. if (L.Browser.ielt9) {
  4583. setTimeout(L.bind(done, this, null, tile), 0);
  4584. } else {
  4585. done(null, tile);
  4586. }
  4587. },
  4588. _tileOnError: function (done, tile, e) {
  4589. var errorUrl = this.options.errorTileUrl;
  4590. if (errorUrl && tile.src !== errorUrl) {
  4591. tile.src = errorUrl;
  4592. }
  4593. done(e, tile);
  4594. },
  4595. getTileSize: function () {
  4596. var map = this._map,
  4597. tileSize = L.GridLayer.prototype.getTileSize.call(this),
  4598. zoom = this._tileZoom + this.options.zoomOffset,
  4599. minNativeZoom = this.options.minNativeZoom,
  4600. maxNativeZoom = this.options.maxNativeZoom;
  4601. // decrease tile size when scaling below minNativeZoom
  4602. if (minNativeZoom !== null && zoom < minNativeZoom) {
  4603. return tileSize.divideBy(map.getZoomScale(minNativeZoom, zoom)).round();
  4604. }
  4605. // increase tile size when scaling above maxNativeZoom
  4606. if (maxNativeZoom !== null && zoom > maxNativeZoom) {
  4607. return tileSize.divideBy(map.getZoomScale(maxNativeZoom, zoom)).round();
  4608. }
  4609. return tileSize;
  4610. },
  4611. _onTileRemove: function (e) {
  4612. e.tile.onload = null;
  4613. },
  4614. _getZoomForUrl: function () {
  4615. var zoom = this._tileZoom,
  4616. maxZoom = this.options.maxZoom,
  4617. zoomReverse = this.options.zoomReverse,
  4618. zoomOffset = this.options.zoomOffset,
  4619. minNativeZoom = this.options.minNativeZoom,
  4620. maxNativeZoom = this.options.maxNativeZoom;
  4621. if (zoomReverse) {
  4622. zoom = maxZoom - zoom;
  4623. }
  4624. zoom += zoomOffset;
  4625. if (minNativeZoom !== null && zoom < minNativeZoom) {
  4626. return minNativeZoom;
  4627. }
  4628. if (maxNativeZoom !== null && zoom > maxNativeZoom) {
  4629. return maxNativeZoom;
  4630. }
  4631. return zoom;
  4632. },
  4633. _getSubdomain: function (tilePoint) {
  4634. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  4635. return this.options.subdomains[index];
  4636. },
  4637. // stops loading all tiles in the background layer
  4638. _abortLoading: function () {
  4639. var i, tile;
  4640. for (i in this._tiles) {
  4641. if (this._tiles[i].coords.z !== this._tileZoom) {
  4642. tile = this._tiles[i].el;
  4643. tile.onload = L.Util.falseFn;
  4644. tile.onerror = L.Util.falseFn;
  4645. if (!tile.complete) {
  4646. tile.src = L.Util.emptyImageUrl;
  4647. L.DomUtil.remove(tile);
  4648. }
  4649. }
  4650. }
  4651. }
  4652. });
  4653. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  4654. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  4655. L.tileLayer = function (url, options) {
  4656. return new L.TileLayer(url, options);
  4657. };
  4658. /*
  4659. * @class TileLayer.WMS
  4660. * @inherits TileLayer
  4661. * @aka L.TileLayer.WMS
  4662. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  4663. *
  4664. * @example
  4665. *
  4666. * ```js
  4667. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  4668. * layers: 'nexrad-n0r-900913',
  4669. * format: 'image/png',
  4670. * transparent: true,
  4671. * attribution: "Weather data © 2012 IEM Nexrad"
  4672. * });
  4673. * ```
  4674. */
  4675. L.TileLayer.WMS = L.TileLayer.extend({
  4676. // @section
  4677. // @aka TileLayer.WMS options
  4678. // If any custom options not documented here are used, they will be sent to the
  4679. // WMS server as extra parameters in each request URL. This can be useful for
  4680. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  4681. defaultWmsParams: {
  4682. service: 'WMS',
  4683. request: 'GetMap',
  4684. // @option layers: String = ''
  4685. // **(required)** Comma-separated list of WMS layers to show.
  4686. layers: '',
  4687. // @option styles: String = ''
  4688. // Comma-separated list of WMS styles.
  4689. styles: '',
  4690. // @option format: String = 'image/jpeg'
  4691. // WMS image format (use `'image/png'` for layers with transparency).
  4692. format: 'image/jpeg',
  4693. // @option transparent: Boolean = false
  4694. // If `true`, the WMS service will return images with transparency.
  4695. transparent: false,
  4696. // @option version: String = '1.1.1'
  4697. // Version of the WMS service to use
  4698. version: '1.1.1'
  4699. },
  4700. options: {
  4701. // @option crs: CRS = null
  4702. // Coordinate Reference System to use for the WMS requests, defaults to
  4703. // map CRS. Don't change this if you're not sure what it means.
  4704. crs: null,
  4705. // @option uppercase: Boolean = false
  4706. // If `true`, WMS request parameter keys will be uppercase.
  4707. uppercase: false
  4708. },
  4709. initialize: function (url, options) {
  4710. this._url = url;
  4711. var wmsParams = L.extend({}, this.defaultWmsParams);
  4712. // all keys that are not TileLayer options go to WMS params
  4713. for (var i in options) {
  4714. if (!(i in this.options)) {
  4715. wmsParams[i] = options[i];
  4716. }
  4717. }
  4718. options = L.setOptions(this, options);
  4719. wmsParams.width = wmsParams.height = options.tileSize * (options.detectRetina && L.Browser.retina ? 2 : 1);
  4720. this.wmsParams = wmsParams;
  4721. },
  4722. onAdd: function (map) {
  4723. this._crs = this.options.crs || map.options.crs;
  4724. this._wmsVersion = parseFloat(this.wmsParams.version);
  4725. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  4726. this.wmsParams[projectionKey] = this._crs.code;
  4727. L.TileLayer.prototype.onAdd.call(this, map);
  4728. },
  4729. getTileUrl: function (coords) {
  4730. var tileBounds = this._tileCoordsToBounds(coords),
  4731. nw = this._crs.project(tileBounds.getNorthWest()),
  4732. se = this._crs.project(tileBounds.getSouthEast()),
  4733. bbox = (this._wmsVersion >= 1.3 && this._crs === L.CRS.EPSG4326 ?
  4734. [se.y, nw.x, nw.y, se.x] :
  4735. [nw.x, se.y, se.x, nw.y]).join(','),
  4736. url = L.TileLayer.prototype.getTileUrl.call(this, coords);
  4737. return url +
  4738. L.Util.getParamString(this.wmsParams, url, this.options.uppercase) +
  4739. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  4740. },
  4741. // @method setParams(params: Object, noRedraw?: Boolean): this
  4742. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  4743. setParams: function (params, noRedraw) {
  4744. L.extend(this.wmsParams, params);
  4745. if (!noRedraw) {
  4746. this.redraw();
  4747. }
  4748. return this;
  4749. }
  4750. });
  4751. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  4752. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  4753. L.tileLayer.wms = function (url, options) {
  4754. return new L.TileLayer.WMS(url, options);
  4755. };
  4756. /*
  4757. * @class ImageOverlay
  4758. * @aka L.ImageOverlay
  4759. * @inherits Interactive layer
  4760. *
  4761. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  4762. *
  4763. * @example
  4764. *
  4765. * ```js
  4766. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  4767. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  4768. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  4769. * ```
  4770. */
  4771. L.ImageOverlay = L.Layer.extend({
  4772. // @section
  4773. // @aka ImageOverlay options
  4774. options: {
  4775. // @option opacity: Number = 1.0
  4776. // The opacity of the image overlay.
  4777. opacity: 1,
  4778. // @option alt: String = ''
  4779. // Text for the `alt` attribute of the image (useful for accessibility).
  4780. alt: '',
  4781. // @option interactive: Boolean = false
  4782. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  4783. interactive: false,
  4784. // @option crossOrigin: Boolean = false
  4785. // If true, the image will have its crossOrigin attribute set to ''. This is needed if you want to access image pixel data.
  4786. crossOrigin: false
  4787. },
  4788. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  4789. this._url = url;
  4790. this._bounds = L.latLngBounds(bounds);
  4791. L.setOptions(this, options);
  4792. },
  4793. onAdd: function () {
  4794. if (!this._image) {
  4795. this._initImage();
  4796. if (this.options.opacity < 1) {
  4797. this._updateOpacity();
  4798. }
  4799. }
  4800. if (this.options.interactive) {
  4801. L.DomUtil.addClass(this._image, 'leaflet-interactive');
  4802. this.addInteractiveTarget(this._image);
  4803. }
  4804. this.getPane().appendChild(this._image);
  4805. this._reset();
  4806. },
  4807. onRemove: function () {
  4808. L.DomUtil.remove(this._image);
  4809. if (this.options.interactive) {
  4810. this.removeInteractiveTarget(this._image);
  4811. }
  4812. },
  4813. // @method setOpacity(opacity: Number): this
  4814. // Sets the opacity of the overlay.
  4815. setOpacity: function (opacity) {
  4816. this.options.opacity = opacity;
  4817. if (this._image) {
  4818. this._updateOpacity();
  4819. }
  4820. return this;
  4821. },
  4822. setStyle: function (styleOpts) {
  4823. if (styleOpts.opacity) {
  4824. this.setOpacity(styleOpts.opacity);
  4825. }
  4826. return this;
  4827. },
  4828. // @method bringToFront(): this
  4829. // Brings the layer to the top of all overlays.
  4830. bringToFront: function () {
  4831. if (this._map) {
  4832. L.DomUtil.toFront(this._image);
  4833. }
  4834. return this;
  4835. },
  4836. // @method bringToBack(): this
  4837. // Brings the layer to the bottom of all overlays.
  4838. bringToBack: function () {
  4839. if (this._map) {
  4840. L.DomUtil.toBack(this._image);
  4841. }
  4842. return this;
  4843. },
  4844. // @method setUrl(url: String): this
  4845. // Changes the URL of the image.
  4846. setUrl: function (url) {
  4847. this._url = url;
  4848. if (this._image) {
  4849. this._image.src = url;
  4850. }
  4851. return this;
  4852. },
  4853. // @method setBounds(bounds: LatLngBounds): this
  4854. // Update the bounds that this ImageOverlay covers
  4855. setBounds: function (bounds) {
  4856. this._bounds = bounds;
  4857. if (this._map) {
  4858. this._reset();
  4859. }
  4860. return this;
  4861. },
  4862. getEvents: function () {
  4863. var events = {
  4864. zoom: this._reset,
  4865. viewreset: this._reset
  4866. };
  4867. if (this._zoomAnimated) {
  4868. events.zoomanim = this._animateZoom;
  4869. }
  4870. return events;
  4871. },
  4872. // @method getBounds(): LatLngBounds
  4873. // Get the bounds that this ImageOverlay covers
  4874. getBounds: function () {
  4875. return this._bounds;
  4876. },
  4877. // @method getElement(): HTMLElement
  4878. // Get the img element that represents the ImageOverlay on the map
  4879. getElement: function () {
  4880. return this._image;
  4881. },
  4882. _initImage: function () {
  4883. var img = this._image = L.DomUtil.create('img',
  4884. 'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated' : ''));
  4885. img.onselectstart = L.Util.falseFn;
  4886. img.onmousemove = L.Util.falseFn;
  4887. img.onload = L.bind(this.fire, this, 'load');
  4888. if (this.options.crossOrigin) {
  4889. img.crossOrigin = '';
  4890. }
  4891. img.src = this._url;
  4892. img.alt = this.options.alt;
  4893. },
  4894. _animateZoom: function (e) {
  4895. var scale = this._map.getZoomScale(e.zoom),
  4896. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  4897. L.DomUtil.setTransform(this._image, offset, scale);
  4898. },
  4899. _reset: function () {
  4900. var image = this._image,
  4901. bounds = new L.Bounds(
  4902. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  4903. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  4904. size = bounds.getSize();
  4905. L.DomUtil.setPosition(image, bounds.min);
  4906. image.style.width = size.x + 'px';
  4907. image.style.height = size.y + 'px';
  4908. },
  4909. _updateOpacity: function () {
  4910. L.DomUtil.setOpacity(this._image, this.options.opacity);
  4911. }
  4912. });
  4913. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  4914. // Instantiates an image overlay object given the URL of the image and the
  4915. // geographical bounds it is tied to.
  4916. L.imageOverlay = function (url, bounds, options) {
  4917. return new L.ImageOverlay(url, bounds, options);
  4918. };
  4919. /*
  4920. * @class Icon
  4921. * @aka L.Icon
  4922. * @inherits Layer
  4923. *
  4924. * Represents an icon to provide when creating a marker.
  4925. *
  4926. * @example
  4927. *
  4928. * ```js
  4929. * var myIcon = L.icon({
  4930. * iconUrl: 'my-icon.png',
  4931. * iconRetinaUrl: 'my-icon@2x.png',
  4932. * iconSize: [38, 95],
  4933. * iconAnchor: [22, 94],
  4934. * popupAnchor: [-3, -76],
  4935. * shadowUrl: 'my-icon-shadow.png',
  4936. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  4937. * shadowSize: [68, 95],
  4938. * shadowAnchor: [22, 94]
  4939. * });
  4940. *
  4941. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  4942. * ```
  4943. *
  4944. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  4945. *
  4946. */
  4947. L.Icon = L.Class.extend({
  4948. /* @section
  4949. * @aka Icon options
  4950. *
  4951. * @option iconUrl: String = null
  4952. * **(required)** The URL to the icon image (absolute or relative to your script path).
  4953. *
  4954. * @option iconRetinaUrl: String = null
  4955. * The URL to a retina sized version of the icon image (absolute or relative to your
  4956. * script path). Used for Retina screen devices.
  4957. *
  4958. * @option iconSize: Point = null
  4959. * Size of the icon image in pixels.
  4960. *
  4961. * @option iconAnchor: Point = null
  4962. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  4963. * will be aligned so that this point is at the marker's geographical location. Centered
  4964. * by default if size is specified, also can be set in CSS with negative margins.
  4965. *
  4966. * @option popupAnchor: Point = null
  4967. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  4968. *
  4969. * @option shadowUrl: String = null
  4970. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  4971. *
  4972. * @option shadowRetinaUrl: String = null
  4973. *
  4974. * @option shadowSize: Point = null
  4975. * Size of the shadow image in pixels.
  4976. *
  4977. * @option shadowAnchor: Point = null
  4978. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  4979. * as iconAnchor if not specified).
  4980. *
  4981. * @option className: String = ''
  4982. * A custom class name to assign to both icon and shadow images. Empty by default.
  4983. */
  4984. initialize: function (options) {
  4985. L.setOptions(this, options);
  4986. },
  4987. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  4988. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  4989. // styled according to the options.
  4990. createIcon: function (oldIcon) {
  4991. return this._createIcon('icon', oldIcon);
  4992. },
  4993. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  4994. // As `createIcon`, but for the shadow beneath it.
  4995. createShadow: function (oldIcon) {
  4996. return this._createIcon('shadow', oldIcon);
  4997. },
  4998. _createIcon: function (name, oldIcon) {
  4999. var src = this._getIconUrl(name);
  5000. if (!src) {
  5001. if (name === 'icon') {
  5002. throw new Error('iconUrl not set in Icon options (see the docs).');
  5003. }
  5004. return null;
  5005. }
  5006. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  5007. this._setIconStyles(img, name);
  5008. return img;
  5009. },
  5010. _setIconStyles: function (img, name) {
  5011. var options = this.options;
  5012. var sizeOption = options[name + 'Size'];
  5013. if (typeof sizeOption === 'number') {
  5014. sizeOption = [sizeOption, sizeOption];
  5015. }
  5016. var size = L.point(sizeOption),
  5017. anchor = L.point(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  5018. size && size.divideBy(2, true));
  5019. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  5020. if (anchor) {
  5021. img.style.marginLeft = (-anchor.x) + 'px';
  5022. img.style.marginTop = (-anchor.y) + 'px';
  5023. }
  5024. if (size) {
  5025. img.style.width = size.x + 'px';
  5026. img.style.height = size.y + 'px';
  5027. }
  5028. },
  5029. _createImg: function (src, el) {
  5030. el = el || document.createElement('img');
  5031. el.src = src;
  5032. return el;
  5033. },
  5034. _getIconUrl: function (name) {
  5035. return L.Browser.retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  5036. }
  5037. });
  5038. // @factory L.icon(options: Icon options)
  5039. // Creates an icon instance with the given options.
  5040. L.icon = function (options) {
  5041. return new L.Icon(options);
  5042. };
  5043. /*
  5044. * @miniclass Icon.Default (Icon)
  5045. * @aka L.Icon.Default
  5046. * @section
  5047. *
  5048. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  5049. * no icon is specified. Points to the blue marker image distributed with Leaflet
  5050. * releases.
  5051. *
  5052. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  5053. * (which is a set of `Icon options`).
  5054. *
  5055. * If you want to _completely_ replace the default icon, override the
  5056. * `L.Marker.prototype.options.icon` with your own icon instead.
  5057. */
  5058. L.Icon.Default = L.Icon.extend({
  5059. options: {
  5060. iconUrl: 'marker-icon.png',
  5061. iconRetinaUrl: 'marker-icon-2x.png',
  5062. shadowUrl: 'marker-shadow.png',
  5063. iconSize: [25, 41],
  5064. iconAnchor: [12, 41],
  5065. popupAnchor: [1, -34],
  5066. tooltipAnchor: [16, -28],
  5067. shadowSize: [41, 41]
  5068. },
  5069. _getIconUrl: function (name) {
  5070. if (!L.Icon.Default.imagePath) { // Deprecated, backwards-compatibility only
  5071. L.Icon.Default.imagePath = this._detectIconPath();
  5072. }
  5073. // @option imagePath: String
  5074. // `L.Icon.Default` will try to auto-detect the absolute location of the
  5075. // blue icon images. If you are placing these images in a non-standard
  5076. // way, set this option to point to the right absolute path.
  5077. return (this.options.imagePath || L.Icon.Default.imagePath) + L.Icon.prototype._getIconUrl.call(this, name);
  5078. },
  5079. _detectIconPath: function () {
  5080. var el = L.DomUtil.create('div', 'leaflet-default-icon-path', document.body);
  5081. var path = L.DomUtil.getStyle(el, 'background-image') ||
  5082. L.DomUtil.getStyle(el, 'backgroundImage'); // IE8
  5083. document.body.removeChild(el);
  5084. return path.indexOf('url') === 0 ?
  5085. path.replace(/^url\([\"\']?/, '').replace(/marker-icon\.png[\"\']?\)$/, '') : '';
  5086. }
  5087. });
  5088. /*
  5089. * @class Marker
  5090. * @inherits Interactive layer
  5091. * @aka L.Marker
  5092. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  5093. *
  5094. * @example
  5095. *
  5096. * ```js
  5097. * L.marker([50.5, 30.5]).addTo(map);
  5098. * ```
  5099. */
  5100. L.Marker = L.Layer.extend({
  5101. // @section
  5102. // @aka Marker options
  5103. options: {
  5104. // @option icon: Icon = *
  5105. // Icon class to use for rendering the marker. See [Icon documentation](#L.Icon) for details on how to customize the marker icon. If not specified, a new `L.Icon.Default` is used.
  5106. icon: new L.Icon.Default(),
  5107. // Option inherited from "Interactive layer" abstract class
  5108. interactive: true,
  5109. // @option draggable: Boolean = false
  5110. // Whether the marker is draggable with mouse/touch or not.
  5111. draggable: false,
  5112. // @option keyboard: Boolean = true
  5113. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  5114. keyboard: true,
  5115. // @option title: String = ''
  5116. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  5117. title: '',
  5118. // @option alt: String = ''
  5119. // Text for the `alt` attribute of the icon image (useful for accessibility).
  5120. alt: '',
  5121. // @option zIndexOffset: Number = 0
  5122. // By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively).
  5123. zIndexOffset: 0,
  5124. // @option opacity: Number = 1.0
  5125. // The opacity of the marker.
  5126. opacity: 1,
  5127. // @option riseOnHover: Boolean = false
  5128. // If `true`, the marker will get on top of others when you hover the mouse over it.
  5129. riseOnHover: false,
  5130. // @option riseOffset: Number = 250
  5131. // The z-index offset used for the `riseOnHover` feature.
  5132. riseOffset: 250,
  5133. // @option pane: String = 'markerPane'
  5134. // `Map pane` where the markers icon will be added.
  5135. pane: 'markerPane',
  5136. // FIXME: shadowPane is no longer a valid option
  5137. nonBubblingEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu']
  5138. },
  5139. /* @section
  5140. *
  5141. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  5142. */
  5143. initialize: function (latlng, options) {
  5144. L.setOptions(this, options);
  5145. this._latlng = L.latLng(latlng);
  5146. },
  5147. onAdd: function (map) {
  5148. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  5149. if (this._zoomAnimated) {
  5150. map.on('zoomanim', this._animateZoom, this);
  5151. }
  5152. this._initIcon();
  5153. this.update();
  5154. },
  5155. onRemove: function (map) {
  5156. if (this.dragging && this.dragging.enabled()) {
  5157. this.options.draggable = true;
  5158. this.dragging.removeHooks();
  5159. }
  5160. if (this._zoomAnimated) {
  5161. map.off('zoomanim', this._animateZoom, this);
  5162. }
  5163. this._removeIcon();
  5164. this._removeShadow();
  5165. },
  5166. getEvents: function () {
  5167. return {
  5168. zoom: this.update,
  5169. viewreset: this.update
  5170. };
  5171. },
  5172. // @method getLatLng: LatLng
  5173. // Returns the current geographical position of the marker.
  5174. getLatLng: function () {
  5175. return this._latlng;
  5176. },
  5177. // @method setLatLng(latlng: LatLng): this
  5178. // Changes the marker position to the given point.
  5179. setLatLng: function (latlng) {
  5180. var oldLatLng = this._latlng;
  5181. this._latlng = L.latLng(latlng);
  5182. this.update();
  5183. // @event move: Event
  5184. // Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
  5185. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  5186. },
  5187. // @method setZIndexOffset(offset: Number): this
  5188. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  5189. setZIndexOffset: function (offset) {
  5190. this.options.zIndexOffset = offset;
  5191. return this.update();
  5192. },
  5193. // @method setIcon(icon: Icon): this
  5194. // Changes the marker icon.
  5195. setIcon: function (icon) {
  5196. this.options.icon = icon;
  5197. if (this._map) {
  5198. this._initIcon();
  5199. this.update();
  5200. }
  5201. if (this._popup) {
  5202. this.bindPopup(this._popup, this._popup.options);
  5203. }
  5204. return this;
  5205. },
  5206. getElement: function () {
  5207. return this._icon;
  5208. },
  5209. update: function () {
  5210. if (this._icon) {
  5211. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  5212. this._setPos(pos);
  5213. }
  5214. return this;
  5215. },
  5216. _initIcon: function () {
  5217. var options = this.options,
  5218. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  5219. var icon = options.icon.createIcon(this._icon),
  5220. addIcon = false;
  5221. // if we're not reusing the icon, remove the old one and init new one
  5222. if (icon !== this._icon) {
  5223. if (this._icon) {
  5224. this._removeIcon();
  5225. }
  5226. addIcon = true;
  5227. if (options.title) {
  5228. icon.title = options.title;
  5229. }
  5230. if (options.alt) {
  5231. icon.alt = options.alt;
  5232. }
  5233. }
  5234. L.DomUtil.addClass(icon, classToAdd);
  5235. if (options.keyboard) {
  5236. icon.tabIndex = '0';
  5237. }
  5238. this._icon = icon;
  5239. if (options.riseOnHover) {
  5240. this.on({
  5241. mouseover: this._bringToFront,
  5242. mouseout: this._resetZIndex
  5243. });
  5244. }
  5245. var newShadow = options.icon.createShadow(this._shadow),
  5246. addShadow = false;
  5247. if (newShadow !== this._shadow) {
  5248. this._removeShadow();
  5249. addShadow = true;
  5250. }
  5251. if (newShadow) {
  5252. L.DomUtil.addClass(newShadow, classToAdd);
  5253. newShadow.alt = '';
  5254. }
  5255. this._shadow = newShadow;
  5256. if (options.opacity < 1) {
  5257. this._updateOpacity();
  5258. }
  5259. if (addIcon) {
  5260. this.getPane().appendChild(this._icon);
  5261. }
  5262. this._initInteraction();
  5263. if (newShadow && addShadow) {
  5264. this.getPane('shadowPane').appendChild(this._shadow);
  5265. }
  5266. },
  5267. _removeIcon: function () {
  5268. if (this.options.riseOnHover) {
  5269. this.off({
  5270. mouseover: this._bringToFront,
  5271. mouseout: this._resetZIndex
  5272. });
  5273. }
  5274. L.DomUtil.remove(this._icon);
  5275. this.removeInteractiveTarget(this._icon);
  5276. this._icon = null;
  5277. },
  5278. _removeShadow: function () {
  5279. if (this._shadow) {
  5280. L.DomUtil.remove(this._shadow);
  5281. }
  5282. this._shadow = null;
  5283. },
  5284. _setPos: function (pos) {
  5285. L.DomUtil.setPosition(this._icon, pos);
  5286. if (this._shadow) {
  5287. L.DomUtil.setPosition(this._shadow, pos);
  5288. }
  5289. this._zIndex = pos.y + this.options.zIndexOffset;
  5290. this._resetZIndex();
  5291. },
  5292. _updateZIndex: function (offset) {
  5293. this._icon.style.zIndex = this._zIndex + offset;
  5294. },
  5295. _animateZoom: function (opt) {
  5296. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  5297. this._setPos(pos);
  5298. },
  5299. _initInteraction: function () {
  5300. if (!this.options.interactive) { return; }
  5301. L.DomUtil.addClass(this._icon, 'leaflet-interactive');
  5302. this.addInteractiveTarget(this._icon);
  5303. if (L.Handler.MarkerDrag) {
  5304. var draggable = this.options.draggable;
  5305. if (this.dragging) {
  5306. draggable = this.dragging.enabled();
  5307. this.dragging.disable();
  5308. }
  5309. this.dragging = new L.Handler.MarkerDrag(this);
  5310. if (draggable) {
  5311. this.dragging.enable();
  5312. }
  5313. }
  5314. },
  5315. // @method setOpacity(opacity: Number): this
  5316. // Changes the opacity of the marker.
  5317. setOpacity: function (opacity) {
  5318. this.options.opacity = opacity;
  5319. if (this._map) {
  5320. this._updateOpacity();
  5321. }
  5322. return this;
  5323. },
  5324. _updateOpacity: function () {
  5325. var opacity = this.options.opacity;
  5326. L.DomUtil.setOpacity(this._icon, opacity);
  5327. if (this._shadow) {
  5328. L.DomUtil.setOpacity(this._shadow, opacity);
  5329. }
  5330. },
  5331. _bringToFront: function () {
  5332. this._updateZIndex(this.options.riseOffset);
  5333. },
  5334. _resetZIndex: function () {
  5335. this._updateZIndex(0);
  5336. },
  5337. _getPopupAnchor: function () {
  5338. return this.options.icon.options.popupAnchor || [0, 0];
  5339. },
  5340. _getTooltipAnchor: function () {
  5341. return this.options.icon.options.tooltipAnchor || [0, 0];
  5342. }
  5343. });
  5344. // factory L.marker(latlng: LatLng, options? : Marker options)
  5345. // @factory L.marker(latlng: LatLng, options? : Marker options)
  5346. // Instantiates a Marker object given a geographical point and optionally an options object.
  5347. L.marker = function (latlng, options) {
  5348. return new L.Marker(latlng, options);
  5349. };
  5350. /*
  5351. * @class DivIcon
  5352. * @aka L.DivIcon
  5353. * @inherits Icon
  5354. *
  5355. * Represents a lightweight icon for markers that uses a simple `<div>`
  5356. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  5357. *
  5358. * @example
  5359. * ```js
  5360. * var myIcon = L.divIcon({className: 'my-div-icon'});
  5361. * // you can set .my-div-icon styles in CSS
  5362. *
  5363. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5364. * ```
  5365. *
  5366. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  5367. */
  5368. L.DivIcon = L.Icon.extend({
  5369. options: {
  5370. // @section
  5371. // @aka DivIcon options
  5372. iconSize: [12, 12], // also can be set through CSS
  5373. // iconAnchor: (Point),
  5374. // popupAnchor: (Point),
  5375. // @option html: String = ''
  5376. // Custom HTML code to put inside the div element, empty by default.
  5377. html: false,
  5378. // @option bgPos: Point = [0, 0]
  5379. // Optional relative position of the background, in pixels
  5380. bgPos: null,
  5381. className: 'leaflet-div-icon'
  5382. },
  5383. createIcon: function (oldIcon) {
  5384. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  5385. options = this.options;
  5386. div.innerHTML = options.html !== false ? options.html : '';
  5387. if (options.bgPos) {
  5388. var bgPos = L.point(options.bgPos);
  5389. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  5390. }
  5391. this._setIconStyles(div, 'icon');
  5392. return div;
  5393. },
  5394. createShadow: function () {
  5395. return null;
  5396. }
  5397. });
  5398. // @factory L.divIcon(options: DivIcon options)
  5399. // Creates a `DivIcon` instance with the given options.
  5400. L.divIcon = function (options) {
  5401. return new L.DivIcon(options);
  5402. };
  5403. /*
  5404. * @class DivOverlay
  5405. * @inherits Layer
  5406. * @aka L.DivOverlay
  5407. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  5408. */
  5409. // @namespace DivOverlay
  5410. L.DivOverlay = L.Layer.extend({
  5411. // @section
  5412. // @aka DivOverlay options
  5413. options: {
  5414. // @option offset: Point = Point(0, 7)
  5415. // The offset of the popup position. Useful to control the anchor
  5416. // of the popup when opening it on some overlays.
  5417. offset: [0, 7],
  5418. // @option className: String = ''
  5419. // A custom CSS class name to assign to the popup.
  5420. className: '',
  5421. // @option pane: String = 'popupPane'
  5422. // `Map pane` where the popup will be added.
  5423. pane: 'popupPane'
  5424. },
  5425. initialize: function (options, source) {
  5426. L.setOptions(this, options);
  5427. this._source = source;
  5428. },
  5429. onAdd: function (map) {
  5430. this._zoomAnimated = map._zoomAnimated;
  5431. if (!this._container) {
  5432. this._initLayout();
  5433. }
  5434. if (map._fadeAnimated) {
  5435. L.DomUtil.setOpacity(this._container, 0);
  5436. }
  5437. clearTimeout(this._removeTimeout);
  5438. this.getPane().appendChild(this._container);
  5439. this.update();
  5440. if (map._fadeAnimated) {
  5441. L.DomUtil.setOpacity(this._container, 1);
  5442. }
  5443. this.bringToFront();
  5444. },
  5445. onRemove: function (map) {
  5446. if (map._fadeAnimated) {
  5447. L.DomUtil.setOpacity(this._container, 0);
  5448. this._removeTimeout = setTimeout(L.bind(L.DomUtil.remove, L.DomUtil, this._container), 200);
  5449. } else {
  5450. L.DomUtil.remove(this._container);
  5451. }
  5452. },
  5453. // @namespace Popup
  5454. // @method getLatLng: LatLng
  5455. // Returns the geographical point of popup.
  5456. getLatLng: function () {
  5457. return this._latlng;
  5458. },
  5459. // @method setLatLng(latlng: LatLng): this
  5460. // Sets the geographical point where the popup will open.
  5461. setLatLng: function (latlng) {
  5462. this._latlng = L.latLng(latlng);
  5463. if (this._map) {
  5464. this._updatePosition();
  5465. this._adjustPan();
  5466. }
  5467. return this;
  5468. },
  5469. // @method getContent: String|HTMLElement
  5470. // Returns the content of the popup.
  5471. getContent: function () {
  5472. return this._content;
  5473. },
  5474. // @method setContent(htmlContent: String|HTMLElement|Function): this
  5475. // Sets the HTML content of the popup. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the popup.
  5476. setContent: function (content) {
  5477. this._content = content;
  5478. this.update();
  5479. return this;
  5480. },
  5481. // @method getElement: String|HTMLElement
  5482. // Alias for [getContent()](#popup-getcontent)
  5483. getElement: function () {
  5484. return this._container;
  5485. },
  5486. // @method update: null
  5487. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  5488. update: function () {
  5489. if (!this._map) { return; }
  5490. this._container.style.visibility = 'hidden';
  5491. this._updateContent();
  5492. this._updateLayout();
  5493. this._updatePosition();
  5494. this._container.style.visibility = '';
  5495. this._adjustPan();
  5496. },
  5497. getEvents: function () {
  5498. var events = {
  5499. zoom: this._updatePosition,
  5500. viewreset: this._updatePosition
  5501. };
  5502. if (this._zoomAnimated) {
  5503. events.zoomanim = this._animateZoom;
  5504. }
  5505. return events;
  5506. },
  5507. // @method isOpen: Boolean
  5508. // Returns `true` when the popup is visible on the map.
  5509. isOpen: function () {
  5510. return !!this._map && this._map.hasLayer(this);
  5511. },
  5512. // @method bringToFront: this
  5513. // Brings this popup in front of other popups (in the same map pane).
  5514. bringToFront: function () {
  5515. if (this._map) {
  5516. L.DomUtil.toFront(this._container);
  5517. }
  5518. return this;
  5519. },
  5520. // @method bringToBack: this
  5521. // Brings this popup to the back of other popups (in the same map pane).
  5522. bringToBack: function () {
  5523. if (this._map) {
  5524. L.DomUtil.toBack(this._container);
  5525. }
  5526. return this;
  5527. },
  5528. _updateContent: function () {
  5529. if (!this._content) { return; }
  5530. var node = this._contentNode;
  5531. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  5532. if (typeof content === 'string') {
  5533. node.innerHTML = content;
  5534. } else {
  5535. while (node.hasChildNodes()) {
  5536. node.removeChild(node.firstChild);
  5537. }
  5538. node.appendChild(content);
  5539. }
  5540. this.fire('contentupdate');
  5541. },
  5542. _updatePosition: function () {
  5543. if (!this._map) { return; }
  5544. var pos = this._map.latLngToLayerPoint(this._latlng),
  5545. offset = L.point(this.options.offset),
  5546. anchor = this._getAnchor();
  5547. if (this._zoomAnimated) {
  5548. L.DomUtil.setPosition(this._container, pos.add(anchor));
  5549. } else {
  5550. offset = offset.add(pos).add(anchor);
  5551. }
  5552. var bottom = this._containerBottom = -offset.y,
  5553. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  5554. // bottom position the popup in case the height of the popup changes (images loading etc)
  5555. this._container.style.bottom = bottom + 'px';
  5556. this._container.style.left = left + 'px';
  5557. },
  5558. _getAnchor: function () {
  5559. return [0, 0];
  5560. }
  5561. });
  5562. /*
  5563. * @class Popup
  5564. * @inherits DivOverlay
  5565. * @aka L.Popup
  5566. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  5567. * open popups while making sure that only one popup is open at one time
  5568. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  5569. *
  5570. * @example
  5571. *
  5572. * If you want to just bind a popup to marker click and then open it, it's really easy:
  5573. *
  5574. * ```js
  5575. * marker.bindPopup(popupContent).openPopup();
  5576. * ```
  5577. * Path overlays like polylines also have a `bindPopup` method.
  5578. * Here's a more complicated way to open a popup on a map:
  5579. *
  5580. * ```js
  5581. * var popup = L.popup()
  5582. * .setLatLng(latlng)
  5583. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  5584. * .openOn(map);
  5585. * ```
  5586. */
  5587. // @namespace Popup
  5588. L.Popup = L.DivOverlay.extend({
  5589. // @section
  5590. // @aka Popup options
  5591. options: {
  5592. // @option maxWidth: Number = 300
  5593. // Max width of the popup, in pixels.
  5594. maxWidth: 300,
  5595. // @option minWidth: Number = 50
  5596. // Min width of the popup, in pixels.
  5597. minWidth: 50,
  5598. // @option maxHeight: Number = null
  5599. // If set, creates a scrollable container of the given height
  5600. // inside a popup if its content exceeds it.
  5601. maxHeight: null,
  5602. // @option autoPan: Boolean = true
  5603. // Set it to `false` if you don't want the map to do panning animation
  5604. // to fit the opened popup.
  5605. autoPan: true,
  5606. // @option autoPanPaddingTopLeft: Point = null
  5607. // The margin between the popup and the top left corner of the map
  5608. // view after autopanning was performed.
  5609. autoPanPaddingTopLeft: null,
  5610. // @option autoPanPaddingBottomRight: Point = null
  5611. // The margin between the popup and the bottom right corner of the map
  5612. // view after autopanning was performed.
  5613. autoPanPaddingBottomRight: null,
  5614. // @option autoPanPadding: Point = Point(5, 5)
  5615. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  5616. autoPanPadding: [5, 5],
  5617. // @option keepInView: Boolean = false
  5618. // Set it to `true` if you want to prevent users from panning the popup
  5619. // off of the screen while it is open.
  5620. keepInView: false,
  5621. // @option closeButton: Boolean = true
  5622. // Controls the presence of a close button in the popup.
  5623. closeButton: true,
  5624. // @option autoClose: Boolean = true
  5625. // Set it to `false` if you want to override the default behavior of
  5626. // the popup closing when user clicks the map (set globally by
  5627. // the Map's [closePopupOnClick](#map-closepopuponclick) option).
  5628. autoClose: true,
  5629. // @option className: String = ''
  5630. // A custom CSS class name to assign to the popup.
  5631. className: ''
  5632. },
  5633. // @namespace Popup
  5634. // @method openOn(map: Map): this
  5635. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  5636. openOn: function (map) {
  5637. map.openPopup(this);
  5638. return this;
  5639. },
  5640. onAdd: function (map) {
  5641. L.DivOverlay.prototype.onAdd.call(this, map);
  5642. // @namespace Map
  5643. // @section Popup events
  5644. // @event popupopen: PopupEvent
  5645. // Fired when a popup is opened in the map
  5646. map.fire('popupopen', {popup: this});
  5647. if (this._source) {
  5648. // @namespace Layer
  5649. // @section Popup events
  5650. // @event popupopen: PopupEvent
  5651. // Fired when a popup bound to this layer is opened
  5652. this._source.fire('popupopen', {popup: this}, true);
  5653. // For non-path layers, we toggle the popup when clicking
  5654. // again the layer, so prevent the map to reopen it.
  5655. if (!(this._source instanceof L.Path)) {
  5656. this._source.on('preclick', L.DomEvent.stopPropagation);
  5657. }
  5658. }
  5659. },
  5660. onRemove: function (map) {
  5661. L.DivOverlay.prototype.onRemove.call(this, map);
  5662. // @namespace Map
  5663. // @section Popup events
  5664. // @event popupclose: PopupEvent
  5665. // Fired when a popup in the map is closed
  5666. map.fire('popupclose', {popup: this});
  5667. if (this._source) {
  5668. // @namespace Layer
  5669. // @section Popup events
  5670. // @event popupclose: PopupEvent
  5671. // Fired when a popup bound to this layer is closed
  5672. this._source.fire('popupclose', {popup: this}, true);
  5673. if (!(this._source instanceof L.Path)) {
  5674. this._source.off('preclick', L.DomEvent.stopPropagation);
  5675. }
  5676. }
  5677. },
  5678. getEvents: function () {
  5679. var events = L.DivOverlay.prototype.getEvents.call(this);
  5680. if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  5681. events.preclick = this._close;
  5682. }
  5683. if (this.options.keepInView) {
  5684. events.moveend = this._adjustPan;
  5685. }
  5686. return events;
  5687. },
  5688. _close: function () {
  5689. if (this._map) {
  5690. this._map.closePopup(this);
  5691. }
  5692. },
  5693. _initLayout: function () {
  5694. var prefix = 'leaflet-popup',
  5695. container = this._container = L.DomUtil.create('div',
  5696. prefix + ' ' + (this.options.className || '') +
  5697. ' leaflet-zoom-animated');
  5698. if (this.options.closeButton) {
  5699. var closeButton = this._closeButton = L.DomUtil.create('a', prefix + '-close-button', container);
  5700. closeButton.href = '#close';
  5701. closeButton.innerHTML = '&#215;';
  5702. L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
  5703. }
  5704. var wrapper = this._wrapper = L.DomUtil.create('div', prefix + '-content-wrapper', container);
  5705. this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
  5706. L.DomEvent
  5707. .disableClickPropagation(wrapper)
  5708. .disableScrollPropagation(this._contentNode)
  5709. .on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
  5710. this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
  5711. this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
  5712. },
  5713. _updateLayout: function () {
  5714. var container = this._contentNode,
  5715. style = container.style;
  5716. style.width = '';
  5717. style.whiteSpace = 'nowrap';
  5718. var width = container.offsetWidth;
  5719. width = Math.min(width, this.options.maxWidth);
  5720. width = Math.max(width, this.options.minWidth);
  5721. style.width = (width + 1) + 'px';
  5722. style.whiteSpace = '';
  5723. style.height = '';
  5724. var height = container.offsetHeight,
  5725. maxHeight = this.options.maxHeight,
  5726. scrolledClass = 'leaflet-popup-scrolled';
  5727. if (maxHeight && height > maxHeight) {
  5728. style.height = maxHeight + 'px';
  5729. L.DomUtil.addClass(container, scrolledClass);
  5730. } else {
  5731. L.DomUtil.removeClass(container, scrolledClass);
  5732. }
  5733. this._containerWidth = this._container.offsetWidth;
  5734. },
  5735. _animateZoom: function (e) {
  5736. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  5737. anchor = this._getAnchor();
  5738. L.DomUtil.setPosition(this._container, pos.add(anchor));
  5739. },
  5740. _adjustPan: function () {
  5741. if (!this.options.autoPan || (this._map._panAnim && this._map._panAnim._inProgress)) { return; }
  5742. var map = this._map,
  5743. marginBottom = parseInt(L.DomUtil.getStyle(this._container, 'marginBottom'), 10) || 0,
  5744. containerHeight = this._container.offsetHeight + marginBottom,
  5745. containerWidth = this._containerWidth,
  5746. layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
  5747. layerPos._add(L.DomUtil.getPosition(this._container));
  5748. var containerPos = map.layerPointToContainerPoint(layerPos),
  5749. padding = L.point(this.options.autoPanPadding),
  5750. paddingTL = L.point(this.options.autoPanPaddingTopLeft || padding),
  5751. paddingBR = L.point(this.options.autoPanPaddingBottomRight || padding),
  5752. size = map.getSize(),
  5753. dx = 0,
  5754. dy = 0;
  5755. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  5756. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  5757. }
  5758. if (containerPos.x - dx - paddingTL.x < 0) { // left
  5759. dx = containerPos.x - paddingTL.x;
  5760. }
  5761. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  5762. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  5763. }
  5764. if (containerPos.y - dy - paddingTL.y < 0) { // top
  5765. dy = containerPos.y - paddingTL.y;
  5766. }
  5767. // @namespace Map
  5768. // @section Popup events
  5769. // @event autopanstart: Event
  5770. // Fired when the map starts autopanning when opening a popup.
  5771. if (dx || dy) {
  5772. map
  5773. .fire('autopanstart')
  5774. .panBy([dx, dy]);
  5775. }
  5776. },
  5777. _onCloseButtonClick: function (e) {
  5778. this._close();
  5779. L.DomEvent.stop(e);
  5780. },
  5781. _getAnchor: function () {
  5782. // Where should we anchor the popup on the source layer?
  5783. return L.point(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  5784. }
  5785. });
  5786. // @namespace Popup
  5787. // @factory L.popup(options?: Popup options, source?: Layer)
  5788. // Instantiates a `Popup` object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the popup with a reference to the Layer to which it refers.
  5789. L.popup = function (options, source) {
  5790. return new L.Popup(options, source);
  5791. };
  5792. /* @namespace Map
  5793. * @section Interaction Options
  5794. * @option closePopupOnClick: Boolean = true
  5795. * Set it to `false` if you don't want popups to close when user clicks the map.
  5796. */
  5797. L.Map.mergeOptions({
  5798. closePopupOnClick: true
  5799. });
  5800. // @namespace Map
  5801. // @section Methods for Layers and Controls
  5802. L.Map.include({
  5803. // @method openPopup(popup: Popup): this
  5804. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  5805. // @alternative
  5806. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  5807. // Creates a popup with the specified content and options and opens it in the given point on a map.
  5808. openPopup: function (popup, latlng, options) {
  5809. if (!(popup instanceof L.Popup)) {
  5810. popup = new L.Popup(options).setContent(popup);
  5811. }
  5812. if (latlng) {
  5813. popup.setLatLng(latlng);
  5814. }
  5815. if (this.hasLayer(popup)) {
  5816. return this;
  5817. }
  5818. if (this._popup && this._popup.options.autoClose) {
  5819. this.closePopup();
  5820. }
  5821. this._popup = popup;
  5822. return this.addLayer(popup);
  5823. },
  5824. // @method closePopup(popup?: Popup): this
  5825. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  5826. closePopup: function (popup) {
  5827. if (!popup || popup === this._popup) {
  5828. popup = this._popup;
  5829. this._popup = null;
  5830. }
  5831. if (popup) {
  5832. this.removeLayer(popup);
  5833. }
  5834. return this;
  5835. }
  5836. });
  5837. /*
  5838. * @namespace Layer
  5839. * @section Popup methods example
  5840. *
  5841. * All layers share a set of methods convenient for binding popups to it.
  5842. *
  5843. * ```js
  5844. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  5845. * layer.openPopup();
  5846. * layer.closePopup();
  5847. * ```
  5848. *
  5849. * Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened.
  5850. */
  5851. // @section Popup methods
  5852. L.Layer.include({
  5853. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  5854. // Binds a popup to the layer with the passed `content` and sets up the
  5855. // neccessary event listeners. If a `Function` is passed it will receive
  5856. // the layer as the first argument and should return a `String` or `HTMLElement`.
  5857. bindPopup: function (content, options) {
  5858. if (content instanceof L.Popup) {
  5859. L.setOptions(content, options);
  5860. this._popup = content;
  5861. content._source = this;
  5862. } else {
  5863. if (!this._popup || options) {
  5864. this._popup = new L.Popup(options, this);
  5865. }
  5866. this._popup.setContent(content);
  5867. }
  5868. if (!this._popupHandlersAdded) {
  5869. this.on({
  5870. click: this._openPopup,
  5871. remove: this.closePopup,
  5872. move: this._movePopup
  5873. });
  5874. this._popupHandlersAdded = true;
  5875. }
  5876. return this;
  5877. },
  5878. // @method unbindPopup(): this
  5879. // Removes the popup previously bound with `bindPopup`.
  5880. unbindPopup: function () {
  5881. if (this._popup) {
  5882. this.off({
  5883. click: this._openPopup,
  5884. remove: this.closePopup,
  5885. move: this._movePopup
  5886. });
  5887. this._popupHandlersAdded = false;
  5888. this._popup = null;
  5889. }
  5890. return this;
  5891. },
  5892. // @method openPopup(latlng?: LatLng): this
  5893. // Opens the bound popup at the specificed `latlng` or at the default popup anchor if no `latlng` is passed.
  5894. openPopup: function (layer, latlng) {
  5895. if (!(layer instanceof L.Layer)) {
  5896. latlng = layer;
  5897. layer = this;
  5898. }
  5899. if (layer instanceof L.FeatureGroup) {
  5900. for (var id in this._layers) {
  5901. layer = this._layers[id];
  5902. break;
  5903. }
  5904. }
  5905. if (!latlng) {
  5906. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  5907. }
  5908. if (this._popup && this._map) {
  5909. // set popup source to this layer
  5910. this._popup._source = layer;
  5911. // update the popup (content, layout, ect...)
  5912. this._popup.update();
  5913. // open the popup on the map
  5914. this._map.openPopup(this._popup, latlng);
  5915. }
  5916. return this;
  5917. },
  5918. // @method closePopup(): this
  5919. // Closes the popup bound to this layer if it is open.
  5920. closePopup: function () {
  5921. if (this._popup) {
  5922. this._popup._close();
  5923. }
  5924. return this;
  5925. },
  5926. // @method togglePopup(): this
  5927. // Opens or closes the popup bound to this layer depending on its current state.
  5928. togglePopup: function (target) {
  5929. if (this._popup) {
  5930. if (this._popup._map) {
  5931. this.closePopup();
  5932. } else {
  5933. this.openPopup(target);
  5934. }
  5935. }
  5936. return this;
  5937. },
  5938. // @method isPopupOpen(): boolean
  5939. // Returns `true` if the popup bound to this layer is currently open.
  5940. isPopupOpen: function () {
  5941. return (this._popup ? this._popup.isOpen() : false);
  5942. },
  5943. // @method setPopupContent(content: String|HTMLElement|Popup): this
  5944. // Sets the content of the popup bound to this layer.
  5945. setPopupContent: function (content) {
  5946. if (this._popup) {
  5947. this._popup.setContent(content);
  5948. }
  5949. return this;
  5950. },
  5951. // @method getPopup(): Popup
  5952. // Returns the popup bound to this layer.
  5953. getPopup: function () {
  5954. return this._popup;
  5955. },
  5956. _openPopup: function (e) {
  5957. var layer = e.layer || e.target;
  5958. if (!this._popup) {
  5959. return;
  5960. }
  5961. if (!this._map) {
  5962. return;
  5963. }
  5964. // prevent map click
  5965. L.DomEvent.stop(e);
  5966. // if this inherits from Path its a vector and we can just
  5967. // open the popup at the new location
  5968. if (layer instanceof L.Path) {
  5969. this.openPopup(e.layer || e.target, e.latlng);
  5970. return;
  5971. }
  5972. // otherwise treat it like a marker and figure out
  5973. // if we should toggle it open/closed
  5974. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  5975. this.closePopup();
  5976. } else {
  5977. this.openPopup(layer, e.latlng);
  5978. }
  5979. },
  5980. _movePopup: function (e) {
  5981. this._popup.setLatLng(e.latlng);
  5982. }
  5983. });
  5984. /*
  5985. * @class Tooltip
  5986. * @inherits DivOverlay
  5987. * @aka L.Tooltip
  5988. * Used to display small texts on top of map layers.
  5989. *
  5990. * @example
  5991. *
  5992. * ```js
  5993. * marker.bindTooltip("my tooltip text").openTooltip();
  5994. * ```
  5995. * Note about tooltip offset. Leaflet takes two options in consideration
  5996. * for computing tooltip offseting:
  5997. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  5998. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  5999. * move it to the bottom. Negatives will move to the left and top.
  6000. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  6001. * should adapt this value if you use a custom icon.
  6002. */
  6003. // @namespace Tooltip
  6004. L.Tooltip = L.DivOverlay.extend({
  6005. // @section
  6006. // @aka Tooltip options
  6007. options: {
  6008. // @option pane: String = 'tooltipPane'
  6009. // `Map pane` where the tooltip will be added.
  6010. pane: 'tooltipPane',
  6011. // @option offset: Point = Point(0, 0)
  6012. // Optional offset of the tooltip position.
  6013. offset: [0, 0],
  6014. // @option direction: String = 'auto'
  6015. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  6016. // `top`, `bottom`, `center`, `auto`.
  6017. // `auto` will dynamicaly switch between `right` and `left` according to the tooltip
  6018. // position on the map.
  6019. direction: 'auto',
  6020. // @option permanent: Boolean = false
  6021. // Whether to open the tooltip permanently or only on mouseover.
  6022. permanent: false,
  6023. // @option sticky: Boolean = false
  6024. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  6025. sticky: false,
  6026. // @option interactive: Boolean = false
  6027. // If true, the tooltip will listen to the feature events.
  6028. interactive: false,
  6029. // @option opacity: Number = 0.9
  6030. // Tooltip container opacity.
  6031. opacity: 0.9
  6032. },
  6033. onAdd: function (map) {
  6034. L.DivOverlay.prototype.onAdd.call(this, map);
  6035. this.setOpacity(this.options.opacity);
  6036. // @namespace Map
  6037. // @section Tooltip events
  6038. // @event tooltipopen: TooltipEvent
  6039. // Fired when a tooltip is opened in the map.
  6040. map.fire('tooltipopen', {tooltip: this});
  6041. if (this._source) {
  6042. // @namespace Layer
  6043. // @section Tooltip events
  6044. // @event tooltipopen: TooltipEvent
  6045. // Fired when a tooltip bound to this layer is opened.
  6046. this._source.fire('tooltipopen', {tooltip: this}, true);
  6047. }
  6048. },
  6049. onRemove: function (map) {
  6050. L.DivOverlay.prototype.onRemove.call(this, map);
  6051. // @namespace Map
  6052. // @section Tooltip events
  6053. // @event tooltipclose: TooltipEvent
  6054. // Fired when a tooltip in the map is closed.
  6055. map.fire('tooltipclose', {tooltip: this});
  6056. if (this._source) {
  6057. // @namespace Layer
  6058. // @section Tooltip events
  6059. // @event tooltipclose: TooltipEvent
  6060. // Fired when a tooltip bound to this layer is closed.
  6061. this._source.fire('tooltipclose', {tooltip: this}, true);
  6062. }
  6063. },
  6064. getEvents: function () {
  6065. var events = L.DivOverlay.prototype.getEvents.call(this);
  6066. if (L.Browser.touch && !this.options.permanent) {
  6067. events.preclick = this._close;
  6068. }
  6069. return events;
  6070. },
  6071. _close: function () {
  6072. if (this._map) {
  6073. this._map.closeTooltip(this);
  6074. }
  6075. },
  6076. _initLayout: function () {
  6077. var prefix = 'leaflet-tooltip',
  6078. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6079. this._contentNode = this._container = L.DomUtil.create('div', className);
  6080. },
  6081. _updateLayout: function () {},
  6082. _adjustPan: function () {},
  6083. _setPosition: function (pos) {
  6084. var map = this._map,
  6085. container = this._container,
  6086. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  6087. tooltipPoint = map.layerPointToContainerPoint(pos),
  6088. direction = this.options.direction,
  6089. tooltipWidth = container.offsetWidth,
  6090. tooltipHeight = container.offsetHeight,
  6091. offset = L.point(this.options.offset),
  6092. anchor = this._getAnchor();
  6093. if (direction === 'top') {
  6094. pos = pos.add(L.point(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true));
  6095. } else if (direction === 'bottom') {
  6096. pos = pos.subtract(L.point(tooltipWidth / 2 - offset.x, -offset.y, true));
  6097. } else if (direction === 'center') {
  6098. pos = pos.subtract(L.point(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true));
  6099. } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
  6100. direction = 'right';
  6101. pos = pos.add(L.point(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true));
  6102. } else {
  6103. direction = 'left';
  6104. pos = pos.subtract(L.point(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true));
  6105. }
  6106. L.DomUtil.removeClass(container, 'leaflet-tooltip-right');
  6107. L.DomUtil.removeClass(container, 'leaflet-tooltip-left');
  6108. L.DomUtil.removeClass(container, 'leaflet-tooltip-top');
  6109. L.DomUtil.removeClass(container, 'leaflet-tooltip-bottom');
  6110. L.DomUtil.addClass(container, 'leaflet-tooltip-' + direction);
  6111. L.DomUtil.setPosition(container, pos);
  6112. },
  6113. _updatePosition: function () {
  6114. var pos = this._map.latLngToLayerPoint(this._latlng);
  6115. this._setPosition(pos);
  6116. },
  6117. setOpacity: function (opacity) {
  6118. this.options.opacity = opacity;
  6119. if (this._container) {
  6120. L.DomUtil.setOpacity(this._container, opacity);
  6121. }
  6122. },
  6123. _animateZoom: function (e) {
  6124. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  6125. this._setPosition(pos);
  6126. },
  6127. _getAnchor: function () {
  6128. // Where should we anchor the tooltip on the source layer?
  6129. return L.point(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  6130. }
  6131. });
  6132. // @namespace Tooltip
  6133. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  6134. // Instantiates a Tooltip object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the tooltip with a reference to the Layer to which it refers.
  6135. L.tooltip = function (options, source) {
  6136. return new L.Tooltip(options, source);
  6137. };
  6138. // @namespace Map
  6139. // @section Methods for Layers and Controls
  6140. L.Map.include({
  6141. // @method openTooltip(tooltip: Tooltip): this
  6142. // Opens the specified tooltip.
  6143. // @alternative
  6144. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  6145. // Creates a tooltip with the specified content and options and open it.
  6146. openTooltip: function (tooltip, latlng, options) {
  6147. if (!(tooltip instanceof L.Tooltip)) {
  6148. tooltip = new L.Tooltip(options).setContent(tooltip);
  6149. }
  6150. if (latlng) {
  6151. tooltip.setLatLng(latlng);
  6152. }
  6153. if (this.hasLayer(tooltip)) {
  6154. return this;
  6155. }
  6156. return this.addLayer(tooltip);
  6157. },
  6158. // @method closeTooltip(tooltip?: Tooltip): this
  6159. // Closes the tooltip given as parameter.
  6160. closeTooltip: function (tooltip) {
  6161. if (tooltip) {
  6162. this.removeLayer(tooltip);
  6163. }
  6164. return this;
  6165. }
  6166. });
  6167. /*
  6168. * @namespace Layer
  6169. * @section Tooltip methods example
  6170. *
  6171. * All layers share a set of methods convenient for binding tooltips to it.
  6172. *
  6173. * ```js
  6174. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  6175. * layer.openTooltip();
  6176. * layer.closeTooltip();
  6177. * ```
  6178. */
  6179. // @section Tooltip methods
  6180. L.Layer.include({
  6181. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  6182. // Binds a tooltip to the layer with the passed `content` and sets up the
  6183. // neccessary event listeners. If a `Function` is passed it will receive
  6184. // the layer as the first argument and should return a `String` or `HTMLElement`.
  6185. bindTooltip: function (content, options) {
  6186. if (content instanceof L.Tooltip) {
  6187. L.setOptions(content, options);
  6188. this._tooltip = content;
  6189. content._source = this;
  6190. } else {
  6191. if (!this._tooltip || options) {
  6192. this._tooltip = L.tooltip(options, this);
  6193. }
  6194. this._tooltip.setContent(content);
  6195. }
  6196. this._initTooltipInteractions();
  6197. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  6198. this.openTooltip();
  6199. }
  6200. return this;
  6201. },
  6202. // @method unbindTooltip(): this
  6203. // Removes the tooltip previously bound with `bindTooltip`.
  6204. unbindTooltip: function () {
  6205. if (this._tooltip) {
  6206. this._initTooltipInteractions(true);
  6207. this.closeTooltip();
  6208. this._tooltip = null;
  6209. }
  6210. return this;
  6211. },
  6212. _initTooltipInteractions: function (remove) {
  6213. if (!remove && this._tooltipHandlersAdded) { return; }
  6214. var onOff = remove ? 'off' : 'on',
  6215. events = {
  6216. remove: this.closeTooltip,
  6217. move: this._moveTooltip
  6218. };
  6219. if (!this._tooltip.options.permanent) {
  6220. events.mouseover = this._openTooltip;
  6221. events.mouseout = this.closeTooltip;
  6222. if (this._tooltip.options.sticky) {
  6223. events.mousemove = this._moveTooltip;
  6224. }
  6225. if (L.Browser.touch) {
  6226. events.click = this._openTooltip;
  6227. }
  6228. } else {
  6229. events.add = this._openTooltip;
  6230. }
  6231. this[onOff](events);
  6232. this._tooltipHandlersAdded = !remove;
  6233. },
  6234. // @method openTooltip(latlng?: LatLng): this
  6235. // Opens the bound tooltip at the specificed `latlng` or at the default tooltip anchor if no `latlng` is passed.
  6236. openTooltip: function (layer, latlng) {
  6237. if (!(layer instanceof L.Layer)) {
  6238. latlng = layer;
  6239. layer = this;
  6240. }
  6241. if (layer instanceof L.FeatureGroup) {
  6242. for (var id in this._layers) {
  6243. layer = this._layers[id];
  6244. break;
  6245. }
  6246. }
  6247. if (!latlng) {
  6248. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  6249. }
  6250. if (this._tooltip && this._map) {
  6251. // set tooltip source to this layer
  6252. this._tooltip._source = layer;
  6253. // update the tooltip (content, layout, ect...)
  6254. this._tooltip.update();
  6255. // open the tooltip on the map
  6256. this._map.openTooltip(this._tooltip, latlng);
  6257. // Tooltip container may not be defined if not permanent and never
  6258. // opened.
  6259. if (this._tooltip.options.interactive && this._tooltip._container) {
  6260. L.DomUtil.addClass(this._tooltip._container, 'leaflet-clickable');
  6261. this.addInteractiveTarget(this._tooltip._container);
  6262. }
  6263. }
  6264. return this;
  6265. },
  6266. // @method closeTooltip(): this
  6267. // Closes the tooltip bound to this layer if it is open.
  6268. closeTooltip: function () {
  6269. if (this._tooltip) {
  6270. this._tooltip._close();
  6271. if (this._tooltip.options.interactive && this._tooltip._container) {
  6272. L.DomUtil.removeClass(this._tooltip._container, 'leaflet-clickable');
  6273. this.removeInteractiveTarget(this._tooltip._container);
  6274. }
  6275. }
  6276. return this;
  6277. },
  6278. // @method toggleTooltip(): this
  6279. // Opens or closes the tooltip bound to this layer depending on its current state.
  6280. toggleTooltip: function (target) {
  6281. if (this._tooltip) {
  6282. if (this._tooltip._map) {
  6283. this.closeTooltip();
  6284. } else {
  6285. this.openTooltip(target);
  6286. }
  6287. }
  6288. return this;
  6289. },
  6290. // @method isTooltipOpen(): boolean
  6291. // Returns `true` if the tooltip bound to this layer is currently open.
  6292. isTooltipOpen: function () {
  6293. return this._tooltip.isOpen();
  6294. },
  6295. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  6296. // Sets the content of the tooltip bound to this layer.
  6297. setTooltipContent: function (content) {
  6298. if (this._tooltip) {
  6299. this._tooltip.setContent(content);
  6300. }
  6301. return this;
  6302. },
  6303. // @method getTooltip(): Tooltip
  6304. // Returns the tooltip bound to this layer.
  6305. getTooltip: function () {
  6306. return this._tooltip;
  6307. },
  6308. _openTooltip: function (e) {
  6309. var layer = e.layer || e.target;
  6310. if (!this._tooltip || !this._map) {
  6311. return;
  6312. }
  6313. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  6314. },
  6315. _moveTooltip: function (e) {
  6316. var latlng = e.latlng, containerPoint, layerPoint;
  6317. if (this._tooltip.options.sticky && e.originalEvent) {
  6318. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  6319. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  6320. latlng = this._map.layerPointToLatLng(layerPoint);
  6321. }
  6322. this._tooltip.setLatLng(latlng);
  6323. }
  6324. });
  6325. /*
  6326. * @class LayerGroup
  6327. * @aka L.LayerGroup
  6328. * @inherits Layer
  6329. *
  6330. * Used to group several layers and handle them as one. If you add it to the map,
  6331. * any layers added or removed from the group will be added/removed on the map as
  6332. * well. Extends `Layer`.
  6333. *
  6334. * @example
  6335. *
  6336. * ```js
  6337. * L.layerGroup([marker1, marker2])
  6338. * .addLayer(polyline)
  6339. * .addTo(map);
  6340. * ```
  6341. */
  6342. L.LayerGroup = L.Layer.extend({
  6343. initialize: function (layers) {
  6344. this._layers = {};
  6345. var i, len;
  6346. if (layers) {
  6347. for (i = 0, len = layers.length; i < len; i++) {
  6348. this.addLayer(layers[i]);
  6349. }
  6350. }
  6351. },
  6352. // @method addLayer(layer: Layer): this
  6353. // Adds the given layer to the group.
  6354. addLayer: function (layer) {
  6355. var id = this.getLayerId(layer);
  6356. this._layers[id] = layer;
  6357. if (this._map) {
  6358. this._map.addLayer(layer);
  6359. }
  6360. return this;
  6361. },
  6362. // @method removeLayer(layer: Layer): this
  6363. // Removes the given layer from the group.
  6364. // @alternative
  6365. // @method removeLayer(id: Number): this
  6366. // Removes the layer with the given internal ID from the group.
  6367. removeLayer: function (layer) {
  6368. var id = layer in this._layers ? layer : this.getLayerId(layer);
  6369. if (this._map && this._layers[id]) {
  6370. this._map.removeLayer(this._layers[id]);
  6371. }
  6372. delete this._layers[id];
  6373. return this;
  6374. },
  6375. // @method hasLayer(layer: Layer): Boolean
  6376. // Returns `true` if the given layer is currently added to the group.
  6377. hasLayer: function (layer) {
  6378. return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
  6379. },
  6380. // @method clearLayers(): this
  6381. // Removes all the layers from the group.
  6382. clearLayers: function () {
  6383. for (var i in this._layers) {
  6384. this.removeLayer(this._layers[i]);
  6385. }
  6386. return this;
  6387. },
  6388. // @method invoke(methodName: String, …): this
  6389. // Calls `methodName` on every layer contained in this group, passing any
  6390. // additional parameters. Has no effect if the layers contained do not
  6391. // implement `methodName`.
  6392. invoke: function (methodName) {
  6393. var args = Array.prototype.slice.call(arguments, 1),
  6394. i, layer;
  6395. for (i in this._layers) {
  6396. layer = this._layers[i];
  6397. if (layer[methodName]) {
  6398. layer[methodName].apply(layer, args);
  6399. }
  6400. }
  6401. return this;
  6402. },
  6403. onAdd: function (map) {
  6404. for (var i in this._layers) {
  6405. map.addLayer(this._layers[i]);
  6406. }
  6407. },
  6408. onRemove: function (map) {
  6409. for (var i in this._layers) {
  6410. map.removeLayer(this._layers[i]);
  6411. }
  6412. },
  6413. // @method eachLayer(fn: Function, context?: Object): this
  6414. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  6415. // ```js
  6416. // group.eachLayer(function (layer) {
  6417. // layer.bindPopup('Hello');
  6418. // });
  6419. // ```
  6420. eachLayer: function (method, context) {
  6421. for (var i in this._layers) {
  6422. method.call(context, this._layers[i]);
  6423. }
  6424. return this;
  6425. },
  6426. // @method getLayer(id: Number): Layer
  6427. // Returns the layer with the given internal ID.
  6428. getLayer: function (id) {
  6429. return this._layers[id];
  6430. },
  6431. // @method getLayers(): Layer[]
  6432. // Returns an array of all the layers added to the group.
  6433. getLayers: function () {
  6434. var layers = [];
  6435. for (var i in this._layers) {
  6436. layers.push(this._layers[i]);
  6437. }
  6438. return layers;
  6439. },
  6440. // @method setZIndex(zIndex: Number): this
  6441. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  6442. setZIndex: function (zIndex) {
  6443. return this.invoke('setZIndex', zIndex);
  6444. },
  6445. // @method getLayerId(layer: Layer): Number
  6446. // Returns the internal ID for a layer
  6447. getLayerId: function (layer) {
  6448. return L.stamp(layer);
  6449. }
  6450. });
  6451. // @factory L.layerGroup(layers: Layer[])
  6452. // Create a layer group, optionally given an initial set of layers.
  6453. L.layerGroup = function (layers) {
  6454. return new L.LayerGroup(layers);
  6455. };
  6456. /*
  6457. * @class FeatureGroup
  6458. * @aka L.FeatureGroup
  6459. * @inherits LayerGroup
  6460. *
  6461. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  6462. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  6463. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  6464. * handler, it will handle events from any of the layers. This includes mouse events
  6465. * and custom events.
  6466. * * Has `layeradd` and `layerremove` events
  6467. *
  6468. * @example
  6469. *
  6470. * ```js
  6471. * L.featureGroup([marker1, marker2, polyline])
  6472. * .bindPopup('Hello world!')
  6473. * .on('click', function() { alert('Clicked on a member of the group!'); })
  6474. * .addTo(map);
  6475. * ```
  6476. */
  6477. L.FeatureGroup = L.LayerGroup.extend({
  6478. addLayer: function (layer) {
  6479. if (this.hasLayer(layer)) {
  6480. return this;
  6481. }
  6482. layer.addEventParent(this);
  6483. L.LayerGroup.prototype.addLayer.call(this, layer);
  6484. // @event layeradd: LayerEvent
  6485. // Fired when a layer is added to this `FeatureGroup`
  6486. return this.fire('layeradd', {layer: layer});
  6487. },
  6488. removeLayer: function (layer) {
  6489. if (!this.hasLayer(layer)) {
  6490. return this;
  6491. }
  6492. if (layer in this._layers) {
  6493. layer = this._layers[layer];
  6494. }
  6495. layer.removeEventParent(this);
  6496. L.LayerGroup.prototype.removeLayer.call(this, layer);
  6497. // @event layerremove: LayerEvent
  6498. // Fired when a layer is removed from this `FeatureGroup`
  6499. return this.fire('layerremove', {layer: layer});
  6500. },
  6501. // @method setStyle(style: Path options): this
  6502. // Sets the given path options to each layer of the group that has a `setStyle` method.
  6503. setStyle: function (style) {
  6504. return this.invoke('setStyle', style);
  6505. },
  6506. // @method bringToFront(): this
  6507. // Brings the layer group to the top of all other layers
  6508. bringToFront: function () {
  6509. return this.invoke('bringToFront');
  6510. },
  6511. // @method bringToBack(): this
  6512. // Brings the layer group to the top of all other layers
  6513. bringToBack: function () {
  6514. return this.invoke('bringToBack');
  6515. },
  6516. // @method getBounds(): LatLngBounds
  6517. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  6518. getBounds: function () {
  6519. var bounds = new L.LatLngBounds();
  6520. for (var id in this._layers) {
  6521. var layer = this._layers[id];
  6522. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  6523. }
  6524. return bounds;
  6525. }
  6526. });
  6527. // @factory L.featureGroup(layers: Layer[])
  6528. // Create a feature group, optionally given an initial set of layers.
  6529. L.featureGroup = function (layers) {
  6530. return new L.FeatureGroup(layers);
  6531. };
  6532. /*
  6533. * @class Renderer
  6534. * @inherits Layer
  6535. * @aka L.Renderer
  6536. *
  6537. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  6538. * DOM container of the renderer, its bounds, and its zoom animation.
  6539. *
  6540. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  6541. * itself can be added or removed to the map. All paths use a renderer, which can
  6542. * be implicit (the map will decide the type of renderer and use it automatically)
  6543. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  6544. *
  6545. * Do not use this class directly, use `SVG` and `Canvas` instead.
  6546. *
  6547. * @event update: Event
  6548. * Fired when the renderer updates its bounds, center and zoom, for example when
  6549. * its map has moved
  6550. */
  6551. L.Renderer = L.Layer.extend({
  6552. // @section
  6553. // @aka Renderer options
  6554. options: {
  6555. // @option padding: Number = 0.1
  6556. // How much to extend the clip area around the map view (relative to its size)
  6557. // e.g. 0.1 would be 10% of map view in each direction
  6558. padding: 0.1
  6559. },
  6560. initialize: function (options) {
  6561. L.setOptions(this, options);
  6562. L.stamp(this);
  6563. this._layers = this._layers || {};
  6564. },
  6565. onAdd: function () {
  6566. if (!this._container) {
  6567. this._initContainer(); // defined by renderer implementations
  6568. if (this._zoomAnimated) {
  6569. L.DomUtil.addClass(this._container, 'leaflet-zoom-animated');
  6570. }
  6571. }
  6572. this.getPane().appendChild(this._container);
  6573. this._update();
  6574. this.on('update', this._updatePaths, this);
  6575. },
  6576. onRemove: function () {
  6577. L.DomUtil.remove(this._container);
  6578. this.off('update', this._updatePaths, this);
  6579. },
  6580. getEvents: function () {
  6581. var events = {
  6582. viewreset: this._reset,
  6583. zoom: this._onZoom,
  6584. moveend: this._update,
  6585. zoomend: this._onZoomEnd
  6586. };
  6587. if (this._zoomAnimated) {
  6588. events.zoomanim = this._onAnimZoom;
  6589. }
  6590. return events;
  6591. },
  6592. _onAnimZoom: function (ev) {
  6593. this._updateTransform(ev.center, ev.zoom);
  6594. },
  6595. _onZoom: function () {
  6596. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  6597. },
  6598. _updateTransform: function (center, zoom) {
  6599. var scale = this._map.getZoomScale(zoom, this._zoom),
  6600. position = L.DomUtil.getPosition(this._container),
  6601. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  6602. currentCenterPoint = this._map.project(this._center, zoom),
  6603. destCenterPoint = this._map.project(center, zoom),
  6604. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  6605. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  6606. if (L.Browser.any3d) {
  6607. L.DomUtil.setTransform(this._container, topLeftOffset, scale);
  6608. } else {
  6609. L.DomUtil.setPosition(this._container, topLeftOffset);
  6610. }
  6611. },
  6612. _reset: function () {
  6613. this._update();
  6614. this._updateTransform(this._center, this._zoom);
  6615. for (var id in this._layers) {
  6616. this._layers[id]._reset();
  6617. }
  6618. },
  6619. _onZoomEnd: function () {
  6620. for (var id in this._layers) {
  6621. this._layers[id]._project();
  6622. }
  6623. },
  6624. _updatePaths: function () {
  6625. for (var id in this._layers) {
  6626. this._layers[id]._update();
  6627. }
  6628. },
  6629. _update: function () {
  6630. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  6631. // Subclasses are responsible of firing the 'update' event.
  6632. var p = this.options.padding,
  6633. size = this._map.getSize(),
  6634. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  6635. this._bounds = new L.Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  6636. this._center = this._map.getCenter();
  6637. this._zoom = this._map.getZoom();
  6638. }
  6639. });
  6640. L.Map.include({
  6641. // @namespace Map; @method getRenderer(layer: Path): Renderer
  6642. // Returns the instance of `Renderer` that should be used to render the given
  6643. // `Path`. It will ensure that the `renderer` options of the map and paths
  6644. // are respected, and that the renderers do exist on the map.
  6645. getRenderer: function (layer) {
  6646. // @namespace Path; @option renderer: Renderer
  6647. // Use this specific instance of `Renderer` for this path. Takes
  6648. // precedence over the map's [default renderer](#map-renderer).
  6649. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  6650. if (!renderer) {
  6651. // @namespace Map; @option preferCanvas: Boolean = false
  6652. // Whether `Path`s should be rendered on a `Canvas` renderer.
  6653. // By default, all `Path`s are rendered in a `SVG` renderer.
  6654. renderer = this._renderer = (this.options.preferCanvas && L.canvas()) || L.svg();
  6655. }
  6656. if (!this.hasLayer(renderer)) {
  6657. this.addLayer(renderer);
  6658. }
  6659. return renderer;
  6660. },
  6661. _getPaneRenderer: function (name) {
  6662. if (name === 'overlayPane' || name === undefined) {
  6663. return false;
  6664. }
  6665. var renderer = this._paneRenderers[name];
  6666. if (renderer === undefined) {
  6667. renderer = (L.SVG && L.svg({pane: name})) || (L.Canvas && L.canvas({pane: name}));
  6668. this._paneRenderers[name] = renderer;
  6669. }
  6670. return renderer;
  6671. }
  6672. });
  6673. /*
  6674. * @class Path
  6675. * @aka L.Path
  6676. * @inherits Interactive layer
  6677. *
  6678. * An abstract class that contains options and constants shared between vector
  6679. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6680. */
  6681. L.Path = L.Layer.extend({
  6682. // @section
  6683. // @aka Path options
  6684. options: {
  6685. // @option stroke: Boolean = true
  6686. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6687. stroke: true,
  6688. // @option color: String = '#3388ff'
  6689. // Stroke color
  6690. color: '#3388ff',
  6691. // @option weight: Number = 3
  6692. // Stroke width in pixels
  6693. weight: 3,
  6694. // @option opacity: Number = 1.0
  6695. // Stroke opacity
  6696. opacity: 1,
  6697. // @option lineCap: String= 'round'
  6698. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6699. lineCap: 'round',
  6700. // @option lineJoin: String = 'round'
  6701. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6702. lineJoin: 'round',
  6703. // @option dashArray: String = null
  6704. // A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
  6705. dashArray: null,
  6706. // @option dashOffset: String = null
  6707. // A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
  6708. dashOffset: null,
  6709. // @option fill: Boolean = depends
  6710. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6711. fill: false,
  6712. // @option fillColor: String = *
  6713. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6714. fillColor: null,
  6715. // @option fillOpacity: Number = 0.2
  6716. // Fill opacity.
  6717. fillOpacity: 0.2,
  6718. // @option fillRule: String = 'evenodd'
  6719. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6720. fillRule: 'evenodd',
  6721. // className: '',
  6722. // Option inherited from "Interactive layer" abstract class
  6723. interactive: true
  6724. },
  6725. beforeAdd: function (map) {
  6726. // Renderer is set here because we need to call renderer.getEvents
  6727. // before this.getEvents.
  6728. this._renderer = map.getRenderer(this);
  6729. },
  6730. onAdd: function () {
  6731. this._renderer._initPath(this);
  6732. this._reset();
  6733. this._renderer._addPath(this);
  6734. },
  6735. onRemove: function () {
  6736. this._renderer._removePath(this);
  6737. },
  6738. // @method redraw(): this
  6739. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6740. redraw: function () {
  6741. if (this._map) {
  6742. this._renderer._updatePath(this);
  6743. }
  6744. return this;
  6745. },
  6746. // @method setStyle(style: Path options): this
  6747. // Changes the appearance of a Path based on the options in the `Path options` object.
  6748. setStyle: function (style) {
  6749. L.setOptions(this, style);
  6750. if (this._renderer) {
  6751. this._renderer._updateStyle(this);
  6752. }
  6753. return this;
  6754. },
  6755. // @method bringToFront(): this
  6756. // Brings the layer to the top of all path layers.
  6757. bringToFront: function () {
  6758. if (this._renderer) {
  6759. this._renderer._bringToFront(this);
  6760. }
  6761. return this;
  6762. },
  6763. // @method bringToBack(): this
  6764. // Brings the layer to the bottom of all path layers.
  6765. bringToBack: function () {
  6766. if (this._renderer) {
  6767. this._renderer._bringToBack(this);
  6768. }
  6769. return this;
  6770. },
  6771. getElement: function () {
  6772. return this._path;
  6773. },
  6774. _reset: function () {
  6775. // defined in children classes
  6776. this._project();
  6777. this._update();
  6778. },
  6779. _clickTolerance: function () {
  6780. // used when doing hit detection for Canvas layers
  6781. return (this.options.stroke ? this.options.weight / 2 : 0) + (L.Browser.touch ? 10 : 0);
  6782. }
  6783. });
  6784. /*
  6785. * @namespace LineUtil
  6786. *
  6787. * Various utility functions for polyine points processing, used by Leaflet internally to make polylines lightning-fast.
  6788. */
  6789. L.LineUtil = {
  6790. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  6791. // Improves rendering performance dramatically by lessening the number of points to draw.
  6792. // @function simplify(points: Point[], tolerance: Number): Point[]
  6793. // Dramatically reduces the number of points in a polyline while retaining
  6794. // its shape and returns a new array of simplified points, using the
  6795. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  6796. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  6797. // each zoom level and also reducing visual noise. tolerance affects the amount of
  6798. // simplification (lesser value means higher quality but slower and with more points).
  6799. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  6800. simplify: function (points, tolerance) {
  6801. if (!tolerance || !points.length) {
  6802. return points.slice();
  6803. }
  6804. var sqTolerance = tolerance * tolerance;
  6805. // stage 1: vertex reduction
  6806. points = this._reducePoints(points, sqTolerance);
  6807. // stage 2: Douglas-Peucker simplification
  6808. points = this._simplifyDP(points, sqTolerance);
  6809. return points;
  6810. },
  6811. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  6812. // Returns the distance between point `p` and segment `p1` to `p2`.
  6813. pointToSegmentDistance: function (p, p1, p2) {
  6814. return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
  6815. },
  6816. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  6817. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  6818. closestPointOnSegment: function (p, p1, p2) {
  6819. return this._sqClosestPointOnSegment(p, p1, p2);
  6820. },
  6821. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  6822. _simplifyDP: function (points, sqTolerance) {
  6823. var len = points.length,
  6824. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  6825. markers = new ArrayConstructor(len);
  6826. markers[0] = markers[len - 1] = 1;
  6827. this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  6828. var i,
  6829. newPoints = [];
  6830. for (i = 0; i < len; i++) {
  6831. if (markers[i]) {
  6832. newPoints.push(points[i]);
  6833. }
  6834. }
  6835. return newPoints;
  6836. },
  6837. _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
  6838. var maxSqDist = 0,
  6839. index, i, sqDist;
  6840. for (i = first + 1; i <= last - 1; i++) {
  6841. sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
  6842. if (sqDist > maxSqDist) {
  6843. index = i;
  6844. maxSqDist = sqDist;
  6845. }
  6846. }
  6847. if (maxSqDist > sqTolerance) {
  6848. markers[index] = 1;
  6849. this._simplifyDPStep(points, markers, sqTolerance, first, index);
  6850. this._simplifyDPStep(points, markers, sqTolerance, index, last);
  6851. }
  6852. },
  6853. // reduce points that are too close to each other to a single point
  6854. _reducePoints: function (points, sqTolerance) {
  6855. var reducedPoints = [points[0]];
  6856. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  6857. if (this._sqDist(points[i], points[prev]) > sqTolerance) {
  6858. reducedPoints.push(points[i]);
  6859. prev = i;
  6860. }
  6861. }
  6862. if (prev < len - 1) {
  6863. reducedPoints.push(points[len - 1]);
  6864. }
  6865. return reducedPoints;
  6866. },
  6867. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  6868. // Clips the segment a to b by rectangular bounds with the
  6869. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  6870. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  6871. // points that are on the screen or near, increasing performance.
  6872. clipSegment: function (a, b, bounds, useLastCode, round) {
  6873. var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
  6874. codeB = this._getBitCode(b, bounds),
  6875. codeOut, p, newCode;
  6876. // save 2nd code to avoid calculating it on the next segment
  6877. this._lastCode = codeB;
  6878. while (true) {
  6879. // if a,b is inside the clip window (trivial accept)
  6880. if (!(codeA | codeB)) {
  6881. return [a, b];
  6882. }
  6883. // if a,b is outside the clip window (trivial reject)
  6884. if (codeA & codeB) {
  6885. return false;
  6886. }
  6887. // other cases
  6888. codeOut = codeA || codeB;
  6889. p = this._getEdgeIntersection(a, b, codeOut, bounds, round);
  6890. newCode = this._getBitCode(p, bounds);
  6891. if (codeOut === codeA) {
  6892. a = p;
  6893. codeA = newCode;
  6894. } else {
  6895. b = p;
  6896. codeB = newCode;
  6897. }
  6898. }
  6899. },
  6900. _getEdgeIntersection: function (a, b, code, bounds, round) {
  6901. var dx = b.x - a.x,
  6902. dy = b.y - a.y,
  6903. min = bounds.min,
  6904. max = bounds.max,
  6905. x, y;
  6906. if (code & 8) { // top
  6907. x = a.x + dx * (max.y - a.y) / dy;
  6908. y = max.y;
  6909. } else if (code & 4) { // bottom
  6910. x = a.x + dx * (min.y - a.y) / dy;
  6911. y = min.y;
  6912. } else if (code & 2) { // right
  6913. x = max.x;
  6914. y = a.y + dy * (max.x - a.x) / dx;
  6915. } else if (code & 1) { // left
  6916. x = min.x;
  6917. y = a.y + dy * (min.x - a.x) / dx;
  6918. }
  6919. return new L.Point(x, y, round);
  6920. },
  6921. _getBitCode: function (p, bounds) {
  6922. var code = 0;
  6923. if (p.x < bounds.min.x) { // left
  6924. code |= 1;
  6925. } else if (p.x > bounds.max.x) { // right
  6926. code |= 2;
  6927. }
  6928. if (p.y < bounds.min.y) { // bottom
  6929. code |= 4;
  6930. } else if (p.y > bounds.max.y) { // top
  6931. code |= 8;
  6932. }
  6933. return code;
  6934. },
  6935. // square distance (to avoid unnecessary Math.sqrt calls)
  6936. _sqDist: function (p1, p2) {
  6937. var dx = p2.x - p1.x,
  6938. dy = p2.y - p1.y;
  6939. return dx * dx + dy * dy;
  6940. },
  6941. // return closest point on segment or distance to that point
  6942. _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
  6943. var x = p1.x,
  6944. y = p1.y,
  6945. dx = p2.x - x,
  6946. dy = p2.y - y,
  6947. dot = dx * dx + dy * dy,
  6948. t;
  6949. if (dot > 0) {
  6950. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  6951. if (t > 1) {
  6952. x = p2.x;
  6953. y = p2.y;
  6954. } else if (t > 0) {
  6955. x += dx * t;
  6956. y += dy * t;
  6957. }
  6958. }
  6959. dx = p.x - x;
  6960. dy = p.y - y;
  6961. return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
  6962. }
  6963. };
  6964. /*
  6965. * @class Polyline
  6966. * @aka L.Polyline
  6967. * @inherits Path
  6968. *
  6969. * A class for drawing polyline overlays on a map. Extends `Path`.
  6970. *
  6971. * @example
  6972. *
  6973. * ```js
  6974. * // create a red polyline from an array of LatLng points
  6975. * var latlngs = [
  6976. * [45.51, -122.68],
  6977. * [37.77, -122.43],
  6978. * [34.04, -118.2]
  6979. * ];
  6980. *
  6981. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6982. *
  6983. * // zoom the map to the polyline
  6984. * map.fitBounds(polyline.getBounds());
  6985. * ```
  6986. *
  6987. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6988. *
  6989. * ```js
  6990. * // create a red polyline from an array of arrays of LatLng points
  6991. * var latlngs = [
  6992. * [[45.51, -122.68],
  6993. * [37.77, -122.43],
  6994. * [34.04, -118.2]],
  6995. * [[40.78, -73.91],
  6996. * [41.83, -87.62],
  6997. * [32.76, -96.72]]
  6998. * ];
  6999. * ```
  7000. */
  7001. L.Polyline = L.Path.extend({
  7002. // @section
  7003. // @aka Polyline options
  7004. options: {
  7005. // @option smoothFactor: Number = 1.0
  7006. // How much to simplify the polyline on each zoom level. More means
  7007. // better performance and smoother look, and less means more accurate representation.
  7008. smoothFactor: 1.0,
  7009. // @option noClip: Boolean = false
  7010. // Disable polyline clipping.
  7011. noClip: false
  7012. },
  7013. initialize: function (latlngs, options) {
  7014. L.setOptions(this, options);
  7015. this._setLatLngs(latlngs);
  7016. },
  7017. // @method getLatLngs(): LatLng[]
  7018. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  7019. getLatLngs: function () {
  7020. return this._latlngs;
  7021. },
  7022. // @method setLatLngs(latlngs: LatLng[]): this
  7023. // Replaces all the points in the polyline with the given array of geographical points.
  7024. setLatLngs: function (latlngs) {
  7025. this._setLatLngs(latlngs);
  7026. return this.redraw();
  7027. },
  7028. // @method isEmpty(): Boolean
  7029. // Returns `true` if the Polyline has no LatLngs.
  7030. isEmpty: function () {
  7031. return !this._latlngs.length;
  7032. },
  7033. closestLayerPoint: function (p) {
  7034. var minDistance = Infinity,
  7035. minPoint = null,
  7036. closest = L.LineUtil._sqClosestPointOnSegment,
  7037. p1, p2;
  7038. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  7039. var points = this._parts[j];
  7040. for (var i = 1, len = points.length; i < len; i++) {
  7041. p1 = points[i - 1];
  7042. p2 = points[i];
  7043. var sqDist = closest(p, p1, p2, true);
  7044. if (sqDist < minDistance) {
  7045. minDistance = sqDist;
  7046. minPoint = closest(p, p1, p2);
  7047. }
  7048. }
  7049. }
  7050. if (minPoint) {
  7051. minPoint.distance = Math.sqrt(minDistance);
  7052. }
  7053. return minPoint;
  7054. },
  7055. // @method getCenter(): LatLng
  7056. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  7057. getCenter: function () {
  7058. // throws error when not yet added to map as this center calculation requires projected coordinates
  7059. if (!this._map) {
  7060. throw new Error('Must add layer to map before using getCenter()');
  7061. }
  7062. var i, halfDist, segDist, dist, p1, p2, ratio,
  7063. points = this._rings[0],
  7064. len = points.length;
  7065. if (!len) { return null; }
  7066. // polyline centroid algorithm; only uses the first ring if there are multiple
  7067. for (i = 0, halfDist = 0; i < len - 1; i++) {
  7068. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  7069. }
  7070. // The line is so small in the current view that all points are on the same pixel.
  7071. if (halfDist === 0) {
  7072. return this._map.layerPointToLatLng(points[0]);
  7073. }
  7074. for (i = 0, dist = 0; i < len - 1; i++) {
  7075. p1 = points[i];
  7076. p2 = points[i + 1];
  7077. segDist = p1.distanceTo(p2);
  7078. dist += segDist;
  7079. if (dist > halfDist) {
  7080. ratio = (dist - halfDist) / segDist;
  7081. return this._map.layerPointToLatLng([
  7082. p2.x - ratio * (p2.x - p1.x),
  7083. p2.y - ratio * (p2.y - p1.y)
  7084. ]);
  7085. }
  7086. }
  7087. },
  7088. // @method getBounds(): LatLngBounds
  7089. // Returns the `LatLngBounds` of the path.
  7090. getBounds: function () {
  7091. return this._bounds;
  7092. },
  7093. // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
  7094. // Adds a given point to the polyline. By default, adds to the first ring of
  7095. // the polyline in case of a multi-polyline, but can be overridden by passing
  7096. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  7097. addLatLng: function (latlng, latlngs) {
  7098. latlngs = latlngs || this._defaultShape();
  7099. latlng = L.latLng(latlng);
  7100. latlngs.push(latlng);
  7101. this._bounds.extend(latlng);
  7102. return this.redraw();
  7103. },
  7104. _setLatLngs: function (latlngs) {
  7105. this._bounds = new L.LatLngBounds();
  7106. this._latlngs = this._convertLatLngs(latlngs);
  7107. },
  7108. _defaultShape: function () {
  7109. return L.Polyline._flat(this._latlngs) ? this._latlngs : this._latlngs[0];
  7110. },
  7111. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  7112. _convertLatLngs: function (latlngs) {
  7113. var result = [],
  7114. flat = L.Polyline._flat(latlngs);
  7115. for (var i = 0, len = latlngs.length; i < len; i++) {
  7116. if (flat) {
  7117. result[i] = L.latLng(latlngs[i]);
  7118. this._bounds.extend(result[i]);
  7119. } else {
  7120. result[i] = this._convertLatLngs(latlngs[i]);
  7121. }
  7122. }
  7123. return result;
  7124. },
  7125. _project: function () {
  7126. var pxBounds = new L.Bounds();
  7127. this._rings = [];
  7128. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  7129. var w = this._clickTolerance(),
  7130. p = new L.Point(w, w);
  7131. if (this._bounds.isValid() && pxBounds.isValid()) {
  7132. pxBounds.min._subtract(p);
  7133. pxBounds.max._add(p);
  7134. this._pxBounds = pxBounds;
  7135. }
  7136. },
  7137. // recursively turns latlngs into a set of rings with projected coordinates
  7138. _projectLatlngs: function (latlngs, result, projectedBounds) {
  7139. var flat = latlngs[0] instanceof L.LatLng,
  7140. len = latlngs.length,
  7141. i, ring;
  7142. if (flat) {
  7143. ring = [];
  7144. for (i = 0; i < len; i++) {
  7145. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  7146. projectedBounds.extend(ring[i]);
  7147. }
  7148. result.push(ring);
  7149. } else {
  7150. for (i = 0; i < len; i++) {
  7151. this._projectLatlngs(latlngs[i], result, projectedBounds);
  7152. }
  7153. }
  7154. },
  7155. // clip polyline by renderer bounds so that we have less to render for performance
  7156. _clipPoints: function () {
  7157. var bounds = this._renderer._bounds;
  7158. this._parts = [];
  7159. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7160. return;
  7161. }
  7162. if (this.options.noClip) {
  7163. this._parts = this._rings;
  7164. return;
  7165. }
  7166. var parts = this._parts,
  7167. i, j, k, len, len2, segment, points;
  7168. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  7169. points = this._rings[i];
  7170. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  7171. segment = L.LineUtil.clipSegment(points[j], points[j + 1], bounds, j, true);
  7172. if (!segment) { continue; }
  7173. parts[k] = parts[k] || [];
  7174. parts[k].push(segment[0]);
  7175. // if segment goes out of screen, or it's the last one, it's the end of the line part
  7176. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  7177. parts[k].push(segment[1]);
  7178. k++;
  7179. }
  7180. }
  7181. }
  7182. },
  7183. // simplify each clipped part of the polyline for performance
  7184. _simplifyPoints: function () {
  7185. var parts = this._parts,
  7186. tolerance = this.options.smoothFactor;
  7187. for (var i = 0, len = parts.length; i < len; i++) {
  7188. parts[i] = L.LineUtil.simplify(parts[i], tolerance);
  7189. }
  7190. },
  7191. _update: function () {
  7192. if (!this._map) { return; }
  7193. this._clipPoints();
  7194. this._simplifyPoints();
  7195. this._updatePath();
  7196. },
  7197. _updatePath: function () {
  7198. this._renderer._updatePoly(this);
  7199. }
  7200. });
  7201. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  7202. // Instantiates a polyline object given an array of geographical points and
  7203. // optionally an options object. You can create a `Polyline` object with
  7204. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  7205. // of geographic points.
  7206. L.polyline = function (latlngs, options) {
  7207. return new L.Polyline(latlngs, options);
  7208. };
  7209. L.Polyline._flat = function (latlngs) {
  7210. // true if it's a flat array of latlngs; false if nested
  7211. return !L.Util.isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  7212. };
  7213. /*
  7214. * @namespace PolyUtil
  7215. * Various utility functions for polygon geometries.
  7216. */
  7217. L.PolyUtil = {};
  7218. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  7219. * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgeman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).
  7220. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  7221. * performance. Note that polygon points needs different algorithm for clipping
  7222. * than polyline, so there's a seperate method for it.
  7223. */
  7224. L.PolyUtil.clipPolygon = function (points, bounds, round) {
  7225. var clippedPoints,
  7226. edges = [1, 4, 2, 8],
  7227. i, j, k,
  7228. a, b,
  7229. len, edge, p,
  7230. lu = L.LineUtil;
  7231. for (i = 0, len = points.length; i < len; i++) {
  7232. points[i]._code = lu._getBitCode(points[i], bounds);
  7233. }
  7234. // for each edge (left, bottom, right, top)
  7235. for (k = 0; k < 4; k++) {
  7236. edge = edges[k];
  7237. clippedPoints = [];
  7238. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  7239. a = points[i];
  7240. b = points[j];
  7241. // if a is inside the clip window
  7242. if (!(a._code & edge)) {
  7243. // if b is outside the clip window (a->b goes out of screen)
  7244. if (b._code & edge) {
  7245. p = lu._getEdgeIntersection(b, a, edge, bounds, round);
  7246. p._code = lu._getBitCode(p, bounds);
  7247. clippedPoints.push(p);
  7248. }
  7249. clippedPoints.push(a);
  7250. // else if b is inside the clip window (a->b enters the screen)
  7251. } else if (!(b._code & edge)) {
  7252. p = lu._getEdgeIntersection(b, a, edge, bounds, round);
  7253. p._code = lu._getBitCode(p, bounds);
  7254. clippedPoints.push(p);
  7255. }
  7256. }
  7257. points = clippedPoints;
  7258. }
  7259. return points;
  7260. };
  7261. /*
  7262. * @class Polygon
  7263. * @aka L.Polygon
  7264. * @inherits Polyline
  7265. *
  7266. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  7267. *
  7268. * Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points.
  7269. *
  7270. *
  7271. * @example
  7272. *
  7273. * ```js
  7274. * // create a red polygon from an array of LatLng points
  7275. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  7276. *
  7277. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  7278. *
  7279. * // zoom the map to the polygon
  7280. * map.fitBounds(polygon.getBounds());
  7281. * ```
  7282. *
  7283. * You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape:
  7284. *
  7285. * ```js
  7286. * var latlngs = [
  7287. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7288. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7289. * ];
  7290. * ```
  7291. *
  7292. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  7293. *
  7294. * ```js
  7295. * var latlngs = [
  7296. * [ // first polygon
  7297. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7298. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7299. * ],
  7300. * [ // second polygon
  7301. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  7302. * ]
  7303. * ];
  7304. * ```
  7305. */
  7306. L.Polygon = L.Polyline.extend({
  7307. options: {
  7308. fill: true
  7309. },
  7310. isEmpty: function () {
  7311. return !this._latlngs.length || !this._latlngs[0].length;
  7312. },
  7313. getCenter: function () {
  7314. // throws error when not yet added to map as this center calculation requires projected coordinates
  7315. if (!this._map) {
  7316. throw new Error('Must add layer to map before using getCenter()');
  7317. }
  7318. var i, j, p1, p2, f, area, x, y, center,
  7319. points = this._rings[0],
  7320. len = points.length;
  7321. if (!len) { return null; }
  7322. // polygon centroid algorithm; only uses the first ring if there are multiple
  7323. area = x = y = 0;
  7324. for (i = 0, j = len - 1; i < len; j = i++) {
  7325. p1 = points[i];
  7326. p2 = points[j];
  7327. f = p1.y * p2.x - p2.y * p1.x;
  7328. x += (p1.x + p2.x) * f;
  7329. y += (p1.y + p2.y) * f;
  7330. area += f * 3;
  7331. }
  7332. if (area === 0) {
  7333. // Polygon is so small that all points are on same pixel.
  7334. center = points[0];
  7335. } else {
  7336. center = [x / area, y / area];
  7337. }
  7338. return this._map.layerPointToLatLng(center);
  7339. },
  7340. _convertLatLngs: function (latlngs) {
  7341. var result = L.Polyline.prototype._convertLatLngs.call(this, latlngs),
  7342. len = result.length;
  7343. // remove last point if it equals first one
  7344. if (len >= 2 && result[0] instanceof L.LatLng && result[0].equals(result[len - 1])) {
  7345. result.pop();
  7346. }
  7347. return result;
  7348. },
  7349. _setLatLngs: function (latlngs) {
  7350. L.Polyline.prototype._setLatLngs.call(this, latlngs);
  7351. if (L.Polyline._flat(this._latlngs)) {
  7352. this._latlngs = [this._latlngs];
  7353. }
  7354. },
  7355. _defaultShape: function () {
  7356. return L.Polyline._flat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  7357. },
  7358. _clipPoints: function () {
  7359. // polygons need a different clipping algorithm so we redefine that
  7360. var bounds = this._renderer._bounds,
  7361. w = this.options.weight,
  7362. p = new L.Point(w, w);
  7363. // increase clip padding by stroke width to avoid stroke on clip edges
  7364. bounds = new L.Bounds(bounds.min.subtract(p), bounds.max.add(p));
  7365. this._parts = [];
  7366. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7367. return;
  7368. }
  7369. if (this.options.noClip) {
  7370. this._parts = this._rings;
  7371. return;
  7372. }
  7373. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  7374. clipped = L.PolyUtil.clipPolygon(this._rings[i], bounds, true);
  7375. if (clipped.length) {
  7376. this._parts.push(clipped);
  7377. }
  7378. }
  7379. },
  7380. _updatePath: function () {
  7381. this._renderer._updatePoly(this, true);
  7382. }
  7383. });
  7384. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  7385. L.polygon = function (latlngs, options) {
  7386. return new L.Polygon(latlngs, options);
  7387. };
  7388. /*
  7389. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  7390. */
  7391. /*
  7392. * @class Rectangle
  7393. * @aka L.Retangle
  7394. * @inherits Polygon
  7395. *
  7396. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  7397. *
  7398. * @example
  7399. *
  7400. * ```js
  7401. * // define rectangle geographical bounds
  7402. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  7403. *
  7404. * // create an orange rectangle
  7405. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  7406. *
  7407. * // zoom the map to the rectangle bounds
  7408. * map.fitBounds(bounds);
  7409. * ```
  7410. *
  7411. */
  7412. L.Rectangle = L.Polygon.extend({
  7413. initialize: function (latLngBounds, options) {
  7414. L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  7415. },
  7416. // @method setBounds(latLngBounds: LatLngBounds): this
  7417. // Redraws the rectangle with the passed bounds.
  7418. setBounds: function (latLngBounds) {
  7419. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  7420. },
  7421. _boundsToLatLngs: function (latLngBounds) {
  7422. latLngBounds = L.latLngBounds(latLngBounds);
  7423. return [
  7424. latLngBounds.getSouthWest(),
  7425. latLngBounds.getNorthWest(),
  7426. latLngBounds.getNorthEast(),
  7427. latLngBounds.getSouthEast()
  7428. ];
  7429. }
  7430. });
  7431. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  7432. L.rectangle = function (latLngBounds, options) {
  7433. return new L.Rectangle(latLngBounds, options);
  7434. };
  7435. /*
  7436. * @class CircleMarker
  7437. * @aka L.CircleMarker
  7438. * @inherits Path
  7439. *
  7440. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  7441. */
  7442. L.CircleMarker = L.Path.extend({
  7443. // @section
  7444. // @aka CircleMarker options
  7445. options: {
  7446. fill: true,
  7447. // @option radius: Number = 10
  7448. // Radius of the circle marker, in pixels
  7449. radius: 10
  7450. },
  7451. initialize: function (latlng, options) {
  7452. L.setOptions(this, options);
  7453. this._latlng = L.latLng(latlng);
  7454. this._radius = this.options.radius;
  7455. },
  7456. // @method setLatLng(latLng: LatLng): this
  7457. // Sets the position of a circle marker to a new location.
  7458. setLatLng: function (latlng) {
  7459. this._latlng = L.latLng(latlng);
  7460. this.redraw();
  7461. return this.fire('move', {latlng: this._latlng});
  7462. },
  7463. // @method getLatLng(): LatLng
  7464. // Returns the current geographical position of the circle marker
  7465. getLatLng: function () {
  7466. return this._latlng;
  7467. },
  7468. // @method setRadius(radius: Number): this
  7469. // Sets the radius of a circle marker. Units are in pixels.
  7470. setRadius: function (radius) {
  7471. this.options.radius = this._radius = radius;
  7472. return this.redraw();
  7473. },
  7474. // @method getRadius(): Number
  7475. // Returns the current radius of the circle
  7476. getRadius: function () {
  7477. return this._radius;
  7478. },
  7479. setStyle : function (options) {
  7480. var radius = options && options.radius || this._radius;
  7481. L.Path.prototype.setStyle.call(this, options);
  7482. this.setRadius(radius);
  7483. return this;
  7484. },
  7485. _project: function () {
  7486. this._point = this._map.latLngToLayerPoint(this._latlng);
  7487. this._updateBounds();
  7488. },
  7489. _updateBounds: function () {
  7490. var r = this._radius,
  7491. r2 = this._radiusY || r,
  7492. w = this._clickTolerance(),
  7493. p = [r + w, r2 + w];
  7494. this._pxBounds = new L.Bounds(this._point.subtract(p), this._point.add(p));
  7495. },
  7496. _update: function () {
  7497. if (this._map) {
  7498. this._updatePath();
  7499. }
  7500. },
  7501. _updatePath: function () {
  7502. this._renderer._updateCircle(this);
  7503. },
  7504. _empty: function () {
  7505. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  7506. }
  7507. });
  7508. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  7509. // Instantiates a circle marker object given a geographical point, and an optional options object.
  7510. L.circleMarker = function (latlng, options) {
  7511. return new L.CircleMarker(latlng, options);
  7512. };
  7513. /*
  7514. * @class Circle
  7515. * @aka L.Circle
  7516. * @inherits CircleMarker
  7517. *
  7518. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  7519. *
  7520. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  7521. *
  7522. * @example
  7523. *
  7524. * ```js
  7525. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  7526. * ```
  7527. */
  7528. L.Circle = L.CircleMarker.extend({
  7529. initialize: function (latlng, options, legacyOptions) {
  7530. if (typeof options === 'number') {
  7531. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  7532. options = L.extend({}, legacyOptions, {radius: options});
  7533. }
  7534. L.setOptions(this, options);
  7535. this._latlng = L.latLng(latlng);
  7536. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  7537. // @section
  7538. // @aka Circle options
  7539. // @option radius: Number; Radius of the circle, in meters.
  7540. this._mRadius = this.options.radius;
  7541. },
  7542. // @method setRadius(radius: Number): this
  7543. // Sets the radius of a circle. Units are in meters.
  7544. setRadius: function (radius) {
  7545. this._mRadius = radius;
  7546. return this.redraw();
  7547. },
  7548. // @method getRadius(): Number
  7549. // Returns the current radius of a circle. Units are in meters.
  7550. getRadius: function () {
  7551. return this._mRadius;
  7552. },
  7553. // @method getBounds(): LatLngBounds
  7554. // Returns the `LatLngBounds` of the path.
  7555. getBounds: function () {
  7556. var half = [this._radius, this._radiusY || this._radius];
  7557. return new L.LatLngBounds(
  7558. this._map.layerPointToLatLng(this._point.subtract(half)),
  7559. this._map.layerPointToLatLng(this._point.add(half)));
  7560. },
  7561. setStyle: L.Path.prototype.setStyle,
  7562. _project: function () {
  7563. var lng = this._latlng.lng,
  7564. lat = this._latlng.lat,
  7565. map = this._map,
  7566. crs = map.options.crs;
  7567. if (crs.distance === L.CRS.Earth.distance) {
  7568. var d = Math.PI / 180,
  7569. latR = (this._mRadius / L.CRS.Earth.R) / d,
  7570. top = map.project([lat + latR, lng]),
  7571. bottom = map.project([lat - latR, lng]),
  7572. p = top.add(bottom).divideBy(2),
  7573. lat2 = map.unproject(p).lat,
  7574. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  7575. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  7576. if (isNaN(lngR) || lngR === 0) {
  7577. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  7578. }
  7579. this._point = p.subtract(map.getPixelOrigin());
  7580. this._radius = isNaN(lngR) ? 0 : Math.max(Math.round(p.x - map.project([lat2, lng - lngR]).x), 1);
  7581. this._radiusY = Math.max(Math.round(p.y - top.y), 1);
  7582. } else {
  7583. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  7584. this._point = map.latLngToLayerPoint(this._latlng);
  7585. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  7586. }
  7587. this._updateBounds();
  7588. }
  7589. });
  7590. // @factory L.circle(latlng: LatLng, options?: Circle options)
  7591. // Instantiates a circle object given a geographical point, and an options object
  7592. // which contains the circle radius.
  7593. // @alternative
  7594. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  7595. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  7596. // Do not use in new applications or plugins.
  7597. L.circle = function (latlng, options, legacyOptions) {
  7598. return new L.Circle(latlng, options, legacyOptions);
  7599. };
  7600. /*
  7601. * @class SVG
  7602. * @inherits Renderer
  7603. * @aka L.SVG
  7604. *
  7605. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  7606. * Inherits `Renderer`.
  7607. *
  7608. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  7609. * available in all web browsers, notably Android 2.x and 3.x.
  7610. *
  7611. * Although SVG is not available on IE7 and IE8, these browsers support
  7612. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  7613. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  7614. * this case.
  7615. *
  7616. * @example
  7617. *
  7618. * Use SVG by default for all paths in the map:
  7619. *
  7620. * ```js
  7621. * var map = L.map('map', {
  7622. * renderer: L.svg()
  7623. * });
  7624. * ```
  7625. *
  7626. * Use a SVG renderer with extra padding for specific vector geometries:
  7627. *
  7628. * ```js
  7629. * var map = L.map('map');
  7630. * var myRenderer = L.svg({ padding: 0.5 });
  7631. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  7632. * var circle = L.circle( center, { renderer: myRenderer } );
  7633. * ```
  7634. */
  7635. L.SVG = L.Renderer.extend({
  7636. getEvents: function () {
  7637. var events = L.Renderer.prototype.getEvents.call(this);
  7638. events.zoomstart = this._onZoomStart;
  7639. return events;
  7640. },
  7641. _initContainer: function () {
  7642. this._container = L.SVG.create('svg');
  7643. // makes it possible to click through svg root; we'll reset it back in individual paths
  7644. this._container.setAttribute('pointer-events', 'none');
  7645. this._rootGroup = L.SVG.create('g');
  7646. this._container.appendChild(this._rootGroup);
  7647. },
  7648. _onZoomStart: function () {
  7649. // Drag-then-pinch interactions might mess up the center and zoom.
  7650. // In this case, the easiest way to prevent this is re-do the renderer
  7651. // bounds and padding when the zooming starts.
  7652. this._update();
  7653. },
  7654. _update: function () {
  7655. if (this._map._animatingZoom && this._bounds) { return; }
  7656. L.Renderer.prototype._update.call(this);
  7657. var b = this._bounds,
  7658. size = b.getSize(),
  7659. container = this._container;
  7660. // set size of svg-container if changed
  7661. if (!this._svgSize || !this._svgSize.equals(size)) {
  7662. this._svgSize = size;
  7663. container.setAttribute('width', size.x);
  7664. container.setAttribute('height', size.y);
  7665. }
  7666. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  7667. L.DomUtil.setPosition(container, b.min);
  7668. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  7669. this.fire('update');
  7670. },
  7671. // methods below are called by vector layers implementations
  7672. _initPath: function (layer) {
  7673. var path = layer._path = L.SVG.create('path');
  7674. // @namespace Path
  7675. // @option className: String = null
  7676. // Custom class name set on an element. Only for SVG renderer.
  7677. if (layer.options.className) {
  7678. L.DomUtil.addClass(path, layer.options.className);
  7679. }
  7680. if (layer.options.interactive) {
  7681. L.DomUtil.addClass(path, 'leaflet-interactive');
  7682. }
  7683. this._updateStyle(layer);
  7684. this._layers[L.stamp(layer)] = layer;
  7685. },
  7686. _addPath: function (layer) {
  7687. this._rootGroup.appendChild(layer._path);
  7688. layer.addInteractiveTarget(layer._path);
  7689. },
  7690. _removePath: function (layer) {
  7691. L.DomUtil.remove(layer._path);
  7692. layer.removeInteractiveTarget(layer._path);
  7693. delete this._layers[L.stamp(layer)];
  7694. },
  7695. _updatePath: function (layer) {
  7696. layer._project();
  7697. layer._update();
  7698. },
  7699. _updateStyle: function (layer) {
  7700. var path = layer._path,
  7701. options = layer.options;
  7702. if (!path) { return; }
  7703. if (options.stroke) {
  7704. path.setAttribute('stroke', options.color);
  7705. path.setAttribute('stroke-opacity', options.opacity);
  7706. path.setAttribute('stroke-width', options.weight);
  7707. path.setAttribute('stroke-linecap', options.lineCap);
  7708. path.setAttribute('stroke-linejoin', options.lineJoin);
  7709. if (options.dashArray) {
  7710. path.setAttribute('stroke-dasharray', options.dashArray);
  7711. } else {
  7712. path.removeAttribute('stroke-dasharray');
  7713. }
  7714. if (options.dashOffset) {
  7715. path.setAttribute('stroke-dashoffset', options.dashOffset);
  7716. } else {
  7717. path.removeAttribute('stroke-dashoffset');
  7718. }
  7719. } else {
  7720. path.setAttribute('stroke', 'none');
  7721. }
  7722. if (options.fill) {
  7723. path.setAttribute('fill', options.fillColor || options.color);
  7724. path.setAttribute('fill-opacity', options.fillOpacity);
  7725. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  7726. } else {
  7727. path.setAttribute('fill', 'none');
  7728. }
  7729. },
  7730. _updatePoly: function (layer, closed) {
  7731. this._setPath(layer, L.SVG.pointsToPath(layer._parts, closed));
  7732. },
  7733. _updateCircle: function (layer) {
  7734. var p = layer._point,
  7735. r = layer._radius,
  7736. r2 = layer._radiusY || r,
  7737. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  7738. // drawing a circle with two half-arcs
  7739. var d = layer._empty() ? 'M0 0' :
  7740. 'M' + (p.x - r) + ',' + p.y +
  7741. arc + (r * 2) + ',0 ' +
  7742. arc + (-r * 2) + ',0 ';
  7743. this._setPath(layer, d);
  7744. },
  7745. _setPath: function (layer, path) {
  7746. layer._path.setAttribute('d', path);
  7747. },
  7748. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  7749. _bringToFront: function (layer) {
  7750. L.DomUtil.toFront(layer._path);
  7751. },
  7752. _bringToBack: function (layer) {
  7753. L.DomUtil.toBack(layer._path);
  7754. }
  7755. });
  7756. // @namespace SVG; @section
  7757. // There are several static functions which can be called without instantiating L.SVG:
  7758. L.extend(L.SVG, {
  7759. // @function create(name: String): SVGElement
  7760. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  7761. // corresponding to the class name passed. For example, using 'line' will return
  7762. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  7763. create: function (name) {
  7764. return document.createElementNS('http://www.w3.org/2000/svg', name);
  7765. },
  7766. // @function pointsToPath(rings: Point[], closed: Boolean): String
  7767. // Generates a SVG path string for multiple rings, with each ring turning
  7768. // into "M..L..L.." instructions
  7769. pointsToPath: function (rings, closed) {
  7770. var str = '',
  7771. i, j, len, len2, points, p;
  7772. for (i = 0, len = rings.length; i < len; i++) {
  7773. points = rings[i];
  7774. for (j = 0, len2 = points.length; j < len2; j++) {
  7775. p = points[j];
  7776. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  7777. }
  7778. // closes the ring for polygons; "x" is VML syntax
  7779. str += closed ? (L.Browser.svg ? 'z' : 'x') : '';
  7780. }
  7781. // SVG complains about empty path strings
  7782. return str || 'M0 0';
  7783. }
  7784. });
  7785. // @namespace Browser; @property svg: Boolean
  7786. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  7787. L.Browser.svg = !!(document.createElementNS && L.SVG.create('svg').createSVGRect);
  7788. // @namespace SVG
  7789. // @factory L.svg(options?: Renderer options)
  7790. // Creates a SVG renderer with the given options.
  7791. L.svg = function (options) {
  7792. return L.Browser.svg || L.Browser.vml ? new L.SVG(options) : null;
  7793. };
  7794. /*
  7795. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  7796. */
  7797. /*
  7798. * @class SVG
  7799. *
  7800. * Although SVG is not available on IE7 and IE8, these browsers support [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language), and the SVG renderer will fall back to VML in this case.
  7801. *
  7802. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  7803. * with old versions of Internet Explorer.
  7804. */
  7805. // @namespace Browser; @property vml: Boolean
  7806. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  7807. L.Browser.vml = !L.Browser.svg && (function () {
  7808. try {
  7809. var div = document.createElement('div');
  7810. div.innerHTML = '<v:shape adj="1"/>';
  7811. var shape = div.firstChild;
  7812. shape.style.behavior = 'url(#default#VML)';
  7813. return shape && (typeof shape.adj === 'object');
  7814. } catch (e) {
  7815. return false;
  7816. }
  7817. }());
  7818. // redefine some SVG methods to handle VML syntax which is similar but with some differences
  7819. L.SVG.include(!L.Browser.vml ? {} : {
  7820. _initContainer: function () {
  7821. this._container = L.DomUtil.create('div', 'leaflet-vml-container');
  7822. },
  7823. _update: function () {
  7824. if (this._map._animatingZoom) { return; }
  7825. L.Renderer.prototype._update.call(this);
  7826. this.fire('update');
  7827. },
  7828. _initPath: function (layer) {
  7829. var container = layer._container = L.SVG.create('shape');
  7830. L.DomUtil.addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  7831. container.coordsize = '1 1';
  7832. layer._path = L.SVG.create('path');
  7833. container.appendChild(layer._path);
  7834. this._updateStyle(layer);
  7835. this._layers[L.stamp(layer)] = layer;
  7836. },
  7837. _addPath: function (layer) {
  7838. var container = layer._container;
  7839. this._container.appendChild(container);
  7840. if (layer.options.interactive) {
  7841. layer.addInteractiveTarget(container);
  7842. }
  7843. },
  7844. _removePath: function (layer) {
  7845. var container = layer._container;
  7846. L.DomUtil.remove(container);
  7847. layer.removeInteractiveTarget(container);
  7848. delete this._layers[L.stamp(layer)];
  7849. },
  7850. _updateStyle: function (layer) {
  7851. var stroke = layer._stroke,
  7852. fill = layer._fill,
  7853. options = layer.options,
  7854. container = layer._container;
  7855. container.stroked = !!options.stroke;
  7856. container.filled = !!options.fill;
  7857. if (options.stroke) {
  7858. if (!stroke) {
  7859. stroke = layer._stroke = L.SVG.create('stroke');
  7860. }
  7861. container.appendChild(stroke);
  7862. stroke.weight = options.weight + 'px';
  7863. stroke.color = options.color;
  7864. stroke.opacity = options.opacity;
  7865. if (options.dashArray) {
  7866. stroke.dashStyle = L.Util.isArray(options.dashArray) ?
  7867. options.dashArray.join(' ') :
  7868. options.dashArray.replace(/( *, *)/g, ' ');
  7869. } else {
  7870. stroke.dashStyle = '';
  7871. }
  7872. stroke.endcap = options.lineCap.replace('butt', 'flat');
  7873. stroke.joinstyle = options.lineJoin;
  7874. } else if (stroke) {
  7875. container.removeChild(stroke);
  7876. layer._stroke = null;
  7877. }
  7878. if (options.fill) {
  7879. if (!fill) {
  7880. fill = layer._fill = L.SVG.create('fill');
  7881. }
  7882. container.appendChild(fill);
  7883. fill.color = options.fillColor || options.color;
  7884. fill.opacity = options.fillOpacity;
  7885. } else if (fill) {
  7886. container.removeChild(fill);
  7887. layer._fill = null;
  7888. }
  7889. },
  7890. _updateCircle: function (layer) {
  7891. var p = layer._point.round(),
  7892. r = Math.round(layer._radius),
  7893. r2 = Math.round(layer._radiusY || r);
  7894. this._setPath(layer, layer._empty() ? 'M0 0' :
  7895. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  7896. },
  7897. _setPath: function (layer, path) {
  7898. layer._path.v = path;
  7899. },
  7900. _bringToFront: function (layer) {
  7901. L.DomUtil.toFront(layer._container);
  7902. },
  7903. _bringToBack: function (layer) {
  7904. L.DomUtil.toBack(layer._container);
  7905. }
  7906. });
  7907. if (L.Browser.vml) {
  7908. L.SVG.create = (function () {
  7909. try {
  7910. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  7911. return function (name) {
  7912. return document.createElement('<lvml:' + name + ' class="lvml">');
  7913. };
  7914. } catch (e) {
  7915. return function (name) {
  7916. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  7917. };
  7918. }
  7919. })();
  7920. }
  7921. /*
  7922. * @class Canvas
  7923. * @inherits Renderer
  7924. * @aka L.Canvas
  7925. *
  7926. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  7927. * Inherits `Renderer`.
  7928. *
  7929. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  7930. * available in all web browsers, notably IE8, and overlapping geometries might
  7931. * not display properly in some edge cases.
  7932. *
  7933. * @example
  7934. *
  7935. * Use Canvas by default for all paths in the map:
  7936. *
  7937. * ```js
  7938. * var map = L.map('map', {
  7939. * renderer: L.canvas()
  7940. * });
  7941. * ```
  7942. *
  7943. * Use a Canvas renderer with extra padding for specific vector geometries:
  7944. *
  7945. * ```js
  7946. * var map = L.map('map');
  7947. * var myRenderer = L.canvas({ padding: 0.5 });
  7948. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  7949. * var circle = L.circle( center, { renderer: myRenderer } );
  7950. * ```
  7951. */
  7952. L.Canvas = L.Renderer.extend({
  7953. getEvents: function () {
  7954. var events = L.Renderer.prototype.getEvents.call(this);
  7955. events.viewprereset = this._onViewPreReset;
  7956. return events;
  7957. },
  7958. _onViewPreReset: function () {
  7959. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  7960. this._postponeUpdatePaths = true;
  7961. },
  7962. onAdd: function () {
  7963. L.Renderer.prototype.onAdd.call(this);
  7964. // Redraw vectors since canvas is cleared upon removal,
  7965. // in case of removing the renderer itself from the map.
  7966. this._draw();
  7967. },
  7968. _initContainer: function () {
  7969. var container = this._container = document.createElement('canvas');
  7970. L.DomEvent
  7971. .on(container, 'mousemove', L.Util.throttle(this._onMouseMove, 32, this), this)
  7972. .on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this)
  7973. .on(container, 'mouseout', this._handleMouseOut, this);
  7974. this._ctx = container.getContext('2d');
  7975. },
  7976. _updatePaths: function () {
  7977. if (this._postponeUpdatePaths) { return; }
  7978. var layer;
  7979. this._redrawBounds = null;
  7980. for (var id in this._layers) {
  7981. layer = this._layers[id];
  7982. layer._update();
  7983. }
  7984. this._redraw();
  7985. },
  7986. _update: function () {
  7987. if (this._map._animatingZoom && this._bounds) { return; }
  7988. this._drawnLayers = {};
  7989. L.Renderer.prototype._update.call(this);
  7990. var b = this._bounds,
  7991. container = this._container,
  7992. size = b.getSize(),
  7993. m = L.Browser.retina ? 2 : 1;
  7994. L.DomUtil.setPosition(container, b.min);
  7995. // set canvas size (also clearing it); use double size on retina
  7996. container.width = m * size.x;
  7997. container.height = m * size.y;
  7998. container.style.width = size.x + 'px';
  7999. container.style.height = size.y + 'px';
  8000. if (L.Browser.retina) {
  8001. this._ctx.scale(2, 2);
  8002. }
  8003. // translate so we use the same path coordinates after canvas element moves
  8004. this._ctx.translate(-b.min.x, -b.min.y);
  8005. // Tell paths to redraw themselves
  8006. this.fire('update');
  8007. },
  8008. _reset: function () {
  8009. L.Renderer.prototype._reset.call(this);
  8010. if (this._postponeUpdatePaths) {
  8011. this._postponeUpdatePaths = false;
  8012. this._updatePaths();
  8013. }
  8014. },
  8015. _initPath: function (layer) {
  8016. this._updateDashArray(layer);
  8017. this._layers[L.stamp(layer)] = layer;
  8018. var order = layer._order = {
  8019. layer: layer,
  8020. prev: this._drawLast,
  8021. next: null
  8022. };
  8023. if (this._drawLast) { this._drawLast.next = order; }
  8024. this._drawLast = order;
  8025. this._drawFirst = this._drawFirst || this._drawLast;
  8026. },
  8027. _addPath: function (layer) {
  8028. this._requestRedraw(layer);
  8029. },
  8030. _removePath: function (layer) {
  8031. var order = layer._order;
  8032. var next = order.next;
  8033. var prev = order.prev;
  8034. if (next) {
  8035. next.prev = prev;
  8036. } else {
  8037. this._drawLast = prev;
  8038. }
  8039. if (prev) {
  8040. prev.next = next;
  8041. } else {
  8042. this._drawFirst = next;
  8043. }
  8044. delete layer._order;
  8045. delete this._layers[L.stamp(layer)];
  8046. this._requestRedraw(layer);
  8047. },
  8048. _updatePath: function (layer) {
  8049. // Redraw the union of the layer's old pixel
  8050. // bounds and the new pixel bounds.
  8051. this._extendRedrawBounds(layer);
  8052. layer._project();
  8053. layer._update();
  8054. // The redraw will extend the redraw bounds
  8055. // with the new pixel bounds.
  8056. this._requestRedraw(layer);
  8057. },
  8058. _updateStyle: function (layer) {
  8059. this._updateDashArray(layer);
  8060. this._requestRedraw(layer);
  8061. },
  8062. _updateDashArray: function (layer) {
  8063. if (layer.options.dashArray) {
  8064. var parts = layer.options.dashArray.split(','),
  8065. dashArray = [],
  8066. i;
  8067. for (i = 0; i < parts.length; i++) {
  8068. dashArray.push(Number(parts[i]));
  8069. }
  8070. layer.options._dashArray = dashArray;
  8071. }
  8072. },
  8073. _requestRedraw: function (layer) {
  8074. if (!this._map) { return; }
  8075. this._extendRedrawBounds(layer);
  8076. this._redrawRequest = this._redrawRequest || L.Util.requestAnimFrame(this._redraw, this);
  8077. },
  8078. _extendRedrawBounds: function (layer) {
  8079. var padding = (layer.options.weight || 0) + 1;
  8080. this._redrawBounds = this._redrawBounds || new L.Bounds();
  8081. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  8082. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  8083. },
  8084. _redraw: function () {
  8085. this._redrawRequest = null;
  8086. if (this._redrawBounds) {
  8087. this._redrawBounds.min._floor();
  8088. this._redrawBounds.max._ceil();
  8089. }
  8090. this._clear(); // clear layers in redraw bounds
  8091. this._draw(); // draw layers
  8092. this._redrawBounds = null;
  8093. },
  8094. _clear: function () {
  8095. var bounds = this._redrawBounds;
  8096. if (bounds) {
  8097. var size = bounds.getSize();
  8098. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  8099. } else {
  8100. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  8101. }
  8102. },
  8103. _draw: function () {
  8104. var layer, bounds = this._redrawBounds;
  8105. this._ctx.save();
  8106. if (bounds) {
  8107. var size = bounds.getSize();
  8108. this._ctx.beginPath();
  8109. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  8110. this._ctx.clip();
  8111. }
  8112. this._drawing = true;
  8113. for (var order = this._drawFirst; order; order = order.next) {
  8114. layer = order.layer;
  8115. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  8116. layer._updatePath();
  8117. }
  8118. }
  8119. this._drawing = false;
  8120. this._ctx.restore(); // Restore state before clipping.
  8121. },
  8122. _updatePoly: function (layer, closed) {
  8123. if (!this._drawing) { return; }
  8124. var i, j, len2, p,
  8125. parts = layer._parts,
  8126. len = parts.length,
  8127. ctx = this._ctx;
  8128. if (!len) { return; }
  8129. this._drawnLayers[layer._leaflet_id] = layer;
  8130. ctx.beginPath();
  8131. if (ctx.setLineDash) {
  8132. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  8133. }
  8134. for (i = 0; i < len; i++) {
  8135. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  8136. p = parts[i][j];
  8137. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  8138. }
  8139. if (closed) {
  8140. ctx.closePath();
  8141. }
  8142. }
  8143. this._fillStroke(ctx, layer);
  8144. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  8145. },
  8146. _updateCircle: function (layer) {
  8147. if (!this._drawing || layer._empty()) { return; }
  8148. var p = layer._point,
  8149. ctx = this._ctx,
  8150. r = layer._radius,
  8151. s = (layer._radiusY || r) / r;
  8152. this._drawnLayers[layer._leaflet_id] = layer;
  8153. if (s !== 1) {
  8154. ctx.save();
  8155. ctx.scale(1, s);
  8156. }
  8157. ctx.beginPath();
  8158. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  8159. if (s !== 1) {
  8160. ctx.restore();
  8161. }
  8162. this._fillStroke(ctx, layer);
  8163. },
  8164. _fillStroke: function (ctx, layer) {
  8165. var options = layer.options;
  8166. if (options.fill) {
  8167. ctx.globalAlpha = options.fillOpacity;
  8168. ctx.fillStyle = options.fillColor || options.color;
  8169. ctx.fill(options.fillRule || 'evenodd');
  8170. }
  8171. if (options.stroke && options.weight !== 0) {
  8172. ctx.globalAlpha = options.opacity;
  8173. ctx.lineWidth = options.weight;
  8174. ctx.strokeStyle = options.color;
  8175. ctx.lineCap = options.lineCap;
  8176. ctx.lineJoin = options.lineJoin;
  8177. ctx.stroke();
  8178. }
  8179. },
  8180. // Canvas obviously doesn't have mouse events for individual drawn objects,
  8181. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  8182. _onClick: function (e) {
  8183. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  8184. for (var order = this._drawFirst; order; order = order.next) {
  8185. layer = order.layer;
  8186. if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
  8187. clickedLayer = layer;
  8188. }
  8189. }
  8190. if (clickedLayer) {
  8191. L.DomEvent._fakeStop(e);
  8192. this._fireEvent([clickedLayer], e);
  8193. }
  8194. },
  8195. _onMouseMove: function (e) {
  8196. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  8197. var point = this._map.mouseEventToLayerPoint(e);
  8198. this._handleMouseHover(e, point);
  8199. },
  8200. _handleMouseOut: function (e) {
  8201. var layer = this._hoveredLayer;
  8202. if (layer) {
  8203. // if we're leaving the layer, fire mouseout
  8204. L.DomUtil.removeClass(this._container, 'leaflet-interactive');
  8205. this._fireEvent([layer], e, 'mouseout');
  8206. this._hoveredLayer = null;
  8207. }
  8208. },
  8209. _handleMouseHover: function (e, point) {
  8210. var layer, candidateHoveredLayer;
  8211. for (var order = this._drawFirst; order; order = order.next) {
  8212. layer = order.layer;
  8213. if (layer.options.interactive && layer._containsPoint(point)) {
  8214. candidateHoveredLayer = layer;
  8215. }
  8216. }
  8217. if (candidateHoveredLayer !== this._hoveredLayer) {
  8218. this._handleMouseOut(e);
  8219. if (candidateHoveredLayer) {
  8220. L.DomUtil.addClass(this._container, 'leaflet-interactive'); // change cursor
  8221. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  8222. this._hoveredLayer = candidateHoveredLayer;
  8223. }
  8224. }
  8225. if (this._hoveredLayer) {
  8226. this._fireEvent([this._hoveredLayer], e);
  8227. }
  8228. },
  8229. _fireEvent: function (layers, e, type) {
  8230. this._map._fireDOMEvent(e, type || e.type, layers);
  8231. },
  8232. _bringToFront: function (layer) {
  8233. var order = layer._order;
  8234. var next = order.next;
  8235. var prev = order.prev;
  8236. if (next) {
  8237. next.prev = prev;
  8238. } else {
  8239. // Already last
  8240. return;
  8241. }
  8242. if (prev) {
  8243. prev.next = next;
  8244. } else if (next) {
  8245. // Update first entry unless this is the
  8246. // signle entry
  8247. this._drawFirst = next;
  8248. }
  8249. order.prev = this._drawLast;
  8250. this._drawLast.next = order;
  8251. order.next = null;
  8252. this._drawLast = order;
  8253. this._requestRedraw(layer);
  8254. },
  8255. _bringToBack: function (layer) {
  8256. var order = layer._order;
  8257. var next = order.next;
  8258. var prev = order.prev;
  8259. if (prev) {
  8260. prev.next = next;
  8261. } else {
  8262. // Already first
  8263. return;
  8264. }
  8265. if (next) {
  8266. next.prev = prev;
  8267. } else if (prev) {
  8268. // Update last entry unless this is the
  8269. // signle entry
  8270. this._drawLast = prev;
  8271. }
  8272. order.prev = null;
  8273. order.next = this._drawFirst;
  8274. this._drawFirst.prev = order;
  8275. this._drawFirst = order;
  8276. this._requestRedraw(layer);
  8277. }
  8278. });
  8279. // @namespace Browser; @property canvas: Boolean
  8280. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  8281. L.Browser.canvas = (function () {
  8282. return !!document.createElement('canvas').getContext;
  8283. }());
  8284. // @namespace Canvas
  8285. // @factory L.canvas(options?: Renderer options)
  8286. // Creates a Canvas renderer with the given options.
  8287. L.canvas = function (options) {
  8288. return L.Browser.canvas ? new L.Canvas(options) : null;
  8289. };
  8290. L.Polyline.prototype._containsPoint = function (p, closed) {
  8291. var i, j, k, len, len2, part,
  8292. w = this._clickTolerance();
  8293. if (!this._pxBounds.contains(p)) { return false; }
  8294. // hit detection for polylines
  8295. for (i = 0, len = this._parts.length; i < len; i++) {
  8296. part = this._parts[i];
  8297. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  8298. if (!closed && (j === 0)) { continue; }
  8299. if (L.LineUtil.pointToSegmentDistance(p, part[k], part[j]) <= w) {
  8300. return true;
  8301. }
  8302. }
  8303. }
  8304. return false;
  8305. };
  8306. L.Polygon.prototype._containsPoint = function (p) {
  8307. var inside = false,
  8308. part, p1, p2, i, j, k, len, len2;
  8309. if (!this._pxBounds.contains(p)) { return false; }
  8310. // ray casting algorithm for detecting if point is in polygon
  8311. for (i = 0, len = this._parts.length; i < len; i++) {
  8312. part = this._parts[i];
  8313. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  8314. p1 = part[j];
  8315. p2 = part[k];
  8316. if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
  8317. inside = !inside;
  8318. }
  8319. }
  8320. }
  8321. // also check if it's on polygon stroke
  8322. return inside || L.Polyline.prototype._containsPoint.call(this, p, true);
  8323. };
  8324. L.CircleMarker.prototype._containsPoint = function (p) {
  8325. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  8326. };
  8327. /*
  8328. * @class GeoJSON
  8329. * @aka L.GeoJSON
  8330. * @inherits FeatureGroup
  8331. *
  8332. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  8333. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  8334. *
  8335. * @example
  8336. *
  8337. * ```js
  8338. * L.geoJSON(data, {
  8339. * style: function (feature) {
  8340. * return {color: feature.properties.color};
  8341. * }
  8342. * }).bindPopup(function (layer) {
  8343. * return layer.feature.properties.description;
  8344. * }).addTo(map);
  8345. * ```
  8346. */
  8347. L.GeoJSON = L.FeatureGroup.extend({
  8348. /* @section
  8349. * @aka GeoJSON options
  8350. *
  8351. * @option pointToLayer: Function = *
  8352. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  8353. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  8354. * The default is to spawn a default `Marker`:
  8355. * ```js
  8356. * function(geoJsonPoint, latlng) {
  8357. * return L.marker(latlng);
  8358. * }
  8359. * ```
  8360. *
  8361. * @option style: Function = *
  8362. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  8363. * called internally when data is added.
  8364. * The default value is to not override any defaults:
  8365. * ```js
  8366. * function (geoJsonFeature) {
  8367. * return {}
  8368. * }
  8369. * ```
  8370. *
  8371. * @option onEachFeature: Function = *
  8372. * A `Function` that will be called once for each created `Feature`, after it has
  8373. * been created and styled. Useful for attaching events and popups to features.
  8374. * The default is to do nothing with the newly created layers:
  8375. * ```js
  8376. * function (feature, layer) {}
  8377. * ```
  8378. *
  8379. * @option filter: Function = *
  8380. * A `Function` that will be used to decide whether to include a feature or not.
  8381. * The default is to include all features:
  8382. * ```js
  8383. * function (geoJsonFeature) {
  8384. * return true;
  8385. * }
  8386. * ```
  8387. * Note: dynamically changing the `filter` option will have effect only on newly
  8388. * added data. It will _not_ re-evaluate already included features.
  8389. *
  8390. * @option coordsToLatLng: Function = *
  8391. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  8392. * The default is the `coordsToLatLng` static method.
  8393. */
  8394. initialize: function (geojson, options) {
  8395. L.setOptions(this, options);
  8396. this._layers = {};
  8397. if (geojson) {
  8398. this.addData(geojson);
  8399. }
  8400. },
  8401. // @method addData( <GeoJSON> data ): this
  8402. // Adds a GeoJSON object to the layer.
  8403. addData: function (geojson) {
  8404. var features = L.Util.isArray(geojson) ? geojson : geojson.features,
  8405. i, len, feature;
  8406. if (features) {
  8407. for (i = 0, len = features.length; i < len; i++) {
  8408. // only add this if geometry or geometries are set and not null
  8409. feature = features[i];
  8410. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  8411. this.addData(feature);
  8412. }
  8413. }
  8414. return this;
  8415. }
  8416. var options = this.options;
  8417. if (options.filter && !options.filter(geojson)) { return this; }
  8418. var layer = L.GeoJSON.geometryToLayer(geojson, options);
  8419. if (!layer) {
  8420. return this;
  8421. }
  8422. layer.feature = L.GeoJSON.asFeature(geojson);
  8423. layer.defaultOptions = layer.options;
  8424. this.resetStyle(layer);
  8425. if (options.onEachFeature) {
  8426. options.onEachFeature(geojson, layer);
  8427. }
  8428. return this.addLayer(layer);
  8429. },
  8430. // @method resetStyle( <Path> layer ): this
  8431. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  8432. resetStyle: function (layer) {
  8433. // reset any custom styles
  8434. layer.options = L.Util.extend({}, layer.defaultOptions);
  8435. this._setLayerStyle(layer, this.options.style);
  8436. return this;
  8437. },
  8438. // @method setStyle( <Function> style ): this
  8439. // Changes styles of GeoJSON vector layers with the given style function.
  8440. setStyle: function (style) {
  8441. return this.eachLayer(function (layer) {
  8442. this._setLayerStyle(layer, style);
  8443. }, this);
  8444. },
  8445. _setLayerStyle: function (layer, style) {
  8446. if (typeof style === 'function') {
  8447. style = style(layer.feature);
  8448. }
  8449. if (layer.setStyle) {
  8450. layer.setStyle(style);
  8451. }
  8452. }
  8453. });
  8454. // @section
  8455. // There are several static functions which can be called without instantiating L.GeoJSON:
  8456. L.extend(L.GeoJSON, {
  8457. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  8458. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  8459. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  8460. // functions if provided as options.
  8461. geometryToLayer: function (geojson, options) {
  8462. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  8463. coords = geometry ? geometry.coordinates : null,
  8464. layers = [],
  8465. pointToLayer = options && options.pointToLayer,
  8466. coordsToLatLng = options && options.coordsToLatLng || this.coordsToLatLng,
  8467. latlng, latlngs, i, len;
  8468. if (!coords && !geometry) {
  8469. return null;
  8470. }
  8471. switch (geometry.type) {
  8472. case 'Point':
  8473. latlng = coordsToLatLng(coords);
  8474. return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
  8475. case 'MultiPoint':
  8476. for (i = 0, len = coords.length; i < len; i++) {
  8477. latlng = coordsToLatLng(coords[i]);
  8478. layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng));
  8479. }
  8480. return new L.FeatureGroup(layers);
  8481. case 'LineString':
  8482. case 'MultiLineString':
  8483. latlngs = this.coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, coordsToLatLng);
  8484. return new L.Polyline(latlngs, options);
  8485. case 'Polygon':
  8486. case 'MultiPolygon':
  8487. latlngs = this.coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, coordsToLatLng);
  8488. return new L.Polygon(latlngs, options);
  8489. case 'GeometryCollection':
  8490. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  8491. var layer = this.geometryToLayer({
  8492. geometry: geometry.geometries[i],
  8493. type: 'Feature',
  8494. properties: geojson.properties
  8495. }, options);
  8496. if (layer) {
  8497. layers.push(layer);
  8498. }
  8499. }
  8500. return new L.FeatureGroup(layers);
  8501. default:
  8502. throw new Error('Invalid GeoJSON object.');
  8503. }
  8504. },
  8505. // @function coordsToLatLng(coords: Array): LatLng
  8506. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  8507. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  8508. coordsToLatLng: function (coords) {
  8509. return new L.LatLng(coords[1], coords[0], coords[2]);
  8510. },
  8511. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  8512. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  8513. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  8514. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  8515. coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) {
  8516. var latlngs = [];
  8517. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  8518. latlng = levelsDeep ?
  8519. this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
  8520. (coordsToLatLng || this.coordsToLatLng)(coords[i]);
  8521. latlngs.push(latlng);
  8522. }
  8523. return latlngs;
  8524. },
  8525. // @function latLngToCoords(latlng: LatLng): Array
  8526. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  8527. latLngToCoords: function (latlng) {
  8528. return latlng.alt !== undefined ?
  8529. [latlng.lng, latlng.lat, latlng.alt] :
  8530. [latlng.lng, latlng.lat];
  8531. },
  8532. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  8533. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  8534. // `closed` determines whether the first point should be appended to the end of the array to close the feature, only used when `levelsDeep` is 0. False by default.
  8535. latLngsToCoords: function (latlngs, levelsDeep, closed) {
  8536. var coords = [];
  8537. for (var i = 0, len = latlngs.length; i < len; i++) {
  8538. coords.push(levelsDeep ?
  8539. L.GeoJSON.latLngsToCoords(latlngs[i], levelsDeep - 1, closed) :
  8540. L.GeoJSON.latLngToCoords(latlngs[i]));
  8541. }
  8542. if (!levelsDeep && closed) {
  8543. coords.push(coords[0]);
  8544. }
  8545. return coords;
  8546. },
  8547. getFeature: function (layer, newGeometry) {
  8548. return layer.feature ?
  8549. L.extend({}, layer.feature, {geometry: newGeometry}) :
  8550. L.GeoJSON.asFeature(newGeometry);
  8551. },
  8552. // @function asFeature(geojson: Object): Object
  8553. // Normalize GeoJSON geometries/features into GeoJSON features.
  8554. asFeature: function (geojson) {
  8555. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  8556. return geojson;
  8557. }
  8558. return {
  8559. type: 'Feature',
  8560. properties: {},
  8561. geometry: geojson
  8562. };
  8563. }
  8564. });
  8565. var PointToGeoJSON = {
  8566. toGeoJSON: function () {
  8567. return L.GeoJSON.getFeature(this, {
  8568. type: 'Point',
  8569. coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
  8570. });
  8571. }
  8572. };
  8573. // @namespace Marker
  8574. // @method toGeoJSON(): Object
  8575. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  8576. L.Marker.include(PointToGeoJSON);
  8577. // @namespace CircleMarker
  8578. // @method toGeoJSON(): Object
  8579. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  8580. L.Circle.include(PointToGeoJSON);
  8581. L.CircleMarker.include(PointToGeoJSON);
  8582. // @namespace Polyline
  8583. // @method toGeoJSON(): Object
  8584. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  8585. L.Polyline.prototype.toGeoJSON = function () {
  8586. var multi = !L.Polyline._flat(this._latlngs);
  8587. var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 1 : 0);
  8588. return L.GeoJSON.getFeature(this, {
  8589. type: (multi ? 'Multi' : '') + 'LineString',
  8590. coordinates: coords
  8591. });
  8592. };
  8593. // @namespace Polygon
  8594. // @method toGeoJSON(): Object
  8595. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  8596. L.Polygon.prototype.toGeoJSON = function () {
  8597. var holes = !L.Polyline._flat(this._latlngs),
  8598. multi = holes && !L.Polyline._flat(this._latlngs[0]);
  8599. var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true);
  8600. if (!holes) {
  8601. coords = [coords];
  8602. }
  8603. return L.GeoJSON.getFeature(this, {
  8604. type: (multi ? 'Multi' : '') + 'Polygon',
  8605. coordinates: coords
  8606. });
  8607. };
  8608. // @namespace LayerGroup
  8609. L.LayerGroup.include({
  8610. toMultiPoint: function () {
  8611. var coords = [];
  8612. this.eachLayer(function (layer) {
  8613. coords.push(layer.toGeoJSON().geometry.coordinates);
  8614. });
  8615. return L.GeoJSON.getFeature(this, {
  8616. type: 'MultiPoint',
  8617. coordinates: coords
  8618. });
  8619. },
  8620. // @method toGeoJSON(): Object
  8621. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `GeometryCollection`).
  8622. toGeoJSON: function () {
  8623. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  8624. if (type === 'MultiPoint') {
  8625. return this.toMultiPoint();
  8626. }
  8627. var isGeometryCollection = type === 'GeometryCollection',
  8628. jsons = [];
  8629. this.eachLayer(function (layer) {
  8630. if (layer.toGeoJSON) {
  8631. var json = layer.toGeoJSON();
  8632. jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json));
  8633. }
  8634. });
  8635. if (isGeometryCollection) {
  8636. return L.GeoJSON.getFeature(this, {
  8637. geometries: jsons,
  8638. type: 'GeometryCollection'
  8639. });
  8640. }
  8641. return {
  8642. type: 'FeatureCollection',
  8643. features: jsons
  8644. };
  8645. }
  8646. });
  8647. // @namespace GeoJSON
  8648. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  8649. // Creates a GeoJSON layer. Optionally accepts an object in
  8650. // [GeoJSON format](http://geojson.org/geojson-spec.html) to display on the map
  8651. // (you can alternatively add it later with `addData` method) and an `options` object.
  8652. L.geoJSON = function (geojson, options) {
  8653. return new L.GeoJSON(geojson, options);
  8654. };
  8655. // Backward compatibility.
  8656. L.geoJson = L.geoJSON;
  8657. /*
  8658. * @class Draggable
  8659. * @aka L.Draggable
  8660. * @inherits Evented
  8661. *
  8662. * A class for making DOM elements draggable (including touch support).
  8663. * Used internally for map and marker dragging. Only works for elements
  8664. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  8665. *
  8666. * @example
  8667. * ```js
  8668. * var draggable = new L.Draggable(elementToDrag);
  8669. * draggable.enable();
  8670. * ```
  8671. */
  8672. L.Draggable = L.Evented.extend({
  8673. options: {
  8674. // @option clickTolerance: Number = 3
  8675. // The max number of pixels a user can shift the mouse pointer during a click
  8676. // for it to be considered a valid click (as opposed to a mouse drag).
  8677. clickTolerance: 3
  8678. },
  8679. statics: {
  8680. START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
  8681. END: {
  8682. mousedown: 'mouseup',
  8683. touchstart: 'touchend',
  8684. pointerdown: 'touchend',
  8685. MSPointerDown: 'touchend'
  8686. },
  8687. MOVE: {
  8688. mousedown: 'mousemove',
  8689. touchstart: 'touchmove',
  8690. pointerdown: 'touchmove',
  8691. MSPointerDown: 'touchmove'
  8692. }
  8693. },
  8694. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline: Boolean)
  8695. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  8696. initialize: function (element, dragStartTarget, preventOutline) {
  8697. this._element = element;
  8698. this._dragStartTarget = dragStartTarget || element;
  8699. this._preventOutline = preventOutline;
  8700. },
  8701. // @method enable()
  8702. // Enables the dragging ability
  8703. enable: function () {
  8704. if (this._enabled) { return; }
  8705. L.DomEvent.on(this._dragStartTarget, L.Draggable.START.join(' '), this._onDown, this);
  8706. this._enabled = true;
  8707. },
  8708. // @method disable()
  8709. // Disables the dragging ability
  8710. disable: function () {
  8711. if (!this._enabled) { return; }
  8712. // If we're currently dragging this draggable,
  8713. // disabling it counts as first ending the drag.
  8714. if (L.Draggable._dragging === this) {
  8715. this.finishDrag();
  8716. }
  8717. L.DomEvent.off(this._dragStartTarget, L.Draggable.START.join(' '), this._onDown, this);
  8718. this._enabled = false;
  8719. this._moved = false;
  8720. },
  8721. _onDown: function (e) {
  8722. // Ignore simulated events, since we handle both touch and
  8723. // mouse explicitly; otherwise we risk getting duplicates of
  8724. // touch events, see #4315.
  8725. // Also ignore the event if disabled; this happens in IE11
  8726. // under some circumstances, see #3666.
  8727. if (e._simulated || !this._enabled) { return; }
  8728. this._moved = false;
  8729. if (L.DomUtil.hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  8730. if (L.Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  8731. L.Draggable._dragging = this; // Prevent dragging multiple objects at once.
  8732. if (this._preventOutline) {
  8733. L.DomUtil.preventOutline(this._element);
  8734. }
  8735. L.DomUtil.disableImageDrag();
  8736. L.DomUtil.disableTextSelection();
  8737. if (this._moving) { return; }
  8738. // @event down: Event
  8739. // Fired when a drag is about to start.
  8740. this.fire('down');
  8741. var first = e.touches ? e.touches[0] : e;
  8742. this._startPoint = new L.Point(first.clientX, first.clientY);
  8743. L.DomEvent
  8744. .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
  8745. .on(document, L.Draggable.END[e.type], this._onUp, this);
  8746. },
  8747. _onMove: function (e) {
  8748. // Ignore simulated events, since we handle both touch and
  8749. // mouse explicitly; otherwise we risk getting duplicates of
  8750. // touch events, see #4315.
  8751. // Also ignore the event if disabled; this happens in IE11
  8752. // under some circumstances, see #3666.
  8753. if (e._simulated || !this._enabled) { return; }
  8754. if (e.touches && e.touches.length > 1) {
  8755. this._moved = true;
  8756. return;
  8757. }
  8758. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  8759. newPoint = new L.Point(first.clientX, first.clientY),
  8760. offset = newPoint.subtract(this._startPoint);
  8761. if (!offset.x && !offset.y) { return; }
  8762. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  8763. L.DomEvent.preventDefault(e);
  8764. if (!this._moved) {
  8765. // @event dragstart: Event
  8766. // Fired when a drag starts
  8767. this.fire('dragstart');
  8768. this._moved = true;
  8769. this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
  8770. L.DomUtil.addClass(document.body, 'leaflet-dragging');
  8771. this._lastTarget = e.target || e.srcElement;
  8772. // IE and Edge do not give the <use> element, so fetch it
  8773. // if necessary
  8774. if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
  8775. this._lastTarget = this._lastTarget.correspondingUseElement;
  8776. }
  8777. L.DomUtil.addClass(this._lastTarget, 'leaflet-drag-target');
  8778. }
  8779. this._newPos = this._startPos.add(offset);
  8780. this._moving = true;
  8781. L.Util.cancelAnimFrame(this._animRequest);
  8782. this._lastEvent = e;
  8783. this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true);
  8784. },
  8785. _updatePosition: function () {
  8786. var e = {originalEvent: this._lastEvent};
  8787. // @event predrag: Event
  8788. // Fired continuously during dragging *before* each corresponding
  8789. // update of the element's position.
  8790. this.fire('predrag', e);
  8791. L.DomUtil.setPosition(this._element, this._newPos);
  8792. // @event drag: Event
  8793. // Fired continuously during dragging.
  8794. this.fire('drag', e);
  8795. },
  8796. _onUp: function (e) {
  8797. // Ignore simulated events, since we handle both touch and
  8798. // mouse explicitly; otherwise we risk getting duplicates of
  8799. // touch events, see #4315.
  8800. // Also ignore the event if disabled; this happens in IE11
  8801. // under some circumstances, see #3666.
  8802. if (e._simulated || !this._enabled) { return; }
  8803. this.finishDrag();
  8804. },
  8805. finishDrag: function () {
  8806. L.DomUtil.removeClass(document.body, 'leaflet-dragging');
  8807. if (this._lastTarget) {
  8808. L.DomUtil.removeClass(this._lastTarget, 'leaflet-drag-target');
  8809. this._lastTarget = null;
  8810. }
  8811. for (var i in L.Draggable.MOVE) {
  8812. L.DomEvent
  8813. .off(document, L.Draggable.MOVE[i], this._onMove, this)
  8814. .off(document, L.Draggable.END[i], this._onUp, this);
  8815. }
  8816. L.DomUtil.enableImageDrag();
  8817. L.DomUtil.enableTextSelection();
  8818. if (this._moved && this._moving) {
  8819. // ensure drag is not fired after dragend
  8820. L.Util.cancelAnimFrame(this._animRequest);
  8821. // @event dragend: DragEndEvent
  8822. // Fired when the drag ends.
  8823. this.fire('dragend', {
  8824. distance: this._newPos.distanceTo(this._startPos)
  8825. });
  8826. }
  8827. this._moving = false;
  8828. L.Draggable._dragging = false;
  8829. }
  8830. });
  8831. /*
  8832. L.Handler is a base class for handler classes that are used internally to inject
  8833. interaction features like dragging to classes like Map and Marker.
  8834. */
  8835. // @class Handler
  8836. // @aka L.Handler
  8837. // Abstract class for map interaction handlers
  8838. L.Handler = L.Class.extend({
  8839. initialize: function (map) {
  8840. this._map = map;
  8841. },
  8842. // @method enable(): this
  8843. // Enables the handler
  8844. enable: function () {
  8845. if (this._enabled) { return this; }
  8846. this._enabled = true;
  8847. this.addHooks();
  8848. return this;
  8849. },
  8850. // @method disable(): this
  8851. // Disables the handler
  8852. disable: function () {
  8853. if (!this._enabled) { return this; }
  8854. this._enabled = false;
  8855. this.removeHooks();
  8856. return this;
  8857. },
  8858. // @method enabled(): Boolean
  8859. // Returns `true` if the handler is enabled
  8860. enabled: function () {
  8861. return !!this._enabled;
  8862. }
  8863. // @section Extension methods
  8864. // Classes inheriting from `Handler` must implement the two following methods:
  8865. // @method addHooks()
  8866. // Called when the handler is enabled, should add event hooks.
  8867. // @method removeHooks()
  8868. // Called when the handler is disabled, should remove the event hooks added previously.
  8869. });
  8870. /*
  8871. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  8872. */
  8873. // @namespace Map
  8874. // @section Interaction Options
  8875. L.Map.mergeOptions({
  8876. // @option dragging: Boolean = true
  8877. // Whether the map be draggable with mouse/touch or not.
  8878. dragging: true,
  8879. // @section Panning Inertia Options
  8880. // @option inertia: Boolean = *
  8881. // If enabled, panning of the map will have an inertia effect where
  8882. // the map builds momentum while dragging and continues moving in
  8883. // the same direction for some time. Feels especially nice on touch
  8884. // devices. Enabled by default unless running on old Android devices.
  8885. inertia: !L.Browser.android23,
  8886. // @option inertiaDeceleration: Number = 3000
  8887. // The rate with which the inertial movement slows down, in pixels/second².
  8888. inertiaDeceleration: 3400, // px/s^2
  8889. // @option inertiaMaxSpeed: Number = Infinity
  8890. // Max speed of the inertial movement, in pixels/second.
  8891. inertiaMaxSpeed: Infinity, // px/s
  8892. // @option easeLinearity: Number = 0.2
  8893. easeLinearity: 0.2,
  8894. // TODO refactor, move to CRS
  8895. // @option worldCopyJump: Boolean = false
  8896. // With this option enabled, the map tracks when you pan to another "copy"
  8897. // of the world and seamlessly jumps to the original one so that all overlays
  8898. // like markers and vector layers are still visible.
  8899. worldCopyJump: false,
  8900. // @option maxBoundsViscosity: Number = 0.0
  8901. // If `maxBounds` is set, this option will control how solid the bounds
  8902. // are when dragging the map around. The default value of `0.0` allows the
  8903. // user to drag outside the bounds at normal speed, higher values will
  8904. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  8905. // solid, preventing the user from dragging outside the bounds.
  8906. maxBoundsViscosity: 0.0
  8907. });
  8908. L.Map.Drag = L.Handler.extend({
  8909. addHooks: function () {
  8910. if (!this._draggable) {
  8911. var map = this._map;
  8912. this._draggable = new L.Draggable(map._mapPane, map._container);
  8913. this._draggable.on({
  8914. down: this._onDown,
  8915. dragstart: this._onDragStart,
  8916. drag: this._onDrag,
  8917. dragend: this._onDragEnd
  8918. }, this);
  8919. this._draggable.on('predrag', this._onPreDragLimit, this);
  8920. if (map.options.worldCopyJump) {
  8921. this._draggable.on('predrag', this._onPreDragWrap, this);
  8922. map.on('zoomend', this._onZoomEnd, this);
  8923. map.whenReady(this._onZoomEnd, this);
  8924. }
  8925. }
  8926. L.DomUtil.addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  8927. this._draggable.enable();
  8928. this._positions = [];
  8929. this._times = [];
  8930. },
  8931. removeHooks: function () {
  8932. L.DomUtil.removeClass(this._map._container, 'leaflet-grab');
  8933. L.DomUtil.removeClass(this._map._container, 'leaflet-touch-drag');
  8934. this._draggable.disable();
  8935. },
  8936. moved: function () {
  8937. return this._draggable && this._draggable._moved;
  8938. },
  8939. moving: function () {
  8940. return this._draggable && this._draggable._moving;
  8941. },
  8942. _onDown: function () {
  8943. this._map._stop();
  8944. },
  8945. _onDragStart: function () {
  8946. var map = this._map;
  8947. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  8948. var bounds = L.latLngBounds(this._map.options.maxBounds);
  8949. this._offsetLimit = L.bounds(
  8950. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  8951. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  8952. .add(this._map.getSize()));
  8953. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  8954. } else {
  8955. this._offsetLimit = null;
  8956. }
  8957. map
  8958. .fire('movestart')
  8959. .fire('dragstart');
  8960. if (map.options.inertia) {
  8961. this._positions = [];
  8962. this._times = [];
  8963. }
  8964. },
  8965. _onDrag: function (e) {
  8966. if (this._map.options.inertia) {
  8967. var time = this._lastTime = +new Date(),
  8968. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  8969. this._positions.push(pos);
  8970. this._times.push(time);
  8971. if (time - this._times[0] > 50) {
  8972. this._positions.shift();
  8973. this._times.shift();
  8974. }
  8975. }
  8976. this._map
  8977. .fire('move', e)
  8978. .fire('drag', e);
  8979. },
  8980. _onZoomEnd: function () {
  8981. var pxCenter = this._map.getSize().divideBy(2),
  8982. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  8983. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  8984. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  8985. },
  8986. _viscousLimit: function (value, threshold) {
  8987. return value - (value - threshold) * this._viscosity;
  8988. },
  8989. _onPreDragLimit: function () {
  8990. if (!this._viscosity || !this._offsetLimit) { return; }
  8991. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  8992. var limit = this._offsetLimit;
  8993. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  8994. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  8995. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  8996. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  8997. this._draggable._newPos = this._draggable._startPos.add(offset);
  8998. },
  8999. _onPreDragWrap: function () {
  9000. // TODO refactor to be able to adjust map pane position after zoom
  9001. var worldWidth = this._worldWidth,
  9002. halfWidth = Math.round(worldWidth / 2),
  9003. dx = this._initialWorldOffset,
  9004. x = this._draggable._newPos.x,
  9005. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  9006. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  9007. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  9008. this._draggable._absPos = this._draggable._newPos.clone();
  9009. this._draggable._newPos.x = newX;
  9010. },
  9011. _onDragEnd: function (e) {
  9012. var map = this._map,
  9013. options = map.options,
  9014. noInertia = !options.inertia || this._times.length < 2;
  9015. map.fire('dragend', e);
  9016. if (noInertia) {
  9017. map.fire('moveend');
  9018. } else {
  9019. var direction = this._lastPos.subtract(this._positions[0]),
  9020. duration = (this._lastTime - this._times[0]) / 1000,
  9021. ease = options.easeLinearity,
  9022. speedVector = direction.multiplyBy(ease / duration),
  9023. speed = speedVector.distanceTo([0, 0]),
  9024. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  9025. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  9026. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  9027. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  9028. if (!offset.x && !offset.y) {
  9029. map.fire('moveend');
  9030. } else {
  9031. offset = map._limitOffset(offset, map.options.maxBounds);
  9032. L.Util.requestAnimFrame(function () {
  9033. map.panBy(offset, {
  9034. duration: decelerationDuration,
  9035. easeLinearity: ease,
  9036. noMoveStart: true,
  9037. animate: true
  9038. });
  9039. });
  9040. }
  9041. }
  9042. }
  9043. });
  9044. // @section Handlers
  9045. // @property dragging: Handler
  9046. // Map dragging handler (by both mouse and touch).
  9047. L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
  9048. /*
  9049. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  9050. */
  9051. // @namespace Map
  9052. // @section Interaction Options
  9053. L.Map.mergeOptions({
  9054. // @option doubleClickZoom: Boolean|String = true
  9055. // Whether the map can be zoomed in by double clicking on it and
  9056. // zoomed out by double clicking while holding shift. If passed
  9057. // `'center'`, double-click zoom will zoom to the center of the
  9058. // view regardless of where the mouse was.
  9059. doubleClickZoom: true
  9060. });
  9061. L.Map.DoubleClickZoom = L.Handler.extend({
  9062. addHooks: function () {
  9063. this._map.on('dblclick', this._onDoubleClick, this);
  9064. },
  9065. removeHooks: function () {
  9066. this._map.off('dblclick', this._onDoubleClick, this);
  9067. },
  9068. _onDoubleClick: function (e) {
  9069. var map = this._map,
  9070. oldZoom = map.getZoom(),
  9071. delta = map.options.zoomDelta,
  9072. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  9073. if (map.options.doubleClickZoom === 'center') {
  9074. map.setZoom(zoom);
  9075. } else {
  9076. map.setZoomAround(e.containerPoint, zoom);
  9077. }
  9078. }
  9079. });
  9080. // @section Handlers
  9081. //
  9082. // Map properties include interaction handlers that allow you to control
  9083. // interaction behavior in runtime, enabling or disabling certain features such
  9084. // as dragging or touch zoom (see `Handler` methods). For example:
  9085. //
  9086. // ```js
  9087. // map.doubleClickZoom.disable();
  9088. // ```
  9089. //
  9090. // @property doubleClickZoom: Handler
  9091. // Double click zoom handler.
  9092. L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
  9093. /*
  9094. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  9095. */
  9096. // @namespace Map
  9097. // @section Interaction Options
  9098. L.Map.mergeOptions({
  9099. // @section Mousewheel options
  9100. // @option scrollWheelZoom: Boolean|String = true
  9101. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  9102. // it will zoom to the center of the view regardless of where the mouse was.
  9103. scrollWheelZoom: true,
  9104. // @option wheelDebounceTime: Number = 40
  9105. // Limits the rate at which a wheel can fire (in milliseconds). By default
  9106. // user can't zoom via wheel more often than once per 40 ms.
  9107. wheelDebounceTime: 40,
  9108. // @option wheelPxPerZoomLevel: Number = 60
  9109. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  9110. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  9111. // faster (and vice versa).
  9112. wheelPxPerZoomLevel: 60
  9113. });
  9114. L.Map.ScrollWheelZoom = L.Handler.extend({
  9115. addHooks: function () {
  9116. L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  9117. this._delta = 0;
  9118. },
  9119. removeHooks: function () {
  9120. L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll, this);
  9121. },
  9122. _onWheelScroll: function (e) {
  9123. var delta = L.DomEvent.getWheelDelta(e);
  9124. var debounce = this._map.options.wheelDebounceTime;
  9125. this._delta += delta;
  9126. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  9127. if (!this._startTime) {
  9128. this._startTime = +new Date();
  9129. }
  9130. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  9131. clearTimeout(this._timer);
  9132. this._timer = setTimeout(L.bind(this._performZoom, this), left);
  9133. L.DomEvent.stop(e);
  9134. },
  9135. _performZoom: function () {
  9136. var map = this._map,
  9137. zoom = map.getZoom(),
  9138. snap = this._map.options.zoomSnap || 0;
  9139. map._stop(); // stop panning and fly animations if any
  9140. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  9141. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  9142. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  9143. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  9144. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  9145. this._delta = 0;
  9146. this._startTime = null;
  9147. if (!delta) { return; }
  9148. if (map.options.scrollWheelZoom === 'center') {
  9149. map.setZoom(zoom + delta);
  9150. } else {
  9151. map.setZoomAround(this._lastMousePos, zoom + delta);
  9152. }
  9153. }
  9154. });
  9155. // @section Handlers
  9156. // @property scrollWheelZoom: Handler
  9157. // Scroll wheel zoom handler.
  9158. L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
  9159. /*
  9160. * Extends the event handling code with double tap support for mobile browsers.
  9161. */
  9162. L.extend(L.DomEvent, {
  9163. _touchstart: L.Browser.msPointer ? 'MSPointerDown' : L.Browser.pointer ? 'pointerdown' : 'touchstart',
  9164. _touchend: L.Browser.msPointer ? 'MSPointerUp' : L.Browser.pointer ? 'pointerup' : 'touchend',
  9165. // inspired by Zepto touch code by Thomas Fuchs
  9166. addDoubleTapListener: function (obj, handler, id) {
  9167. var last, touch,
  9168. doubleTap = false,
  9169. delay = 250;
  9170. function onTouchStart(e) {
  9171. var count;
  9172. if (L.Browser.pointer) {
  9173. if ((!L.Browser.edge) || e.pointerType === 'mouse') { return; }
  9174. count = L.DomEvent._pointersCount;
  9175. } else {
  9176. count = e.touches.length;
  9177. }
  9178. if (count > 1) { return; }
  9179. var now = Date.now(),
  9180. delta = now - (last || now);
  9181. touch = e.touches ? e.touches[0] : e;
  9182. doubleTap = (delta > 0 && delta <= delay);
  9183. last = now;
  9184. }
  9185. function onTouchEnd(e) {
  9186. if (doubleTap && !touch.cancelBubble) {
  9187. if (L.Browser.pointer) {
  9188. if ((!L.Browser.edge) || e.pointerType === 'mouse') { return; }
  9189. // work around .type being readonly with MSPointer* events
  9190. var newTouch = {},
  9191. prop, i;
  9192. for (i in touch) {
  9193. prop = touch[i];
  9194. newTouch[i] = prop && prop.bind ? prop.bind(touch) : prop;
  9195. }
  9196. touch = newTouch;
  9197. }
  9198. touch.type = 'dblclick';
  9199. handler(touch);
  9200. last = null;
  9201. }
  9202. }
  9203. var pre = '_leaflet_',
  9204. touchstart = this._touchstart,
  9205. touchend = this._touchend;
  9206. obj[pre + touchstart + id] = onTouchStart;
  9207. obj[pre + touchend + id] = onTouchEnd;
  9208. obj[pre + 'dblclick' + id] = handler;
  9209. obj.addEventListener(touchstart, onTouchStart, false);
  9210. obj.addEventListener(touchend, onTouchEnd, false);
  9211. // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
  9212. // the browser doesn't fire touchend/pointerup events but does fire
  9213. // native dblclicks. See #4127.
  9214. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
  9215. obj.addEventListener('dblclick', handler, false);
  9216. return this;
  9217. },
  9218. removeDoubleTapListener: function (obj, id) {
  9219. var pre = '_leaflet_',
  9220. touchstart = obj[pre + this._touchstart + id],
  9221. touchend = obj[pre + this._touchend + id],
  9222. dblclick = obj[pre + 'dblclick' + id];
  9223. obj.removeEventListener(this._touchstart, touchstart, false);
  9224. obj.removeEventListener(this._touchend, touchend, false);
  9225. if (!L.Browser.edge) {
  9226. obj.removeEventListener('dblclick', dblclick, false);
  9227. }
  9228. return this;
  9229. }
  9230. });
  9231. /*
  9232. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  9233. */
  9234. L.extend(L.DomEvent, {
  9235. POINTER_DOWN: L.Browser.msPointer ? 'MSPointerDown' : 'pointerdown',
  9236. POINTER_MOVE: L.Browser.msPointer ? 'MSPointerMove' : 'pointermove',
  9237. POINTER_UP: L.Browser.msPointer ? 'MSPointerUp' : 'pointerup',
  9238. POINTER_CANCEL: L.Browser.msPointer ? 'MSPointerCancel' : 'pointercancel',
  9239. TAG_WHITE_LIST: ['INPUT', 'SELECT', 'OPTION'],
  9240. _pointers: {},
  9241. _pointersCount: 0,
  9242. // Provides a touch events wrapper for (ms)pointer events.
  9243. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  9244. addPointerListener: function (obj, type, handler, id) {
  9245. if (type === 'touchstart') {
  9246. this._addPointerStart(obj, handler, id);
  9247. } else if (type === 'touchmove') {
  9248. this._addPointerMove(obj, handler, id);
  9249. } else if (type === 'touchend') {
  9250. this._addPointerEnd(obj, handler, id);
  9251. }
  9252. return this;
  9253. },
  9254. removePointerListener: function (obj, type, id) {
  9255. var handler = obj['_leaflet_' + type + id];
  9256. if (type === 'touchstart') {
  9257. obj.removeEventListener(this.POINTER_DOWN, handler, false);
  9258. } else if (type === 'touchmove') {
  9259. obj.removeEventListener(this.POINTER_MOVE, handler, false);
  9260. } else if (type === 'touchend') {
  9261. obj.removeEventListener(this.POINTER_UP, handler, false);
  9262. obj.removeEventListener(this.POINTER_CANCEL, handler, false);
  9263. }
  9264. return this;
  9265. },
  9266. _addPointerStart: function (obj, handler, id) {
  9267. var onDown = L.bind(function (e) {
  9268. if (e.pointerType !== 'mouse' && e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
  9269. // In IE11, some touch events needs to fire for form controls, or
  9270. // the controls will stop working. We keep a whitelist of tag names that
  9271. // need these events. For other target tags, we prevent default on the event.
  9272. if (this.TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
  9273. L.DomEvent.preventDefault(e);
  9274. } else {
  9275. return;
  9276. }
  9277. }
  9278. this._handlePointer(e, handler);
  9279. }, this);
  9280. obj['_leaflet_touchstart' + id] = onDown;
  9281. obj.addEventListener(this.POINTER_DOWN, onDown, false);
  9282. // need to keep track of what pointers and how many are active to provide e.touches emulation
  9283. if (!this._pointerDocListener) {
  9284. var pointerUp = L.bind(this._globalPointerUp, this);
  9285. // we listen documentElement as any drags that end by moving the touch off the screen get fired there
  9286. document.documentElement.addEventListener(this.POINTER_DOWN, L.bind(this._globalPointerDown, this), true);
  9287. document.documentElement.addEventListener(this.POINTER_MOVE, L.bind(this._globalPointerMove, this), true);
  9288. document.documentElement.addEventListener(this.POINTER_UP, pointerUp, true);
  9289. document.documentElement.addEventListener(this.POINTER_CANCEL, pointerUp, true);
  9290. this._pointerDocListener = true;
  9291. }
  9292. },
  9293. _globalPointerDown: function (e) {
  9294. this._pointers[e.pointerId] = e;
  9295. this._pointersCount++;
  9296. },
  9297. _globalPointerMove: function (e) {
  9298. if (this._pointers[e.pointerId]) {
  9299. this._pointers[e.pointerId] = e;
  9300. }
  9301. },
  9302. _globalPointerUp: function (e) {
  9303. delete this._pointers[e.pointerId];
  9304. this._pointersCount--;
  9305. },
  9306. _handlePointer: function (e, handler) {
  9307. e.touches = [];
  9308. for (var i in this._pointers) {
  9309. e.touches.push(this._pointers[i]);
  9310. }
  9311. e.changedTouches = [e];
  9312. handler(e);
  9313. },
  9314. _addPointerMove: function (obj, handler, id) {
  9315. var onMove = L.bind(function (e) {
  9316. // don't fire touch moves when mouse isn't down
  9317. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
  9318. this._handlePointer(e, handler);
  9319. }, this);
  9320. obj['_leaflet_touchmove' + id] = onMove;
  9321. obj.addEventListener(this.POINTER_MOVE, onMove, false);
  9322. },
  9323. _addPointerEnd: function (obj, handler, id) {
  9324. var onUp = L.bind(function (e) {
  9325. this._handlePointer(e, handler);
  9326. }, this);
  9327. obj['_leaflet_touchend' + id] = onUp;
  9328. obj.addEventListener(this.POINTER_UP, onUp, false);
  9329. obj.addEventListener(this.POINTER_CANCEL, onUp, false);
  9330. }
  9331. });
  9332. /*
  9333. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  9334. */
  9335. // @namespace Map
  9336. // @section Interaction Options
  9337. L.Map.mergeOptions({
  9338. // @section Touch interaction options
  9339. // @option touchZoom: Boolean|String = *
  9340. // Whether the map can be zoomed by touch-dragging with two fingers. If
  9341. // passed `'center'`, it will zoom to the center of the view regardless of
  9342. // where the touch events (fingers) were. Enabled for touch-capable web
  9343. // browsers except for old Androids.
  9344. touchZoom: L.Browser.touch && !L.Browser.android23,
  9345. // @option bounceAtZoomLimits: Boolean = true
  9346. // Set it to false if you don't want the map to zoom beyond min/max zoom
  9347. // and then bounce back when pinch-zooming.
  9348. bounceAtZoomLimits: true
  9349. });
  9350. L.Map.TouchZoom = L.Handler.extend({
  9351. addHooks: function () {
  9352. L.DomUtil.addClass(this._map._container, 'leaflet-touch-zoom');
  9353. L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
  9354. },
  9355. removeHooks: function () {
  9356. L.DomUtil.removeClass(this._map._container, 'leaflet-touch-zoom');
  9357. L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
  9358. },
  9359. _onTouchStart: function (e) {
  9360. var map = this._map;
  9361. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  9362. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  9363. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  9364. this._centerPoint = map.getSize()._divideBy(2);
  9365. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  9366. if (map.options.touchZoom !== 'center') {
  9367. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  9368. }
  9369. this._startDist = p1.distanceTo(p2);
  9370. this._startZoom = map.getZoom();
  9371. this._moved = false;
  9372. this._zooming = true;
  9373. map._stop();
  9374. L.DomEvent
  9375. .on(document, 'touchmove', this._onTouchMove, this)
  9376. .on(document, 'touchend', this._onTouchEnd, this);
  9377. L.DomEvent.preventDefault(e);
  9378. },
  9379. _onTouchMove: function (e) {
  9380. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  9381. var map = this._map,
  9382. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  9383. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  9384. scale = p1.distanceTo(p2) / this._startDist;
  9385. this._zoom = map.getScaleZoom(scale, this._startZoom);
  9386. if (!map.options.bounceAtZoomLimits && (
  9387. (this._zoom < map.getMinZoom() && scale < 1) ||
  9388. (this._zoom > map.getMaxZoom() && scale > 1))) {
  9389. this._zoom = map._limitZoom(this._zoom);
  9390. }
  9391. if (map.options.touchZoom === 'center') {
  9392. this._center = this._startLatLng;
  9393. if (scale === 1) { return; }
  9394. } else {
  9395. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  9396. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  9397. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  9398. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  9399. }
  9400. if (!this._moved) {
  9401. map._moveStart(true);
  9402. this._moved = true;
  9403. }
  9404. L.Util.cancelAnimFrame(this._animRequest);
  9405. var moveFn = L.bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  9406. this._animRequest = L.Util.requestAnimFrame(moveFn, this, true);
  9407. L.DomEvent.preventDefault(e);
  9408. },
  9409. _onTouchEnd: function () {
  9410. if (!this._moved || !this._zooming) {
  9411. this._zooming = false;
  9412. return;
  9413. }
  9414. this._zooming = false;
  9415. L.Util.cancelAnimFrame(this._animRequest);
  9416. L.DomEvent
  9417. .off(document, 'touchmove', this._onTouchMove)
  9418. .off(document, 'touchend', this._onTouchEnd);
  9419. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  9420. if (this._map.options.zoomAnimation) {
  9421. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  9422. } else {
  9423. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  9424. }
  9425. }
  9426. });
  9427. // @section Handlers
  9428. // @property touchZoom: Handler
  9429. // Touch zoom handler.
  9430. L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
  9431. /*
  9432. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  9433. */
  9434. // @namespace Map
  9435. // @section Interaction Options
  9436. L.Map.mergeOptions({
  9437. // @section Touch interaction options
  9438. // @option tap: Boolean = true
  9439. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  9440. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  9441. tap: true,
  9442. // @option tapTolerance: Number = 15
  9443. // The max number of pixels a user can shift his finger during touch
  9444. // for it to be considered a valid tap.
  9445. tapTolerance: 15
  9446. });
  9447. L.Map.Tap = L.Handler.extend({
  9448. addHooks: function () {
  9449. L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
  9450. },
  9451. removeHooks: function () {
  9452. L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
  9453. },
  9454. _onDown: function (e) {
  9455. if (!e.touches) { return; }
  9456. L.DomEvent.preventDefault(e);
  9457. this._fireClick = true;
  9458. // don't simulate click or track longpress if more than 1 touch
  9459. if (e.touches.length > 1) {
  9460. this._fireClick = false;
  9461. clearTimeout(this._holdTimeout);
  9462. return;
  9463. }
  9464. var first = e.touches[0],
  9465. el = first.target;
  9466. this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
  9467. // if touching a link, highlight it
  9468. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  9469. L.DomUtil.addClass(el, 'leaflet-active');
  9470. }
  9471. // simulate long hold but setting a timeout
  9472. this._holdTimeout = setTimeout(L.bind(function () {
  9473. if (this._isTapValid()) {
  9474. this._fireClick = false;
  9475. this._onUp();
  9476. this._simulateEvent('contextmenu', first);
  9477. }
  9478. }, this), 1000);
  9479. this._simulateEvent('mousedown', first);
  9480. L.DomEvent.on(document, {
  9481. touchmove: this._onMove,
  9482. touchend: this._onUp
  9483. }, this);
  9484. },
  9485. _onUp: function (e) {
  9486. clearTimeout(this._holdTimeout);
  9487. L.DomEvent.off(document, {
  9488. touchmove: this._onMove,
  9489. touchend: this._onUp
  9490. }, this);
  9491. if (this._fireClick && e && e.changedTouches) {
  9492. var first = e.changedTouches[0],
  9493. el = first.target;
  9494. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  9495. L.DomUtil.removeClass(el, 'leaflet-active');
  9496. }
  9497. this._simulateEvent('mouseup', first);
  9498. // simulate click if the touch didn't move too much
  9499. if (this._isTapValid()) {
  9500. this._simulateEvent('click', first);
  9501. }
  9502. }
  9503. },
  9504. _isTapValid: function () {
  9505. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  9506. },
  9507. _onMove: function (e) {
  9508. var first = e.touches[0];
  9509. this._newPos = new L.Point(first.clientX, first.clientY);
  9510. this._simulateEvent('mousemove', first);
  9511. },
  9512. _simulateEvent: function (type, e) {
  9513. var simulatedEvent = document.createEvent('MouseEvents');
  9514. simulatedEvent._simulated = true;
  9515. e.target._simulatedClick = true;
  9516. simulatedEvent.initMouseEvent(
  9517. type, true, true, window, 1,
  9518. e.screenX, e.screenY,
  9519. e.clientX, e.clientY,
  9520. false, false, false, false, 0, null);
  9521. e.target.dispatchEvent(simulatedEvent);
  9522. }
  9523. });
  9524. // @section Handlers
  9525. // @property tap: Handler
  9526. // Mobile touch hacks (quick tap and touch hold) handler.
  9527. if (L.Browser.touch && !L.Browser.pointer) {
  9528. L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
  9529. }
  9530. /*
  9531. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  9532. * (zoom to a selected bounding box), enabled by default.
  9533. */
  9534. // @namespace Map
  9535. // @section Interaction Options
  9536. L.Map.mergeOptions({
  9537. // @option boxZoom: Boolean = true
  9538. // Whether the map can be zoomed to a rectangular area specified by
  9539. // dragging the mouse while pressing the shift key.
  9540. boxZoom: true
  9541. });
  9542. L.Map.BoxZoom = L.Handler.extend({
  9543. initialize: function (map) {
  9544. this._map = map;
  9545. this._container = map._container;
  9546. this._pane = map._panes.overlayPane;
  9547. },
  9548. addHooks: function () {
  9549. L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
  9550. },
  9551. removeHooks: function () {
  9552. L.DomEvent.off(this._container, 'mousedown', this._onMouseDown, this);
  9553. },
  9554. moved: function () {
  9555. return this._moved;
  9556. },
  9557. _resetState: function () {
  9558. this._moved = false;
  9559. },
  9560. _onMouseDown: function (e) {
  9561. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  9562. this._resetState();
  9563. L.DomUtil.disableTextSelection();
  9564. L.DomUtil.disableImageDrag();
  9565. this._startPoint = this._map.mouseEventToContainerPoint(e);
  9566. L.DomEvent.on(document, {
  9567. contextmenu: L.DomEvent.stop,
  9568. mousemove: this._onMouseMove,
  9569. mouseup: this._onMouseUp,
  9570. keydown: this._onKeyDown
  9571. }, this);
  9572. },
  9573. _onMouseMove: function (e) {
  9574. if (!this._moved) {
  9575. this._moved = true;
  9576. this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._container);
  9577. L.DomUtil.addClass(this._container, 'leaflet-crosshair');
  9578. this._map.fire('boxzoomstart');
  9579. }
  9580. this._point = this._map.mouseEventToContainerPoint(e);
  9581. var bounds = new L.Bounds(this._point, this._startPoint),
  9582. size = bounds.getSize();
  9583. L.DomUtil.setPosition(this._box, bounds.min);
  9584. this._box.style.width = size.x + 'px';
  9585. this._box.style.height = size.y + 'px';
  9586. },
  9587. _finish: function () {
  9588. if (this._moved) {
  9589. L.DomUtil.remove(this._box);
  9590. L.DomUtil.removeClass(this._container, 'leaflet-crosshair');
  9591. }
  9592. L.DomUtil.enableTextSelection();
  9593. L.DomUtil.enableImageDrag();
  9594. L.DomEvent.off(document, {
  9595. contextmenu: L.DomEvent.stop,
  9596. mousemove: this._onMouseMove,
  9597. mouseup: this._onMouseUp,
  9598. keydown: this._onKeyDown
  9599. }, this);
  9600. },
  9601. _onMouseUp: function (e) {
  9602. if ((e.which !== 1) && (e.button !== 1)) { return; }
  9603. this._finish();
  9604. if (!this._moved) { return; }
  9605. // Postpone to next JS tick so internal click event handling
  9606. // still see it as "moved".
  9607. setTimeout(L.bind(this._resetState, this), 0);
  9608. var bounds = new L.LatLngBounds(
  9609. this._map.containerPointToLatLng(this._startPoint),
  9610. this._map.containerPointToLatLng(this._point));
  9611. this._map
  9612. .fitBounds(bounds)
  9613. .fire('boxzoomend', {boxZoomBounds: bounds});
  9614. },
  9615. _onKeyDown: function (e) {
  9616. if (e.keyCode === 27) {
  9617. this._finish();
  9618. }
  9619. }
  9620. });
  9621. // @section Handlers
  9622. // @property boxZoom: Handler
  9623. // Box (shift-drag with mouse) zoom handler.
  9624. L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
  9625. /*
  9626. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  9627. */
  9628. // @namespace Map
  9629. // @section Keyboard Navigation Options
  9630. L.Map.mergeOptions({
  9631. // @option keyboard: Boolean = true
  9632. // Makes the map focusable and allows users to navigate the map with keyboard
  9633. // arrows and `+`/`-` keys.
  9634. keyboard: true,
  9635. // @option keyboardPanDelta: Number = 80
  9636. // Amount of pixels to pan when pressing an arrow key.
  9637. keyboardPanDelta: 80
  9638. });
  9639. L.Map.Keyboard = L.Handler.extend({
  9640. keyCodes: {
  9641. left: [37],
  9642. right: [39],
  9643. down: [40],
  9644. up: [38],
  9645. zoomIn: [187, 107, 61, 171],
  9646. zoomOut: [189, 109, 54, 173]
  9647. },
  9648. initialize: function (map) {
  9649. this._map = map;
  9650. this._setPanDelta(map.options.keyboardPanDelta);
  9651. this._setZoomDelta(map.options.zoomDelta);
  9652. },
  9653. addHooks: function () {
  9654. var container = this._map._container;
  9655. // make the container focusable by tabbing
  9656. if (container.tabIndex <= 0) {
  9657. container.tabIndex = '0';
  9658. }
  9659. L.DomEvent.on(container, {
  9660. focus: this._onFocus,
  9661. blur: this._onBlur,
  9662. mousedown: this._onMouseDown
  9663. }, this);
  9664. this._map.on({
  9665. focus: this._addHooks,
  9666. blur: this._removeHooks
  9667. }, this);
  9668. },
  9669. removeHooks: function () {
  9670. this._removeHooks();
  9671. L.DomEvent.off(this._map._container, {
  9672. focus: this._onFocus,
  9673. blur: this._onBlur,
  9674. mousedown: this._onMouseDown
  9675. }, this);
  9676. this._map.off({
  9677. focus: this._addHooks,
  9678. blur: this._removeHooks
  9679. }, this);
  9680. },
  9681. _onMouseDown: function () {
  9682. if (this._focused) { return; }
  9683. var body = document.body,
  9684. docEl = document.documentElement,
  9685. top = body.scrollTop || docEl.scrollTop,
  9686. left = body.scrollLeft || docEl.scrollLeft;
  9687. this._map._container.focus();
  9688. window.scrollTo(left, top);
  9689. },
  9690. _onFocus: function () {
  9691. this._focused = true;
  9692. this._map.fire('focus');
  9693. },
  9694. _onBlur: function () {
  9695. this._focused = false;
  9696. this._map.fire('blur');
  9697. },
  9698. _setPanDelta: function (panDelta) {
  9699. var keys = this._panKeys = {},
  9700. codes = this.keyCodes,
  9701. i, len;
  9702. for (i = 0, len = codes.left.length; i < len; i++) {
  9703. keys[codes.left[i]] = [-1 * panDelta, 0];
  9704. }
  9705. for (i = 0, len = codes.right.length; i < len; i++) {
  9706. keys[codes.right[i]] = [panDelta, 0];
  9707. }
  9708. for (i = 0, len = codes.down.length; i < len; i++) {
  9709. keys[codes.down[i]] = [0, panDelta];
  9710. }
  9711. for (i = 0, len = codes.up.length; i < len; i++) {
  9712. keys[codes.up[i]] = [0, -1 * panDelta];
  9713. }
  9714. },
  9715. _setZoomDelta: function (zoomDelta) {
  9716. var keys = this._zoomKeys = {},
  9717. codes = this.keyCodes,
  9718. i, len;
  9719. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  9720. keys[codes.zoomIn[i]] = zoomDelta;
  9721. }
  9722. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  9723. keys[codes.zoomOut[i]] = -zoomDelta;
  9724. }
  9725. },
  9726. _addHooks: function () {
  9727. L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
  9728. },
  9729. _removeHooks: function () {
  9730. L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
  9731. },
  9732. _onKeyDown: function (e) {
  9733. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  9734. var key = e.keyCode,
  9735. map = this._map,
  9736. offset;
  9737. if (key in this._panKeys) {
  9738. if (map._panAnim && map._panAnim._inProgress) { return; }
  9739. offset = this._panKeys[key];
  9740. if (e.shiftKey) {
  9741. offset = L.point(offset).multiplyBy(3);
  9742. }
  9743. map.panBy(offset);
  9744. if (map.options.maxBounds) {
  9745. map.panInsideBounds(map.options.maxBounds);
  9746. }
  9747. } else if (key in this._zoomKeys) {
  9748. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  9749. } else if (key === 27) {
  9750. map.closePopup();
  9751. } else {
  9752. return;
  9753. }
  9754. L.DomEvent.stop(e);
  9755. }
  9756. });
  9757. // @section Handlers
  9758. // @section Handlers
  9759. // @property keyboard: Handler
  9760. // Keyboard navigation handler.
  9761. L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
  9762. /*
  9763. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  9764. */
  9765. /* @namespace Marker
  9766. * @section Interaction handlers
  9767. *
  9768. * Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see `Handler` methods). Example:
  9769. *
  9770. * ```js
  9771. * marker.dragging.disable();
  9772. * ```
  9773. *
  9774. * @property dragging: Handler
  9775. * Marker dragging handler (by both mouse and touch).
  9776. */
  9777. L.Handler.MarkerDrag = L.Handler.extend({
  9778. initialize: function (marker) {
  9779. this._marker = marker;
  9780. },
  9781. addHooks: function () {
  9782. var icon = this._marker._icon;
  9783. if (!this._draggable) {
  9784. this._draggable = new L.Draggable(icon, icon, true);
  9785. }
  9786. this._draggable.on({
  9787. dragstart: this._onDragStart,
  9788. drag: this._onDrag,
  9789. dragend: this._onDragEnd
  9790. }, this).enable();
  9791. L.DomUtil.addClass(icon, 'leaflet-marker-draggable');
  9792. },
  9793. removeHooks: function () {
  9794. this._draggable.off({
  9795. dragstart: this._onDragStart,
  9796. drag: this._onDrag,
  9797. dragend: this._onDragEnd
  9798. }, this).disable();
  9799. if (this._marker._icon) {
  9800. L.DomUtil.removeClass(this._marker._icon, 'leaflet-marker-draggable');
  9801. }
  9802. },
  9803. moved: function () {
  9804. return this._draggable && this._draggable._moved;
  9805. },
  9806. _onDragStart: function () {
  9807. // @section Dragging events
  9808. // @event dragstart: Event
  9809. // Fired when the user starts dragging the marker.
  9810. // @event movestart: Event
  9811. // Fired when the marker starts moving (because of dragging).
  9812. this._oldLatLng = this._marker.getLatLng();
  9813. this._marker
  9814. .closePopup()
  9815. .fire('movestart')
  9816. .fire('dragstart');
  9817. },
  9818. _onDrag: function (e) {
  9819. var marker = this._marker,
  9820. shadow = marker._shadow,
  9821. iconPos = L.DomUtil.getPosition(marker._icon),
  9822. latlng = marker._map.layerPointToLatLng(iconPos);
  9823. // update shadow position
  9824. if (shadow) {
  9825. L.DomUtil.setPosition(shadow, iconPos);
  9826. }
  9827. marker._latlng = latlng;
  9828. e.latlng = latlng;
  9829. e.oldLatLng = this._oldLatLng;
  9830. // @event drag: Event
  9831. // Fired repeatedly while the user drags the marker.
  9832. marker
  9833. .fire('move', e)
  9834. .fire('drag', e);
  9835. },
  9836. _onDragEnd: function (e) {
  9837. // @event dragend: DragEndEvent
  9838. // Fired when the user stops dragging the marker.
  9839. // @event moveend: Event
  9840. // Fired when the marker stops moving (because of dragging).
  9841. delete this._oldLatLng;
  9842. this._marker
  9843. .fire('moveend')
  9844. .fire('dragend', e);
  9845. }
  9846. });
  9847. /*
  9848. * @class Control
  9849. * @aka L.Control
  9850. * @inherits Class
  9851. *
  9852. * L.Control is a base class for implementing map controls. Handles positioning.
  9853. * All other controls extend from this class.
  9854. */
  9855. L.Control = L.Class.extend({
  9856. // @section
  9857. // @aka Control options
  9858. options: {
  9859. // @option position: String = 'topright'
  9860. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  9861. // `'topright'`, `'bottomleft'` or `'bottomright'`
  9862. position: 'topright'
  9863. },
  9864. initialize: function (options) {
  9865. L.setOptions(this, options);
  9866. },
  9867. /* @section
  9868. * Classes extending L.Control will inherit the following methods:
  9869. *
  9870. * @method getPosition: string
  9871. * Returns the position of the control.
  9872. */
  9873. getPosition: function () {
  9874. return this.options.position;
  9875. },
  9876. // @method setPosition(position: string): this
  9877. // Sets the position of the control.
  9878. setPosition: function (position) {
  9879. var map = this._map;
  9880. if (map) {
  9881. map.removeControl(this);
  9882. }
  9883. this.options.position = position;
  9884. if (map) {
  9885. map.addControl(this);
  9886. }
  9887. return this;
  9888. },
  9889. // @method getContainer: HTMLElement
  9890. // Returns the HTMLElement that contains the control.
  9891. getContainer: function () {
  9892. return this._container;
  9893. },
  9894. // @method addTo(map: Map): this
  9895. // Adds the control to the given map.
  9896. addTo: function (map) {
  9897. this.remove();
  9898. this._map = map;
  9899. var container = this._container = this.onAdd(map),
  9900. pos = this.getPosition(),
  9901. corner = map._controlCorners[pos];
  9902. L.DomUtil.addClass(container, 'leaflet-control');
  9903. if (pos.indexOf('bottom') !== -1) {
  9904. corner.insertBefore(container, corner.firstChild);
  9905. } else {
  9906. corner.appendChild(container);
  9907. }
  9908. return this;
  9909. },
  9910. // @method remove: this
  9911. // Removes the control from the map it is currently active on.
  9912. remove: function () {
  9913. if (!this._map) {
  9914. return this;
  9915. }
  9916. L.DomUtil.remove(this._container);
  9917. if (this.onRemove) {
  9918. this.onRemove(this._map);
  9919. }
  9920. this._map = null;
  9921. return this;
  9922. },
  9923. _refocusOnMap: function (e) {
  9924. // if map exists and event is not a keyboard event
  9925. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  9926. this._map.getContainer().focus();
  9927. }
  9928. }
  9929. });
  9930. L.control = function (options) {
  9931. return new L.Control(options);
  9932. };
  9933. /* @section Extension methods
  9934. * @uninheritable
  9935. *
  9936. * Every control should extend from `L.Control` and (re-)implement the following methods.
  9937. *
  9938. * @method onAdd(map: Map): HTMLElement
  9939. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  9940. *
  9941. * @method onRemove(map: Map)
  9942. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  9943. */
  9944. /* @namespace Map
  9945. * @section Methods for Layers and Controls
  9946. */
  9947. L.Map.include({
  9948. // @method addControl(control: Control): this
  9949. // Adds the given control to the map
  9950. addControl: function (control) {
  9951. control.addTo(this);
  9952. return this;
  9953. },
  9954. // @method removeControl(control: Control): this
  9955. // Removes the given control from the map
  9956. removeControl: function (control) {
  9957. control.remove();
  9958. return this;
  9959. },
  9960. _initControlPos: function () {
  9961. var corners = this._controlCorners = {},
  9962. l = 'leaflet-',
  9963. container = this._controlContainer =
  9964. L.DomUtil.create('div', l + 'control-container', this._container);
  9965. function createCorner(vSide, hSide) {
  9966. var className = l + vSide + ' ' + l + hSide;
  9967. corners[vSide + hSide] = L.DomUtil.create('div', className, container);
  9968. }
  9969. createCorner('top', 'left');
  9970. createCorner('top', 'right');
  9971. createCorner('bottom', 'left');
  9972. createCorner('bottom', 'right');
  9973. },
  9974. _clearControlPos: function () {
  9975. L.DomUtil.remove(this._controlContainer);
  9976. }
  9977. });
  9978. /*
  9979. * @class Control.Zoom
  9980. * @aka L.Control.Zoom
  9981. * @inherits Control
  9982. *
  9983. * A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`.
  9984. */
  9985. L.Control.Zoom = L.Control.extend({
  9986. // @section
  9987. // @aka Control.Zoom options
  9988. options: {
  9989. position: 'topleft',
  9990. // @option zoomInText: String = '+'
  9991. // The text set on the 'zoom in' button.
  9992. zoomInText: '+',
  9993. // @option zoomInTitle: String = 'Zoom in'
  9994. // The title set on the 'zoom in' button.
  9995. zoomInTitle: 'Zoom in',
  9996. // @option zoomOutText: String = '-'
  9997. // The text set on the 'zoom out' button.
  9998. zoomOutText: '-',
  9999. // @option zoomOutTitle: String = 'Zoom out'
  10000. // The title set on the 'zoom out' button.
  10001. zoomOutTitle: 'Zoom out'
  10002. },
  10003. onAdd: function (map) {
  10004. var zoomName = 'leaflet-control-zoom',
  10005. container = L.DomUtil.create('div', zoomName + ' leaflet-bar'),
  10006. options = this.options;
  10007. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  10008. zoomName + '-in', container, this._zoomIn);
  10009. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  10010. zoomName + '-out', container, this._zoomOut);
  10011. this._updateDisabled();
  10012. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  10013. return container;
  10014. },
  10015. onRemove: function (map) {
  10016. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  10017. },
  10018. disable: function () {
  10019. this._disabled = true;
  10020. this._updateDisabled();
  10021. return this;
  10022. },
  10023. enable: function () {
  10024. this._disabled = false;
  10025. this._updateDisabled();
  10026. return this;
  10027. },
  10028. _zoomIn: function (e) {
  10029. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  10030. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  10031. }
  10032. },
  10033. _zoomOut: function (e) {
  10034. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  10035. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  10036. }
  10037. },
  10038. _createButton: function (html, title, className, container, fn) {
  10039. var link = L.DomUtil.create('a', className, container);
  10040. link.innerHTML = html;
  10041. link.href = '#';
  10042. link.title = title;
  10043. /*
  10044. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  10045. */
  10046. link.setAttribute('role', 'button');
  10047. link.setAttribute('aria-label', title);
  10048. L.DomEvent
  10049. .on(link, 'mousedown dblclick', L.DomEvent.stopPropagation)
  10050. .on(link, 'click', L.DomEvent.stop)
  10051. .on(link, 'click', fn, this)
  10052. .on(link, 'click', this._refocusOnMap, this);
  10053. return link;
  10054. },
  10055. _updateDisabled: function () {
  10056. var map = this._map,
  10057. className = 'leaflet-disabled';
  10058. L.DomUtil.removeClass(this._zoomInButton, className);
  10059. L.DomUtil.removeClass(this._zoomOutButton, className);
  10060. if (this._disabled || map._zoom === map.getMinZoom()) {
  10061. L.DomUtil.addClass(this._zoomOutButton, className);
  10062. }
  10063. if (this._disabled || map._zoom === map.getMaxZoom()) {
  10064. L.DomUtil.addClass(this._zoomInButton, className);
  10065. }
  10066. }
  10067. });
  10068. // @namespace Map
  10069. // @section Control options
  10070. // @option zoomControl: Boolean = true
  10071. // Whether a [zoom control](#control-zoom) is added to the map by default.
  10072. L.Map.mergeOptions({
  10073. zoomControl: true
  10074. });
  10075. L.Map.addInitHook(function () {
  10076. if (this.options.zoomControl) {
  10077. this.zoomControl = new L.Control.Zoom();
  10078. this.addControl(this.zoomControl);
  10079. }
  10080. });
  10081. // @namespace Control.Zoom
  10082. // @factory L.control.zoom(options: Control.Zoom options)
  10083. // Creates a zoom control
  10084. L.control.zoom = function (options) {
  10085. return new L.Control.Zoom(options);
  10086. };
  10087. /*
  10088. * @class Control.Attribution
  10089. * @aka L.Control.Attribution
  10090. * @inherits Control
  10091. *
  10092. * The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its [`attributionControl` option](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control.
  10093. */
  10094. L.Control.Attribution = L.Control.extend({
  10095. // @section
  10096. // @aka Control.Attribution options
  10097. options: {
  10098. position: 'bottomright',
  10099. // @option prefix: String = 'Leaflet'
  10100. // The HTML text shown before the attributions. Pass `false` to disable.
  10101. prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  10102. },
  10103. initialize: function (options) {
  10104. L.setOptions(this, options);
  10105. this._attributions = {};
  10106. },
  10107. onAdd: function (map) {
  10108. map.attributionControl = this;
  10109. this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
  10110. if (L.DomEvent) {
  10111. L.DomEvent.disableClickPropagation(this._container);
  10112. }
  10113. // TODO ugly, refactor
  10114. for (var i in map._layers) {
  10115. if (map._layers[i].getAttribution) {
  10116. this.addAttribution(map._layers[i].getAttribution());
  10117. }
  10118. }
  10119. this._update();
  10120. return this._container;
  10121. },
  10122. // @method setPrefix(prefix: String): this
  10123. // Sets the text before the attributions.
  10124. setPrefix: function (prefix) {
  10125. this.options.prefix = prefix;
  10126. this._update();
  10127. return this;
  10128. },
  10129. // @method addAttribution(text: String): this
  10130. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  10131. addAttribution: function (text) {
  10132. if (!text) { return this; }
  10133. if (!this._attributions[text]) {
  10134. this._attributions[text] = 0;
  10135. }
  10136. this._attributions[text]++;
  10137. this._update();
  10138. return this;
  10139. },
  10140. // @method removeAttribution(text: String): this
  10141. // Removes an attribution text.
  10142. removeAttribution: function (text) {
  10143. if (!text) { return this; }
  10144. if (this._attributions[text]) {
  10145. this._attributions[text]--;
  10146. this._update();
  10147. }
  10148. return this;
  10149. },
  10150. _update: function () {
  10151. if (!this._map) { return; }
  10152. var attribs = [];
  10153. for (var i in this._attributions) {
  10154. if (this._attributions[i]) {
  10155. attribs.push(i);
  10156. }
  10157. }
  10158. var prefixAndAttribs = [];
  10159. if (this.options.prefix) {
  10160. prefixAndAttribs.push(this.options.prefix);
  10161. }
  10162. if (attribs.length) {
  10163. prefixAndAttribs.push(attribs.join(', '));
  10164. }
  10165. this._container.innerHTML = prefixAndAttribs.join(' | ');
  10166. }
  10167. });
  10168. // @namespace Map
  10169. // @section Control options
  10170. // @option attributionControl: Boolean = true
  10171. // Whether a [attribution control](#control-attribution) is added to the map by default.
  10172. L.Map.mergeOptions({
  10173. attributionControl: true
  10174. });
  10175. L.Map.addInitHook(function () {
  10176. if (this.options.attributionControl) {
  10177. new L.Control.Attribution().addTo(this);
  10178. }
  10179. });
  10180. // @namespace Control.Attribution
  10181. // @factory L.control.attribution(options: Control.Attribution options)
  10182. // Creates an attribution control.
  10183. L.control.attribution = function (options) {
  10184. return new L.Control.Attribution(options);
  10185. };
  10186. /*
  10187. * @class Control.Scale
  10188. * @aka L.Control.Scale
  10189. * @inherits Control
  10190. *
  10191. * A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends `Control`.
  10192. *
  10193. * @example
  10194. *
  10195. * ```js
  10196. * L.control.scale().addTo(map);
  10197. * ```
  10198. */
  10199. L.Control.Scale = L.Control.extend({
  10200. // @section
  10201. // @aka Control.Scale options
  10202. options: {
  10203. position: 'bottomleft',
  10204. // @option maxWidth: Number = 100
  10205. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  10206. maxWidth: 100,
  10207. // @option metric: Boolean = True
  10208. // Whether to show the metric scale line (m/km).
  10209. metric: true,
  10210. // @option imperial: Boolean = True
  10211. // Whether to show the imperial scale line (mi/ft).
  10212. imperial: true
  10213. // @option updateWhenIdle: Boolean = false
  10214. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  10215. },
  10216. onAdd: function (map) {
  10217. var className = 'leaflet-control-scale',
  10218. container = L.DomUtil.create('div', className),
  10219. options = this.options;
  10220. this._addScales(options, className + '-line', container);
  10221. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  10222. map.whenReady(this._update, this);
  10223. return container;
  10224. },
  10225. onRemove: function (map) {
  10226. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  10227. },
  10228. _addScales: function (options, className, container) {
  10229. if (options.metric) {
  10230. this._mScale = L.DomUtil.create('div', className, container);
  10231. }
  10232. if (options.imperial) {
  10233. this._iScale = L.DomUtil.create('div', className, container);
  10234. }
  10235. },
  10236. _update: function () {
  10237. var map = this._map,
  10238. y = map.getSize().y / 2;
  10239. var maxMeters = map.distance(
  10240. map.containerPointToLatLng([0, y]),
  10241. map.containerPointToLatLng([this.options.maxWidth, y]));
  10242. this._updateScales(maxMeters);
  10243. },
  10244. _updateScales: function (maxMeters) {
  10245. if (this.options.metric && maxMeters) {
  10246. this._updateMetric(maxMeters);
  10247. }
  10248. if (this.options.imperial && maxMeters) {
  10249. this._updateImperial(maxMeters);
  10250. }
  10251. },
  10252. _updateMetric: function (maxMeters) {
  10253. var meters = this._getRoundNum(maxMeters),
  10254. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  10255. this._updateScale(this._mScale, label, meters / maxMeters);
  10256. },
  10257. _updateImperial: function (maxMeters) {
  10258. var maxFeet = maxMeters * 3.2808399,
  10259. maxMiles, miles, feet;
  10260. if (maxFeet > 5280) {
  10261. maxMiles = maxFeet / 5280;
  10262. miles = this._getRoundNum(maxMiles);
  10263. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  10264. } else {
  10265. feet = this._getRoundNum(maxFeet);
  10266. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  10267. }
  10268. },
  10269. _updateScale: function (scale, text, ratio) {
  10270. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  10271. scale.innerHTML = text;
  10272. },
  10273. _getRoundNum: function (num) {
  10274. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  10275. d = num / pow10;
  10276. d = d >= 10 ? 10 :
  10277. d >= 5 ? 5 :
  10278. d >= 3 ? 3 :
  10279. d >= 2 ? 2 : 1;
  10280. return pow10 * d;
  10281. }
  10282. });
  10283. // @factory L.control.scale(options?: Control.Scale options)
  10284. // Creates an scale control with the given options.
  10285. L.control.scale = function (options) {
  10286. return new L.Control.Scale(options);
  10287. };
  10288. /*
  10289. * @class Control.Layers
  10290. * @aka L.Control.Layers
  10291. * @inherits Control
  10292. *
  10293. * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control.html)). Extends `Control`.
  10294. *
  10295. * @example
  10296. *
  10297. * ```js
  10298. * var baseLayers = {
  10299. * "Mapbox": mapbox,
  10300. * "OpenStreetMap": osm
  10301. * };
  10302. *
  10303. * var overlays = {
  10304. * "Marker": marker,
  10305. * "Roads": roadsLayer
  10306. * };
  10307. *
  10308. * L.control.layers(baseLayers, overlays).addTo(map);
  10309. * ```
  10310. *
  10311. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  10312. *
  10313. * ```js
  10314. * {
  10315. * "<someName1>": layer1,
  10316. * "<someName2>": layer2
  10317. * }
  10318. * ```
  10319. *
  10320. * The layer names can contain HTML, which allows you to add additional styling to the items:
  10321. *
  10322. * ```js
  10323. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  10324. * ```
  10325. */
  10326. L.Control.Layers = L.Control.extend({
  10327. // @section
  10328. // @aka Control.Layers options
  10329. options: {
  10330. // @option collapsed: Boolean = true
  10331. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  10332. collapsed: true,
  10333. position: 'topright',
  10334. // @option autoZIndex: Boolean = true
  10335. // If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.
  10336. autoZIndex: true,
  10337. // @option hideSingleBase: Boolean = false
  10338. // If `true`, the base layers in the control will be hidden when there is only one.
  10339. hideSingleBase: false,
  10340. // @option sortLayers: Boolean = false
  10341. // Whether to sort the layers. When `false`, layers will keep the order
  10342. // in which they were added to the control.
  10343. sortLayers: false,
  10344. // @option sortFunction: Function = *
  10345. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  10346. // that will be used for sorting the layers, when `sortLayers` is `true`.
  10347. // The function receives both the `L.Layer` instances and their names, as in
  10348. // `sortFunction(layerA, layerB, nameA, nameB)`.
  10349. // By default, it sorts layers alphabetically by their name.
  10350. sortFunction: function (layerA, layerB, nameA, nameB) {
  10351. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  10352. }
  10353. },
  10354. initialize: function (baseLayers, overlays, options) {
  10355. L.setOptions(this, options);
  10356. this._layers = [];
  10357. this._lastZIndex = 0;
  10358. this._handlingClick = false;
  10359. for (var i in baseLayers) {
  10360. this._addLayer(baseLayers[i], i);
  10361. }
  10362. for (i in overlays) {
  10363. this._addLayer(overlays[i], i, true);
  10364. }
  10365. },
  10366. onAdd: function (map) {
  10367. this._initLayout();
  10368. this._update();
  10369. this._map = map;
  10370. map.on('zoomend', this._checkDisabledLayers, this);
  10371. return this._container;
  10372. },
  10373. onRemove: function () {
  10374. this._map.off('zoomend', this._checkDisabledLayers, this);
  10375. for (var i = 0; i < this._layers.length; i++) {
  10376. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  10377. }
  10378. },
  10379. // @method addBaseLayer(layer: Layer, name: String): this
  10380. // Adds a base layer (radio button entry) with the given name to the control.
  10381. addBaseLayer: function (layer, name) {
  10382. this._addLayer(layer, name);
  10383. return (this._map) ? this._update() : this;
  10384. },
  10385. // @method addOverlay(layer: Layer, name: String): this
  10386. // Adds an overlay (checkbox entry) with the given name to the control.
  10387. addOverlay: function (layer, name) {
  10388. this._addLayer(layer, name, true);
  10389. return (this._map) ? this._update() : this;
  10390. },
  10391. // @method removeLayer(layer: Layer): this
  10392. // Remove the given layer from the control.
  10393. removeLayer: function (layer) {
  10394. layer.off('add remove', this._onLayerChange, this);
  10395. var obj = this._getLayer(L.stamp(layer));
  10396. if (obj) {
  10397. this._layers.splice(this._layers.indexOf(obj), 1);
  10398. }
  10399. return (this._map) ? this._update() : this;
  10400. },
  10401. // @method expand(): this
  10402. // Expand the control container if collapsed.
  10403. expand: function () {
  10404. L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
  10405. this._form.style.height = null;
  10406. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  10407. if (acceptableHeight < this._form.clientHeight) {
  10408. L.DomUtil.addClass(this._form, 'leaflet-control-layers-scrollbar');
  10409. this._form.style.height = acceptableHeight + 'px';
  10410. } else {
  10411. L.DomUtil.removeClass(this._form, 'leaflet-control-layers-scrollbar');
  10412. }
  10413. this._checkDisabledLayers();
  10414. return this;
  10415. },
  10416. // @method collapse(): this
  10417. // Collapse the control container if expanded.
  10418. collapse: function () {
  10419. L.DomUtil.removeClass(this._container, 'leaflet-control-layers-expanded');
  10420. return this;
  10421. },
  10422. _initLayout: function () {
  10423. var className = 'leaflet-control-layers',
  10424. container = this._container = L.DomUtil.create('div', className),
  10425. collapsed = this.options.collapsed;
  10426. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  10427. container.setAttribute('aria-haspopup', true);
  10428. L.DomEvent.disableClickPropagation(container);
  10429. if (!L.Browser.touch) {
  10430. L.DomEvent.disableScrollPropagation(container);
  10431. }
  10432. var form = this._form = L.DomUtil.create('form', className + '-list');
  10433. if (collapsed) {
  10434. this._map.on('click', this.collapse, this);
  10435. if (!L.Browser.android) {
  10436. L.DomEvent.on(container, {
  10437. mouseenter: this.expand,
  10438. mouseleave: this.collapse
  10439. }, this);
  10440. }
  10441. }
  10442. var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
  10443. link.href = '#';
  10444. link.title = 'Layers';
  10445. if (L.Browser.touch) {
  10446. L.DomEvent
  10447. .on(link, 'click', L.DomEvent.stop)
  10448. .on(link, 'click', this.expand, this);
  10449. } else {
  10450. L.DomEvent.on(link, 'focus', this.expand, this);
  10451. }
  10452. // work around for Firefox Android issue https://github.com/Leaflet/Leaflet/issues/2033
  10453. L.DomEvent.on(form, 'click', function () {
  10454. setTimeout(L.bind(this._onInputClick, this), 0);
  10455. }, this);
  10456. // TODO keyboard accessibility
  10457. if (!collapsed) {
  10458. this.expand();
  10459. }
  10460. this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
  10461. this._separator = L.DomUtil.create('div', className + '-separator', form);
  10462. this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
  10463. container.appendChild(form);
  10464. },
  10465. _getLayer: function (id) {
  10466. for (var i = 0; i < this._layers.length; i++) {
  10467. if (this._layers[i] && L.stamp(this._layers[i].layer) === id) {
  10468. return this._layers[i];
  10469. }
  10470. }
  10471. },
  10472. _addLayer: function (layer, name, overlay) {
  10473. layer.on('add remove', this._onLayerChange, this);
  10474. this._layers.push({
  10475. layer: layer,
  10476. name: name,
  10477. overlay: overlay
  10478. });
  10479. if (this.options.sortLayers) {
  10480. this._layers.sort(L.bind(function (a, b) {
  10481. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  10482. }, this));
  10483. }
  10484. if (this.options.autoZIndex && layer.setZIndex) {
  10485. this._lastZIndex++;
  10486. layer.setZIndex(this._lastZIndex);
  10487. }
  10488. },
  10489. _update: function () {
  10490. if (!this._container) { return this; }
  10491. L.DomUtil.empty(this._baseLayersList);
  10492. L.DomUtil.empty(this._overlaysList);
  10493. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  10494. for (i = 0; i < this._layers.length; i++) {
  10495. obj = this._layers[i];
  10496. this._addItem(obj);
  10497. overlaysPresent = overlaysPresent || obj.overlay;
  10498. baseLayersPresent = baseLayersPresent || !obj.overlay;
  10499. baseLayersCount += !obj.overlay ? 1 : 0;
  10500. }
  10501. // Hide base layers section if there's only one layer.
  10502. if (this.options.hideSingleBase) {
  10503. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  10504. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  10505. }
  10506. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  10507. return this;
  10508. },
  10509. _onLayerChange: function (e) {
  10510. if (!this._handlingClick) {
  10511. this._update();
  10512. }
  10513. var obj = this._getLayer(L.stamp(e.target));
  10514. // @namespace Map
  10515. // @section Layer events
  10516. // @event baselayerchange: LayersControlEvent
  10517. // Fired when the base layer is changed through the [layer control](#control-layers).
  10518. // @event overlayadd: LayersControlEvent
  10519. // Fired when an overlay is selected through the [layer control](#control-layers).
  10520. // @event overlayremove: LayersControlEvent
  10521. // Fired when an overlay is deselected through the [layer control](#control-layers).
  10522. // @namespace Control.Layers
  10523. var type = obj.overlay ?
  10524. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  10525. (e.type === 'add' ? 'baselayerchange' : null);
  10526. if (type) {
  10527. this._map.fire(type, obj);
  10528. }
  10529. },
  10530. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  10531. _createRadioElement: function (name, checked) {
  10532. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  10533. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  10534. var radioFragment = document.createElement('div');
  10535. radioFragment.innerHTML = radioHtml;
  10536. return radioFragment.firstChild;
  10537. },
  10538. _addItem: function (obj) {
  10539. var label = document.createElement('label'),
  10540. checked = this._map.hasLayer(obj.layer),
  10541. input;
  10542. if (obj.overlay) {
  10543. input = document.createElement('input');
  10544. input.type = 'checkbox';
  10545. input.className = 'leaflet-control-layers-selector';
  10546. input.defaultChecked = checked;
  10547. } else {
  10548. input = this._createRadioElement('leaflet-base-layers', checked);
  10549. }
  10550. input.layerId = L.stamp(obj.layer);
  10551. L.DomEvent.on(input, 'click', this._onInputClick, this);
  10552. var name = document.createElement('span');
  10553. name.innerHTML = ' ' + obj.name;
  10554. // Helps from preventing layer control flicker when checkboxes are disabled
  10555. // https://github.com/Leaflet/Leaflet/issues/2771
  10556. var holder = document.createElement('div');
  10557. label.appendChild(holder);
  10558. holder.appendChild(input);
  10559. holder.appendChild(name);
  10560. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  10561. container.appendChild(label);
  10562. this._checkDisabledLayers();
  10563. return label;
  10564. },
  10565. _onInputClick: function () {
  10566. var inputs = this._form.getElementsByTagName('input'),
  10567. input, layer, hasLayer;
  10568. var addedLayers = [],
  10569. removedLayers = [];
  10570. this._handlingClick = true;
  10571. for (var i = inputs.length - 1; i >= 0; i--) {
  10572. input = inputs[i];
  10573. layer = this._getLayer(input.layerId).layer;
  10574. hasLayer = this._map.hasLayer(layer);
  10575. if (input.checked && !hasLayer) {
  10576. addedLayers.push(layer);
  10577. } else if (!input.checked && hasLayer) {
  10578. removedLayers.push(layer);
  10579. }
  10580. }
  10581. // Bugfix issue 2318: Should remove all old layers before readding new ones
  10582. for (i = 0; i < removedLayers.length; i++) {
  10583. this._map.removeLayer(removedLayers[i]);
  10584. }
  10585. for (i = 0; i < addedLayers.length; i++) {
  10586. this._map.addLayer(addedLayers[i]);
  10587. }
  10588. this._handlingClick = false;
  10589. this._refocusOnMap();
  10590. },
  10591. _checkDisabledLayers: function () {
  10592. var inputs = this._form.getElementsByTagName('input'),
  10593. input,
  10594. layer,
  10595. zoom = this._map.getZoom();
  10596. for (var i = inputs.length - 1; i >= 0; i--) {
  10597. input = inputs[i];
  10598. layer = this._getLayer(input.layerId).layer;
  10599. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  10600. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  10601. }
  10602. },
  10603. _expand: function () {
  10604. // Backward compatibility, remove me in 1.1.
  10605. return this.expand();
  10606. },
  10607. _collapse: function () {
  10608. // Backward compatibility, remove me in 1.1.
  10609. return this.collapse();
  10610. }
  10611. });
  10612. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  10613. // Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
  10614. L.control.layers = function (baseLayers, overlays, options) {
  10615. return new L.Control.Layers(baseLayers, overlays, options);
  10616. };
  10617. }(window, document));
  10618. //# sourceMappingURL=leaflet-src.map