Map.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  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 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, options.pan && options.pan.noMoveStart);
  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 (this.listens('moveend', this._panInsideMaxBounds)) {
  356. this.off('moveend', this._panInsideMaxBounds);
  357. }
  358. if (!bounds.isValid()) {
  359. this.options.maxBounds = null;
  360. return this;
  361. }
  362. this.options.maxBounds = bounds;
  363. if (this._loaded) {
  364. this._panInsideMaxBounds();
  365. }
  366. return this.on('moveend', this._panInsideMaxBounds);
  367. },
  368. // @method setMinZoom(zoom: Number): this
  369. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  370. setMinZoom: function (zoom) {
  371. var oldZoom = this.options.minZoom;
  372. this.options.minZoom = zoom;
  373. if (this._loaded && oldZoom !== zoom) {
  374. this.fire('zoomlevelschange');
  375. if (this.getZoom() < this.options.minZoom) {
  376. return this.setZoom(zoom);
  377. }
  378. }
  379. return this;
  380. },
  381. // @method setMaxZoom(zoom: Number): this
  382. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  383. setMaxZoom: function (zoom) {
  384. var oldZoom = this.options.maxZoom;
  385. this.options.maxZoom = zoom;
  386. if (this._loaded && oldZoom !== zoom) {
  387. this.fire('zoomlevelschange');
  388. if (this.getZoom() > this.options.maxZoom) {
  389. return this.setZoom(zoom);
  390. }
  391. }
  392. return this;
  393. },
  394. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  395. // 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.
  396. panInsideBounds: function (bounds, options) {
  397. this._enforcingBounds = true;
  398. var center = this.getCenter(),
  399. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  400. if (!center.equals(newCenter)) {
  401. this.panTo(newCenter, options);
  402. }
  403. this._enforcingBounds = false;
  404. return this;
  405. },
  406. // @method panInside(latlng: LatLng, options?: padding options): this
  407. // Pans the map the minimum amount to make the `latlng` visible. Use
  408. // padding options to fit the display to more restricted bounds.
  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. if (!this._container._leaflet_id) { return; }
  539. var c = error.code,
  540. message = error.message ||
  541. (c === 1 ? 'permission denied' :
  542. (c === 2 ? 'position unavailable' : 'timeout'));
  543. if (this._locateOptions.setView && !this._loaded) {
  544. this.fitWorld();
  545. }
  546. // @section Location events
  547. // @event locationerror: ErrorEvent
  548. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  549. this.fire('locationerror', {
  550. code: c,
  551. message: 'Geolocation error: ' + message + '.'
  552. });
  553. },
  554. _handleGeolocationResponse: function (pos) {
  555. if (!this._container._leaflet_id) { return; }
  556. var lat = pos.coords.latitude,
  557. lng = pos.coords.longitude,
  558. latlng = new LatLng(lat, lng),
  559. bounds = latlng.toBounds(pos.coords.accuracy * 2),
  560. options = this._locateOptions;
  561. if (options.setView) {
  562. var zoom = this.getBoundsZoom(bounds);
  563. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  564. }
  565. var data = {
  566. latlng: latlng,
  567. bounds: bounds,
  568. timestamp: pos.timestamp
  569. };
  570. for (var i in pos.coords) {
  571. if (typeof pos.coords[i] === 'number') {
  572. data[i] = pos.coords[i];
  573. }
  574. }
  575. // @event locationfound: LocationEvent
  576. // Fired when geolocation (using the [`locate`](#map-locate) method)
  577. // went successfully.
  578. this.fire('locationfound', data);
  579. },
  580. // TODO Appropriate docs section?
  581. // @section Other Methods
  582. // @method addHandler(name: String, HandlerClass: Function): this
  583. // Adds a new `Handler` to the map, given its name and constructor function.
  584. addHandler: function (name, HandlerClass) {
  585. if (!HandlerClass) { return this; }
  586. var handler = this[name] = new HandlerClass(this);
  587. this._handlers.push(handler);
  588. if (this.options[name]) {
  589. handler.enable();
  590. }
  591. return this;
  592. },
  593. // @method remove(): this
  594. // Destroys the map and clears all related event listeners.
  595. remove: function () {
  596. this._initEvents(true);
  597. if (this.options.maxBounds) { this.off('moveend', this._panInsideMaxBounds); }
  598. if (this._containerId !== this._container._leaflet_id) {
  599. throw new Error('Map container is being reused by another instance');
  600. }
  601. try {
  602. // throws error in IE6-8
  603. delete this._container._leaflet_id;
  604. delete this._containerId;
  605. } catch (e) {
  606. /*eslint-disable */
  607. this._container._leaflet_id = undefined;
  608. /* eslint-enable */
  609. this._containerId = undefined;
  610. }
  611. if (this._locationWatchId !== undefined) {
  612. this.stopLocate();
  613. }
  614. this._stop();
  615. DomUtil.remove(this._mapPane);
  616. if (this._clearControlPos) {
  617. this._clearControlPos();
  618. }
  619. if (this._resizeRequest) {
  620. Util.cancelAnimFrame(this._resizeRequest);
  621. this._resizeRequest = null;
  622. }
  623. this._clearHandlers();
  624. if (this._loaded) {
  625. // @section Map state change events
  626. // @event unload: Event
  627. // Fired when the map is destroyed with [remove](#map-remove) method.
  628. this.fire('unload');
  629. }
  630. var i;
  631. for (i in this._layers) {
  632. this._layers[i].remove();
  633. }
  634. for (i in this._panes) {
  635. DomUtil.remove(this._panes[i]);
  636. }
  637. this._layers = [];
  638. this._panes = [];
  639. delete this._mapPane;
  640. delete this._renderer;
  641. return this;
  642. },
  643. // @section Other Methods
  644. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  645. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  646. // then returns it. The pane is created as a child of `container`, or
  647. // as a child of the main map pane if not set.
  648. createPane: function (name, container) {
  649. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  650. pane = DomUtil.create('div', className, container || this._mapPane);
  651. if (name) {
  652. this._panes[name] = pane;
  653. }
  654. return pane;
  655. },
  656. // @section Methods for Getting Map State
  657. // @method getCenter(): LatLng
  658. // Returns the geographical center of the map view
  659. getCenter: function () {
  660. this._checkIfLoaded();
  661. if (this._lastCenter && !this._moved()) {
  662. return this._lastCenter.clone();
  663. }
  664. return this.layerPointToLatLng(this._getCenterLayerPoint());
  665. },
  666. // @method getZoom(): Number
  667. // Returns the current zoom level of the map view
  668. getZoom: function () {
  669. return this._zoom;
  670. },
  671. // @method getBounds(): LatLngBounds
  672. // Returns the geographical bounds visible in the current map view
  673. getBounds: function () {
  674. var bounds = this.getPixelBounds(),
  675. sw = this.unproject(bounds.getBottomLeft()),
  676. ne = this.unproject(bounds.getTopRight());
  677. return new LatLngBounds(sw, ne);
  678. },
  679. // @method getMinZoom(): Number
  680. // 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.
  681. getMinZoom: function () {
  682. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  683. },
  684. // @method getMaxZoom(): Number
  685. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  686. getMaxZoom: function () {
  687. return this.options.maxZoom === undefined ?
  688. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  689. this.options.maxZoom;
  690. },
  691. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
  692. // Returns the maximum zoom level on which the given bounds fit to the map
  693. // view in its entirety. If `inside` (optional) is set to `true`, the method
  694. // instead returns the minimum zoom level on which the map view fits into
  695. // the given bounds in its entirety.
  696. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  697. bounds = toLatLngBounds(bounds);
  698. padding = toPoint(padding || [0, 0]);
  699. var zoom = this.getZoom() || 0,
  700. min = this.getMinZoom(),
  701. max = this.getMaxZoom(),
  702. nw = bounds.getNorthWest(),
  703. se = bounds.getSouthEast(),
  704. size = this.getSize().subtract(padding),
  705. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  706. snap = Browser.any3d ? this.options.zoomSnap : 1,
  707. scalex = size.x / boundsSize.x,
  708. scaley = size.y / boundsSize.y,
  709. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  710. zoom = this.getScaleZoom(scale, zoom);
  711. if (snap) {
  712. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  713. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  714. }
  715. return Math.max(min, Math.min(max, zoom));
  716. },
  717. // @method getSize(): Point
  718. // Returns the current size of the map container (in pixels).
  719. getSize: function () {
  720. if (!this._size || this._sizeChanged) {
  721. this._size = new Point(
  722. this._container.clientWidth || 0,
  723. this._container.clientHeight || 0);
  724. this._sizeChanged = false;
  725. }
  726. return this._size.clone();
  727. },
  728. // @method getPixelBounds(): Bounds
  729. // Returns the bounds of the current map view in projected pixel
  730. // coordinates (sometimes useful in layer and overlay implementations).
  731. getPixelBounds: function (center, zoom) {
  732. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  733. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  734. },
  735. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  736. // the map pane? "left point of the map layer" can be confusing, specially
  737. // since there can be negative offsets.
  738. // @method getPixelOrigin(): Point
  739. // Returns the projected pixel coordinates of the top left point of
  740. // the map layer (useful in custom layer and overlay implementations).
  741. getPixelOrigin: function () {
  742. this._checkIfLoaded();
  743. return this._pixelOrigin;
  744. },
  745. // @method getPixelWorldBounds(zoom?: Number): Bounds
  746. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  747. // If `zoom` is omitted, the map's current zoom level is used.
  748. getPixelWorldBounds: function (zoom) {
  749. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  750. },
  751. // @section Other Methods
  752. // @method getPane(pane: String|HTMLElement): HTMLElement
  753. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  754. getPane: function (pane) {
  755. return typeof pane === 'string' ? this._panes[pane] : pane;
  756. },
  757. // @method getPanes(): Object
  758. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  759. // the panes as values.
  760. getPanes: function () {
  761. return this._panes;
  762. },
  763. // @method getContainer: HTMLElement
  764. // Returns the HTML element that contains the map.
  765. getContainer: function () {
  766. return this._container;
  767. },
  768. // @section Conversion Methods
  769. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  770. // Returns the scale factor to be applied to a map transition from zoom level
  771. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  772. getZoomScale: function (toZoom, fromZoom) {
  773. // TODO replace with universal implementation after refactoring projections
  774. var crs = this.options.crs;
  775. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  776. return crs.scale(toZoom) / crs.scale(fromZoom);
  777. },
  778. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  779. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  780. // level and everything is scaled by a factor of `scale`. Inverse of
  781. // [`getZoomScale`](#map-getZoomScale).
  782. getScaleZoom: function (scale, fromZoom) {
  783. var crs = this.options.crs;
  784. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  785. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  786. return isNaN(zoom) ? Infinity : zoom;
  787. },
  788. // @method project(latlng: LatLng, zoom: Number): Point
  789. // Projects a geographical coordinate `LatLng` according to the projection
  790. // of the map's CRS, then scales it according to `zoom` and the CRS's
  791. // `Transformation`. The result is pixel coordinate relative to
  792. // the CRS origin.
  793. project: function (latlng, zoom) {
  794. zoom = zoom === undefined ? this._zoom : zoom;
  795. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  796. },
  797. // @method unproject(point: Point, zoom: Number): LatLng
  798. // Inverse of [`project`](#map-project).
  799. unproject: function (point, zoom) {
  800. zoom = zoom === undefined ? this._zoom : zoom;
  801. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  802. },
  803. // @method layerPointToLatLng(point: Point): LatLng
  804. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  805. // returns the corresponding geographical coordinate (for the current zoom level).
  806. layerPointToLatLng: function (point) {
  807. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  808. return this.unproject(projectedPoint);
  809. },
  810. // @method latLngToLayerPoint(latlng: LatLng): Point
  811. // Given a geographical coordinate, returns the corresponding pixel coordinate
  812. // relative to the [origin pixel](#map-getpixelorigin).
  813. latLngToLayerPoint: function (latlng) {
  814. var projectedPoint = this.project(toLatLng(latlng))._round();
  815. return projectedPoint._subtract(this.getPixelOrigin());
  816. },
  817. // @method wrapLatLng(latlng: LatLng): LatLng
  818. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  819. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  820. // CRS's bounds.
  821. // By default this means longitude is wrapped around the dateline so its
  822. // value is between -180 and +180 degrees.
  823. wrapLatLng: function (latlng) {
  824. return this.options.crs.wrapLatLng(toLatLng(latlng));
  825. },
  826. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  827. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  828. // its center is within the CRS's bounds.
  829. // By default this means the center longitude is wrapped around the dateline so its
  830. // value is between -180 and +180 degrees, and the majority of the bounds
  831. // overlaps the CRS's bounds.
  832. wrapLatLngBounds: function (latlng) {
  833. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  834. },
  835. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  836. // Returns the distance between two geographical coordinates according to
  837. // the map's CRS. By default this measures distance in meters.
  838. distance: function (latlng1, latlng2) {
  839. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  840. },
  841. // @method containerPointToLayerPoint(point: Point): Point
  842. // Given a pixel coordinate relative to the map container, returns the corresponding
  843. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  844. containerPointToLayerPoint: function (point) { // (Point)
  845. return toPoint(point).subtract(this._getMapPanePos());
  846. },
  847. // @method layerPointToContainerPoint(point: Point): Point
  848. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  849. // returns the corresponding pixel coordinate relative to the map container.
  850. layerPointToContainerPoint: function (point) { // (Point)
  851. return toPoint(point).add(this._getMapPanePos());
  852. },
  853. // @method containerPointToLatLng(point: Point): LatLng
  854. // Given a pixel coordinate relative to the map container, returns
  855. // the corresponding geographical coordinate (for the current zoom level).
  856. containerPointToLatLng: function (point) {
  857. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  858. return this.layerPointToLatLng(layerPoint);
  859. },
  860. // @method latLngToContainerPoint(latlng: LatLng): Point
  861. // Given a geographical coordinate, returns the corresponding pixel coordinate
  862. // relative to the map container.
  863. latLngToContainerPoint: function (latlng) {
  864. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  865. },
  866. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  867. // Given a MouseEvent object, returns the pixel coordinate relative to the
  868. // map container where the event took place.
  869. mouseEventToContainerPoint: function (e) {
  870. return DomEvent.getMousePosition(e, this._container);
  871. },
  872. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  873. // Given a MouseEvent object, returns the pixel coordinate relative to
  874. // the [origin pixel](#map-getpixelorigin) where the event took place.
  875. mouseEventToLayerPoint: function (e) {
  876. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  877. },
  878. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  879. // Given a MouseEvent object, returns geographical coordinate where the
  880. // event took place.
  881. mouseEventToLatLng: function (e) { // (MouseEvent)
  882. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  883. },
  884. // map initialization methods
  885. _initContainer: function (id) {
  886. var container = this._container = DomUtil.get(id);
  887. if (!container) {
  888. throw new Error('Map container not found.');
  889. } else if (container._leaflet_id) {
  890. throw new Error('Map container is already initialized.');
  891. }
  892. DomEvent.on(container, 'scroll', this._onScroll, this);
  893. this._containerId = Util.stamp(container);
  894. },
  895. _initLayout: function () {
  896. var container = this._container;
  897. this._fadeAnimated = this.options.fadeAnimation && Browser.any3d;
  898. DomUtil.addClass(container, 'leaflet-container' +
  899. (Browser.touch ? ' leaflet-touch' : '') +
  900. (Browser.retina ? ' leaflet-retina' : '') +
  901. (Browser.ielt9 ? ' leaflet-oldie' : '') +
  902. (Browser.safari ? ' leaflet-safari' : '') +
  903. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  904. var position = DomUtil.getStyle(container, 'position');
  905. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed' && position !== 'sticky') {
  906. container.style.position = 'relative';
  907. }
  908. this._initPanes();
  909. if (this._initControlPos) {
  910. this._initControlPos();
  911. }
  912. },
  913. _initPanes: function () {
  914. var panes = this._panes = {};
  915. this._paneRenderers = {};
  916. // @section
  917. //
  918. // Panes are DOM elements used to control the ordering of layers on the map. You
  919. // can access panes with [`map.getPane`](#map-getpane) or
  920. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  921. // [`map.createPane`](#map-createpane) method.
  922. //
  923. // Every map has the following default panes that differ only in zIndex.
  924. //
  925. // @pane mapPane: HTMLElement = 'auto'
  926. // Pane that contains all other map panes
  927. this._mapPane = this.createPane('mapPane', this._container);
  928. DomUtil.setPosition(this._mapPane, new Point(0, 0));
  929. // @pane tilePane: HTMLElement = 200
  930. // Pane for `GridLayer`s and `TileLayer`s
  931. this.createPane('tilePane');
  932. // @pane overlayPane: HTMLElement = 400
  933. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  934. this.createPane('overlayPane');
  935. // @pane shadowPane: HTMLElement = 500
  936. // Pane for overlay shadows (e.g. `Marker` shadows)
  937. this.createPane('shadowPane');
  938. // @pane markerPane: HTMLElement = 600
  939. // Pane for `Icon`s of `Marker`s
  940. this.createPane('markerPane');
  941. // @pane tooltipPane: HTMLElement = 650
  942. // Pane for `Tooltip`s.
  943. this.createPane('tooltipPane');
  944. // @pane popupPane: HTMLElement = 700
  945. // Pane for `Popup`s.
  946. this.createPane('popupPane');
  947. if (!this.options.markerZoomAnimation) {
  948. DomUtil.addClass(panes.markerPane, 'leaflet-zoom-hide');
  949. DomUtil.addClass(panes.shadowPane, 'leaflet-zoom-hide');
  950. }
  951. },
  952. // private methods that modify map state
  953. // @section Map state change events
  954. _resetView: function (center, zoom, noMoveStart) {
  955. DomUtil.setPosition(this._mapPane, new Point(0, 0));
  956. var loading = !this._loaded;
  957. this._loaded = true;
  958. zoom = this._limitZoom(zoom);
  959. this.fire('viewprereset');
  960. var zoomChanged = this._zoom !== zoom;
  961. this
  962. ._moveStart(zoomChanged, noMoveStart)
  963. ._move(center, zoom)
  964. ._moveEnd(zoomChanged);
  965. // @event viewreset: Event
  966. // Fired when the map needs to redraw its content (this usually happens
  967. // on map zoom or load). Very useful for creating custom overlays.
  968. this.fire('viewreset');
  969. // @event load: Event
  970. // Fired when the map is initialized (when its center and zoom are set
  971. // for the first time).
  972. if (loading) {
  973. this.fire('load');
  974. }
  975. },
  976. _moveStart: function (zoomChanged, noMoveStart) {
  977. // @event zoomstart: Event
  978. // Fired when the map zoom is about to change (e.g. before zoom animation).
  979. // @event movestart: Event
  980. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  981. if (zoomChanged) {
  982. this.fire('zoomstart');
  983. }
  984. if (!noMoveStart) {
  985. this.fire('movestart');
  986. }
  987. return this;
  988. },
  989. _move: function (center, zoom, data, supressEvent) {
  990. if (zoom === undefined) {
  991. zoom = this._zoom;
  992. }
  993. var zoomChanged = this._zoom !== zoom;
  994. this._zoom = zoom;
  995. this._lastCenter = center;
  996. this._pixelOrigin = this._getNewPixelOrigin(center);
  997. if (!supressEvent) {
  998. // @event zoom: Event
  999. // Fired repeatedly during any change in zoom level,
  1000. // including zoom and fly animations.
  1001. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  1002. this.fire('zoom', data);
  1003. }
  1004. // @event move: Event
  1005. // Fired repeatedly during any movement of the map,
  1006. // including pan and fly animations.
  1007. this.fire('move', data);
  1008. } else if (data && data.pinch) { // Always fire 'zoom' if pinching because #3530
  1009. this.fire('zoom', data);
  1010. }
  1011. return this;
  1012. },
  1013. _moveEnd: function (zoomChanged) {
  1014. // @event zoomend: Event
  1015. // Fired when the map zoom changed, after any animations.
  1016. if (zoomChanged) {
  1017. this.fire('zoomend');
  1018. }
  1019. // @event moveend: Event
  1020. // Fired when the center of the map stops changing
  1021. // (e.g. user stopped dragging the map or after non-centered zoom).
  1022. return this.fire('moveend');
  1023. },
  1024. _stop: function () {
  1025. Util.cancelAnimFrame(this._flyToFrame);
  1026. if (this._panAnim) {
  1027. this._panAnim.stop();
  1028. }
  1029. return this;
  1030. },
  1031. _rawPanBy: function (offset) {
  1032. DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  1033. },
  1034. _getZoomSpan: function () {
  1035. return this.getMaxZoom() - this.getMinZoom();
  1036. },
  1037. _panInsideMaxBounds: function () {
  1038. if (!this._enforcingBounds) {
  1039. this.panInsideBounds(this.options.maxBounds);
  1040. }
  1041. },
  1042. _checkIfLoaded: function () {
  1043. if (!this._loaded) {
  1044. throw new Error('Set map center and zoom first.');
  1045. }
  1046. },
  1047. // DOM event handling
  1048. // @section Interaction events
  1049. _initEvents: function (remove) {
  1050. this._targets = {};
  1051. this._targets[Util.stamp(this._container)] = this;
  1052. var onOff = remove ? DomEvent.off : DomEvent.on;
  1053. // @event click: MouseEvent
  1054. // Fired when the user clicks (or taps) the map.
  1055. // @event dblclick: MouseEvent
  1056. // Fired when the user double-clicks (or double-taps) the map.
  1057. // @event mousedown: MouseEvent
  1058. // Fired when the user pushes the mouse button on the map.
  1059. // @event mouseup: MouseEvent
  1060. // Fired when the user releases the mouse button on the map.
  1061. // @event mouseover: MouseEvent
  1062. // Fired when the mouse enters the map.
  1063. // @event mouseout: MouseEvent
  1064. // Fired when the mouse leaves the map.
  1065. // @event mousemove: MouseEvent
  1066. // Fired while the mouse moves over the map.
  1067. // @event contextmenu: MouseEvent
  1068. // Fired when the user pushes the right mouse button on the map, prevents
  1069. // default browser context menu from showing if there are listeners on
  1070. // this event. Also fired on mobile when the user holds a single touch
  1071. // for a second (also called long press).
  1072. // @event keypress: KeyboardEvent
  1073. // Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
  1074. // @event keydown: KeyboardEvent
  1075. // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
  1076. // the `keydown` event is fired for keys that produce a character value and for keys
  1077. // that do not produce a character value.
  1078. // @event keyup: KeyboardEvent
  1079. // Fired when the user releases a key from the keyboard while the map is focused.
  1080. onOff(this._container, 'click dblclick mousedown mouseup ' +
  1081. 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
  1082. if (this.options.trackResize) {
  1083. onOff(window, 'resize', this._onResize, this);
  1084. }
  1085. if (Browser.any3d && this.options.transform3DLimit) {
  1086. (remove ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  1087. }
  1088. },
  1089. _onResize: function () {
  1090. Util.cancelAnimFrame(this._resizeRequest);
  1091. this._resizeRequest = Util.requestAnimFrame(
  1092. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  1093. },
  1094. _onScroll: function () {
  1095. this._container.scrollTop = 0;
  1096. this._container.scrollLeft = 0;
  1097. },
  1098. _onMoveEnd: function () {
  1099. var pos = this._getMapPanePos();
  1100. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  1101. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  1102. // a pixel offset on very high values, see: https://jsfiddle.net/dg6r5hhb/
  1103. this._resetView(this.getCenter(), this.getZoom());
  1104. }
  1105. },
  1106. _findEventTargets: function (e, type) {
  1107. var targets = [],
  1108. target,
  1109. isHover = type === 'mouseout' || type === 'mouseover',
  1110. src = e.target || e.srcElement,
  1111. dragging = false;
  1112. while (src) {
  1113. target = this._targets[Util.stamp(src)];
  1114. if (target && (type === 'click' || type === 'preclick') && this._draggableMoved(target)) {
  1115. // Prevent firing click after you just dragged an object.
  1116. dragging = true;
  1117. break;
  1118. }
  1119. if (target && target.listens(type, true)) {
  1120. if (isHover && !DomEvent.isExternalTarget(src, e)) { break; }
  1121. targets.push(target);
  1122. if (isHover) { break; }
  1123. }
  1124. if (src === this._container) { break; }
  1125. src = src.parentNode;
  1126. }
  1127. if (!targets.length && !dragging && !isHover && this.listens(type, true)) {
  1128. targets = [this];
  1129. }
  1130. return targets;
  1131. },
  1132. _isClickDisabled: function (el) {
  1133. while (el && el !== this._container) {
  1134. if (el['_leaflet_disable_click']) { return true; }
  1135. el = el.parentNode;
  1136. }
  1137. },
  1138. _handleDOMEvent: function (e) {
  1139. var el = (e.target || e.srcElement);
  1140. if (!this._loaded || el['_leaflet_disable_events'] || e.type === 'click' && this._isClickDisabled(el)) {
  1141. return;
  1142. }
  1143. var type = e.type;
  1144. if (type === 'mousedown') {
  1145. // prevents outline when clicking on keyboard-focusable element
  1146. DomUtil.preventOutline(el);
  1147. }
  1148. this._fireDOMEvent(e, type);
  1149. },
  1150. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  1151. _fireDOMEvent: function (e, type, canvasTargets) {
  1152. if (e.type === 'click') {
  1153. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  1154. // @event preclick: MouseEvent
  1155. // Fired before mouse click on the map (sometimes useful when you
  1156. // want something to happen on click before any existing click
  1157. // handlers start running).
  1158. var synth = Util.extend({}, e);
  1159. synth.type = 'preclick';
  1160. this._fireDOMEvent(synth, synth.type, canvasTargets);
  1161. }
  1162. // Find the layer the event is propagating from and its parents.
  1163. var targets = this._findEventTargets(e, type);
  1164. if (canvasTargets) {
  1165. var filtered = []; // pick only targets with listeners
  1166. for (var i = 0; i < canvasTargets.length; i++) {
  1167. if (canvasTargets[i].listens(type, true)) {
  1168. filtered.push(canvasTargets[i]);
  1169. }
  1170. }
  1171. targets = filtered.concat(targets);
  1172. }
  1173. if (!targets.length) { return; }
  1174. if (type === 'contextmenu') {
  1175. DomEvent.preventDefault(e);
  1176. }
  1177. var target = targets[0];
  1178. var data = {
  1179. originalEvent: e
  1180. };
  1181. if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
  1182. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  1183. data.containerPoint = isMarker ?
  1184. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  1185. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  1186. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  1187. }
  1188. for (i = 0; i < targets.length; i++) {
  1189. targets[i].fire(type, data, true);
  1190. if (data.originalEvent._stopped ||
  1191. (targets[i].options.bubblingMouseEvents === false && Util.indexOf(this._mouseEvents, type) !== -1)) { return; }
  1192. }
  1193. },
  1194. _draggableMoved: function (obj) {
  1195. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  1196. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  1197. },
  1198. _clearHandlers: function () {
  1199. for (var i = 0, len = this._handlers.length; i < len; i++) {
  1200. this._handlers[i].disable();
  1201. }
  1202. },
  1203. // @section Other Methods
  1204. // @method whenReady(fn: Function, context?: Object): this
  1205. // Runs the given function `fn` when the map gets initialized with
  1206. // a view (center and zoom) and at least one layer, or immediately
  1207. // if it's already initialized, optionally passing a function context.
  1208. whenReady: function (callback, context) {
  1209. if (this._loaded) {
  1210. callback.call(context || this, {target: this});
  1211. } else {
  1212. this.on('load', callback, context);
  1213. }
  1214. return this;
  1215. },
  1216. // private methods for getting map state
  1217. _getMapPanePos: function () {
  1218. return DomUtil.getPosition(this._mapPane) || new Point(0, 0);
  1219. },
  1220. _moved: function () {
  1221. var pos = this._getMapPanePos();
  1222. return pos && !pos.equals([0, 0]);
  1223. },
  1224. _getTopLeftPoint: function (center, zoom) {
  1225. var pixelOrigin = center && zoom !== undefined ?
  1226. this._getNewPixelOrigin(center, zoom) :
  1227. this.getPixelOrigin();
  1228. return pixelOrigin.subtract(this._getMapPanePos());
  1229. },
  1230. _getNewPixelOrigin: function (center, zoom) {
  1231. var viewHalf = this.getSize()._divideBy(2);
  1232. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  1233. },
  1234. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  1235. var topLeft = this._getNewPixelOrigin(center, zoom);
  1236. return this.project(latlng, zoom)._subtract(topLeft);
  1237. },
  1238. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  1239. var topLeft = this._getNewPixelOrigin(center, zoom);
  1240. return toBounds([
  1241. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  1242. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  1243. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  1244. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  1245. ]);
  1246. },
  1247. // layer point of the current center
  1248. _getCenterLayerPoint: function () {
  1249. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  1250. },
  1251. // offset of the specified place to the current center in pixels
  1252. _getCenterOffset: function (latlng) {
  1253. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  1254. },
  1255. // adjust center for view to get inside bounds
  1256. _limitCenter: function (center, zoom, bounds) {
  1257. if (!bounds) { return center; }
  1258. var centerPoint = this.project(center, zoom),
  1259. viewHalf = this.getSize().divideBy(2),
  1260. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  1261. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  1262. // If offset is less than a pixel, ignore.
  1263. // This prevents unstable projections from getting into
  1264. // an infinite loop of tiny offsets.
  1265. if (Math.abs(offset.x) <= 1 && Math.abs(offset.y) <= 1) {
  1266. return center;
  1267. }
  1268. return this.unproject(centerPoint.add(offset), zoom);
  1269. },
  1270. // adjust offset for view to get inside bounds
  1271. _limitOffset: function (offset, bounds) {
  1272. if (!bounds) { return offset; }
  1273. var viewBounds = this.getPixelBounds(),
  1274. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  1275. return offset.add(this._getBoundsOffset(newBounds, bounds));
  1276. },
  1277. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  1278. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  1279. var projectedMaxBounds = toBounds(
  1280. this.project(maxBounds.getNorthEast(), zoom),
  1281. this.project(maxBounds.getSouthWest(), zoom)
  1282. ),
  1283. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  1284. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  1285. dx = this._rebound(minOffset.x, -maxOffset.x),
  1286. dy = this._rebound(minOffset.y, -maxOffset.y);
  1287. return new Point(dx, dy);
  1288. },
  1289. _rebound: function (left, right) {
  1290. return left + right > 0 ?
  1291. Math.round(left - right) / 2 :
  1292. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  1293. },
  1294. _limitZoom: function (zoom) {
  1295. var min = this.getMinZoom(),
  1296. max = this.getMaxZoom(),
  1297. snap = Browser.any3d ? this.options.zoomSnap : 1;
  1298. if (snap) {
  1299. zoom = Math.round(zoom / snap) * snap;
  1300. }
  1301. return Math.max(min, Math.min(max, zoom));
  1302. },
  1303. _onPanTransitionStep: function () {
  1304. this.fire('move');
  1305. },
  1306. _onPanTransitionEnd: function () {
  1307. DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
  1308. this.fire('moveend');
  1309. },
  1310. _tryAnimatedPan: function (center, options) {
  1311. // difference between the new and current centers in pixels
  1312. var offset = this._getCenterOffset(center)._trunc();
  1313. // don't animate too far unless animate: true specified in options
  1314. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  1315. this.panBy(offset, options);
  1316. return true;
  1317. },
  1318. _createAnimProxy: function () {
  1319. var proxy = this._proxy = DomUtil.create('div', 'leaflet-proxy leaflet-zoom-animated');
  1320. this._panes.mapPane.appendChild(proxy);
  1321. this.on('zoomanim', function (e) {
  1322. var prop = DomUtil.TRANSFORM,
  1323. transform = this._proxy.style[prop];
  1324. DomUtil.setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  1325. // workaround for case when transform is the same and so transitionend event is not fired
  1326. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  1327. this._onZoomTransitionEnd();
  1328. }
  1329. }, this);
  1330. this.on('load moveend', this._animMoveEnd, this);
  1331. this._on('unload', this._destroyAnimProxy, this);
  1332. },
  1333. _destroyAnimProxy: function () {
  1334. DomUtil.remove(this._proxy);
  1335. this.off('load moveend', this._animMoveEnd, this);
  1336. delete this._proxy;
  1337. },
  1338. _animMoveEnd: function () {
  1339. var c = this.getCenter(),
  1340. z = this.getZoom();
  1341. DomUtil.setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  1342. },
  1343. _catchTransitionEnd: function (e) {
  1344. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  1345. this._onZoomTransitionEnd();
  1346. }
  1347. },
  1348. _nothingToAnimate: function () {
  1349. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  1350. },
  1351. _tryAnimatedZoom: function (center, zoom, options) {
  1352. if (this._animatingZoom) { return true; }
  1353. options = options || {};
  1354. // don't animate if disabled, not supported or zoom difference is too large
  1355. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  1356. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  1357. // offset is the pixel coords of the zoom origin relative to the current center
  1358. var scale = this.getZoomScale(zoom),
  1359. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  1360. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  1361. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  1362. Util.requestAnimFrame(function () {
  1363. this
  1364. ._moveStart(true, options.noMoveStart || false)
  1365. ._animateZoom(center, zoom, true);
  1366. }, this);
  1367. return true;
  1368. },
  1369. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  1370. if (!this._mapPane) { return; }
  1371. if (startAnim) {
  1372. this._animatingZoom = true;
  1373. // remember what center/zoom to set after animation
  1374. this._animateToCenter = center;
  1375. this._animateToZoom = zoom;
  1376. DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
  1377. }
  1378. // @section Other Events
  1379. // @event zoomanim: ZoomAnimEvent
  1380. // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
  1381. this.fire('zoomanim', {
  1382. center: center,
  1383. zoom: zoom,
  1384. noUpdate: noUpdate
  1385. });
  1386. if (!this._tempFireZoomEvent) {
  1387. this._tempFireZoomEvent = this._zoom !== this._animateToZoom;
  1388. }
  1389. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  1390. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  1391. setTimeout(Util.bind(this._onZoomTransitionEnd, this), 250);
  1392. },
  1393. _onZoomTransitionEnd: function () {
  1394. if (!this._animatingZoom) { return; }
  1395. if (this._mapPane) {
  1396. DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
  1397. }
  1398. this._animatingZoom = false;
  1399. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  1400. if (this._tempFireZoomEvent) {
  1401. this.fire('zoom');
  1402. }
  1403. delete this._tempFireZoomEvent;
  1404. this.fire('move');
  1405. this._moveEnd(true);
  1406. }
  1407. });
  1408. // @section
  1409. // @factory L.map(id: String, options?: Map options)
  1410. // Instantiates a map object given the DOM ID of a `<div>` element
  1411. // and optionally an object literal with `Map options`.
  1412. //
  1413. // @alternative
  1414. // @factory L.map(el: HTMLElement, options?: Map options)
  1415. // Instantiates a map object given an instance of a `<div>` HTML element
  1416. // and optionally an object literal with `Map options`.
  1417. export function createMap(id, options) {
  1418. return new Map(id, options);
  1419. }