Le repo des sources pour le site web des JM2L
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

13610 lines
381 KiB

  1. /* @preserve
  2. * Leaflet 1.2.0+Detached: 1ac320ba232cb85b73ac81f3d82780c9d07f0d4e.1ac320b, a JS library for interactive maps. http://leafletjs.com
  3. * (c) 2010-2017 Vladimir Agafonkin, (c) 2010-2011 CloudMade
  4. */
  5. (function (global, factory) {
  6. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  7. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  8. (factory((global.L = {})));
  9. }(this, (function (exports) { 'use strict';
  10. var version = "1.2.0+HEAD.1ac320b";
  11. /*
  12. * @namespace Util
  13. *
  14. * Various utility functions, used by Leaflet internally.
  15. */
  16. var freeze = Object.freeze;
  17. Object.freeze = function (obj) { return obj; };
  18. // @function extend(dest: Object, src?: Object): Object
  19. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  20. function extend(dest) {
  21. var i, j, len, src;
  22. for (j = 1, len = arguments.length; j < len; j++) {
  23. src = arguments[j];
  24. for (i in src) {
  25. dest[i] = src[i];
  26. }
  27. }
  28. return dest;
  29. }
  30. // @function create(proto: Object, properties?: Object): Object
  31. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  32. var create = Object.create || (function () {
  33. function F() {}
  34. return function (proto) {
  35. F.prototype = proto;
  36. return new F();
  37. };
  38. })();
  39. // @function bind(fn: Function, …): Function
  40. // 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).
  41. // Has a `L.bind()` shortcut.
  42. function bind(fn, obj) {
  43. var slice = Array.prototype.slice;
  44. if (fn.bind) {
  45. return fn.bind.apply(fn, slice.call(arguments, 1));
  46. }
  47. var args = slice.call(arguments, 2);
  48. return function () {
  49. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  50. };
  51. }
  52. // @property lastId: Number
  53. // Last unique ID used by [`stamp()`](#util-stamp)
  54. var lastId = 0;
  55. // @function stamp(obj: Object): Number
  56. // Returns the unique ID of an object, assiging it one if it doesn't have it.
  57. function stamp(obj) {
  58. /*eslint-disable */
  59. obj._leaflet_id = obj._leaflet_id || ++lastId;
  60. return obj._leaflet_id;
  61. /*eslint-enable */
  62. }
  63. // @function throttle(fn: Function, time: Number, context: Object): Function
  64. // Returns a function which executes function `fn` with the given scope `context`
  65. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  66. // `fn` will be called no more than one time per given amount of `time`. The arguments
  67. // received by the bound function will be any arguments passed when binding the
  68. // function, followed by any arguments passed when invoking the bound function.
  69. // Has an `L.throttle` shortcut.
  70. function throttle(fn, time, context) {
  71. var lock, args, wrapperFn, later;
  72. later = function () {
  73. // reset lock and call if queued
  74. lock = false;
  75. if (args) {
  76. wrapperFn.apply(context, args);
  77. args = false;
  78. }
  79. };
  80. wrapperFn = function () {
  81. if (lock) {
  82. // called too soon, queue to call later
  83. args = arguments;
  84. } else {
  85. // call and lock until later
  86. fn.apply(context, arguments);
  87. setTimeout(later, time);
  88. lock = true;
  89. }
  90. };
  91. return wrapperFn;
  92. }
  93. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  94. // Returns the number `num` modulo `range` in such a way so it lies within
  95. // `range[0]` and `range[1]`. The returned value will be always smaller than
  96. // `range[1]` unless `includeMax` is set to `true`.
  97. function wrapNum(x, range, includeMax) {
  98. var max = range[1],
  99. min = range[0],
  100. d = max - min;
  101. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  102. }
  103. // @function falseFn(): Function
  104. // Returns a function which always returns `false`.
  105. function falseFn() { return false; }
  106. // @function formatNum(num: Number, digits?: Number): Number
  107. // Returns the number `num` rounded to `digits` decimals, or to 5 decimals by default.
  108. function formatNum(num, digits) {
  109. var pow = Math.pow(10, digits || 5);
  110. return Math.round(num * pow) / pow;
  111. }
  112. // @function trim(str: String): String
  113. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  114. function trim(str) {
  115. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  116. }
  117. // @function splitWords(str: String): String[]
  118. // Trims and splits the string on whitespace and returns the array of parts.
  119. function splitWords(str) {
  120. return trim(str).split(/\s+/);
  121. }
  122. // @function setOptions(obj: Object, options: Object): Object
  123. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  124. function setOptions(obj, options) {
  125. if (!obj.hasOwnProperty('options')) {
  126. obj.options = obj.options ? create(obj.options) : {};
  127. }
  128. for (var i in options) {
  129. obj.options[i] = options[i];
  130. }
  131. return obj.options;
  132. }
  133. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  134. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  135. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  136. // be appended at the end. If `uppercase` is `true`, the parameter names will
  137. // be uppercased (e.g. `'?A=foo&B=bar'`)
  138. function getParamString(obj, existingUrl, uppercase) {
  139. var params = [];
  140. for (var i in obj) {
  141. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  142. }
  143. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  144. }
  145. var templateRe = /\{ *([\w_\-]+) *\}/g;
  146. // @function template(str: String, data: Object): String
  147. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  148. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  149. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  150. // data values — they will be evaluated passing `data` as an argument.
  151. function template(str, data) {
  152. return str.replace(templateRe, function (str, key) {
  153. var value = data[key];
  154. if (value === undefined) {
  155. throw new Error('No value provided for variable ' + str);
  156. } else if (typeof value === 'function') {
  157. value = value(data);
  158. }
  159. return value;
  160. });
  161. }
  162. // @function isArray(obj): Boolean
  163. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  164. var isArray = Array.isArray || function (obj) {
  165. return (Object.prototype.toString.call(obj) === '[object Array]');
  166. };
  167. // @function indexOf(array: Array, el: Object): Number
  168. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  169. function indexOf(array, el) {
  170. for (var i = 0; i < array.length; i++) {
  171. if (array[i] === el) { return i; }
  172. }
  173. return -1;
  174. }
  175. // @property emptyImageUrl: String
  176. // Data URI string containing a base64-encoded empty GIF image.
  177. // Used as a hack to free memory from unused images on WebKit-powered
  178. // mobile devices (by setting image `src` to this string).
  179. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  180. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  181. function getPrefixed(name) {
  182. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  183. }
  184. var lastTime = 0;
  185. // fallback for IE 7-8
  186. function timeoutDefer(fn) {
  187. var time = +new Date(),
  188. timeToCall = Math.max(0, 16 - (time - lastTime));
  189. lastTime = time + timeToCall;
  190. return window.setTimeout(fn, timeToCall);
  191. }
  192. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  193. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  194. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  195. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  196. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  197. // `context` if given. When `immediate` is set, `fn` is called immediately if
  198. // the browser doesn't have native support for
  199. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  200. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  201. function requestAnimFrame(fn, context, immediate) {
  202. if (immediate && requestFn === timeoutDefer) {
  203. fn.call(context);
  204. } else {
  205. return requestFn.call(window, bind(fn, context));
  206. }
  207. }
  208. // @function cancelAnimFrame(id: Number): undefined
  209. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  210. function cancelAnimFrame(id) {
  211. if (id) {
  212. cancelFn.call(window, id);
  213. }
  214. }
  215. var Util = (Object.freeze || Object)({
  216. freeze: freeze,
  217. extend: extend,
  218. create: create,
  219. bind: bind,
  220. lastId: lastId,
  221. stamp: stamp,
  222. throttle: throttle,
  223. wrapNum: wrapNum,
  224. falseFn: falseFn,
  225. formatNum: formatNum,
  226. trim: trim,
  227. splitWords: splitWords,
  228. setOptions: setOptions,
  229. getParamString: getParamString,
  230. template: template,
  231. isArray: isArray,
  232. indexOf: indexOf,
  233. emptyImageUrl: emptyImageUrl,
  234. requestFn: requestFn,
  235. cancelFn: cancelFn,
  236. requestAnimFrame: requestAnimFrame,
  237. cancelAnimFrame: cancelAnimFrame
  238. });
  239. // @class Class
  240. // @aka L.Class
  241. // @section
  242. // @uninheritable
  243. // Thanks to John Resig and Dean Edwards for inspiration!
  244. function Class() {}
  245. 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 = 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' && i !== '__super__') {
  264. NewClass[i] = this[i];
  265. }
  266. }
  267. // mix static properties into the class
  268. if (props.statics) {
  269. extend(NewClass, props.statics);
  270. delete props.statics;
  271. }
  272. // mix includes into the prototype
  273. if (props.includes) {
  274. checkDeprecatedMixinEvents(props.includes);
  275. extend.apply(null, [proto].concat(props.includes));
  276. delete props.includes;
  277. }
  278. // merge options
  279. if (proto.options) {
  280. props.options = extend(create(proto.options), props.options);
  281. }
  282. // mix given properties into the prototype
  283. extend(proto, props);
  284. proto._initHooks = [];
  285. // add method for calling all hooks
  286. proto.callInitHooks = function () {
  287. if (this._initHooksCalled) { return; }
  288. if (parentProto.callInitHooks) {
  289. parentProto.callInitHooks.call(this);
  290. }
  291. this._initHooksCalled = true;
  292. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  293. proto._initHooks[i].call(this);
  294. }
  295. };
  296. return NewClass;
  297. };
  298. // @function include(properties: Object): this
  299. // [Includes a mixin](#class-includes) into the current class.
  300. Class.include = function (props) {
  301. extend(this.prototype, props);
  302. return this;
  303. };
  304. // @function mergeOptions(options: Object): this
  305. // [Merges `options`](#class-options) into the defaults of the class.
  306. Class.mergeOptions = function (options) {
  307. extend(this.prototype.options, options);
  308. return this;
  309. };
  310. // @function addInitHook(fn: Function): this
  311. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  312. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  313. var args = Array.prototype.slice.call(arguments, 1);
  314. var init = typeof fn === 'function' ? fn : function () {
  315. this[fn].apply(this, args);
  316. };
  317. this.prototype._initHooks = this.prototype._initHooks || [];
  318. this.prototype._initHooks.push(init);
  319. return this;
  320. };
  321. function checkDeprecatedMixinEvents(includes) {
  322. if (!L || !L.Mixin) { return; }
  323. includes = isArray(includes) ? includes : [includes];
  324. for (var i = 0; i < includes.length; i++) {
  325. if (includes[i] === L.Mixin.Events) {
  326. console.warn('Deprecated include of L.Mixin.Events: ' +
  327. 'this property will be removed in future releases, ' +
  328. 'please inherit from L.Evented instead.', new Error().stack);
  329. }
  330. }
  331. }
  332. /*
  333. * @class Evented
  334. * @aka L.Evented
  335. * @inherits Class
  336. *
  337. * 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).
  338. *
  339. * @example
  340. *
  341. * ```js
  342. * map.on('click', function(e) {
  343. * alert(e.latlng);
  344. * } );
  345. * ```
  346. *
  347. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  348. *
  349. * ```js
  350. * function onClick(e) { ... }
  351. *
  352. * map.on('click', onClick);
  353. * map.off('click', onClick);
  354. * ```
  355. */
  356. var Events = {
  357. /* @method on(type: String, fn: Function, context?: Object): this
  358. * 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'`).
  359. *
  360. * @alternative
  361. * @method on(eventMap: Object): this
  362. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  363. */
  364. on: function (types, fn, context) {
  365. // types can be a map of types/handlers
  366. if (typeof types === 'object') {
  367. for (var type in types) {
  368. // we don't process space-separated events here for performance;
  369. // it's a hot path since Layer uses the on(obj) syntax
  370. this._on(type, types[type], fn);
  371. }
  372. } else {
  373. // types can be a string of space-separated words
  374. types = splitWords(types);
  375. for (var i = 0, len = types.length; i < len; i++) {
  376. this._on(types[i], fn, context);
  377. }
  378. }
  379. return this;
  380. },
  381. /* @method off(type: String, fn?: Function, context?: Object): this
  382. * 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.
  383. *
  384. * @alternative
  385. * @method off(eventMap: Object): this
  386. * Removes a set of type/listener pairs.
  387. *
  388. * @alternative
  389. * @method off: this
  390. * Removes all listeners to all events on the object.
  391. */
  392. off: function (types, fn, context) {
  393. if (!types) {
  394. // clear all listeners if called without arguments
  395. delete this._events;
  396. } else if (typeof types === 'object') {
  397. for (var type in types) {
  398. this._off(type, types[type], fn);
  399. }
  400. } else {
  401. types = splitWords(types);
  402. for (var i = 0, len = types.length; i < len; i++) {
  403. this._off(types[i], fn, context);
  404. }
  405. }
  406. return this;
  407. },
  408. // attach listener (without syntactic sugar now)
  409. _on: function (type, fn, context) {
  410. this._events = this._events || {};
  411. /* get/init listeners for type */
  412. var typeListeners = this._events[type];
  413. if (!typeListeners) {
  414. typeListeners = [];
  415. this._events[type] = typeListeners;
  416. }
  417. if (context === this) {
  418. // Less memory footprint.
  419. context = undefined;
  420. }
  421. var newListener = {fn: fn, ctx: context},
  422. listeners = typeListeners;
  423. // check if fn already there
  424. for (var i = 0, len = listeners.length; i < len; i++) {
  425. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  426. return;
  427. }
  428. }
  429. listeners.push(newListener);
  430. },
  431. _off: function (type, fn, context) {
  432. var listeners,
  433. i,
  434. len;
  435. if (!this._events) { return; }
  436. listeners = this._events[type];
  437. if (!listeners) {
  438. return;
  439. }
  440. if (!fn) {
  441. // Set all removed listeners to noop so they are not called if remove happens in fire
  442. for (i = 0, len = listeners.length; i < len; i++) {
  443. listeners[i].fn = falseFn;
  444. }
  445. // clear all listeners for a type if function isn't specified
  446. delete this._events[type];
  447. return;
  448. }
  449. if (context === this) {
  450. context = undefined;
  451. }
  452. if (listeners) {
  453. // find fn and remove it
  454. for (i = 0, len = listeners.length; i < len; i++) {
  455. var l = listeners[i];
  456. if (l.ctx !== context) { continue; }
  457. if (l.fn === fn) {
  458. // set the removed listener to noop so that's not called if remove happens in fire
  459. l.fn = falseFn;
  460. if (this._firingCount) {
  461. /* copy array in case events are being fired */
  462. this._events[type] = listeners = listeners.slice();
  463. }
  464. listeners.splice(i, 1);
  465. return;
  466. }
  467. }
  468. }
  469. },
  470. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  471. // Fires an event of the specified type. You can optionally provide an data
  472. // object — the first argument of the listener function will contain its
  473. // properties. The event can optionally be propagated to event parents.
  474. fire: function (type, data, propagate) {
  475. if (!this.listens(type, propagate)) { return this; }
  476. var event = extend({}, data, {type: type, target: this});
  477. if (this._events) {
  478. var listeners = this._events[type];
  479. if (listeners) {
  480. this._firingCount = (this._firingCount + 1) || 1;
  481. for (var i = 0, len = listeners.length; i < len; i++) {
  482. var l = listeners[i];
  483. l.fn.call(l.ctx || this, event);
  484. }
  485. this._firingCount--;
  486. }
  487. }
  488. if (propagate) {
  489. // propagate the event to parents (set with addEventParent)
  490. this._propagateEvent(event);
  491. }
  492. return this;
  493. },
  494. // @method listens(type: String): Boolean
  495. // Returns `true` if a particular event type has any listeners attached to it.
  496. listens: function (type, propagate) {
  497. var listeners = this._events && this._events[type];
  498. if (listeners && listeners.length) { return true; }
  499. if (propagate) {
  500. // also check parents for listeners if event propagates
  501. for (var id in this._eventParents) {
  502. if (this._eventParents[id].listens(type, propagate)) { return true; }
  503. }
  504. }
  505. return false;
  506. },
  507. // @method once(…): this
  508. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  509. once: function (types, fn, context) {
  510. if (typeof types === 'object') {
  511. for (var type in types) {
  512. this.once(type, types[type], fn);
  513. }
  514. return this;
  515. }
  516. var handler = bind(function () {
  517. this
  518. .off(types, fn, context)
  519. .off(types, handler, context);
  520. }, this);
  521. // add a listener that's executed once and removed after that
  522. return this
  523. .on(types, fn, context)
  524. .on(types, handler, context);
  525. },
  526. // @method addEventParent(obj: Evented): this
  527. // Adds an event parent - an `Evented` that will receive propagated events
  528. addEventParent: function (obj) {
  529. this._eventParents = this._eventParents || {};
  530. this._eventParents[stamp(obj)] = obj;
  531. return this;
  532. },
  533. // @method removeEventParent(obj: Evented): this
  534. // Removes an event parent, so it will stop receiving propagated events
  535. removeEventParent: function (obj) {
  536. if (this._eventParents) {
  537. delete this._eventParents[stamp(obj)];
  538. }
  539. return this;
  540. },
  541. _propagateEvent: function (e) {
  542. for (var id in this._eventParents) {
  543. this._eventParents[id].fire(e.type, extend({layer: e.target}, e), true);
  544. }
  545. }
  546. };
  547. // aliases; we should ditch those eventually
  548. // @method addEventListener(…): this
  549. // Alias to [`on(…)`](#evented-on)
  550. Events.addEventListener = Events.on;
  551. // @method removeEventListener(…): this
  552. // Alias to [`off(…)`](#evented-off)
  553. // @method clearAllEventListeners(…): this
  554. // Alias to [`off()`](#evented-off)
  555. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  556. // @method addOneTimeEventListener(…): this
  557. // Alias to [`once(…)`](#evented-once)
  558. Events.addOneTimeEventListener = Events.once;
  559. // @method fireEvent(…): this
  560. // Alias to [`fire(…)`](#evented-fire)
  561. Events.fireEvent = Events.fire;
  562. // @method hasEventListeners(…): Boolean
  563. // Alias to [`listens(…)`](#evented-listens)
  564. Events.hasEventListeners = Events.listens;
  565. var Evented = Class.extend(Events);
  566. /*
  567. * @class Point
  568. * @aka L.Point
  569. *
  570. * Represents a point with `x` and `y` coordinates in pixels.
  571. *
  572. * @example
  573. *
  574. * ```js
  575. * var point = L.point(200, 300);
  576. * ```
  577. *
  578. * 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:
  579. *
  580. * ```js
  581. * map.panBy([200, 300]);
  582. * map.panBy(L.point(200, 300));
  583. * ```
  584. */
  585. function Point(x, y, round) {
  586. // @property x: Number; The `x` coordinate of the point
  587. this.x = (round ? Math.round(x) : x);
  588. // @property y: Number; The `y` coordinate of the point
  589. this.y = (round ? Math.round(y) : y);
  590. }
  591. Point.prototype = {
  592. // @method clone(): Point
  593. // Returns a copy of the current point.
  594. clone: function () {
  595. return new Point(this.x, this.y);
  596. },
  597. // @method add(otherPoint: Point): Point
  598. // Returns the result of addition of the current and the given points.
  599. add: function (point) {
  600. // non-destructive, returns a new point
  601. return this.clone()._add(toPoint(point));
  602. },
  603. _add: function (point) {
  604. // destructive, used directly for performance in situations where it's safe to modify existing point
  605. this.x += point.x;
  606. this.y += point.y;
  607. return this;
  608. },
  609. // @method subtract(otherPoint: Point): Point
  610. // Returns the result of subtraction of the given point from the current.
  611. subtract: function (point) {
  612. return this.clone()._subtract(toPoint(point));
  613. },
  614. _subtract: function (point) {
  615. this.x -= point.x;
  616. this.y -= point.y;
  617. return this;
  618. },
  619. // @method divideBy(num: Number): Point
  620. // Returns the result of division of the current point by the given number.
  621. divideBy: function (num) {
  622. return this.clone()._divideBy(num);
  623. },
  624. _divideBy: function (num) {
  625. this.x /= num;
  626. this.y /= num;
  627. return this;
  628. },
  629. // @method multiplyBy(num: Number): Point
  630. // Returns the result of multiplication of the current point by the given number.
  631. multiplyBy: function (num) {
  632. return this.clone()._multiplyBy(num);
  633. },
  634. _multiplyBy: function (num) {
  635. this.x *= num;
  636. this.y *= num;
  637. return this;
  638. },
  639. // @method scaleBy(scale: Point): Point
  640. // Multiply each coordinate of the current point by each coordinate of
  641. // `scale`. In linear algebra terms, multiply the point by the
  642. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  643. // defined by `scale`.
  644. scaleBy: function (point) {
  645. return new Point(this.x * point.x, this.y * point.y);
  646. },
  647. // @method unscaleBy(scale: Point): Point
  648. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  649. // each coordinate of `scale`.
  650. unscaleBy: function (point) {
  651. return new Point(this.x / point.x, this.y / point.y);
  652. },
  653. // @method round(): Point
  654. // Returns a copy of the current point with rounded coordinates.
  655. round: function () {
  656. return this.clone()._round();
  657. },
  658. _round: function () {
  659. this.x = Math.round(this.x);
  660. this.y = Math.round(this.y);
  661. return this;
  662. },
  663. // @method floor(): Point
  664. // Returns a copy of the current point with floored coordinates (rounded down).
  665. floor: function () {
  666. return this.clone()._floor();
  667. },
  668. _floor: function () {
  669. this.x = Math.floor(this.x);
  670. this.y = Math.floor(this.y);
  671. return this;
  672. },
  673. // @method ceil(): Point
  674. // Returns a copy of the current point with ceiled coordinates (rounded up).
  675. ceil: function () {
  676. return this.clone()._ceil();
  677. },
  678. _ceil: function () {
  679. this.x = Math.ceil(this.x);
  680. this.y = Math.ceil(this.y);
  681. return this;
  682. },
  683. // @method distanceTo(otherPoint: Point): Number
  684. // Returns the cartesian distance between the current and the given points.
  685. distanceTo: function (point) {
  686. point = toPoint(point);
  687. var x = point.x - this.x,
  688. y = point.y - this.y;
  689. return Math.sqrt(x * x + y * y);
  690. },
  691. // @method equals(otherPoint: Point): Boolean
  692. // Returns `true` if the given point has the same coordinates.
  693. equals: function (point) {
  694. point = toPoint(point);
  695. return point.x === this.x &&
  696. point.y === this.y;
  697. },
  698. // @method contains(otherPoint: Point): Boolean
  699. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  700. contains: function (point) {
  701. point = toPoint(point);
  702. return Math.abs(point.x) <= Math.abs(this.x) &&
  703. Math.abs(point.y) <= Math.abs(this.y);
  704. },
  705. // @method toString(): String
  706. // Returns a string representation of the point for debugging purposes.
  707. toString: function () {
  708. return 'Point(' +
  709. formatNum(this.x) + ', ' +
  710. formatNum(this.y) + ')';
  711. }
  712. };
  713. // @factory L.point(x: Number, y: Number, round?: Boolean)
  714. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  715. // @alternative
  716. // @factory L.point(coords: Number[])
  717. // Expects an array of the form `[x, y]` instead.
  718. // @alternative
  719. // @factory L.point(coords: Object)
  720. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  721. function toPoint(x, y, round) {
  722. if (x instanceof Point) {
  723. return x;
  724. }
  725. if (isArray(x)) {
  726. return new Point(x[0], x[1]);
  727. }
  728. if (x === undefined || x === null) {
  729. return x;
  730. }
  731. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  732. return new Point(x.x, x.y);
  733. }
  734. return new Point(x, y, round);
  735. }
  736. /*
  737. * @class Bounds
  738. * @aka L.Bounds
  739. *
  740. * Represents a rectangular area in pixel coordinates.
  741. *
  742. * @example
  743. *
  744. * ```js
  745. * var p1 = L.point(10, 10),
  746. * p2 = L.point(40, 60),
  747. * bounds = L.bounds(p1, p2);
  748. * ```
  749. *
  750. * 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:
  751. *
  752. * ```js
  753. * otherBounds.intersects([[10, 10], [40, 60]]);
  754. * ```
  755. */
  756. function Bounds(a, b) {
  757. if (!a) { return; }
  758. var points = b ? [a, b] : a;
  759. for (var i = 0, len = points.length; i < len; i++) {
  760. this.extend(points[i]);
  761. }
  762. }
  763. Bounds.prototype = {
  764. // @method extend(point: Point): this
  765. // Extends the bounds to contain the given point.
  766. extend: function (point) { // (Point)
  767. point = toPoint(point);
  768. // @property min: Point
  769. // The top left corner of the rectangle.
  770. // @property max: Point
  771. // The bottom right corner of the rectangle.
  772. if (!this.min && !this.max) {
  773. this.min = point.clone();
  774. this.max = point.clone();
  775. } else {
  776. this.min.x = Math.min(point.x, this.min.x);
  777. this.max.x = Math.max(point.x, this.max.x);
  778. this.min.y = Math.min(point.y, this.min.y);
  779. this.max.y = Math.max(point.y, this.max.y);
  780. }
  781. return this;
  782. },
  783. // @method getCenter(round?: Boolean): Point
  784. // Returns the center point of the bounds.
  785. getCenter: function (round) {
  786. return new Point(
  787. (this.min.x + this.max.x) / 2,
  788. (this.min.y + this.max.y) / 2, round);
  789. },
  790. // @method getBottomLeft(): Point
  791. // Returns the bottom-left point of the bounds.
  792. getBottomLeft: function () {
  793. return new Point(this.min.x, this.max.y);
  794. },
  795. // @method getTopRight(): Point
  796. // Returns the top-right point of the bounds.
  797. getTopRight: function () { // -> Point
  798. return new Point(this.max.x, this.min.y);
  799. },
  800. // @method getTopLeft(): Point
  801. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  802. getTopLeft: function () {
  803. return this.min; // left, top
  804. },
  805. // @method getBottomRight(): Point
  806. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  807. getBottomRight: function () {
  808. return this.max; // right, bottom
  809. },
  810. // @method getSize(): Point
  811. // Returns the size of the given bounds
  812. getSize: function () {
  813. return this.max.subtract(this.min);
  814. },
  815. // @method contains(otherBounds: Bounds): Boolean
  816. // Returns `true` if the rectangle contains the given one.
  817. // @alternative
  818. // @method contains(point: Point): Boolean
  819. // Returns `true` if the rectangle contains the given point.
  820. contains: function (obj) {
  821. var min, max;
  822. if (typeof obj[0] === 'number' || obj instanceof Point) {
  823. obj = toPoint(obj);
  824. } else {
  825. obj = toBounds(obj);
  826. }
  827. if (obj instanceof Bounds) {
  828. min = obj.min;
  829. max = obj.max;
  830. } else {
  831. min = max = obj;
  832. }
  833. return (min.x >= this.min.x) &&
  834. (max.x <= this.max.x) &&
  835. (min.y >= this.min.y) &&
  836. (max.y <= this.max.y);
  837. },
  838. // @method intersects(otherBounds: Bounds): Boolean
  839. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  840. // intersect if they have at least one point in common.
  841. intersects: function (bounds) { // (Bounds) -> Boolean
  842. bounds = toBounds(bounds);
  843. var min = this.min,
  844. max = this.max,
  845. min2 = bounds.min,
  846. max2 = bounds.max,
  847. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  848. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  849. return xIntersects && yIntersects;
  850. },
  851. // @method overlaps(otherBounds: Bounds): Boolean
  852. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  853. // overlap if their intersection is an area.
  854. overlaps: function (bounds) { // (Bounds) -> Boolean
  855. bounds = toBounds(bounds);
  856. var min = this.min,
  857. max = this.max,
  858. min2 = bounds.min,
  859. max2 = bounds.max,
  860. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  861. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  862. return xOverlaps && yOverlaps;
  863. },
  864. isValid: function () {
  865. return !!(this.min && this.max);
  866. }
  867. };
  868. // @factory L.bounds(corner1: Point, corner2: Point)
  869. // Creates a Bounds object from two corners coordinate pairs.
  870. // @alternative
  871. // @factory L.bounds(points: Point[])
  872. // Creates a Bounds object from the given array of points.
  873. function toBounds(a, b) {
  874. if (!a || a instanceof Bounds) {
  875. return a;
  876. }
  877. return new Bounds(a, b);
  878. }
  879. /*
  880. * @class LatLngBounds
  881. * @aka L.LatLngBounds
  882. *
  883. * Represents a rectangular geographical area on a map.
  884. *
  885. * @example
  886. *
  887. * ```js
  888. * var corner1 = L.latLng(40.712, -74.227),
  889. * corner2 = L.latLng(40.774, -74.125),
  890. * bounds = L.latLngBounds(corner1, corner2);
  891. * ```
  892. *
  893. * 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:
  894. *
  895. * ```js
  896. * map.fitBounds([
  897. * [40.712, -74.227],
  898. * [40.774, -74.125]
  899. * ]);
  900. * ```
  901. *
  902. * 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.
  903. */
  904. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  905. if (!corner1) { return; }
  906. var latlngs = corner2 ? [corner1, corner2] : corner1;
  907. for (var i = 0, len = latlngs.length; i < len; i++) {
  908. this.extend(latlngs[i]);
  909. }
  910. }
  911. LatLngBounds.prototype = {
  912. // @method extend(latlng: LatLng): this
  913. // Extend the bounds to contain the given point
  914. // @alternative
  915. // @method extend(otherBounds: LatLngBounds): this
  916. // Extend the bounds to contain the given bounds
  917. extend: function (obj) {
  918. var sw = this._southWest,
  919. ne = this._northEast,
  920. sw2, ne2;
  921. if (obj instanceof LatLng) {
  922. sw2 = obj;
  923. ne2 = obj;
  924. } else if (obj instanceof LatLngBounds) {
  925. sw2 = obj._southWest;
  926. ne2 = obj._northEast;
  927. if (!sw2 || !ne2) { return this; }
  928. } else {
  929. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  930. }
  931. if (!sw && !ne) {
  932. this._southWest = new LatLng(sw2.lat, sw2.lng);
  933. this._northEast = new LatLng(ne2.lat, ne2.lng);
  934. } else {
  935. sw.lat = Math.min(sw2.lat, sw.lat);
  936. sw.lng = Math.min(sw2.lng, sw.lng);
  937. ne.lat = Math.max(ne2.lat, ne.lat);
  938. ne.lng = Math.max(ne2.lng, ne.lng);
  939. }
  940. return this;
  941. },
  942. // @method pad(bufferRatio: Number): LatLngBounds
  943. // Returns bigger bounds created by extending the current bounds by a given percentage in each direction.
  944. pad: function (bufferRatio) {
  945. var sw = this._southWest,
  946. ne = this._northEast,
  947. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  948. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  949. return new LatLngBounds(
  950. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  951. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  952. },
  953. // @method getCenter(): LatLng
  954. // Returns the center point of the bounds.
  955. getCenter: function () {
  956. return new LatLng(
  957. (this._southWest.lat + this._northEast.lat) / 2,
  958. (this._southWest.lng + this._northEast.lng) / 2);
  959. },
  960. // @method getSouthWest(): LatLng
  961. // Returns the south-west point of the bounds.
  962. getSouthWest: function () {
  963. return this._southWest;
  964. },
  965. // @method getNorthEast(): LatLng
  966. // Returns the north-east point of the bounds.
  967. getNorthEast: function () {
  968. return this._northEast;
  969. },
  970. // @method getNorthWest(): LatLng
  971. // Returns the north-west point of the bounds.
  972. getNorthWest: function () {
  973. return new LatLng(this.getNorth(), this.getWest());
  974. },
  975. // @method getSouthEast(): LatLng
  976. // Returns the south-east point of the bounds.
  977. getSouthEast: function () {
  978. return new LatLng(this.getSouth(), this.getEast());
  979. },
  980. // @method getWest(): Number
  981. // Returns the west longitude of the bounds
  982. getWest: function () {
  983. return this._southWest.lng;
  984. },
  985. // @method getSouth(): Number
  986. // Returns the south latitude of the bounds
  987. getSouth: function () {
  988. return this._southWest.lat;
  989. },
  990. // @method getEast(): Number
  991. // Returns the east longitude of the bounds
  992. getEast: function () {
  993. return this._northEast.lng;
  994. },
  995. // @method getNorth(): Number
  996. // Returns the north latitude of the bounds
  997. getNorth: function () {
  998. return this._northEast.lat;
  999. },
  1000. // @method contains(otherBounds: LatLngBounds): Boolean
  1001. // Returns `true` if the rectangle contains the given one.
  1002. // @alternative
  1003. // @method contains (latlng: LatLng): Boolean
  1004. // Returns `true` if the rectangle contains the given point.
  1005. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1006. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1007. obj = toLatLng(obj);
  1008. } else {
  1009. obj = toLatLngBounds(obj);
  1010. }
  1011. var sw = this._southWest,
  1012. ne = this._northEast,
  1013. sw2, ne2;
  1014. if (obj instanceof LatLngBounds) {
  1015. sw2 = obj.getSouthWest();
  1016. ne2 = obj.getNorthEast();
  1017. } else {
  1018. sw2 = ne2 = obj;
  1019. }
  1020. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1021. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1022. },
  1023. // @method intersects(otherBounds: LatLngBounds): Boolean
  1024. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1025. intersects: function (bounds) {
  1026. bounds = toLatLngBounds(bounds);
  1027. var sw = this._southWest,
  1028. ne = this._northEast,
  1029. sw2 = bounds.getSouthWest(),
  1030. ne2 = bounds.getNorthEast(),
  1031. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1032. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1033. return latIntersects && lngIntersects;
  1034. },
  1035. // @method overlaps(otherBounds: Bounds): Boolean
  1036. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1037. overlaps: function (bounds) {
  1038. bounds = toLatLngBounds(bounds);
  1039. var sw = this._southWest,
  1040. ne = this._northEast,
  1041. sw2 = bounds.getSouthWest(),
  1042. ne2 = bounds.getNorthEast(),
  1043. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1044. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1045. return latOverlaps && lngOverlaps;
  1046. },
  1047. // @method toBBoxString(): String
  1048. // 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.
  1049. toBBoxString: function () {
  1050. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1051. },
  1052. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1053. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overriden by setting `maxMargin` to a small number.
  1054. equals: function (bounds, maxMargin) {
  1055. if (!bounds) { return false; }
  1056. bounds = toLatLngBounds(bounds);
  1057. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1058. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1059. },
  1060. // @method isValid(): Boolean
  1061. // Returns `true` if the bounds are properly initialized.
  1062. isValid: function () {
  1063. return !!(this._southWest && this._northEast);
  1064. }
  1065. };
  1066. // TODO International date line?
  1067. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1068. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1069. // @alternative
  1070. // @factory L.latLngBounds(latlngs: LatLng[])
  1071. // 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).
  1072. function toLatLngBounds(a, b) {
  1073. if (a instanceof LatLngBounds) {
  1074. return a;
  1075. }
  1076. return new LatLngBounds(a, b);
  1077. }
  1078. /* @class LatLng
  1079. * @aka L.LatLng
  1080. *
  1081. * Represents a geographical point with a certain latitude and longitude.
  1082. *
  1083. * @example
  1084. *
  1085. * ```
  1086. * var latlng = L.latLng(50.5, 30.5);
  1087. * ```
  1088. *
  1089. * 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:
  1090. *
  1091. * ```
  1092. * map.panTo([50, 30]);
  1093. * map.panTo({lon: 30, lat: 50});
  1094. * map.panTo({lat: 50, lng: 30});
  1095. * map.panTo(L.latLng(50, 30));
  1096. * ```
  1097. */
  1098. function LatLng(lat, lng, alt) {
  1099. if (isNaN(lat) || isNaN(lng)) {
  1100. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1101. }
  1102. // @property lat: Number
  1103. // Latitude in degrees
  1104. this.lat = +lat;
  1105. // @property lng: Number
  1106. // Longitude in degrees
  1107. this.lng = +lng;
  1108. // @property alt: Number
  1109. // Altitude in meters (optional)
  1110. if (alt !== undefined) {
  1111. this.alt = +alt;
  1112. }
  1113. }
  1114. LatLng.prototype = {
  1115. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1116. // 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.
  1117. equals: function (obj, maxMargin) {
  1118. if (!obj) { return false; }
  1119. obj = toLatLng(obj);
  1120. var margin = Math.max(
  1121. Math.abs(this.lat - obj.lat),
  1122. Math.abs(this.lng - obj.lng));
  1123. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1124. },
  1125. // @method toString(): String
  1126. // Returns a string representation of the point (for debugging purposes).
  1127. toString: function (precision) {
  1128. return 'LatLng(' +
  1129. formatNum(this.lat, precision) + ', ' +
  1130. formatNum(this.lng, precision) + ')';
  1131. },
  1132. // @method distanceTo(otherLatLng: LatLng): Number
  1133. // Returns the distance (in meters) to the given `LatLng` calculated using the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula).
  1134. distanceTo: function (other) {
  1135. return Earth.distance(this, toLatLng(other));
  1136. },
  1137. // @method wrap(): LatLng
  1138. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1139. wrap: function () {
  1140. return Earth.wrapLatLng(this);
  1141. },
  1142. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1143. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1144. toBounds: function (sizeInMeters) {
  1145. var latAccuracy = 180 * sizeInMeters / 40075017,
  1146. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1147. return toLatLngBounds(
  1148. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1149. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1150. },
  1151. clone: function () {
  1152. return new LatLng(this.lat, this.lng, this.alt);
  1153. }
  1154. };
  1155. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1156. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1157. // @alternative
  1158. // @factory L.latLng(coords: Array): LatLng
  1159. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1160. // @alternative
  1161. // @factory L.latLng(coords: Object): LatLng
  1162. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1163. function toLatLng(a, b, c) {
  1164. if (a instanceof LatLng) {
  1165. return a;
  1166. }
  1167. if (isArray(a) && typeof a[0] !== 'object') {
  1168. if (a.length === 3) {
  1169. return new LatLng(a[0], a[1], a[2]);
  1170. }
  1171. if (a.length === 2) {
  1172. return new LatLng(a[0], a[1]);
  1173. }
  1174. return null;
  1175. }
  1176. if (a === undefined || a === null) {
  1177. return a;
  1178. }
  1179. if (typeof a === 'object' && 'lat' in a) {
  1180. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1181. }
  1182. if (b === undefined) {
  1183. return null;
  1184. }
  1185. return new LatLng(a, b, c);
  1186. }
  1187. /*
  1188. * @namespace CRS
  1189. * @crs L.CRS.Base
  1190. * Object that defines coordinate reference systems for projecting
  1191. * geographical points into pixel (screen) coordinates and back (and to
  1192. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1193. * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
  1194. *
  1195. * Leaflet defines the most usual CRSs by default. If you want to use a
  1196. * CRS not defined by default, take a look at the
  1197. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1198. */
  1199. var CRS = {
  1200. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1201. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1202. latLngToPoint: function (latlng, zoom) {
  1203. var projectedPoint = this.projection.project(latlng),
  1204. scale = this.scale(zoom);
  1205. return this.transformation._transform(projectedPoint, scale);
  1206. },
  1207. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1208. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1209. // zoom into geographical coordinates.
  1210. pointToLatLng: function (point, zoom) {
  1211. var scale = this.scale(zoom),
  1212. untransformedPoint = this.transformation.untransform(point, scale);
  1213. return this.projection.unproject(untransformedPoint);
  1214. },
  1215. // @method project(latlng: LatLng): Point
  1216. // Projects geographical coordinates into coordinates in units accepted for
  1217. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1218. project: function (latlng) {
  1219. return this.projection.project(latlng);
  1220. },
  1221. // @method unproject(point: Point): LatLng
  1222. // Given a projected coordinate returns the corresponding LatLng.
  1223. // The inverse of `project`.
  1224. unproject: function (point) {
  1225. return this.projection.unproject(point);
  1226. },
  1227. // @method scale(zoom: Number): Number
  1228. // Returns the scale used when transforming projected coordinates into
  1229. // pixel coordinates for a particular zoom. For example, it returns
  1230. // `256 * 2^zoom` for Mercator-based CRS.
  1231. scale: function (zoom) {
  1232. return 256 * Math.pow(2, zoom);
  1233. },
  1234. // @method zoom(scale: Number): Number
  1235. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1236. // factor of `scale`.
  1237. zoom: function (scale) {
  1238. return Math.log(scale / 256) / Math.LN2;
  1239. },
  1240. // @method getProjectedBounds(zoom: Number): Bounds
  1241. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1242. getProjectedBounds: function (zoom) {
  1243. if (this.infinite) { return null; }
  1244. var b = this.projection.bounds,
  1245. s = this.scale(zoom),
  1246. min = this.transformation.transform(b.min, s),
  1247. max = this.transformation.transform(b.max, s);
  1248. return new Bounds(min, max);
  1249. },
  1250. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1251. // Returns the distance between two geographical coordinates.
  1252. // @property code: String
  1253. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1254. //
  1255. // @property wrapLng: Number[]
  1256. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1257. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1258. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1259. //
  1260. // @property wrapLat: Number[]
  1261. // Like `wrapLng`, but for the latitude (vertical) axis.
  1262. // wrapLng: [min, max],
  1263. // wrapLat: [min, max],
  1264. // @property infinite: Boolean
  1265. // If true, the coordinate space will be unbounded (infinite in both axes)
  1266. infinite: false,
  1267. // @method wrapLatLng(latlng: LatLng): LatLng
  1268. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1269. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1270. wrapLatLng: function (latlng) {
  1271. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1272. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1273. alt = latlng.alt;
  1274. return new LatLng(lat, lng, alt);
  1275. },
  1276. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1277. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1278. // that its center is within the CRS's bounds.
  1279. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1280. wrapLatLngBounds: function (bounds) {
  1281. var center = bounds.getCenter(),
  1282. newCenter = this.wrapLatLng(center),
  1283. latShift = center.lat - newCenter.lat,
  1284. lngShift = center.lng - newCenter.lng;
  1285. if (latShift === 0 && lngShift === 0) {
  1286. return bounds;
  1287. }
  1288. var sw = bounds.getSouthWest(),
  1289. ne = bounds.getNorthEast(),
  1290. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1291. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1292. return new LatLngBounds(newSw, newNe);
  1293. }
  1294. };
  1295. /*
  1296. * @namespace CRS
  1297. * @crs L.CRS.Earth
  1298. *
  1299. * Serves as the base for CRS that are global such that they cover the earth.
  1300. * Can only be used as the base for other CRS and cannot be used directly,
  1301. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1302. * meters.
  1303. */
  1304. var Earth = extend({}, CRS, {
  1305. wrapLng: [-180, 180],
  1306. // Mean Earth Radius, as recommended for use by
  1307. // the International Union of Geodesy and Geophysics,
  1308. // see http://rosettacode.org/wiki/Haversine_formula
  1309. R: 6371000,
  1310. // distance between two geographical points using spherical law of cosines approximation
  1311. distance: function (latlng1, latlng2) {
  1312. var rad = Math.PI / 180,
  1313. lat1 = latlng1.lat * rad,
  1314. lat2 = latlng2.lat * rad,
  1315. a = Math.sin(lat1) * Math.sin(lat2) +
  1316. Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad);
  1317. return this.R * Math.acos(Math.min(a, 1));
  1318. }
  1319. });
  1320. /*
  1321. * @namespace Projection
  1322. * @projection L.Projection.SphericalMercator
  1323. *
  1324. * Spherical Mercator projection — the most common projection for online maps,
  1325. * used by almost all free and commercial tile providers. Assumes that Earth is
  1326. * a sphere. Used by the `EPSG:3857` CRS.
  1327. */
  1328. var SphericalMercator = {
  1329. R: 6378137,
  1330. MAX_LATITUDE: 85.0511287798,
  1331. project: function (latlng) {
  1332. var d = Math.PI / 180,
  1333. max = this.MAX_LATITUDE,
  1334. lat = Math.max(Math.min(max, latlng.lat), -max),
  1335. sin = Math.sin(lat * d);
  1336. return new Point(
  1337. this.R * latlng.lng * d,
  1338. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1339. },
  1340. unproject: function (point) {
  1341. var d = 180 / Math.PI;
  1342. return new LatLng(
  1343. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1344. point.x * d / this.R);
  1345. },
  1346. bounds: (function () {
  1347. var d = 6378137 * Math.PI;
  1348. return new Bounds([-d, -d], [d, d]);
  1349. })()
  1350. };
  1351. /*
  1352. * @class Transformation
  1353. * @aka L.Transformation
  1354. *
  1355. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1356. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1357. * the reverse. Used by Leaflet in its projections code.
  1358. *
  1359. * @example
  1360. *
  1361. * ```js
  1362. * var transformation = L.transformation(2, 5, -1, 10),
  1363. * p = L.point(1, 2),
  1364. * p2 = transformation.transform(p), // L.point(7, 8)
  1365. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1366. * ```
  1367. */
  1368. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1369. // Creates a `Transformation` object with the given coefficients.
  1370. function Transformation(a, b, c, d) {
  1371. if (isArray(a)) {
  1372. // use array properties
  1373. this._a = a[0];
  1374. this._b = a[1];
  1375. this._c = a[2];
  1376. this._d = a[3];
  1377. return;
  1378. }
  1379. this._a = a;
  1380. this._b = b;
  1381. this._c = c;
  1382. this._d = d;
  1383. }
  1384. Transformation.prototype = {
  1385. // @method transform(point: Point, scale?: Number): Point
  1386. // Returns a transformed point, optionally multiplied by the given scale.
  1387. // Only accepts actual `L.Point` instances, not arrays.
  1388. transform: function (point, scale) { // (Point, Number) -> Point
  1389. return this._transform(point.clone(), scale);
  1390. },
  1391. // destructive transform (faster)
  1392. _transform: function (point, scale) {
  1393. scale = scale || 1;
  1394. point.x = scale * (this._a * point.x + this._b);
  1395. point.y = scale * (this._c * point.y + this._d);
  1396. return point;
  1397. },
  1398. // @method untransform(point: Point, scale?: Number): Point
  1399. // Returns the reverse transformation of the given point, optionally divided
  1400. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1401. untransform: function (point, scale) {
  1402. scale = scale || 1;
  1403. return new Point(
  1404. (point.x / scale - this._b) / this._a,
  1405. (point.y / scale - this._d) / this._c);
  1406. }
  1407. };
  1408. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1409. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1410. // Instantiates a Transformation object with the given coefficients.
  1411. // @alternative
  1412. // @factory L.transformation(coefficients: Array): Transformation
  1413. // Expects an coeficients array of the form
  1414. // `[a: Number, b: Number, c: Number, d: Number]`.
  1415. function toTransformation(a, b, c, d) {
  1416. return new Transformation(a, b, c, d);
  1417. }
  1418. /*
  1419. * @namespace CRS
  1420. * @crs L.CRS.EPSG3857
  1421. *
  1422. * The most common CRS for online maps, used by almost all free and commercial
  1423. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1424. * Map's `crs` option.
  1425. */
  1426. var EPSG3857 = extend({}, Earth, {
  1427. code: 'EPSG:3857',
  1428. projection: SphericalMercator,
  1429. transformation: (function () {
  1430. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1431. return toTransformation(scale, 0.5, -scale, 0.5);
  1432. }())
  1433. });
  1434. var EPSG900913 = extend({}, EPSG3857, {
  1435. code: 'EPSG:900913'
  1436. });
  1437. // @namespace SVG; @section
  1438. // There are several static functions which can be called without instantiating L.SVG:
  1439. // @function create(name: String): SVGElement
  1440. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1441. // corresponding to the class name passed. For example, using 'line' will return
  1442. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1443. function svgCreate(name) {
  1444. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1445. }
  1446. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1447. // Generates a SVG path string for multiple rings, with each ring turning
  1448. // into "M..L..L.." instructions
  1449. function pointsToPath(rings, closed) {
  1450. var str = '',
  1451. i, j, len, len2, points, p;
  1452. for (i = 0, len = rings.length; i < len; i++) {
  1453. points = rings[i];
  1454. for (j = 0, len2 = points.length; j < len2; j++) {
  1455. p = points[j];
  1456. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1457. }
  1458. // closes the ring for polygons; "x" is VML syntax
  1459. str += closed ? (svg ? 'z' : 'x') : '';
  1460. }
  1461. // SVG complains about empty path strings
  1462. return str || 'M0 0';
  1463. }
  1464. /*
  1465. * @namespace Browser
  1466. * @aka L.Browser
  1467. *
  1468. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1469. *
  1470. * @example
  1471. *
  1472. * ```js
  1473. * if (L.Browser.ielt9) {
  1474. * alert('Upgrade your browser, dude!');
  1475. * }
  1476. * ```
  1477. */
  1478. var style$1 = document.documentElement.style;
  1479. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1480. var ie = 'ActiveXObject' in window;
  1481. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1482. var ielt9 = ie && !document.addEventListener;
  1483. // @property edge: Boolean; `true` for the Edge web browser.
  1484. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1485. // @property webkit: Boolean;
  1486. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1487. var webkit = userAgentContains('webkit');
  1488. // @property android: Boolean
  1489. // `true` for any browser running on an Android platform.
  1490. var android = userAgentContains('android');
  1491. // @property android23: Boolean; `true` for browsers running on Android 2 or Android 3.
  1492. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1493. // @property opera: Boolean; `true` for the Opera browser
  1494. var opera = !!window.opera;
  1495. // @property chrome: Boolean; `true` for the Chrome browser.
  1496. var chrome = userAgentContains('chrome');
  1497. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1498. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1499. // @property safari: Boolean; `true` for the Safari browser.
  1500. var safari = !chrome && userAgentContains('safari');
  1501. var phantom = userAgentContains('phantom');
  1502. // @property opera12: Boolean
  1503. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1504. var opera12 = 'OTransition' in style$1;
  1505. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1506. var win = navigator.platform.indexOf('Win') === 0;
  1507. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1508. var ie3d = ie && ('transition' in style$1);
  1509. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1510. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1511. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1512. var gecko3d = 'MozPerspective' in style$1;
  1513. // @property any3d: Boolean
  1514. // `true` for all browsers supporting CSS transforms.
  1515. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1516. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1517. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1518. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1519. var mobileWebkit = mobile && webkit;
  1520. // @property mobileWebkit3d: Boolean
  1521. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1522. var mobileWebkit3d = mobile && webkit3d;
  1523. // @property msPointer: Boolean
  1524. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1525. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1526. // @property pointer: Boolean
  1527. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1528. var pointer = !!(window.PointerEvent || msPointer);
  1529. // @property touch: Boolean
  1530. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1531. // This does not necessarily mean that the browser is running in a computer with
  1532. // a touchscreen, it only means that the browser is capable of understanding
  1533. // touch events.
  1534. var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
  1535. (window.DocumentTouch && document instanceof window.DocumentTouch));
  1536. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1537. var mobileOpera = mobile && opera;
  1538. // @property mobileGecko: Boolean
  1539. // `true` for gecko-based browsers running in a mobile device.
  1540. var mobileGecko = mobile && gecko;
  1541. // @property retina: Boolean
  1542. // `true` for browsers on a high-resolution "retina" screen.
  1543. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1544. // @property canvas: Boolean
  1545. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1546. var canvas = (function () {
  1547. return !!document.createElement('canvas').getContext;
  1548. }());
  1549. // @property svg: Boolean
  1550. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1551. var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1552. // @property vml: Boolean
  1553. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1554. var vml = !svg && (function () {
  1555. try {
  1556. var div = document.createElement('div');
  1557. div.innerHTML = '<v:shape adj="1"/>';
  1558. var shape = div.firstChild;
  1559. shape.style.behavior = 'url(#default#VML)';
  1560. return shape && (typeof shape.adj === 'object');
  1561. } catch (e) {
  1562. return false;
  1563. }
  1564. }());
  1565. function userAgentContains(str) {
  1566. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1567. }
  1568. var Browser = (Object.freeze || Object)({
  1569. ie: ie,
  1570. ielt9: ielt9,
  1571. edge: edge,
  1572. webkit: webkit,
  1573. android: android,
  1574. android23: android23,
  1575. opera: opera,
  1576. chrome: chrome,
  1577. gecko: gecko,
  1578. safari: safari,
  1579. phantom: phantom,
  1580. opera12: opera12,
  1581. win: win,
  1582. ie3d: ie3d,
  1583. webkit3d: webkit3d,
  1584. gecko3d: gecko3d,
  1585. any3d: any3d,
  1586. mobile: mobile,
  1587. mobileWebkit: mobileWebkit,
  1588. mobileWebkit3d: mobileWebkit3d,
  1589. msPointer: msPointer,
  1590. pointer: pointer,
  1591. touch: touch,
  1592. mobileOpera: mobileOpera,
  1593. mobileGecko: mobileGecko,
  1594. retina: retina,
  1595. canvas: canvas,
  1596. svg: svg,
  1597. vml: vml
  1598. });
  1599. /*
  1600. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1601. */
  1602. var POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';
  1603. var POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';
  1604. var POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';
  1605. var POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';
  1606. var TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION'];
  1607. var _pointers = {};
  1608. var _pointerDocListener = false;
  1609. // DomEvent.DoubleTap needs to know about this
  1610. var _pointersCount = 0;
  1611. // Provides a touch events wrapper for (ms)pointer events.
  1612. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1613. function addPointerListener(obj, type, handler, id) {
  1614. if (type === 'touchstart') {
  1615. _addPointerStart(obj, handler, id);
  1616. } else if (type === 'touchmove') {
  1617. _addPointerMove(obj, handler, id);
  1618. } else if (type === 'touchend') {
  1619. _addPointerEnd(obj, handler, id);
  1620. }
  1621. return this;
  1622. }
  1623. function removePointerListener(obj, type, id) {
  1624. var handler = obj['_leaflet_' + type + id];
  1625. if (type === 'touchstart') {
  1626. obj.removeEventListener(POINTER_DOWN, handler, false);
  1627. } else if (type === 'touchmove') {
  1628. obj.removeEventListener(POINTER_MOVE, handler, false);
  1629. } else if (type === 'touchend') {
  1630. obj.removeEventListener(POINTER_UP, handler, false);
  1631. obj.removeEventListener(POINTER_CANCEL, handler, false);
  1632. }
  1633. return this;
  1634. }
  1635. function _addPointerStart(obj, handler, id) {
  1636. var onDown = bind(function (e) {
  1637. if (e.pointerType !== 'mouse' && e.pointerType !== e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
  1638. // In IE11, some touch events needs to fire for form controls, or
  1639. // the controls will stop working. We keep a whitelist of tag names that
  1640. // need these events. For other target tags, we prevent default on the event.
  1641. if (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
  1642. preventDefault(e);
  1643. } else {
  1644. return;
  1645. }
  1646. }
  1647. _handlePointer(e, handler);
  1648. });
  1649. obj['_leaflet_touchstart' + id] = onDown;
  1650. obj.addEventListener(POINTER_DOWN, onDown, false);
  1651. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1652. if (!_pointerDocListener) {
  1653. // we listen documentElement as any drags that end by moving the touch off the screen get fired there
  1654. document.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1655. document.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1656. document.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true);
  1657. document.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1658. _pointerDocListener = true;
  1659. }
  1660. }
  1661. function _globalPointerDown(e) {
  1662. _pointers[e.pointerId] = e;
  1663. _pointersCount++;
  1664. }
  1665. function _globalPointerMove(e) {
  1666. if (_pointers[e.pointerId]) {
  1667. _pointers[e.pointerId] = e;
  1668. }
  1669. }
  1670. function _globalPointerUp(e) {
  1671. delete _pointers[e.pointerId];
  1672. _pointersCount--;
  1673. }
  1674. function _handlePointer(e, handler) {
  1675. e.touches = [];
  1676. for (var i in _pointers) {
  1677. e.touches.push(_pointers[i]);
  1678. }
  1679. e.changedTouches = [e];
  1680. handler(e);
  1681. }
  1682. function _addPointerMove(obj, handler, id) {
  1683. var onMove = function (e) {
  1684. // don't fire touch moves when mouse isn't down
  1685. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
  1686. _handlePointer(e, handler);
  1687. };
  1688. obj['_leaflet_touchmove' + id] = onMove;
  1689. obj.addEventListener(POINTER_MOVE, onMove, false);
  1690. }
  1691. function _addPointerEnd(obj, handler, id) {
  1692. var onUp = function (e) {
  1693. _handlePointer(e, handler);
  1694. };
  1695. obj['_leaflet_touchend' + id] = onUp;
  1696. obj.addEventListener(POINTER_UP, onUp, false);
  1697. obj.addEventListener(POINTER_CANCEL, onUp, false);
  1698. }
  1699. /*
  1700. * Extends the event handling code with double tap support for mobile browsers.
  1701. */
  1702. var _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';
  1703. var _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';
  1704. var _pre = '_leaflet_';
  1705. // inspired by Zepto touch code by Thomas Fuchs
  1706. function addDoubleTapListener(obj, handler, id) {
  1707. var last, touch$$1,
  1708. doubleTap = false,
  1709. delay = 250;
  1710. function onTouchStart(e) {
  1711. var count;
  1712. if (pointer) {
  1713. if ((!edge) || e.pointerType === 'mouse') { return; }
  1714. count = _pointersCount;
  1715. } else {
  1716. count = e.touches.length;
  1717. }
  1718. if (count > 1) { return; }
  1719. var now = Date.now(),
  1720. delta = now - (last || now);
  1721. touch$$1 = e.touches ? e.touches[0] : e;
  1722. doubleTap = (delta > 0 && delta <= delay);
  1723. last = now;
  1724. }
  1725. function onTouchEnd(e) {
  1726. if (doubleTap && !touch$$1.cancelBubble) {
  1727. if (pointer) {
  1728. if ((!edge) || e.pointerType === 'mouse') { return; }
  1729. // work around .type being readonly with MSPointer* events
  1730. var newTouch = {},
  1731. prop, i;
  1732. for (i in touch$$1) {
  1733. prop = touch$$1[i];
  1734. newTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;
  1735. }
  1736. touch$$1 = newTouch;
  1737. }
  1738. touch$$1.type = 'dblclick';
  1739. handler(touch$$1);
  1740. last = null;
  1741. }
  1742. }
  1743. obj[_pre + _touchstart + id] = onTouchStart;
  1744. obj[_pre + _touchend + id] = onTouchEnd;
  1745. obj[_pre + 'dblclick' + id] = handler;
  1746. obj.addEventListener(_touchstart, onTouchStart, false);
  1747. obj.addEventListener(_touchend, onTouchEnd, false);
  1748. // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
  1749. // the browser doesn't fire touchend/pointerup events but does fire
  1750. // native dblclicks. See #4127.
  1751. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
  1752. obj.addEventListener('dblclick', handler, false);
  1753. return this;
  1754. }
  1755. function removeDoubleTapListener(obj, id) {
  1756. var touchstart = obj[_pre + _touchstart + id],
  1757. touchend = obj[_pre + _touchend + id],
  1758. dblclick = obj[_pre + 'dblclick' + id];
  1759. obj.removeEventListener(_touchstart, touchstart, false);
  1760. obj.removeEventListener(_touchend, touchend, false);
  1761. if (!edge) {
  1762. obj.removeEventListener('dblclick', dblclick, false);
  1763. }
  1764. return this;
  1765. }
  1766. /*
  1767. * @namespace DomEvent
  1768. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  1769. */
  1770. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  1771. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  1772. // Adds a listener function (`fn`) to a particular DOM event type of the
  1773. // element `el`. You can optionally specify the context of the listener
  1774. // (object the `this` keyword will point to). You can also pass several
  1775. // space-separated types (e.g. `'click dblclick'`).
  1776. // @alternative
  1777. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  1778. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  1779. function on(obj, types, fn, context) {
  1780. if (typeof types === 'object') {
  1781. for (var type in types) {
  1782. addOne(obj, type, types[type], fn);
  1783. }
  1784. } else {
  1785. types = splitWords(types);
  1786. for (var i = 0, len = types.length; i < len; i++) {
  1787. addOne(obj, types[i], fn, context);
  1788. }
  1789. }
  1790. return this;
  1791. }
  1792. var eventsKey = '_leaflet_events';
  1793. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  1794. // Removes a previously added listener function. If no function is specified,
  1795. // it will remove all the listeners of that particular DOM event from the element.
  1796. // Note that if you passed a custom context to on, you must pass the same
  1797. // context to `off` in order to remove the listener.
  1798. // @alternative
  1799. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  1800. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  1801. // @alternative
  1802. // @function off(el: HTMLElement): this
  1803. // Removes all known event listeners
  1804. function off(obj, types, fn, context) {
  1805. if (typeof types === 'object') {
  1806. for (var type in types) {
  1807. removeOne(obj, type, types[type], fn);
  1808. }
  1809. } else if (types) {
  1810. types = splitWords(types);
  1811. for (var i = 0, len = types.length; i < len; i++) {
  1812. removeOne(obj, types[i], fn, context);
  1813. }
  1814. } else {
  1815. for (var j in obj[eventsKey]) {
  1816. removeOne(obj, j, obj[eventsKey][j]);
  1817. }
  1818. delete obj[eventsKey];
  1819. }
  1820. return this;
  1821. }
  1822. function addOne(obj, type, fn, context) {
  1823. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  1824. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  1825. var handler = function (e) {
  1826. return fn.call(context || obj, e || window.event);
  1827. };
  1828. var originalHandler = handler;
  1829. if (pointer && type.indexOf('touch') === 0) {
  1830. // Needs DomEvent.Pointer.js
  1831. addPointerListener(obj, type, handler, id);
  1832. } else if (touch && (type === 'dblclick') && addDoubleTapListener &&
  1833. !(pointer && chrome)) {
  1834. // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener
  1835. // See #5180
  1836. addDoubleTapListener(obj, handler, id);
  1837. } else if ('addEventListener' in obj) {
  1838. if (type === 'mousewheel') {
  1839. obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  1840. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  1841. handler = function (e) {
  1842. e = e || window.event;
  1843. if (isExternalTarget(obj, e)) {
  1844. originalHandler(e);
  1845. }
  1846. };
  1847. obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
  1848. } else {
  1849. if (type === 'click' && android) {
  1850. handler = function (e) {
  1851. filterClick(e, originalHandler);
  1852. };
  1853. }
  1854. obj.addEventListener(type, handler, false);
  1855. }
  1856. } else if ('attachEvent' in obj) {
  1857. obj.attachEvent('on' + type, handler);
  1858. }
  1859. obj[eventsKey] = obj[eventsKey] || {};
  1860. obj[eventsKey][id] = handler;
  1861. }
  1862. function removeOne(obj, type, fn, context) {
  1863. var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),
  1864. handler = obj[eventsKey] && obj[eventsKey][id];
  1865. if (!handler) { return this; }
  1866. if (pointer && type.indexOf('touch') === 0) {
  1867. removePointerListener(obj, type, id);
  1868. } else if (touch && (type === 'dblclick') && removeDoubleTapListener) {
  1869. removeDoubleTapListener(obj, id);
  1870. } else if ('removeEventListener' in obj) {
  1871. if (type === 'mousewheel') {
  1872. obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  1873. } else {
  1874. obj.removeEventListener(
  1875. type === 'mouseenter' ? 'mouseover' :
  1876. type === 'mouseleave' ? 'mouseout' : type, handler, false);
  1877. }
  1878. } else if ('detachEvent' in obj) {
  1879. obj.detachEvent('on' + type, handler);
  1880. }
  1881. obj[eventsKey][id] = null;
  1882. }
  1883. // @function stopPropagation(ev: DOMEvent): this
  1884. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  1885. // ```js
  1886. // L.DomEvent.on(div, 'click', function (ev) {
  1887. // L.DomEvent.stopPropagation(ev);
  1888. // });
  1889. // ```
  1890. function stopPropagation(e) {
  1891. if (e.stopPropagation) {
  1892. e.stopPropagation();
  1893. } else if (e.originalEvent) { // In case of Leaflet event.
  1894. e.originalEvent._stopped = true;
  1895. } else {
  1896. e.cancelBubble = true;
  1897. }
  1898. skipped(e);
  1899. return this;
  1900. }
  1901. // @function disableScrollPropagation(el: HTMLElement): this
  1902. // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
  1903. function disableScrollPropagation(el) {
  1904. addOne(el, 'mousewheel', stopPropagation);
  1905. return this;
  1906. }
  1907. // @function disableClickPropagation(el: HTMLElement): this
  1908. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  1909. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  1910. function disableClickPropagation(el) {
  1911. on(el, 'mousedown touchstart dblclick', stopPropagation);
  1912. addOne(el, 'click', fakeStop);
  1913. return this;
  1914. }
  1915. // @function preventDefault(ev: DOMEvent): this
  1916. // Prevents the default action of the DOM Event `ev` from happening (such as
  1917. // following a link in the href of the a element, or doing a POST request
  1918. // with page reload when a `<form>` is submitted).
  1919. // Use it inside listener functions.
  1920. function preventDefault(e) {
  1921. if (e.preventDefault) {
  1922. e.preventDefault();
  1923. } else {
  1924. e.returnValue = false;
  1925. }
  1926. return this;
  1927. }
  1928. // @function stop(ev): this
  1929. // Does `stopPropagation` and `preventDefault` at the same time.
  1930. function stop(e) {
  1931. preventDefault(e);
  1932. stopPropagation(e);
  1933. return this;
  1934. }
  1935. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  1936. // Gets normalized mouse position from a DOM event relative to the
  1937. // `container` or to the whole page if not specified.
  1938. function getMousePosition(e, container) {
  1939. if (!container) {
  1940. return new Point(e.clientX, e.clientY);
  1941. }
  1942. var rect = container.getBoundingClientRect();
  1943. return new Point(
  1944. e.clientX - rect.left - container.clientLeft,
  1945. e.clientY - rect.top - container.clientTop);
  1946. }
  1947. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  1948. // and Firefox scrolls device pixels, not CSS pixels
  1949. var wheelPxFactor =
  1950. (win && chrome) ? 2 * window.devicePixelRatio :
  1951. gecko ? window.devicePixelRatio : 1;
  1952. // @function getWheelDelta(ev: DOMEvent): Number
  1953. // Gets normalized wheel delta from a mousewheel DOM event, in vertical
  1954. // pixels scrolled (negative if scrolling down).
  1955. // Events from pointing devices without precise scrolling are mapped to
  1956. // a best guess of 60 pixels.
  1957. function getWheelDelta(e) {
  1958. return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  1959. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  1960. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  1961. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  1962. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  1963. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  1964. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  1965. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  1966. 0;
  1967. }
  1968. var skipEvents = {};
  1969. function fakeStop(e) {
  1970. // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)
  1971. skipEvents[e.type] = true;
  1972. }
  1973. function skipped(e) {
  1974. var events = skipEvents[e.type];
  1975. // reset when checking, as it's only used in map container and propagates outside of the map
  1976. skipEvents[e.type] = false;
  1977. return events;
  1978. }
  1979. // check if element really left/entered the event target (for mouseenter/mouseleave)
  1980. function isExternalTarget(el, e) {
  1981. var related = e.relatedTarget;
  1982. if (!related) { return true; }
  1983. try {
  1984. while (related && (related !== el)) {
  1985. related = related.parentNode;
  1986. }
  1987. } catch (err) {
  1988. return false;
  1989. }
  1990. return (related !== el);
  1991. }
  1992. var lastClick;
  1993. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  1994. function filterClick(e, handler) {
  1995. var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
  1996. elapsed = lastClick && (timeStamp - lastClick);
  1997. // are they closer together than 500ms yet more than 100ms?
  1998. // Android typically triggers them ~300ms apart while multiple listeners
  1999. // on the same event should be triggered far faster;
  2000. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  2001. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  2002. stop(e);
  2003. return;
  2004. }
  2005. lastClick = timeStamp;
  2006. handler(e);
  2007. }
  2008. var DomEvent = (Object.freeze || Object)({
  2009. on: on,
  2010. off: off,
  2011. stopPropagation: stopPropagation,
  2012. disableScrollPropagation: disableScrollPropagation,
  2013. disableClickPropagation: disableClickPropagation,
  2014. preventDefault: preventDefault,
  2015. stop: stop,
  2016. getMousePosition: getMousePosition,
  2017. getWheelDelta: getWheelDelta,
  2018. fakeStop: fakeStop,
  2019. skipped: skipped,
  2020. isExternalTarget: isExternalTarget,
  2021. addListener: on,
  2022. removeListener: off
  2023. });
  2024. /*
  2025. * @namespace DomUtil
  2026. *
  2027. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  2028. * tree, used by Leaflet internally.
  2029. *
  2030. * Most functions expecting or returning a `HTMLElement` also work for
  2031. * SVG elements. The only difference is that classes refer to CSS classes
  2032. * in HTML and SVG classes in SVG.
  2033. */
  2034. // @property TRANSFORM: String
  2035. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  2036. var TRANSFORM = testProp(
  2037. ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  2038. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  2039. // the same for the transitionend event, in particular the Android 4.1 stock browser
  2040. // @property TRANSITION: String
  2041. // Vendor-prefixed transition style name.
  2042. var TRANSITION = testProp(
  2043. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  2044. // @property TRANSITION_END: String
  2045. // Vendor-prefixed transitionend event name.
  2046. var TRANSITION_END =
  2047. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  2048. // @function get(id: String|HTMLElement): HTMLElement
  2049. // Returns an element given its DOM id, or returns the element itself
  2050. // if it was passed directly.
  2051. function get(id) {
  2052. return typeof id === 'string' ? document.getElementById(id) : id;
  2053. }
  2054. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  2055. // Returns the value for a certain style attribute on an element,
  2056. // including computed values or values set through CSS.
  2057. function getStyle(el, style) {
  2058. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  2059. if ((!value || value === 'auto') && document.defaultView) {
  2060. var css = document.defaultView.getComputedStyle(el, null);
  2061. value = css ? css[style] : null;
  2062. }
  2063. return value === 'auto' ? null : value;
  2064. }
  2065. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  2066. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  2067. function create$1(tagName, className, container) {
  2068. var el = document.createElement(tagName);
  2069. el.className = className || '';
  2070. if (container) {
  2071. container.appendChild(el);
  2072. }
  2073. return el;
  2074. }
  2075. // @function remove(el: HTMLElement)
  2076. // Removes `el` from its parent element
  2077. function remove(el) {
  2078. var parent = el.parentNode;
  2079. if (parent) {
  2080. parent.removeChild(el);
  2081. }
  2082. }
  2083. // @function empty(el: HTMLElement)
  2084. // Removes all of `el`'s children elements from `el`
  2085. function empty(el) {
  2086. while (el.firstChild) {
  2087. el.removeChild(el.firstChild);
  2088. }
  2089. }
  2090. // @function toFront(el: HTMLElement)
  2091. // Makes `el` the last child of its parent, so it renders in front of the other children.
  2092. function toFront(el) {
  2093. var parent = el.parentNode;
  2094. if (parent.lastChild !== el) {
  2095. parent.appendChild(el);
  2096. }
  2097. }
  2098. // @function toBack(el: HTMLElement)
  2099. // Makes `el` the first child of its parent, so it renders behind the other children.
  2100. function toBack(el) {
  2101. var parent = el.parentNode;
  2102. if (parent.firstChild !== el) {
  2103. parent.insertBefore(el, parent.firstChild);
  2104. }
  2105. }
  2106. // @function hasClass(el: HTMLElement, name: String): Boolean
  2107. // Returns `true` if the element's class attribute contains `name`.
  2108. function hasClass(el, name) {
  2109. if (el.classList !== undefined) {
  2110. return el.classList.contains(name);
  2111. }
  2112. var className = getClass(el);
  2113. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  2114. }
  2115. // @function addClass(el: HTMLElement, name: String)
  2116. // Adds `name` to the element's class attribute.
  2117. function addClass(el, name) {
  2118. if (el.classList !== undefined) {
  2119. var classes = splitWords(name);
  2120. for (var i = 0, len = classes.length; i < len; i++) {
  2121. el.classList.add(classes[i]);
  2122. }
  2123. } else if (!hasClass(el, name)) {
  2124. var className = getClass(el);
  2125. setClass(el, (className ? className + ' ' : '') + name);
  2126. }
  2127. }
  2128. // @function removeClass(el: HTMLElement, name: String)
  2129. // Removes `name` from the element's class attribute.
  2130. function removeClass(el, name) {
  2131. if (el.classList !== undefined) {
  2132. el.classList.remove(name);
  2133. } else {
  2134. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  2135. }
  2136. }
  2137. // @function setClass(el: HTMLElement, name: String)
  2138. // Sets the element's class.
  2139. function setClass(el, name) {
  2140. if (el.className.baseVal === undefined) {
  2141. el.className = name;
  2142. } else {
  2143. // in case of SVG element
  2144. el.className.baseVal = name;
  2145. }
  2146. }
  2147. // @function getClass(el: HTMLElement): String
  2148. // Returns the element's class.
  2149. function getClass(el) {
  2150. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  2151. }
  2152. // @function setOpacity(el: HTMLElement, opacity: Number)
  2153. // Set the opacity of an element (including old IE support).
  2154. // `opacity` must be a number from `0` to `1`.
  2155. function setOpacity(el, value) {
  2156. if ('opacity' in el.style) {
  2157. el.style.opacity = value;
  2158. } else if ('filter' in el.style) {
  2159. _setOpacityIE(el, value);
  2160. }
  2161. }
  2162. function _setOpacityIE(el, value) {
  2163. var filter = false,
  2164. filterName = 'DXImageTransform.Microsoft.Alpha';
  2165. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  2166. try {
  2167. filter = el.filters.item(filterName);
  2168. } catch (e) {
  2169. // don't set opacity to 1 if we haven't already set an opacity,
  2170. // it isn't needed and breaks transparent pngs.
  2171. if (value === 1) { return; }
  2172. }
  2173. value = Math.round(value * 100);
  2174. if (filter) {
  2175. filter.Enabled = (value !== 100);
  2176. filter.Opacity = value;
  2177. } else {
  2178. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  2179. }
  2180. }
  2181. // @function testProp(props: String[]): String|false
  2182. // Goes through the array of style names and returns the first name
  2183. // that is a valid style name for an element. If no such name is found,
  2184. // it returns false. Useful for vendor-prefixed styles like `transform`.
  2185. function testProp(props) {
  2186. var style = document.documentElement.style;
  2187. for (var i = 0; i < props.length; i++) {
  2188. if (props[i] in style) {
  2189. return props[i];
  2190. }
  2191. }
  2192. return false;
  2193. }
  2194. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  2195. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  2196. // and optionally scaled by `scale`. Does not have an effect if the
  2197. // browser doesn't support 3D CSS transforms.
  2198. function setTransform(el, offset, scale) {
  2199. var pos = offset || new Point(0, 0);
  2200. el.style[TRANSFORM] =
  2201. (ie3d ?
  2202. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2203. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2204. (scale ? ' scale(' + scale + ')' : '');
  2205. }
  2206. // @function setPosition(el: HTMLElement, position: Point)
  2207. // Sets the position of `el` to coordinates specified by `position`,
  2208. // using CSS translate or top/left positioning depending on the browser
  2209. // (used by Leaflet internally to position its layers).
  2210. function setPosition(el, point) {
  2211. /*eslint-disable */
  2212. el._leaflet_pos = point;
  2213. /*eslint-enable */
  2214. if (any3d) {
  2215. setTransform(el, point);
  2216. } else {
  2217. el.style.left = point.x + 'px';
  2218. el.style.top = point.y + 'px';
  2219. }
  2220. }
  2221. // @function getPosition(el: HTMLElement): Point
  2222. // Returns the coordinates of an element previously positioned with setPosition.
  2223. function getPosition(el) {
  2224. // this method is only used for elements previously positioned using setPosition,
  2225. // so it's safe to cache the position for performance
  2226. return el._leaflet_pos || new Point(0, 0);
  2227. }
  2228. // @function disableTextSelection()
  2229. // Prevents the user from generating `selectstart` DOM events, usually generated
  2230. // when the user drags the mouse through a page with text. Used internally
  2231. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2232. // the map. Affects drag interactions on the whole document.
  2233. // @function enableTextSelection()
  2234. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2235. var disableTextSelection;
  2236. var enableTextSelection;
  2237. var _userSelect;
  2238. if ('onselectstart' in document) {
  2239. disableTextSelection = function () {
  2240. on(window, 'selectstart', preventDefault);
  2241. };
  2242. enableTextSelection = function () {
  2243. off(window, 'selectstart', preventDefault);
  2244. };
  2245. } else {
  2246. var userSelectProperty = testProp(
  2247. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2248. disableTextSelection = function () {
  2249. if (userSelectProperty) {
  2250. var style = document.documentElement.style;
  2251. _userSelect = style[userSelectProperty];
  2252. style[userSelectProperty] = 'none';
  2253. }
  2254. };
  2255. enableTextSelection = function () {
  2256. if (userSelectProperty) {
  2257. document.documentElement.style[userSelectProperty] = _userSelect;
  2258. _userSelect = undefined;
  2259. }
  2260. };
  2261. }
  2262. // @function disableImageDrag()
  2263. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2264. // for `dragstart` DOM events, usually generated when the user drags an image.
  2265. function disableImageDrag() {
  2266. on(window, 'dragstart', preventDefault);
  2267. }
  2268. // @function enableImageDrag()
  2269. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2270. function enableImageDrag() {
  2271. off(window, 'dragstart', preventDefault);
  2272. }
  2273. var _outlineElement;
  2274. var _outlineStyle;
  2275. // @function preventOutline(el: HTMLElement)
  2276. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2277. // of the element `el` invisible. Used internally by Leaflet to prevent
  2278. // focusable elements from displaying an outline when the user performs a
  2279. // drag interaction on them.
  2280. function preventOutline(element) {
  2281. while (element.tabIndex === -1) {
  2282. element = element.parentNode;
  2283. }
  2284. if (!element.style) { return; }
  2285. restoreOutline();
  2286. _outlineElement = element;
  2287. _outlineStyle = element.style.outline;
  2288. element.style.outline = 'none';
  2289. on(window, 'keydown', restoreOutline);
  2290. }
  2291. // @function restoreOutline()
  2292. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2293. function restoreOutline() {
  2294. if (!_outlineElement) { return; }
  2295. _outlineElement.style.outline = _outlineStyle;
  2296. _outlineElement = undefined;
  2297. _outlineStyle = undefined;
  2298. off(window, 'keydown', restoreOutline);
  2299. }
  2300. var DomUtil = (Object.freeze || Object)({
  2301. TRANSFORM: TRANSFORM,
  2302. TRANSITION: TRANSITION,
  2303. TRANSITION_END: TRANSITION_END,
  2304. get: get,
  2305. getStyle: getStyle,
  2306. create: create$1,
  2307. remove: remove,
  2308. empty: empty,
  2309. toFront: toFront,
  2310. toBack: toBack,
  2311. hasClass: hasClass,
  2312. addClass: addClass,
  2313. removeClass: removeClass,
  2314. setClass: setClass,
  2315. getClass: getClass,
  2316. setOpacity: setOpacity,
  2317. testProp: testProp,
  2318. setTransform: setTransform,
  2319. setPosition: setPosition,
  2320. getPosition: getPosition,
  2321. disableTextSelection: disableTextSelection,
  2322. enableTextSelection: enableTextSelection,
  2323. disableImageDrag: disableImageDrag,
  2324. enableImageDrag: enableImageDrag,
  2325. preventOutline: preventOutline,
  2326. restoreOutline: restoreOutline
  2327. });
  2328. /*
  2329. * @class PosAnimation
  2330. * @aka L.PosAnimation
  2331. * @inherits Evented
  2332. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2333. *
  2334. * @example
  2335. * ```js
  2336. * var fx = new L.PosAnimation();
  2337. * fx.run(el, [300, 500], 0.5);
  2338. * ```
  2339. *
  2340. * @constructor L.PosAnimation()
  2341. * Creates a `PosAnimation` object.
  2342. *
  2343. */
  2344. var PosAnimation = Evented.extend({
  2345. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2346. // Run an animation of a given element to a new position, optionally setting
  2347. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2348. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  2349. // `0.5` by default).
  2350. run: function (el, newPos, duration, easeLinearity) {
  2351. this.stop();
  2352. this._el = el;
  2353. this._inProgress = true;
  2354. this._duration = duration || 0.25;
  2355. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2356. this._startPos = getPosition(el);
  2357. this._offset = newPos.subtract(this._startPos);
  2358. this._startTime = +new Date();
  2359. // @event start: Event
  2360. // Fired when the animation starts
  2361. this.fire('start');
  2362. this._animate();
  2363. },
  2364. // @method stop()
  2365. // Stops the animation (if currently running).
  2366. stop: function () {
  2367. if (!this._inProgress) { return; }
  2368. this._step(true);
  2369. this._complete();
  2370. },
  2371. _animate: function () {
  2372. // animation loop
  2373. this._animId = requestAnimFrame(this._animate, this);
  2374. this._step();
  2375. },
  2376. _step: function (round) {
  2377. var elapsed = (+new Date()) - this._startTime,
  2378. duration = this._duration * 1000;
  2379. if (elapsed < duration) {
  2380. this._runFrame(this._easeOut(elapsed / duration), round);
  2381. } else {
  2382. this._runFrame(1);
  2383. this._complete();
  2384. }
  2385. },
  2386. _runFrame: function (progress, round) {
  2387. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2388. if (round) {
  2389. pos._round();
  2390. }
  2391. setPosition(this._el, pos);
  2392. // @event step: Event
  2393. // Fired continuously during the animation.
  2394. this.fire('step');
  2395. },
  2396. _complete: function () {
  2397. cancelAnimFrame(this._animId);
  2398. this._inProgress = false;
  2399. // @event end: Event
  2400. // Fired when the animation ends.
  2401. this.fire('end');
  2402. },
  2403. _easeOut: function (t) {
  2404. return 1 - Math.pow(1 - t, this._easeOutPower);
  2405. }
  2406. });
  2407. /*
  2408. * @class Map
  2409. * @aka L.Map
  2410. * @inherits Evented
  2411. *
  2412. * The central class of the API — it is used to create a map on a page and manipulate it.
  2413. *
  2414. * @example
  2415. *
  2416. * ```js
  2417. * // initialize the map on the "map" div with a given center and zoom
  2418. * var map = L.map('map', {
  2419. * center: [51.505, -0.09],
  2420. * zoom: 13
  2421. * });
  2422. * ```
  2423. *
  2424. */
  2425. var Map = Evented.extend({
  2426. options: {
  2427. // @section Map State Options
  2428. // @option crs: CRS = L.CRS.EPSG3857
  2429. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2430. // sure what it means.
  2431. crs: EPSG3857,
  2432. // @option center: LatLng = undefined
  2433. // Initial geographic center of the map
  2434. center: undefined,
  2435. // @option zoom: Number = undefined
  2436. // Initial map zoom level
  2437. zoom: undefined,
  2438. // @option minZoom: Number = *
  2439. // Minimum zoom level of the map.
  2440. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2441. // the lowest of their `minZoom` options will be used instead.
  2442. minZoom: undefined,
  2443. // @option maxZoom: Number = *
  2444. // Maximum zoom level of the map.
  2445. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2446. // the highest of their `maxZoom` options will be used instead.
  2447. maxZoom: undefined,
  2448. // @option layers: Layer[] = []
  2449. // Array of layers that will be added to the map initially
  2450. layers: [],
  2451. // @option maxBounds: LatLngBounds = null
  2452. // When this option is set, the map restricts the view to the given
  2453. // geographical bounds, bouncing the user back if the user tries to pan
  2454. // outside the view. To set the restriction dynamically, use
  2455. // [`setMaxBounds`](#map-setmaxbounds) method.
  2456. maxBounds: undefined,
  2457. // @option renderer: Renderer = *
  2458. // The default method for drawing vector layers on the map. `L.SVG`
  2459. // or `L.Canvas` by default depending on browser support.
  2460. renderer: undefined,
  2461. // @section Animation Options
  2462. // @option zoomAnimation: Boolean = true
  2463. // Whether the map zoom animation is enabled. By default it's enabled
  2464. // in all browsers that support CSS3 Transitions except Android.
  2465. zoomAnimation: true,
  2466. // @option zoomAnimationThreshold: Number = 4
  2467. // Won't animate zoom if the zoom difference exceeds this value.
  2468. zoomAnimationThreshold: 4,
  2469. // @option fadeAnimation: Boolean = true
  2470. // Whether the tile fade animation is enabled. By default it's enabled
  2471. // in all browsers that support CSS3 Transitions except Android.
  2472. fadeAnimation: true,
  2473. // @option markerZoomAnimation: Boolean = true
  2474. // Whether markers animate their zoom with the zoom animation, if disabled
  2475. // they will disappear for the length of the animation. By default it's
  2476. // enabled in all browsers that support CSS3 Transitions except Android.
  2477. markerZoomAnimation: true,
  2478. // @option transform3DLimit: Number = 2^23
  2479. // Defines the maximum size of a CSS translation transform. The default
  2480. // value should not be changed unless a web browser positions layers in
  2481. // the wrong place after doing a large `panBy`.
  2482. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2483. // @section Interaction Options
  2484. // @option zoomSnap: Number = 1
  2485. // Forces the map's zoom level to always be a multiple of this, particularly
  2486. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2487. // By default, the zoom level snaps to the nearest integer; lower values
  2488. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2489. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2490. zoomSnap: 1,
  2491. // @option zoomDelta: Number = 1
  2492. // Controls how much the map's zoom level will change after a
  2493. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2494. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2495. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2496. zoomDelta: 1,
  2497. // @option trackResize: Boolean = true
  2498. // Whether the map automatically handles browser window resize to update itself.
  2499. trackResize: true
  2500. },
  2501. initialize: function (id, options) { // (HTMLElement or String, Object)
  2502. options = setOptions(this, options);
  2503. this._initContainer(id);
  2504. this._initLayout();
  2505. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2506. this._onResize = bind(this._onResize, this);
  2507. this._initEvents();
  2508. if (options.maxBounds) {
  2509. this.setMaxBounds(options.maxBounds);
  2510. }
  2511. if (options.zoom !== undefined) {
  2512. this._zoom = this._limitZoom(options.zoom);
  2513. }
  2514. if (options.center && options.zoom !== undefined) {
  2515. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2516. }
  2517. this._handlers = [];
  2518. this._layers = {};
  2519. this._zoomBoundLayers = {};
  2520. this._sizeChanged = true;
  2521. this.callInitHooks();
  2522. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2523. this._zoomAnimated = TRANSITION && any3d && !mobileOpera &&
  2524. this.options.zoomAnimation;
  2525. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2526. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2527. if (this._zoomAnimated) {
  2528. this._createAnimProxy();
  2529. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2530. }
  2531. this._addLayers(this.options.layers);
  2532. },
  2533. // @section Methods for modifying map state
  2534. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2535. // Sets the view of the map (geographical center and zoom) with the given
  2536. // animation options.
  2537. setView: function (center, zoom, options) {
  2538. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2539. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2540. options = options || {};
  2541. this._stop();
  2542. if (this._loaded && !options.reset && options !== true) {
  2543. if (options.animate !== undefined) {
  2544. options.zoom = extend({animate: options.animate}, options.zoom);
  2545. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2546. }
  2547. // try animating pan or zoom
  2548. var moved = (this._zoom !== zoom) ?
  2549. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2550. this._tryAnimatedPan(center, options.pan);
  2551. if (moved) {
  2552. // prevent resize handler call, the view will refresh after animation anyway
  2553. clearTimeout(this._sizeTimer);
  2554. return this;
  2555. }
  2556. }
  2557. // animation didn't start, just reset the map view
  2558. this._resetView(center, zoom);
  2559. return this;
  2560. },
  2561. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2562. // Sets the zoom of the map.
  2563. setZoom: function (zoom, options) {
  2564. if (!this._loaded) {
  2565. this._zoom = zoom;
  2566. return this;
  2567. }
  2568. return this.setView(this.getCenter(), zoom, {zoom: options});
  2569. },
  2570. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2571. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2572. zoomIn: function (delta, options) {
  2573. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2574. return this.setZoom(this._zoom + delta, options);
  2575. },
  2576. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2577. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2578. zoomOut: function (delta, options) {
  2579. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2580. return this.setZoom(this._zoom - delta, options);
  2581. },
  2582. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2583. // Zooms the map while keeping a specified geographical point on the map
  2584. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2585. // @alternative
  2586. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2587. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2588. setZoomAround: function (latlng, zoom, options) {
  2589. var scale = this.getZoomScale(zoom),
  2590. viewHalf = this.getSize().divideBy(2),
  2591. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2592. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2593. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2594. return this.setView(newCenter, zoom, {zoom: options});
  2595. },
  2596. _getBoundsCenterZoom: function (bounds, options) {
  2597. options = options || {};
  2598. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2599. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2600. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2601. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2602. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2603. if (zoom === Infinity) {
  2604. return {
  2605. center: bounds.getCenter(),
  2606. zoom: zoom
  2607. };
  2608. }
  2609. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2610. swPoint = this.project(bounds.getSouthWest(), zoom),
  2611. nePoint = this.project(bounds.getNorthEast(), zoom),
  2612. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2613. return {
  2614. center: center,
  2615. zoom: zoom
  2616. };
  2617. },
  2618. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2619. // Sets a map view that contains the given geographical bounds with the
  2620. // maximum zoom level possible.
  2621. fitBounds: function (bounds, options) {
  2622. bounds = toLatLngBounds(bounds);
  2623. if (!bounds.isValid()) {
  2624. throw new Error('Bounds are not valid.');
  2625. }
  2626. var target = this._getBoundsCenterZoom(bounds, options);
  2627. return this.setView(target.center, target.zoom, options);
  2628. },
  2629. // @method fitWorld(options?: fitBounds options): this
  2630. // Sets a map view that mostly contains the whole world with the maximum
  2631. // zoom level possible.
  2632. fitWorld: function (options) {
  2633. return this.fitBounds([[-90, -180], [90, 180]], options);
  2634. },
  2635. // @method panTo(latlng: LatLng, options?: Pan options): this
  2636. // Pans the map to a given center.
  2637. panTo: function (center, options) { // (LatLng)
  2638. return this.setView(center, this._zoom, {pan: options});
  2639. },
  2640. // @method panBy(offset: Point, options?: Pan options): this
  2641. // Pans the map by a given number of pixels (animated).
  2642. panBy: function (offset, options) {
  2643. offset = toPoint(offset).round();
  2644. options = options || {};
  2645. if (!offset.x && !offset.y) {
  2646. return this.fire('moveend');
  2647. }
  2648. // If we pan too far, Chrome gets issues with tiles
  2649. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2650. if (options.animate !== true && !this.getSize().contains(offset)) {
  2651. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2652. return this;
  2653. }
  2654. if (!this._panAnim) {
  2655. this._panAnim = new PosAnimation();
  2656. this._panAnim.on({
  2657. 'step': this._onPanTransitionStep,
  2658. 'end': this._onPanTransitionEnd
  2659. }, this);
  2660. }
  2661. // don't fire movestart if animating inertia
  2662. if (!options.noMoveStart) {
  2663. this.fire('movestart');
  2664. }
  2665. // animate pan unless animate: false specified
  2666. if (options.animate !== false) {
  2667. addClass(this._mapPane, 'leaflet-pan-anim');
  2668. var newPos = this._getMapPanePos().subtract(offset).round();
  2669. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2670. } else {
  2671. this._rawPanBy(offset);
  2672. this.fire('move').fire('moveend');
  2673. }
  2674. return this;
  2675. },
  2676. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2677. // Sets the view of the map (geographical center and zoom) performing a smooth
  2678. // pan-zoom animation.
  2679. flyTo: function (targetCenter, targetZoom, options) {
  2680. options = options || {};
  2681. if (options.animate === false || !any3d) {
  2682. return this.setView(targetCenter, targetZoom, options);
  2683. }
  2684. this._stop();
  2685. var from = this.project(this.getCenter()),
  2686. to = this.project(targetCenter),
  2687. size = this.getSize(),
  2688. startZoom = this._zoom;
  2689. targetCenter = toLatLng(targetCenter);
  2690. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2691. var w0 = Math.max(size.x, size.y),
  2692. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2693. u1 = (to.distanceTo(from)) || 1,
  2694. rho = 1.42,
  2695. rho2 = rho * rho;
  2696. function r(i) {
  2697. var s1 = i ? -1 : 1,
  2698. s2 = i ? w1 : w0,
  2699. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2700. b1 = 2 * s2 * rho2 * u1,
  2701. b = t1 / b1,
  2702. sq = Math.sqrt(b * b + 1) - b;
  2703. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2704. // thus triggering an infinite loop in flyTo
  2705. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2706. return log;
  2707. }
  2708. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2709. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2710. function tanh(n) { return sinh(n) / cosh(n); }
  2711. var r0 = r(0);
  2712. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2713. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2714. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2715. var start = Date.now(),
  2716. S = (r(1) - r0) / rho,
  2717. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2718. function frame() {
  2719. var t = (Date.now() - start) / duration,
  2720. s = easeOut(t) * S;
  2721. if (t <= 1) {
  2722. this._flyToFrame = requestAnimFrame(frame, this);
  2723. this._move(
  2724. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2725. this.getScaleZoom(w0 / w(s), startZoom),
  2726. {flyTo: true});
  2727. } else {
  2728. this
  2729. ._move(targetCenter, targetZoom)
  2730. ._moveEnd(true);
  2731. }
  2732. }
  2733. this._moveStart(true);
  2734. frame.call(this);
  2735. return this;
  2736. },
  2737. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2738. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2739. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2740. flyToBounds: function (bounds, options) {
  2741. var target = this._getBoundsCenterZoom(bounds, options);
  2742. return this.flyTo(target.center, target.zoom, options);
  2743. },
  2744. // @method setMaxBounds(bounds: Bounds): this
  2745. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2746. setMaxBounds: function (bounds) {
  2747. bounds = toLatLngBounds(bounds);
  2748. if (!bounds.isValid()) {
  2749. this.options.maxBounds = null;
  2750. return this.off('moveend', this._panInsideMaxBounds);
  2751. } else if (this.options.maxBounds) {
  2752. this.off('moveend', this._panInsideMaxBounds);
  2753. }
  2754. this.options.maxBounds = bounds;
  2755. if (this._loaded) {
  2756. this._panInsideMaxBounds();
  2757. }
  2758. return this.on('moveend', this._panInsideMaxBounds);
  2759. },
  2760. // @method setMinZoom(zoom: Number): this
  2761. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2762. setMinZoom: function (zoom) {
  2763. this.options.minZoom = zoom;
  2764. if (this._loaded && this.getZoom() < this.options.minZoom) {
  2765. return this.setZoom(zoom);
  2766. }
  2767. return this;
  2768. },
  2769. // @method setMaxZoom(zoom: Number): this
  2770. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2771. setMaxZoom: function (zoom) {
  2772. this.options.maxZoom = zoom;
  2773. if (this._loaded && (this.getZoom() > this.options.maxZoom)) {
  2774. return this.setZoom(zoom);
  2775. }
  2776. return this;
  2777. },
  2778. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2779. // 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.
  2780. panInsideBounds: function (bounds, options) {
  2781. this._enforcingBounds = true;
  2782. var center = this.getCenter(),
  2783. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2784. if (!center.equals(newCenter)) {
  2785. this.panTo(newCenter, options);
  2786. }
  2787. this._enforcingBounds = false;
  2788. return this;
  2789. },
  2790. // @method invalidateSize(options: Zoom/Pan options): this
  2791. // Checks if the map container size changed and updates the map if so —
  2792. // call it after you've changed the map size dynamically, also animating
  2793. // pan by default. If `options.pan` is `false`, panning will not occur.
  2794. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2795. // that it doesn't happen often even if the method is called many
  2796. // times in a row.
  2797. // @alternative
  2798. // @method invalidateSize(animate: Boolean): this
  2799. // Checks if the map container size changed and updates the map if so —
  2800. // call it after you've changed the map size dynamically, also animating
  2801. // pan by default.
  2802. invalidateSize: function (options) {
  2803. if (!this._loaded) { return this; }
  2804. options = extend({
  2805. animate: false,
  2806. pan: true
  2807. }, options === true ? {animate: true} : options);
  2808. var oldSize = this.getSize();
  2809. this._sizeChanged = true;
  2810. this._lastCenter = null;
  2811. var newSize = this.getSize(),
  2812. oldCenter = oldSize.divideBy(2).round(),
  2813. newCenter = newSize.divideBy(2).round(),
  2814. offset = oldCenter.subtract(newCenter);
  2815. if (!offset.x && !offset.y) { return this; }
  2816. if (options.animate && options.pan) {
  2817. this.panBy(offset);
  2818. } else {
  2819. if (options.pan) {
  2820. this._rawPanBy(offset);
  2821. }
  2822. this.fire('move');
  2823. if (options.debounceMoveend) {
  2824. clearTimeout(this._sizeTimer);
  2825. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  2826. } else {
  2827. this.fire('moveend');
  2828. }
  2829. }
  2830. // @section Map state change events
  2831. // @event resize: ResizeEvent
  2832. // Fired when the map is resized.
  2833. return this.fire('resize', {
  2834. oldSize: oldSize,
  2835. newSize: newSize
  2836. });
  2837. },
  2838. // @section Methods for modifying map state
  2839. // @method stop(): this
  2840. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2841. stop: function () {
  2842. this.setZoom(this._limitZoom(this._zoom));
  2843. if (!this.options.zoomSnap) {
  2844. this.fire('viewreset');
  2845. }
  2846. return this._stop();
  2847. },
  2848. // @section Geolocation methods
  2849. // @method locate(options?: Locate options): this
  2850. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  2851. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  2852. // and optionally sets the map view to the user's location with respect to
  2853. // detection accuracy (or to the world view if geolocation failed).
  2854. // Note that, if your page doesn't use HTTPS, this method will fail in
  2855. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  2856. // See `Locate options` for more details.
  2857. locate: function (options) {
  2858. options = this._locateOptions = extend({
  2859. timeout: 10000,
  2860. watch: false
  2861. // setView: false
  2862. // maxZoom: <Number>
  2863. // maximumAge: 0
  2864. // enableHighAccuracy: false
  2865. }, options);
  2866. if (!('geolocation' in navigator)) {
  2867. this._handleGeolocationError({
  2868. code: 0,
  2869. message: 'Geolocation not supported.'
  2870. });
  2871. return this;
  2872. }
  2873. var onResponse = bind(this._handleGeolocationResponse, this),
  2874. onError = bind(this._handleGeolocationError, this);
  2875. if (options.watch) {
  2876. this._locationWatchId =
  2877. navigator.geolocation.watchPosition(onResponse, onError, options);
  2878. } else {
  2879. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  2880. }
  2881. return this;
  2882. },
  2883. // @method stopLocate(): this
  2884. // Stops watching location previously initiated by `map.locate({watch: true})`
  2885. // and aborts resetting the map view if map.locate was called with
  2886. // `{setView: true}`.
  2887. stopLocate: function () {
  2888. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  2889. navigator.geolocation.clearWatch(this._locationWatchId);
  2890. }
  2891. if (this._locateOptions) {
  2892. this._locateOptions.setView = false;
  2893. }
  2894. return this;
  2895. },
  2896. _handleGeolocationError: function (error) {
  2897. var c = error.code,
  2898. message = error.message ||
  2899. (c === 1 ? 'permission denied' :
  2900. (c === 2 ? 'position unavailable' : 'timeout'));
  2901. if (this._locateOptions.setView && !this._loaded) {
  2902. this.fitWorld();
  2903. }
  2904. // @section Location events
  2905. // @event locationerror: ErrorEvent
  2906. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  2907. this.fire('locationerror', {
  2908. code: c,
  2909. message: 'Geolocation error: ' + message + '.'
  2910. });
  2911. },
  2912. _handleGeolocationResponse: function (pos) {
  2913. var lat = pos.coords.latitude,
  2914. lng = pos.coords.longitude,
  2915. latlng = new LatLng(lat, lng),
  2916. bounds = latlng.toBounds(pos.coords.accuracy),
  2917. options = this._locateOptions;
  2918. if (options.setView) {
  2919. var zoom = this.getBoundsZoom(bounds);
  2920. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  2921. }
  2922. var data = {
  2923. latlng: latlng,
  2924. bounds: bounds,
  2925. timestamp: pos.timestamp
  2926. };
  2927. for (var i in pos.coords) {
  2928. if (typeof pos.coords[i] === 'number') {
  2929. data[i] = pos.coords[i];
  2930. }
  2931. }
  2932. // @event locationfound: LocationEvent
  2933. // Fired when geolocation (using the [`locate`](#map-locate) method)
  2934. // went successfully.
  2935. this.fire('locationfound', data);
  2936. },
  2937. // TODO handler.addTo
  2938. // TODO Appropiate docs section?
  2939. // @section Other Methods
  2940. // @method addHandler(name: String, HandlerClass: Function): this
  2941. // Adds a new `Handler` to the map, given its name and constructor function.
  2942. addHandler: function (name, HandlerClass) {
  2943. if (!HandlerClass) { return this; }
  2944. var handler = this[name] = new HandlerClass(this);
  2945. this._handlers.push(handler);
  2946. if (this.options[name]) {
  2947. handler.enable();
  2948. }
  2949. return this;
  2950. },
  2951. // @method remove(): this
  2952. // Destroys the map and clears all related event listeners.
  2953. remove: function () {
  2954. this._initEvents(true);
  2955. if (this._containerId !== this._container._leaflet_id) {
  2956. throw new Error('Map container is being reused by another instance');
  2957. }
  2958. try {
  2959. // throws error in IE6-8
  2960. delete this._container._leaflet_id;
  2961. delete this._containerId;
  2962. } catch (e) {
  2963. /*eslint-disable */
  2964. this._container._leaflet_id = undefined;
  2965. /*eslint-enable */
  2966. this._containerId = undefined;
  2967. }
  2968. remove(this._mapPane);
  2969. if (this._clearControlPos) {
  2970. this._clearControlPos();
  2971. }
  2972. this._clearHandlers();
  2973. if (this._loaded) {
  2974. // @section Map state change events
  2975. // @event unload: Event
  2976. // Fired when the map is destroyed with [remove](#map-remove) method.
  2977. this.fire('unload');
  2978. }
  2979. var i;
  2980. for (i in this._layers) {
  2981. this._layers[i].remove();
  2982. }
  2983. for (i in this._panes) {
  2984. remove(this._panes[i]);
  2985. }
  2986. this._layers = [];
  2987. this._panes = [];
  2988. delete this._mapPane;
  2989. delete this._renderer;
  2990. return this;
  2991. },
  2992. // @section Other Methods
  2993. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  2994. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  2995. // then returns it. The pane is created as a child of `container`, or
  2996. // as a child of the main map pane if not set.
  2997. createPane: function (name, container) {
  2998. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  2999. pane = create$1('div', className, container || this._mapPane);
  3000. if (name) {
  3001. this._panes[name] = pane;
  3002. }
  3003. return pane;
  3004. },
  3005. // @section Methods for Getting Map State
  3006. // @method getCenter(): LatLng
  3007. // Returns the geographical center of the map view
  3008. getCenter: function () {
  3009. this._checkIfLoaded();
  3010. if (this._lastCenter && !this._moved()) {
  3011. return this._lastCenter;
  3012. }
  3013. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3014. },
  3015. // @method getZoom(): Number
  3016. // Returns the current zoom level of the map view
  3017. getZoom: function () {
  3018. return this._zoom;
  3019. },
  3020. // @method getBounds(): LatLngBounds
  3021. // Returns the geographical bounds visible in the current map view
  3022. getBounds: function () {
  3023. var bounds = this.getPixelBounds(),
  3024. sw = this.unproject(bounds.getBottomLeft()),
  3025. ne = this.unproject(bounds.getTopRight());
  3026. return new LatLngBounds(sw, ne);
  3027. },
  3028. // @method getMinZoom(): Number
  3029. // 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.
  3030. getMinZoom: function () {
  3031. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3032. },
  3033. // @method getMaxZoom(): Number
  3034. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3035. getMaxZoom: function () {
  3036. return this.options.maxZoom === undefined ?
  3037. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3038. this.options.maxZoom;
  3039. },
  3040. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean): Number
  3041. // Returns the maximum zoom level on which the given bounds fit to the map
  3042. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3043. // instead returns the minimum zoom level on which the map view fits into
  3044. // the given bounds in its entirety.
  3045. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3046. bounds = toLatLngBounds(bounds);
  3047. padding = toPoint(padding || [0, 0]);
  3048. var zoom = this.getZoom() || 0,
  3049. min = this.getMinZoom(),
  3050. max = this.getMaxZoom(),
  3051. nw = bounds.getNorthWest(),
  3052. se = bounds.getSouthEast(),
  3053. size = this.getSize().subtract(padding),
  3054. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3055. snap = any3d ? this.options.zoomSnap : 1,
  3056. scalex = size.x / boundsSize.x,
  3057. scaley = size.y / boundsSize.y,
  3058. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3059. zoom = this.getScaleZoom(scale, zoom);
  3060. if (snap) {
  3061. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3062. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3063. }
  3064. return Math.max(min, Math.min(max, zoom));
  3065. },
  3066. // @method getSize(): Point
  3067. // Returns the current size of the map container (in pixels).
  3068. getSize: function () {
  3069. if (!this._size || this._sizeChanged) {
  3070. this._size = new Point(
  3071. this._container.clientWidth || 0,
  3072. this._container.clientHeight || 0);
  3073. this._sizeChanged = false;
  3074. }
  3075. return this._size.clone();
  3076. },
  3077. // @method getPixelBounds(): Bounds
  3078. // Returns the bounds of the current map view in projected pixel
  3079. // coordinates (sometimes useful in layer and overlay implementations).
  3080. getPixelBounds: function (center, zoom) {
  3081. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3082. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3083. },
  3084. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3085. // the map pane? "left point of the map layer" can be confusing, specially
  3086. // since there can be negative offsets.
  3087. // @method getPixelOrigin(): Point
  3088. // Returns the projected pixel coordinates of the top left point of
  3089. // the map layer (useful in custom layer and overlay implementations).
  3090. getPixelOrigin: function () {
  3091. this._checkIfLoaded();
  3092. return this._pixelOrigin;
  3093. },
  3094. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3095. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3096. // If `zoom` is omitted, the map's current zoom level is used.
  3097. getPixelWorldBounds: function (zoom) {
  3098. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3099. },
  3100. // @section Other Methods
  3101. // @method getPane(pane: String|HTMLElement): HTMLElement
  3102. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3103. getPane: function (pane) {
  3104. return typeof pane === 'string' ? this._panes[pane] : pane;
  3105. },
  3106. // @method getPanes(): Object
  3107. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3108. // the panes as values.
  3109. getPanes: function () {
  3110. return this._panes;
  3111. },
  3112. // @method getContainer: HTMLElement
  3113. // Returns the HTML element that contains the map.
  3114. getContainer: function () {
  3115. return this._container;
  3116. },
  3117. // @section Conversion Methods
  3118. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3119. // Returns the scale factor to be applied to a map transition from zoom level
  3120. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3121. getZoomScale: function (toZoom, fromZoom) {
  3122. // TODO replace with universal implementation after refactoring projections
  3123. var crs = this.options.crs;
  3124. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3125. return crs.scale(toZoom) / crs.scale(fromZoom);
  3126. },
  3127. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3128. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3129. // level and everything is scaled by a factor of `scale`. Inverse of
  3130. // [`getZoomScale`](#map-getZoomScale).
  3131. getScaleZoom: function (scale, fromZoom) {
  3132. var crs = this.options.crs;
  3133. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3134. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3135. return isNaN(zoom) ? Infinity : zoom;
  3136. },
  3137. // @method project(latlng: LatLng, zoom: Number): Point
  3138. // Projects a geographical coordinate `LatLng` according to the projection
  3139. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3140. // `Transformation`. The result is pixel coordinate relative to
  3141. // the CRS origin.
  3142. project: function (latlng, zoom) {
  3143. zoom = zoom === undefined ? this._zoom : zoom;
  3144. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3145. },
  3146. // @method unproject(point: Point, zoom: Number): LatLng
  3147. // Inverse of [`project`](#map-project).
  3148. unproject: function (point, zoom) {
  3149. zoom = zoom === undefined ? this._zoom : zoom;
  3150. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3151. },
  3152. // @method layerPointToLatLng(point: Point): LatLng
  3153. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3154. // returns the corresponding geographical coordinate (for the current zoom level).
  3155. layerPointToLatLng: function (point) {
  3156. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3157. return this.unproject(projectedPoint);
  3158. },
  3159. // @method latLngToLayerPoint(latlng: LatLng): Point
  3160. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3161. // relative to the [origin pixel](#map-getpixelorigin).
  3162. latLngToLayerPoint: function (latlng) {
  3163. var projectedPoint = this.project(toLatLng(latlng))._round();
  3164. return projectedPoint._subtract(this.getPixelOrigin());
  3165. },
  3166. // @method wrapLatLng(latlng: LatLng): LatLng
  3167. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3168. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3169. // CRS's bounds.
  3170. // By default this means longitude is wrapped around the dateline so its
  3171. // value is between -180 and +180 degrees.
  3172. wrapLatLng: function (latlng) {
  3173. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3174. },
  3175. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3176. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3177. // its center is within the CRS's bounds.
  3178. // By default this means the center longitude is wrapped around the dateline so its
  3179. // value is between -180 and +180 degrees, and the majority of the bounds
  3180. // overlaps the CRS's bounds.
  3181. wrapLatLngBounds: function (latlng) {
  3182. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3183. },
  3184. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3185. // Returns the distance between two geographical coordinates according to
  3186. // the map's CRS. By default this measures distance in meters.
  3187. distance: function (latlng1, latlng2) {
  3188. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3189. },
  3190. // @method containerPointToLayerPoint(point: Point): Point
  3191. // Given a pixel coordinate relative to the map container, returns the corresponding
  3192. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3193. containerPointToLayerPoint: function (point) { // (Point)
  3194. return toPoint(point).subtract(this._getMapPanePos());
  3195. },
  3196. // @method layerPointToContainerPoint(point: Point): Point
  3197. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3198. // returns the corresponding pixel coordinate relative to the map container.
  3199. layerPointToContainerPoint: function (point) { // (Point)
  3200. return toPoint(point).add(this._getMapPanePos());
  3201. },
  3202. // @method containerPointToLatLng(point: Point): LatLng
  3203. // Given a pixel coordinate relative to the map container, returns
  3204. // the corresponding geographical coordinate (for the current zoom level).
  3205. containerPointToLatLng: function (point) {
  3206. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3207. return this.layerPointToLatLng(layerPoint);
  3208. },
  3209. // @method latLngToContainerPoint(latlng: LatLng): Point
  3210. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3211. // relative to the map container.
  3212. latLngToContainerPoint: function (latlng) {
  3213. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3214. },
  3215. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3216. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3217. // map container where the event took place.
  3218. mouseEventToContainerPoint: function (e) {
  3219. return getMousePosition(e, this._container);
  3220. },
  3221. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3222. // Given a MouseEvent object, returns the pixel coordinate relative to
  3223. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3224. mouseEventToLayerPoint: function (e) {
  3225. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3226. },
  3227. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3228. // Given a MouseEvent object, returns geographical coordinate where the
  3229. // event took place.
  3230. mouseEventToLatLng: function (e) { // (MouseEvent)
  3231. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3232. },
  3233. // map initialization methods
  3234. _initContainer: function (id) {
  3235. var container = this._container = get(id);
  3236. if (!container) {
  3237. throw new Error('Map container not found.');
  3238. } else if (container._leaflet_id) {
  3239. throw new Error('Map container is already initialized.');
  3240. }
  3241. on(container, 'scroll', this._onScroll, this);
  3242. this._containerId = stamp(container);
  3243. },
  3244. _initLayout: function () {
  3245. var container = this._container;
  3246. this._fadeAnimated = this.options.fadeAnimation && any3d;
  3247. addClass(container, 'leaflet-container' +
  3248. (touch ? ' leaflet-touch' : '') +
  3249. (retina ? ' leaflet-retina' : '') +
  3250. (ielt9 ? ' leaflet-oldie' : '') +
  3251. (safari ? ' leaflet-safari' : '') +
  3252. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3253. var position = getStyle(container, 'position');
  3254. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  3255. container.style.position = 'relative';
  3256. }
  3257. this._initPanes();
  3258. if (this._initControlPos) {
  3259. this._initControlPos();
  3260. }
  3261. },
  3262. _initPanes: function () {
  3263. var panes = this._panes = {};
  3264. this._paneRenderers = {};
  3265. // @section
  3266. //
  3267. // Panes are DOM elements used to control the ordering of layers on the map. You
  3268. // can access panes with [`map.getPane`](#map-getpane) or
  3269. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3270. // [`map.createPane`](#map-createpane) method.
  3271. //
  3272. // Every map has the following default panes that differ only in zIndex.
  3273. //
  3274. // @pane mapPane: HTMLElement = 'auto'
  3275. // Pane that contains all other map panes
  3276. this._mapPane = this.createPane('mapPane', this._container);
  3277. setPosition(this._mapPane, new Point(0, 0));
  3278. // @pane tilePane: HTMLElement = 200
  3279. // Pane for `GridLayer`s and `TileLayer`s
  3280. this.createPane('tilePane');
  3281. // @pane overlayPane: HTMLElement = 400
  3282. // Pane for vector overlays (`Path`s), like `Polyline`s and `Polygon`s
  3283. this.createPane('shadowPane');
  3284. // @pane shadowPane: HTMLElement = 500
  3285. // Pane for overlay shadows (e.g. `Marker` shadows)
  3286. this.createPane('overlayPane');
  3287. // @pane markerPane: HTMLElement = 600
  3288. // Pane for `Icon`s of `Marker`s
  3289. this.createPane('markerPane');
  3290. // @pane tooltipPane: HTMLElement = 650
  3291. // Pane for tooltip.
  3292. this.createPane('tooltipPane');
  3293. // @pane popupPane: HTMLElement = 700
  3294. // Pane for `Popup`s.
  3295. this.createPane('popupPane');
  3296. if (!this.options.markerZoomAnimation) {
  3297. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3298. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3299. }
  3300. },
  3301. // private methods that modify map state
  3302. // @section Map state change events
  3303. _resetView: function (center, zoom) {
  3304. setPosition(this._mapPane, new Point(0, 0));
  3305. var loading = !this._loaded;
  3306. this._loaded = true;
  3307. zoom = this._limitZoom(zoom);
  3308. this.fire('viewprereset');
  3309. var zoomChanged = this._zoom !== zoom;
  3310. this
  3311. ._moveStart(zoomChanged)
  3312. ._move(center, zoom)
  3313. ._moveEnd(zoomChanged);
  3314. // @event viewreset: Event
  3315. // Fired when the map needs to redraw its content (this usually happens
  3316. // on map zoom or load). Very useful for creating custom overlays.
  3317. this.fire('viewreset');
  3318. // @event load: Event
  3319. // Fired when the map is initialized (when its center and zoom are set
  3320. // for the first time).
  3321. if (loading) {
  3322. this.fire('load');
  3323. }
  3324. },
  3325. _moveStart: function (zoomChanged) {
  3326. // @event zoomstart: Event
  3327. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3328. // @event movestart: Event
  3329. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3330. if (zoomChanged) {
  3331. this.fire('zoomstart');
  3332. }
  3333. return this.fire('movestart');
  3334. },
  3335. _move: function (center, zoom, data) {
  3336. if (zoom === undefined) {
  3337. zoom = this._zoom;
  3338. }
  3339. var zoomChanged = this._zoom !== zoom;
  3340. this._zoom = zoom;
  3341. this._lastCenter = center;
  3342. this._pixelOrigin = this._getNewPixelOrigin(center);
  3343. // @event zoom: Event
  3344. // Fired repeatedly during any change in zoom level, including zoom
  3345. // and fly animations.
  3346. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3347. this.fire('zoom', data);
  3348. }
  3349. // @event move: Event
  3350. // Fired repeatedly during any movement of the map, including pan and
  3351. // fly animations.
  3352. return this.fire('move', data);
  3353. },
  3354. _moveEnd: function (zoomChanged) {
  3355. // @event zoomend: Event
  3356. // Fired when the map has changed, after any animations.
  3357. if (zoomChanged) {
  3358. this.fire('zoomend');
  3359. }
  3360. // @event moveend: Event
  3361. // Fired when the center of the map stops changing (e.g. user stopped
  3362. // dragging the map).
  3363. return this.fire('moveend');
  3364. },
  3365. _stop: function () {
  3366. cancelAnimFrame(this._flyToFrame);
  3367. if (this._panAnim) {
  3368. this._panAnim.stop();
  3369. }
  3370. return this;
  3371. },
  3372. _rawPanBy: function (offset) {
  3373. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3374. },
  3375. _getZoomSpan: function () {
  3376. return this.getMaxZoom() - this.getMinZoom();
  3377. },
  3378. _panInsideMaxBounds: function () {
  3379. if (!this._enforcingBounds) {
  3380. this.panInsideBounds(this.options.maxBounds);
  3381. }
  3382. },
  3383. _checkIfLoaded: function () {
  3384. if (!this._loaded) {
  3385. throw new Error('Set map center and zoom first.');
  3386. }
  3387. },
  3388. // DOM event handling
  3389. // @section Interaction events
  3390. _initEvents: function (remove$$1) {
  3391. this._targets = {};
  3392. this._targets[stamp(this._container)] = this;
  3393. var onOff = remove$$1 ? off : on;
  3394. // @event click: MouseEvent
  3395. // Fired when the user clicks (or taps) the map.
  3396. // @event dblclick: MouseEvent
  3397. // Fired when the user double-clicks (or double-taps) the map.
  3398. // @event mousedown: MouseEvent
  3399. // Fired when the user pushes the mouse button on the map.
  3400. // @event mouseup: MouseEvent
  3401. // Fired when the user releases the mouse button on the map.
  3402. // @event mouseover: MouseEvent
  3403. // Fired when the mouse enters the map.
  3404. // @event mouseout: MouseEvent
  3405. // Fired when the mouse leaves the map.
  3406. // @event mousemove: MouseEvent
  3407. // Fired while the mouse moves over the map.
  3408. // @event contextmenu: MouseEvent
  3409. // Fired when the user pushes the right mouse button on the map, prevents
  3410. // default browser context menu from showing if there are listeners on
  3411. // this event. Also fired on mobile when the user holds a single touch
  3412. // for a second (also called long press).
  3413. // @event keypress: KeyboardEvent
  3414. // Fired when the user presses a key from the keyboard while the map is focused.
  3415. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3416. 'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this);
  3417. if (this.options.trackResize) {
  3418. onOff(window, 'resize', this._onResize, this);
  3419. }
  3420. if (any3d && this.options.transform3DLimit) {
  3421. (remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3422. }
  3423. },
  3424. _onResize: function () {
  3425. cancelAnimFrame(this._resizeRequest);
  3426. this._resizeRequest = requestAnimFrame(
  3427. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3428. },
  3429. _onScroll: function () {
  3430. this._container.scrollTop = 0;
  3431. this._container.scrollLeft = 0;
  3432. },
  3433. _onMoveEnd: function () {
  3434. var pos = this._getMapPanePos();
  3435. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3436. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3437. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  3438. this._resetView(this.getCenter(), this.getZoom());
  3439. }
  3440. },
  3441. _findEventTargets: function (e, type) {
  3442. var targets = [],
  3443. target,
  3444. isHover = type === 'mouseout' || type === 'mouseover',
  3445. src = e.target || e.srcElement,
  3446. dragging = false;
  3447. while (src) {
  3448. target = this._targets[stamp(src)];
  3449. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  3450. // Prevent firing click after you just dragged an object.
  3451. dragging = true;
  3452. break;
  3453. }
  3454. if (target && target.listens(type, true)) {
  3455. if (isHover && !isExternalTarget(src, e)) { break; }
  3456. targets.push(target);
  3457. if (isHover) { break; }
  3458. }
  3459. if (src === this._container) { break; }
  3460. src = src.parentNode;
  3461. }
  3462. if (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {
  3463. targets = [this];
  3464. }
  3465. return targets;
  3466. },
  3467. _handleDOMEvent: function (e) {
  3468. if (!this._loaded || skipped(e)) { return; }
  3469. var type = e.type;
  3470. if (type === 'mousedown' || type === 'keypress') {
  3471. // prevents outline when clicking on keyboard-focusable element
  3472. preventOutline(e.target || e.srcElement);
  3473. }
  3474. this._fireDOMEvent(e, type);
  3475. },
  3476. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3477. _fireDOMEvent: function (e, type, targets) {
  3478. if (e.type === 'click') {
  3479. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3480. // @event preclick: MouseEvent
  3481. // Fired before mouse click on the map (sometimes useful when you
  3482. // want something to happen on click before any existing click
  3483. // handlers start running).
  3484. var synth = extend({}, e);
  3485. synth.type = 'preclick';
  3486. this._fireDOMEvent(synth, synth.type, targets);
  3487. }
  3488. if (e._stopped) { return; }
  3489. // Find the layer the event is propagating from and its parents.
  3490. targets = (targets || []).concat(this._findEventTargets(e, type));
  3491. if (!targets.length) { return; }
  3492. var target = targets[0];
  3493. if (type === 'contextmenu' && target.listens(type, true)) {
  3494. preventDefault(e);
  3495. }
  3496. var data = {
  3497. originalEvent: e
  3498. };
  3499. if (e.type !== 'keypress') {
  3500. var isMarker = (target.options && 'icon' in target.options);
  3501. data.containerPoint = isMarker ?
  3502. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3503. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3504. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3505. }
  3506. for (var i = 0; i < targets.length; i++) {
  3507. targets[i].fire(type, data, true);
  3508. if (data.originalEvent._stopped ||
  3509. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3510. }
  3511. },
  3512. _draggableMoved: function (obj) {
  3513. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3514. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3515. },
  3516. _clearHandlers: function () {
  3517. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3518. this._handlers[i].disable();
  3519. }
  3520. },
  3521. // @section Other Methods
  3522. // @method whenReady(fn: Function, context?: Object): this
  3523. // Runs the given function `fn` when the map gets initialized with
  3524. // a view (center and zoom) and at least one layer, or immediately
  3525. // if it's already initialized, optionally passing a function context.
  3526. whenReady: function (callback, context) {
  3527. if (this._loaded) {
  3528. callback.call(context || this, {target: this});
  3529. } else {
  3530. this.on('load', callback, context);
  3531. }
  3532. return this;
  3533. },
  3534. // private methods for getting map state
  3535. _getMapPanePos: function () {
  3536. return getPosition(this._mapPane) || new Point(0, 0);
  3537. },
  3538. _moved: function () {
  3539. var pos = this._getMapPanePos();
  3540. return pos && !pos.equals([0, 0]);
  3541. },
  3542. _getTopLeftPoint: function (center, zoom) {
  3543. var pixelOrigin = center && zoom !== undefined ?
  3544. this._getNewPixelOrigin(center, zoom) :
  3545. this.getPixelOrigin();
  3546. return pixelOrigin.subtract(this._getMapPanePos());
  3547. },
  3548. _getNewPixelOrigin: function (center, zoom) {
  3549. var viewHalf = this.getSize()._divideBy(2);
  3550. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3551. },
  3552. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3553. var topLeft = this._getNewPixelOrigin(center, zoom);
  3554. return this.project(latlng, zoom)._subtract(topLeft);
  3555. },
  3556. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3557. var topLeft = this._getNewPixelOrigin(center, zoom);
  3558. return toBounds([
  3559. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3560. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3561. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3562. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3563. ]);
  3564. },
  3565. // layer point of the current center
  3566. _getCenterLayerPoint: function () {
  3567. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3568. },
  3569. // offset of the specified place to the current center in pixels
  3570. _getCenterOffset: function (latlng) {
  3571. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3572. },
  3573. // adjust center for view to get inside bounds
  3574. _limitCenter: function (center, zoom, bounds) {
  3575. if (!bounds) { return center; }
  3576. var centerPoint = this.project(center, zoom),
  3577. viewHalf = this.getSize().divideBy(2),
  3578. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3579. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3580. // If offset is less than a pixel, ignore.
  3581. // This prevents unstable projections from getting into
  3582. // an infinite loop of tiny offsets.
  3583. if (offset.round().equals([0, 0])) {
  3584. return center;
  3585. }
  3586. return this.unproject(centerPoint.add(offset), zoom);
  3587. },
  3588. // adjust offset for view to get inside bounds
  3589. _limitOffset: function (offset, bounds) {
  3590. if (!bounds) { return offset; }
  3591. var viewBounds = this.getPixelBounds(),
  3592. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3593. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3594. },
  3595. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3596. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3597. var projectedMaxBounds = toBounds(
  3598. this.project(maxBounds.getNorthEast(), zoom),
  3599. this.project(maxBounds.getSouthWest(), zoom)
  3600. ),
  3601. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3602. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3603. dx = this._rebound(minOffset.x, -maxOffset.x),
  3604. dy = this._rebound(minOffset.y, -maxOffset.y);
  3605. return new Point(dx, dy);
  3606. },
  3607. _rebound: function (left, right) {
  3608. return left + right > 0 ?
  3609. Math.round(left - right) / 2 :
  3610. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3611. },
  3612. _limitZoom: function (zoom) {
  3613. var min = this.getMinZoom(),
  3614. max = this.getMaxZoom(),
  3615. snap = any3d ? this.options.zoomSnap : 1;
  3616. if (snap) {
  3617. zoom = Math.round(zoom / snap) * snap;
  3618. }
  3619. return Math.max(min, Math.min(max, zoom));
  3620. },
  3621. _onPanTransitionStep: function () {
  3622. this.fire('move');
  3623. },
  3624. _onPanTransitionEnd: function () {
  3625. removeClass(this._mapPane, 'leaflet-pan-anim');
  3626. this.fire('moveend');
  3627. },
  3628. _tryAnimatedPan: function (center, options) {
  3629. // difference between the new and current centers in pixels
  3630. var offset = this._getCenterOffset(center)._floor();
  3631. // don't animate too far unless animate: true specified in options
  3632. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3633. this.panBy(offset, options);
  3634. return true;
  3635. },
  3636. _createAnimProxy: function () {
  3637. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3638. this._panes.mapPane.appendChild(proxy);
  3639. this.on('zoomanim', function (e) {
  3640. var prop = TRANSFORM,
  3641. transform = this._proxy.style[prop];
  3642. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3643. // workaround for case when transform is the same and so transitionend event is not fired
  3644. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3645. this._onZoomTransitionEnd();
  3646. }
  3647. }, this);
  3648. this.on('load moveend', function () {
  3649. var c = this.getCenter(),
  3650. z = this.getZoom();
  3651. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3652. }, this);
  3653. this._on('unload', this._destroyAnimProxy, this);
  3654. },
  3655. _destroyAnimProxy: function () {
  3656. remove(this._proxy);
  3657. delete this._proxy;
  3658. },
  3659. _catchTransitionEnd: function (e) {
  3660. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3661. this._onZoomTransitionEnd();
  3662. }
  3663. },
  3664. _nothingToAnimate: function () {
  3665. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3666. },
  3667. _tryAnimatedZoom: function (center, zoom, options) {
  3668. if (this._animatingZoom) { return true; }
  3669. options = options || {};
  3670. // don't animate if disabled, not supported or zoom difference is too large
  3671. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3672. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3673. // offset is the pixel coords of the zoom origin relative to the current center
  3674. var scale = this.getZoomScale(zoom),
  3675. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3676. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3677. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3678. requestAnimFrame(function () {
  3679. this
  3680. ._moveStart(true)
  3681. ._animateZoom(center, zoom, true);
  3682. }, this);
  3683. return true;
  3684. },
  3685. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3686. if (startAnim) {
  3687. this._animatingZoom = true;
  3688. // remember what center/zoom to set after animation
  3689. this._animateToCenter = center;
  3690. this._animateToZoom = zoom;
  3691. addClass(this._mapPane, 'leaflet-zoom-anim');
  3692. }
  3693. // @event zoomanim: ZoomAnimEvent
  3694. // Fired on every frame of a zoom animation
  3695. this.fire('zoomanim', {
  3696. center: center,
  3697. zoom: zoom,
  3698. noUpdate: noUpdate
  3699. });
  3700. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3701. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3702. },
  3703. _onZoomTransitionEnd: function () {
  3704. if (!this._animatingZoom) { return; }
  3705. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3706. this._animatingZoom = false;
  3707. this._move(this._animateToCenter, this._animateToZoom);
  3708. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  3709. requestAnimFrame(function () {
  3710. this._moveEnd(true);
  3711. }, this);
  3712. }
  3713. });
  3714. // @section
  3715. // @factory L.map(id: String, options?: Map options)
  3716. // Instantiates a map object given the DOM ID of a `<div>` element
  3717. // and optionally an object literal with `Map options`.
  3718. //
  3719. // @alternative
  3720. // @factory L.map(el: HTMLElement, options?: Map options)
  3721. // Instantiates a map object given an instance of a `<div>` HTML element
  3722. // and optionally an object literal with `Map options`.
  3723. function createMap(id, options) {
  3724. return new Map(id, options);
  3725. }
  3726. /*
  3727. * @class Control
  3728. * @aka L.Control
  3729. * @inherits Class
  3730. *
  3731. * L.Control is a base class for implementing map controls. Handles positioning.
  3732. * All other controls extend from this class.
  3733. */
  3734. var Control = Class.extend({
  3735. // @section
  3736. // @aka Control options
  3737. options: {
  3738. // @option position: String = 'topright'
  3739. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  3740. // `'topright'`, `'bottomleft'` or `'bottomright'`
  3741. position: 'topright'
  3742. },
  3743. initialize: function (options) {
  3744. setOptions(this, options);
  3745. },
  3746. /* @section
  3747. * Classes extending L.Control will inherit the following methods:
  3748. *
  3749. * @method getPosition: string
  3750. * Returns the position of the control.
  3751. */
  3752. getPosition: function () {
  3753. return this.options.position;
  3754. },
  3755. // @method setPosition(position: string): this
  3756. // Sets the position of the control.
  3757. setPosition: function (position) {
  3758. var map = this._map;
  3759. if (map) {
  3760. map.removeControl(this);
  3761. }
  3762. this.options.position = position;
  3763. if (map) {
  3764. map.addControl(this);
  3765. }
  3766. return this;
  3767. },
  3768. // @method getContainer: HTMLElement
  3769. // Returns the HTMLElement that contains the control.
  3770. getContainer: function () {
  3771. return this._container;
  3772. },
  3773. // @method addTo(map: Map): this
  3774. // Adds the control to the given map.
  3775. addTo: function (map) {
  3776. this.remove();
  3777. this._map = map;
  3778. var container = this._container = this.onAdd(map),
  3779. pos = this.getPosition(),
  3780. corner = map._controlCorners[pos];
  3781. addClass(container, 'leaflet-control');
  3782. if (pos.indexOf('bottom') !== -1) {
  3783. corner.insertBefore(container, corner.firstChild);
  3784. } else {
  3785. corner.appendChild(container);
  3786. }
  3787. return this;
  3788. },
  3789. // @method remove: this
  3790. // Removes the control from the map it is currently active on.
  3791. remove: function () {
  3792. if (!this._map) {
  3793. return this;
  3794. }
  3795. remove(this._container);
  3796. if (this.onRemove) {
  3797. this.onRemove(this._map);
  3798. }
  3799. this._map = null;
  3800. return this;
  3801. },
  3802. _refocusOnMap: function (e) {
  3803. // if map exists and event is not a keyboard event
  3804. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  3805. this._map.getContainer().focus();
  3806. }
  3807. }
  3808. });
  3809. var control = function (options) {
  3810. return new Control(options);
  3811. };
  3812. /* @section Extension methods
  3813. * @uninheritable
  3814. *
  3815. * Every control should extend from `L.Control` and (re-)implement the following methods.
  3816. *
  3817. * @method onAdd(map: Map): HTMLElement
  3818. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  3819. *
  3820. * @method onRemove(map: Map)
  3821. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  3822. */
  3823. /* @namespace Map
  3824. * @section Methods for Layers and Controls
  3825. */
  3826. Map.include({
  3827. // @method addControl(control: Control): this
  3828. // Adds the given control to the map
  3829. addControl: function (control) {
  3830. control.addTo(this);
  3831. return this;
  3832. },
  3833. // @method removeControl(control: Control): this
  3834. // Removes the given control from the map
  3835. removeControl: function (control) {
  3836. control.remove();
  3837. return this;
  3838. },
  3839. _initControlPos: function () {
  3840. var corners = this._controlCorners = {},
  3841. l = 'leaflet-',
  3842. container = this._controlContainer =
  3843. create$1('div', l + 'control-container', this._container);
  3844. function createCorner(vSide, hSide) {
  3845. var className = l + vSide + ' ' + l + hSide;
  3846. corners[vSide + hSide] = create$1('div', className, container);
  3847. }
  3848. createCorner('top', 'left');
  3849. createCorner('top', 'right');
  3850. createCorner('bottom', 'left');
  3851. createCorner('bottom', 'right');
  3852. },
  3853. _clearControlPos: function () {
  3854. for (var i in this._controlCorners) {
  3855. remove(this._controlCorners[i]);
  3856. }
  3857. remove(this._controlContainer);
  3858. delete this._controlCorners;
  3859. delete this._controlContainer;
  3860. }
  3861. });
  3862. /*
  3863. * @class Control.Layers
  3864. * @aka L.Control.Layers
  3865. * @inherits Control
  3866. *
  3867. * 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/)). Extends `Control`.
  3868. *
  3869. * @example
  3870. *
  3871. * ```js
  3872. * var baseLayers = {
  3873. * "Mapbox": mapbox,
  3874. * "OpenStreetMap": osm
  3875. * };
  3876. *
  3877. * var overlays = {
  3878. * "Marker": marker,
  3879. * "Roads": roadsLayer
  3880. * };
  3881. *
  3882. * L.control.layers(baseLayers, overlays).addTo(map);
  3883. * ```
  3884. *
  3885. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  3886. *
  3887. * ```js
  3888. * {
  3889. * "<someName1>": layer1,
  3890. * "<someName2>": layer2
  3891. * }
  3892. * ```
  3893. *
  3894. * The layer names can contain HTML, which allows you to add additional styling to the items:
  3895. *
  3896. * ```js
  3897. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  3898. * ```
  3899. */
  3900. var Layers = Control.extend({
  3901. // @section
  3902. // @aka Control.Layers options
  3903. options: {
  3904. // @option collapsed: Boolean = true
  3905. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  3906. collapsed: true,
  3907. position: 'topright',
  3908. // @option autoZIndex: Boolean = true
  3909. // 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.
  3910. autoZIndex: true,
  3911. // @option hideSingleBase: Boolean = false
  3912. // If `true`, the base layers in the control will be hidden when there is only one.
  3913. hideSingleBase: false,
  3914. // @option sortLayers: Boolean = false
  3915. // Whether to sort the layers. When `false`, layers will keep the order
  3916. // in which they were added to the control.
  3917. sortLayers: false,
  3918. // @option sortFunction: Function = *
  3919. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  3920. // that will be used for sorting the layers, when `sortLayers` is `true`.
  3921. // The function receives both the `L.Layer` instances and their names, as in
  3922. // `sortFunction(layerA, layerB, nameA, nameB)`.
  3923. // By default, it sorts layers alphabetically by their name.
  3924. sortFunction: function (layerA, layerB, nameA, nameB) {
  3925. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  3926. }
  3927. },
  3928. initialize: function (baseLayers, overlays, options) {
  3929. setOptions(this, options);
  3930. this._layerControlInputs = [];
  3931. this._layers = [];
  3932. this._lastZIndex = 0;
  3933. this._handlingClick = false;
  3934. for (var i in baseLayers) {
  3935. this._addLayer(baseLayers[i], i);
  3936. }
  3937. for (i in overlays) {
  3938. this._addLayer(overlays[i], i, true);
  3939. }
  3940. },
  3941. onAdd: function (map) {
  3942. this._initLayout();
  3943. this._update();
  3944. this._map = map;
  3945. map.on('zoomend', this._checkDisabledLayers, this);
  3946. for (var i = 0; i < this._layers.length; i++) {
  3947. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  3948. }
  3949. return this._container;
  3950. },
  3951. addTo: function (map) {
  3952. Control.prototype.addTo.call(this, map);
  3953. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  3954. return this._expandIfNotCollapsed();
  3955. },
  3956. onRemove: function () {
  3957. this._map.off('zoomend', this._checkDisabledLayers, this);
  3958. for (var i = 0; i < this._layers.length; i++) {
  3959. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  3960. }
  3961. },
  3962. // @method addBaseLayer(layer: Layer, name: String): this
  3963. // Adds a base layer (radio button entry) with the given name to the control.
  3964. addBaseLayer: function (layer, name) {
  3965. this._addLayer(layer, name);
  3966. return (this._map) ? this._update() : this;
  3967. },
  3968. // @method addOverlay(layer: Layer, name: String): this
  3969. // Adds an overlay (checkbox entry) with the given name to the control.
  3970. addOverlay: function (layer, name) {
  3971. this._addLayer(layer, name, true);
  3972. return (this._map) ? this._update() : this;
  3973. },
  3974. // @method removeLayer(layer: Layer): this
  3975. // Remove the given layer from the control.
  3976. removeLayer: function (layer) {
  3977. layer.off('add remove', this._onLayerChange, this);
  3978. var obj = this._getLayer(stamp(layer));
  3979. if (obj) {
  3980. this._layers.splice(this._layers.indexOf(obj), 1);
  3981. }
  3982. return (this._map) ? this._update() : this;
  3983. },
  3984. // @method expand(): this
  3985. // Expand the control container if collapsed.
  3986. expand: function () {
  3987. addClass(this._container, 'leaflet-control-layers-expanded');
  3988. this._form.style.height = null;
  3989. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  3990. if (acceptableHeight < this._form.clientHeight) {
  3991. addClass(this._form, 'leaflet-control-layers-scrollbar');
  3992. this._form.style.height = acceptableHeight + 'px';
  3993. } else {
  3994. removeClass(this._form, 'leaflet-control-layers-scrollbar');
  3995. }
  3996. this._checkDisabledLayers();
  3997. return this;
  3998. },
  3999. // @method collapse(): this
  4000. // Collapse the control container if expanded.
  4001. collapse: function () {
  4002. removeClass(this._container, 'leaflet-control-layers-expanded');
  4003. return this;
  4004. },
  4005. _initLayout: function () {
  4006. var className = 'leaflet-control-layers',
  4007. container = this._container = create$1('div', className),
  4008. collapsed = this.options.collapsed;
  4009. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4010. container.setAttribute('aria-haspopup', true);
  4011. disableClickPropagation(container);
  4012. disableScrollPropagation(container);
  4013. var form = this._form = create$1('form', className + '-list');
  4014. if (collapsed) {
  4015. this._map.on('click', this.collapse, this);
  4016. if (!android) {
  4017. on(container, {
  4018. mouseenter: this.expand,
  4019. mouseleave: this.collapse
  4020. }, this);
  4021. }
  4022. }
  4023. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4024. link.href = '#';
  4025. link.title = 'Layers';
  4026. if (touch) {
  4027. on(link, 'click', stop);
  4028. on(link, 'click', this.expand, this);
  4029. } else {
  4030. on(link, 'focus', this.expand, this);
  4031. }
  4032. if (!collapsed) {
  4033. this.expand();
  4034. }
  4035. this._baseLayersList = create$1('div', className + '-base', form);
  4036. this._separator = create$1('div', className + '-separator', form);
  4037. this._overlaysList = create$1('div', className + '-overlays', form);
  4038. container.appendChild(form);
  4039. },
  4040. _getLayer: function (id) {
  4041. for (var i = 0; i < this._layers.length; i++) {
  4042. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4043. return this._layers[i];
  4044. }
  4045. }
  4046. },
  4047. _addLayer: function (layer, name, overlay) {
  4048. if (this._map) {
  4049. layer.on('add remove', this._onLayerChange, this);
  4050. }
  4051. this._layers.push({
  4052. layer: layer,
  4053. name: name,
  4054. overlay: overlay
  4055. });
  4056. if (this.options.sortLayers) {
  4057. this._layers.sort(bind(function (a, b) {
  4058. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4059. }, this));
  4060. }
  4061. if (this.options.autoZIndex && layer.setZIndex) {
  4062. this._lastZIndex++;
  4063. layer.setZIndex(this._lastZIndex);
  4064. }
  4065. this._expandIfNotCollapsed();
  4066. },
  4067. _update: function () {
  4068. if (!this._container) { return this; }
  4069. empty(this._baseLayersList);
  4070. empty(this._overlaysList);
  4071. this._layerControlInputs = [];
  4072. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4073. for (i = 0; i < this._layers.length; i++) {
  4074. obj = this._layers[i];
  4075. this._addItem(obj);
  4076. overlaysPresent = overlaysPresent || obj.overlay;
  4077. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4078. baseLayersCount += !obj.overlay ? 1 : 0;
  4079. }
  4080. // Hide base layers section if there's only one layer.
  4081. if (this.options.hideSingleBase) {
  4082. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4083. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4084. }
  4085. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4086. return this;
  4087. },
  4088. _onLayerChange: function (e) {
  4089. if (!this._handlingClick) {
  4090. this._update();
  4091. }
  4092. var obj = this._getLayer(stamp(e.target));
  4093. // @namespace Map
  4094. // @section Layer events
  4095. // @event baselayerchange: LayersControlEvent
  4096. // Fired when the base layer is changed through the [layer control](#control-layers).
  4097. // @event overlayadd: LayersControlEvent
  4098. // Fired when an overlay is selected through the [layer control](#control-layers).
  4099. // @event overlayremove: LayersControlEvent
  4100. // Fired when an overlay is deselected through the [layer control](#control-layers).
  4101. // @namespace Control.Layers
  4102. var type = obj.overlay ?
  4103. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4104. (e.type === 'add' ? 'baselayerchange' : null);
  4105. if (type) {
  4106. this._map.fire(type, obj);
  4107. }
  4108. },
  4109. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  4110. _createRadioElement: function (name, checked) {
  4111. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4112. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4113. var radioFragment = document.createElement('div');
  4114. radioFragment.innerHTML = radioHtml;
  4115. return radioFragment.firstChild;
  4116. },
  4117. _addItem: function (obj) {
  4118. var label = document.createElement('label'),
  4119. checked = this._map.hasLayer(obj.layer),
  4120. input;
  4121. if (obj.overlay) {
  4122. input = document.createElement('input');
  4123. input.type = 'checkbox';
  4124. input.className = 'leaflet-control-layers-selector';
  4125. input.defaultChecked = checked;
  4126. } else {
  4127. input = this._createRadioElement('leaflet-base-layers', checked);
  4128. }
  4129. this._layerControlInputs.push(input);
  4130. input.layerId = stamp(obj.layer);
  4131. on(input, 'click', this._onInputClick, this);
  4132. var name = document.createElement('span');
  4133. name.innerHTML = ' ' + obj.name;
  4134. // Helps from preventing layer control flicker when checkboxes are disabled
  4135. // https://github.com/Leaflet/Leaflet/issues/2771
  4136. var holder = document.createElement('div');
  4137. label.appendChild(holder);
  4138. holder.appendChild(input);
  4139. holder.appendChild(name);
  4140. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4141. container.appendChild(label);
  4142. this._checkDisabledLayers();
  4143. return label;
  4144. },
  4145. _onInputClick: function () {
  4146. var inputs = this._layerControlInputs,
  4147. input, layer;
  4148. var addedLayers = [],
  4149. removedLayers = [];
  4150. this._handlingClick = true;
  4151. for (var i = inputs.length - 1; i >= 0; i--) {
  4152. input = inputs[i];
  4153. layer = this._getLayer(input.layerId).layer;
  4154. if (input.checked) {
  4155. addedLayers.push(layer);
  4156. } else if (!input.checked) {
  4157. removedLayers.push(layer);
  4158. }
  4159. }
  4160. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4161. for (i = 0; i < removedLayers.length; i++) {
  4162. if (this._map.hasLayer(removedLayers[i])) {
  4163. this._map.removeLayer(removedLayers[i]);
  4164. }
  4165. }
  4166. for (i = 0; i < addedLayers.length; i++) {
  4167. if (!this._map.hasLayer(addedLayers[i])) {
  4168. this._map.addLayer(addedLayers[i]);
  4169. }
  4170. }
  4171. this._handlingClick = false;
  4172. this._refocusOnMap();
  4173. },
  4174. _checkDisabledLayers: function () {
  4175. var inputs = this._layerControlInputs,
  4176. input,
  4177. layer,
  4178. zoom = this._map.getZoom();
  4179. for (var i = inputs.length - 1; i >= 0; i--) {
  4180. input = inputs[i];
  4181. layer = this._getLayer(input.layerId).layer;
  4182. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4183. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4184. }
  4185. },
  4186. _expandIfNotCollapsed: function () {
  4187. if (this._map && !this.options.collapsed) {
  4188. this.expand();
  4189. }
  4190. return this;
  4191. },
  4192. _expand: function () {
  4193. // Backward compatibility, remove me in 1.1.
  4194. return this.expand();
  4195. },
  4196. _collapse: function () {
  4197. // Backward compatibility, remove me in 1.1.
  4198. return this.collapse();
  4199. }
  4200. });
  4201. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4202. // 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.
  4203. var layers = function (baseLayers, overlays, options) {
  4204. return new Layers(baseLayers, overlays, options);
  4205. };
  4206. /*
  4207. * @class Control.Zoom
  4208. * @aka L.Control.Zoom
  4209. * @inherits Control
  4210. *
  4211. * 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`.
  4212. */
  4213. var Zoom = Control.extend({
  4214. // @section
  4215. // @aka Control.Zoom options
  4216. options: {
  4217. position: 'topleft',
  4218. // @option zoomInText: String = '+'
  4219. // The text set on the 'zoom in' button.
  4220. zoomInText: '+',
  4221. // @option zoomInTitle: String = 'Zoom in'
  4222. // The title set on the 'zoom in' button.
  4223. zoomInTitle: 'Zoom in',
  4224. // @option zoomOutText: String = '&#x2212;'
  4225. // The text set on the 'zoom out' button.
  4226. zoomOutText: '&#x2212;',
  4227. // @option zoomOutTitle: String = 'Zoom out'
  4228. // The title set on the 'zoom out' button.
  4229. zoomOutTitle: 'Zoom out'
  4230. },
  4231. onAdd: function (map) {
  4232. var zoomName = 'leaflet-control-zoom',
  4233. container = create$1('div', zoomName + ' leaflet-bar'),
  4234. options = this.options;
  4235. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4236. zoomName + '-in', container, this._zoomIn);
  4237. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4238. zoomName + '-out', container, this._zoomOut);
  4239. this._updateDisabled();
  4240. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4241. return container;
  4242. },
  4243. onRemove: function (map) {
  4244. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4245. },
  4246. disable: function () {
  4247. this._disabled = true;
  4248. this._updateDisabled();
  4249. return this;
  4250. },
  4251. enable: function () {
  4252. this._disabled = false;
  4253. this._updateDisabled();
  4254. return this;
  4255. },
  4256. _zoomIn: function (e) {
  4257. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4258. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4259. }
  4260. },
  4261. _zoomOut: function (e) {
  4262. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4263. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4264. }
  4265. },
  4266. _createButton: function (html, title, className, container, fn) {
  4267. var link = create$1('a', className, container);
  4268. link.innerHTML = html;
  4269. link.href = '#';
  4270. link.title = title;
  4271. /*
  4272. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4273. */
  4274. link.setAttribute('role', 'button');
  4275. link.setAttribute('aria-label', title);
  4276. disableClickPropagation(link);
  4277. on(link, 'click', stop);
  4278. on(link, 'click', fn, this);
  4279. on(link, 'click', this._refocusOnMap, this);
  4280. return link;
  4281. },
  4282. _updateDisabled: function () {
  4283. var map = this._map,
  4284. className = 'leaflet-disabled';
  4285. removeClass(this._zoomInButton, className);
  4286. removeClass(this._zoomOutButton, className);
  4287. if (this._disabled || map._zoom === map.getMinZoom()) {
  4288. addClass(this._zoomOutButton, className);
  4289. }
  4290. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4291. addClass(this._zoomInButton, className);
  4292. }
  4293. }
  4294. });
  4295. // @namespace Map
  4296. // @section Control options
  4297. // @option zoomControl: Boolean = true
  4298. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4299. Map.mergeOptions({
  4300. zoomControl: true
  4301. });
  4302. Map.addInitHook(function () {
  4303. if (this.options.zoomControl) {
  4304. this.zoomControl = new Zoom();
  4305. this.addControl(this.zoomControl);
  4306. }
  4307. });
  4308. // @namespace Control.Zoom
  4309. // @factory L.control.zoom(options: Control.Zoom options)
  4310. // Creates a zoom control
  4311. var zoom = function (options) {
  4312. return new Zoom(options);
  4313. };
  4314. /*
  4315. * @class Control.Scale
  4316. * @aka L.Control.Scale
  4317. * @inherits Control
  4318. *
  4319. * 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`.
  4320. *
  4321. * @example
  4322. *
  4323. * ```js
  4324. * L.control.scale().addTo(map);
  4325. * ```
  4326. */
  4327. var Scale = Control.extend({
  4328. // @section
  4329. // @aka Control.Scale options
  4330. options: {
  4331. position: 'bottomleft',
  4332. // @option maxWidth: Number = 100
  4333. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4334. maxWidth: 100,
  4335. // @option metric: Boolean = True
  4336. // Whether to show the metric scale line (m/km).
  4337. metric: true,
  4338. // @option imperial: Boolean = True
  4339. // Whether to show the imperial scale line (mi/ft).
  4340. imperial: true
  4341. // @option updateWhenIdle: Boolean = false
  4342. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4343. },
  4344. onAdd: function (map) {
  4345. var className = 'leaflet-control-scale',
  4346. container = create$1('div', className),
  4347. options = this.options;
  4348. this._addScales(options, className + '-line', container);
  4349. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4350. map.whenReady(this._update, this);
  4351. return container;
  4352. },
  4353. onRemove: function (map) {
  4354. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4355. },
  4356. _addScales: function (options, className, container) {
  4357. if (options.metric) {
  4358. this._mScale = create$1('div', className, container);
  4359. }
  4360. if (options.imperial) {
  4361. this._iScale = create$1('div', className, container);
  4362. }
  4363. },
  4364. _update: function () {
  4365. var map = this._map,
  4366. y = map.getSize().y / 2;
  4367. var maxMeters = map.distance(
  4368. map.containerPointToLatLng([0, y]),
  4369. map.containerPointToLatLng([this.options.maxWidth, y]));
  4370. this._updateScales(maxMeters);
  4371. },
  4372. _updateScales: function (maxMeters) {
  4373. if (this.options.metric && maxMeters) {
  4374. this._updateMetric(maxMeters);
  4375. }
  4376. if (this.options.imperial && maxMeters) {
  4377. this._updateImperial(maxMeters);
  4378. }
  4379. },
  4380. _updateMetric: function (maxMeters) {
  4381. var meters = this._getRoundNum(maxMeters),
  4382. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4383. this._updateScale(this._mScale, label, meters / maxMeters);
  4384. },
  4385. _updateImperial: function (maxMeters) {
  4386. var maxFeet = maxMeters * 3.2808399,
  4387. maxMiles, miles, feet;
  4388. if (maxFeet > 5280) {
  4389. maxMiles = maxFeet / 5280;
  4390. miles = this._getRoundNum(maxMiles);
  4391. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4392. } else {
  4393. feet = this._getRoundNum(maxFeet);
  4394. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4395. }
  4396. },
  4397. _updateScale: function (scale, text, ratio) {
  4398. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4399. scale.innerHTML = text;
  4400. },
  4401. _getRoundNum: function (num) {
  4402. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4403. d = num / pow10;
  4404. d = d >= 10 ? 10 :
  4405. d >= 5 ? 5 :
  4406. d >= 3 ? 3 :
  4407. d >= 2 ? 2 : 1;
  4408. return pow10 * d;
  4409. }
  4410. });
  4411. // @factory L.control.scale(options?: Control.Scale options)
  4412. // Creates an scale control with the given options.
  4413. var scale = function (options) {
  4414. return new Scale(options);
  4415. };
  4416. /*
  4417. * @class Control.Attribution
  4418. * @aka L.Control.Attribution
  4419. * @inherits Control
  4420. *
  4421. * 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.
  4422. */
  4423. var Attribution = Control.extend({
  4424. // @section
  4425. // @aka Control.Attribution options
  4426. options: {
  4427. position: 'bottomright',
  4428. // @option prefix: String = 'Leaflet'
  4429. // The HTML text shown before the attributions. Pass `false` to disable.
  4430. prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  4431. },
  4432. initialize: function (options) {
  4433. setOptions(this, options);
  4434. this._attributions = {};
  4435. },
  4436. onAdd: function (map) {
  4437. map.attributionControl = this;
  4438. this._container = create$1('div', 'leaflet-control-attribution');
  4439. disableClickPropagation(this._container);
  4440. // TODO ugly, refactor
  4441. for (var i in map._layers) {
  4442. if (map._layers[i].getAttribution) {
  4443. this.addAttribution(map._layers[i].getAttribution());
  4444. }
  4445. }
  4446. this._update();
  4447. return this._container;
  4448. },
  4449. // @method setPrefix(prefix: String): this
  4450. // Sets the text before the attributions.
  4451. setPrefix: function (prefix) {
  4452. this.options.prefix = prefix;
  4453. this._update();
  4454. return this;
  4455. },
  4456. // @method addAttribution(text: String): this
  4457. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  4458. addAttribution: function (text) {
  4459. if (!text) { return this; }
  4460. if (!this._attributions[text]) {
  4461. this._attributions[text] = 0;
  4462. }
  4463. this._attributions[text]++;
  4464. this._update();
  4465. return this;
  4466. },
  4467. // @method removeAttribution(text: String): this
  4468. // Removes an attribution text.
  4469. removeAttribution: function (text) {
  4470. if (!text) { return this; }
  4471. if (this._attributions[text]) {
  4472. this._attributions[text]--;
  4473. this._update();
  4474. }
  4475. return this;
  4476. },
  4477. _update: function () {
  4478. if (!this._map) { return; }
  4479. var attribs = [];
  4480. for (var i in this._attributions) {
  4481. if (this._attributions[i]) {
  4482. attribs.push(i);
  4483. }
  4484. }
  4485. var prefixAndAttribs = [];
  4486. if (this.options.prefix) {
  4487. prefixAndAttribs.push(this.options.prefix);
  4488. }
  4489. if (attribs.length) {
  4490. prefixAndAttribs.push(attribs.join(', '));
  4491. }
  4492. this._container.innerHTML = prefixAndAttribs.join(' | ');
  4493. }
  4494. });
  4495. // @namespace Map
  4496. // @section Control options
  4497. // @option attributionControl: Boolean = true
  4498. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4499. Map.mergeOptions({
  4500. attributionControl: true
  4501. });
  4502. Map.addInitHook(function () {
  4503. if (this.options.attributionControl) {
  4504. new Attribution().addTo(this);
  4505. }
  4506. });
  4507. // @namespace Control.Attribution
  4508. // @factory L.control.attribution(options: Control.Attribution options)
  4509. // Creates an attribution control.
  4510. var attribution = function (options) {
  4511. return new Attribution(options);
  4512. };
  4513. Control.Layers = Layers;
  4514. Control.Zoom = Zoom;
  4515. Control.Scale = Scale;
  4516. Control.Attribution = Attribution;
  4517. control.layers = layers;
  4518. control.zoom = zoom;
  4519. control.scale = scale;
  4520. control.attribution = attribution;
  4521. /*
  4522. L.Handler is a base class for handler classes that are used internally to inject
  4523. interaction features like dragging to classes like Map and Marker.
  4524. */
  4525. // @class Handler
  4526. // @aka L.Handler
  4527. // Abstract class for map interaction handlers
  4528. var Handler = Class.extend({
  4529. initialize: function (map) {
  4530. this._map = map;
  4531. },
  4532. // @method enable(): this
  4533. // Enables the handler
  4534. enable: function () {
  4535. if (this._enabled) { return this; }
  4536. this._enabled = true;
  4537. this.addHooks();
  4538. return this;
  4539. },
  4540. // @method disable(): this
  4541. // Disables the handler
  4542. disable: function () {
  4543. if (!this._enabled) { return this; }
  4544. this._enabled = false;
  4545. this.removeHooks();
  4546. return this;
  4547. },
  4548. // @method enabled(): Boolean
  4549. // Returns `true` if the handler is enabled
  4550. enabled: function () {
  4551. return !!this._enabled;
  4552. }
  4553. // @section Extension methods
  4554. // Classes inheriting from `Handler` must implement the two following methods:
  4555. // @method addHooks()
  4556. // Called when the handler is enabled, should add event hooks.
  4557. // @method removeHooks()
  4558. // Called when the handler is disabled, should remove the event hooks added previously.
  4559. });
  4560. var Mixin = {Events: Events};
  4561. /*
  4562. * @class Draggable
  4563. * @aka L.Draggable
  4564. * @inherits Evented
  4565. *
  4566. * A class for making DOM elements draggable (including touch support).
  4567. * Used internally for map and marker dragging. Only works for elements
  4568. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4569. *
  4570. * @example
  4571. * ```js
  4572. * var draggable = new L.Draggable(elementToDrag);
  4573. * draggable.enable();
  4574. * ```
  4575. */
  4576. var START = touch ? 'touchstart mousedown' : 'mousedown';
  4577. var END = {
  4578. mousedown: 'mouseup',
  4579. touchstart: 'touchend',
  4580. pointerdown: 'touchend',
  4581. MSPointerDown: 'touchend'
  4582. };
  4583. var MOVE = {
  4584. mousedown: 'mousemove',
  4585. touchstart: 'touchmove',
  4586. pointerdown: 'touchmove',
  4587. MSPointerDown: 'touchmove'
  4588. };
  4589. var Draggable = Evented.extend({
  4590. options: {
  4591. // @section
  4592. // @aka Draggable options
  4593. // @option clickTolerance: Number = 3
  4594. // The max number of pixels a user can shift the mouse pointer during a click
  4595. // for it to be considered a valid click (as opposed to a mouse drag).
  4596. clickTolerance: 3
  4597. },
  4598. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4599. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4600. initialize: function (element, dragStartTarget, preventOutline$$1, options) {
  4601. setOptions(this, options);
  4602. this._element = element;
  4603. this._dragStartTarget = dragStartTarget || element;
  4604. this._preventOutline = preventOutline$$1;
  4605. },
  4606. // @method enable()
  4607. // Enables the dragging ability
  4608. enable: function () {
  4609. if (this._enabled) { return; }
  4610. on(this._dragStartTarget, START, this._onDown, this);
  4611. this._enabled = true;
  4612. },
  4613. // @method disable()
  4614. // Disables the dragging ability
  4615. disable: function () {
  4616. if (!this._enabled) { return; }
  4617. // If we're currently dragging this draggable,
  4618. // disabling it counts as first ending the drag.
  4619. if (Draggable._dragging === this) {
  4620. this.finishDrag();
  4621. }
  4622. off(this._dragStartTarget, START, this._onDown, this);
  4623. this._enabled = false;
  4624. this._moved = false;
  4625. },
  4626. _onDown: function (e) {
  4627. // Ignore simulated events, since we handle both touch and
  4628. // mouse explicitly; otherwise we risk getting duplicates of
  4629. // touch events, see #4315.
  4630. // Also ignore the event if disabled; this happens in IE11
  4631. // under some circumstances, see #3666.
  4632. if (e._simulated || !this._enabled) { return; }
  4633. this._moved = false;
  4634. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4635. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4636. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4637. if (this._preventOutline) {
  4638. preventOutline(this._element);
  4639. }
  4640. disableImageDrag();
  4641. disableTextSelection();
  4642. if (this._moving) { return; }
  4643. // @event down: Event
  4644. // Fired when a drag is about to start.
  4645. this.fire('down');
  4646. var first = e.touches ? e.touches[0] : e;
  4647. this._startPoint = new Point(first.clientX, first.clientY);
  4648. on(document, MOVE[e.type], this._onMove, this);
  4649. on(document, END[e.type], this._onUp, this);
  4650. },
  4651. _onMove: function (e) {
  4652. // Ignore simulated events, since we handle both touch and
  4653. // mouse explicitly; otherwise we risk getting duplicates of
  4654. // touch events, see #4315.
  4655. // Also ignore the event if disabled; this happens in IE11
  4656. // under some circumstances, see #3666.
  4657. if (e._simulated || !this._enabled) { return; }
  4658. if (e.touches && e.touches.length > 1) {
  4659. this._moved = true;
  4660. return;
  4661. }
  4662. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4663. newPoint = new Point(first.clientX, first.clientY),
  4664. offset = newPoint.subtract(this._startPoint);
  4665. if (!offset.x && !offset.y) { return; }
  4666. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4667. preventDefault(e);
  4668. if (!this._moved) {
  4669. // @event dragstart: Event
  4670. // Fired when a drag starts
  4671. this.fire('dragstart');
  4672. this._moved = true;
  4673. this._startPos = getPosition(this._element).subtract(offset);
  4674. addClass(document.body, 'leaflet-dragging');
  4675. this._lastTarget = e.target || e.srcElement;
  4676. // IE and Edge do not give the <use> element, so fetch it
  4677. // if necessary
  4678. if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
  4679. this._lastTarget = this._lastTarget.correspondingUseElement;
  4680. }
  4681. addClass(this._lastTarget, 'leaflet-drag-target');
  4682. }
  4683. this._newPos = this._startPos.add(offset);
  4684. this._moving = true;
  4685. cancelAnimFrame(this._animRequest);
  4686. this._lastEvent = e;
  4687. this._animRequest = requestAnimFrame(this._updatePosition, this, true);
  4688. },
  4689. _updatePosition: function () {
  4690. var e = {originalEvent: this._lastEvent};
  4691. // @event predrag: Event
  4692. // Fired continuously during dragging *before* each corresponding
  4693. // update of the element's position.
  4694. this.fire('predrag', e);
  4695. setPosition(this._element, this._newPos);
  4696. // @event drag: Event
  4697. // Fired continuously during dragging.
  4698. this.fire('drag', e);
  4699. },
  4700. _onUp: function (e) {
  4701. // Ignore simulated events, since we handle both touch and
  4702. // mouse explicitly; otherwise we risk getting duplicates of
  4703. // touch events, see #4315.
  4704. // Also ignore the event if disabled; this happens in IE11
  4705. // under some circumstances, see #3666.
  4706. if (e._simulated || !this._enabled) { return; }
  4707. this.finishDrag();
  4708. },
  4709. finishDrag: function () {
  4710. removeClass(document.body, 'leaflet-dragging');
  4711. if (this._lastTarget) {
  4712. removeClass(this._lastTarget, 'leaflet-drag-target');
  4713. this._lastTarget = null;
  4714. }
  4715. for (var i in MOVE) {
  4716. off(document, MOVE[i], this._onMove, this);
  4717. off(document, END[i], this._onUp, this);
  4718. }
  4719. enableImageDrag();
  4720. enableTextSelection();
  4721. if (this._moved && this._moving) {
  4722. // ensure drag is not fired after dragend
  4723. cancelAnimFrame(this._animRequest);
  4724. // @event dragend: DragEndEvent
  4725. // Fired when the drag ends.
  4726. this.fire('dragend', {
  4727. distance: this._newPos.distanceTo(this._startPos)
  4728. });
  4729. }
  4730. this._moving = false;
  4731. Draggable._dragging = false;
  4732. }
  4733. });
  4734. /*
  4735. * @namespace LineUtil
  4736. *
  4737. * Various utility functions for polyine points processing, used by Leaflet internally to make polylines lightning-fast.
  4738. */
  4739. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  4740. // Improves rendering performance dramatically by lessening the number of points to draw.
  4741. // @function simplify(points: Point[], tolerance: Number): Point[]
  4742. // Dramatically reduces the number of points in a polyline while retaining
  4743. // its shape and returns a new array of simplified points, using the
  4744. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  4745. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  4746. // each zoom level and also reducing visual noise. tolerance affects the amount of
  4747. // simplification (lesser value means higher quality but slower and with more points).
  4748. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  4749. function simplify(points, tolerance) {
  4750. if (!tolerance || !points.length) {
  4751. return points.slice();
  4752. }
  4753. var sqTolerance = tolerance * tolerance;
  4754. // stage 1: vertex reduction
  4755. points = _reducePoints(points, sqTolerance);
  4756. // stage 2: Douglas-Peucker simplification
  4757. points = _simplifyDP(points, sqTolerance);
  4758. return points;
  4759. }
  4760. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  4761. // Returns the distance between point `p` and segment `p1` to `p2`.
  4762. function pointToSegmentDistance(p, p1, p2) {
  4763. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  4764. }
  4765. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  4766. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  4767. function closestPointOnSegment(p, p1, p2) {
  4768. return _sqClosestPointOnSegment(p, p1, p2);
  4769. }
  4770. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  4771. function _simplifyDP(points, sqTolerance) {
  4772. var len = points.length,
  4773. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  4774. markers = new ArrayConstructor(len);
  4775. markers[0] = markers[len - 1] = 1;
  4776. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  4777. var i,
  4778. newPoints = [];
  4779. for (i = 0; i < len; i++) {
  4780. if (markers[i]) {
  4781. newPoints.push(points[i]);
  4782. }
  4783. }
  4784. return newPoints;
  4785. }
  4786. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  4787. var maxSqDist = 0,
  4788. index, i, sqDist;
  4789. for (i = first + 1; i <= last - 1; i++) {
  4790. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  4791. if (sqDist > maxSqDist) {
  4792. index = i;
  4793. maxSqDist = sqDist;
  4794. }
  4795. }
  4796. if (maxSqDist > sqTolerance) {
  4797. markers[index] = 1;
  4798. _simplifyDPStep(points, markers, sqTolerance, first, index);
  4799. _simplifyDPStep(points, markers, sqTolerance, index, last);
  4800. }
  4801. }
  4802. // reduce points that are too close to each other to a single point
  4803. function _reducePoints(points, sqTolerance) {
  4804. var reducedPoints = [points[0]];
  4805. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  4806. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  4807. reducedPoints.push(points[i]);
  4808. prev = i;
  4809. }
  4810. }
  4811. if (prev < len - 1) {
  4812. reducedPoints.push(points[len - 1]);
  4813. }
  4814. return reducedPoints;
  4815. }
  4816. var _lastCode;
  4817. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  4818. // Clips the segment a to b by rectangular bounds with the
  4819. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  4820. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  4821. // points that are on the screen or near, increasing performance.
  4822. function clipSegment(a, b, bounds, useLastCode, round) {
  4823. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  4824. codeB = _getBitCode(b, bounds),
  4825. codeOut, p, newCode;
  4826. // save 2nd code to avoid calculating it on the next segment
  4827. _lastCode = codeB;
  4828. while (true) {
  4829. // if a,b is inside the clip window (trivial accept)
  4830. if (!(codeA | codeB)) {
  4831. return [a, b];
  4832. }
  4833. // if a,b is outside the clip window (trivial reject)
  4834. if (codeA & codeB) {
  4835. return false;
  4836. }
  4837. // other cases
  4838. codeOut = codeA || codeB;
  4839. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  4840. newCode = _getBitCode(p, bounds);
  4841. if (codeOut === codeA) {
  4842. a = p;
  4843. codeA = newCode;
  4844. } else {
  4845. b = p;
  4846. codeB = newCode;
  4847. }
  4848. }
  4849. }
  4850. function _getEdgeIntersection(a, b, code, bounds, round) {
  4851. var dx = b.x - a.x,
  4852. dy = b.y - a.y,
  4853. min = bounds.min,
  4854. max = bounds.max,
  4855. x, y;
  4856. if (code & 8) { // top
  4857. x = a.x + dx * (max.y - a.y) / dy;
  4858. y = max.y;
  4859. } else if (code & 4) { // bottom
  4860. x = a.x + dx * (min.y - a.y) / dy;
  4861. y = min.y;
  4862. } else if (code & 2) { // right
  4863. x = max.x;
  4864. y = a.y + dy * (max.x - a.x) / dx;
  4865. } else if (code & 1) { // left
  4866. x = min.x;
  4867. y = a.y + dy * (min.x - a.x) / dx;
  4868. }
  4869. return new Point(x, y, round);
  4870. }
  4871. function _getBitCode(p, bounds) {
  4872. var code = 0;
  4873. if (p.x < bounds.min.x) { // left
  4874. code |= 1;
  4875. } else if (p.x > bounds.max.x) { // right
  4876. code |= 2;
  4877. }
  4878. if (p.y < bounds.min.y) { // bottom
  4879. code |= 4;
  4880. } else if (p.y > bounds.max.y) { // top
  4881. code |= 8;
  4882. }
  4883. return code;
  4884. }
  4885. // square distance (to avoid unnecessary Math.sqrt calls)
  4886. function _sqDist(p1, p2) {
  4887. var dx = p2.x - p1.x,
  4888. dy = p2.y - p1.y;
  4889. return dx * dx + dy * dy;
  4890. }
  4891. // return closest point on segment or distance to that point
  4892. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  4893. var x = p1.x,
  4894. y = p1.y,
  4895. dx = p2.x - x,
  4896. dy = p2.y - y,
  4897. dot = dx * dx + dy * dy,
  4898. t;
  4899. if (dot > 0) {
  4900. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  4901. if (t > 1) {
  4902. x = p2.x;
  4903. y = p2.y;
  4904. } else if (t > 0) {
  4905. x += dx * t;
  4906. y += dy * t;
  4907. }
  4908. }
  4909. dx = p.x - x;
  4910. dy = p.y - y;
  4911. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  4912. }
  4913. // @function isFlat(latlngs: LatLng[]): Boolean
  4914. // Returns true if `latlngs` is a flat array, false is nested.
  4915. function isFlat(latlngs) {
  4916. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  4917. }
  4918. function _flat(latlngs) {
  4919. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  4920. return isFlat(latlngs);
  4921. }
  4922. var LineUtil = (Object.freeze || Object)({
  4923. simplify: simplify,
  4924. pointToSegmentDistance: pointToSegmentDistance,
  4925. closestPointOnSegment: closestPointOnSegment,
  4926. clipSegment: clipSegment,
  4927. _getEdgeIntersection: _getEdgeIntersection,
  4928. _getBitCode: _getBitCode,
  4929. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  4930. isFlat: isFlat,
  4931. _flat: _flat
  4932. });
  4933. /*
  4934. * @namespace PolyUtil
  4935. * Various utility functions for polygon geometries.
  4936. */
  4937. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  4938. * 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)).
  4939. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  4940. * performance. Note that polygon points needs different algorithm for clipping
  4941. * than polyline, so there's a seperate method for it.
  4942. */
  4943. function clipPolygon(points, bounds, round) {
  4944. var clippedPoints,
  4945. edges = [1, 4, 2, 8],
  4946. i, j, k,
  4947. a, b,
  4948. len, edge, p;
  4949. for (i = 0, len = points.length; i < len; i++) {
  4950. points[i]._code = _getBitCode(points[i], bounds);
  4951. }
  4952. // for each edge (left, bottom, right, top)
  4953. for (k = 0; k < 4; k++) {
  4954. edge = edges[k];
  4955. clippedPoints = [];
  4956. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  4957. a = points[i];
  4958. b = points[j];
  4959. // if a is inside the clip window
  4960. if (!(a._code & edge)) {
  4961. // if b is outside the clip window (a->b goes out of screen)
  4962. if (b._code & edge) {
  4963. p = _getEdgeIntersection(b, a, edge, bounds, round);
  4964. p._code = _getBitCode(p, bounds);
  4965. clippedPoints.push(p);
  4966. }
  4967. clippedPoints.push(a);
  4968. // else if b is inside the clip window (a->b enters the screen)
  4969. } else if (!(b._code & edge)) {
  4970. p = _getEdgeIntersection(b, a, edge, bounds, round);
  4971. p._code = _getBitCode(p, bounds);
  4972. clippedPoints.push(p);
  4973. }
  4974. }
  4975. points = clippedPoints;
  4976. }
  4977. return points;
  4978. }
  4979. var PolyUtil = (Object.freeze || Object)({
  4980. clipPolygon: clipPolygon
  4981. });
  4982. /*
  4983. * @namespace Projection
  4984. * @section
  4985. * Leaflet comes with a set of already defined Projections out of the box:
  4986. *
  4987. * @projection L.Projection.LonLat
  4988. *
  4989. * Equirectangular, or Plate Carree projection — the most simple projection,
  4990. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  4991. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  4992. * `EPSG:4326` and `Simple` CRS.
  4993. */
  4994. var LonLat = {
  4995. project: function (latlng) {
  4996. return new Point(latlng.lng, latlng.lat);
  4997. },
  4998. unproject: function (point) {
  4999. return new LatLng(point.y, point.x);
  5000. },
  5001. bounds: new Bounds([-180, -90], [180, 90])
  5002. };
  5003. /*
  5004. * @namespace Projection
  5005. * @projection L.Projection.Mercator
  5006. *
  5007. * 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.
  5008. */
  5009. var Mercator = {
  5010. R: 6378137,
  5011. R_MINOR: 6356752.314245179,
  5012. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5013. project: function (latlng) {
  5014. var d = Math.PI / 180,
  5015. r = this.R,
  5016. y = latlng.lat * d,
  5017. tmp = this.R_MINOR / r,
  5018. e = Math.sqrt(1 - tmp * tmp),
  5019. con = e * Math.sin(y);
  5020. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5021. y = -r * Math.log(Math.max(ts, 1E-10));
  5022. return new Point(latlng.lng * d * r, y);
  5023. },
  5024. unproject: function (point) {
  5025. var d = 180 / Math.PI,
  5026. r = this.R,
  5027. tmp = this.R_MINOR / r,
  5028. e = Math.sqrt(1 - tmp * tmp),
  5029. ts = Math.exp(-point.y / r),
  5030. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5031. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5032. con = e * Math.sin(phi);
  5033. con = Math.pow((1 - con) / (1 + con), e / 2);
  5034. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5035. phi += dphi;
  5036. }
  5037. return new LatLng(phi * d, point.x * d / r);
  5038. }
  5039. };
  5040. /*
  5041. * @class Projection
  5042. * An object with methods for projecting geographical coordinates of the world onto
  5043. * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).
  5044. * @property bounds: Bounds
  5045. * The bounds (specified in CRS units) where the projection is valid
  5046. * @method project(latlng: LatLng): Point
  5047. * Projects geographical coordinates into a 2D point.
  5048. * Only accepts actual `L.LatLng` instances, not arrays.
  5049. * @method unproject(point: Point): LatLng
  5050. * The inverse of `project`. Projects a 2D point into a geographical location.
  5051. * Only accepts actual `L.Point` instances, not arrays.
  5052. */
  5053. var index = (Object.freeze || Object)({
  5054. LonLat: LonLat,
  5055. Mercator: Mercator,
  5056. SphericalMercator: SphericalMercator
  5057. });
  5058. /*
  5059. * @namespace CRS
  5060. * @crs L.CRS.EPSG3395
  5061. *
  5062. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5063. */
  5064. var EPSG3395 = extend({}, Earth, {
  5065. code: 'EPSG:3395',
  5066. projection: Mercator,
  5067. transformation: (function () {
  5068. var scale = 0.5 / (Math.PI * Mercator.R);
  5069. return toTransformation(scale, 0.5, -scale, 0.5);
  5070. }())
  5071. });
  5072. /*
  5073. * @namespace CRS
  5074. * @crs L.CRS.EPSG4326
  5075. *
  5076. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5077. *
  5078. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5079. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5080. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5081. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5082. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5083. */
  5084. var EPSG4326 = extend({}, Earth, {
  5085. code: 'EPSG:4326',
  5086. projection: LonLat,
  5087. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5088. });
  5089. /*
  5090. * @namespace CRS
  5091. * @crs L.CRS.Simple
  5092. *
  5093. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5094. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5095. * axis should still be inverted (going from bottom to top). `distance()` returns
  5096. * simple euclidean distance.
  5097. */
  5098. var Simple = extend({}, CRS, {
  5099. projection: LonLat,
  5100. transformation: toTransformation(1, 0, -1, 0),
  5101. scale: function (zoom) {
  5102. return Math.pow(2, zoom);
  5103. },
  5104. zoom: function (scale) {
  5105. return Math.log(scale) / Math.LN2;
  5106. },
  5107. distance: function (latlng1, latlng2) {
  5108. var dx = latlng2.lng - latlng1.lng,
  5109. dy = latlng2.lat - latlng1.lat;
  5110. return Math.sqrt(dx * dx + dy * dy);
  5111. },
  5112. infinite: true
  5113. });
  5114. CRS.Earth = Earth;
  5115. CRS.EPSG3395 = EPSG3395;
  5116. CRS.EPSG3857 = EPSG3857;
  5117. CRS.EPSG900913 = EPSG900913;
  5118. CRS.EPSG4326 = EPSG4326;
  5119. CRS.Simple = Simple;
  5120. /*
  5121. * @class Layer
  5122. * @inherits Evented
  5123. * @aka L.Layer
  5124. * @aka ILayer
  5125. *
  5126. * A set of methods from the Layer base class that all Leaflet layers use.
  5127. * Inherits all methods, options and events from `L.Evented`.
  5128. *
  5129. * @example
  5130. *
  5131. * ```js
  5132. * var layer = L.Marker(latlng).addTo(map);
  5133. * layer.addTo(map);
  5134. * layer.remove();
  5135. * ```
  5136. *
  5137. * @event add: Event
  5138. * Fired after the layer is added to a map
  5139. *
  5140. * @event remove: Event
  5141. * Fired after the layer is removed from a map
  5142. */
  5143. var Layer = Evented.extend({
  5144. // Classes extending `L.Layer` will inherit the following options:
  5145. options: {
  5146. // @option pane: String = 'overlayPane'
  5147. // 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.
  5148. pane: 'overlayPane',
  5149. // @option attribution: String = null
  5150. // String to be shown in the attribution control, describes the layer data, e.g. "© Mapbox".
  5151. attribution: null,
  5152. bubblingMouseEvents: true
  5153. },
  5154. /* @section
  5155. * Classes extending `L.Layer` will inherit the following methods:
  5156. *
  5157. * @method addTo(map: Map|LayerGroup): this
  5158. * Adds the layer to the given map or layer group.
  5159. */
  5160. addTo: function (map) {
  5161. map.addLayer(this);
  5162. return this;
  5163. },
  5164. // @method remove: this
  5165. // Removes the layer from the map it is currently active on.
  5166. remove: function () {
  5167. return this.removeFrom(this._map || this._mapToAdd);
  5168. },
  5169. // @method removeFrom(map: Map): this
  5170. // Removes the layer from the given map
  5171. removeFrom: function (obj) {
  5172. if (obj) {
  5173. obj.removeLayer(this);
  5174. }
  5175. return this;
  5176. },
  5177. // @method getPane(name? : String): HTMLElement
  5178. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5179. getPane: function (name) {
  5180. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5181. },
  5182. addInteractiveTarget: function (targetEl) {
  5183. this._map._targets[stamp(targetEl)] = this;
  5184. return this;
  5185. },
  5186. removeInteractiveTarget: function (targetEl) {
  5187. delete this._map._targets[stamp(targetEl)];
  5188. return this;
  5189. },
  5190. // @method getAttribution: String
  5191. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5192. getAttribution: function () {
  5193. return this.options.attribution;
  5194. },
  5195. _layerAdd: function (e) {
  5196. var map = e.target;
  5197. // check in case layer gets added and then removed before the map is ready
  5198. if (!map.hasLayer(this)) { return; }
  5199. this._map = map;
  5200. this._zoomAnimated = map._zoomAnimated;
  5201. if (this.getEvents) {
  5202. var events = this.getEvents();
  5203. map.on(events, this);
  5204. this.once('remove', function () {
  5205. map.off(events, this);
  5206. }, this);
  5207. }
  5208. this.onAdd(map);
  5209. if (this.getAttribution && map.attributionControl) {
  5210. map.attributionControl.addAttribution(this.getAttribution());
  5211. }
  5212. this.fire('add');
  5213. map.fire('layeradd', {layer: this});
  5214. }
  5215. });
  5216. /* @section Extension methods
  5217. * @uninheritable
  5218. *
  5219. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5220. *
  5221. * @method onAdd(map: Map): this
  5222. * 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).
  5223. *
  5224. * @method onRemove(map: Map): this
  5225. * 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).
  5226. *
  5227. * @method getEvents(): Object
  5228. * 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.
  5229. *
  5230. * @method getAttribution(): String
  5231. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5232. *
  5233. * @method beforeAdd(map: Map): this
  5234. * 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.
  5235. */
  5236. /* @namespace Map
  5237. * @section Layer events
  5238. *
  5239. * @event layeradd: LayerEvent
  5240. * Fired when a new layer is added to the map.
  5241. *
  5242. * @event layerremove: LayerEvent
  5243. * Fired when some layer is removed from the map
  5244. *
  5245. * @section Methods for Layers and Controls
  5246. */
  5247. Map.include({
  5248. // @method addLayer(layer: Layer): this
  5249. // Adds the given layer to the map
  5250. addLayer: function (layer) {
  5251. if (!layer._layerAdd) {
  5252. throw new Error('The provided object is not a Layer.');
  5253. }
  5254. var id = stamp(layer);
  5255. if (this._layers[id]) { return this; }
  5256. this._layers[id] = layer;
  5257. layer._mapToAdd = this;
  5258. if (layer.beforeAdd) {
  5259. layer.beforeAdd(this);
  5260. }
  5261. this.whenReady(layer._layerAdd, layer);
  5262. return this;
  5263. },
  5264. // @method removeLayer(layer: Layer): this
  5265. // Removes the given layer from the map.
  5266. removeLayer: function (layer) {
  5267. var id = stamp(layer);
  5268. if (!this._layers[id]) { return this; }
  5269. if (this._loaded) {
  5270. layer.onRemove(this);
  5271. }
  5272. if (layer.getAttribution && this.attributionControl) {
  5273. this.attributionControl.removeAttribution(layer.getAttribution());
  5274. }
  5275. delete this._layers[id];
  5276. if (this._loaded) {
  5277. this.fire('layerremove', {layer: layer});
  5278. layer.fire('remove');
  5279. }
  5280. layer._map = layer._mapToAdd = null;
  5281. return this;
  5282. },
  5283. // @method hasLayer(layer: Layer): Boolean
  5284. // Returns `true` if the given layer is currently added to the map
  5285. hasLayer: function (layer) {
  5286. return !!layer && (stamp(layer) in this._layers);
  5287. },
  5288. /* @method eachLayer(fn: Function, context?: Object): this
  5289. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5290. * ```
  5291. * map.eachLayer(function(layer){
  5292. * layer.bindPopup('Hello');
  5293. * });
  5294. * ```
  5295. */
  5296. eachLayer: function (method, context) {
  5297. for (var i in this._layers) {
  5298. method.call(context, this._layers[i]);
  5299. }
  5300. return this;
  5301. },
  5302. _addLayers: function (layers) {
  5303. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5304. for (var i = 0, len = layers.length; i < len; i++) {
  5305. this.addLayer(layers[i]);
  5306. }
  5307. },
  5308. _addZoomLimit: function (layer) {
  5309. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5310. this._zoomBoundLayers[stamp(layer)] = layer;
  5311. this._updateZoomLevels();
  5312. }
  5313. },
  5314. _removeZoomLimit: function (layer) {
  5315. var id = stamp(layer);
  5316. if (this._zoomBoundLayers[id]) {
  5317. delete this._zoomBoundLayers[id];
  5318. this._updateZoomLevels();
  5319. }
  5320. },
  5321. _updateZoomLevels: function () {
  5322. var minZoom = Infinity,
  5323. maxZoom = -Infinity,
  5324. oldZoomSpan = this._getZoomSpan();
  5325. for (var i in this._zoomBoundLayers) {
  5326. var options = this._zoomBoundLayers[i].options;
  5327. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5328. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5329. }
  5330. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5331. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5332. // @section Map state change events
  5333. // @event zoomlevelschange: Event
  5334. // Fired when the number of zoomlevels on the map is changed due
  5335. // to adding or removing a layer.
  5336. if (oldZoomSpan !== this._getZoomSpan()) {
  5337. this.fire('zoomlevelschange');
  5338. }
  5339. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5340. this.setZoom(this._layersMaxZoom);
  5341. }
  5342. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5343. this.setZoom(this._layersMinZoom);
  5344. }
  5345. }
  5346. });
  5347. /*
  5348. * @class LayerGroup
  5349. * @aka L.LayerGroup
  5350. * @inherits Layer
  5351. *
  5352. * Used to group several layers and handle them as one. If you add it to the map,
  5353. * any layers added or removed from the group will be added/removed on the map as
  5354. * well. Extends `Layer`.
  5355. *
  5356. * @example
  5357. *
  5358. * ```js
  5359. * L.layerGroup([marker1, marker2])
  5360. * .addLayer(polyline)
  5361. * .addTo(map);
  5362. * ```
  5363. */
  5364. var LayerGroup = Layer.extend({
  5365. initialize: function (layers) {
  5366. this._layers = {};
  5367. var i, len;
  5368. if (layers) {
  5369. for (i = 0, len = layers.length; i < len; i++) {
  5370. this.addLayer(layers[i]);
  5371. }
  5372. }
  5373. },
  5374. // @method addLayer(layer: Layer): this
  5375. // Adds the given layer to the group.
  5376. addLayer: function (layer) {
  5377. var id = this.getLayerId(layer);
  5378. this._layers[id] = layer;
  5379. if (this._map) {
  5380. this._map.addLayer(layer);
  5381. }
  5382. return this;
  5383. },
  5384. // @method removeLayer(layer: Layer): this
  5385. // Removes the given layer from the group.
  5386. // @alternative
  5387. // @method removeLayer(id: Number): this
  5388. // Removes the layer with the given internal ID from the group.
  5389. removeLayer: function (layer) {
  5390. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5391. if (this._map && this._layers[id]) {
  5392. this._map.removeLayer(this._layers[id]);
  5393. }
  5394. delete this._layers[id];
  5395. return this;
  5396. },
  5397. // @method hasLayer(layer: Layer): Boolean
  5398. // Returns `true` if the given layer is currently added to the group.
  5399. // @alternative
  5400. // @method hasLayer(id: Number): Boolean
  5401. // Returns `true` if the given internal ID is currently added to the group.
  5402. hasLayer: function (layer) {
  5403. return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
  5404. },
  5405. // @method clearLayers(): this
  5406. // Removes all the layers from the group.
  5407. clearLayers: function () {
  5408. for (var i in this._layers) {
  5409. this.removeLayer(this._layers[i]);
  5410. }
  5411. return this;
  5412. },
  5413. // @method invoke(methodName: String, …): this
  5414. // Calls `methodName` on every layer contained in this group, passing any
  5415. // additional parameters. Has no effect if the layers contained do not
  5416. // implement `methodName`.
  5417. invoke: function (methodName) {
  5418. var args = Array.prototype.slice.call(arguments, 1),
  5419. i, layer;
  5420. for (i in this._layers) {
  5421. layer = this._layers[i];
  5422. if (layer[methodName]) {
  5423. layer[methodName].apply(layer, args);
  5424. }
  5425. }
  5426. return this;
  5427. },
  5428. onAdd: function (map) {
  5429. for (var i in this._layers) {
  5430. map.addLayer(this._layers[i]);
  5431. }
  5432. },
  5433. onRemove: function (map) {
  5434. for (var i in this._layers) {
  5435. map.removeLayer(this._layers[i]);
  5436. }
  5437. },
  5438. // @method eachLayer(fn: Function, context?: Object): this
  5439. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5440. // ```js
  5441. // group.eachLayer(function (layer) {
  5442. // layer.bindPopup('Hello');
  5443. // });
  5444. // ```
  5445. eachLayer: function (method, context) {
  5446. for (var i in this._layers) {
  5447. method.call(context, this._layers[i]);
  5448. }
  5449. return this;
  5450. },
  5451. // @method getLayer(id: Number): Layer
  5452. // Returns the layer with the given internal ID.
  5453. getLayer: function (id) {
  5454. return this._layers[id];
  5455. },
  5456. // @method getLayers(): Layer[]
  5457. // Returns an array of all the layers added to the group.
  5458. getLayers: function () {
  5459. var layers = [];
  5460. for (var i in this._layers) {
  5461. layers.push(this._layers[i]);
  5462. }
  5463. return layers;
  5464. },
  5465. // @method setZIndex(zIndex: Number): this
  5466. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5467. setZIndex: function (zIndex) {
  5468. return this.invoke('setZIndex', zIndex);
  5469. },
  5470. // @method getLayerId(layer: Layer): Number
  5471. // Returns the internal ID for a layer
  5472. getLayerId: function (layer) {
  5473. return stamp(layer);
  5474. }
  5475. });
  5476. // @factory L.layerGroup(layers?: Layer[])
  5477. // Create a layer group, optionally given an initial set of layers.
  5478. var layerGroup = function (layers) {
  5479. return new LayerGroup(layers);
  5480. };
  5481. /*
  5482. * @class FeatureGroup
  5483. * @aka L.FeatureGroup
  5484. * @inherits LayerGroup
  5485. *
  5486. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5487. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5488. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5489. * handler, it will handle events from any of the layers. This includes mouse events
  5490. * and custom events.
  5491. * * Has `layeradd` and `layerremove` events
  5492. *
  5493. * @example
  5494. *
  5495. * ```js
  5496. * L.featureGroup([marker1, marker2, polyline])
  5497. * .bindPopup('Hello world!')
  5498. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5499. * .addTo(map);
  5500. * ```
  5501. */
  5502. var FeatureGroup = LayerGroup.extend({
  5503. addLayer: function (layer) {
  5504. if (this.hasLayer(layer)) {
  5505. return this;
  5506. }
  5507. layer.addEventParent(this);
  5508. LayerGroup.prototype.addLayer.call(this, layer);
  5509. // @event layeradd: LayerEvent
  5510. // Fired when a layer is added to this `FeatureGroup`
  5511. return this.fire('layeradd', {layer: layer});
  5512. },
  5513. removeLayer: function (layer) {
  5514. if (!this.hasLayer(layer)) {
  5515. return this;
  5516. }
  5517. if (layer in this._layers) {
  5518. layer = this._layers[layer];
  5519. }
  5520. layer.removeEventParent(this);
  5521. LayerGroup.prototype.removeLayer.call(this, layer);
  5522. // @event layerremove: LayerEvent
  5523. // Fired when a layer is removed from this `FeatureGroup`
  5524. return this.fire('layerremove', {layer: layer});
  5525. },
  5526. // @method setStyle(style: Path options): this
  5527. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5528. setStyle: function (style) {
  5529. return this.invoke('setStyle', style);
  5530. },
  5531. // @method bringToFront(): this
  5532. // Brings the layer group to the top of all other layers
  5533. bringToFront: function () {
  5534. return this.invoke('bringToFront');
  5535. },
  5536. // @method bringToBack(): this
  5537. // Brings the layer group to the top of all other layers
  5538. bringToBack: function () {
  5539. return this.invoke('bringToBack');
  5540. },
  5541. // @method getBounds(): LatLngBounds
  5542. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5543. getBounds: function () {
  5544. var bounds = new LatLngBounds();
  5545. for (var id in this._layers) {
  5546. var layer = this._layers[id];
  5547. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5548. }
  5549. return bounds;
  5550. }
  5551. });
  5552. // @factory L.featureGroup(layers: Layer[])
  5553. // Create a feature group, optionally given an initial set of layers.
  5554. var featureGroup = function (layers) {
  5555. return new FeatureGroup(layers);
  5556. };
  5557. /*
  5558. * @class Icon
  5559. * @aka L.Icon
  5560. *
  5561. * Represents an icon to provide when creating a marker.
  5562. *
  5563. * @example
  5564. *
  5565. * ```js
  5566. * var myIcon = L.icon({
  5567. * iconUrl: 'my-icon.png',
  5568. * iconRetinaUrl: 'my-icon@2x.png',
  5569. * iconSize: [38, 95],
  5570. * iconAnchor: [22, 94],
  5571. * popupAnchor: [-3, -76],
  5572. * shadowUrl: 'my-icon-shadow.png',
  5573. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5574. * shadowSize: [68, 95],
  5575. * shadowAnchor: [22, 94]
  5576. * });
  5577. *
  5578. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5579. * ```
  5580. *
  5581. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5582. *
  5583. */
  5584. var Icon = Class.extend({
  5585. /* @section
  5586. * @aka Icon options
  5587. *
  5588. * @option iconUrl: String = null
  5589. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5590. *
  5591. * @option iconRetinaUrl: String = null
  5592. * The URL to a retina sized version of the icon image (absolute or relative to your
  5593. * script path). Used for Retina screen devices.
  5594. *
  5595. * @option iconSize: Point = null
  5596. * Size of the icon image in pixels.
  5597. *
  5598. * @option iconAnchor: Point = null
  5599. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5600. * will be aligned so that this point is at the marker's geographical location. Centered
  5601. * by default if size is specified, also can be set in CSS with negative margins.
  5602. *
  5603. * @option popupAnchor: Point = null
  5604. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5605. *
  5606. * @option shadowUrl: String = null
  5607. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  5608. *
  5609. * @option shadowRetinaUrl: String = null
  5610. *
  5611. * @option shadowSize: Point = null
  5612. * Size of the shadow image in pixels.
  5613. *
  5614. * @option shadowAnchor: Point = null
  5615. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  5616. * as iconAnchor if not specified).
  5617. *
  5618. * @option className: String = ''
  5619. * A custom class name to assign to both icon and shadow images. Empty by default.
  5620. */
  5621. initialize: function (options) {
  5622. setOptions(this, options);
  5623. },
  5624. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  5625. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  5626. // styled according to the options.
  5627. createIcon: function (oldIcon) {
  5628. return this._createIcon('icon', oldIcon);
  5629. },
  5630. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  5631. // As `createIcon`, but for the shadow beneath it.
  5632. createShadow: function (oldIcon) {
  5633. return this._createIcon('shadow', oldIcon);
  5634. },
  5635. _createIcon: function (name, oldIcon) {
  5636. var src = this._getIconUrl(name);
  5637. if (!src) {
  5638. if (name === 'icon') {
  5639. throw new Error('iconUrl not set in Icon options (see the docs).');
  5640. }
  5641. return null;
  5642. }
  5643. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  5644. this._setIconStyles(img, name);
  5645. return img;
  5646. },
  5647. _setIconStyles: function (img, name) {
  5648. var options = this.options;
  5649. var sizeOption = options[name + 'Size'];
  5650. if (typeof sizeOption === 'number') {
  5651. sizeOption = [sizeOption, sizeOption];
  5652. }
  5653. var size = toPoint(sizeOption),
  5654. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  5655. size && size.divideBy(2, true));
  5656. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  5657. if (anchor) {
  5658. img.style.marginLeft = (-anchor.x) + 'px';
  5659. img.style.marginTop = (-anchor.y) + 'px';
  5660. }
  5661. if (size) {
  5662. img.style.width = size.x + 'px';
  5663. img.style.height = size.y + 'px';
  5664. }
  5665. },
  5666. _createImg: function (src, el) {
  5667. el = el || document.createElement('img');
  5668. el.src = src;
  5669. return el;
  5670. },
  5671. _getIconUrl: function (name) {
  5672. return retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  5673. }
  5674. });
  5675. // @factory L.icon(options: Icon options)
  5676. // Creates an icon instance with the given options.
  5677. function icon(options) {
  5678. return new Icon(options);
  5679. }
  5680. /*
  5681. * @miniclass Icon.Default (Icon)
  5682. * @aka L.Icon.Default
  5683. * @section
  5684. *
  5685. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  5686. * no icon is specified. Points to the blue marker image distributed with Leaflet
  5687. * releases.
  5688. *
  5689. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  5690. * (which is a set of `Icon options`).
  5691. *
  5692. * If you want to _completely_ replace the default icon, override the
  5693. * `L.Marker.prototype.options.icon` with your own icon instead.
  5694. */
  5695. var IconDefault = Icon.extend({
  5696. options: {
  5697. iconUrl: 'marker-icon.png',
  5698. iconRetinaUrl: 'marker-icon-2x.png',
  5699. shadowUrl: 'marker-shadow.png',
  5700. iconSize: [25, 41],
  5701. iconAnchor: [12, 41],
  5702. popupAnchor: [1, -34],
  5703. tooltipAnchor: [16, -28],
  5704. shadowSize: [41, 41]
  5705. },
  5706. _getIconUrl: function (name) {
  5707. if (!IconDefault.imagePath) { // Deprecated, backwards-compatibility only
  5708. IconDefault.imagePath = this._detectIconPath();
  5709. }
  5710. // @option imagePath: String
  5711. // `Icon.Default` will try to auto-detect the absolute location of the
  5712. // blue icon images. If you are placing these images in a non-standard
  5713. // way, set this option to point to the right absolute path.
  5714. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  5715. },
  5716. _detectIconPath: function () {
  5717. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  5718. var path = getStyle(el, 'background-image') ||
  5719. getStyle(el, 'backgroundImage'); // IE8
  5720. document.body.removeChild(el);
  5721. if (path === null || path.indexOf('url') !== 0) {
  5722. path = '';
  5723. } else {
  5724. path = path.replace(/^url\([\"\']?/, '').replace(/marker-icon\.png[\"\']?\)$/, '');
  5725. }
  5726. return path;
  5727. }
  5728. });
  5729. /*
  5730. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  5731. */
  5732. /* @namespace Marker
  5733. * @section Interaction handlers
  5734. *
  5735. * 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:
  5736. *
  5737. * ```js
  5738. * marker.dragging.disable();
  5739. * ```
  5740. *
  5741. * @property dragging: Handler
  5742. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  5743. */
  5744. var MarkerDrag = Handler.extend({
  5745. initialize: function (marker) {
  5746. this._marker = marker;
  5747. },
  5748. addHooks: function () {
  5749. var icon = this._marker._icon;
  5750. if (!this._draggable) {
  5751. this._draggable = new Draggable(icon, icon, true);
  5752. }
  5753. this._draggable.on({
  5754. dragstart: this._onDragStart,
  5755. drag: this._onDrag,
  5756. dragend: this._onDragEnd
  5757. }, this).enable();
  5758. addClass(icon, 'leaflet-marker-draggable');
  5759. },
  5760. removeHooks: function () {
  5761. this._draggable.off({
  5762. dragstart: this._onDragStart,
  5763. drag: this._onDrag,
  5764. dragend: this._onDragEnd
  5765. }, this).disable();
  5766. if (this._marker._icon) {
  5767. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  5768. }
  5769. },
  5770. moved: function () {
  5771. return this._draggable && this._draggable._moved;
  5772. },
  5773. _onDragStart: function () {
  5774. // @section Dragging events
  5775. // @event dragstart: Event
  5776. // Fired when the user starts dragging the marker.
  5777. // @event movestart: Event
  5778. // Fired when the marker starts moving (because of dragging).
  5779. this._oldLatLng = this._marker.getLatLng();
  5780. this._marker
  5781. .closePopup()
  5782. .fire('movestart')
  5783. .fire('dragstart');
  5784. },
  5785. _onDrag: function (e) {
  5786. var marker = this._marker,
  5787. shadow = marker._shadow,
  5788. iconPos = getPosition(marker._icon),
  5789. latlng = marker._map.layerPointToLatLng(iconPos);
  5790. // update shadow position
  5791. if (shadow) {
  5792. setPosition(shadow, iconPos);
  5793. }
  5794. marker._latlng = latlng;
  5795. e.latlng = latlng;
  5796. e.oldLatLng = this._oldLatLng;
  5797. // @event drag: Event
  5798. // Fired repeatedly while the user drags the marker.
  5799. marker
  5800. .fire('move', e)
  5801. .fire('drag', e);
  5802. },
  5803. _onDragEnd: function (e) {
  5804. // @event dragend: DragEndEvent
  5805. // Fired when the user stops dragging the marker.
  5806. // @event moveend: Event
  5807. // Fired when the marker stops moving (because of dragging).
  5808. delete this._oldLatLng;
  5809. this._marker
  5810. .fire('moveend')
  5811. .fire('dragend', e);
  5812. }
  5813. });
  5814. /*
  5815. * @class Marker
  5816. * @inherits Interactive layer
  5817. * @aka L.Marker
  5818. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  5819. *
  5820. * @example
  5821. *
  5822. * ```js
  5823. * L.marker([50.5, 30.5]).addTo(map);
  5824. * ```
  5825. */
  5826. var Marker = Layer.extend({
  5827. // @section
  5828. // @aka Marker options
  5829. options: {
  5830. // @option icon: Icon = *
  5831. // Icon instance to use for rendering the marker.
  5832. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  5833. // If not specified, a common instance of `L.Icon.Default` is used.
  5834. icon: new IconDefault(),
  5835. // Option inherited from "Interactive layer" abstract class
  5836. interactive: true,
  5837. // @option draggable: Boolean = false
  5838. // Whether the marker is draggable with mouse/touch or not.
  5839. draggable: false,
  5840. // @option keyboard: Boolean = true
  5841. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  5842. keyboard: true,
  5843. // @option title: String = ''
  5844. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  5845. title: '',
  5846. // @option alt: String = ''
  5847. // Text for the `alt` attribute of the icon image (useful for accessibility).
  5848. alt: '',
  5849. // @option zIndexOffset: Number = 0
  5850. // 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).
  5851. zIndexOffset: 0,
  5852. // @option opacity: Number = 1.0
  5853. // The opacity of the marker.
  5854. opacity: 1,
  5855. // @option riseOnHover: Boolean = false
  5856. // If `true`, the marker will get on top of others when you hover the mouse over it.
  5857. riseOnHover: false,
  5858. // @option riseOffset: Number = 250
  5859. // The z-index offset used for the `riseOnHover` feature.
  5860. riseOffset: 250,
  5861. // @option pane: String = 'markerPane'
  5862. // `Map pane` where the markers icon will be added.
  5863. pane: 'markerPane',
  5864. // @option bubblingMouseEvents: Boolean = false
  5865. // When `true`, a mouse event on this marker will trigger the same event on the map
  5866. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  5867. bubblingMouseEvents: false
  5868. },
  5869. /* @section
  5870. *
  5871. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  5872. */
  5873. initialize: function (latlng, options) {
  5874. setOptions(this, options);
  5875. this._latlng = toLatLng(latlng);
  5876. },
  5877. onAdd: function (map) {
  5878. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  5879. if (this._zoomAnimated) {
  5880. map.on('zoomanim', this._animateZoom, this);
  5881. }
  5882. this._initIcon();
  5883. this.update();
  5884. },
  5885. onRemove: function (map) {
  5886. if (this.dragging && this.dragging.enabled()) {
  5887. this.options.draggable = true;
  5888. this.dragging.removeHooks();
  5889. }
  5890. delete this.dragging;
  5891. if (this._zoomAnimated) {
  5892. map.off('zoomanim', this._animateZoom, this);
  5893. }
  5894. this._removeIcon();
  5895. this._removeShadow();
  5896. },
  5897. getEvents: function () {
  5898. return {
  5899. zoom: this.update,
  5900. viewreset: this.update
  5901. };
  5902. },
  5903. // @method getLatLng: LatLng
  5904. // Returns the current geographical position of the marker.
  5905. getLatLng: function () {
  5906. return this._latlng;
  5907. },
  5908. // @method setLatLng(latlng: LatLng): this
  5909. // Changes the marker position to the given point.
  5910. setLatLng: function (latlng) {
  5911. var oldLatLng = this._latlng;
  5912. this._latlng = toLatLng(latlng);
  5913. this.update();
  5914. // @event move: Event
  5915. // 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`.
  5916. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  5917. },
  5918. // @method setZIndexOffset(offset: Number): this
  5919. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  5920. setZIndexOffset: function (offset) {
  5921. this.options.zIndexOffset = offset;
  5922. return this.update();
  5923. },
  5924. // @method setIcon(icon: Icon): this
  5925. // Changes the marker icon.
  5926. setIcon: function (icon) {
  5927. this.options.icon = icon;
  5928. if (this._map) {
  5929. this._initIcon();
  5930. this.update();
  5931. }
  5932. if (this._popup) {
  5933. this.bindPopup(this._popup, this._popup.options);
  5934. }
  5935. return this;
  5936. },
  5937. getElement: function () {
  5938. return this._icon;
  5939. },
  5940. update: function () {
  5941. if (this._icon) {
  5942. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  5943. this._setPos(pos);
  5944. }
  5945. return this;
  5946. },
  5947. _initIcon: function () {
  5948. var options = this.options,
  5949. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  5950. var icon = options.icon.createIcon(this._icon),
  5951. addIcon = false;
  5952. // if we're not reusing the icon, remove the old one and init new one
  5953. if (icon !== this._icon) {
  5954. if (this._icon) {
  5955. this._removeIcon();
  5956. }
  5957. addIcon = true;
  5958. if (options.title) {
  5959. icon.title = options.title;
  5960. }
  5961. if (options.alt) {
  5962. icon.alt = options.alt;
  5963. }
  5964. }
  5965. addClass(icon, classToAdd);
  5966. if (options.keyboard) {
  5967. icon.tabIndex = '0';
  5968. }
  5969. this._icon = icon;
  5970. if (options.riseOnHover) {
  5971. this.on({
  5972. mouseover: this._bringToFront,
  5973. mouseout: this._resetZIndex
  5974. });
  5975. }
  5976. var newShadow = options.icon.createShadow(this._shadow),
  5977. addShadow = false;
  5978. if (newShadow !== this._shadow) {
  5979. this._removeShadow();
  5980. addShadow = true;
  5981. }
  5982. if (newShadow) {
  5983. addClass(newShadow, classToAdd);
  5984. newShadow.alt = '';
  5985. }
  5986. this._shadow = newShadow;
  5987. if (options.opacity < 1) {
  5988. this._updateOpacity();
  5989. }
  5990. if (addIcon) {
  5991. this.getPane().appendChild(this._icon);
  5992. }
  5993. this._initInteraction();
  5994. if (newShadow && addShadow) {
  5995. this.getPane('shadowPane').appendChild(this._shadow);
  5996. }
  5997. },
  5998. _removeIcon: function () {
  5999. if (this.options.riseOnHover) {
  6000. this.off({
  6001. mouseover: this._bringToFront,
  6002. mouseout: this._resetZIndex
  6003. });
  6004. }
  6005. remove(this._icon);
  6006. this.removeInteractiveTarget(this._icon);
  6007. this._icon = null;
  6008. },
  6009. _removeShadow: function () {
  6010. if (this._shadow) {
  6011. remove(this._shadow);
  6012. }
  6013. this._shadow = null;
  6014. },
  6015. _setPos: function (pos) {
  6016. setPosition(this._icon, pos);
  6017. if (this._shadow) {
  6018. setPosition(this._shadow, pos);
  6019. }
  6020. this._zIndex = pos.y + this.options.zIndexOffset;
  6021. this._resetZIndex();
  6022. },
  6023. _updateZIndex: function (offset) {
  6024. this._icon.style.zIndex = this._zIndex + offset;
  6025. },
  6026. _animateZoom: function (opt) {
  6027. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6028. this._setPos(pos);
  6029. },
  6030. _initInteraction: function () {
  6031. if (!this.options.interactive) { return; }
  6032. addClass(this._icon, 'leaflet-interactive');
  6033. this.addInteractiveTarget(this._icon);
  6034. if (MarkerDrag) {
  6035. var draggable = this.options.draggable;
  6036. if (this.dragging) {
  6037. draggable = this.dragging.enabled();
  6038. this.dragging.disable();
  6039. }
  6040. this.dragging = new MarkerDrag(this);
  6041. if (draggable) {
  6042. this.dragging.enable();
  6043. }
  6044. }
  6045. },
  6046. // @method setOpacity(opacity: Number): this
  6047. // Changes the opacity of the marker.
  6048. setOpacity: function (opacity) {
  6049. this.options.opacity = opacity;
  6050. if (this._map) {
  6051. this._updateOpacity();
  6052. }
  6053. return this;
  6054. },
  6055. _updateOpacity: function () {
  6056. var opacity = this.options.opacity;
  6057. setOpacity(this._icon, opacity);
  6058. if (this._shadow) {
  6059. setOpacity(this._shadow, opacity);
  6060. }
  6061. },
  6062. _bringToFront: function () {
  6063. this._updateZIndex(this.options.riseOffset);
  6064. },
  6065. _resetZIndex: function () {
  6066. this._updateZIndex(0);
  6067. },
  6068. _getPopupAnchor: function () {
  6069. return this.options.icon.options.popupAnchor || [0, 0];
  6070. },
  6071. _getTooltipAnchor: function () {
  6072. return this.options.icon.options.tooltipAnchor || [0, 0];
  6073. }
  6074. });
  6075. // factory L.marker(latlng: LatLng, options? : Marker options)
  6076. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6077. // Instantiates a Marker object given a geographical point and optionally an options object.
  6078. function marker(latlng, options) {
  6079. return new Marker(latlng, options);
  6080. }
  6081. /*
  6082. * @class Path
  6083. * @aka L.Path
  6084. * @inherits Interactive layer
  6085. *
  6086. * An abstract class that contains options and constants shared between vector
  6087. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6088. */
  6089. var Path = Layer.extend({
  6090. // @section
  6091. // @aka Path options
  6092. options: {
  6093. // @option stroke: Boolean = true
  6094. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6095. stroke: true,
  6096. // @option color: String = '#3388ff'
  6097. // Stroke color
  6098. color: '#3388ff',
  6099. // @option weight: Number = 3
  6100. // Stroke width in pixels
  6101. weight: 3,
  6102. // @option opacity: Number = 1.0
  6103. // Stroke opacity
  6104. opacity: 1,
  6105. // @option lineCap: String= 'round'
  6106. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6107. lineCap: 'round',
  6108. // @option lineJoin: String = 'round'
  6109. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6110. lineJoin: 'round',
  6111. // @option dashArray: String = null
  6112. // 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).
  6113. dashArray: null,
  6114. // @option dashOffset: String = null
  6115. // 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).
  6116. dashOffset: null,
  6117. // @option fill: Boolean = depends
  6118. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6119. fill: false,
  6120. // @option fillColor: String = *
  6121. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6122. fillColor: null,
  6123. // @option fillOpacity: Number = 0.2
  6124. // Fill opacity.
  6125. fillOpacity: 0.2,
  6126. // @option fillRule: String = 'evenodd'
  6127. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6128. fillRule: 'evenodd',
  6129. // className: '',
  6130. // Option inherited from "Interactive layer" abstract class
  6131. interactive: true,
  6132. // @option bubblingMouseEvents: Boolean = true
  6133. // When `true`, a mouse event on this path will trigger the same event on the map
  6134. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6135. bubblingMouseEvents: true
  6136. },
  6137. beforeAdd: function (map) {
  6138. // Renderer is set here because we need to call renderer.getEvents
  6139. // before this.getEvents.
  6140. this._renderer = map.getRenderer(this);
  6141. },
  6142. onAdd: function () {
  6143. this._renderer._initPath(this);
  6144. this._reset();
  6145. this._renderer._addPath(this);
  6146. },
  6147. onRemove: function () {
  6148. this._renderer._removePath(this);
  6149. },
  6150. // @method redraw(): this
  6151. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6152. redraw: function () {
  6153. if (this._map) {
  6154. this._renderer._updatePath(this);
  6155. }
  6156. return this;
  6157. },
  6158. // @method setStyle(style: Path options): this
  6159. // Changes the appearance of a Path based on the options in the `Path options` object.
  6160. setStyle: function (style) {
  6161. setOptions(this, style);
  6162. if (this._renderer) {
  6163. this._renderer._updateStyle(this);
  6164. }
  6165. return this;
  6166. },
  6167. // @method bringToFront(): this
  6168. // Brings the layer to the top of all path layers.
  6169. bringToFront: function () {
  6170. if (this._renderer) {
  6171. this._renderer._bringToFront(this);
  6172. }
  6173. return this;
  6174. },
  6175. // @method bringToBack(): this
  6176. // Brings the layer to the bottom of all path layers.
  6177. bringToBack: function () {
  6178. if (this._renderer) {
  6179. this._renderer._bringToBack(this);
  6180. }
  6181. return this;
  6182. },
  6183. getElement: function () {
  6184. return this._path;
  6185. },
  6186. _reset: function () {
  6187. // defined in child classes
  6188. this._project();
  6189. this._update();
  6190. },
  6191. _clickTolerance: function () {
  6192. // used when doing hit detection for Canvas layers
  6193. return (this.options.stroke ? this.options.weight / 2 : 0) + (touch ? 10 : 0);
  6194. }
  6195. });
  6196. /*
  6197. * @class CircleMarker
  6198. * @aka L.CircleMarker
  6199. * @inherits Path
  6200. *
  6201. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6202. */
  6203. var CircleMarker = Path.extend({
  6204. // @section
  6205. // @aka CircleMarker options
  6206. options: {
  6207. fill: true,
  6208. // @option radius: Number = 10
  6209. // Radius of the circle marker, in pixels
  6210. radius: 10
  6211. },
  6212. initialize: function (latlng, options) {
  6213. setOptions(this, options);
  6214. this._latlng = toLatLng(latlng);
  6215. this._radius = this.options.radius;
  6216. },
  6217. // @method setLatLng(latLng: LatLng): this
  6218. // Sets the position of a circle marker to a new location.
  6219. setLatLng: function (latlng) {
  6220. this._latlng = toLatLng(latlng);
  6221. this.redraw();
  6222. return this.fire('move', {latlng: this._latlng});
  6223. },
  6224. // @method getLatLng(): LatLng
  6225. // Returns the current geographical position of the circle marker
  6226. getLatLng: function () {
  6227. return this._latlng;
  6228. },
  6229. // @method setRadius(radius: Number): this
  6230. // Sets the radius of a circle marker. Units are in pixels.
  6231. setRadius: function (radius) {
  6232. this.options.radius = this._radius = radius;
  6233. return this.redraw();
  6234. },
  6235. // @method getRadius(): Number
  6236. // Returns the current radius of the circle
  6237. getRadius: function () {
  6238. return this._radius;
  6239. },
  6240. setStyle : function (options) {
  6241. var radius = options && options.radius || this._radius;
  6242. Path.prototype.setStyle.call(this, options);
  6243. this.setRadius(radius);
  6244. return this;
  6245. },
  6246. _project: function () {
  6247. this._point = this._map.latLngToLayerPoint(this._latlng);
  6248. this._updateBounds();
  6249. },
  6250. _updateBounds: function () {
  6251. var r = this._radius,
  6252. r2 = this._radiusY || r,
  6253. w = this._clickTolerance(),
  6254. p = [r + w, r2 + w];
  6255. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6256. },
  6257. _update: function () {
  6258. if (this._map) {
  6259. this._updatePath();
  6260. }
  6261. },
  6262. _updatePath: function () {
  6263. this._renderer._updateCircle(this);
  6264. },
  6265. _empty: function () {
  6266. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6267. },
  6268. // Needed by the `Canvas` renderer for interactivity
  6269. _containsPoint: function (p) {
  6270. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6271. }
  6272. });
  6273. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6274. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6275. function circleMarker(latlng, options) {
  6276. return new CircleMarker(latlng, options);
  6277. }
  6278. /*
  6279. * @class Circle
  6280. * @aka L.Circle
  6281. * @inherits CircleMarker
  6282. *
  6283. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6284. *
  6285. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6286. *
  6287. * @example
  6288. *
  6289. * ```js
  6290. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6291. * ```
  6292. */
  6293. var Circle = CircleMarker.extend({
  6294. initialize: function (latlng, options, legacyOptions) {
  6295. if (typeof options === 'number') {
  6296. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6297. options = extend({}, legacyOptions, {radius: options});
  6298. }
  6299. setOptions(this, options);
  6300. this._latlng = toLatLng(latlng);
  6301. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6302. // @section
  6303. // @aka Circle options
  6304. // @option radius: Number; Radius of the circle, in meters.
  6305. this._mRadius = this.options.radius;
  6306. },
  6307. // @method setRadius(radius: Number): this
  6308. // Sets the radius of a circle. Units are in meters.
  6309. setRadius: function (radius) {
  6310. this._mRadius = radius;
  6311. return this.redraw();
  6312. },
  6313. // @method getRadius(): Number
  6314. // Returns the current radius of a circle. Units are in meters.
  6315. getRadius: function () {
  6316. return this._mRadius;
  6317. },
  6318. // @method getBounds(): LatLngBounds
  6319. // Returns the `LatLngBounds` of the path.
  6320. getBounds: function () {
  6321. var half = [this._radius, this._radiusY || this._radius];
  6322. return new LatLngBounds(
  6323. this._map.layerPointToLatLng(this._point.subtract(half)),
  6324. this._map.layerPointToLatLng(this._point.add(half)));
  6325. },
  6326. setStyle: Path.prototype.setStyle,
  6327. _project: function () {
  6328. var lng = this._latlng.lng,
  6329. lat = this._latlng.lat,
  6330. map = this._map,
  6331. crs = map.options.crs;
  6332. if (crs.distance === Earth.distance) {
  6333. var d = Math.PI / 180,
  6334. latR = (this._mRadius / Earth.R) / d,
  6335. top = map.project([lat + latR, lng]),
  6336. bottom = map.project([lat - latR, lng]),
  6337. p = top.add(bottom).divideBy(2),
  6338. lat2 = map.unproject(p).lat,
  6339. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6340. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6341. if (isNaN(lngR) || lngR === 0) {
  6342. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6343. }
  6344. this._point = p.subtract(map.getPixelOrigin());
  6345. this._radius = isNaN(lngR) ? 0 : Math.max(Math.round(p.x - map.project([lat2, lng - lngR]).x), 1);
  6346. this._radiusY = Math.max(Math.round(p.y - top.y), 1);
  6347. } else {
  6348. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6349. this._point = map.latLngToLayerPoint(this._latlng);
  6350. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6351. }
  6352. this._updateBounds();
  6353. }
  6354. });
  6355. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6356. // Instantiates a circle object given a geographical point, and an options object
  6357. // which contains the circle radius.
  6358. // @alternative
  6359. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6360. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6361. // Do not use in new applications or plugins.
  6362. function circle(latlng, options, legacyOptions) {
  6363. return new Circle(latlng, options, legacyOptions);
  6364. }
  6365. /*
  6366. * @class Polyline
  6367. * @aka L.Polyline
  6368. * @inherits Path
  6369. *
  6370. * A class for drawing polyline overlays on a map. Extends `Path`.
  6371. *
  6372. * @example
  6373. *
  6374. * ```js
  6375. * // create a red polyline from an array of LatLng points
  6376. * var latlngs = [
  6377. * [45.51, -122.68],
  6378. * [37.77, -122.43],
  6379. * [34.04, -118.2]
  6380. * ];
  6381. *
  6382. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6383. *
  6384. * // zoom the map to the polyline
  6385. * map.fitBounds(polyline.getBounds());
  6386. * ```
  6387. *
  6388. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6389. *
  6390. * ```js
  6391. * // create a red polyline from an array of arrays of LatLng points
  6392. * var latlngs = [
  6393. * [[45.51, -122.68],
  6394. * [37.77, -122.43],
  6395. * [34.04, -118.2]],
  6396. * [[40.78, -73.91],
  6397. * [41.83, -87.62],
  6398. * [32.76, -96.72]]
  6399. * ];
  6400. * ```
  6401. */
  6402. var Polyline = Path.extend({
  6403. // @section
  6404. // @aka Polyline options
  6405. options: {
  6406. // @option smoothFactor: Number = 1.0
  6407. // How much to simplify the polyline on each zoom level. More means
  6408. // better performance and smoother look, and less means more accurate representation.
  6409. smoothFactor: 1.0,
  6410. // @option noClip: Boolean = false
  6411. // Disable polyline clipping.
  6412. noClip: false
  6413. },
  6414. initialize: function (latlngs, options) {
  6415. setOptions(this, options);
  6416. this._setLatLngs(latlngs);
  6417. },
  6418. // @method getLatLngs(): LatLng[]
  6419. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6420. getLatLngs: function () {
  6421. return this._latlngs;
  6422. },
  6423. // @method setLatLngs(latlngs: LatLng[]): this
  6424. // Replaces all the points in the polyline with the given array of geographical points.
  6425. setLatLngs: function (latlngs) {
  6426. this._setLatLngs(latlngs);
  6427. return this.redraw();
  6428. },
  6429. // @method isEmpty(): Boolean
  6430. // Returns `true` if the Polyline has no LatLngs.
  6431. isEmpty: function () {
  6432. return !this._latlngs.length;
  6433. },
  6434. closestLayerPoint: function (p) {
  6435. var minDistance = Infinity,
  6436. minPoint = null,
  6437. closest = _sqClosestPointOnSegment,
  6438. p1, p2;
  6439. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6440. var points = this._parts[j];
  6441. for (var i = 1, len = points.length; i < len; i++) {
  6442. p1 = points[i - 1];
  6443. p2 = points[i];
  6444. var sqDist = closest(p, p1, p2, true);
  6445. if (sqDist < minDistance) {
  6446. minDistance = sqDist;
  6447. minPoint = closest(p, p1, p2);
  6448. }
  6449. }
  6450. }
  6451. if (minPoint) {
  6452. minPoint.distance = Math.sqrt(minDistance);
  6453. }
  6454. return minPoint;
  6455. },
  6456. // @method getCenter(): LatLng
  6457. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6458. getCenter: function () {
  6459. // throws error when not yet added to map as this center calculation requires projected coordinates
  6460. if (!this._map) {
  6461. throw new Error('Must add layer to map before using getCenter()');
  6462. }
  6463. var i, halfDist, segDist, dist, p1, p2, ratio,
  6464. points = this._rings[0],
  6465. len = points.length;
  6466. if (!len) { return null; }
  6467. // polyline centroid algorithm; only uses the first ring if there are multiple
  6468. for (i = 0, halfDist = 0; i < len - 1; i++) {
  6469. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  6470. }
  6471. // The line is so small in the current view that all points are on the same pixel.
  6472. if (halfDist === 0) {
  6473. return this._map.layerPointToLatLng(points[0]);
  6474. }
  6475. for (i = 0, dist = 0; i < len - 1; i++) {
  6476. p1 = points[i];
  6477. p2 = points[i + 1];
  6478. segDist = p1.distanceTo(p2);
  6479. dist += segDist;
  6480. if (dist > halfDist) {
  6481. ratio = (dist - halfDist) / segDist;
  6482. return this._map.layerPointToLatLng([
  6483. p2.x - ratio * (p2.x - p1.x),
  6484. p2.y - ratio * (p2.y - p1.y)
  6485. ]);
  6486. }
  6487. }
  6488. },
  6489. // @method getBounds(): LatLngBounds
  6490. // Returns the `LatLngBounds` of the path.
  6491. getBounds: function () {
  6492. return this._bounds;
  6493. },
  6494. // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
  6495. // Adds a given point to the polyline. By default, adds to the first ring of
  6496. // the polyline in case of a multi-polyline, but can be overridden by passing
  6497. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6498. addLatLng: function (latlng, latlngs) {
  6499. latlngs = latlngs || this._defaultShape();
  6500. latlng = toLatLng(latlng);
  6501. latlngs.push(latlng);
  6502. this._bounds.extend(latlng);
  6503. return this.redraw();
  6504. },
  6505. _setLatLngs: function (latlngs) {
  6506. this._bounds = new LatLngBounds();
  6507. this._latlngs = this._convertLatLngs(latlngs);
  6508. },
  6509. _defaultShape: function () {
  6510. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6511. },
  6512. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6513. _convertLatLngs: function (latlngs) {
  6514. var result = [],
  6515. flat = isFlat(latlngs);
  6516. for (var i = 0, len = latlngs.length; i < len; i++) {
  6517. if (flat) {
  6518. result[i] = toLatLng(latlngs[i]);
  6519. this._bounds.extend(result[i]);
  6520. } else {
  6521. result[i] = this._convertLatLngs(latlngs[i]);
  6522. }
  6523. }
  6524. return result;
  6525. },
  6526. _project: function () {
  6527. var pxBounds = new Bounds();
  6528. this._rings = [];
  6529. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  6530. var w = this._clickTolerance(),
  6531. p = new Point(w, w);
  6532. if (this._bounds.isValid() && pxBounds.isValid()) {
  6533. pxBounds.min._subtract(p);
  6534. pxBounds.max._add(p);
  6535. this._pxBounds = pxBounds;
  6536. }
  6537. },
  6538. // recursively turns latlngs into a set of rings with projected coordinates
  6539. _projectLatlngs: function (latlngs, result, projectedBounds) {
  6540. var flat = latlngs[0] instanceof LatLng,
  6541. len = latlngs.length,
  6542. i, ring;
  6543. if (flat) {
  6544. ring = [];
  6545. for (i = 0; i < len; i++) {
  6546. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  6547. projectedBounds.extend(ring[i]);
  6548. }
  6549. result.push(ring);
  6550. } else {
  6551. for (i = 0; i < len; i++) {
  6552. this._projectLatlngs(latlngs[i], result, projectedBounds);
  6553. }
  6554. }
  6555. },
  6556. // clip polyline by renderer bounds so that we have less to render for performance
  6557. _clipPoints: function () {
  6558. var bounds = this._renderer._bounds;
  6559. this._parts = [];
  6560. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6561. return;
  6562. }
  6563. if (this.options.noClip) {
  6564. this._parts = this._rings;
  6565. return;
  6566. }
  6567. var parts = this._parts,
  6568. i, j, k, len, len2, segment, points;
  6569. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  6570. points = this._rings[i];
  6571. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  6572. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  6573. if (!segment) { continue; }
  6574. parts[k] = parts[k] || [];
  6575. parts[k].push(segment[0]);
  6576. // if segment goes out of screen, or it's the last one, it's the end of the line part
  6577. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  6578. parts[k].push(segment[1]);
  6579. k++;
  6580. }
  6581. }
  6582. }
  6583. },
  6584. // simplify each clipped part of the polyline for performance
  6585. _simplifyPoints: function () {
  6586. var parts = this._parts,
  6587. tolerance = this.options.smoothFactor;
  6588. for (var i = 0, len = parts.length; i < len; i++) {
  6589. parts[i] = simplify(parts[i], tolerance);
  6590. }
  6591. },
  6592. _update: function () {
  6593. if (!this._map) { return; }
  6594. this._clipPoints();
  6595. this._simplifyPoints();
  6596. this._updatePath();
  6597. },
  6598. _updatePath: function () {
  6599. this._renderer._updatePoly(this);
  6600. },
  6601. // Needed by the `Canvas` renderer for interactivity
  6602. _containsPoint: function (p, closed) {
  6603. var i, j, k, len, len2, part,
  6604. w = this._clickTolerance();
  6605. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  6606. // hit detection for polylines
  6607. for (i = 0, len = this._parts.length; i < len; i++) {
  6608. part = this._parts[i];
  6609. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6610. if (!closed && (j === 0)) { continue; }
  6611. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  6612. return true;
  6613. }
  6614. }
  6615. }
  6616. return false;
  6617. }
  6618. });
  6619. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  6620. // Instantiates a polyline object given an array of geographical points and
  6621. // optionally an options object. You can create a `Polyline` object with
  6622. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  6623. // of geographic points.
  6624. function polyline(latlngs, options) {
  6625. return new Polyline(latlngs, options);
  6626. }
  6627. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  6628. Polyline._flat = _flat;
  6629. /*
  6630. * @class Polygon
  6631. * @aka L.Polygon
  6632. * @inherits Polyline
  6633. *
  6634. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  6635. *
  6636. * 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.
  6637. *
  6638. *
  6639. * @example
  6640. *
  6641. * ```js
  6642. * // create a red polygon from an array of LatLng points
  6643. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  6644. *
  6645. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  6646. *
  6647. * // zoom the map to the polygon
  6648. * map.fitBounds(polygon.getBounds());
  6649. * ```
  6650. *
  6651. * 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:
  6652. *
  6653. * ```js
  6654. * var latlngs = [
  6655. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6656. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6657. * ];
  6658. * ```
  6659. *
  6660. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  6661. *
  6662. * ```js
  6663. * var latlngs = [
  6664. * [ // first polygon
  6665. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6666. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6667. * ],
  6668. * [ // second polygon
  6669. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  6670. * ]
  6671. * ];
  6672. * ```
  6673. */
  6674. var Polygon = Polyline.extend({
  6675. options: {
  6676. fill: true
  6677. },
  6678. isEmpty: function () {
  6679. return !this._latlngs.length || !this._latlngs[0].length;
  6680. },
  6681. getCenter: function () {
  6682. // throws error when not yet added to map as this center calculation requires projected coordinates
  6683. if (!this._map) {
  6684. throw new Error('Must add layer to map before using getCenter()');
  6685. }
  6686. var i, j, p1, p2, f, area, x, y, center,
  6687. points = this._rings[0],
  6688. len = points.length;
  6689. if (!len) { return null; }
  6690. // polygon centroid algorithm; only uses the first ring if there are multiple
  6691. area = x = y = 0;
  6692. for (i = 0, j = len - 1; i < len; j = i++) {
  6693. p1 = points[i];
  6694. p2 = points[j];
  6695. f = p1.y * p2.x - p2.y * p1.x;
  6696. x += (p1.x + p2.x) * f;
  6697. y += (p1.y + p2.y) * f;
  6698. area += f * 3;
  6699. }
  6700. if (area === 0) {
  6701. // Polygon is so small that all points are on same pixel.
  6702. center = points[0];
  6703. } else {
  6704. center = [x / area, y / area];
  6705. }
  6706. return this._map.layerPointToLatLng(center);
  6707. },
  6708. _convertLatLngs: function (latlngs) {
  6709. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  6710. len = result.length;
  6711. // remove last point if it equals first one
  6712. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  6713. result.pop();
  6714. }
  6715. return result;
  6716. },
  6717. _setLatLngs: function (latlngs) {
  6718. Polyline.prototype._setLatLngs.call(this, latlngs);
  6719. if (isFlat(this._latlngs)) {
  6720. this._latlngs = [this._latlngs];
  6721. }
  6722. },
  6723. _defaultShape: function () {
  6724. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  6725. },
  6726. _clipPoints: function () {
  6727. // polygons need a different clipping algorithm so we redefine that
  6728. var bounds = this._renderer._bounds,
  6729. w = this.options.weight,
  6730. p = new Point(w, w);
  6731. // increase clip padding by stroke width to avoid stroke on clip edges
  6732. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  6733. this._parts = [];
  6734. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6735. return;
  6736. }
  6737. if (this.options.noClip) {
  6738. this._parts = this._rings;
  6739. return;
  6740. }
  6741. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  6742. clipped = clipPolygon(this._rings[i], bounds, true);
  6743. if (clipped.length) {
  6744. this._parts.push(clipped);
  6745. }
  6746. }
  6747. },
  6748. _updatePath: function () {
  6749. this._renderer._updatePoly(this, true);
  6750. },
  6751. // Needed by the `Canvas` renderer for interactivity
  6752. _containsPoint: function (p) {
  6753. var inside = false,
  6754. part, p1, p2, i, j, k, len, len2;
  6755. if (!this._pxBounds.contains(p)) { return false; }
  6756. // ray casting algorithm for detecting if point is in polygon
  6757. for (i = 0, len = this._parts.length; i < len; i++) {
  6758. part = this._parts[i];
  6759. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6760. p1 = part[j];
  6761. p2 = part[k];
  6762. 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)) {
  6763. inside = !inside;
  6764. }
  6765. }
  6766. }
  6767. // also check if it's on polygon stroke
  6768. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  6769. }
  6770. });
  6771. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  6772. function polygon(latlngs, options) {
  6773. return new Polygon(latlngs, options);
  6774. }
  6775. /*
  6776. * @class GeoJSON
  6777. * @aka L.GeoJSON
  6778. * @inherits FeatureGroup
  6779. *
  6780. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  6781. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  6782. *
  6783. * @example
  6784. *
  6785. * ```js
  6786. * L.geoJSON(data, {
  6787. * style: function (feature) {
  6788. * return {color: feature.properties.color};
  6789. * }
  6790. * }).bindPopup(function (layer) {
  6791. * return layer.feature.properties.description;
  6792. * }).addTo(map);
  6793. * ```
  6794. */
  6795. var GeoJSON = FeatureGroup.extend({
  6796. /* @section
  6797. * @aka GeoJSON options
  6798. *
  6799. * @option pointToLayer: Function = *
  6800. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  6801. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  6802. * The default is to spawn a default `Marker`:
  6803. * ```js
  6804. * function(geoJsonPoint, latlng) {
  6805. * return L.marker(latlng);
  6806. * }
  6807. * ```
  6808. *
  6809. * @option style: Function = *
  6810. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  6811. * called internally when data is added.
  6812. * The default value is to not override any defaults:
  6813. * ```js
  6814. * function (geoJsonFeature) {
  6815. * return {}
  6816. * }
  6817. * ```
  6818. *
  6819. * @option onEachFeature: Function = *
  6820. * A `Function` that will be called once for each created `Feature`, after it has
  6821. * been created and styled. Useful for attaching events and popups to features.
  6822. * The default is to do nothing with the newly created layers:
  6823. * ```js
  6824. * function (feature, layer) {}
  6825. * ```
  6826. *
  6827. * @option filter: Function = *
  6828. * A `Function` that will be used to decide whether to include a feature or not.
  6829. * The default is to include all features:
  6830. * ```js
  6831. * function (geoJsonFeature) {
  6832. * return true;
  6833. * }
  6834. * ```
  6835. * Note: dynamically changing the `filter` option will have effect only on newly
  6836. * added data. It will _not_ re-evaluate already included features.
  6837. *
  6838. * @option coordsToLatLng: Function = *
  6839. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  6840. * The default is the `coordsToLatLng` static method.
  6841. */
  6842. initialize: function (geojson, options) {
  6843. setOptions(this, options);
  6844. this._layers = {};
  6845. if (geojson) {
  6846. this.addData(geojson);
  6847. }
  6848. },
  6849. // @method addData( <GeoJSON> data ): this
  6850. // Adds a GeoJSON object to the layer.
  6851. addData: function (geojson) {
  6852. var features = isArray(geojson) ? geojson : geojson.features,
  6853. i, len, feature;
  6854. if (features) {
  6855. for (i = 0, len = features.length; i < len; i++) {
  6856. // only add this if geometry or geometries are set and not null
  6857. feature = features[i];
  6858. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  6859. this.addData(feature);
  6860. }
  6861. }
  6862. return this;
  6863. }
  6864. var options = this.options;
  6865. if (options.filter && !options.filter(geojson)) { return this; }
  6866. var layer = geometryToLayer(geojson, options);
  6867. if (!layer) {
  6868. return this;
  6869. }
  6870. layer.feature = asFeature(geojson);
  6871. layer.defaultOptions = layer.options;
  6872. this.resetStyle(layer);
  6873. if (options.onEachFeature) {
  6874. options.onEachFeature(geojson, layer);
  6875. }
  6876. return this.addLayer(layer);
  6877. },
  6878. // @method resetStyle( <Path> layer ): this
  6879. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  6880. resetStyle: function (layer) {
  6881. // reset any custom styles
  6882. layer.options = extend({}, layer.defaultOptions);
  6883. this._setLayerStyle(layer, this.options.style);
  6884. return this;
  6885. },
  6886. // @method setStyle( <Function> style ): this
  6887. // Changes styles of GeoJSON vector layers with the given style function.
  6888. setStyle: function (style) {
  6889. return this.eachLayer(function (layer) {
  6890. this._setLayerStyle(layer, style);
  6891. }, this);
  6892. },
  6893. _setLayerStyle: function (layer, style) {
  6894. if (typeof style === 'function') {
  6895. style = style(layer.feature);
  6896. }
  6897. if (layer.setStyle) {
  6898. layer.setStyle(style);
  6899. }
  6900. }
  6901. });
  6902. // @section
  6903. // There are several static functions which can be called without instantiating L.GeoJSON:
  6904. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  6905. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  6906. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  6907. // functions if provided as options.
  6908. function geometryToLayer(geojson, options) {
  6909. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  6910. coords = geometry ? geometry.coordinates : null,
  6911. layers = [],
  6912. pointToLayer = options && options.pointToLayer,
  6913. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  6914. latlng, latlngs, i, len;
  6915. if (!coords && !geometry) {
  6916. return null;
  6917. }
  6918. switch (geometry.type) {
  6919. case 'Point':
  6920. latlng = _coordsToLatLng(coords);
  6921. return pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng);
  6922. case 'MultiPoint':
  6923. for (i = 0, len = coords.length; i < len; i++) {
  6924. latlng = _coordsToLatLng(coords[i]);
  6925. layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng));
  6926. }
  6927. return new FeatureGroup(layers);
  6928. case 'LineString':
  6929. case 'MultiLineString':
  6930. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  6931. return new Polyline(latlngs, options);
  6932. case 'Polygon':
  6933. case 'MultiPolygon':
  6934. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  6935. return new Polygon(latlngs, options);
  6936. case 'GeometryCollection':
  6937. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  6938. var layer = geometryToLayer({
  6939. geometry: geometry.geometries[i],
  6940. type: 'Feature',
  6941. properties: geojson.properties
  6942. }, options);
  6943. if (layer) {
  6944. layers.push(layer);
  6945. }
  6946. }
  6947. return new FeatureGroup(layers);
  6948. default:
  6949. throw new Error('Invalid GeoJSON object.');
  6950. }
  6951. }
  6952. // @function coordsToLatLng(coords: Array): LatLng
  6953. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  6954. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  6955. function coordsToLatLng(coords) {
  6956. return new LatLng(coords[1], coords[0], coords[2]);
  6957. }
  6958. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  6959. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  6960. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  6961. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  6962. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  6963. var latlngs = [];
  6964. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  6965. latlng = levelsDeep ?
  6966. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  6967. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  6968. latlngs.push(latlng);
  6969. }
  6970. return latlngs;
  6971. }
  6972. // @function latLngToCoords(latlng: LatLng, precision?: Number): Array
  6973. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  6974. function latLngToCoords(latlng, precision) {
  6975. precision = typeof precision === 'number' ? precision : 6;
  6976. return latlng.alt !== undefined ?
  6977. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  6978. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  6979. }
  6980. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  6981. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  6982. // `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.
  6983. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  6984. var coords = [];
  6985. for (var i = 0, len = latlngs.length; i < len; i++) {
  6986. coords.push(levelsDeep ?
  6987. latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :
  6988. latLngToCoords(latlngs[i], precision));
  6989. }
  6990. if (!levelsDeep && closed) {
  6991. coords.push(coords[0]);
  6992. }
  6993. return coords;
  6994. }
  6995. function getFeature(layer, newGeometry) {
  6996. return layer.feature ?
  6997. extend({}, layer.feature, {geometry: newGeometry}) :
  6998. asFeature(newGeometry);
  6999. }
  7000. // @function asFeature(geojson: Object): Object
  7001. // Normalize GeoJSON geometries/features into GeoJSON features.
  7002. function asFeature(geojson) {
  7003. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7004. return geojson;
  7005. }
  7006. return {
  7007. type: 'Feature',
  7008. properties: {},
  7009. geometry: geojson
  7010. };
  7011. }
  7012. var PointToGeoJSON = {
  7013. toGeoJSON: function (precision) {
  7014. return getFeature(this, {
  7015. type: 'Point',
  7016. coordinates: latLngToCoords(this.getLatLng(), precision)
  7017. });
  7018. }
  7019. };
  7020. // @namespace Marker
  7021. // @method toGeoJSON(): Object
  7022. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7023. Marker.include(PointToGeoJSON);
  7024. // @namespace CircleMarker
  7025. // @method toGeoJSON(): Object
  7026. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7027. Circle.include(PointToGeoJSON);
  7028. CircleMarker.include(PointToGeoJSON);
  7029. // @namespace Polyline
  7030. // @method toGeoJSON(): Object
  7031. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7032. Polyline.include({
  7033. toGeoJSON: function (precision) {
  7034. var multi = !isFlat(this._latlngs);
  7035. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7036. return getFeature(this, {
  7037. type: (multi ? 'Multi' : '') + 'LineString',
  7038. coordinates: coords
  7039. });
  7040. }
  7041. });
  7042. // @namespace Polygon
  7043. // @method toGeoJSON(): Object
  7044. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7045. Polygon.include({
  7046. toGeoJSON: function (precision) {
  7047. var holes = !isFlat(this._latlngs),
  7048. multi = holes && !isFlat(this._latlngs[0]);
  7049. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7050. if (!holes) {
  7051. coords = [coords];
  7052. }
  7053. return getFeature(this, {
  7054. type: (multi ? 'Multi' : '') + 'Polygon',
  7055. coordinates: coords
  7056. });
  7057. }
  7058. });
  7059. // @namespace LayerGroup
  7060. LayerGroup.include({
  7061. toMultiPoint: function (precision) {
  7062. var coords = [];
  7063. this.eachLayer(function (layer) {
  7064. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7065. });
  7066. return getFeature(this, {
  7067. type: 'MultiPoint',
  7068. coordinates: coords
  7069. });
  7070. },
  7071. // @method toGeoJSON(): Object
  7072. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7073. toGeoJSON: function (precision) {
  7074. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7075. if (type === 'MultiPoint') {
  7076. return this.toMultiPoint(precision);
  7077. }
  7078. var isGeometryCollection = type === 'GeometryCollection',
  7079. jsons = [];
  7080. this.eachLayer(function (layer) {
  7081. if (layer.toGeoJSON) {
  7082. var json = layer.toGeoJSON(precision);
  7083. if (isGeometryCollection) {
  7084. jsons.push(json.geometry);
  7085. } else {
  7086. var feature = asFeature(json);
  7087. // Squash nested feature collections
  7088. if (feature.type === 'FeatureCollection') {
  7089. jsons.push.apply(jsons, feature.features);
  7090. } else {
  7091. jsons.push(feature);
  7092. }
  7093. }
  7094. }
  7095. });
  7096. if (isGeometryCollection) {
  7097. return getFeature(this, {
  7098. geometries: jsons,
  7099. type: 'GeometryCollection'
  7100. });
  7101. }
  7102. return {
  7103. type: 'FeatureCollection',
  7104. features: jsons
  7105. };
  7106. }
  7107. });
  7108. // @namespace GeoJSON
  7109. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7110. // Creates a GeoJSON layer. Optionally accepts an object in
  7111. // [GeoJSON format](http://geojson.org/geojson-spec.html) to display on the map
  7112. // (you can alternatively add it later with `addData` method) and an `options` object.
  7113. function geoJSON(geojson, options) {
  7114. return new GeoJSON(geojson, options);
  7115. }
  7116. // Backward compatibility.
  7117. var geoJson = geoJSON;
  7118. /*
  7119. * @class ImageOverlay
  7120. * @aka L.ImageOverlay
  7121. * @inherits Interactive layer
  7122. *
  7123. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7124. *
  7125. * @example
  7126. *
  7127. * ```js
  7128. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7129. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7130. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7131. * ```
  7132. */
  7133. var ImageOverlay = Layer.extend({
  7134. // @section
  7135. // @aka ImageOverlay options
  7136. options: {
  7137. // @option opacity: Number = 1.0
  7138. // The opacity of the image overlay.
  7139. opacity: 1,
  7140. // @option alt: String = ''
  7141. // Text for the `alt` attribute of the image (useful for accessibility).
  7142. alt: '',
  7143. // @option interactive: Boolean = false
  7144. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7145. interactive: false,
  7146. // @option crossOrigin: Boolean = false
  7147. // If true, the image will have its crossOrigin attribute set to ''. This is needed if you want to access image pixel data.
  7148. crossOrigin: false,
  7149. // @option errorOverlayUrl: String = ''
  7150. // URL to the overlay image to show in place of the overlay that failed to load.
  7151. errorOverlayUrl: '',
  7152. // @option zIndex: Number = 1
  7153. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the tile layer.
  7154. zIndex: 1,
  7155. // @option className: String = ''
  7156. // A custom class name to assign to the image. Empty by default.
  7157. className: '',
  7158. },
  7159. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7160. this._url = url;
  7161. this._bounds = toLatLngBounds(bounds);
  7162. setOptions(this, options);
  7163. },
  7164. onAdd: function () {
  7165. if (!this._image) {
  7166. this._initImage();
  7167. if (this.options.opacity < 1) {
  7168. this._updateOpacity();
  7169. }
  7170. }
  7171. if (this.options.interactive) {
  7172. addClass(this._image, 'leaflet-interactive');
  7173. this.addInteractiveTarget(this._image);
  7174. }
  7175. this.getPane().appendChild(this._image);
  7176. this._reset();
  7177. },
  7178. onRemove: function () {
  7179. remove(this._image);
  7180. if (this.options.interactive) {
  7181. this.removeInteractiveTarget(this._image);
  7182. }
  7183. },
  7184. // @method setOpacity(opacity: Number): this
  7185. // Sets the opacity of the overlay.
  7186. setOpacity: function (opacity) {
  7187. this.options.opacity = opacity;
  7188. if (this._image) {
  7189. this._updateOpacity();
  7190. }
  7191. return this;
  7192. },
  7193. setStyle: function (styleOpts) {
  7194. if (styleOpts.opacity) {
  7195. this.setOpacity(styleOpts.opacity);
  7196. }
  7197. return this;
  7198. },
  7199. // @method bringToFront(): this
  7200. // Brings the layer to the top of all overlays.
  7201. bringToFront: function () {
  7202. if (this._map) {
  7203. toFront(this._image);
  7204. }
  7205. return this;
  7206. },
  7207. // @method bringToBack(): this
  7208. // Brings the layer to the bottom of all overlays.
  7209. bringToBack: function () {
  7210. if (this._map) {
  7211. toBack(this._image);
  7212. }
  7213. return this;
  7214. },
  7215. // @method setUrl(url: String): this
  7216. // Changes the URL of the image.
  7217. setUrl: function (url) {
  7218. this._url = url;
  7219. if (this._image) {
  7220. this._image.src = url;
  7221. }
  7222. return this;
  7223. },
  7224. // @method setBounds(bounds: LatLngBounds): this
  7225. // Update the bounds that this ImageOverlay covers
  7226. setBounds: function (bounds) {
  7227. this._bounds = toLatLngBounds(bounds);
  7228. if (this._map) {
  7229. this._reset();
  7230. }
  7231. return this;
  7232. },
  7233. getEvents: function () {
  7234. var events = {
  7235. zoom: this._reset,
  7236. viewreset: this._reset
  7237. };
  7238. if (this._zoomAnimated) {
  7239. events.zoomanim = this._animateZoom;
  7240. }
  7241. return events;
  7242. },
  7243. // @method: setZIndex(value: Number) : this
  7244. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7245. setZIndex: function (value) {
  7246. this.options.zIndex = value;
  7247. this._updateZIndex();
  7248. return this;
  7249. },
  7250. // @method getBounds(): LatLngBounds
  7251. // Get the bounds that this ImageOverlay covers
  7252. getBounds: function () {
  7253. return this._bounds;
  7254. },
  7255. // @method getElement(): HTMLElement
  7256. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7257. // used by this overlay.
  7258. getElement: function () {
  7259. return this._image;
  7260. },
  7261. _initImage: function () {
  7262. var img = this._image = create$1('img',
  7263. 'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated' : '') +
  7264. (this.options.className || ''));
  7265. img.onselectstart = falseFn;
  7266. img.onmousemove = falseFn;
  7267. // @event load: Event
  7268. // Fired when the ImageOverlay layer has loaded its image
  7269. img.onload = bind(this.fire, this, 'load');
  7270. img.onerror = bind(this._overlayOnError, this, 'error');
  7271. if (this.options.crossOrigin) {
  7272. img.crossOrigin = '';
  7273. }
  7274. if (this.options.zIndex) {
  7275. this._updateZIndex();
  7276. }
  7277. img.src = this._url;
  7278. img.alt = this.options.alt;
  7279. },
  7280. _animateZoom: function (e) {
  7281. var scale = this._map.getZoomScale(e.zoom),
  7282. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7283. setTransform(this._image, offset, scale);
  7284. },
  7285. _reset: function () {
  7286. var image = this._image,
  7287. bounds = new Bounds(
  7288. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7289. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7290. size = bounds.getSize();
  7291. setPosition(image, bounds.min);
  7292. image.style.width = size.x + 'px';
  7293. image.style.height = size.y + 'px';
  7294. },
  7295. _updateOpacity: function () {
  7296. setOpacity(this._image, this.options.opacity);
  7297. },
  7298. _updateZIndex: function () {
  7299. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7300. this._image.style.zIndex = this.options.zIndex;
  7301. }
  7302. },
  7303. _overlayOnError: function () {
  7304. // @event error: Event
  7305. // Fired when the ImageOverlay layer has loaded its image
  7306. this.fire('error');
  7307. var errorUrl = this.options.errorOverlayUrl;
  7308. if (errorUrl && this._url !== errorUrl) {
  7309. this._url = errorUrl;
  7310. this._image.src = errorUrl;
  7311. }
  7312. }
  7313. });
  7314. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7315. // Instantiates an image overlay object given the URL of the image and the
  7316. // geographical bounds it is tied to.
  7317. var imageOverlay = function (url, bounds, options) {
  7318. return new ImageOverlay(url, bounds, options);
  7319. };
  7320. /*
  7321. * @class VideoOverlay
  7322. * @aka L.VideoOverlay
  7323. * @inherits ImageOverlay
  7324. *
  7325. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7326. *
  7327. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7328. * HTML5 element.
  7329. *
  7330. * @example
  7331. *
  7332. * ```js
  7333. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7334. * videoBounds = [[ 32, -130], [ 13, -100]];
  7335. * L.VideoOverlay(videoUrl, videoBounds ).addTo(map);
  7336. * ```
  7337. */
  7338. var VideoOverlay = ImageOverlay.extend({
  7339. // @section
  7340. // @aka VideoOverlay options
  7341. options: {
  7342. // @option autoplay: Boolean = true
  7343. // Whether the video starts playing automatically when loaded.
  7344. autoplay: true,
  7345. // @option loop: Boolean = true
  7346. // Whether the video will loop back to the beginning when played.
  7347. loop: true
  7348. },
  7349. _initImage: function () {
  7350. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7351. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7352. vid.class = vid.class || '';
  7353. vid.class += 'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated' : '');
  7354. vid.onselectstart = falseFn;
  7355. vid.onmousemove = falseFn;
  7356. // @event load: Event
  7357. // Fired when the video has finished loading the first frame
  7358. vid.onloadeddata = bind(this.fire, this, 'load');
  7359. if (wasElementSupplied) { return; }
  7360. if (!isArray(this._url)) { this._url = [this._url]; }
  7361. vid.autoplay = !!this.options.autoplay;
  7362. vid.loop = !!this.options.loop;
  7363. for (var i = 0; i < this._url.length; i++) {
  7364. var source = create$1('source');
  7365. source.src = this._url[i];
  7366. vid.appendChild(source);
  7367. }
  7368. }
  7369. // @method getElement(): HTMLVideoElement
  7370. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7371. // used by this overlay.
  7372. });
  7373. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7374. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7375. // geographical bounds it is tied to.
  7376. function videoOverlay(video, bounds, options) {
  7377. return new VideoOverlay(video, bounds, options);
  7378. }
  7379. /*
  7380. * @class DivOverlay
  7381. * @inherits Layer
  7382. * @aka L.DivOverlay
  7383. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  7384. */
  7385. // @namespace DivOverlay
  7386. var DivOverlay = Layer.extend({
  7387. // @section
  7388. // @aka DivOverlay options
  7389. options: {
  7390. // @option offset: Point = Point(0, 7)
  7391. // The offset of the popup position. Useful to control the anchor
  7392. // of the popup when opening it on some overlays.
  7393. offset: [0, 7],
  7394. // @option className: String = ''
  7395. // A custom CSS class name to assign to the popup.
  7396. className: '',
  7397. // @option pane: String = 'popupPane'
  7398. // `Map pane` where the popup will be added.
  7399. pane: 'popupPane'
  7400. },
  7401. initialize: function (options, source) {
  7402. setOptions(this, options);
  7403. this._source = source;
  7404. },
  7405. onAdd: function (map) {
  7406. this._zoomAnimated = map._zoomAnimated;
  7407. if (!this._container) {
  7408. this._initLayout();
  7409. }
  7410. if (map._fadeAnimated) {
  7411. setOpacity(this._container, 0);
  7412. }
  7413. clearTimeout(this._removeTimeout);
  7414. this.getPane().appendChild(this._container);
  7415. this.update();
  7416. if (map._fadeAnimated) {
  7417. setOpacity(this._container, 1);
  7418. }
  7419. this.bringToFront();
  7420. },
  7421. onRemove: function (map) {
  7422. if (map._fadeAnimated) {
  7423. setOpacity(this._container, 0);
  7424. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  7425. } else {
  7426. remove(this._container);
  7427. }
  7428. },
  7429. // @namespace Popup
  7430. // @method getLatLng: LatLng
  7431. // Returns the geographical point of popup.
  7432. getLatLng: function () {
  7433. return this._latlng;
  7434. },
  7435. // @method setLatLng(latlng: LatLng): this
  7436. // Sets the geographical point where the popup will open.
  7437. setLatLng: function (latlng) {
  7438. this._latlng = toLatLng(latlng);
  7439. if (this._map) {
  7440. this._updatePosition();
  7441. this._adjustPan();
  7442. }
  7443. return this;
  7444. },
  7445. // @method getContent: String|HTMLElement
  7446. // Returns the content of the popup.
  7447. getContent: function () {
  7448. return this._content;
  7449. },
  7450. // @method setContent(htmlContent: String|HTMLElement|Function): this
  7451. // 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.
  7452. setContent: function (content) {
  7453. this._content = content;
  7454. this.update();
  7455. return this;
  7456. },
  7457. // @method getElement: String|HTMLElement
  7458. // Alias for [getContent()](#popup-getcontent)
  7459. getElement: function () {
  7460. return this._container;
  7461. },
  7462. // @method update: null
  7463. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  7464. update: function () {
  7465. if (!this._map) { return; }
  7466. this._container.style.visibility = 'hidden';
  7467. this._updateContent();
  7468. this._updateLayout();
  7469. this._updatePosition();
  7470. this._container.style.visibility = '';
  7471. this._adjustPan();
  7472. },
  7473. getEvents: function () {
  7474. var events = {
  7475. zoom: this._updatePosition,
  7476. viewreset: this._updatePosition
  7477. };
  7478. if (this._zoomAnimated) {
  7479. events.zoomanim = this._animateZoom;
  7480. }
  7481. return events;
  7482. },
  7483. // @method isOpen: Boolean
  7484. // Returns `true` when the popup is visible on the map.
  7485. isOpen: function () {
  7486. return !!this._map && this._map.hasLayer(this);
  7487. },
  7488. // @method bringToFront: this
  7489. // Brings this popup in front of other popups (in the same map pane).
  7490. bringToFront: function () {
  7491. if (this._map) {
  7492. toFront(this._container);
  7493. }
  7494. return this;
  7495. },
  7496. // @method bringToBack: this
  7497. // Brings this popup to the back of other popups (in the same map pane).
  7498. bringToBack: function () {
  7499. if (this._map) {
  7500. toBack(this._container);
  7501. }
  7502. return this;
  7503. },
  7504. _updateContent: function () {
  7505. if (!this._content) { return; }
  7506. var node = this._contentNode;
  7507. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  7508. if (typeof content === 'string') {
  7509. node.innerHTML = content;
  7510. } else {
  7511. while (node.hasChildNodes()) {
  7512. node.removeChild(node.firstChild);
  7513. }
  7514. node.appendChild(content);
  7515. }
  7516. this.fire('contentupdate');
  7517. },
  7518. _updatePosition: function () {
  7519. if (!this._map) { return; }
  7520. var pos = this._map.latLngToLayerPoint(this._latlng),
  7521. offset = toPoint(this.options.offset),
  7522. anchor = this._getAnchor();
  7523. if (this._zoomAnimated) {
  7524. setPosition(this._container, pos.add(anchor));
  7525. } else {
  7526. offset = offset.add(pos).add(anchor);
  7527. }
  7528. var bottom = this._containerBottom = -offset.y,
  7529. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  7530. // bottom position the popup in case the height of the popup changes (images loading etc)
  7531. this._container.style.bottom = bottom + 'px';
  7532. this._container.style.left = left + 'px';
  7533. },
  7534. _getAnchor: function () {
  7535. return [0, 0];
  7536. }
  7537. });
  7538. /*
  7539. * @class Popup
  7540. * @inherits DivOverlay
  7541. * @aka L.Popup
  7542. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  7543. * open popups while making sure that only one popup is open at one time
  7544. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  7545. *
  7546. * @example
  7547. *
  7548. * If you want to just bind a popup to marker click and then open it, it's really easy:
  7549. *
  7550. * ```js
  7551. * marker.bindPopup(popupContent).openPopup();
  7552. * ```
  7553. * Path overlays like polylines also have a `bindPopup` method.
  7554. * Here's a more complicated way to open a popup on a map:
  7555. *
  7556. * ```js
  7557. * var popup = L.popup()
  7558. * .setLatLng(latlng)
  7559. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  7560. * .openOn(map);
  7561. * ```
  7562. */
  7563. // @namespace Popup
  7564. var Popup = DivOverlay.extend({
  7565. // @section
  7566. // @aka Popup options
  7567. options: {
  7568. // @option maxWidth: Number = 300
  7569. // Max width of the popup, in pixels.
  7570. maxWidth: 300,
  7571. // @option minWidth: Number = 50
  7572. // Min width of the popup, in pixels.
  7573. minWidth: 50,
  7574. // @option maxHeight: Number = null
  7575. // If set, creates a scrollable container of the given height
  7576. // inside a popup if its content exceeds it.
  7577. maxHeight: null,
  7578. // @option autoPan: Boolean = true
  7579. // Set it to `false` if you don't want the map to do panning animation
  7580. // to fit the opened popup.
  7581. autoPan: true,
  7582. // @option autoPanPaddingTopLeft: Point = null
  7583. // The margin between the popup and the top left corner of the map
  7584. // view after autopanning was performed.
  7585. autoPanPaddingTopLeft: null,
  7586. // @option autoPanPaddingBottomRight: Point = null
  7587. // The margin between the popup and the bottom right corner of the map
  7588. // view after autopanning was performed.
  7589. autoPanPaddingBottomRight: null,
  7590. // @option autoPanPadding: Point = Point(5, 5)
  7591. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  7592. autoPanPadding: [5, 5],
  7593. // @option keepInView: Boolean = false
  7594. // Set it to `true` if you want to prevent users from panning the popup
  7595. // off of the screen while it is open.
  7596. keepInView: false,
  7597. // @option closeButton: Boolean = true
  7598. // Controls the presence of a close button in the popup.
  7599. closeButton: true,
  7600. // @option autoClose: Boolean = true
  7601. // Set it to `false` if you want to override the default behavior of
  7602. // the popup closing when another popup is opened.
  7603. autoClose: true,
  7604. // @option closeOnClick: Boolean = *
  7605. // Set it if you want to override the default behavior of the popup closing when user clicks
  7606. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  7607. // @option className: String = ''
  7608. // A custom CSS class name to assign to the popup.
  7609. className: ''
  7610. },
  7611. // @namespace Popup
  7612. // @method openOn(map: Map): this
  7613. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  7614. openOn: function (map) {
  7615. map.openPopup(this);
  7616. return this;
  7617. },
  7618. onAdd: function (map) {
  7619. DivOverlay.prototype.onAdd.call(this, map);
  7620. // @namespace Map
  7621. // @section Popup events
  7622. // @event popupopen: PopupEvent
  7623. // Fired when a popup is opened in the map
  7624. map.fire('popupopen', {popup: this});
  7625. if (this._source) {
  7626. // @namespace Layer
  7627. // @section Popup events
  7628. // @event popupopen: PopupEvent
  7629. // Fired when a popup bound to this layer is opened
  7630. this._source.fire('popupopen', {popup: this}, true);
  7631. // For non-path layers, we toggle the popup when clicking
  7632. // again the layer, so prevent the map to reopen it.
  7633. if (!(this._source instanceof Path)) {
  7634. this._source.on('preclick', stopPropagation);
  7635. }
  7636. }
  7637. },
  7638. onRemove: function (map) {
  7639. DivOverlay.prototype.onRemove.call(this, map);
  7640. // @namespace Map
  7641. // @section Popup events
  7642. // @event popupclose: PopupEvent
  7643. // Fired when a popup in the map is closed
  7644. map.fire('popupclose', {popup: this});
  7645. if (this._source) {
  7646. // @namespace Layer
  7647. // @section Popup events
  7648. // @event popupclose: PopupEvent
  7649. // Fired when a popup bound to this layer is closed
  7650. this._source.fire('popupclose', {popup: this}, true);
  7651. if (!(this._source instanceof Path)) {
  7652. this._source.off('preclick', stopPropagation);
  7653. }
  7654. }
  7655. },
  7656. getEvents: function () {
  7657. var events = DivOverlay.prototype.getEvents.call(this);
  7658. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  7659. events.preclick = this._close;
  7660. }
  7661. if (this.options.keepInView) {
  7662. events.moveend = this._adjustPan;
  7663. }
  7664. return events;
  7665. },
  7666. _close: function () {
  7667. if (this._map) {
  7668. this._map.closePopup(this);
  7669. }
  7670. },
  7671. _initLayout: function () {
  7672. var prefix = 'leaflet-popup',
  7673. container = this._container = create$1('div',
  7674. prefix + ' ' + (this.options.className || '') +
  7675. ' leaflet-zoom-animated');
  7676. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  7677. this._contentNode = create$1('div', prefix + '-content', wrapper);
  7678. disableClickPropagation(wrapper);
  7679. disableScrollPropagation(this._contentNode);
  7680. on(wrapper, 'contextmenu', stopPropagation);
  7681. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  7682. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  7683. if (this.options.closeButton) {
  7684. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  7685. closeButton.href = '#close';
  7686. closeButton.innerHTML = '&#215;';
  7687. on(closeButton, 'click', this._onCloseButtonClick, this);
  7688. }
  7689. },
  7690. _updateLayout: function () {
  7691. var container = this._contentNode,
  7692. style = container.style;
  7693. style.width = '';
  7694. style.whiteSpace = 'nowrap';
  7695. var width = container.offsetWidth;
  7696. width = Math.min(width, this.options.maxWidth);
  7697. width = Math.max(width, this.options.minWidth);
  7698. style.width = (width + 1) + 'px';
  7699. style.whiteSpace = '';
  7700. style.height = '';
  7701. var height = container.offsetHeight,
  7702. maxHeight = this.options.maxHeight,
  7703. scrolledClass = 'leaflet-popup-scrolled';
  7704. if (maxHeight && height > maxHeight) {
  7705. style.height = maxHeight + 'px';
  7706. addClass(container, scrolledClass);
  7707. } else {
  7708. removeClass(container, scrolledClass);
  7709. }
  7710. this._containerWidth = this._container.offsetWidth;
  7711. },
  7712. _animateZoom: function (e) {
  7713. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  7714. anchor = this._getAnchor();
  7715. setPosition(this._container, pos.add(anchor));
  7716. },
  7717. _adjustPan: function () {
  7718. if (!this.options.autoPan || (this._map._panAnim && this._map._panAnim._inProgress)) { return; }
  7719. var map = this._map,
  7720. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  7721. containerHeight = this._container.offsetHeight + marginBottom,
  7722. containerWidth = this._containerWidth,
  7723. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  7724. layerPos._add(getPosition(this._container));
  7725. var containerPos = map.layerPointToContainerPoint(layerPos),
  7726. padding = toPoint(this.options.autoPanPadding),
  7727. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  7728. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  7729. size = map.getSize(),
  7730. dx = 0,
  7731. dy = 0;
  7732. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  7733. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  7734. }
  7735. if (containerPos.x - dx - paddingTL.x < 0) { // left
  7736. dx = containerPos.x - paddingTL.x;
  7737. }
  7738. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  7739. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  7740. }
  7741. if (containerPos.y - dy - paddingTL.y < 0) { // top
  7742. dy = containerPos.y - paddingTL.y;
  7743. }
  7744. // @namespace Map
  7745. // @section Popup events
  7746. // @event autopanstart: Event
  7747. // Fired when the map starts autopanning when opening a popup.
  7748. if (dx || dy) {
  7749. map
  7750. .fire('autopanstart')
  7751. .panBy([dx, dy]);
  7752. }
  7753. },
  7754. _onCloseButtonClick: function (e) {
  7755. this._close();
  7756. stop(e);
  7757. },
  7758. _getAnchor: function () {
  7759. // Where should we anchor the popup on the source layer?
  7760. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  7761. }
  7762. });
  7763. // @namespace Popup
  7764. // @factory L.popup(options?: Popup options, source?: Layer)
  7765. // 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.
  7766. var popup = function (options, source) {
  7767. return new Popup(options, source);
  7768. };
  7769. /* @namespace Map
  7770. * @section Interaction Options
  7771. * @option closePopupOnClick: Boolean = true
  7772. * Set it to `false` if you don't want popups to close when user clicks the map.
  7773. */
  7774. Map.mergeOptions({
  7775. closePopupOnClick: true
  7776. });
  7777. // @namespace Map
  7778. // @section Methods for Layers and Controls
  7779. Map.include({
  7780. // @method openPopup(popup: Popup): this
  7781. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  7782. // @alternative
  7783. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  7784. // Creates a popup with the specified content and options and opens it in the given point on a map.
  7785. openPopup: function (popup, latlng, options) {
  7786. if (!(popup instanceof Popup)) {
  7787. popup = new Popup(options).setContent(popup);
  7788. }
  7789. if (latlng) {
  7790. popup.setLatLng(latlng);
  7791. }
  7792. if (this.hasLayer(popup)) {
  7793. return this;
  7794. }
  7795. if (this._popup && this._popup.options.autoClose) {
  7796. this.closePopup();
  7797. }
  7798. this._popup = popup;
  7799. return this.addLayer(popup);
  7800. },
  7801. // @method closePopup(popup?: Popup): this
  7802. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  7803. closePopup: function (popup) {
  7804. if (!popup || popup === this._popup) {
  7805. popup = this._popup;
  7806. this._popup = null;
  7807. }
  7808. if (popup) {
  7809. this.removeLayer(popup);
  7810. }
  7811. return this;
  7812. }
  7813. });
  7814. /*
  7815. * @namespace Layer
  7816. * @section Popup methods example
  7817. *
  7818. * All layers share a set of methods convenient for binding popups to it.
  7819. *
  7820. * ```js
  7821. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  7822. * layer.openPopup();
  7823. * layer.closePopup();
  7824. * ```
  7825. *
  7826. * 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.
  7827. */
  7828. // @section Popup methods
  7829. Layer.include({
  7830. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  7831. // Binds a popup to the layer with the passed `content` and sets up the
  7832. // necessary event listeners. If a `Function` is passed it will receive
  7833. // the layer as the first argument and should return a `String` or `HTMLElement`.
  7834. bindPopup: function (content, options) {
  7835. if (content instanceof Popup) {
  7836. setOptions(content, options);
  7837. this._popup = content;
  7838. content._source = this;
  7839. } else {
  7840. if (!this._popup || options) {
  7841. this._popup = new Popup(options, this);
  7842. }
  7843. this._popup.setContent(content);
  7844. }
  7845. if (!this._popupHandlersAdded) {
  7846. this.on({
  7847. click: this._openPopup,
  7848. keypress: this._onKeyPress,
  7849. remove: this.closePopup,
  7850. move: this._movePopup
  7851. });
  7852. this._popupHandlersAdded = true;
  7853. }
  7854. return this;
  7855. },
  7856. // @method unbindPopup(): this
  7857. // Removes the popup previously bound with `bindPopup`.
  7858. unbindPopup: function () {
  7859. if (this._popup) {
  7860. this.off({
  7861. click: this._openPopup,
  7862. keypress: this._onKeyPress,
  7863. remove: this.closePopup,
  7864. move: this._movePopup
  7865. });
  7866. this._popupHandlersAdded = false;
  7867. this._popup = null;
  7868. }
  7869. return this;
  7870. },
  7871. // @method openPopup(latlng?: LatLng): this
  7872. // Opens the bound popup at the specificed `latlng` or at the default popup anchor if no `latlng` is passed.
  7873. openPopup: function (layer, latlng) {
  7874. if (!(layer instanceof Layer)) {
  7875. latlng = layer;
  7876. layer = this;
  7877. }
  7878. if (layer instanceof FeatureGroup) {
  7879. for (var id in this._layers) {
  7880. layer = this._layers[id];
  7881. break;
  7882. }
  7883. }
  7884. if (!latlng) {
  7885. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  7886. }
  7887. if (this._popup && this._map) {
  7888. // set popup source to this layer
  7889. this._popup._source = layer;
  7890. // update the popup (content, layout, ect...)
  7891. this._popup.update();
  7892. // open the popup on the map
  7893. this._map.openPopup(this._popup, latlng);
  7894. }
  7895. return this;
  7896. },
  7897. // @method closePopup(): this
  7898. // Closes the popup bound to this layer if it is open.
  7899. closePopup: function () {
  7900. if (this._popup) {
  7901. this._popup._close();
  7902. }
  7903. return this;
  7904. },
  7905. // @method togglePopup(): this
  7906. // Opens or closes the popup bound to this layer depending on its current state.
  7907. togglePopup: function (target) {
  7908. if (this._popup) {
  7909. if (this._popup._map) {
  7910. this.closePopup();
  7911. } else {
  7912. this.openPopup(target);
  7913. }
  7914. }
  7915. return this;
  7916. },
  7917. // @method isPopupOpen(): boolean
  7918. // Returns `true` if the popup bound to this layer is currently open.
  7919. isPopupOpen: function () {
  7920. return (this._popup ? this._popup.isOpen() : false);
  7921. },
  7922. // @method setPopupContent(content: String|HTMLElement|Popup): this
  7923. // Sets the content of the popup bound to this layer.
  7924. setPopupContent: function (content) {
  7925. if (this._popup) {
  7926. this._popup.setContent(content);
  7927. }
  7928. return this;
  7929. },
  7930. // @method getPopup(): Popup
  7931. // Returns the popup bound to this layer.
  7932. getPopup: function () {
  7933. return this._popup;
  7934. },
  7935. _openPopup: function (e) {
  7936. var layer = e.layer || e.target;
  7937. if (!this._popup) {
  7938. return;
  7939. }
  7940. if (!this._map) {
  7941. return;
  7942. }
  7943. // prevent map click
  7944. stop(e);
  7945. // if this inherits from Path its a vector and we can just
  7946. // open the popup at the new location
  7947. if (layer instanceof Path) {
  7948. this.openPopup(e.layer || e.target, e.latlng);
  7949. return;
  7950. }
  7951. // otherwise treat it like a marker and figure out
  7952. // if we should toggle it open/closed
  7953. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  7954. this.closePopup();
  7955. } else {
  7956. this.openPopup(layer, e.latlng);
  7957. }
  7958. },
  7959. _movePopup: function (e) {
  7960. this._popup.setLatLng(e.latlng);
  7961. },
  7962. _onKeyPress: function (e) {
  7963. if (e.originalEvent.keyCode === 13) {
  7964. this._openPopup(e);
  7965. }
  7966. }
  7967. });
  7968. /*
  7969. * @class Tooltip
  7970. * @inherits DivOverlay
  7971. * @aka L.Tooltip
  7972. * Used to display small texts on top of map layers.
  7973. *
  7974. * @example
  7975. *
  7976. * ```js
  7977. * marker.bindTooltip("my tooltip text").openTooltip();
  7978. * ```
  7979. * Note about tooltip offset. Leaflet takes two options in consideration
  7980. * for computing tooltip offseting:
  7981. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  7982. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  7983. * move it to the bottom. Negatives will move to the left and top.
  7984. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  7985. * should adapt this value if you use a custom icon.
  7986. */
  7987. // @namespace Tooltip
  7988. var Tooltip = DivOverlay.extend({
  7989. // @section
  7990. // @aka Tooltip options
  7991. options: {
  7992. // @option pane: String = 'tooltipPane'
  7993. // `Map pane` where the tooltip will be added.
  7994. pane: 'tooltipPane',
  7995. // @option offset: Point = Point(0, 0)
  7996. // Optional offset of the tooltip position.
  7997. offset: [0, 0],
  7998. // @option direction: String = 'auto'
  7999. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8000. // `top`, `bottom`, `center`, `auto`.
  8001. // `auto` will dynamicaly switch between `right` and `left` according to the tooltip
  8002. // position on the map.
  8003. direction: 'auto',
  8004. // @option permanent: Boolean = false
  8005. // Whether to open the tooltip permanently or only on mouseover.
  8006. permanent: false,
  8007. // @option sticky: Boolean = false
  8008. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8009. sticky: false,
  8010. // @option interactive: Boolean = false
  8011. // If true, the tooltip will listen to the feature events.
  8012. interactive: false,
  8013. // @option opacity: Number = 0.9
  8014. // Tooltip container opacity.
  8015. opacity: 0.9
  8016. },
  8017. onAdd: function (map) {
  8018. DivOverlay.prototype.onAdd.call(this, map);
  8019. this.setOpacity(this.options.opacity);
  8020. // @namespace Map
  8021. // @section Tooltip events
  8022. // @event tooltipopen: TooltipEvent
  8023. // Fired when a tooltip is opened in the map.
  8024. map.fire('tooltipopen', {tooltip: this});
  8025. if (this._source) {
  8026. // @namespace Layer
  8027. // @section Tooltip events
  8028. // @event tooltipopen: TooltipEvent
  8029. // Fired when a tooltip bound to this layer is opened.
  8030. this._source.fire('tooltipopen', {tooltip: this}, true);
  8031. }
  8032. },
  8033. onRemove: function (map) {
  8034. DivOverlay.prototype.onRemove.call(this, map);
  8035. // @namespace Map
  8036. // @section Tooltip events
  8037. // @event tooltipclose: TooltipEvent
  8038. // Fired when a tooltip in the map is closed.
  8039. map.fire('tooltipclose', {tooltip: this});
  8040. if (this._source) {
  8041. // @namespace Layer
  8042. // @section Tooltip events
  8043. // @event tooltipclose: TooltipEvent
  8044. // Fired when a tooltip bound to this layer is closed.
  8045. this._source.fire('tooltipclose', {tooltip: this}, true);
  8046. }
  8047. },
  8048. getEvents: function () {
  8049. var events = DivOverlay.prototype.getEvents.call(this);
  8050. if (touch && !this.options.permanent) {
  8051. events.preclick = this._close;
  8052. }
  8053. return events;
  8054. },
  8055. _close: function () {
  8056. if (this._map) {
  8057. this._map.closeTooltip(this);
  8058. }
  8059. },
  8060. _initLayout: function () {
  8061. var prefix = 'leaflet-tooltip',
  8062. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8063. this._contentNode = this._container = create$1('div', className);
  8064. },
  8065. _updateLayout: function () {},
  8066. _adjustPan: function () {},
  8067. _setPosition: function (pos) {
  8068. var map = this._map,
  8069. container = this._container,
  8070. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8071. tooltipPoint = map.layerPointToContainerPoint(pos),
  8072. direction = this.options.direction,
  8073. tooltipWidth = container.offsetWidth,
  8074. tooltipHeight = container.offsetHeight,
  8075. offset = toPoint(this.options.offset),
  8076. anchor = this._getAnchor();
  8077. if (direction === 'top') {
  8078. pos = pos.add(toPoint(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true));
  8079. } else if (direction === 'bottom') {
  8080. pos = pos.subtract(toPoint(tooltipWidth / 2 - offset.x, -offset.y, true));
  8081. } else if (direction === 'center') {
  8082. pos = pos.subtract(toPoint(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true));
  8083. } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
  8084. direction = 'right';
  8085. pos = pos.add(toPoint(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true));
  8086. } else {
  8087. direction = 'left';
  8088. pos = pos.subtract(toPoint(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true));
  8089. }
  8090. removeClass(container, 'leaflet-tooltip-right');
  8091. removeClass(container, 'leaflet-tooltip-left');
  8092. removeClass(container, 'leaflet-tooltip-top');
  8093. removeClass(container, 'leaflet-tooltip-bottom');
  8094. addClass(container, 'leaflet-tooltip-' + direction);
  8095. setPosition(container, pos);
  8096. },
  8097. _updatePosition: function () {
  8098. var pos = this._map.latLngToLayerPoint(this._latlng);
  8099. this._setPosition(pos);
  8100. },
  8101. setOpacity: function (opacity) {
  8102. this.options.opacity = opacity;
  8103. if (this._container) {
  8104. setOpacity(this._container, opacity);
  8105. }
  8106. },
  8107. _animateZoom: function (e) {
  8108. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8109. this._setPosition(pos);
  8110. },
  8111. _getAnchor: function () {
  8112. // Where should we anchor the tooltip on the source layer?
  8113. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8114. }
  8115. });
  8116. // @namespace Tooltip
  8117. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8118. // 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.
  8119. var tooltip = function (options, source) {
  8120. return new Tooltip(options, source);
  8121. };
  8122. // @namespace Map
  8123. // @section Methods for Layers and Controls
  8124. Map.include({
  8125. // @method openTooltip(tooltip: Tooltip): this
  8126. // Opens the specified tooltip.
  8127. // @alternative
  8128. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8129. // Creates a tooltip with the specified content and options and open it.
  8130. openTooltip: function (tooltip, latlng, options) {
  8131. if (!(tooltip instanceof Tooltip)) {
  8132. tooltip = new Tooltip(options).setContent(tooltip);
  8133. }
  8134. if (latlng) {
  8135. tooltip.setLatLng(latlng);
  8136. }
  8137. if (this.hasLayer(tooltip)) {
  8138. return this;
  8139. }
  8140. return this.addLayer(tooltip);
  8141. },
  8142. // @method closeTooltip(tooltip?: Tooltip): this
  8143. // Closes the tooltip given as parameter.
  8144. closeTooltip: function (tooltip) {
  8145. if (tooltip) {
  8146. this.removeLayer(tooltip);
  8147. }
  8148. return this;
  8149. }
  8150. });
  8151. /*
  8152. * @namespace Layer
  8153. * @section Tooltip methods example
  8154. *
  8155. * All layers share a set of methods convenient for binding tooltips to it.
  8156. *
  8157. * ```js
  8158. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8159. * layer.openTooltip();
  8160. * layer.closeTooltip();
  8161. * ```
  8162. */
  8163. // @section Tooltip methods
  8164. Layer.include({
  8165. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8166. // Binds a tooltip to the layer with the passed `content` and sets up the
  8167. // necessary event listeners. If a `Function` is passed it will receive
  8168. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8169. bindTooltip: function (content, options) {
  8170. if (content instanceof Tooltip) {
  8171. setOptions(content, options);
  8172. this._tooltip = content;
  8173. content._source = this;
  8174. } else {
  8175. if (!this._tooltip || options) {
  8176. this._tooltip = new Tooltip(options, this);
  8177. }
  8178. this._tooltip.setContent(content);
  8179. }
  8180. this._initTooltipInteractions();
  8181. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8182. this.openTooltip();
  8183. }
  8184. return this;
  8185. },
  8186. // @method unbindTooltip(): this
  8187. // Removes the tooltip previously bound with `bindTooltip`.
  8188. unbindTooltip: function () {
  8189. if (this._tooltip) {
  8190. this._initTooltipInteractions(true);
  8191. this.closeTooltip();
  8192. this._tooltip = null;
  8193. }
  8194. return this;
  8195. },
  8196. _initTooltipInteractions: function (remove$$1) {
  8197. if (!remove$$1 && this._tooltipHandlersAdded) { return; }
  8198. var onOff = remove$$1 ? 'off' : 'on',
  8199. events = {
  8200. remove: this.closeTooltip,
  8201. move: this._moveTooltip
  8202. };
  8203. if (!this._tooltip.options.permanent) {
  8204. events.mouseover = this._openTooltip;
  8205. events.mouseout = this.closeTooltip;
  8206. if (this._tooltip.options.sticky) {
  8207. events.mousemove = this._moveTooltip;
  8208. }
  8209. if (touch) {
  8210. events.click = this._openTooltip;
  8211. }
  8212. } else {
  8213. events.add = this._openTooltip;
  8214. }
  8215. this[onOff](events);
  8216. this._tooltipHandlersAdded = !remove$$1;
  8217. },
  8218. // @method openTooltip(latlng?: LatLng): this
  8219. // Opens the bound tooltip at the specificed `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8220. openTooltip: function (layer, latlng) {
  8221. if (!(layer instanceof Layer)) {
  8222. latlng = layer;
  8223. layer = this;
  8224. }
  8225. if (layer instanceof FeatureGroup) {
  8226. for (var id in this._layers) {
  8227. layer = this._layers[id];
  8228. break;
  8229. }
  8230. }
  8231. if (!latlng) {
  8232. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  8233. }
  8234. if (this._tooltip && this._map) {
  8235. // set tooltip source to this layer
  8236. this._tooltip._source = layer;
  8237. // update the tooltip (content, layout, ect...)
  8238. this._tooltip.update();
  8239. // open the tooltip on the map
  8240. this._map.openTooltip(this._tooltip, latlng);
  8241. // Tooltip container may not be defined if not permanent and never
  8242. // opened.
  8243. if (this._tooltip.options.interactive && this._tooltip._container) {
  8244. addClass(this._tooltip._container, 'leaflet-clickable');
  8245. this.addInteractiveTarget(this._tooltip._container);
  8246. }
  8247. }
  8248. return this;
  8249. },
  8250. // @method closeTooltip(): this
  8251. // Closes the tooltip bound to this layer if it is open.
  8252. closeTooltip: function () {
  8253. if (this._tooltip) {
  8254. this._tooltip._close();
  8255. if (this._tooltip.options.interactive && this._tooltip._container) {
  8256. removeClass(this._tooltip._container, 'leaflet-clickable');
  8257. this.removeInteractiveTarget(this._tooltip._container);
  8258. }
  8259. }
  8260. return this;
  8261. },
  8262. // @method toggleTooltip(): this
  8263. // Opens or closes the tooltip bound to this layer depending on its current state.
  8264. toggleTooltip: function (target) {
  8265. if (this._tooltip) {
  8266. if (this._tooltip._map) {
  8267. this.closeTooltip();
  8268. } else {
  8269. this.openTooltip(target);
  8270. }
  8271. }
  8272. return this;
  8273. },
  8274. // @method isTooltipOpen(): boolean
  8275. // Returns `true` if the tooltip bound to this layer is currently open.
  8276. isTooltipOpen: function () {
  8277. return this._tooltip.isOpen();
  8278. },
  8279. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8280. // Sets the content of the tooltip bound to this layer.
  8281. setTooltipContent: function (content) {
  8282. if (this._tooltip) {
  8283. this._tooltip.setContent(content);
  8284. }
  8285. return this;
  8286. },
  8287. // @method getTooltip(): Tooltip
  8288. // Returns the tooltip bound to this layer.
  8289. getTooltip: function () {
  8290. return this._tooltip;
  8291. },
  8292. _openTooltip: function (e) {
  8293. var layer = e.layer || e.target;
  8294. if (!this._tooltip || !this._map) {
  8295. return;
  8296. }
  8297. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  8298. },
  8299. _moveTooltip: function (e) {
  8300. var latlng = e.latlng, containerPoint, layerPoint;
  8301. if (this._tooltip.options.sticky && e.originalEvent) {
  8302. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  8303. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  8304. latlng = this._map.layerPointToLatLng(layerPoint);
  8305. }
  8306. this._tooltip.setLatLng(latlng);
  8307. }
  8308. });
  8309. /*
  8310. * @class DivIcon
  8311. * @aka L.DivIcon
  8312. * @inherits Icon
  8313. *
  8314. * Represents a lightweight icon for markers that uses a simple `<div>`
  8315. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  8316. *
  8317. * @example
  8318. * ```js
  8319. * var myIcon = L.divIcon({className: 'my-div-icon'});
  8320. * // you can set .my-div-icon styles in CSS
  8321. *
  8322. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  8323. * ```
  8324. *
  8325. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  8326. */
  8327. var DivIcon = Icon.extend({
  8328. options: {
  8329. // @section
  8330. // @aka DivIcon options
  8331. iconSize: [12, 12], // also can be set through CSS
  8332. // iconAnchor: (Point),
  8333. // popupAnchor: (Point),
  8334. // @option html: String = ''
  8335. // Custom HTML code to put inside the div element, empty by default.
  8336. html: false,
  8337. // @option bgPos: Point = [0, 0]
  8338. // Optional relative position of the background, in pixels
  8339. bgPos: null,
  8340. className: 'leaflet-div-icon'
  8341. },
  8342. createIcon: function (oldIcon) {
  8343. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  8344. options = this.options;
  8345. div.innerHTML = options.html !== false ? options.html : '';
  8346. if (options.bgPos) {
  8347. var bgPos = toPoint(options.bgPos);
  8348. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  8349. }
  8350. this._setIconStyles(div, 'icon');
  8351. return div;
  8352. },
  8353. createShadow: function () {
  8354. return null;
  8355. }
  8356. });
  8357. // @factory L.divIcon(options: DivIcon options)
  8358. // Creates a `DivIcon` instance with the given options.
  8359. function divIcon(options) {
  8360. return new DivIcon(options);
  8361. }
  8362. Icon.Default = IconDefault;
  8363. /*
  8364. * @class GridLayer
  8365. * @inherits Layer
  8366. * @aka L.GridLayer
  8367. *
  8368. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  8369. * 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.
  8370. *
  8371. *
  8372. * @section Synchronous usage
  8373. * @example
  8374. *
  8375. * 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.
  8376. *
  8377. * ```js
  8378. * var CanvasLayer = L.GridLayer.extend({
  8379. * createTile: function(coords){
  8380. * // create a <canvas> element for drawing
  8381. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8382. *
  8383. * // setup tile width and height according to the options
  8384. * var size = this.getTileSize();
  8385. * tile.width = size.x;
  8386. * tile.height = size.y;
  8387. *
  8388. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  8389. * var ctx = tile.getContext('2d');
  8390. *
  8391. * // return the tile so it can be rendered on screen
  8392. * return tile;
  8393. * }
  8394. * });
  8395. * ```
  8396. *
  8397. * @section Asynchronous usage
  8398. * @example
  8399. *
  8400. * 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.
  8401. *
  8402. * ```js
  8403. * var CanvasLayer = L.GridLayer.extend({
  8404. * createTile: function(coords, done){
  8405. * var error;
  8406. *
  8407. * // create a <canvas> element for drawing
  8408. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8409. *
  8410. * // setup tile width and height according to the options
  8411. * var size = this.getTileSize();
  8412. * tile.width = size.x;
  8413. * tile.height = size.y;
  8414. *
  8415. * // draw something asynchronously and pass the tile to the done() callback
  8416. * setTimeout(function() {
  8417. * done(error, tile);
  8418. * }, 1000);
  8419. *
  8420. * return tile;
  8421. * }
  8422. * });
  8423. * ```
  8424. *
  8425. * @section
  8426. */
  8427. var GridLayer = Layer.extend({
  8428. // @section
  8429. // @aka GridLayer options
  8430. options: {
  8431. // @option tileSize: Number|Point = 256
  8432. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  8433. tileSize: 256,
  8434. // @option opacity: Number = 1.0
  8435. // Opacity of the tiles. Can be used in the `createTile()` function.
  8436. opacity: 1,
  8437. // @option updateWhenIdle: Boolean = (depends)
  8438. // Load new tiles only when panning ends.
  8439. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  8440. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  8441. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  8442. updateWhenIdle: mobile,
  8443. // @option updateWhenZooming: Boolean = true
  8444. // 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.
  8445. updateWhenZooming: true,
  8446. // @option updateInterval: Number = 200
  8447. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  8448. updateInterval: 200,
  8449. // @option zIndex: Number = 1
  8450. // The explicit zIndex of the tile layer.
  8451. zIndex: 1,
  8452. // @option bounds: LatLngBounds = undefined
  8453. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  8454. bounds: null,
  8455. // @option minZoom: Number = 0
  8456. // The minimum zoom level down to which this layer will be displayed (inclusive).
  8457. minZoom: 0,
  8458. // @option maxZoom: Number = undefined
  8459. // The maximum zoom level up to which this layer will be displayed (inclusive).
  8460. maxZoom: undefined,
  8461. // @option maxNativeZoom: Number = undefined
  8462. // Maximum zoom number the tile source has available. If it is specified,
  8463. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  8464. // from `maxNativeZoom` level and auto-scaled.
  8465. maxNativeZoom: undefined,
  8466. // @option minNativeZoom: Number = undefined
  8467. // Minimum zoom number the tile source has available. If it is specified,
  8468. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  8469. // from `minNativeZoom` level and auto-scaled.
  8470. minNativeZoom: undefined,
  8471. // @option noWrap: Boolean = false
  8472. // Whether the layer is wrapped around the antimeridian. If `true`, the
  8473. // GridLayer will only be displayed once at low zoom levels. Has no
  8474. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  8475. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  8476. // tiles outside the CRS limits.
  8477. noWrap: false,
  8478. // @option pane: String = 'tilePane'
  8479. // `Map pane` where the grid layer will be added.
  8480. pane: 'tilePane',
  8481. // @option className: String = ''
  8482. // A custom class name to assign to the tile layer. Empty by default.
  8483. className: '',
  8484. // @option keepBuffer: Number = 2
  8485. // When panning the map, keep this many rows and columns of tiles before unloading them.
  8486. keepBuffer: 2
  8487. },
  8488. initialize: function (options) {
  8489. setOptions(this, options);
  8490. },
  8491. onAdd: function () {
  8492. this._initContainer();
  8493. this._levels = {};
  8494. this._tiles = {};
  8495. this._resetView();
  8496. this._update();
  8497. },
  8498. beforeAdd: function (map) {
  8499. map._addZoomLimit(this);
  8500. },
  8501. onRemove: function (map) {
  8502. this._removeAllTiles();
  8503. remove(this._container);
  8504. map._removeZoomLimit(this);
  8505. this._container = null;
  8506. this._tileZoom = null;
  8507. },
  8508. // @method bringToFront: this
  8509. // Brings the tile layer to the top of all tile layers.
  8510. bringToFront: function () {
  8511. if (this._map) {
  8512. toFront(this._container);
  8513. this._setAutoZIndex(Math.max);
  8514. }
  8515. return this;
  8516. },
  8517. // @method bringToBack: this
  8518. // Brings the tile layer to the bottom of all tile layers.
  8519. bringToBack: function () {
  8520. if (this._map) {
  8521. toBack(this._container);
  8522. this._setAutoZIndex(Math.min);
  8523. }
  8524. return this;
  8525. },
  8526. // @method getContainer: HTMLElement
  8527. // Returns the HTML element that contains the tiles for this layer.
  8528. getContainer: function () {
  8529. return this._container;
  8530. },
  8531. // @method setOpacity(opacity: Number): this
  8532. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  8533. setOpacity: function (opacity) {
  8534. this.options.opacity = opacity;
  8535. this._updateOpacity();
  8536. return this;
  8537. },
  8538. // @method setZIndex(zIndex: Number): this
  8539. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  8540. setZIndex: function (zIndex) {
  8541. this.options.zIndex = zIndex;
  8542. this._updateZIndex();
  8543. return this;
  8544. },
  8545. // @method isLoading: Boolean
  8546. // Returns `true` if any tile in the grid layer has not finished loading.
  8547. isLoading: function () {
  8548. return this._loading;
  8549. },
  8550. // @method redraw: this
  8551. // Causes the layer to clear all the tiles and request them again.
  8552. redraw: function () {
  8553. if (this._map) {
  8554. this._removeAllTiles();
  8555. this._update();
  8556. }
  8557. return this;
  8558. },
  8559. getEvents: function () {
  8560. var events = {
  8561. viewprereset: this._invalidateAll,
  8562. viewreset: this._resetView,
  8563. zoom: this._resetView,
  8564. moveend: this._onMoveEnd
  8565. };
  8566. if (!this.options.updateWhenIdle) {
  8567. // update tiles on move, but not more often than once per given interval
  8568. if (!this._onMove) {
  8569. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  8570. }
  8571. events.move = this._onMove;
  8572. }
  8573. if (this._zoomAnimated) {
  8574. events.zoomanim = this._animateZoom;
  8575. }
  8576. return events;
  8577. },
  8578. // @section Extension methods
  8579. // Layers extending `GridLayer` shall reimplement the following method.
  8580. // @method createTile(coords: Object, done?: Function): HTMLElement
  8581. // Called only internally, must be overriden by classes extending `GridLayer`.
  8582. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  8583. // is specified, it must be called when the tile has finished loading and drawing.
  8584. createTile: function () {
  8585. return document.createElement('div');
  8586. },
  8587. // @section
  8588. // @method getTileSize: Point
  8589. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  8590. getTileSize: function () {
  8591. var s = this.options.tileSize;
  8592. return s instanceof Point ? s : new Point(s, s);
  8593. },
  8594. _updateZIndex: function () {
  8595. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  8596. this._container.style.zIndex = this.options.zIndex;
  8597. }
  8598. },
  8599. _setAutoZIndex: function (compare) {
  8600. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  8601. var layers = this.getPane().children,
  8602. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  8603. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  8604. zIndex = layers[i].style.zIndex;
  8605. if (layers[i] !== this._container && zIndex) {
  8606. edgeZIndex = compare(edgeZIndex, +zIndex);
  8607. }
  8608. }
  8609. if (isFinite(edgeZIndex)) {
  8610. this.options.zIndex = edgeZIndex + compare(-1, 1);
  8611. this._updateZIndex();
  8612. }
  8613. },
  8614. _updateOpacity: function () {
  8615. if (!this._map) { return; }
  8616. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  8617. if (ielt9) { return; }
  8618. setOpacity(this._container, this.options.opacity);
  8619. var now = +new Date(),
  8620. nextFrame = false,
  8621. willPrune = false;
  8622. for (var key in this._tiles) {
  8623. var tile = this._tiles[key];
  8624. if (!tile.current || !tile.loaded) { continue; }
  8625. var fade = Math.min(1, (now - tile.loaded) / 200);
  8626. setOpacity(tile.el, fade);
  8627. if (fade < 1) {
  8628. nextFrame = true;
  8629. } else {
  8630. if (tile.active) {
  8631. willPrune = true;
  8632. } else {
  8633. this._onOpaqueTile(tile);
  8634. }
  8635. tile.active = true;
  8636. }
  8637. }
  8638. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  8639. if (nextFrame) {
  8640. cancelAnimFrame(this._fadeFrame);
  8641. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  8642. }
  8643. },
  8644. _onOpaqueTile: falseFn,
  8645. _initContainer: function () {
  8646. if (this._container) { return; }
  8647. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  8648. this._updateZIndex();
  8649. if (this.options.opacity < 1) {
  8650. this._updateOpacity();
  8651. }
  8652. this.getPane().appendChild(this._container);
  8653. },
  8654. _updateLevels: function () {
  8655. var zoom = this._tileZoom,
  8656. maxZoom = this.options.maxZoom;
  8657. if (zoom === undefined) { return undefined; }
  8658. for (var z in this._levels) {
  8659. if (this._levels[z].el.children.length || z === zoom) {
  8660. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  8661. this._onUpdateLevel(z);
  8662. } else {
  8663. remove(this._levels[z].el);
  8664. this._removeTilesAtZoom(z);
  8665. this._onRemoveLevel(z);
  8666. delete this._levels[z];
  8667. }
  8668. }
  8669. var level = this._levels[zoom],
  8670. map = this._map;
  8671. if (!level) {
  8672. level = this._levels[zoom] = {};
  8673. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  8674. level.el.style.zIndex = maxZoom;
  8675. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  8676. level.zoom = zoom;
  8677. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  8678. // force the browser to consider the newly added element for transition
  8679. falseFn(level.el.offsetWidth);
  8680. this._onCreateLevel(level);
  8681. }
  8682. this._level = level;
  8683. return level;
  8684. },
  8685. _onUpdateLevel: falseFn,
  8686. _onRemoveLevel: falseFn,
  8687. _onCreateLevel: falseFn,
  8688. _pruneTiles: function () {
  8689. if (!this._map) {
  8690. return;
  8691. }
  8692. var key, tile;
  8693. var zoom = this._map.getZoom();
  8694. if (zoom > this.options.maxZoom ||
  8695. zoom < this.options.minZoom) {
  8696. this._removeAllTiles();
  8697. return;
  8698. }
  8699. for (key in this._tiles) {
  8700. tile = this._tiles[key];
  8701. tile.retain = tile.current;
  8702. }
  8703. for (key in this._tiles) {
  8704. tile = this._tiles[key];
  8705. if (tile.current && !tile.active) {
  8706. var coords = tile.coords;
  8707. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  8708. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  8709. }
  8710. }
  8711. }
  8712. for (key in this._tiles) {
  8713. if (!this._tiles[key].retain) {
  8714. this._removeTile(key);
  8715. }
  8716. }
  8717. },
  8718. _removeTilesAtZoom: function (zoom) {
  8719. for (var key in this._tiles) {
  8720. if (this._tiles[key].coords.z !== zoom) {
  8721. continue;
  8722. }
  8723. this._removeTile(key);
  8724. }
  8725. },
  8726. _removeAllTiles: function () {
  8727. for (var key in this._tiles) {
  8728. this._removeTile(key);
  8729. }
  8730. },
  8731. _invalidateAll: function () {
  8732. for (var z in this._levels) {
  8733. remove(this._levels[z].el);
  8734. this._onRemoveLevel(z);
  8735. delete this._levels[z];
  8736. }
  8737. this._removeAllTiles();
  8738. this._tileZoom = null;
  8739. },
  8740. _retainParent: function (x, y, z, minZoom) {
  8741. var x2 = Math.floor(x / 2),
  8742. y2 = Math.floor(y / 2),
  8743. z2 = z - 1,
  8744. coords2 = new Point(+x2, +y2);
  8745. coords2.z = +z2;
  8746. var key = this._tileCoordsToKey(coords2),
  8747. tile = this._tiles[key];
  8748. if (tile && tile.active) {
  8749. tile.retain = true;
  8750. return true;
  8751. } else if (tile && tile.loaded) {
  8752. tile.retain = true;
  8753. }
  8754. if (z2 > minZoom) {
  8755. return this._retainParent(x2, y2, z2, minZoom);
  8756. }
  8757. return false;
  8758. },
  8759. _retainChildren: function (x, y, z, maxZoom) {
  8760. for (var i = 2 * x; i < 2 * x + 2; i++) {
  8761. for (var j = 2 * y; j < 2 * y + 2; j++) {
  8762. var coords = new Point(i, j);
  8763. coords.z = z + 1;
  8764. var key = this._tileCoordsToKey(coords),
  8765. tile = this._tiles[key];
  8766. if (tile && tile.active) {
  8767. tile.retain = true;
  8768. continue;
  8769. } else if (tile && tile.loaded) {
  8770. tile.retain = true;
  8771. }
  8772. if (z + 1 < maxZoom) {
  8773. this._retainChildren(i, j, z + 1, maxZoom);
  8774. }
  8775. }
  8776. }
  8777. },
  8778. _resetView: function (e) {
  8779. var animating = e && (e.pinch || e.flyTo);
  8780. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  8781. },
  8782. _animateZoom: function (e) {
  8783. this._setView(e.center, e.zoom, true, e.noUpdate);
  8784. },
  8785. _clampZoom: function (zoom) {
  8786. var options = this.options;
  8787. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  8788. return options.minNativeZoom;
  8789. }
  8790. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  8791. return options.maxNativeZoom;
  8792. }
  8793. return zoom;
  8794. },
  8795. _setView: function (center, zoom, noPrune, noUpdate) {
  8796. var tileZoom = this._clampZoom(Math.round(zoom));
  8797. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  8798. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  8799. tileZoom = undefined;
  8800. }
  8801. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  8802. if (!noUpdate || tileZoomChanged) {
  8803. this._tileZoom = tileZoom;
  8804. if (this._abortLoading) {
  8805. this._abortLoading();
  8806. }
  8807. this._updateLevels();
  8808. this._resetGrid();
  8809. if (tileZoom !== undefined) {
  8810. this._update(center);
  8811. }
  8812. if (!noPrune) {
  8813. this._pruneTiles();
  8814. }
  8815. // Flag to prevent _updateOpacity from pruning tiles during
  8816. // a zoom anim or a pinch gesture
  8817. this._noPrune = !!noPrune;
  8818. }
  8819. this._setZoomTransforms(center, zoom);
  8820. },
  8821. _setZoomTransforms: function (center, zoom) {
  8822. for (var i in this._levels) {
  8823. this._setZoomTransform(this._levels[i], center, zoom);
  8824. }
  8825. },
  8826. _setZoomTransform: function (level, center, zoom) {
  8827. var scale = this._map.getZoomScale(zoom, level.zoom),
  8828. translate = level.origin.multiplyBy(scale)
  8829. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  8830. if (any3d) {
  8831. setTransform(level.el, translate, scale);
  8832. } else {
  8833. setPosition(level.el, translate);
  8834. }
  8835. },
  8836. _resetGrid: function () {
  8837. var map = this._map,
  8838. crs = map.options.crs,
  8839. tileSize = this._tileSize = this.getTileSize(),
  8840. tileZoom = this._tileZoom;
  8841. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  8842. if (bounds) {
  8843. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  8844. }
  8845. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  8846. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  8847. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  8848. ];
  8849. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  8850. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  8851. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  8852. ];
  8853. },
  8854. _onMoveEnd: function () {
  8855. if (!this._map || this._map._animatingZoom) { return; }
  8856. this._update();
  8857. },
  8858. _getTiledPixelBounds: function (center) {
  8859. var map = this._map,
  8860. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  8861. scale = map.getZoomScale(mapZoom, this._tileZoom),
  8862. pixelCenter = map.project(center, this._tileZoom).floor(),
  8863. halfSize = map.getSize().divideBy(scale * 2);
  8864. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  8865. },
  8866. // Private method to load tiles in the grid's active zoom level according to map bounds
  8867. _update: function (center) {
  8868. var map = this._map;
  8869. if (!map) { return; }
  8870. var zoom = this._clampZoom(map.getZoom());
  8871. if (center === undefined) { center = map.getCenter(); }
  8872. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  8873. var pixelBounds = this._getTiledPixelBounds(center),
  8874. tileRange = this._pxBoundsToTileRange(pixelBounds),
  8875. tileCenter = tileRange.getCenter(),
  8876. queue = [],
  8877. margin = this.options.keepBuffer,
  8878. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  8879. tileRange.getTopRight().add([margin, -margin]));
  8880. // Sanity check: panic if the tile range contains Infinity somewhere.
  8881. if (!(isFinite(tileRange.min.x) &&
  8882. isFinite(tileRange.min.y) &&
  8883. isFinite(tileRange.max.x) &&
  8884. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  8885. for (var key in this._tiles) {
  8886. var c = this._tiles[key].coords;
  8887. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  8888. this._tiles[key].current = false;
  8889. }
  8890. }
  8891. // _update just loads more tiles. If the tile zoom level differs too much
  8892. // from the map's, let _setView reset levels and prune old tiles.
  8893. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  8894. // create a queue of coordinates to load tiles from
  8895. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  8896. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  8897. var coords = new Point(i, j);
  8898. coords.z = this._tileZoom;
  8899. if (!this._isValidTile(coords)) { continue; }
  8900. if (!this._tiles[this._tileCoordsToKey(coords)]) {
  8901. queue.push(coords);
  8902. }
  8903. }
  8904. }
  8905. // sort tile queue to load tiles in order of their distance to center
  8906. queue.sort(function (a, b) {
  8907. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  8908. });
  8909. if (queue.length !== 0) {
  8910. // if it's the first batch of tiles to load
  8911. if (!this._loading) {
  8912. this._loading = true;
  8913. // @event loading: Event
  8914. // Fired when the grid layer starts loading tiles.
  8915. this.fire('loading');
  8916. }
  8917. // create DOM fragment to append tiles in one batch
  8918. var fragment = document.createDocumentFragment();
  8919. for (i = 0; i < queue.length; i++) {
  8920. this._addTile(queue[i], fragment);
  8921. }
  8922. this._level.el.appendChild(fragment);
  8923. }
  8924. },
  8925. _isValidTile: function (coords) {
  8926. var crs = this._map.options.crs;
  8927. if (!crs.infinite) {
  8928. // don't load tile if it's out of bounds and not wrapped
  8929. var bounds = this._globalTileRange;
  8930. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  8931. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  8932. }
  8933. if (!this.options.bounds) { return true; }
  8934. // don't load tile if it doesn't intersect the bounds in options
  8935. var tileBounds = this._tileCoordsToBounds(coords);
  8936. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  8937. },
  8938. _keyToBounds: function (key) {
  8939. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  8940. },
  8941. // converts tile coordinates to its geographical bounds
  8942. _tileCoordsToBounds: function (coords) {
  8943. var map = this._map,
  8944. tileSize = this.getTileSize(),
  8945. nwPoint = coords.scaleBy(tileSize),
  8946. sePoint = nwPoint.add(tileSize),
  8947. nw = map.unproject(nwPoint, coords.z),
  8948. se = map.unproject(sePoint, coords.z),
  8949. bounds = new LatLngBounds(nw, se);
  8950. if (!this.options.noWrap) {
  8951. map.wrapLatLngBounds(bounds);
  8952. }
  8953. return bounds;
  8954. },
  8955. // converts tile coordinates to key for the tile cache
  8956. _tileCoordsToKey: function (coords) {
  8957. return coords.x + ':' + coords.y + ':' + coords.z;
  8958. },
  8959. // converts tile cache key to coordinates
  8960. _keyToTileCoords: function (key) {
  8961. var k = key.split(':'),
  8962. coords = new Point(+k[0], +k[1]);
  8963. coords.z = +k[2];
  8964. return coords;
  8965. },
  8966. _removeTile: function (key) {
  8967. var tile = this._tiles[key];
  8968. if (!tile) { return; }
  8969. remove(tile.el);
  8970. delete this._tiles[key];
  8971. // @event tileunload: TileEvent
  8972. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  8973. this.fire('tileunload', {
  8974. tile: tile.el,
  8975. coords: this._keyToTileCoords(key)
  8976. });
  8977. },
  8978. _initTile: function (tile) {
  8979. addClass(tile, 'leaflet-tile');
  8980. var tileSize = this.getTileSize();
  8981. tile.style.width = tileSize.x + 'px';
  8982. tile.style.height = tileSize.y + 'px';
  8983. tile.onselectstart = falseFn;
  8984. tile.onmousemove = falseFn;
  8985. // update opacity on tiles in IE7-8 because of filter inheritance problems
  8986. if (ielt9 && this.options.opacity < 1) {
  8987. setOpacity(tile, this.options.opacity);
  8988. }
  8989. // without this hack, tiles disappear after zoom on Chrome for Android
  8990. // https://github.com/Leaflet/Leaflet/issues/2078
  8991. if (android && !android23) {
  8992. tile.style.WebkitBackfaceVisibility = 'hidden';
  8993. }
  8994. },
  8995. _addTile: function (coords, container) {
  8996. var tilePos = this._getTilePos(coords),
  8997. key = this._tileCoordsToKey(coords);
  8998. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  8999. this._initTile(tile);
  9000. // if createTile is defined with a second argument ("done" callback),
  9001. // we know that tile is async and will be ready later; otherwise
  9002. if (this.createTile.length < 2) {
  9003. // mark tile as ready, but delay one frame for opacity animation to happen
  9004. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9005. }
  9006. setPosition(tile, tilePos);
  9007. // save tile in cache
  9008. this._tiles[key] = {
  9009. el: tile,
  9010. coords: coords,
  9011. current: true
  9012. };
  9013. container.appendChild(tile);
  9014. // @event tileloadstart: TileEvent
  9015. // Fired when a tile is requested and starts loading.
  9016. this.fire('tileloadstart', {
  9017. tile: tile,
  9018. coords: coords
  9019. });
  9020. },
  9021. _tileReady: function (coords, err, tile) {
  9022. if (!this._map) { return; }
  9023. if (err) {
  9024. // @event tileerror: TileErrorEvent
  9025. // Fired when there is an error loading a tile.
  9026. this.fire('tileerror', {
  9027. error: err,
  9028. tile: tile,
  9029. coords: coords
  9030. });
  9031. }
  9032. var key = this._tileCoordsToKey(coords);
  9033. tile = this._tiles[key];
  9034. if (!tile) { return; }
  9035. tile.loaded = +new Date();
  9036. if (this._map._fadeAnimated) {
  9037. setOpacity(tile.el, 0);
  9038. cancelAnimFrame(this._fadeFrame);
  9039. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9040. } else {
  9041. tile.active = true;
  9042. this._pruneTiles();
  9043. }
  9044. if (!err) {
  9045. addClass(tile.el, 'leaflet-tile-loaded');
  9046. // @event tileload: TileEvent
  9047. // Fired when a tile loads.
  9048. this.fire('tileload', {
  9049. tile: tile.el,
  9050. coords: coords
  9051. });
  9052. }
  9053. if (this._noTilesToLoad()) {
  9054. this._loading = false;
  9055. // @event load: Event
  9056. // Fired when the grid layer loaded all visible tiles.
  9057. this.fire('load');
  9058. if (ielt9 || !this._map._fadeAnimated) {
  9059. requestAnimFrame(this._pruneTiles, this);
  9060. } else {
  9061. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9062. // to trigger a pruning.
  9063. setTimeout(bind(this._pruneTiles, this), 250);
  9064. }
  9065. }
  9066. },
  9067. _getTilePos: function (coords) {
  9068. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9069. },
  9070. _wrapCoords: function (coords) {
  9071. var newCoords = new Point(
  9072. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9073. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9074. newCoords.z = coords.z;
  9075. return newCoords;
  9076. },
  9077. _pxBoundsToTileRange: function (bounds) {
  9078. var tileSize = this.getTileSize();
  9079. return new Bounds(
  9080. bounds.min.unscaleBy(tileSize).floor(),
  9081. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9082. },
  9083. _noTilesToLoad: function () {
  9084. for (var key in this._tiles) {
  9085. if (!this._tiles[key].loaded) { return false; }
  9086. }
  9087. return true;
  9088. }
  9089. });
  9090. // @factory L.gridLayer(options?: GridLayer options)
  9091. // Creates a new instance of GridLayer with the supplied options.
  9092. function gridLayer(options) {
  9093. return new GridLayer(options);
  9094. }
  9095. /*
  9096. * @class TileLayer
  9097. * @inherits GridLayer
  9098. * @aka L.TileLayer
  9099. * Used to load and display tile layers on the map. Extends `GridLayer`.
  9100. *
  9101. * @example
  9102. *
  9103. * ```js
  9104. * L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map);
  9105. * ```
  9106. *
  9107. * @section URL template
  9108. * @example
  9109. *
  9110. * A string of the following form:
  9111. *
  9112. * ```
  9113. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9114. * ```
  9115. *
  9116. * `{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 "&commat;2x" to the URL to load retina tiles.
  9117. *
  9118. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9119. *
  9120. * ```
  9121. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9122. * ```
  9123. */
  9124. var TileLayer = GridLayer.extend({
  9125. // @section
  9126. // @aka TileLayer options
  9127. options: {
  9128. // @option minZoom: Number = 0
  9129. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9130. minZoom: 0,
  9131. // @option maxZoom: Number = 18
  9132. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9133. maxZoom: 18,
  9134. // @option subdomains: String|String[] = 'abc'
  9135. // 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.
  9136. subdomains: 'abc',
  9137. // @option errorTileUrl: String = ''
  9138. // URL to the tile image to show in place of the tile that failed to load.
  9139. errorTileUrl: '',
  9140. // @option zoomOffset: Number = 0
  9141. // The zoom number used in tile URLs will be offset with this value.
  9142. zoomOffset: 0,
  9143. // @option tms: Boolean = false
  9144. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9145. tms: false,
  9146. // @option zoomReverse: Boolean = false
  9147. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9148. zoomReverse: false,
  9149. // @option detectRetina: Boolean = false
  9150. // 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.
  9151. detectRetina: false,
  9152. // @option crossOrigin: Boolean = false
  9153. // If true, all tiles will have their crossOrigin attribute set to ''. This is needed if you want to access tile pixel data.
  9154. crossOrigin: false
  9155. },
  9156. initialize: function (url, options) {
  9157. this._url = url;
  9158. options = setOptions(this, options);
  9159. // detecting retina displays, adjusting tileSize and zoom levels
  9160. if (options.detectRetina && retina && options.maxZoom > 0) {
  9161. options.tileSize = Math.floor(options.tileSize / 2);
  9162. if (!options.zoomReverse) {
  9163. options.zoomOffset++;
  9164. options.maxZoom--;
  9165. } else {
  9166. options.zoomOffset--;
  9167. options.minZoom++;
  9168. }
  9169. options.minZoom = Math.max(0, options.minZoom);
  9170. }
  9171. if (typeof options.subdomains === 'string') {
  9172. options.subdomains = options.subdomains.split('');
  9173. }
  9174. // for https://github.com/Leaflet/Leaflet/issues/137
  9175. if (!android) {
  9176. this.on('tileunload', this._onTileRemove);
  9177. }
  9178. },
  9179. // @method setUrl(url: String, noRedraw?: Boolean): this
  9180. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9181. setUrl: function (url, noRedraw) {
  9182. this._url = url;
  9183. if (!noRedraw) {
  9184. this.redraw();
  9185. }
  9186. return this;
  9187. },
  9188. // @method createTile(coords: Object, done?: Function): HTMLElement
  9189. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9190. // to return an `<img>` HTML element with the appropiate image URL given `coords`. The `done`
  9191. // callback is called when the tile has been loaded.
  9192. createTile: function (coords, done) {
  9193. var tile = document.createElement('img');
  9194. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9195. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9196. if (this.options.crossOrigin) {
  9197. tile.crossOrigin = '';
  9198. }
  9199. /*
  9200. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  9201. http://www.w3.org/TR/WCAG20-TECHS/H67
  9202. */
  9203. tile.alt = '';
  9204. /*
  9205. Set role="presentation" to force screen readers to ignore this
  9206. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  9207. */
  9208. tile.setAttribute('role', 'presentation');
  9209. tile.src = this.getTileUrl(coords);
  9210. return tile;
  9211. },
  9212. // @section Extension methods
  9213. // @uninheritable
  9214. // Layers extending `TileLayer` might reimplement the following method.
  9215. // @method getTileUrl(coords: Object): String
  9216. // Called only internally, returns the URL for a tile given its coordinates.
  9217. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9218. getTileUrl: function (coords) {
  9219. var data = {
  9220. r: retina ? '@2x' : '',
  9221. s: this._getSubdomain(coords),
  9222. x: coords.x,
  9223. y: coords.y,
  9224. z: this._getZoomForUrl()
  9225. };
  9226. if (this._map && !this._map.options.crs.infinite) {
  9227. var invertedY = this._globalTileRange.max.y - coords.y;
  9228. if (this.options.tms) {
  9229. data['y'] = invertedY;
  9230. }
  9231. data['-y'] = invertedY;
  9232. }
  9233. return template(this._url, extend(data, this.options));
  9234. },
  9235. _tileOnLoad: function (done, tile) {
  9236. // For https://github.com/Leaflet/Leaflet/issues/3332
  9237. if (ielt9) {
  9238. setTimeout(bind(done, this, null, tile), 0);
  9239. } else {
  9240. done(null, tile);
  9241. }
  9242. },
  9243. _tileOnError: function (done, tile, e) {
  9244. var errorUrl = this.options.errorTileUrl;
  9245. if (errorUrl && tile.src !== errorUrl) {
  9246. tile.src = errorUrl;
  9247. }
  9248. done(e, tile);
  9249. },
  9250. _onTileRemove: function (e) {
  9251. e.tile.onload = null;
  9252. },
  9253. _getZoomForUrl: function () {
  9254. var zoom = this._tileZoom,
  9255. maxZoom = this.options.maxZoom,
  9256. zoomReverse = this.options.zoomReverse,
  9257. zoomOffset = this.options.zoomOffset;
  9258. if (zoomReverse) {
  9259. zoom = maxZoom - zoom;
  9260. }
  9261. return zoom + zoomOffset;
  9262. },
  9263. _getSubdomain: function (tilePoint) {
  9264. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  9265. return this.options.subdomains[index];
  9266. },
  9267. // stops loading all tiles in the background layer
  9268. _abortLoading: function () {
  9269. var i, tile;
  9270. for (i in this._tiles) {
  9271. if (this._tiles[i].coords.z !== this._tileZoom) {
  9272. tile = this._tiles[i].el;
  9273. tile.onload = falseFn;
  9274. tile.onerror = falseFn;
  9275. if (!tile.complete) {
  9276. tile.src = emptyImageUrl;
  9277. remove(tile);
  9278. }
  9279. }
  9280. }
  9281. }
  9282. });
  9283. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  9284. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  9285. function tileLayer(url, options) {
  9286. return new TileLayer(url, options);
  9287. }
  9288. /*
  9289. * @class TileLayer.WMS
  9290. * @inherits TileLayer
  9291. * @aka L.TileLayer.WMS
  9292. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  9293. *
  9294. * @example
  9295. *
  9296. * ```js
  9297. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  9298. * layers: 'nexrad-n0r-900913',
  9299. * format: 'image/png',
  9300. * transparent: true,
  9301. * attribution: "Weather data © 2012 IEM Nexrad"
  9302. * });
  9303. * ```
  9304. */
  9305. var TileLayerWMS = TileLayer.extend({
  9306. // @section
  9307. // @aka TileLayer.WMS options
  9308. // If any custom options not documented here are used, they will be sent to the
  9309. // WMS server as extra parameters in each request URL. This can be useful for
  9310. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  9311. defaultWmsParams: {
  9312. service: 'WMS',
  9313. request: 'GetMap',
  9314. // @option layers: String = ''
  9315. // **(required)** Comma-separated list of WMS layers to show.
  9316. layers: '',
  9317. // @option styles: String = ''
  9318. // Comma-separated list of WMS styles.
  9319. styles: '',
  9320. // @option format: String = 'image/jpeg'
  9321. // WMS image format (use `'image/png'` for layers with transparency).
  9322. format: 'image/jpeg',
  9323. // @option transparent: Boolean = false
  9324. // If `true`, the WMS service will return images with transparency.
  9325. transparent: false,
  9326. // @option version: String = '1.1.1'
  9327. // Version of the WMS service to use
  9328. version: '1.1.1'
  9329. },
  9330. options: {
  9331. // @option crs: CRS = null
  9332. // Coordinate Reference System to use for the WMS requests, defaults to
  9333. // map CRS. Don't change this if you're not sure what it means.
  9334. crs: null,
  9335. // @option uppercase: Boolean = false
  9336. // If `true`, WMS request parameter keys will be uppercase.
  9337. uppercase: false
  9338. },
  9339. initialize: function (url, options) {
  9340. this._url = url;
  9341. var wmsParams = extend({}, this.defaultWmsParams);
  9342. // all keys that are not TileLayer options go to WMS params
  9343. for (var i in options) {
  9344. if (!(i in this.options)) {
  9345. wmsParams[i] = options[i];
  9346. }
  9347. }
  9348. options = setOptions(this, options);
  9349. wmsParams.width = wmsParams.height = options.tileSize * (options.detectRetina && retina ? 2 : 1);
  9350. this.wmsParams = wmsParams;
  9351. },
  9352. onAdd: function (map) {
  9353. this._crs = this.options.crs || map.options.crs;
  9354. this._wmsVersion = parseFloat(this.wmsParams.version);
  9355. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  9356. this.wmsParams[projectionKey] = this._crs.code;
  9357. TileLayer.prototype.onAdd.call(this, map);
  9358. },
  9359. getTileUrl: function (coords) {
  9360. var tileBounds = this._tileCoordsToBounds(coords),
  9361. nw = this._crs.project(tileBounds.getNorthWest()),
  9362. se = this._crs.project(tileBounds.getSouthEast()),
  9363. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  9364. [se.y, nw.x, nw.y, se.x] :
  9365. [nw.x, se.y, se.x, nw.y]).join(','),
  9366. url = TileLayer.prototype.getTileUrl.call(this, coords);
  9367. return url +
  9368. getParamString(this.wmsParams, url, this.options.uppercase) +
  9369. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  9370. },
  9371. // @method setParams(params: Object, noRedraw?: Boolean): this
  9372. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  9373. setParams: function (params, noRedraw) {
  9374. extend(this.wmsParams, params);
  9375. if (!noRedraw) {
  9376. this.redraw();
  9377. }
  9378. return this;
  9379. }
  9380. });
  9381. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  9382. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  9383. function tileLayerWMS(url, options) {
  9384. return new TileLayerWMS(url, options);
  9385. }
  9386. TileLayer.WMS = TileLayerWMS;
  9387. tileLayer.wms = tileLayerWMS;
  9388. /*
  9389. * @class Renderer
  9390. * @inherits Layer
  9391. * @aka L.Renderer
  9392. *
  9393. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  9394. * DOM container of the renderer, its bounds, and its zoom animation.
  9395. *
  9396. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  9397. * itself can be added or removed to the map. All paths use a renderer, which can
  9398. * be implicit (the map will decide the type of renderer and use it automatically)
  9399. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  9400. *
  9401. * Do not use this class directly, use `SVG` and `Canvas` instead.
  9402. *
  9403. * @event update: Event
  9404. * Fired when the renderer updates its bounds, center and zoom, for example when
  9405. * its map has moved
  9406. */
  9407. var Renderer = Layer.extend({
  9408. // @section
  9409. // @aka Renderer options
  9410. options: {
  9411. // @option padding: Number = 0.1
  9412. // How much to extend the clip area around the map view (relative to its size)
  9413. // e.g. 0.1 would be 10% of map view in each direction
  9414. padding: 0.1
  9415. },
  9416. initialize: function (options) {
  9417. setOptions(this, options);
  9418. stamp(this);
  9419. this._layers = this._layers || {};
  9420. },
  9421. onAdd: function () {
  9422. if (!this._container) {
  9423. this._initContainer(); // defined by renderer implementations
  9424. if (this._zoomAnimated) {
  9425. addClass(this._container, 'leaflet-zoom-animated');
  9426. }
  9427. }
  9428. this.getPane().appendChild(this._container);
  9429. this._update();
  9430. this.on('update', this._updatePaths, this);
  9431. },
  9432. onRemove: function () {
  9433. this.off('update', this._updatePaths, this);
  9434. this._destroyContainer();
  9435. },
  9436. getEvents: function () {
  9437. var events = {
  9438. viewreset: this._reset,
  9439. zoom: this._onZoom,
  9440. moveend: this._update,
  9441. zoomend: this._onZoomEnd
  9442. };
  9443. if (this._zoomAnimated) {
  9444. events.zoomanim = this._onAnimZoom;
  9445. }
  9446. return events;
  9447. },
  9448. _onAnimZoom: function (ev) {
  9449. this._updateTransform(ev.center, ev.zoom);
  9450. },
  9451. _onZoom: function () {
  9452. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  9453. },
  9454. _updateTransform: function (center, zoom) {
  9455. var scale = this._map.getZoomScale(zoom, this._zoom),
  9456. position = getPosition(this._container),
  9457. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  9458. currentCenterPoint = this._map.project(this._center, zoom),
  9459. destCenterPoint = this._map.project(center, zoom),
  9460. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  9461. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  9462. if (any3d) {
  9463. setTransform(this._container, topLeftOffset, scale);
  9464. } else {
  9465. setPosition(this._container, topLeftOffset);
  9466. }
  9467. },
  9468. _reset: function () {
  9469. this._update();
  9470. this._updateTransform(this._center, this._zoom);
  9471. for (var id in this._layers) {
  9472. this._layers[id]._reset();
  9473. }
  9474. },
  9475. _onZoomEnd: function () {
  9476. for (var id in this._layers) {
  9477. this._layers[id]._project();
  9478. }
  9479. },
  9480. _updatePaths: function () {
  9481. for (var id in this._layers) {
  9482. this._layers[id]._update();
  9483. }
  9484. },
  9485. _update: function () {
  9486. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  9487. // Subclasses are responsible of firing the 'update' event.
  9488. var p = this.options.padding,
  9489. size = this._map.getSize(),
  9490. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  9491. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  9492. this._center = this._map.getCenter();
  9493. this._zoom = this._map.getZoom();
  9494. }
  9495. });
  9496. /*
  9497. * @class Canvas
  9498. * @inherits Renderer
  9499. * @aka L.Canvas
  9500. *
  9501. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  9502. * Inherits `Renderer`.
  9503. *
  9504. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  9505. * available in all web browsers, notably IE8, and overlapping geometries might
  9506. * not display properly in some edge cases.
  9507. *
  9508. * @example
  9509. *
  9510. * Use Canvas by default for all paths in the map:
  9511. *
  9512. * ```js
  9513. * var map = L.map('map', {
  9514. * renderer: L.canvas()
  9515. * });
  9516. * ```
  9517. *
  9518. * Use a Canvas renderer with extra padding for specific vector geometries:
  9519. *
  9520. * ```js
  9521. * var map = L.map('map');
  9522. * var myRenderer = L.canvas({ padding: 0.5 });
  9523. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  9524. * var circle = L.circle( center, { renderer: myRenderer } );
  9525. * ```
  9526. */
  9527. var Canvas = Renderer.extend({
  9528. getEvents: function () {
  9529. var events = Renderer.prototype.getEvents.call(this);
  9530. events.viewprereset = this._onViewPreReset;
  9531. return events;
  9532. },
  9533. _onViewPreReset: function () {
  9534. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  9535. this._postponeUpdatePaths = true;
  9536. },
  9537. onAdd: function () {
  9538. Renderer.prototype.onAdd.call(this);
  9539. // Redraw vectors since canvas is cleared upon removal,
  9540. // in case of removing the renderer itself from the map.
  9541. this._draw();
  9542. },
  9543. _initContainer: function () {
  9544. var container = this._container = document.createElement('canvas');
  9545. on(container, 'mousemove', throttle(this._onMouseMove, 32, this), this);
  9546. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  9547. on(container, 'mouseout', this._handleMouseOut, this);
  9548. this._ctx = container.getContext('2d');
  9549. },
  9550. _destroyContainer: function () {
  9551. delete this._ctx;
  9552. remove(this._container);
  9553. off(this._container);
  9554. delete this._container;
  9555. },
  9556. _updatePaths: function () {
  9557. if (this._postponeUpdatePaths) { return; }
  9558. var layer;
  9559. this._redrawBounds = null;
  9560. for (var id in this._layers) {
  9561. layer = this._layers[id];
  9562. layer._update();
  9563. }
  9564. this._redraw();
  9565. },
  9566. _update: function () {
  9567. if (this._map._animatingZoom && this._bounds) { return; }
  9568. this._drawnLayers = {};
  9569. Renderer.prototype._update.call(this);
  9570. var b = this._bounds,
  9571. container = this._container,
  9572. size = b.getSize(),
  9573. m = retina ? 2 : 1;
  9574. setPosition(container, b.min);
  9575. // set canvas size (also clearing it); use double size on retina
  9576. container.width = m * size.x;
  9577. container.height = m * size.y;
  9578. container.style.width = size.x + 'px';
  9579. container.style.height = size.y + 'px';
  9580. if (retina) {
  9581. this._ctx.scale(2, 2);
  9582. }
  9583. // translate so we use the same path coordinates after canvas element moves
  9584. this._ctx.translate(-b.min.x, -b.min.y);
  9585. // Tell paths to redraw themselves
  9586. this.fire('update');
  9587. },
  9588. _reset: function () {
  9589. Renderer.prototype._reset.call(this);
  9590. if (this._postponeUpdatePaths) {
  9591. this._postponeUpdatePaths = false;
  9592. this._updatePaths();
  9593. }
  9594. },
  9595. _initPath: function (layer) {
  9596. this._updateDashArray(layer);
  9597. this._layers[stamp(layer)] = layer;
  9598. var order = layer._order = {
  9599. layer: layer,
  9600. prev: this._drawLast,
  9601. next: null
  9602. };
  9603. if (this._drawLast) { this._drawLast.next = order; }
  9604. this._drawLast = order;
  9605. this._drawFirst = this._drawFirst || this._drawLast;
  9606. },
  9607. _addPath: function (layer) {
  9608. this._requestRedraw(layer);
  9609. },
  9610. _removePath: function (layer) {
  9611. var order = layer._order;
  9612. var next = order.next;
  9613. var prev = order.prev;
  9614. if (next) {
  9615. next.prev = prev;
  9616. } else {
  9617. this._drawLast = prev;
  9618. }
  9619. if (prev) {
  9620. prev.next = next;
  9621. } else {
  9622. this._drawFirst = next;
  9623. }
  9624. delete layer._order;
  9625. delete this._layers[L.stamp(layer)];
  9626. this._requestRedraw(layer);
  9627. },
  9628. _updatePath: function (layer) {
  9629. // Redraw the union of the layer's old pixel
  9630. // bounds and the new pixel bounds.
  9631. this._extendRedrawBounds(layer);
  9632. layer._project();
  9633. layer._update();
  9634. // The redraw will extend the redraw bounds
  9635. // with the new pixel bounds.
  9636. this._requestRedraw(layer);
  9637. },
  9638. _updateStyle: function (layer) {
  9639. this._updateDashArray(layer);
  9640. this._requestRedraw(layer);
  9641. },
  9642. _updateDashArray: function (layer) {
  9643. if (layer.options.dashArray) {
  9644. var parts = layer.options.dashArray.split(','),
  9645. dashArray = [],
  9646. i;
  9647. for (i = 0; i < parts.length; i++) {
  9648. dashArray.push(Number(parts[i]));
  9649. }
  9650. layer.options._dashArray = dashArray;
  9651. }
  9652. },
  9653. _requestRedraw: function (layer) {
  9654. if (!this._map) { return; }
  9655. this._extendRedrawBounds(layer);
  9656. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  9657. },
  9658. _extendRedrawBounds: function (layer) {
  9659. if (layer._pxBounds) {
  9660. var padding = (layer.options.weight || 0) + 1;
  9661. this._redrawBounds = this._redrawBounds || new Bounds();
  9662. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  9663. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  9664. }
  9665. },
  9666. _redraw: function () {
  9667. this._redrawRequest = null;
  9668. if (this._redrawBounds) {
  9669. this._redrawBounds.min._floor();
  9670. this._redrawBounds.max._ceil();
  9671. }
  9672. this._clear(); // clear layers in redraw bounds
  9673. this._draw(); // draw layers
  9674. this._redrawBounds = null;
  9675. },
  9676. _clear: function () {
  9677. var bounds = this._redrawBounds;
  9678. if (bounds) {
  9679. var size = bounds.getSize();
  9680. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  9681. } else {
  9682. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  9683. }
  9684. },
  9685. _draw: function () {
  9686. var layer, bounds = this._redrawBounds;
  9687. this._ctx.save();
  9688. if (bounds) {
  9689. var size = bounds.getSize();
  9690. this._ctx.beginPath();
  9691. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  9692. this._ctx.clip();
  9693. }
  9694. this._drawing = true;
  9695. for (var order = this._drawFirst; order; order = order.next) {
  9696. layer = order.layer;
  9697. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  9698. layer._updatePath();
  9699. }
  9700. }
  9701. this._drawing = false;
  9702. this._ctx.restore(); // Restore state before clipping.
  9703. },
  9704. _updatePoly: function (layer, closed) {
  9705. if (!this._drawing) { return; }
  9706. var i, j, len2, p,
  9707. parts = layer._parts,
  9708. len = parts.length,
  9709. ctx = this._ctx;
  9710. if (!len) { return; }
  9711. this._drawnLayers[layer._leaflet_id] = layer;
  9712. ctx.beginPath();
  9713. for (i = 0; i < len; i++) {
  9714. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  9715. p = parts[i][j];
  9716. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  9717. }
  9718. if (closed) {
  9719. ctx.closePath();
  9720. }
  9721. }
  9722. this._fillStroke(ctx, layer);
  9723. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  9724. },
  9725. _updateCircle: function (layer) {
  9726. if (!this._drawing || layer._empty()) { return; }
  9727. var p = layer._point,
  9728. ctx = this._ctx,
  9729. r = layer._radius,
  9730. s = (layer._radiusY || r) / r;
  9731. this._drawnLayers[layer._leaflet_id] = layer;
  9732. if (s !== 1) {
  9733. ctx.save();
  9734. ctx.scale(1, s);
  9735. }
  9736. ctx.beginPath();
  9737. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  9738. if (s !== 1) {
  9739. ctx.restore();
  9740. }
  9741. this._fillStroke(ctx, layer);
  9742. },
  9743. _fillStroke: function (ctx, layer) {
  9744. var options = layer.options;
  9745. if (options.fill) {
  9746. ctx.globalAlpha = options.fillOpacity;
  9747. ctx.fillStyle = options.fillColor || options.color;
  9748. ctx.fill(options.fillRule || 'evenodd');
  9749. }
  9750. if (options.stroke && options.weight !== 0) {
  9751. if (ctx.setLineDash) {
  9752. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  9753. }
  9754. ctx.globalAlpha = options.opacity;
  9755. ctx.lineWidth = options.weight;
  9756. ctx.strokeStyle = options.color;
  9757. ctx.lineCap = options.lineCap;
  9758. ctx.lineJoin = options.lineJoin;
  9759. ctx.stroke();
  9760. }
  9761. },
  9762. // Canvas obviously doesn't have mouse events for individual drawn objects,
  9763. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  9764. _onClick: function (e) {
  9765. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  9766. for (var order = this._drawFirst; order; order = order.next) {
  9767. layer = order.layer;
  9768. if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
  9769. clickedLayer = layer;
  9770. }
  9771. }
  9772. if (clickedLayer) {
  9773. fakeStop(e);
  9774. this._fireEvent([clickedLayer], e);
  9775. }
  9776. },
  9777. _onMouseMove: function (e) {
  9778. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  9779. var point = this._map.mouseEventToLayerPoint(e);
  9780. this._handleMouseHover(e, point);
  9781. },
  9782. _handleMouseOut: function (e) {
  9783. var layer = this._hoveredLayer;
  9784. if (layer) {
  9785. // if we're leaving the layer, fire mouseout
  9786. removeClass(this._container, 'leaflet-interactive');
  9787. this._fireEvent([layer], e, 'mouseout');
  9788. this._hoveredLayer = null;
  9789. }
  9790. },
  9791. _handleMouseHover: function (e, point) {
  9792. var layer, candidateHoveredLayer;
  9793. for (var order = this._drawFirst; order; order = order.next) {
  9794. layer = order.layer;
  9795. if (layer.options.interactive && layer._containsPoint(point)) {
  9796. candidateHoveredLayer = layer;
  9797. }
  9798. }
  9799. if (candidateHoveredLayer !== this._hoveredLayer) {
  9800. this._handleMouseOut(e);
  9801. if (candidateHoveredLayer) {
  9802. addClass(this._container, 'leaflet-interactive'); // change cursor
  9803. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  9804. this._hoveredLayer = candidateHoveredLayer;
  9805. }
  9806. }
  9807. if (this._hoveredLayer) {
  9808. this._fireEvent([this._hoveredLayer], e);
  9809. }
  9810. },
  9811. _fireEvent: function (layers, e, type) {
  9812. this._map._fireDOMEvent(e, type || e.type, layers);
  9813. },
  9814. _bringToFront: function (layer) {
  9815. var order = layer._order;
  9816. var next = order.next;
  9817. var prev = order.prev;
  9818. if (next) {
  9819. next.prev = prev;
  9820. } else {
  9821. // Already last
  9822. return;
  9823. }
  9824. if (prev) {
  9825. prev.next = next;
  9826. } else if (next) {
  9827. // Update first entry unless this is the
  9828. // signle entry
  9829. this._drawFirst = next;
  9830. }
  9831. order.prev = this._drawLast;
  9832. this._drawLast.next = order;
  9833. order.next = null;
  9834. this._drawLast = order;
  9835. this._requestRedraw(layer);
  9836. },
  9837. _bringToBack: function (layer) {
  9838. var order = layer._order;
  9839. var next = order.next;
  9840. var prev = order.prev;
  9841. if (prev) {
  9842. prev.next = next;
  9843. } else {
  9844. // Already first
  9845. return;
  9846. }
  9847. if (next) {
  9848. next.prev = prev;
  9849. } else if (prev) {
  9850. // Update last entry unless this is the
  9851. // signle entry
  9852. this._drawLast = prev;
  9853. }
  9854. order.prev = null;
  9855. order.next = this._drawFirst;
  9856. this._drawFirst.prev = order;
  9857. this._drawFirst = order;
  9858. this._requestRedraw(layer);
  9859. }
  9860. });
  9861. // @factory L.canvas(options?: Renderer options)
  9862. // Creates a Canvas renderer with the given options.
  9863. function canvas$1(options) {
  9864. return canvas ? new Canvas(options) : null;
  9865. }
  9866. /*
  9867. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  9868. */
  9869. var vmlCreate = (function () {
  9870. try {
  9871. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  9872. return function (name) {
  9873. return document.createElement('<lvml:' + name + ' class="lvml">');
  9874. };
  9875. } catch (e) {
  9876. return function (name) {
  9877. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  9878. };
  9879. }
  9880. })();
  9881. /*
  9882. * @class SVG
  9883. *
  9884. * 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.
  9885. *
  9886. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  9887. * with old versions of Internet Explorer.
  9888. */
  9889. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  9890. var vmlMixin = {
  9891. _initContainer: function () {
  9892. this._container = create$1('div', 'leaflet-vml-container');
  9893. },
  9894. _update: function () {
  9895. if (this._map._animatingZoom) { return; }
  9896. Renderer.prototype._update.call(this);
  9897. this.fire('update');
  9898. },
  9899. _initPath: function (layer) {
  9900. var container = layer._container = vmlCreate('shape');
  9901. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  9902. container.coordsize = '1 1';
  9903. layer._path = vmlCreate('path');
  9904. container.appendChild(layer._path);
  9905. this._updateStyle(layer);
  9906. this._layers[stamp(layer)] = layer;
  9907. },
  9908. _addPath: function (layer) {
  9909. var container = layer._container;
  9910. this._container.appendChild(container);
  9911. if (layer.options.interactive) {
  9912. layer.addInteractiveTarget(container);
  9913. }
  9914. },
  9915. _removePath: function (layer) {
  9916. var container = layer._container;
  9917. remove(container);
  9918. layer.removeInteractiveTarget(container);
  9919. delete this._layers[stamp(layer)];
  9920. },
  9921. _updateStyle: function (layer) {
  9922. var stroke = layer._stroke,
  9923. fill = layer._fill,
  9924. options = layer.options,
  9925. container = layer._container;
  9926. container.stroked = !!options.stroke;
  9927. container.filled = !!options.fill;
  9928. if (options.stroke) {
  9929. if (!stroke) {
  9930. stroke = layer._stroke = vmlCreate('stroke');
  9931. }
  9932. container.appendChild(stroke);
  9933. stroke.weight = options.weight + 'px';
  9934. stroke.color = options.color;
  9935. stroke.opacity = options.opacity;
  9936. if (options.dashArray) {
  9937. stroke.dashStyle = isArray(options.dashArray) ?
  9938. options.dashArray.join(' ') :
  9939. options.dashArray.replace(/( *, *)/g, ' ');
  9940. } else {
  9941. stroke.dashStyle = '';
  9942. }
  9943. stroke.endcap = options.lineCap.replace('butt', 'flat');
  9944. stroke.joinstyle = options.lineJoin;
  9945. } else if (stroke) {
  9946. container.removeChild(stroke);
  9947. layer._stroke = null;
  9948. }
  9949. if (options.fill) {
  9950. if (!fill) {
  9951. fill = layer._fill = vmlCreate('fill');
  9952. }
  9953. container.appendChild(fill);
  9954. fill.color = options.fillColor || options.color;
  9955. fill.opacity = options.fillOpacity;
  9956. } else if (fill) {
  9957. container.removeChild(fill);
  9958. layer._fill = null;
  9959. }
  9960. },
  9961. _updateCircle: function (layer) {
  9962. var p = layer._point.round(),
  9963. r = Math.round(layer._radius),
  9964. r2 = Math.round(layer._radiusY || r);
  9965. this._setPath(layer, layer._empty() ? 'M0 0' :
  9966. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  9967. },
  9968. _setPath: function (layer, path) {
  9969. layer._path.v = path;
  9970. },
  9971. _bringToFront: function (layer) {
  9972. toFront(layer._container);
  9973. },
  9974. _bringToBack: function (layer) {
  9975. toBack(layer._container);
  9976. }
  9977. };
  9978. var create$2 = vml ? vmlCreate : svgCreate;
  9979. /*
  9980. * @class SVG
  9981. * @inherits Renderer
  9982. * @aka L.SVG
  9983. *
  9984. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  9985. * Inherits `Renderer`.
  9986. *
  9987. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  9988. * available in all web browsers, notably Android 2.x and 3.x.
  9989. *
  9990. * Although SVG is not available on IE7 and IE8, these browsers support
  9991. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  9992. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  9993. * this case.
  9994. *
  9995. * @example
  9996. *
  9997. * Use SVG by default for all paths in the map:
  9998. *
  9999. * ```js
  10000. * var map = L.map('map', {
  10001. * renderer: L.svg()
  10002. * });
  10003. * ```
  10004. *
  10005. * Use a SVG renderer with extra padding for specific vector geometries:
  10006. *
  10007. * ```js
  10008. * var map = L.map('map');
  10009. * var myRenderer = L.svg({ padding: 0.5 });
  10010. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10011. * var circle = L.circle( center, { renderer: myRenderer } );
  10012. * ```
  10013. */
  10014. var SVG = Renderer.extend({
  10015. getEvents: function () {
  10016. var events = Renderer.prototype.getEvents.call(this);
  10017. events.zoomstart = this._onZoomStart;
  10018. return events;
  10019. },
  10020. _initContainer: function () {
  10021. this._container = create$2('svg');
  10022. // makes it possible to click through svg root; we'll reset it back in individual paths
  10023. this._container.setAttribute('pointer-events', 'none');
  10024. this._rootGroup = create$2('g');
  10025. this._container.appendChild(this._rootGroup);
  10026. },
  10027. _destroyContainer: function () {
  10028. remove(this._container);
  10029. off(this._container);
  10030. delete this._container;
  10031. delete this._rootGroup;
  10032. },
  10033. _onZoomStart: function () {
  10034. // Drag-then-pinch interactions might mess up the center and zoom.
  10035. // In this case, the easiest way to prevent this is re-do the renderer
  10036. // bounds and padding when the zooming starts.
  10037. this._update();
  10038. },
  10039. _update: function () {
  10040. if (this._map._animatingZoom && this._bounds) { return; }
  10041. Renderer.prototype._update.call(this);
  10042. var b = this._bounds,
  10043. size = b.getSize(),
  10044. container = this._container;
  10045. // set size of svg-container if changed
  10046. if (!this._svgSize || !this._svgSize.equals(size)) {
  10047. this._svgSize = size;
  10048. container.setAttribute('width', size.x);
  10049. container.setAttribute('height', size.y);
  10050. }
  10051. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10052. setPosition(container, b.min);
  10053. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10054. this.fire('update');
  10055. },
  10056. // methods below are called by vector layers implementations
  10057. _initPath: function (layer) {
  10058. var path = layer._path = create$2('path');
  10059. // @namespace Path
  10060. // @option className: String = null
  10061. // Custom class name set on an element. Only for SVG renderer.
  10062. if (layer.options.className) {
  10063. addClass(path, layer.options.className);
  10064. }
  10065. if (layer.options.interactive) {
  10066. addClass(path, 'leaflet-interactive');
  10067. }
  10068. this._updateStyle(layer);
  10069. this._layers[stamp(layer)] = layer;
  10070. },
  10071. _addPath: function (layer) {
  10072. if (!this._rootGroup) { this._initContainer(); }
  10073. this._rootGroup.appendChild(layer._path);
  10074. layer.addInteractiveTarget(layer._path);
  10075. },
  10076. _removePath: function (layer) {
  10077. remove(layer._path);
  10078. layer.removeInteractiveTarget(layer._path);
  10079. delete this._layers[stamp(layer)];
  10080. },
  10081. _updatePath: function (layer) {
  10082. layer._project();
  10083. layer._update();
  10084. },
  10085. _updateStyle: function (layer) {
  10086. var path = layer._path,
  10087. options = layer.options;
  10088. if (!path) { return; }
  10089. if (options.stroke) {
  10090. path.setAttribute('stroke', options.color);
  10091. path.setAttribute('stroke-opacity', options.opacity);
  10092. path.setAttribute('stroke-width', options.weight);
  10093. path.setAttribute('stroke-linecap', options.lineCap);
  10094. path.setAttribute('stroke-linejoin', options.lineJoin);
  10095. if (options.dashArray) {
  10096. path.setAttribute('stroke-dasharray', options.dashArray);
  10097. } else {
  10098. path.removeAttribute('stroke-dasharray');
  10099. }
  10100. if (options.dashOffset) {
  10101. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10102. } else {
  10103. path.removeAttribute('stroke-dashoffset');
  10104. }
  10105. } else {
  10106. path.setAttribute('stroke', 'none');
  10107. }
  10108. if (options.fill) {
  10109. path.setAttribute('fill', options.fillColor || options.color);
  10110. path.setAttribute('fill-opacity', options.fillOpacity);
  10111. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10112. } else {
  10113. path.setAttribute('fill', 'none');
  10114. }
  10115. },
  10116. _updatePoly: function (layer, closed) {
  10117. this._setPath(layer, pointsToPath(layer._parts, closed));
  10118. },
  10119. _updateCircle: function (layer) {
  10120. var p = layer._point,
  10121. r = layer._radius,
  10122. r2 = layer._radiusY || r,
  10123. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10124. // drawing a circle with two half-arcs
  10125. var d = layer._empty() ? 'M0 0' :
  10126. 'M' + (p.x - r) + ',' + p.y +
  10127. arc + (r * 2) + ',0 ' +
  10128. arc + (-r * 2) + ',0 ';
  10129. this._setPath(layer, d);
  10130. },
  10131. _setPath: function (layer, path) {
  10132. layer._path.setAttribute('d', path);
  10133. },
  10134. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10135. _bringToFront: function (layer) {
  10136. toFront(layer._path);
  10137. },
  10138. _bringToBack: function (layer) {
  10139. toBack(layer._path);
  10140. }
  10141. });
  10142. if (vml) {
  10143. SVG.include(vmlMixin);
  10144. }
  10145. // @factory L.svg(options?: Renderer options)
  10146. // Creates a SVG renderer with the given options.
  10147. function svg$1(options) {
  10148. return svg || vml ? new SVG(options) : null;
  10149. }
  10150. Map.include({
  10151. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10152. // Returns the instance of `Renderer` that should be used to render the given
  10153. // `Path`. It will ensure that the `renderer` options of the map and paths
  10154. // are respected, and that the renderers do exist on the map.
  10155. getRenderer: function (layer) {
  10156. // @namespace Path; @option renderer: Renderer
  10157. // Use this specific instance of `Renderer` for this path. Takes
  10158. // precedence over the map's [default renderer](#map-renderer).
  10159. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10160. if (!renderer) {
  10161. // @namespace Map; @option preferCanvas: Boolean = false
  10162. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10163. // By default, all `Path`s are rendered in a `SVG` renderer.
  10164. renderer = this._renderer = (this.options.preferCanvas && canvas$1()) || svg$1();
  10165. }
  10166. if (!this.hasLayer(renderer)) {
  10167. this.addLayer(renderer);
  10168. }
  10169. return renderer;
  10170. },
  10171. _getPaneRenderer: function (name) {
  10172. if (name === 'overlayPane' || name === undefined) {
  10173. return false;
  10174. }
  10175. var renderer = this._paneRenderers[name];
  10176. if (renderer === undefined) {
  10177. renderer = (SVG && svg$1({pane: name})) || (Canvas && canvas$1({pane: name}));
  10178. this._paneRenderers[name] = renderer;
  10179. }
  10180. return renderer;
  10181. }
  10182. });
  10183. /*
  10184. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10185. */
  10186. /*
  10187. * @class Rectangle
  10188. * @aka L.Retangle
  10189. * @inherits Polygon
  10190. *
  10191. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10192. *
  10193. * @example
  10194. *
  10195. * ```js
  10196. * // define rectangle geographical bounds
  10197. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10198. *
  10199. * // create an orange rectangle
  10200. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10201. *
  10202. * // zoom the map to the rectangle bounds
  10203. * map.fitBounds(bounds);
  10204. * ```
  10205. *
  10206. */
  10207. var Rectangle = Polygon.extend({
  10208. initialize: function (latLngBounds, options) {
  10209. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10210. },
  10211. // @method setBounds(latLngBounds: LatLngBounds): this
  10212. // Redraws the rectangle with the passed bounds.
  10213. setBounds: function (latLngBounds) {
  10214. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  10215. },
  10216. _boundsToLatLngs: function (latLngBounds) {
  10217. latLngBounds = toLatLngBounds(latLngBounds);
  10218. return [
  10219. latLngBounds.getSouthWest(),
  10220. latLngBounds.getNorthWest(),
  10221. latLngBounds.getNorthEast(),
  10222. latLngBounds.getSouthEast()
  10223. ];
  10224. }
  10225. });
  10226. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  10227. function rectangle(latLngBounds, options) {
  10228. return new Rectangle(latLngBounds, options);
  10229. }
  10230. SVG.create = create$2;
  10231. SVG.pointsToPath = pointsToPath;
  10232. GeoJSON.geometryToLayer = geometryToLayer;
  10233. GeoJSON.coordsToLatLng = coordsToLatLng;
  10234. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  10235. GeoJSON.latLngToCoords = latLngToCoords;
  10236. GeoJSON.latLngsToCoords = latLngsToCoords;
  10237. GeoJSON.getFeature = getFeature;
  10238. GeoJSON.asFeature = asFeature;
  10239. /*
  10240. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  10241. * (zoom to a selected bounding box), enabled by default.
  10242. */
  10243. // @namespace Map
  10244. // @section Interaction Options
  10245. Map.mergeOptions({
  10246. // @option boxZoom: Boolean = true
  10247. // Whether the map can be zoomed to a rectangular area specified by
  10248. // dragging the mouse while pressing the shift key.
  10249. boxZoom: true
  10250. });
  10251. var BoxZoom = Handler.extend({
  10252. initialize: function (map) {
  10253. this._map = map;
  10254. this._container = map._container;
  10255. this._pane = map._panes.overlayPane;
  10256. this._resetStateTimeout = 0;
  10257. map.on('unload', this._destroy, this);
  10258. },
  10259. addHooks: function () {
  10260. on(this._container, 'mousedown', this._onMouseDown, this);
  10261. },
  10262. removeHooks: function () {
  10263. off(this._container, 'mousedown', this._onMouseDown, this);
  10264. },
  10265. moved: function () {
  10266. return this._moved;
  10267. },
  10268. _destroy: function () {
  10269. remove(this._pane);
  10270. delete this._pane;
  10271. },
  10272. _resetState: function () {
  10273. this._resetStateTimeout = 0;
  10274. this._moved = false;
  10275. },
  10276. _clearDeferredResetState: function () {
  10277. if (this._resetStateTimeout !== 0) {
  10278. clearTimeout(this._resetStateTimeout);
  10279. this._resetStateTimeout = 0;
  10280. }
  10281. },
  10282. _onMouseDown: function (e) {
  10283. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  10284. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  10285. // will interrupt the interaction and orphan a box element in the container.
  10286. this._clearDeferredResetState();
  10287. this._resetState();
  10288. disableTextSelection();
  10289. disableImageDrag();
  10290. this._startPoint = this._map.mouseEventToContainerPoint(e);
  10291. on(document, {
  10292. contextmenu: stop,
  10293. mousemove: this._onMouseMove,
  10294. mouseup: this._onMouseUp,
  10295. keydown: this._onKeyDown
  10296. }, this);
  10297. },
  10298. _onMouseMove: function (e) {
  10299. if (!this._moved) {
  10300. this._moved = true;
  10301. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  10302. addClass(this._container, 'leaflet-crosshair');
  10303. this._map.fire('boxzoomstart');
  10304. }
  10305. this._point = this._map.mouseEventToContainerPoint(e);
  10306. var bounds = new Bounds(this._point, this._startPoint),
  10307. size = bounds.getSize();
  10308. setPosition(this._box, bounds.min);
  10309. this._box.style.width = size.x + 'px';
  10310. this._box.style.height = size.y + 'px';
  10311. },
  10312. _finish: function () {
  10313. if (this._moved) {
  10314. remove(this._box);
  10315. removeClass(this._container, 'leaflet-crosshair');
  10316. }
  10317. enableTextSelection();
  10318. enableImageDrag();
  10319. off(document, {
  10320. contextmenu: stop,
  10321. mousemove: this._onMouseMove,
  10322. mouseup: this._onMouseUp,
  10323. keydown: this._onKeyDown
  10324. }, this);
  10325. },
  10326. _onMouseUp: function (e) {
  10327. if ((e.which !== 1) && (e.button !== 1)) { return; }
  10328. this._finish();
  10329. if (!this._moved) { return; }
  10330. // Postpone to next JS tick so internal click event handling
  10331. // still see it as "moved".
  10332. this._clearDeferredResetState();
  10333. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  10334. var bounds = new LatLngBounds(
  10335. this._map.containerPointToLatLng(this._startPoint),
  10336. this._map.containerPointToLatLng(this._point));
  10337. this._map
  10338. .fitBounds(bounds)
  10339. .fire('boxzoomend', {boxZoomBounds: bounds});
  10340. },
  10341. _onKeyDown: function (e) {
  10342. if (e.keyCode === 27) {
  10343. this._finish();
  10344. }
  10345. }
  10346. });
  10347. // @section Handlers
  10348. // @property boxZoom: Handler
  10349. // Box (shift-drag with mouse) zoom handler.
  10350. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  10351. /*
  10352. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  10353. */
  10354. // @namespace Map
  10355. // @section Interaction Options
  10356. Map.mergeOptions({
  10357. // @option doubleClickZoom: Boolean|String = true
  10358. // Whether the map can be zoomed in by double clicking on it and
  10359. // zoomed out by double clicking while holding shift. If passed
  10360. // `'center'`, double-click zoom will zoom to the center of the
  10361. // view regardless of where the mouse was.
  10362. doubleClickZoom: true
  10363. });
  10364. var DoubleClickZoom = Handler.extend({
  10365. addHooks: function () {
  10366. this._map.on('dblclick', this._onDoubleClick, this);
  10367. },
  10368. removeHooks: function () {
  10369. this._map.off('dblclick', this._onDoubleClick, this);
  10370. },
  10371. _onDoubleClick: function (e) {
  10372. var map = this._map,
  10373. oldZoom = map.getZoom(),
  10374. delta = map.options.zoomDelta,
  10375. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  10376. if (map.options.doubleClickZoom === 'center') {
  10377. map.setZoom(zoom);
  10378. } else {
  10379. map.setZoomAround(e.containerPoint, zoom);
  10380. }
  10381. }
  10382. });
  10383. // @section Handlers
  10384. //
  10385. // Map properties include interaction handlers that allow you to control
  10386. // interaction behavior in runtime, enabling or disabling certain features such
  10387. // as dragging or touch zoom (see `Handler` methods). For example:
  10388. //
  10389. // ```js
  10390. // map.doubleClickZoom.disable();
  10391. // ```
  10392. //
  10393. // @property doubleClickZoom: Handler
  10394. // Double click zoom handler.
  10395. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  10396. /*
  10397. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  10398. */
  10399. // @namespace Map
  10400. // @section Interaction Options
  10401. Map.mergeOptions({
  10402. // @option dragging: Boolean = true
  10403. // Whether the map be draggable with mouse/touch or not.
  10404. dragging: true,
  10405. // @section Panning Inertia Options
  10406. // @option inertia: Boolean = *
  10407. // If enabled, panning of the map will have an inertia effect where
  10408. // the map builds momentum while dragging and continues moving in
  10409. // the same direction for some time. Feels especially nice on touch
  10410. // devices. Enabled by default unless running on old Android devices.
  10411. inertia: !android23,
  10412. // @option inertiaDeceleration: Number = 3000
  10413. // The rate with which the inertial movement slows down, in pixels/second².
  10414. inertiaDeceleration: 3400, // px/s^2
  10415. // @option inertiaMaxSpeed: Number = Infinity
  10416. // Max speed of the inertial movement, in pixels/second.
  10417. inertiaMaxSpeed: Infinity, // px/s
  10418. // @option easeLinearity: Number = 0.2
  10419. easeLinearity: 0.2,
  10420. // TODO refactor, move to CRS
  10421. // @option worldCopyJump: Boolean = false
  10422. // With this option enabled, the map tracks when you pan to another "copy"
  10423. // of the world and seamlessly jumps to the original one so that all overlays
  10424. // like markers and vector layers are still visible.
  10425. worldCopyJump: false,
  10426. // @option maxBoundsViscosity: Number = 0.0
  10427. // If `maxBounds` is set, this option will control how solid the bounds
  10428. // are when dragging the map around. The default value of `0.0` allows the
  10429. // user to drag outside the bounds at normal speed, higher values will
  10430. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  10431. // solid, preventing the user from dragging outside the bounds.
  10432. maxBoundsViscosity: 0.0
  10433. });
  10434. var Drag = Handler.extend({
  10435. addHooks: function () {
  10436. if (!this._draggable) {
  10437. var map = this._map;
  10438. this._draggable = new Draggable(map._mapPane, map._container);
  10439. this._draggable.on({
  10440. dragstart: this._onDragStart,
  10441. drag: this._onDrag,
  10442. dragend: this._onDragEnd
  10443. }, this);
  10444. this._draggable.on('predrag', this._onPreDragLimit, this);
  10445. if (map.options.worldCopyJump) {
  10446. this._draggable.on('predrag', this._onPreDragWrap, this);
  10447. map.on('zoomend', this._onZoomEnd, this);
  10448. map.whenReady(this._onZoomEnd, this);
  10449. }
  10450. }
  10451. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  10452. this._draggable.enable();
  10453. this._positions = [];
  10454. this._times = [];
  10455. },
  10456. removeHooks: function () {
  10457. removeClass(this._map._container, 'leaflet-grab');
  10458. removeClass(this._map._container, 'leaflet-touch-drag');
  10459. this._draggable.disable();
  10460. },
  10461. moved: function () {
  10462. return this._draggable && this._draggable._moved;
  10463. },
  10464. moving: function () {
  10465. return this._draggable && this._draggable._moving;
  10466. },
  10467. _onDragStart: function () {
  10468. var map = this._map;
  10469. map._stop();
  10470. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  10471. var bounds = toLatLngBounds(this._map.options.maxBounds);
  10472. this._offsetLimit = toBounds(
  10473. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  10474. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  10475. .add(this._map.getSize()));
  10476. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  10477. } else {
  10478. this._offsetLimit = null;
  10479. }
  10480. map
  10481. .fire('movestart')
  10482. .fire('dragstart');
  10483. if (map.options.inertia) {
  10484. this._positions = [];
  10485. this._times = [];
  10486. }
  10487. },
  10488. _onDrag: function (e) {
  10489. if (this._map.options.inertia) {
  10490. var time = this._lastTime = +new Date(),
  10491. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  10492. this._positions.push(pos);
  10493. this._times.push(time);
  10494. if (time - this._times[0] > 50) {
  10495. this._positions.shift();
  10496. this._times.shift();
  10497. }
  10498. }
  10499. this._map
  10500. .fire('move', e)
  10501. .fire('drag', e);
  10502. },
  10503. _onZoomEnd: function () {
  10504. var pxCenter = this._map.getSize().divideBy(2),
  10505. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  10506. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  10507. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  10508. },
  10509. _viscousLimit: function (value, threshold) {
  10510. return value - (value - threshold) * this._viscosity;
  10511. },
  10512. _onPreDragLimit: function () {
  10513. if (!this._viscosity || !this._offsetLimit) { return; }
  10514. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  10515. var limit = this._offsetLimit;
  10516. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  10517. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  10518. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  10519. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  10520. this._draggable._newPos = this._draggable._startPos.add(offset);
  10521. },
  10522. _onPreDragWrap: function () {
  10523. // TODO refactor to be able to adjust map pane position after zoom
  10524. var worldWidth = this._worldWidth,
  10525. halfWidth = Math.round(worldWidth / 2),
  10526. dx = this._initialWorldOffset,
  10527. x = this._draggable._newPos.x,
  10528. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  10529. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  10530. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  10531. this._draggable._absPos = this._draggable._newPos.clone();
  10532. this._draggable._newPos.x = newX;
  10533. },
  10534. _onDragEnd: function (e) {
  10535. var map = this._map,
  10536. options = map.options,
  10537. noInertia = !options.inertia || this._times.length < 2;
  10538. map.fire('dragend', e);
  10539. if (noInertia) {
  10540. map.fire('moveend');
  10541. } else {
  10542. var direction = this._lastPos.subtract(this._positions[0]),
  10543. duration = (this._lastTime - this._times[0]) / 1000,
  10544. ease = options.easeLinearity,
  10545. speedVector = direction.multiplyBy(ease / duration),
  10546. speed = speedVector.distanceTo([0, 0]),
  10547. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  10548. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  10549. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  10550. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  10551. if (!offset.x && !offset.y) {
  10552. map.fire('moveend');
  10553. } else {
  10554. offset = map._limitOffset(offset, map.options.maxBounds);
  10555. requestAnimFrame(function () {
  10556. map.panBy(offset, {
  10557. duration: decelerationDuration,
  10558. easeLinearity: ease,
  10559. noMoveStart: true,
  10560. animate: true
  10561. });
  10562. });
  10563. }
  10564. }
  10565. }
  10566. });
  10567. // @section Handlers
  10568. // @property dragging: Handler
  10569. // Map dragging handler (by both mouse and touch).
  10570. Map.addInitHook('addHandler', 'dragging', Drag);
  10571. /*
  10572. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  10573. */
  10574. // @namespace Map
  10575. // @section Keyboard Navigation Options
  10576. Map.mergeOptions({
  10577. // @option keyboard: Boolean = true
  10578. // Makes the map focusable and allows users to navigate the map with keyboard
  10579. // arrows and `+`/`-` keys.
  10580. keyboard: true,
  10581. // @option keyboardPanDelta: Number = 80
  10582. // Amount of pixels to pan when pressing an arrow key.
  10583. keyboardPanDelta: 80
  10584. });
  10585. var Keyboard = Handler.extend({
  10586. keyCodes: {
  10587. left: [37],
  10588. right: [39],
  10589. down: [40],
  10590. up: [38],
  10591. zoomIn: [187, 107, 61, 171],
  10592. zoomOut: [189, 109, 54, 173]
  10593. },
  10594. initialize: function (map) {
  10595. this._map = map;
  10596. this._setPanDelta(map.options.keyboardPanDelta);
  10597. this._setZoomDelta(map.options.zoomDelta);
  10598. },
  10599. addHooks: function () {
  10600. var container = this._map._container;
  10601. // make the container focusable by tabbing
  10602. if (container.tabIndex <= 0) {
  10603. container.tabIndex = '0';
  10604. }
  10605. on(container, {
  10606. focus: this._onFocus,
  10607. blur: this._onBlur,
  10608. mousedown: this._onMouseDown
  10609. }, this);
  10610. this._map.on({
  10611. focus: this._addHooks,
  10612. blur: this._removeHooks
  10613. }, this);
  10614. },
  10615. removeHooks: function () {
  10616. this._removeHooks();
  10617. off(this._map._container, {
  10618. focus: this._onFocus,
  10619. blur: this._onBlur,
  10620. mousedown: this._onMouseDown
  10621. }, this);
  10622. this._map.off({
  10623. focus: this._addHooks,
  10624. blur: this._removeHooks
  10625. }, this);
  10626. },
  10627. _onMouseDown: function () {
  10628. if (this._focused) { return; }
  10629. var body = document.body,
  10630. docEl = document.documentElement,
  10631. top = body.scrollTop || docEl.scrollTop,
  10632. left = body.scrollLeft || docEl.scrollLeft;
  10633. this._map._container.focus();
  10634. window.scrollTo(left, top);
  10635. },
  10636. _onFocus: function () {
  10637. this._focused = true;
  10638. this._map.fire('focus');
  10639. },
  10640. _onBlur: function () {
  10641. this._focused = false;
  10642. this._map.fire('blur');
  10643. },
  10644. _setPanDelta: function (panDelta) {
  10645. var keys = this._panKeys = {},
  10646. codes = this.keyCodes,
  10647. i, len;
  10648. for (i = 0, len = codes.left.length; i < len; i++) {
  10649. keys[codes.left[i]] = [-1 * panDelta, 0];
  10650. }
  10651. for (i = 0, len = codes.right.length; i < len; i++) {
  10652. keys[codes.right[i]] = [panDelta, 0];
  10653. }
  10654. for (i = 0, len = codes.down.length; i < len; i++) {
  10655. keys[codes.down[i]] = [0, panDelta];
  10656. }
  10657. for (i = 0, len = codes.up.length; i < len; i++) {
  10658. keys[codes.up[i]] = [0, -1 * panDelta];
  10659. }
  10660. },
  10661. _setZoomDelta: function (zoomDelta) {
  10662. var keys = this._zoomKeys = {},
  10663. codes = this.keyCodes,
  10664. i, len;
  10665. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  10666. keys[codes.zoomIn[i]] = zoomDelta;
  10667. }
  10668. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  10669. keys[codes.zoomOut[i]] = -zoomDelta;
  10670. }
  10671. },
  10672. _addHooks: function () {
  10673. on(document, 'keydown', this._onKeyDown, this);
  10674. },
  10675. _removeHooks: function () {
  10676. off(document, 'keydown', this._onKeyDown, this);
  10677. },
  10678. _onKeyDown: function (e) {
  10679. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  10680. var key = e.keyCode,
  10681. map = this._map,
  10682. offset;
  10683. if (key in this._panKeys) {
  10684. if (map._panAnim && map._panAnim._inProgress) { return; }
  10685. offset = this._panKeys[key];
  10686. if (e.shiftKey) {
  10687. offset = toPoint(offset).multiplyBy(3);
  10688. }
  10689. map.panBy(offset);
  10690. if (map.options.maxBounds) {
  10691. map.panInsideBounds(map.options.maxBounds);
  10692. }
  10693. } else if (key in this._zoomKeys) {
  10694. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  10695. } else if (key === 27 && map._popup) {
  10696. map.closePopup();
  10697. } else {
  10698. return;
  10699. }
  10700. stop(e);
  10701. }
  10702. });
  10703. // @section Handlers
  10704. // @section Handlers
  10705. // @property keyboard: Handler
  10706. // Keyboard navigation handler.
  10707. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  10708. /*
  10709. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  10710. */
  10711. // @namespace Map
  10712. // @section Interaction Options
  10713. Map.mergeOptions({
  10714. // @section Mousewheel options
  10715. // @option scrollWheelZoom: Boolean|String = true
  10716. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  10717. // it will zoom to the center of the view regardless of where the mouse was.
  10718. scrollWheelZoom: true,
  10719. // @option wheelDebounceTime: Number = 40
  10720. // Limits the rate at which a wheel can fire (in milliseconds). By default
  10721. // user can't zoom via wheel more often than once per 40 ms.
  10722. wheelDebounceTime: 40,
  10723. // @option wheelPxPerZoomLevel: Number = 60
  10724. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  10725. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  10726. // faster (and vice versa).
  10727. wheelPxPerZoomLevel: 60
  10728. });
  10729. var ScrollWheelZoom = Handler.extend({
  10730. addHooks: function () {
  10731. on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  10732. this._delta = 0;
  10733. },
  10734. removeHooks: function () {
  10735. off(this._map._container, 'mousewheel', this._onWheelScroll, this);
  10736. },
  10737. _onWheelScroll: function (e) {
  10738. var delta = getWheelDelta(e);
  10739. var debounce = this._map.options.wheelDebounceTime;
  10740. this._delta += delta;
  10741. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  10742. if (!this._startTime) {
  10743. this._startTime = +new Date();
  10744. }
  10745. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  10746. clearTimeout(this._timer);
  10747. this._timer = setTimeout(bind(this._performZoom, this), left);
  10748. stop(e);
  10749. },
  10750. _performZoom: function () {
  10751. var map = this._map,
  10752. zoom = map.getZoom(),
  10753. snap = this._map.options.zoomSnap || 0;
  10754. map._stop(); // stop panning and fly animations if any
  10755. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  10756. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  10757. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  10758. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  10759. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  10760. this._delta = 0;
  10761. this._startTime = null;
  10762. if (!delta) { return; }
  10763. if (map.options.scrollWheelZoom === 'center') {
  10764. map.setZoom(zoom + delta);
  10765. } else {
  10766. map.setZoomAround(this._lastMousePos, zoom + delta);
  10767. }
  10768. }
  10769. });
  10770. // @section Handlers
  10771. // @property scrollWheelZoom: Handler
  10772. // Scroll wheel zoom handler.
  10773. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  10774. /*
  10775. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  10776. */
  10777. // @namespace Map
  10778. // @section Interaction Options
  10779. Map.mergeOptions({
  10780. // @section Touch interaction options
  10781. // @option tap: Boolean = true
  10782. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  10783. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  10784. tap: true,
  10785. // @option tapTolerance: Number = 15
  10786. // The max number of pixels a user can shift his finger during touch
  10787. // for it to be considered a valid tap.
  10788. tapTolerance: 15
  10789. });
  10790. var Tap = Handler.extend({
  10791. addHooks: function () {
  10792. on(this._map._container, 'touchstart', this._onDown, this);
  10793. },
  10794. removeHooks: function () {
  10795. off(this._map._container, 'touchstart', this._onDown, this);
  10796. },
  10797. _onDown: function (e) {
  10798. if (!e.touches) { return; }
  10799. preventDefault(e);
  10800. this._fireClick = true;
  10801. // don't simulate click or track longpress if more than 1 touch
  10802. if (e.touches.length > 1) {
  10803. this._fireClick = false;
  10804. clearTimeout(this._holdTimeout);
  10805. return;
  10806. }
  10807. var first = e.touches[0],
  10808. el = first.target;
  10809. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  10810. // if touching a link, highlight it
  10811. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  10812. addClass(el, 'leaflet-active');
  10813. }
  10814. // simulate long hold but setting a timeout
  10815. this._holdTimeout = setTimeout(bind(function () {
  10816. if (this._isTapValid()) {
  10817. this._fireClick = false;
  10818. this._onUp();
  10819. this._simulateEvent('contextmenu', first);
  10820. }
  10821. }, this), 1000);
  10822. this._simulateEvent('mousedown', first);
  10823. on(document, {
  10824. touchmove: this._onMove,
  10825. touchend: this._onUp
  10826. }, this);
  10827. },
  10828. _onUp: function (e) {
  10829. clearTimeout(this._holdTimeout);
  10830. off(document, {
  10831. touchmove: this._onMove,
  10832. touchend: this._onUp
  10833. }, this);
  10834. if (this._fireClick && e && e.changedTouches) {
  10835. var first = e.changedTouches[0],
  10836. el = first.target;
  10837. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  10838. removeClass(el, 'leaflet-active');
  10839. }
  10840. this._simulateEvent('mouseup', first);
  10841. // simulate click if the touch didn't move too much
  10842. if (this._isTapValid()) {
  10843. this._simulateEvent('click', first);
  10844. }
  10845. }
  10846. },
  10847. _isTapValid: function () {
  10848. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  10849. },
  10850. _onMove: function (e) {
  10851. var first = e.touches[0];
  10852. this._newPos = new Point(first.clientX, first.clientY);
  10853. this._simulateEvent('mousemove', first);
  10854. },
  10855. _simulateEvent: function (type, e) {
  10856. var simulatedEvent = document.createEvent('MouseEvents');
  10857. simulatedEvent._simulated = true;
  10858. e.target._simulatedClick = true;
  10859. simulatedEvent.initMouseEvent(
  10860. type, true, true, window, 1,
  10861. e.screenX, e.screenY,
  10862. e.clientX, e.clientY,
  10863. false, false, false, false, 0, null);
  10864. e.target.dispatchEvent(simulatedEvent);
  10865. }
  10866. });
  10867. // @section Handlers
  10868. // @property tap: Handler
  10869. // Mobile touch hacks (quick tap and touch hold) handler.
  10870. if (touch && !pointer) {
  10871. Map.addInitHook('addHandler', 'tap', Tap);
  10872. }
  10873. /*
  10874. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  10875. */
  10876. // @namespace Map
  10877. // @section Interaction Options
  10878. Map.mergeOptions({
  10879. // @section Touch interaction options
  10880. // @option touchZoom: Boolean|String = *
  10881. // Whether the map can be zoomed by touch-dragging with two fingers. If
  10882. // passed `'center'`, it will zoom to the center of the view regardless of
  10883. // where the touch events (fingers) were. Enabled for touch-capable web
  10884. // browsers except for old Androids.
  10885. touchZoom: touch && !android23,
  10886. // @option bounceAtZoomLimits: Boolean = true
  10887. // Set it to false if you don't want the map to zoom beyond min/max zoom
  10888. // and then bounce back when pinch-zooming.
  10889. bounceAtZoomLimits: true
  10890. });
  10891. var TouchZoom = Handler.extend({
  10892. addHooks: function () {
  10893. addClass(this._map._container, 'leaflet-touch-zoom');
  10894. on(this._map._container, 'touchstart', this._onTouchStart, this);
  10895. },
  10896. removeHooks: function () {
  10897. removeClass(this._map._container, 'leaflet-touch-zoom');
  10898. off(this._map._container, 'touchstart', this._onTouchStart, this);
  10899. },
  10900. _onTouchStart: function (e) {
  10901. var map = this._map;
  10902. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  10903. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  10904. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  10905. this._centerPoint = map.getSize()._divideBy(2);
  10906. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  10907. if (map.options.touchZoom !== 'center') {
  10908. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  10909. }
  10910. this._startDist = p1.distanceTo(p2);
  10911. this._startZoom = map.getZoom();
  10912. this._moved = false;
  10913. this._zooming = true;
  10914. map._stop();
  10915. on(document, 'touchmove', this._onTouchMove, this);
  10916. on(document, 'touchend', this._onTouchEnd, this);
  10917. preventDefault(e);
  10918. },
  10919. _onTouchMove: function (e) {
  10920. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  10921. var map = this._map,
  10922. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  10923. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  10924. scale = p1.distanceTo(p2) / this._startDist;
  10925. this._zoom = map.getScaleZoom(scale, this._startZoom);
  10926. if (!map.options.bounceAtZoomLimits && (
  10927. (this._zoom < map.getMinZoom() && scale < 1) ||
  10928. (this._zoom > map.getMaxZoom() && scale > 1))) {
  10929. this._zoom = map._limitZoom(this._zoom);
  10930. }
  10931. if (map.options.touchZoom === 'center') {
  10932. this._center = this._startLatLng;
  10933. if (scale === 1) { return; }
  10934. } else {
  10935. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  10936. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  10937. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  10938. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  10939. }
  10940. if (!this._moved) {
  10941. map._moveStart(true);
  10942. this._moved = true;
  10943. }
  10944. cancelAnimFrame(this._animRequest);
  10945. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  10946. this._animRequest = requestAnimFrame(moveFn, this, true);
  10947. preventDefault(e);
  10948. },
  10949. _onTouchEnd: function () {
  10950. if (!this._moved || !this._zooming) {
  10951. this._zooming = false;
  10952. return;
  10953. }
  10954. this._zooming = false;
  10955. cancelAnimFrame(this._animRequest);
  10956. off(document, 'touchmove', this._onTouchMove);
  10957. off(document, 'touchend', this._onTouchEnd);
  10958. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  10959. if (this._map.options.zoomAnimation) {
  10960. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  10961. } else {
  10962. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  10963. }
  10964. }
  10965. });
  10966. // @section Handlers
  10967. // @property touchZoom: Handler
  10968. // Touch zoom handler.
  10969. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  10970. Map.BoxZoom = BoxZoom;
  10971. Map.DoubleClickZoom = DoubleClickZoom;
  10972. Map.Drag = Drag;
  10973. Map.Keyboard = Keyboard;
  10974. Map.ScrollWheelZoom = ScrollWheelZoom;
  10975. Map.Tap = Tap;
  10976. Map.TouchZoom = TouchZoom;
  10977. // misc
  10978. var oldL = window.L;
  10979. function noConflict() {
  10980. window.L = oldL;
  10981. return this;
  10982. }
  10983. // Always export us to window global (see #2364)
  10984. window.L = exports;
  10985. Object.freeze = freeze;
  10986. exports.version = version;
  10987. exports.noConflict = noConflict;
  10988. exports.Control = Control;
  10989. exports.control = control;
  10990. exports.Browser = Browser;
  10991. exports.Evented = Evented;
  10992. exports.Mixin = Mixin;
  10993. exports.Util = Util;
  10994. exports.Class = Class;
  10995. exports.Handler = Handler;
  10996. exports.extend = extend;
  10997. exports.bind = bind;
  10998. exports.stamp = stamp;
  10999. exports.setOptions = setOptions;
  11000. exports.DomEvent = DomEvent;
  11001. exports.DomUtil = DomUtil;
  11002. exports.PosAnimation = PosAnimation;
  11003. exports.Draggable = Draggable;
  11004. exports.LineUtil = LineUtil;
  11005. exports.PolyUtil = PolyUtil;
  11006. exports.Point = Point;
  11007. exports.point = toPoint;
  11008. exports.Bounds = Bounds;
  11009. exports.bounds = toBounds;
  11010. exports.Transformation = Transformation;
  11011. exports.transformation = toTransformation;
  11012. exports.Projection = index;
  11013. exports.LatLng = LatLng;
  11014. exports.latLng = toLatLng;
  11015. exports.LatLngBounds = LatLngBounds;
  11016. exports.latLngBounds = toLatLngBounds;
  11017. exports.CRS = CRS;
  11018. exports.GeoJSON = GeoJSON;
  11019. exports.geoJSON = geoJSON;
  11020. exports.geoJson = geoJson;
  11021. exports.Layer = Layer;
  11022. exports.LayerGroup = LayerGroup;
  11023. exports.layerGroup = layerGroup;
  11024. exports.FeatureGroup = FeatureGroup;
  11025. exports.featureGroup = featureGroup;
  11026. exports.ImageOverlay = ImageOverlay;
  11027. exports.imageOverlay = imageOverlay;
  11028. exports.VideoOverlay = VideoOverlay;
  11029. exports.videoOverlay = videoOverlay;
  11030. exports.DivOverlay = DivOverlay;
  11031. exports.Popup = Popup;
  11032. exports.popup = popup;
  11033. exports.Tooltip = Tooltip;
  11034. exports.tooltip = tooltip;
  11035. exports.Icon = Icon;
  11036. exports.icon = icon;
  11037. exports.DivIcon = DivIcon;
  11038. exports.divIcon = divIcon;
  11039. exports.Marker = Marker;
  11040. exports.marker = marker;
  11041. exports.TileLayer = TileLayer;
  11042. exports.tileLayer = tileLayer;
  11043. exports.GridLayer = GridLayer;
  11044. exports.gridLayer = gridLayer;
  11045. exports.SVG = SVG;
  11046. exports.svg = svg$1;
  11047. exports.Renderer = Renderer;
  11048. exports.Canvas = Canvas;
  11049. exports.canvas = canvas$1;
  11050. exports.Path = Path;
  11051. exports.CircleMarker = CircleMarker;
  11052. exports.circleMarker = circleMarker;
  11053. exports.Circle = Circle;
  11054. exports.circle = circle;
  11055. exports.Polyline = Polyline;
  11056. exports.polyline = polyline;
  11057. exports.Polygon = Polygon;
  11058. exports.polygon = polygon;
  11059. exports.Rectangle = Rectangle;
  11060. exports.rectangle = rectangle;
  11061. exports.Map = Map;
  11062. exports.map = createMap;
  11063. })));
  11064. //# sourceMappingURL=leaflet-src.js.map