当前位置:   article > 正文

Leaflet源码解析_map container is being reused by another instance

map container is being reused by another instance

Map.js

  1. import * as Util from '../core/Util';
  2. import {Evented} from '../core/Events';
  3. import {EPSG3857} from '../geo/crs/CRS.EPSG3857';
  4. import {Point, toPoint} from '../geometry/Point';
  5. import {Bounds, toBounds} from '../geometry/Bounds';
  6. import {LatLng, toLatLng} from '../geo/LatLng';
  7. import {LatLngBounds, toLatLngBounds} from '../geo/LatLngBounds';
  8. import * as Browser from '../core/Browser';
  9. import * as DomEvent from '../dom/DomEvent';
  10. import * as DomUtil from '../dom/DomUtil';
  11. import {PosAnimation} from '../dom/PosAnimation';
  12. /*
  13. * @class Map
  14. * @aka L.Map
  15. * @inherits Evented
  16. *
  17. * The central class of the API — it is used to create a map on a page and manipulate it.
  18. *
  19. * @example
  20. *
  21. * ```js
  22. * // initialize the map on the "map" div with a given center and zoom
  23. * var map = L.map('map', {
  24. * center: [51.505, -0.09],
  25. * zoom: 13
  26. * });
  27. * ```
  28. *
  29. */
  30. export var Map = Evented.extend({
  31. options: {
  32. // @section Map State Options
  33. // @option crs: CRS = L.CRS.EPSG3857
  34. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  35. // sure what it means.
  36. crs: EPSG3857,
  37. // @option center: LatLng = undefined
  38. // Initial geographic center of the map
  39. center: undefined,
  40. // @option zoom: Number = undefined
  41. // Initial map zoom level
  42. zoom: undefined,
  43. // @option minZoom: Number = *
  44. // Minimum zoom level of the map.
  45. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  46. // the lowest of their `minZoom` options will be used instead.
  47. minZoom: undefined,
  48. // @option maxZoom: Number = *
  49. // Maximum zoom level of the map.
  50. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  51. // the highest of their `maxZoom` options will be used instead.
  52. maxZoom: undefined,
  53. // @option layers: Layer[] = []
  54. // Array of layers that will be added to the map initially
  55. layers: [],
  56. // @option maxBounds: LatLngBounds = null
  57. // When this option is set, the map restricts the view to the given
  58. // geographical bounds, bouncing the user back if the user tries to pan
  59. // outside the view. To set the restriction dynamically, use
  60. // [`setMaxBounds`](#map-setmaxbounds) method.
  61. maxBounds: undefined,
  62. // @option renderer: Renderer = *
  63. // The default method for drawing vector layers on the map. `L.SVG`
  64. // or `L.Canvas` by default depending on browser support.
  65. renderer: undefined,
  66. // @section Animation Options
  67. // @option zoomAnimation: Boolean = true
  68. // Whether the map zoom animation is enabled. By default it's enabled
  69. // in all browsers that support CSS3 Transitions except Android.
  70. zoomAnimation: true,
  71. // @option zoomAnimationThreshold: Number = 4
  72. // Won't animate zoom if the zoom difference exceeds this value.
  73. zoomAnimationThreshold: 4,
  74. // @option fadeAnimation: Boolean = true
  75. // Whether the tile fade animation is enabled. By default it's enabled
  76. // in all browsers that support CSS3 Transitions except Android.
  77. fadeAnimation: true,
  78. // @option markerZoomAnimation: Boolean = true
  79. // Whether markers animate their zoom with the zoom animation, if disabled
  80. // they will disappear for the length of the animation. By default it's
  81. // enabled in all browsers that support CSS3 Transitions except Android.
  82. markerZoomAnimation: true,
  83. // @option transform3DLimit: Number = 2^23
  84. // Defines the maximum size of a CSS translation transform. The default
  85. // value should not be changed unless a web browser positions layers in
  86. // the wrong place after doing a large `panBy`.
  87. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  88. // @section Interaction Options
  89. // @option zoomSnap: Number = 1
  90. // Forces the map's zoom level to always be a multiple of this, particularly
  91. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  92. // By default, the zoom level snaps to the nearest integer; lower values
  93. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  94. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  95. zoomSnap: 1,
  96. // @option zoomDelta: Number = 1
  97. // Controls how much the map's zoom level will change after a
  98. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  99. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  100. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  101. zoomDelta: 1,
  102. // @option trackResize: Boolean = true
  103. // Whether the map automatically handles browser window resize to update itself.
  104. trackResize: true
  105. },
  106. initialize: function (id, options) { // (HTMLElement or String, Object)
  107. options = Util.setOptions(this, options);
  108. // Make sure to assign internal flags at the beginning,
  109. // to avoid inconsistent state in some edge cases.
  110. this._handlers = [];
  111. this._layers = {};
  112. this._zoomBoundLayers = {};
  113. this._sizeChanged = true;
  114. this._initContainer(id);
  115. this._initLayout();
  116. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  117. this._onResize = Util.bind(this._onResize, this);
  118. this._initEvents();
  119. if (options.maxBounds) {
  120. this.setMaxBounds(options.maxBounds);
  121. }
  122. if (options.zoom !== undefined) {
  123. this._zoom = this._limitZoom(options.zoom);
  124. }
  125. if (options.center && options.zoom !== undefined) {
  126. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  127. }
  128. this.callInitHooks();
  129. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  130. this._zoomAnimated = DomUtil.TRANSITION && Browser.any3d && !Browser.mobileOpera &&
  131. this.options.zoomAnimation;
  132. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  133. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  134. if (this._zoomAnimated) {
  135. this._createAnimProxy();
  136. DomEvent.on(this._proxy, DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
  137. }
  138. this._addLayers(this.options.layers);
  139. },
  140. // @section Methods for modifying map state
  141. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  142. // Sets the view of the map (geographical center and zoom) with the given
  143. // animation options.
  144. setView: function (center, zoom, options) {
  145. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  146. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  147. options = options || {};
  148. this._stop();
  149. if (this._loaded && !options.reset && options !== true) {
  150. if (options.animate !== undefined) {
  151. options.zoom = Util.extend({animate: options.animate}, options.zoom);
  152. options.pan = Util.extend({animate: options.animate, duration: options.duration}, options.pan);
  153. }
  154. // try animating pan or zoom
  155. var moved = (this._zoom !== zoom) ?
  156. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  157. this._tryAnimatedPan(center, options.pan);
  158. if (moved) {
  159. // prevent resize handler call, the view will refresh after animation anyway
  160. clearTimeout(this._sizeTimer);
  161. return this;
  162. }
  163. }
  164. // animation didn't start, just reset the map view
  165. this._resetView(center, zoom);
  166. return this;
  167. },
  168. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  169. // Sets the zoom of the map.
  170. setZoom: function (zoom, options) {
  171. if (!this._loaded) {
  172. this._zoom = zoom;
  173. return this;
  174. }
  175. return this.setView(this.getCenter(), zoom, {zoom: options});
  176. },
  177. // @method zoomIn(delta?: Number, options?: Zoom options): this
  178. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  179. zoomIn: function (delta, options) {
  180. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  181. return this.setZoom(this._zoom + delta, options);
  182. },
  183. // @method zoomOut(delta?: Number, options?: Zoom options): this
  184. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  185. zoomOut: function (delta, options) {
  186. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  187. return this.setZoom(this._zoom - delta, options);
  188. },
  189. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  190. // Zooms the map while keeping a specified geographical point on the map
  191. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  192. // @alternative
  193. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  194. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  195. setZoomAround: function (latlng, zoom, options) {
  196. var scale = this.getZoomScale(zoom),
  197. viewHalf = this.getSize().divideBy(2),
  198. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  199. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  200. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  201. return this.setView(newCenter, zoom, {zoom: options});
  202. },
  203. _getBoundsCenterZoom: function (bounds, options) {
  204. options = options || {};
  205. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  206. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  207. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  208. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  209. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  210. if (zoom === Infinity) {
  211. return {
  212. center: bounds.getCenter(),
  213. zoom: zoom
  214. };
  215. }
  216. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  217. swPoint = this.project(bounds.getSouthWest(), zoom),
  218. nePoint = this.project(bounds.getNorthEast(), zoom),
  219. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  220. return {
  221. center: center,
  222. zoom: zoom
  223. };
  224. },
  225. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  226. // Sets a map view that contains the given geographical bounds with the
  227. // maximum zoom level possible.
  228. fitBounds: function (bounds, options) {
  229. bounds = toLatLngBounds(bounds);
  230. if (!bounds.isValid()) {
  231. throw new Error('Bounds are not valid.');
  232. }
  233. var target = this._getBoundsCenterZoom(bounds, options);
  234. return this.setView(target.center, target.zoom, options);
  235. },
  236. // @method fitWorld(options?: fitBounds options): this
  237. // Sets a map view that mostly contains the whole world with the maximum
  238. // zoom level possible.
  239. fitWorld: function (options) {
  240. return this.fitBounds([[-90, -180], [90, 180]], options);
  241. },
  242. // @method panTo(latlng: LatLng, options?: Pan options): this
  243. // Pans the map to a given center.
  244. panTo: function (center, options) { // (LatLng)
  245. return this.setView(center, this._zoom, {pan: options});
  246. },
  247. // @method panBy(offset: Point, options?: Pan options): this
  248. // Pans the map by a given number of pixels (animated).
  249. panBy: function (offset, options) {
  250. offset = toPoint(offset).round();
  251. options = options || {};
  252. if (!offset.x && !offset.y) {
  253. return this.fire('moveend');
  254. }
  255. // If we pan too far, Chrome gets issues with tiles
  256. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  257. if (options.animate !== true && !this.getSize().contains(offset)) {
  258. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  259. return this;
  260. }
  261. if (!this._panAnim) {
  262. this._panAnim = new PosAnimation();
  263. this._panAnim.on({
  264. 'step': this._onPanTransitionStep,
  265. 'end': this._onPanTransitionEnd
  266. }, this);
  267. }
  268. // don't fire movestart if animating inertia
  269. if (!options.noMoveStart) {
  270. this.fire('movestart');
  271. }
  272. // animate pan unless animate: false specified
  273. if (options.animate !== false) {
  274. DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
  275. var newPos = this._getMapPanePos().subtract(offset).round();
  276. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  277. } else {
  278. this._rawPanBy(offset);
  279. this.fire('move').fire('moveend');
  280. }
  281. return this;
  282. },
  283. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  284. // Sets the view of the map (geographical center and zoom) performing a smooth
  285. // pan-zoom animation.
  286. flyTo: function (targetCenter, targetZoom, options) {
  287. options = options || {};
  288. if (options.animate === false || !Browser.any3d) {
  289. return this.setView(targetCenter, targetZoom, options);
  290. }
  291. this._stop();
  292. var from = this.project(this.getCenter()),
  293. to = this.project(targetCenter),
  294. size = this.getSize(),
  295. startZoom = this._zoom;
  296. targetCenter = toLatLng(targetCenter);
  297. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  298. var w0 = Math.max(size.x, size.y),
  299. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  300. u1 = (to.distanceTo(from)) || 1,
  301. rho = 1.42,
  302. rho2 = rho * rho;
  303. function r(i) {
  304. var s1 = i ? -1 : 1,
  305. s2 = i ? w1 : w0,
  306. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  307. b1 = 2 * s2 * rho2 * u1,
  308. b = t1 / b1,
  309. sq = Math.sqrt(b * b + 1) - b;
  310. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  311. // thus triggering an infinite loop in flyTo
  312. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  313. return log;
  314. }
  315. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  316. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  317. function tanh(n) { return sinh(n) / cosh(n); }
  318. var r0 = r(0);
  319. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  320. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  321. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  322. var start = Date.now(),
  323. S = (r(1) - r0) / rho,
  324. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  325. function frame() {
  326. var t = (Date.now() - start) / duration,
  327. s = easeOut(t) * S;
  328. if (t <= 1) {
  329. this._flyToFrame = Util.requestAnimFrame(frame, this);
  330. this._move(
  331. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  332. this.getScaleZoom(w0 / w(s), startZoom),
  333. {flyTo: true});
  334. } else {
  335. this
  336. ._move(targetCenter, targetZoom)
  337. ._moveEnd(true);
  338. }
  339. }
  340. this._moveStart(true, options.noMoveStart);
  341. frame.call(this);
  342. return this;
  343. },
  344. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  345. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  346. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  347. flyToBounds: function (bounds, options) {
  348. var target = this._getBoundsCenterZoom(bounds, options);
  349. return this.flyTo(target.center, target.zoom, options);
  350. },
  351. // @method setMaxBounds(bounds: LatLngBounds): this
  352. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  353. setMaxBounds: function (bounds) {
  354. bounds = toLatLngBounds(bounds);
  355. if (!bounds.isValid()) {
  356. this.options.maxBounds = null;
  357. return this.off('moveend', this._panInsideMaxBounds);
  358. } else if (this.options.maxBounds) {
  359. this.off('moveend', this._panInsideMaxBounds);
  360. }
  361. this.options.maxBounds = bounds;
  362. if (this._loaded) {
  363. this._panInsideMaxBounds();
  364. }
  365. return this.on('moveend', this._panInsideMaxBounds);
  366. },
  367. // @method setMinZoom(zoom: Number): this
  368. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  369. setMinZoom: function (zoom) {
  370. var oldZoom = this.options.minZoom;
  371. this.options.minZoom = zoom;
  372. if (this._loaded && oldZoom !== zoom) {
  373. this.fire('zoomlevelschange');
  374. if (this.getZoom() < this.options.minZoom) {
  375. return this.setZoom(zoom);
  376. }
  377. }
  378. return this;
  379. },
  380. // @method setMaxZoom(zoom: Number): this
  381. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  382. setMaxZoom: function (zoom) {
  383. var oldZoom = this.options.maxZoom;
  384. this.options.maxZoom = zoom;
  385. if (this._loaded && oldZoom !== zoom) {
  386. this.fire('zoomlevelschange');
  387. if (this.getZoom() > this.options.maxZoom) {
  388. return this.setZoom(zoom);
  389. }
  390. }
  391. return this;
  392. },
  393. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  394. // 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.
  395. panInsideBounds: function (bounds, options) {
  396. this._enforcingBounds = true;
  397. var center = this.getCenter(),
  398. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  399. if (!center.equals(newCenter)) {
  400. this.panTo(newCenter, options);
  401. }
  402. this._enforcingBounds = false;
  403. return this;
  404. },
  405. // @method panInside(latlng: LatLng, options?: options): this
  406. // Pans the map the minimum amount to make the `latlng` visible. Use
  407. // `padding`, `paddingTopLeft` and `paddingBottomRight` options to fit
  408. // the display to more restricted bounds, like [`fitBounds`](#map-fitbounds).
  409. // If `latlng` is already within the (optionally padded) display bounds,
  410. // the map will not be panned.
  411. panInside: function (latlng, options) {
  412. options = options || {};
  413. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  414. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  415. pixelCenter = this.project(this.getCenter()),
  416. pixelPoint = this.project(latlng),
  417. pixelBounds = this.getPixelBounds(),
  418. paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]),
  419. paddedSize = paddedBounds.getSize();
  420. if (!paddedBounds.contains(pixelPoint)) {
  421. this._enforcingBounds = true;
  422. var centerOffset = pixelPoint.subtract(paddedBounds.getCenter());
  423. var offset = paddedBounds.extend(pixelPoint).getSize().subtract(paddedSize);
  424. pixelCenter.x += centerOffset.x < 0 ? -offset.x : offset.x;
  425. pixelCenter.y += centerOffset.y < 0 ? -offset.y : offset.y;
  426. this.panTo(this.unproject(pixelCenter), options);
  427. this._enforcingBounds = false;
  428. }
  429. return this;
  430. },
  431. // @method invalidateSize(options: Zoom/pan options): this
  432. // Checks if the map container size changed and updates the map if so —
  433. // call it after you've changed the map size dynamically, also animating
  434. // pan by default. If `options.pan` is `false`, panning will not occur.
  435. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  436. // that it doesn't happen often even if the method is called many
  437. // times in a row.
  438. // @alternative
  439. // @method invalidateSize(animate: Boolean): this
  440. // Checks if the map container size changed and updates the map if so —
  441. // call it after you've changed the map size dynamically, also animating
  442. // pan by default.
  443. invalidateSize: function (options) {
  444. if (!this._loaded) { return this; }
  445. options = Util.extend({
  446. animate: false,
  447. pan: true
  448. }, options === true ? {animate: true} : options);
  449. var oldSize = this.getSize();
  450. this._sizeChanged = true;
  451. this._lastCenter = null;
  452. var newSize = this.getSize(),
  453. oldCenter = oldSize.divideBy(2).round(),
  454. newCenter = newSize.divideBy(2).round(),
  455. offset = oldCenter.subtract(newCenter);
  456. if (!offset.x && !offset.y) { return this; }
  457. if (options.animate && options.pan) {
  458. this.panBy(offset);
  459. } else {
  460. if (options.pan) {
  461. this._rawPanBy(offset);
  462. }
  463. this.fire('move');
  464. if (options.debounceMoveend) {
  465. clearTimeout(this._sizeTimer);
  466. this._sizeTimer = setTimeout(Util.bind(this.fire, this, 'moveend'), 200);
  467. } else {
  468. this.fire('moveend');
  469. }
  470. }
  471. // @section Map state change events
  472. // @event resize: ResizeEvent
  473. // Fired when the map is resized.
  474. return this.fire('resize', {
  475. oldSize: oldSize,
  476. newSize: newSize
  477. });
  478. },
  479. // @section Methods for modifying map state
  480. // @method stop(): this
  481. // Stops the currently running `panTo` or `flyTo` animation, if any.
  482. stop: function () {
  483. this.setZoom(this._limitZoom(this._zoom));
  484. if (!this.options.zoomSnap) {
  485. this.fire('viewreset');
  486. }
  487. return this._stop();
  488. },
  489. // @section Geolocation methods
  490. // @method locate(options?: Locate options): this
  491. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  492. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  493. // and optionally sets the map view to the user's location with respect to
  494. // detection accuracy (or to the world view if geolocation failed).
  495. // Note that, if your page doesn't use HTTPS, this method will fail in
  496. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  497. // See `Locate options` for more details.
  498. locate: function (options) {
  499. options = this._locateOptions = Util.extend({
  500. timeout: 10000,
  501. watch: false
  502. // setView: false
  503. // maxZoom: <Number>
  504. // maximumAge: 0
  505. // enableHighAccuracy: false
  506. }, options);
  507. if (!('geolocation' in navigator)) {
  508. this._handleGeolocationError({
  509. code: 0,
  510. message: 'Geolocation not supported.'
  511. });
  512. return this;
  513. }
  514. var onResponse = Util.bind(this._handleGeolocationResponse, this),
  515. onError = Util.bind(this._handleGeolocationError, this);
  516. if (options.watch) {
  517. this._locationWatchId =
  518. navigator.geolocation.watchPosition(onResponse, onError, options);
  519. } else {
  520. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  521. }
  522. return this;
  523. },
  524. // @method stopLocate(): this
  525. // Stops watching location previously initiated by `map.locate({watch: true})`
  526. // and aborts resetting the map view if map.locate was called with
  527. // `{setView: true}`.
  528. stopLocate: function () {
  529. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  530. navigator.geolocation.clearWatch(this._locationWatchId);
  531. }
  532. if (this._locateOptions) {
  533. this._locateOptions.setView = false;
  534. }
  535. return this;
  536. },
  537. _handleGeolocationError: function (error) {
  538. var c = error.code,
  539. message = error.message ||
  540. (c === 1 ? 'permission denied' :
  541. (c === 2 ? 'position unavailable' : 'timeout'));
  542. if (this._locateOptions.setView && !this._loaded) {
  543. this.fitWorld();
  544. }
  545. // @section Location events
  546. // @event locationerror: ErrorEvent
  547. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  548. this.fire('locationerror', {
  549. code: c,
  550. message: 'Geolocation error: ' + message + '.'
  551. });
  552. },
  553. _handleGeolocationResponse: function (pos) {
  554. var lat = pos.coords.latitude,
  555. lng = pos.coords.longitude,
  556. latlng = new LatLng(lat, lng),
  557. bounds = latlng.toBounds(pos.coords.accuracy * 2),
  558. options = this._locateOptions;
  559. if (options.setView) {
  560. var zoom = this.getBoundsZoom(bounds);
  561. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  562. }
  563. var data = {
  564. latlng: latlng,
  565. bounds: bounds,
  566. timestamp: pos.timestamp
  567. };
  568. for (var i in pos.coords) {
  569. if (typeof pos.coords[i] === 'number') {
  570. data[i] = pos.coords[i];
  571. }
  572. }
  573. // @event locationfound: LocationEvent
  574. // Fired when geolocation (using the [`locate`](#map-locate) method)
  575. // went successfully.
  576. this.fire('locationfound', data);
  577. },
  578. // TODO Appropriate docs section?
  579. // @section Other Methods
  580. // @method addHandler(name: String, HandlerClass: Function): this
  581. // Adds a new `Handler` to the map, given its name and constructor function.
  582. addHandler: function (name, HandlerClass) {
  583. if (!HandlerClass) { return this; }
  584. var handler = this[name] = new HandlerClass(this);
  585. this._handlers.push(handler);
  586. if (this.options[name]) {
  587. handler.enable();
  588. }
  589. return this;
  590. },
  591. // @method remove(): this
  592. // Destroys the map and clears all related event listeners.
  593. remove: function () {
  594. this._initEvents(true);
  595. this.off('moveend', this._panInsideMaxBounds);
  596. if (this._containerId !== this._container._leaflet_id) {
  597. throw new Error('Map container is being reused by another instance');
  598. }
  599. try {
  600. // throws error in IE6-8
  601. delete this._container._leaflet_id;
  602. delete this._containerId;
  603. } catch (e) {
  604. /*eslint-disable */
  605. this._container._leaflet_id = undefined;
  606. /* eslint-enable */
  607. this._containerId = undefined;
  608. }
  609. if (this._locationWatchId !== undefined) {
  610. this.stopLocate();
  611. }
  612. this._stop();
  613. DomUtil.remove(this._mapPane);
  614. if (this._clearControlPos) {
  615. this._clearControlPos();
  616. }
  617. if (this._resizeRequest) {
  618. Util.cancelAnimFrame(this._resizeRequest);
  619. this._resizeRequest = null;
  620. }
  621. this._clearHandlers();
  622. if (this._loaded) {
  623. // @section Map state change events
  624. // @event unload: Event
  625. // Fired when the map is destroyed with [remove](#map-remove) method.
  626. this.fire('unload');
  627. }
  628. var i;
  629. for (i in this._layers) {
  630. this._layers[i].remove();
  631. }
  632. for (i in this._panes) {
  633. DomUtil.remove(this._panes[i]);
  634. }
  635. this._layers = [];
  636. this._panes = [];
  637. delete this._mapPane;
  638. delete this._renderer;
  639. return this;
  640. },
  641. // @section Other Methods
  642. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  643. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  644. // then returns it. The pane is created as a child of `container`, or
  645. // as a child of the main map pane if not set.
  646. createPane: function (name, container) {
  647. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  648. pane = DomUtil.create('div', className, container || this._mapPane);
  649. if (name) {
  650. this._panes[name] = pane;
  651. }
  652. return pane;
  653. },
  654. // @section Methods for Getting Map State
  655. // @method getCenter(): LatLng
  656. // Returns the geographical center of the map view
  657. getCenter: function () {
  658. this._checkIfLoaded();
  659. if (this._lastCenter && !this._moved()) {
  660. return this._lastCenter;
  661. }
  662. return this.layerPointToLatLng(this._getCenterLayerPoint());
  663. },
  664. // @method getZoom(): Number
  665. // Returns the current zoom level of the map view
  666. getZoom: function () {
  667. return this._zoom;
  668. },
  669. // @method getBounds(): LatLngBounds
  670. // Returns the geographical bounds visible in the current map view
  671. getBounds: function () {
  672. var bounds = this.getPixelBounds(),
  673. sw = this.unproject(bounds.getBottomLeft()),
  674. ne = this.unproject(bounds.getTopRight());
  675. return new LatLngBounds(sw, ne);
  676. },
  677. // @method getMinZoom(): Number
  678. // 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.
  679. getMinZoom: function () {
  680. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  681. },
  682. // @method getMaxZoom(): Number
  683. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  684. getMaxZoom: function () {
  685. return this.options.maxZoom === undefined ?
  686. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  687. this.options.maxZoom;
  688. },
  689. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
  690. // Returns the maximum zoom level on which the given bounds fit to the map
  691. // view in its entirety. If `inside` (optional) is set to `true`, the method
  692. // instead returns the minimum zoom level on which the map view fits into
  693. // the given bounds in its entirety.
  694. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  695. bounds = toLatLngBounds(bounds);
  696. padding = toPoint(padding || [0, 0]);
  697. var zoom = this.getZoom() || 0,
  698. min = this.getMinZoom(),
  699. max = this.getMaxZoom(),
  700. nw = bounds.getNorthWest(),
  701. se = bounds.getSouthEast(),
  702. size = this.getSize().subtract(padding),
  703. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  704. snap = Browser.any3d ? this.options.zoomSnap : 1,
  705. scalex = size.x / boundsSize.x,
  706. scaley = size.y / boundsSize.y,
  707. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  708. zoom = this.getScaleZoom(scale, zoom);
  709. if (snap) {
  710. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  711. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  712. }
  713. return Math.max(min, Math.min(max, zoom));
  714. },
  715. // @method getSize(): Point
  716. // Returns the current size of the map container (in pixels).
  717. getSize: function () {
  718. if (!this._size || this._sizeChanged) {
  719. this._size = new Point(
  720. this._container.clientWidth || 0,
  721. this._container.clientHeight || 0);
  722. this._sizeChanged = false;
  723. }
  724. return this._size.clone();
  725. },
  726. // @method getPixelBounds(): Bounds
  727. // Returns the bounds of the current map view in projected pixel
  728. // coordinates (sometimes useful in layer and overlay implementations).
  729. getPixelBounds: function (center, zoom) {
  730. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  731. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  732. },
  733. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  734. // the map pane? "left point of the map layer" can be confusing, specially
  735. // since there can be negative offsets.
  736. // @method getPixelOrigin(): Point
  737. // Returns the projected pixel coordinates of the top left point of
  738. // the map layer (useful in custom layer and overlay implementations).
  739. getPixelOrigin: function () {
  740. this._checkIfLoaded();
  741. return this._pixelOrigin;
  742. },
  743. // @method getPixelWorldBounds(zoom?: Number): Bounds
  744. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  745. // If `zoom` is omitted, the map's current zoom level is used.
  746. getPixelWorldBounds: function (zoom) {
  747. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  748. },
  749. // @section Other Methods
  750. // @method getPane(pane: String|HTMLElement): HTMLElement
  751. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  752. getPane: function (pane) {
  753. return typeof pane === 'string' ? this._panes[pane] : pane;
  754. },
  755. // @method getPanes(): Object
  756. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  757. // the panes as values.
  758. getPanes: function () {
  759. return this._panes;
  760. },
  761. // @method getContainer: HTMLElement
  762. // Returns the HTML element that contains the map.
  763. getContainer: function () {
  764. return this._container;
  765. },
  766. // @section Conversion Methods
  767. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  768. // Returns the scale factor to be applied to a map transition from zoom level
  769. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  770. getZoomScale: function (toZoom, fromZoom) {
  771. // TODO replace with universal implementation after refactoring projections
  772. var crs = this.options.crs;
  773. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  774. return crs.scale(toZoom) / crs.scale(fromZoom);
  775. },
  776. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  777. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  778. // level and everything is scaled by a factor of `scale`. Inverse of
  779. // [`getZoomScale`](#map-getZoomScale).
  780. getScaleZoom: function (scale, fromZoom) {
  781. var crs = this.options.crs;
  782. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  783. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  784. return isNaN(zoom) ? Infinity : zoom;
  785. },
  786. // @method project(latlng: LatLng, zoom: Number): Point
  787. // Projects a geographical coordinate `LatLng` according to the projection
  788. // of the map's CRS, then scales it according to `zoom` and the CRS's
  789. // `Transformation`. The result is pixel coordinate relative to
  790. // the CRS origin.
  791. project: function (latlng, zoom) {
  792. zoom = zoom === undefined ? this._zoom : zoom;
  793. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  794. },
  795. // @method unproject(point: Point, zoom: Number): LatLng
  796. // Inverse of [`project`](#map-project).
  797. unproject: function (point, zoom) {
  798. zoom = zoom === undefined ? this._zoom : zoom;
  799. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  800. },
  801. // @method layerPointToLatLng(point: Point): LatLng
  802. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  803. // returns the corresponding geographical coordinate (for the current zoom level).
  804. layerPointToLatLng: function (point) {
  805. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  806. return this.unproject(projectedPoint);
  807. },
  808. // @method latLngToLayerPoint(latlng: LatLng): Point
  809. // Given a geographical coordinate, returns the corresponding pixel coordinate
  810. // relative to the [origin pixel](#map-getpixelorigin).
  811. latLngToLayerPoint: function (latlng) {
  812. var projectedPoint = this.project(toLatLng(latlng))._round();
  813. return projectedPoint._subtract(this.getPixelOrigin());
  814. },
  815. // @method wrapLatLng(latlng: LatLng): LatLng
  816. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  817. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  818. // CRS's bounds.
  819. // By default this means longitude is wrapped around the dateline so its
  820. // value is between -180 and +180 degrees.
  821. wrapLatLng: function (latlng) {
  822. return this.options.crs.wrapLatLng(toLatLng(latlng));
  823. },
  824. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  825. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  826. // its center is within the CRS's bounds.
  827. // By default this means the center longitude is wrapped around the dateline so its
  828. // value is between -180 and +180 degrees, and the majority of the bounds
  829. // overlaps the CRS's bounds.
  830. wrapLatLngBounds: function (latlng) {
  831. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  832. },
  833. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  834. // Returns the distance between two geographical coordinates according to
  835. // the map's CRS. By default this measures distance in meters.
  836. distance: function (latlng1, latlng2) {
  837. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  838. },
  839. // @method containerPointToLayerPoint(point: Point): Point
  840. // Given a pixel coordinate relative to the map container, returns the corresponding
  841. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  842. containerPointToLayerPoint: function (point) { // (Point)
  843. return toPoint(point).subtract(this._getMapPanePos());
  844. },
  845. // @method layerPointToContainerPoint(point: Point): Point
  846. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  847. // returns the corresponding pixel coordinate relative to the map container.
  848. layerPointToContainerPoint: function (point) { // (Point)
  849. return toPoint(point).add(this._getMapPanePos());
  850. },
  851. // @method containerPointToLatLng(point: Point): LatLng
  852. // Given a pixel coordinate relative to the map container, returns
  853. // the corresponding geographical coordinate (for the current zoom level).
  854. containerPointToLatLng: function (point) {
  855. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  856. return this.layerPointToLatLng(layerPoint);
  857. },
  858. // @method latLngToContainerPoint(latlng: LatLng): Point
  859. // Given a geographical coordinate, returns the corresponding pixel coordinate
  860. // relative to the map container.
  861. latLngToContainerPoint: function (latlng) {
  862. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  863. },
  864. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  865. // Given a MouseEvent object, returns the pixel coordinate relative to the
  866. // map container where the event took place.
  867. mouseEventToContainerPoint: function (e) {
  868. return DomEvent.getMousePosition(e, this._container);
  869. },
  870. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  871. // Given a MouseEvent object, returns the pixel coordinate relative to
  872. // the [origin pixel](#map-getpixelorigin) where the event took place.
  873. mouseEventToLayerPoint: function (e) {
  874. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  875. },
  876. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  877. // Given a MouseEvent object, returns geographical coordinate where the
  878. // event took place.
  879. mouseEventToLatLng: function (e) { // (MouseEvent)
  880. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  881. },
  882. // map initialization methods
  883. _initContainer: function (id) {
  884. var container = this._container = DomUtil.get(id);
  885. if (!container) {
  886. throw new Error('Map container not found.');
  887. } else if (container._leaflet_id) {
  888. throw new Error('Map container is already initialized.');
  889. }
  890. DomEvent.on(container, 'scroll', this._onScroll, this);
  891. this._containerId = Util.stamp(container);
  892. },
  893. _initLayout: function () {
  894. var container = this._container;
  895. this._fadeAnimated = this.options.fadeAnimation && Browser.any3d;
  896. DomUtil.addClass(container, 'leaflet-container' +
  897. (Browser.touch ? ' leaflet-touch' : '') +
  898. (Browser.retina ? ' leaflet-retina' : '') +
  899. (Browser.ielt9 ? ' leaflet-oldie' : '') +
  900. (Browser.safari ? ' leaflet-safari' : '') +
  901. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  902. var position = DomUtil.getStyle(container, 'position');
  903. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  904. container.style.position = 'relative';
  905. }
  906. this._initPanes();
  907. if (this._initControlPos) {
  908. this._initControlPos();
  909. }
  910. },
  911. _initPanes: function () {
  912. var panes = this._panes = {};
  913. this._paneRenderers = {};
  914. // @section
  915. //
  916. // Panes are DOM elements used to control the ordering of layers on the map. You
  917. // can access panes with [`map.getPane`](#map-getpane) or
  918. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  919. // [`map.createPane`](#map-createpane) method.
  920. //
  921. // Every map has the following default panes that differ only in zIndex.
  922. //
  923. // @pane mapPane: HTMLElement = 'auto'
  924. // Pane that contains all other map panes
  925. this._mapPane = this.createPane('mapPane', this._container);
  926. DomUtil.setPosition(this._mapPane, new Point(0, 0));
  927. // @pane tilePane: HTMLElement = 200
  928. // Pane for `GridLayer`s and `TileLayer`s
  929. this.createPane('tilePane');
  930. // @pane overlayPane: HTMLElement = 400
  931. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  932. this.createPane('overlayPane');
  933. // @pane shadowPane: HTMLElement = 500
  934. // Pane for overlay shadows (e.g. `Marker` shadows)
  935. this.createPane('shadowPane');
  936. // @pane markerPane: HTMLElement = 600
  937. // Pane for `Icon`s of `Marker`s
  938. this.createPane('markerPane');
  939. // @pane tooltipPane: HTMLElement = 650
  940. // Pane for `Tooltip`s.
  941. this.createPane('tooltipPane');
  942. // @pane popupPane: HTMLElement = 700
  943. // Pane for `Popup`s.
  944. this.createPane('popupPane');
  945. if (!this.options.markerZoomAnimation) {
  946. DomUtil.addClass(panes.markerPane, 'leaflet-zoom-hide');
  947. DomUtil.addClass(panes.shadowPane, 'leaflet-zoom-hide');
  948. }
  949. },
  950. // private methods that modify map state
  951. // @section Map state change events
  952. _resetView: function (center, zoom) {
  953. DomUtil.setPosition(this._mapPane, new Point(0, 0));
  954. var loading = !this._loaded;
  955. this._loaded = true;
  956. zoom = this._limitZoom(zoom);
  957. this.fire('viewprereset');
  958. var zoomChanged = this._zoom !== zoom;
  959. this
  960. ._moveStart(zoomChanged, false)
  961. ._move(center, zoom)
  962. ._moveEnd(zoomChanged);
  963. // @event viewreset: Event
  964. // Fired when the map needs to redraw its content (this usually happens
  965. // on map zoom or load). Very useful for creating custom overlays.
  966. this.fire('viewreset');
  967. // @event load: Event
  968. // Fired when the map is initialized (when its center and zoom are set
  969. // for the first time).
  970. if (loading) {
  971. this.fire('load');
  972. }
  973. },
  974. _moveStart: function (zoomChanged, noMoveStart) {
  975. // @event zoomstart: Event
  976. // Fired when the map zoom is about to change (e.g. before zoom animation).
  977. // @event movestart: Event
  978. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  979. if (zoomChanged) {
  980. this.fire('zoomstart');
  981. }
  982. if (!noMoveStart) {
  983. this.fire('movestart');
  984. }
  985. return this;
  986. },
  987. _move: function (center, zoom, data) {
  988. if (zoom === undefined) {
  989. zoom = this._zoom;
  990. }
  991. var zoomChanged = this._zoom !== zoom;
  992. this._zoom = zoom;
  993. this._lastCenter = center;
  994. this._pixelOrigin = this._getNewPixelOrigin(center);
  995. // @event zoom: Event
  996. // Fired repeatedly during any change in zoom level, including zoom
  997. // and fly animations.
  998. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  999. this.fire('zoom', data);
  1000. }
  1001. // @event move: Event
  1002. // Fired repeatedly during any movement of the map, including pan and
  1003. // fly animations.
  1004. return this.fire('move', data);
  1005. },
  1006. _moveEnd: function (zoomChanged) {
  1007. // @event zoomend: Event
  1008. // Fired when the map has changed, after any animations.
  1009. if (zoomChanged) {
  1010. this.fire('zoomend');
  1011. }
  1012. // @event moveend: Event
  1013. // Fired when the center of the map stops changing (e.g. user stopped
  1014. // dragging the map).
  1015. return this.fire('moveend');
  1016. },
  1017. _stop: function () {
  1018. Util.cancelAnimFrame(this._flyToFrame);
  1019. if (this._panAnim) {
  1020. this._panAnim.stop();
  1021. }
  1022. return this;
  1023. },
  1024. _rawPanBy: function (offset) {
  1025. DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  1026. },
  1027. _getZoomSpan: function () {
  1028. return this.getMaxZoom() - this.getMinZoom();
  1029. },
  1030. _panInsideMaxBounds: function () {
  1031. if (!this._enforcingBounds) {
  1032. this.panInsideBounds(this.options.maxBounds);
  1033. }
  1034. },
  1035. _checkIfLoaded: function () {
  1036. if (!this._loaded) {
  1037. throw new Error('Set map center and zoom first.');
  1038. }
  1039. },
  1040. // DOM event handling
  1041. // @section Interaction events
  1042. _initEvents: function (remove) {
  1043. this._targets = {};
  1044. this._targets[Util.stamp(this._container)] = this;
  1045. var onOff = remove ? DomEvent.off : DomEvent.on;
  1046. // @event click: MouseEvent
  1047. // Fired when the user clicks (or taps) the map.
  1048. // @event dblclick: MouseEvent
  1049. // Fired when the user double-clicks (or double-taps) the map.
  1050. // @event mousedown: MouseEvent
  1051. // Fired when the user pushes the mouse button on the map.
  1052. // @event mouseup: MouseEvent
  1053. // Fired when the user releases the mouse button on the map.
  1054. // @event mouseover: MouseEvent
  1055. // Fired when the mouse enters the map.
  1056. // @event mouseout: MouseEvent
  1057. // Fired when the mouse leaves the map.
  1058. // @event mousemove: MouseEvent
  1059. // Fired while the mouse moves over the map.
  1060. // @event contextmenu: MouseEvent
  1061. // Fired when the user pushes the right mouse button on the map, prevents
  1062. // default browser context menu from showing if there are listeners on
  1063. // this event. Also fired on mobile when the user holds a single touch
  1064. // for a second (also called long press).
  1065. // @event keypress: KeyboardEvent
  1066. // Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
  1067. // @event keydown: KeyboardEvent
  1068. // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
  1069. // the `keydown` event is fired for keys that produce a character value and for keys
  1070. // that do not produce a character value.
  1071. // @event keyup: KeyboardEvent
  1072. // Fired when the user releases a key from the keyboard while the map is focused.
  1073. onOff(this._container, 'click dblclick mousedown mouseup ' +
  1074. 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
  1075. if (this.options.trackResize) {
  1076. onOff(window, 'resize', this._onResize, this);
  1077. }
  1078. if (Browser.any3d && this.options.transform3DLimit) {
  1079. (remove ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  1080. }
  1081. },
  1082. _onResize: function () {
  1083. Util.cancelAnimFrame(this._resizeRequest);
  1084. this._resizeRequest = Util.requestAnimFrame(
  1085. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  1086. },
  1087. _onScroll: function () {
  1088. this._container.scrollTop = 0;
  1089. this._container.scrollLeft = 0;
  1090. },
  1091. _onMoveEnd: function () {
  1092. var pos = this._getMapPanePos();
  1093. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  1094. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  1095. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  1096. this._resetView(this.getCenter(), this.getZoom());
  1097. }
  1098. },
  1099. _findEventTargets: function (e, type) {
  1100. var targets = [],
  1101. target,
  1102. isHover = type === 'mouseout' || type === 'mouseover',
  1103. src = e.target || e.srcElement,
  1104. dragging = false;
  1105. while (src) {
  1106. target = this._targets[Util.stamp(src)];
  1107. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  1108. // Prevent firing click after you just dragged an object.
  1109. dragging = true;
  1110. break;
  1111. }
  1112. if (target && target.listens(type, true)) {
  1113. if (isHover && !DomEvent.isExternalTarget(src, e)) { break; }
  1114. targets.push(target);
  1115. if (isHover) { break; }
  1116. }
  1117. if (src === this._container) { break; }
  1118. src = src.parentNode;
  1119. }
  1120. if (!targets.length && !dragging && !isHover && DomEvent.isExternalTarget(src, e)) {
  1121. targets = [this];
  1122. }
  1123. return targets;
  1124. },
  1125. _handleDOMEvent: function (e) {
  1126. if (!this._loaded || DomEvent.skipped(e)) { return; }
  1127. var type = e.type;
  1128. if (type === 'mousedown') {
  1129. // prevents outline when clicking on keyboard-focusable element
  1130. DomUtil.preventOutline(e.target || e.srcElement);
  1131. }
  1132. this._fireDOMEvent(e, type);
  1133. },
  1134. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  1135. _fireDOMEvent: function (e, type, targets) {
  1136. if (e.type === 'click') {
  1137. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  1138. // @event preclick: MouseEvent
  1139. // Fired before mouse click on the map (sometimes useful when you
  1140. // want something to happen on click before any existing click
  1141. // handlers start running).
  1142. var synth = Util.extend({}, e);
  1143. synth.type = 'preclick';
  1144. this._fireDOMEvent(synth, synth.type, targets);
  1145. }
  1146. if (e._stopped) { return; }
  1147. // Find the layer the event is propagating from and its parents.
  1148. targets = (targets || []).concat(this._findEventTargets(e, type));
  1149. if (!targets.length) { return; }
  1150. var target = targets[0];
  1151. if (type === 'contextmenu' && target.listens(type, true)) {
  1152. DomEvent.preventDefault(e);
  1153. }
  1154. var data = {
  1155. originalEvent: e
  1156. };
  1157. if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
  1158. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  1159. data.containerPoint = isMarker ?
  1160. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  1161. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  1162. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  1163. }
  1164. for (var i = 0; i < targets.length; i++) {
  1165. targets[i].fire(type, data, true);
  1166. if (data.originalEvent._stopped ||
  1167. (targets[i].options.bubblingMouseEvents === false && Util.indexOf(this._mouseEvents, type) !== -1)) { return; }
  1168. }
  1169. },
  1170. _draggableMoved: function (obj) {
  1171. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  1172. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  1173. },
  1174. _clearHandlers: function () {
  1175. for (var i = 0, len = this._handlers.length; i < len; i++) {
  1176. this._handlers[i].disable();
  1177. }
  1178. },
  1179. // @section Other Methods
  1180. // @method whenReady(fn: Function, context?: Object): this
  1181. // Runs the given function `fn` when the map gets initialized with
  1182. // a view (center and zoom) and at least one layer, or immediately
  1183. // if it's already initialized, optionally passing a function context.
  1184. whenReady: function (callback, context) {
  1185. if (this._loaded) {
  1186. callback.call(context || this, {target: this});
  1187. } else {
  1188. this.on('load', callback, context);
  1189. }
  1190. return this;
  1191. },
  1192. // private methods for getting map state
  1193. _getMapPanePos: function () {
  1194. return DomUtil.getPosition(this._mapPane) || new Point(0, 0);
  1195. },
  1196. _moved: function () {
  1197. var pos = this._getMapPanePos();
  1198. return pos && !pos.equals([0, 0]);
  1199. },
  1200. _getTopLeftPoint: function (center, zoom) {
  1201. var pixelOrigin = center && zoom !== undefined ?
  1202. this._getNewPixelOrigin(center, zoom) :
  1203. this.getPixelOrigin();
  1204. return pixelOrigin.subtract(this._getMapPanePos());
  1205. },
  1206. _getNewPixelOrigin: function (center, zoom) {
  1207. var viewHalf = this.getSize()._divideBy(2);
  1208. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  1209. },
  1210. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  1211. var topLeft = this._getNewPixelOrigin(center, zoom);
  1212. return this.project(latlng, zoom)._subtract(topLeft);
  1213. },
  1214. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  1215. var topLeft = this._getNewPixelOrigin(center, zoom);
  1216. return toBounds([
  1217. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  1218. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  1219. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  1220. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  1221. ]);
  1222. },
  1223. // layer point of the current center
  1224. _getCenterLayerPoint: function () {
  1225. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  1226. },
  1227. // offset of the specified place to the current center in pixels
  1228. _getCenterOffset: function (latlng) {
  1229. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  1230. },
  1231. // adjust center for view to get inside bounds
  1232. _limitCenter: function (center, zoom, bounds) {
  1233. if (!bounds) { return center; }
  1234. var centerPoint = this.project(center, zoom),
  1235. viewHalf = this.getSize().divideBy(2),
  1236. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  1237. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  1238. // If offset is less than a pixel, ignore.
  1239. // This prevents unstable projections from getting into
  1240. // an infinite loop of tiny offsets.
  1241. if (offset.round().equals([0, 0])) {
  1242. return center;
  1243. }
  1244. return this.unproject(centerPoint.add(offset), zoom);
  1245. },
  1246. // adjust offset for view to get inside bounds
  1247. _limitOffset: function (offset, bounds) {
  1248. if (!bounds) { return offset; }
  1249. var viewBounds = this.getPixelBounds(),
  1250. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  1251. return offset.add(this._getBoundsOffset(newBounds, bounds));
  1252. },
  1253. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  1254. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  1255. var projectedMaxBounds = toBounds(
  1256. this.project(maxBounds.getNorthEast(), zoom),
  1257. this.project(maxBounds.getSouthWest(), zoom)
  1258. ),
  1259. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  1260. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  1261. dx = this._rebound(minOffset.x, -maxOffset.x),
  1262. dy = this._rebound(minOffset.y, -maxOffset.y);
  1263. return new Point(dx, dy);
  1264. },
  1265. _rebound: function (left, right) {
  1266. return left + right > 0 ?
  1267. Math.round(left - right) / 2 :
  1268. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  1269. },
  1270. _limitZoom: function (zoom) {
  1271. var min = this.getMinZoom(),
  1272. max = this.getMaxZoom(),
  1273. snap = Browser.any3d ? this.options.zoomSnap : 1;
  1274. if (snap) {
  1275. zoom = Math.round(zoom / snap) * snap;
  1276. }
  1277. return Math.max(min, Math.min(max, zoom));
  1278. },
  1279. _onPanTransitionStep: function () {
  1280. this.fire('move');
  1281. },
  1282. _onPanTransitionEnd: function () {
  1283. DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
  1284. this.fire('moveend');
  1285. },
  1286. _tryAnimatedPan: function (center, options) {
  1287. // difference between the new and current centers in pixels
  1288. var offset = this._getCenterOffset(center)._trunc();
  1289. // don't animate too far unless animate: true specified in options
  1290. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  1291. this.panBy(offset, options);
  1292. return true;
  1293. },
  1294. _createAnimProxy: function () {
  1295. var proxy = this._proxy = DomUtil.create('div', 'leaflet-proxy leaflet-zoom-animated');
  1296. this._panes.mapPane.appendChild(proxy);
  1297. this.on('zoomanim', function (e) {
  1298. var prop = DomUtil.TRANSFORM,
  1299. transform = this._proxy.style[prop];
  1300. DomUtil.setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  1301. // workaround for case when transform is the same and so transitionend event is not fired
  1302. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  1303. this._onZoomTransitionEnd();
  1304. }
  1305. }, this);
  1306. this.on('load moveend', this._animMoveEnd, this);
  1307. this._on('unload', this._destroyAnimProxy, this);
  1308. },
  1309. _destroyAnimProxy: function () {
  1310. DomUtil.remove(this._proxy);
  1311. this.off('load moveend', this._animMoveEnd, this);
  1312. delete this._proxy;
  1313. },
  1314. _animMoveEnd: function () {
  1315. var c = this.getCenter(),
  1316. z = this.getZoom();
  1317. DomUtil.setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  1318. },
  1319. _catchTransitionEnd: function (e) {
  1320. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  1321. this._onZoomTransitionEnd();
  1322. }
  1323. },
  1324. _nothingToAnimate: function () {
  1325. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  1326. },
  1327. _tryAnimatedZoom: function (center, zoom, options) {
  1328. if (this._animatingZoom) { return true; }
  1329. options = options || {};
  1330. // don't animate if disabled, not supported or zoom difference is too large
  1331. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  1332. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  1333. // offset is the pixel coords of the zoom origin relative to the current center
  1334. var scale = this.getZoomScale(zoom),
  1335. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  1336. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  1337. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  1338. Util.requestAnimFrame(function () {
  1339. this
  1340. ._moveStart(true, false)
  1341. ._animateZoom(center, zoom, true);
  1342. }, this);
  1343. return true;
  1344. },
  1345. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  1346. if (!this._mapPane) { return; }
  1347. if (startAnim) {
  1348. this._animatingZoom = true;
  1349. // remember what center/zoom to set after animation
  1350. this._animateToCenter = center;
  1351. this._animateToZoom = zoom;
  1352. DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
  1353. }
  1354. // @section Other Events
  1355. // @event zoomanim: ZoomAnimEvent
  1356. // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
  1357. this.fire('zoomanim', {
  1358. center: center,
  1359. zoom: zoom,
  1360. noUpdate: noUpdate
  1361. });
  1362. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  1363. setTimeout(Util.bind(this._onZoomTransitionEnd, this), 250);
  1364. },
  1365. _onZoomTransitionEnd: function () {
  1366. if (!this._animatingZoom) { return; }
  1367. if (this._mapPane) {
  1368. DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
  1369. }
  1370. this._animatingZoom = false;
  1371. this._move(this._animateToCenter, this._animateToZoom);
  1372. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  1373. Util.requestAnimFrame(function () {
  1374. this._moveEnd(true);
  1375. }, this);
  1376. }
  1377. });
  1378. // @section
  1379. // @factory L.map(id: String, options?: Map options)
  1380. // Instantiates a map object given the DOM ID of a `<div>` element
  1381. // and optionally an object literal with `Map options`.
  1382. //
  1383. // @alternative
  1384. // @factory L.map(el: HTMLElement, options?: Map options)
  1385. // Instantiates a map object given an instance of a `<div>` HTML element
  1386. // and optionally an object literal with `Map options`.
  1387. export function createMap(id, options) {
  1388. return new Map(id, options);
  1389. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/234975
推荐阅读
相关标签
  

闽ICP备14008679号