leaflet-src.js 373 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611
  1. /* @preserve
  2. * Leaflet 1.2.0+Detached: 1ac320ba232cb85b73ac81f3d82780c9d07f0d4e.1ac320b, a JS library for interactive maps. http://leafletjs.com
  3. * (c) 2010-2017 Vladimir Agafonkin, (c) 2010-2011 CloudMade
  4. */
  5. (function (global, factory) {
  6. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  7. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  8. (factory((global.L = {})));
  9. }(this, (function (exports) { 'use strict';
  10. var version = "1.2.0+HEAD.1ac320b";
  11. /*
  12. * @namespace Util
  13. *
  14. * Various utility functions, used by Leaflet internally.
  15. */
  16. var freeze = Object.freeze;
  17. Object.freeze = function (obj) { return obj; };
  18. // @function extend(dest: Object, src?: Object): Object
  19. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  20. function extend(dest) {
  21. var i, j, len, src;
  22. for (j = 1, len = arguments.length; j < len; j++) {
  23. src = arguments[j];
  24. for (i in src) {
  25. dest[i] = src[i];
  26. }
  27. }
  28. return dest;
  29. }
  30. // @function create(proto: Object, properties?: Object): Object
  31. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  32. var create = Object.create || (function () {
  33. function F() {}
  34. return function (proto) {
  35. F.prototype = proto;
  36. return new F();
  37. };
  38. })();
  39. // @function bind(fn: Function, …): Function
  40. // Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
  41. // Has a `L.bind()` shortcut.
  42. function bind(fn, obj) {
  43. var slice = Array.prototype.slice;
  44. if (fn.bind) {
  45. return fn.bind.apply(fn, slice.call(arguments, 1));
  46. }
  47. var args = slice.call(arguments, 2);
  48. return function () {
  49. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  50. };
  51. }
  52. // @property lastId: Number
  53. // Last unique ID used by [`stamp()`](#util-stamp)
  54. var lastId = 0;
  55. // @function stamp(obj: Object): Number
  56. // Returns the unique ID of an object, assiging it one if it doesn't have it.
  57. function stamp(obj) {
  58. /*eslint-disable */
  59. obj._leaflet_id = obj._leaflet_id || ++lastId;
  60. return obj._leaflet_id;
  61. /*eslint-enable */
  62. }
  63. // @function throttle(fn: Function, time: Number, context: Object): Function
  64. // Returns a function which executes function `fn` with the given scope `context`
  65. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  66. // `fn` will be called no more than one time per given amount of `time`. The arguments
  67. // received by the bound function will be any arguments passed when binding the
  68. // function, followed by any arguments passed when invoking the bound function.
  69. // Has an `L.throttle` shortcut.
  70. function throttle(fn, time, context) {
  71. var lock, args, wrapperFn, later;
  72. later = function () {
  73. // reset lock and call if queued
  74. lock = false;
  75. if (args) {
  76. wrapperFn.apply(context, args);
  77. args = false;
  78. }
  79. };
  80. wrapperFn = function () {
  81. if (lock) {
  82. // called too soon, queue to call later
  83. args = arguments;
  84. } else {
  85. // call and lock until later
  86. fn.apply(context, arguments);
  87. setTimeout(later, time);
  88. lock = true;
  89. }
  90. };
  91. return wrapperFn;
  92. }
  93. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  94. // Returns the number `num` modulo `range` in such a way so it lies within
  95. // `range[0]` and `range[1]`. The returned value will be always smaller than
  96. // `range[1]` unless `includeMax` is set to `true`.
  97. function wrapNum(x, range, includeMax) {
  98. var max = range[1],
  99. min = range[0],
  100. d = max - min;
  101. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  102. }
  103. // @function falseFn(): Function
  104. // Returns a function which always returns `false`.
  105. function falseFn() { return false; }
  106. // @function formatNum(num: Number, digits?: Number): Number
  107. // Returns the number `num` rounded to `digits` decimals, or to 5 decimals by default.
  108. function formatNum(num, digits) {
  109. var pow = Math.pow(10, digits || 5);
  110. return Math.round(num * pow) / pow;
  111. }
  112. // @function trim(str: String): String
  113. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  114. function trim(str) {
  115. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  116. }
  117. // @function splitWords(str: String): String[]
  118. // Trims and splits the string on whitespace and returns the array of parts.
  119. function splitWords(str) {
  120. return trim(str).split(/\s+/);
  121. }
  122. // @function setOptions(obj: Object, options: Object): Object
  123. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  124. function setOptions(obj, options) {
  125. if (!obj.hasOwnProperty('options')) {
  126. obj.options = obj.options ? create(obj.options) : {};
  127. }
  128. for (var i in options) {
  129. obj.options[i] = options[i];
  130. }
  131. return obj.options;
  132. }
  133. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  134. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  135. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  136. // be appended at the end. If `uppercase` is `true`, the parameter names will
  137. // be uppercased (e.g. `'?A=foo&B=bar'`)
  138. function getParamString(obj, existingUrl, uppercase) {
  139. var params = [];
  140. for (var i in obj) {
  141. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  142. }
  143. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  144. }
  145. var templateRe = /\{ *([\w_\-]+) *\}/g;
  146. // @function template(str: String, data: Object): String
  147. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  148. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  149. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  150. // data values — they will be evaluated passing `data` as an argument.
  151. function template(str, data) {
  152. return str.replace(templateRe, function (str, key) {
  153. var value = data[key];
  154. if (value === undefined) {
  155. throw new Error('No value provided for variable ' + str);
  156. } else if (typeof value === 'function') {
  157. value = value(data);
  158. }
  159. return value;
  160. });
  161. }
  162. // @function isArray(obj): Boolean
  163. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  164. var isArray = Array.isArray || function (obj) {
  165. return (Object.prototype.toString.call(obj) === '[object Array]');
  166. };
  167. // @function indexOf(array: Array, el: Object): Number
  168. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  169. function indexOf(array, el) {
  170. for (var i = 0; i < array.length; i++) {
  171. if (array[i] === el) { return i; }
  172. }
  173. return -1;
  174. }
  175. // @property emptyImageUrl: String
  176. // Data URI string containing a base64-encoded empty GIF image.
  177. // Used as a hack to free memory from unused images on WebKit-powered
  178. // mobile devices (by setting image `src` to this string).
  179. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  180. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  181. function getPrefixed(name) {
  182. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  183. }
  184. var lastTime = 0;
  185. // fallback for IE 7-8
  186. function timeoutDefer(fn) {
  187. var time = +new Date(),
  188. timeToCall = Math.max(0, 16 - (time - lastTime));
  189. lastTime = time + timeToCall;
  190. return window.setTimeout(fn, timeToCall);
  191. }
  192. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  193. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  194. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  195. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  196. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  197. // `context` if given. When `immediate` is set, `fn` is called immediately if
  198. // the browser doesn't have native support for
  199. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  200. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  201. function requestAnimFrame(fn, context, immediate) {
  202. if (immediate && requestFn === timeoutDefer) {
  203. fn.call(context);
  204. } else {
  205. return requestFn.call(window, bind(fn, context));
  206. }
  207. }
  208. // @function cancelAnimFrame(id: Number): undefined
  209. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  210. function cancelAnimFrame(id) {
  211. if (id) {
  212. cancelFn.call(window, id);
  213. }
  214. }
  215. var Util = (Object.freeze || Object)({
  216. freeze: freeze,
  217. extend: extend,
  218. create: create,
  219. bind: bind,
  220. lastId: lastId,
  221. stamp: stamp,
  222. throttle: throttle,
  223. wrapNum: wrapNum,
  224. falseFn: falseFn,
  225. formatNum: formatNum,
  226. trim: trim,
  227. splitWords: splitWords,
  228. setOptions: setOptions,
  229. getParamString: getParamString,
  230. template: template,
  231. isArray: isArray,
  232. indexOf: indexOf,
  233. emptyImageUrl: emptyImageUrl,
  234. requestFn: requestFn,
  235. cancelFn: cancelFn,
  236. requestAnimFrame: requestAnimFrame,
  237. cancelAnimFrame: cancelAnimFrame
  238. });
  239. // @class Class
  240. // @aka L.Class
  241. // @section
  242. // @uninheritable
  243. // Thanks to John Resig and Dean Edwards for inspiration!
  244. function Class() {}
  245. Class.extend = function (props) {
  246. // @function extend(props: Object): Function
  247. // [Extends the current class](#class-inheritance) given the properties to be included.
  248. // Returns a Javascript function that is a class constructor (to be called with `new`).
  249. var NewClass = function () {
  250. // call the constructor
  251. if (this.initialize) {
  252. this.initialize.apply(this, arguments);
  253. }
  254. // call all constructor hooks
  255. this.callInitHooks();
  256. };
  257. var parentProto = NewClass.__super__ = this.prototype;
  258. var proto = create(parentProto);
  259. proto.constructor = NewClass;
  260. NewClass.prototype = proto;
  261. // inherit parent's statics
  262. for (var i in this) {
  263. if (this.hasOwnProperty(i) && i !== 'prototype' && i !== '__super__') {
  264. NewClass[i] = this[i];
  265. }
  266. }
  267. // mix static properties into the class
  268. if (props.statics) {
  269. extend(NewClass, props.statics);
  270. delete props.statics;
  271. }
  272. // mix includes into the prototype
  273. if (props.includes) {
  274. checkDeprecatedMixinEvents(props.includes);
  275. extend.apply(null, [proto].concat(props.includes));
  276. delete props.includes;
  277. }
  278. // merge options
  279. if (proto.options) {
  280. props.options = extend(create(proto.options), props.options);
  281. }
  282. // mix given properties into the prototype
  283. extend(proto, props);
  284. proto._initHooks = [];
  285. // add method for calling all hooks
  286. proto.callInitHooks = function () {
  287. if (this._initHooksCalled) { return; }
  288. if (parentProto.callInitHooks) {
  289. parentProto.callInitHooks.call(this);
  290. }
  291. this._initHooksCalled = true;
  292. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  293. proto._initHooks[i].call(this);
  294. }
  295. };
  296. return NewClass;
  297. };
  298. // @function include(properties: Object): this
  299. // [Includes a mixin](#class-includes) into the current class.
  300. Class.include = function (props) {
  301. extend(this.prototype, props);
  302. return this;
  303. };
  304. // @function mergeOptions(options: Object): this
  305. // [Merges `options`](#class-options) into the defaults of the class.
  306. Class.mergeOptions = function (options) {
  307. extend(this.prototype.options, options);
  308. return this;
  309. };
  310. // @function addInitHook(fn: Function): this
  311. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  312. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  313. var args = Array.prototype.slice.call(arguments, 1);
  314. var init = typeof fn === 'function' ? fn : function () {
  315. this[fn].apply(this, args);
  316. };
  317. this.prototype._initHooks = this.prototype._initHooks || [];
  318. this.prototype._initHooks.push(init);
  319. return this;
  320. };
  321. function checkDeprecatedMixinEvents(includes) {
  322. if (!L || !L.Mixin) { return; }
  323. includes = isArray(includes) ? includes : [includes];
  324. for (var i = 0; i < includes.length; i++) {
  325. if (includes[i] === L.Mixin.Events) {
  326. console.warn('Deprecated include of L.Mixin.Events: ' +
  327. 'this property will be removed in future releases, ' +
  328. 'please inherit from L.Evented instead.', new Error().stack);
  329. }
  330. }
  331. }
  332. /*
  333. * @class Evented
  334. * @aka L.Evented
  335. * @inherits Class
  336. *
  337. * A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event).
  338. *
  339. * @example
  340. *
  341. * ```js
  342. * map.on('click', function(e) {
  343. * alert(e.latlng);
  344. * } );
  345. * ```
  346. *
  347. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  348. *
  349. * ```js
  350. * function onClick(e) { ... }
  351. *
  352. * map.on('click', onClick);
  353. * map.off('click', onClick);
  354. * ```
  355. */
  356. var Events = {
  357. /* @method on(type: String, fn: Function, context?: Object): this
  358. * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).
  359. *
  360. * @alternative
  361. * @method on(eventMap: Object): this
  362. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  363. */
  364. on: function (types, fn, context) {
  365. // types can be a map of types/handlers
  366. if (typeof types === 'object') {
  367. for (var type in types) {
  368. // we don't process space-separated events here for performance;
  369. // it's a hot path since Layer uses the on(obj) syntax
  370. this._on(type, types[type], fn);
  371. }
  372. } else {
  373. // types can be a string of space-separated words
  374. types = splitWords(types);
  375. for (var i = 0, len = types.length; i < len; i++) {
  376. this._on(types[i], fn, context);
  377. }
  378. }
  379. return this;
  380. },
  381. /* @method off(type: String, fn?: Function, context?: Object): this
  382. * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.
  383. *
  384. * @alternative
  385. * @method off(eventMap: Object): this
  386. * Removes a set of type/listener pairs.
  387. *
  388. * @alternative
  389. * @method off: this
  390. * Removes all listeners to all events on the object.
  391. */
  392. off: function (types, fn, context) {
  393. if (!types) {
  394. // clear all listeners if called without arguments
  395. delete this._events;
  396. } else if (typeof types === 'object') {
  397. for (var type in types) {
  398. this._off(type, types[type], fn);
  399. }
  400. } else {
  401. types = splitWords(types);
  402. for (var i = 0, len = types.length; i < len; i++) {
  403. this._off(types[i], fn, context);
  404. }
  405. }
  406. return this;
  407. },
  408. // attach listener (without syntactic sugar now)
  409. _on: function (type, fn, context) {
  410. this._events = this._events || {};
  411. /* get/init listeners for type */
  412. var typeListeners = this._events[type];
  413. if (!typeListeners) {
  414. typeListeners = [];
  415. this._events[type] = typeListeners;
  416. }
  417. if (context === this) {
  418. // Less memory footprint.
  419. context = undefined;
  420. }
  421. var newListener = {fn: fn, ctx: context},
  422. listeners = typeListeners;
  423. // check if fn already there
  424. for (var i = 0, len = listeners.length; i < len; i++) {
  425. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  426. return;
  427. }
  428. }
  429. listeners.push(newListener);
  430. },
  431. _off: function (type, fn, context) {
  432. var listeners,
  433. i,
  434. len;
  435. if (!this._events) { return; }
  436. listeners = this._events[type];
  437. if (!listeners) {
  438. return;
  439. }
  440. if (!fn) {
  441. // Set all removed listeners to noop so they are not called if remove happens in fire
  442. for (i = 0, len = listeners.length; i < len; i++) {
  443. listeners[i].fn = falseFn;
  444. }
  445. // clear all listeners for a type if function isn't specified
  446. delete this._events[type];
  447. return;
  448. }
  449. if (context === this) {
  450. context = undefined;
  451. }
  452. if (listeners) {
  453. // find fn and remove it
  454. for (i = 0, len = listeners.length; i < len; i++) {
  455. var l = listeners[i];
  456. if (l.ctx !== context) { continue; }
  457. if (l.fn === fn) {
  458. // set the removed listener to noop so that's not called if remove happens in fire
  459. l.fn = falseFn;
  460. if (this._firingCount) {
  461. /* copy array in case events are being fired */
  462. this._events[type] = listeners = listeners.slice();
  463. }
  464. listeners.splice(i, 1);
  465. return;
  466. }
  467. }
  468. }
  469. },
  470. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  471. // Fires an event of the specified type. You can optionally provide an data
  472. // object — the first argument of the listener function will contain its
  473. // properties. The event can optionally be propagated to event parents.
  474. fire: function (type, data, propagate) {
  475. if (!this.listens(type, propagate)) { return this; }
  476. var event = extend({}, data, {type: type, target: this});
  477. if (this._events) {
  478. var listeners = this._events[type];
  479. if (listeners) {
  480. this._firingCount = (this._firingCount + 1) || 1;
  481. for (var i = 0, len = listeners.length; i < len; i++) {
  482. var l = listeners[i];
  483. l.fn.call(l.ctx || this, event);
  484. }
  485. this._firingCount--;
  486. }
  487. }
  488. if (propagate) {
  489. // propagate the event to parents (set with addEventParent)
  490. this._propagateEvent(event);
  491. }
  492. return this;
  493. },
  494. // @method listens(type: String): Boolean
  495. // Returns `true` if a particular event type has any listeners attached to it.
  496. listens: function (type, propagate) {
  497. var listeners = this._events && this._events[type];
  498. if (listeners && listeners.length) { return true; }
  499. if (propagate) {
  500. // also check parents for listeners if event propagates
  501. for (var id in this._eventParents) {
  502. if (this._eventParents[id].listens(type, propagate)) { return true; }
  503. }
  504. }
  505. return false;
  506. },
  507. // @method once(…): this
  508. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  509. once: function (types, fn, context) {
  510. if (typeof types === 'object') {
  511. for (var type in types) {
  512. this.once(type, types[type], fn);
  513. }
  514. return this;
  515. }
  516. var handler = bind(function () {
  517. this
  518. .off(types, fn, context)
  519. .off(types, handler, context);
  520. }, this);
  521. // add a listener that's executed once and removed after that
  522. return this
  523. .on(types, fn, context)
  524. .on(types, handler, context);
  525. },
  526. // @method addEventParent(obj: Evented): this
  527. // Adds an event parent - an `Evented` that will receive propagated events
  528. addEventParent: function (obj) {
  529. this._eventParents = this._eventParents || {};
  530. this._eventParents[stamp(obj)] = obj;
  531. return this;
  532. },
  533. // @method removeEventParent(obj: Evented): this
  534. // Removes an event parent, so it will stop receiving propagated events
  535. removeEventParent: function (obj) {
  536. if (this._eventParents) {
  537. delete this._eventParents[stamp(obj)];
  538. }
  539. return this;
  540. },
  541. _propagateEvent: function (e) {
  542. for (var id in this._eventParents) {
  543. this._eventParents[id].fire(e.type, extend({layer: e.target}, e), true);
  544. }
  545. }
  546. };
  547. // aliases; we should ditch those eventually
  548. // @method addEventListener(…): this
  549. // Alias to [`on(…)`](#evented-on)
  550. Events.addEventListener = Events.on;
  551. // @method removeEventListener(…): this
  552. // Alias to [`off(…)`](#evented-off)
  553. // @method clearAllEventListeners(…): this
  554. // Alias to [`off()`](#evented-off)
  555. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  556. // @method addOneTimeEventListener(…): this
  557. // Alias to [`once(…)`](#evented-once)
  558. Events.addOneTimeEventListener = Events.once;
  559. // @method fireEvent(…): this
  560. // Alias to [`fire(…)`](#evented-fire)
  561. Events.fireEvent = Events.fire;
  562. // @method hasEventListeners(…): Boolean
  563. // Alias to [`listens(…)`](#evented-listens)
  564. Events.hasEventListeners = Events.listens;
  565. var Evented = Class.extend(Events);
  566. /*
  567. * @class Point
  568. * @aka L.Point
  569. *
  570. * Represents a point with `x` and `y` coordinates in pixels.
  571. *
  572. * @example
  573. *
  574. * ```js
  575. * var point = L.point(200, 300);
  576. * ```
  577. *
  578. * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:
  579. *
  580. * ```js
  581. * map.panBy([200, 300]);
  582. * map.panBy(L.point(200, 300));
  583. * ```
  584. */
  585. function Point(x, y, round) {
  586. // @property x: Number; The `x` coordinate of the point
  587. this.x = (round ? Math.round(x) : x);
  588. // @property y: Number; The `y` coordinate of the point
  589. this.y = (round ? Math.round(y) : y);
  590. }
  591. Point.prototype = {
  592. // @method clone(): Point
  593. // Returns a copy of the current point.
  594. clone: function () {
  595. return new Point(this.x, this.y);
  596. },
  597. // @method add(otherPoint: Point): Point
  598. // Returns the result of addition of the current and the given points.
  599. add: function (point) {
  600. // non-destructive, returns a new point
  601. return this.clone()._add(toPoint(point));
  602. },
  603. _add: function (point) {
  604. // destructive, used directly for performance in situations where it's safe to modify existing point
  605. this.x += point.x;
  606. this.y += point.y;
  607. return this;
  608. },
  609. // @method subtract(otherPoint: Point): Point
  610. // Returns the result of subtraction of the given point from the current.
  611. subtract: function (point) {
  612. return this.clone()._subtract(toPoint(point));
  613. },
  614. _subtract: function (point) {
  615. this.x -= point.x;
  616. this.y -= point.y;
  617. return this;
  618. },
  619. // @method divideBy(num: Number): Point
  620. // Returns the result of division of the current point by the given number.
  621. divideBy: function (num) {
  622. return this.clone()._divideBy(num);
  623. },
  624. _divideBy: function (num) {
  625. this.x /= num;
  626. this.y /= num;
  627. return this;
  628. },
  629. // @method multiplyBy(num: Number): Point
  630. // Returns the result of multiplication of the current point by the given number.
  631. multiplyBy: function (num) {
  632. return this.clone()._multiplyBy(num);
  633. },
  634. _multiplyBy: function (num) {
  635. this.x *= num;
  636. this.y *= num;
  637. return this;
  638. },
  639. // @method scaleBy(scale: Point): Point
  640. // Multiply each coordinate of the current point by each coordinate of
  641. // `scale`. In linear algebra terms, multiply the point by the
  642. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  643. // defined by `scale`.
  644. scaleBy: function (point) {
  645. return new Point(this.x * point.x, this.y * point.y);
  646. },
  647. // @method unscaleBy(scale: Point): Point
  648. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  649. // each coordinate of `scale`.
  650. unscaleBy: function (point) {
  651. return new Point(this.x / point.x, this.y / point.y);
  652. },
  653. // @method round(): Point
  654. // Returns a copy of the current point with rounded coordinates.
  655. round: function () {
  656. return this.clone()._round();
  657. },
  658. _round: function () {
  659. this.x = Math.round(this.x);
  660. this.y = Math.round(this.y);
  661. return this;
  662. },
  663. // @method floor(): Point
  664. // Returns a copy of the current point with floored coordinates (rounded down).
  665. floor: function () {
  666. return this.clone()._floor();
  667. },
  668. _floor: function () {
  669. this.x = Math.floor(this.x);
  670. this.y = Math.floor(this.y);
  671. return this;
  672. },
  673. // @method ceil(): Point
  674. // Returns a copy of the current point with ceiled coordinates (rounded up).
  675. ceil: function () {
  676. return this.clone()._ceil();
  677. },
  678. _ceil: function () {
  679. this.x = Math.ceil(this.x);
  680. this.y = Math.ceil(this.y);
  681. return this;
  682. },
  683. // @method distanceTo(otherPoint: Point): Number
  684. // Returns the cartesian distance between the current and the given points.
  685. distanceTo: function (point) {
  686. point = toPoint(point);
  687. var x = point.x - this.x,
  688. y = point.y - this.y;
  689. return Math.sqrt(x * x + y * y);
  690. },
  691. // @method equals(otherPoint: Point): Boolean
  692. // Returns `true` if the given point has the same coordinates.
  693. equals: function (point) {
  694. point = toPoint(point);
  695. return point.x === this.x &&
  696. point.y === this.y;
  697. },
  698. // @method contains(otherPoint: Point): Boolean
  699. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  700. contains: function (point) {
  701. point = toPoint(point);
  702. return Math.abs(point.x) <= Math.abs(this.x) &&
  703. Math.abs(point.y) <= Math.abs(this.y);
  704. },
  705. // @method toString(): String
  706. // Returns a string representation of the point for debugging purposes.
  707. toString: function () {
  708. return 'Point(' +
  709. formatNum(this.x) + ', ' +
  710. formatNum(this.y) + ')';
  711. }
  712. };
  713. // @factory L.point(x: Number, y: Number, round?: Boolean)
  714. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  715. // @alternative
  716. // @factory L.point(coords: Number[])
  717. // Expects an array of the form `[x, y]` instead.
  718. // @alternative
  719. // @factory L.point(coords: Object)
  720. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  721. function toPoint(x, y, round) {
  722. if (x instanceof Point) {
  723. return x;
  724. }
  725. if (isArray(x)) {
  726. return new Point(x[0], x[1]);
  727. }
  728. if (x === undefined || x === null) {
  729. return x;
  730. }
  731. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  732. return new Point(x.x, x.y);
  733. }
  734. return new Point(x, y, round);
  735. }
  736. /*
  737. * @class Bounds
  738. * @aka L.Bounds
  739. *
  740. * Represents a rectangular area in pixel coordinates.
  741. *
  742. * @example
  743. *
  744. * ```js
  745. * var p1 = L.point(10, 10),
  746. * p2 = L.point(40, 60),
  747. * bounds = L.bounds(p1, p2);
  748. * ```
  749. *
  750. * All Leaflet methods that accept `Bounds` objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:
  751. *
  752. * ```js
  753. * otherBounds.intersects([[10, 10], [40, 60]]);
  754. * ```
  755. */
  756. function Bounds(a, b) {
  757. if (!a) { return; }
  758. var points = b ? [a, b] : a;
  759. for (var i = 0, len = points.length; i < len; i++) {
  760. this.extend(points[i]);
  761. }
  762. }
  763. Bounds.prototype = {
  764. // @method extend(point: Point): this
  765. // Extends the bounds to contain the given point.
  766. extend: function (point) { // (Point)
  767. point = toPoint(point);
  768. // @property min: Point
  769. // The top left corner of the rectangle.
  770. // @property max: Point
  771. // The bottom right corner of the rectangle.
  772. if (!this.min && !this.max) {
  773. this.min = point.clone();
  774. this.max = point.clone();
  775. } else {
  776. this.min.x = Math.min(point.x, this.min.x);
  777. this.max.x = Math.max(point.x, this.max.x);
  778. this.min.y = Math.min(point.y, this.min.y);
  779. this.max.y = Math.max(point.y, this.max.y);
  780. }
  781. return this;
  782. },
  783. // @method getCenter(round?: Boolean): Point
  784. // Returns the center point of the bounds.
  785. getCenter: function (round) {
  786. return new Point(
  787. (this.min.x + this.max.x) / 2,
  788. (this.min.y + this.max.y) / 2, round);
  789. },
  790. // @method getBottomLeft(): Point
  791. // Returns the bottom-left point of the bounds.
  792. getBottomLeft: function () {
  793. return new Point(this.min.x, this.max.y);
  794. },
  795. // @method getTopRight(): Point
  796. // Returns the top-right point of the bounds.
  797. getTopRight: function () { // -> Point
  798. return new Point(this.max.x, this.min.y);
  799. },
  800. // @method getTopLeft(): Point
  801. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  802. getTopLeft: function () {
  803. return this.min; // left, top
  804. },
  805. // @method getBottomRight(): Point
  806. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  807. getBottomRight: function () {
  808. return this.max; // right, bottom
  809. },
  810. // @method getSize(): Point
  811. // Returns the size of the given bounds
  812. getSize: function () {
  813. return this.max.subtract(this.min);
  814. },
  815. // @method contains(otherBounds: Bounds): Boolean
  816. // Returns `true` if the rectangle contains the given one.
  817. // @alternative
  818. // @method contains(point: Point): Boolean
  819. // Returns `true` if the rectangle contains the given point.
  820. contains: function (obj) {
  821. var min, max;
  822. if (typeof obj[0] === 'number' || obj instanceof Point) {
  823. obj = toPoint(obj);
  824. } else {
  825. obj = toBounds(obj);
  826. }
  827. if (obj instanceof Bounds) {
  828. min = obj.min;
  829. max = obj.max;
  830. } else {
  831. min = max = obj;
  832. }
  833. return (min.x >= this.min.x) &&
  834. (max.x <= this.max.x) &&
  835. (min.y >= this.min.y) &&
  836. (max.y <= this.max.y);
  837. },
  838. // @method intersects(otherBounds: Bounds): Boolean
  839. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  840. // intersect if they have at least one point in common.
  841. intersects: function (bounds) { // (Bounds) -> Boolean
  842. bounds = toBounds(bounds);
  843. var min = this.min,
  844. max = this.max,
  845. min2 = bounds.min,
  846. max2 = bounds.max,
  847. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  848. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  849. return xIntersects && yIntersects;
  850. },
  851. // @method overlaps(otherBounds: Bounds): Boolean
  852. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  853. // overlap if their intersection is an area.
  854. overlaps: function (bounds) { // (Bounds) -> Boolean
  855. bounds = toBounds(bounds);
  856. var min = this.min,
  857. max = this.max,
  858. min2 = bounds.min,
  859. max2 = bounds.max,
  860. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  861. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  862. return xOverlaps && yOverlaps;
  863. },
  864. isValid: function () {
  865. return !!(this.min && this.max);
  866. }
  867. };
  868. // @factory L.bounds(corner1: Point, corner2: Point)
  869. // Creates a Bounds object from two corners coordinate pairs.
  870. // @alternative
  871. // @factory L.bounds(points: Point[])
  872. // Creates a Bounds object from the given array of points.
  873. function toBounds(a, b) {
  874. if (!a || a instanceof Bounds) {
  875. return a;
  876. }
  877. return new Bounds(a, b);
  878. }
  879. /*
  880. * @class LatLngBounds
  881. * @aka L.LatLngBounds
  882. *
  883. * Represents a rectangular geographical area on a map.
  884. *
  885. * @example
  886. *
  887. * ```js
  888. * var corner1 = L.latLng(40.712, -74.227),
  889. * corner2 = L.latLng(40.774, -74.125),
  890. * bounds = L.latLngBounds(corner1, corner2);
  891. * ```
  892. *
  893. * All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:
  894. *
  895. * ```js
  896. * map.fitBounds([
  897. * [40.712, -74.227],
  898. * [40.774, -74.125]
  899. * ]);
  900. * ```
  901. *
  902. * Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range.
  903. */
  904. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  905. if (!corner1) { return; }
  906. var latlngs = corner2 ? [corner1, corner2] : corner1;
  907. for (var i = 0, len = latlngs.length; i < len; i++) {
  908. this.extend(latlngs[i]);
  909. }
  910. }
  911. LatLngBounds.prototype = {
  912. // @method extend(latlng: LatLng): this
  913. // Extend the bounds to contain the given point
  914. // @alternative
  915. // @method extend(otherBounds: LatLngBounds): this
  916. // Extend the bounds to contain the given bounds
  917. extend: function (obj) {
  918. var sw = this._southWest,
  919. ne = this._northEast,
  920. sw2, ne2;
  921. if (obj instanceof LatLng) {
  922. sw2 = obj;
  923. ne2 = obj;
  924. } else if (obj instanceof LatLngBounds) {
  925. sw2 = obj._southWest;
  926. ne2 = obj._northEast;
  927. if (!sw2 || !ne2) { return this; }
  928. } else {
  929. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  930. }
  931. if (!sw && !ne) {
  932. this._southWest = new LatLng(sw2.lat, sw2.lng);
  933. this._northEast = new LatLng(ne2.lat, ne2.lng);
  934. } else {
  935. sw.lat = Math.min(sw2.lat, sw.lat);
  936. sw.lng = Math.min(sw2.lng, sw.lng);
  937. ne.lat = Math.max(ne2.lat, ne.lat);
  938. ne.lng = Math.max(ne2.lng, ne.lng);
  939. }
  940. return this;
  941. },
  942. // @method pad(bufferRatio: Number): LatLngBounds
  943. // Returns bigger bounds created by extending the current bounds by a given percentage in each direction.
  944. pad: function (bufferRatio) {
  945. var sw = this._southWest,
  946. ne = this._northEast,
  947. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  948. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  949. return new LatLngBounds(
  950. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  951. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  952. },
  953. // @method getCenter(): LatLng
  954. // Returns the center point of the bounds.
  955. getCenter: function () {
  956. return new LatLng(
  957. (this._southWest.lat + this._northEast.lat) / 2,
  958. (this._southWest.lng + this._northEast.lng) / 2);
  959. },
  960. // @method getSouthWest(): LatLng
  961. // Returns the south-west point of the bounds.
  962. getSouthWest: function () {
  963. return this._southWest;
  964. },
  965. // @method getNorthEast(): LatLng
  966. // Returns the north-east point of the bounds.
  967. getNorthEast: function () {
  968. return this._northEast;
  969. },
  970. // @method getNorthWest(): LatLng
  971. // Returns the north-west point of the bounds.
  972. getNorthWest: function () {
  973. return new LatLng(this.getNorth(), this.getWest());
  974. },
  975. // @method getSouthEast(): LatLng
  976. // Returns the south-east point of the bounds.
  977. getSouthEast: function () {
  978. return new LatLng(this.getSouth(), this.getEast());
  979. },
  980. // @method getWest(): Number
  981. // Returns the west longitude of the bounds
  982. getWest: function () {
  983. return this._southWest.lng;
  984. },
  985. // @method getSouth(): Number
  986. // Returns the south latitude of the bounds
  987. getSouth: function () {
  988. return this._southWest.lat;
  989. },
  990. // @method getEast(): Number
  991. // Returns the east longitude of the bounds
  992. getEast: function () {
  993. return this._northEast.lng;
  994. },
  995. // @method getNorth(): Number
  996. // Returns the north latitude of the bounds
  997. getNorth: function () {
  998. return this._northEast.lat;
  999. },
  1000. // @method contains(otherBounds: LatLngBounds): Boolean
  1001. // Returns `true` if the rectangle contains the given one.
  1002. // @alternative
  1003. // @method contains (latlng: LatLng): Boolean
  1004. // Returns `true` if the rectangle contains the given point.
  1005. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1006. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1007. obj = toLatLng(obj);
  1008. } else {
  1009. obj = toLatLngBounds(obj);
  1010. }
  1011. var sw = this._southWest,
  1012. ne = this._northEast,
  1013. sw2, ne2;
  1014. if (obj instanceof LatLngBounds) {
  1015. sw2 = obj.getSouthWest();
  1016. ne2 = obj.getNorthEast();
  1017. } else {
  1018. sw2 = ne2 = obj;
  1019. }
  1020. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1021. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1022. },
  1023. // @method intersects(otherBounds: LatLngBounds): Boolean
  1024. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1025. intersects: function (bounds) {
  1026. bounds = toLatLngBounds(bounds);
  1027. var sw = this._southWest,
  1028. ne = this._northEast,
  1029. sw2 = bounds.getSouthWest(),
  1030. ne2 = bounds.getNorthEast(),
  1031. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1032. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1033. return latIntersects && lngIntersects;
  1034. },
  1035. // @method overlaps(otherBounds: Bounds): Boolean
  1036. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1037. overlaps: function (bounds) {
  1038. bounds = toLatLngBounds(bounds);
  1039. var sw = this._southWest,
  1040. ne = this._northEast,
  1041. sw2 = bounds.getSouthWest(),
  1042. ne2 = bounds.getNorthEast(),
  1043. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1044. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1045. return latOverlaps && lngOverlaps;
  1046. },
  1047. // @method toBBoxString(): String
  1048. // Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.
  1049. toBBoxString: function () {
  1050. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1051. },
  1052. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1053. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overriden by setting `maxMargin` to a small number.
  1054. equals: function (bounds, maxMargin) {
  1055. if (!bounds) { return false; }
  1056. bounds = toLatLngBounds(bounds);
  1057. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1058. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1059. },
  1060. // @method isValid(): Boolean
  1061. // Returns `true` if the bounds are properly initialized.
  1062. isValid: function () {
  1063. return !!(this._southWest && this._northEast);
  1064. }
  1065. };
  1066. // TODO International date line?
  1067. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1068. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1069. // @alternative
  1070. // @factory L.latLngBounds(latlngs: LatLng[])
  1071. // Creates a `LatLngBounds` object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds).
  1072. function toLatLngBounds(a, b) {
  1073. if (a instanceof LatLngBounds) {
  1074. return a;
  1075. }
  1076. return new LatLngBounds(a, b);
  1077. }
  1078. /* @class LatLng
  1079. * @aka L.LatLng
  1080. *
  1081. * Represents a geographical point with a certain latitude and longitude.
  1082. *
  1083. * @example
  1084. *
  1085. * ```
  1086. * var latlng = L.latLng(50.5, 30.5);
  1087. * ```
  1088. *
  1089. * All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent:
  1090. *
  1091. * ```
  1092. * map.panTo([50, 30]);
  1093. * map.panTo({lon: 30, lat: 50});
  1094. * map.panTo({lat: 50, lng: 30});
  1095. * map.panTo(L.latLng(50, 30));
  1096. * ```
  1097. */
  1098. function LatLng(lat, lng, alt) {
  1099. if (isNaN(lat) || isNaN(lng)) {
  1100. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1101. }
  1102. // @property lat: Number
  1103. // Latitude in degrees
  1104. this.lat = +lat;
  1105. // @property lng: Number
  1106. // Longitude in degrees
  1107. this.lng = +lng;
  1108. // @property alt: Number
  1109. // Altitude in meters (optional)
  1110. if (alt !== undefined) {
  1111. this.alt = +alt;
  1112. }
  1113. }
  1114. LatLng.prototype = {
  1115. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1116. // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overriden by setting `maxMargin` to a small number.
  1117. equals: function (obj, maxMargin) {
  1118. if (!obj) { return false; }
  1119. obj = toLatLng(obj);
  1120. var margin = Math.max(
  1121. Math.abs(this.lat - obj.lat),
  1122. Math.abs(this.lng - obj.lng));
  1123. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1124. },
  1125. // @method toString(): String
  1126. // Returns a string representation of the point (for debugging purposes).
  1127. toString: function (precision) {
  1128. return 'LatLng(' +
  1129. formatNum(this.lat, precision) + ', ' +
  1130. formatNum(this.lng, precision) + ')';
  1131. },
  1132. // @method distanceTo(otherLatLng: LatLng): Number
  1133. // Returns the distance (in meters) to the given `LatLng` calculated using the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula).
  1134. distanceTo: function (other) {
  1135. return Earth.distance(this, toLatLng(other));
  1136. },
  1137. // @method wrap(): LatLng
  1138. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1139. wrap: function () {
  1140. return Earth.wrapLatLng(this);
  1141. },
  1142. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1143. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1144. toBounds: function (sizeInMeters) {
  1145. var latAccuracy = 180 * sizeInMeters / 40075017,
  1146. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1147. return toLatLngBounds(
  1148. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1149. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1150. },
  1151. clone: function () {
  1152. return new LatLng(this.lat, this.lng, this.alt);
  1153. }
  1154. };
  1155. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1156. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1157. // @alternative
  1158. // @factory L.latLng(coords: Array): LatLng
  1159. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1160. // @alternative
  1161. // @factory L.latLng(coords: Object): LatLng
  1162. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1163. function toLatLng(a, b, c) {
  1164. if (a instanceof LatLng) {
  1165. return a;
  1166. }
  1167. if (isArray(a) && typeof a[0] !== 'object') {
  1168. if (a.length === 3) {
  1169. return new LatLng(a[0], a[1], a[2]);
  1170. }
  1171. if (a.length === 2) {
  1172. return new LatLng(a[0], a[1]);
  1173. }
  1174. return null;
  1175. }
  1176. if (a === undefined || a === null) {
  1177. return a;
  1178. }
  1179. if (typeof a === 'object' && 'lat' in a) {
  1180. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1181. }
  1182. if (b === undefined) {
  1183. return null;
  1184. }
  1185. return new LatLng(a, b, c);
  1186. }
  1187. /*
  1188. * @namespace CRS
  1189. * @crs L.CRS.Base
  1190. * Object that defines coordinate reference systems for projecting
  1191. * geographical points into pixel (screen) coordinates and back (and to
  1192. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1193. * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
  1194. *
  1195. * Leaflet defines the most usual CRSs by default. If you want to use a
  1196. * CRS not defined by default, take a look at the
  1197. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1198. */
  1199. var CRS = {
  1200. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1201. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1202. latLngToPoint: function (latlng, zoom) {
  1203. var projectedPoint = this.projection.project(latlng),
  1204. scale = this.scale(zoom);
  1205. return this.transformation._transform(projectedPoint, scale);
  1206. },
  1207. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1208. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1209. // zoom into geographical coordinates.
  1210. pointToLatLng: function (point, zoom) {
  1211. var scale = this.scale(zoom),
  1212. untransformedPoint = this.transformation.untransform(point, scale);
  1213. return this.projection.unproject(untransformedPoint);
  1214. },
  1215. // @method project(latlng: LatLng): Point
  1216. // Projects geographical coordinates into coordinates in units accepted for
  1217. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1218. project: function (latlng) {
  1219. return this.projection.project(latlng);
  1220. },
  1221. // @method unproject(point: Point): LatLng
  1222. // Given a projected coordinate returns the corresponding LatLng.
  1223. // The inverse of `project`.
  1224. unproject: function (point) {
  1225. return this.projection.unproject(point);
  1226. },
  1227. // @method scale(zoom: Number): Number
  1228. // Returns the scale used when transforming projected coordinates into
  1229. // pixel coordinates for a particular zoom. For example, it returns
  1230. // `256 * 2^zoom` for Mercator-based CRS.
  1231. scale: function (zoom) {
  1232. return 256 * Math.pow(2, zoom);
  1233. },
  1234. // @method zoom(scale: Number): Number
  1235. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1236. // factor of `scale`.
  1237. zoom: function (scale) {
  1238. return Math.log(scale / 256) / Math.LN2;
  1239. },
  1240. // @method getProjectedBounds(zoom: Number): Bounds
  1241. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1242. getProjectedBounds: function (zoom) {
  1243. if (this.infinite) { return null; }
  1244. var b = this.projection.bounds,
  1245. s = this.scale(zoom),
  1246. min = this.transformation.transform(b.min, s),
  1247. max = this.transformation.transform(b.max, s);
  1248. return new Bounds(min, max);
  1249. },
  1250. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1251. // Returns the distance between two geographical coordinates.
  1252. // @property code: String
  1253. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1254. //
  1255. // @property wrapLng: Number[]
  1256. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1257. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1258. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1259. //
  1260. // @property wrapLat: Number[]
  1261. // Like `wrapLng`, but for the latitude (vertical) axis.
  1262. // wrapLng: [min, max],
  1263. // wrapLat: [min, max],
  1264. // @property infinite: Boolean
  1265. // If true, the coordinate space will be unbounded (infinite in both axes)
  1266. infinite: false,
  1267. // @method wrapLatLng(latlng: LatLng): LatLng
  1268. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1269. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1270. wrapLatLng: function (latlng) {
  1271. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1272. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1273. alt = latlng.alt;
  1274. return new LatLng(lat, lng, alt);
  1275. },
  1276. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1277. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1278. // that its center is within the CRS's bounds.
  1279. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1280. wrapLatLngBounds: function (bounds) {
  1281. var center = bounds.getCenter(),
  1282. newCenter = this.wrapLatLng(center),
  1283. latShift = center.lat - newCenter.lat,
  1284. lngShift = center.lng - newCenter.lng;
  1285. if (latShift === 0 && lngShift === 0) {
  1286. return bounds;
  1287. }
  1288. var sw = bounds.getSouthWest(),
  1289. ne = bounds.getNorthEast(),
  1290. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1291. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1292. return new LatLngBounds(newSw, newNe);
  1293. }
  1294. };
  1295. /*
  1296. * @namespace CRS
  1297. * @crs L.CRS.Earth
  1298. *
  1299. * Serves as the base for CRS that are global such that they cover the earth.
  1300. * Can only be used as the base for other CRS and cannot be used directly,
  1301. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1302. * meters.
  1303. */
  1304. var Earth = extend({}, CRS, {
  1305. wrapLng: [-180, 180],
  1306. // Mean Earth Radius, as recommended for use by
  1307. // the International Union of Geodesy and Geophysics,
  1308. // see http://rosettacode.org/wiki/Haversine_formula
  1309. R: 6371000,
  1310. // distance between two geographical points using spherical law of cosines approximation
  1311. distance: function (latlng1, latlng2) {
  1312. var rad = Math.PI / 180,
  1313. lat1 = latlng1.lat * rad,
  1314. lat2 = latlng2.lat * rad,
  1315. a = Math.sin(lat1) * Math.sin(lat2) +
  1316. Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad);
  1317. return this.R * Math.acos(Math.min(a, 1));
  1318. }
  1319. });
  1320. /*
  1321. * @namespace Projection
  1322. * @projection L.Projection.SphericalMercator
  1323. *
  1324. * Spherical Mercator projection — the most common projection for online maps,
  1325. * used by almost all free and commercial tile providers. Assumes that Earth is
  1326. * a sphere. Used by the `EPSG:3857` CRS.
  1327. */
  1328. var SphericalMercator = {
  1329. R: 6378137,
  1330. MAX_LATITUDE: 85.0511287798,
  1331. project: function (latlng) {
  1332. var d = Math.PI / 180,
  1333. max = this.MAX_LATITUDE,
  1334. lat = Math.max(Math.min(max, latlng.lat), -max),
  1335. sin = Math.sin(lat * d);
  1336. return new Point(
  1337. this.R * latlng.lng * d,
  1338. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1339. },
  1340. unproject: function (point) {
  1341. var d = 180 / Math.PI;
  1342. return new LatLng(
  1343. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1344. point.x * d / this.R);
  1345. },
  1346. bounds: (function () {
  1347. var d = 6378137 * Math.PI;
  1348. return new Bounds([-d, -d], [d, d]);
  1349. })()
  1350. };
  1351. /*
  1352. * @class Transformation
  1353. * @aka L.Transformation
  1354. *
  1355. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1356. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1357. * the reverse. Used by Leaflet in its projections code.
  1358. *
  1359. * @example
  1360. *
  1361. * ```js
  1362. * var transformation = L.transformation(2, 5, -1, 10),
  1363. * p = L.point(1, 2),
  1364. * p2 = transformation.transform(p), // L.point(7, 8)
  1365. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1366. * ```
  1367. */
  1368. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1369. // Creates a `Transformation` object with the given coefficients.
  1370. function Transformation(a, b, c, d) {
  1371. if (isArray(a)) {
  1372. // use array properties
  1373. this._a = a[0];
  1374. this._b = a[1];
  1375. this._c = a[2];
  1376. this._d = a[3];
  1377. return;
  1378. }
  1379. this._a = a;
  1380. this._b = b;
  1381. this._c = c;
  1382. this._d = d;
  1383. }
  1384. Transformation.prototype = {
  1385. // @method transform(point: Point, scale?: Number): Point
  1386. // Returns a transformed point, optionally multiplied by the given scale.
  1387. // Only accepts actual `L.Point` instances, not arrays.
  1388. transform: function (point, scale) { // (Point, Number) -> Point
  1389. return this._transform(point.clone(), scale);
  1390. },
  1391. // destructive transform (faster)
  1392. _transform: function (point, scale) {
  1393. scale = scale || 1;
  1394. point.x = scale * (this._a * point.x + this._b);
  1395. point.y = scale * (this._c * point.y + this._d);
  1396. return point;
  1397. },
  1398. // @method untransform(point: Point, scale?: Number): Point
  1399. // Returns the reverse transformation of the given point, optionally divided
  1400. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1401. untransform: function (point, scale) {
  1402. scale = scale || 1;
  1403. return new Point(
  1404. (point.x / scale - this._b) / this._a,
  1405. (point.y / scale - this._d) / this._c);
  1406. }
  1407. };
  1408. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1409. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1410. // Instantiates a Transformation object with the given coefficients.
  1411. // @alternative
  1412. // @factory L.transformation(coefficients: Array): Transformation
  1413. // Expects an coeficients array of the form
  1414. // `[a: Number, b: Number, c: Number, d: Number]`.
  1415. function toTransformation(a, b, c, d) {
  1416. return new Transformation(a, b, c, d);
  1417. }
  1418. /*
  1419. * @namespace CRS
  1420. * @crs L.CRS.EPSG3857
  1421. *
  1422. * The most common CRS for online maps, used by almost all free and commercial
  1423. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1424. * Map's `crs` option.
  1425. */
  1426. var EPSG3857 = extend({}, Earth, {
  1427. code: 'EPSG:3857',
  1428. projection: SphericalMercator,
  1429. transformation: (function () {
  1430. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1431. return toTransformation(scale, 0.5, -scale, 0.5);
  1432. }())
  1433. });
  1434. var EPSG900913 = extend({}, EPSG3857, {
  1435. code: 'EPSG:900913'
  1436. });
  1437. // @namespace SVG; @section
  1438. // There are several static functions which can be called without instantiating L.SVG:
  1439. // @function create(name: String): SVGElement
  1440. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1441. // corresponding to the class name passed. For example, using 'line' will return
  1442. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1443. function svgCreate(name) {
  1444. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1445. }
  1446. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1447. // Generates a SVG path string for multiple rings, with each ring turning
  1448. // into "M..L..L.." instructions
  1449. function pointsToPath(rings, closed) {
  1450. var str = '',
  1451. i, j, len, len2, points, p;
  1452. for (i = 0, len = rings.length; i < len; i++) {
  1453. points = rings[i];
  1454. for (j = 0, len2 = points.length; j < len2; j++) {
  1455. p = points[j];
  1456. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1457. }
  1458. // closes the ring for polygons; "x" is VML syntax
  1459. str += closed ? (svg ? 'z' : 'x') : '';
  1460. }
  1461. // SVG complains about empty path strings
  1462. return str || 'M0 0';
  1463. }
  1464. /*
  1465. * @namespace Browser
  1466. * @aka L.Browser
  1467. *
  1468. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1469. *
  1470. * @example
  1471. *
  1472. * ```js
  1473. * if (L.Browser.ielt9) {
  1474. * alert('Upgrade your browser, dude!');
  1475. * }
  1476. * ```
  1477. */
  1478. var style$1 = document.documentElement.style;
  1479. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1480. var ie = 'ActiveXObject' in window;
  1481. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1482. var ielt9 = ie && !document.addEventListener;
  1483. // @property edge: Boolean; `true` for the Edge web browser.
  1484. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1485. // @property webkit: Boolean;
  1486. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1487. var webkit = userAgentContains('webkit');
  1488. // @property android: Boolean
  1489. // `true` for any browser running on an Android platform.
  1490. var android = userAgentContains('android');
  1491. // @property android23: Boolean; `true` for browsers running on Android 2 or Android 3.
  1492. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1493. // @property opera: Boolean; `true` for the Opera browser
  1494. var opera = !!window.opera;
  1495. // @property chrome: Boolean; `true` for the Chrome browser.
  1496. var chrome = userAgentContains('chrome');
  1497. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1498. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1499. // @property safari: Boolean; `true` for the Safari browser.
  1500. var safari = !chrome && userAgentContains('safari');
  1501. var phantom = userAgentContains('phantom');
  1502. // @property opera12: Boolean
  1503. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1504. var opera12 = 'OTransition' in style$1;
  1505. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1506. var win = navigator.platform.indexOf('Win') === 0;
  1507. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1508. var ie3d = ie && ('transition' in style$1);
  1509. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1510. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1511. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1512. var gecko3d = 'MozPerspective' in style$1;
  1513. // @property any3d: Boolean
  1514. // `true` for all browsers supporting CSS transforms.
  1515. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1516. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1517. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1518. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1519. var mobileWebkit = mobile && webkit;
  1520. // @property mobileWebkit3d: Boolean
  1521. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1522. var mobileWebkit3d = mobile && webkit3d;
  1523. // @property msPointer: Boolean
  1524. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1525. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1526. // @property pointer: Boolean
  1527. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1528. var pointer = !!(window.PointerEvent || msPointer);
  1529. // @property touch: Boolean
  1530. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1531. // This does not necessarily mean that the browser is running in a computer with
  1532. // a touchscreen, it only means that the browser is capable of understanding
  1533. // touch events.
  1534. var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
  1535. (window.DocumentTouch && document instanceof window.DocumentTouch));
  1536. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1537. var mobileOpera = mobile && opera;
  1538. // @property mobileGecko: Boolean
  1539. // `true` for gecko-based browsers running in a mobile device.
  1540. var mobileGecko = mobile && gecko;
  1541. // @property retina: Boolean
  1542. // `true` for browsers on a high-resolution "retina" screen.
  1543. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1544. // @property canvas: Boolean
  1545. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1546. var canvas = (function () {
  1547. return !!document.createElement('canvas').getContext;
  1548. }());
  1549. // @property svg: Boolean
  1550. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1551. var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1552. // @property vml: Boolean
  1553. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1554. var vml = !svg && (function () {
  1555. try {
  1556. var div = document.createElement('div');
  1557. div.innerHTML = '<v:shape adj="1"/>';
  1558. var shape = div.firstChild;
  1559. shape.style.behavior = 'url(#default#VML)';
  1560. return shape && (typeof shape.adj === 'object');
  1561. } catch (e) {
  1562. return false;
  1563. }
  1564. }());
  1565. function userAgentContains(str) {
  1566. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1567. }
  1568. var Browser = (Object.freeze || Object)({
  1569. ie: ie,
  1570. ielt9: ielt9,
  1571. edge: edge,
  1572. webkit: webkit,
  1573. android: android,
  1574. android23: android23,
  1575. opera: opera,
  1576. chrome: chrome,
  1577. gecko: gecko,
  1578. safari: safari,
  1579. phantom: phantom,
  1580. opera12: opera12,
  1581. win: win,
  1582. ie3d: ie3d,
  1583. webkit3d: webkit3d,
  1584. gecko3d: gecko3d,
  1585. any3d: any3d,
  1586. mobile: mobile,
  1587. mobileWebkit: mobileWebkit,
  1588. mobileWebkit3d: mobileWebkit3d,
  1589. msPointer: msPointer,
  1590. pointer: pointer,
  1591. touch: touch,
  1592. mobileOpera: mobileOpera,
  1593. mobileGecko: mobileGecko,
  1594. retina: retina,
  1595. canvas: canvas,
  1596. svg: svg,
  1597. vml: vml
  1598. });
  1599. /*
  1600. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1601. */
  1602. var POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';
  1603. var POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';
  1604. var POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';
  1605. var POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';
  1606. var TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION'];
  1607. var _pointers = {};
  1608. var _pointerDocListener = false;
  1609. // DomEvent.DoubleTap needs to know about this
  1610. var _pointersCount = 0;
  1611. // Provides a touch events wrapper for (ms)pointer events.
  1612. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1613. function addPointerListener(obj, type, handler, id) {
  1614. if (type === 'touchstart') {
  1615. _addPointerStart(obj, handler, id);
  1616. } else if (type === 'touchmove') {
  1617. _addPointerMove(obj, handler, id);
  1618. } else if (type === 'touchend') {
  1619. _addPointerEnd(obj, handler, id);
  1620. }
  1621. return this;
  1622. }
  1623. function removePointerListener(obj, type, id) {
  1624. var handler = obj['_leaflet_' + type + id];
  1625. if (type === 'touchstart') {
  1626. obj.removeEventListener(POINTER_DOWN, handler, false);
  1627. } else if (type === 'touchmove') {
  1628. obj.removeEventListener(POINTER_MOVE, handler, false);
  1629. } else if (type === 'touchend') {
  1630. obj.removeEventListener(POINTER_UP, handler, false);
  1631. obj.removeEventListener(POINTER_CANCEL, handler, false);
  1632. }
  1633. return this;
  1634. }
  1635. function _addPointerStart(obj, handler, id) {
  1636. var onDown = bind(function (e) {
  1637. if (e.pointerType !== 'mouse' && e.pointerType !== e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
  1638. // In IE11, some touch events needs to fire for form controls, or
  1639. // the controls will stop working. We keep a whitelist of tag names that
  1640. // need these events. For other target tags, we prevent default on the event.
  1641. if (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
  1642. preventDefault(e);
  1643. } else {
  1644. return;
  1645. }
  1646. }
  1647. _handlePointer(e, handler);
  1648. });
  1649. obj['_leaflet_touchstart' + id] = onDown;
  1650. obj.addEventListener(POINTER_DOWN, onDown, false);
  1651. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1652. if (!_pointerDocListener) {
  1653. // we listen documentElement as any drags that end by moving the touch off the screen get fired there
  1654. document.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1655. document.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1656. document.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true);
  1657. document.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1658. _pointerDocListener = true;
  1659. }
  1660. }
  1661. function _globalPointerDown(e) {
  1662. _pointers[e.pointerId] = e;
  1663. _pointersCount++;
  1664. }
  1665. function _globalPointerMove(e) {
  1666. if (_pointers[e.pointerId]) {
  1667. _pointers[e.pointerId] = e;
  1668. }
  1669. }
  1670. function _globalPointerUp(e) {
  1671. delete _pointers[e.pointerId];
  1672. _pointersCount--;
  1673. }
  1674. function _handlePointer(e, handler) {
  1675. e.touches = [];
  1676. for (var i in _pointers) {
  1677. e.touches.push(_pointers[i]);
  1678. }
  1679. e.changedTouches = [e];
  1680. handler(e);
  1681. }
  1682. function _addPointerMove(obj, handler, id) {
  1683. var onMove = function (e) {
  1684. // don't fire touch moves when mouse isn't down
  1685. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
  1686. _handlePointer(e, handler);
  1687. };
  1688. obj['_leaflet_touchmove' + id] = onMove;
  1689. obj.addEventListener(POINTER_MOVE, onMove, false);
  1690. }
  1691. function _addPointerEnd(obj, handler, id) {
  1692. var onUp = function (e) {
  1693. _handlePointer(e, handler);
  1694. };
  1695. obj['_leaflet_touchend' + id] = onUp;
  1696. obj.addEventListener(POINTER_UP, onUp, false);
  1697. obj.addEventListener(POINTER_CANCEL, onUp, false);
  1698. }
  1699. /*
  1700. * Extends the event handling code with double tap support for mobile browsers.
  1701. */
  1702. var _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';
  1703. var _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';
  1704. var _pre = '_leaflet_';
  1705. // inspired by Zepto touch code by Thomas Fuchs
  1706. function addDoubleTapListener(obj, handler, id) {
  1707. var last, touch$$1,
  1708. doubleTap = false,
  1709. delay = 250;
  1710. function onTouchStart(e) {
  1711. var count;
  1712. if (pointer) {
  1713. if ((!edge) || e.pointerType === 'mouse') { return; }
  1714. count = _pointersCount;
  1715. } else {
  1716. count = e.touches.length;
  1717. }
  1718. if (count > 1) { return; }
  1719. var now = Date.now(),
  1720. delta = now - (last || now);
  1721. touch$$1 = e.touches ? e.touches[0] : e;
  1722. doubleTap = (delta > 0 && delta <= delay);
  1723. last = now;
  1724. }
  1725. function onTouchEnd(e) {
  1726. if (doubleTap && !touch$$1.cancelBubble) {
  1727. if (pointer) {
  1728. if ((!edge) || e.pointerType === 'mouse') { return; }
  1729. // work around .type being readonly with MSPointer* events
  1730. var newTouch = {},
  1731. prop, i;
  1732. for (i in touch$$1) {
  1733. prop = touch$$1[i];
  1734. newTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;
  1735. }
  1736. touch$$1 = newTouch;
  1737. }
  1738. touch$$1.type = 'dblclick';
  1739. handler(touch$$1);
  1740. last = null;
  1741. }
  1742. }
  1743. obj[_pre + _touchstart + id] = onTouchStart;
  1744. obj[_pre + _touchend + id] = onTouchEnd;
  1745. obj[_pre + 'dblclick' + id] = handler;
  1746. obj.addEventListener(_touchstart, onTouchStart, false);
  1747. obj.addEventListener(_touchend, onTouchEnd, false);
  1748. // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
  1749. // the browser doesn't fire touchend/pointerup events but does fire
  1750. // native dblclicks. See #4127.
  1751. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
  1752. obj.addEventListener('dblclick', handler, false);
  1753. return this;
  1754. }
  1755. function removeDoubleTapListener(obj, id) {
  1756. var touchstart = obj[_pre + _touchstart + id],
  1757. touchend = obj[_pre + _touchend + id],
  1758. dblclick = obj[_pre + 'dblclick' + id];
  1759. obj.removeEventListener(_touchstart, touchstart, false);
  1760. obj.removeEventListener(_touchend, touchend, false);
  1761. if (!edge) {
  1762. obj.removeEventListener('dblclick', dblclick, false);
  1763. }
  1764. return this;
  1765. }
  1766. /*
  1767. * @namespace DomEvent
  1768. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  1769. */
  1770. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  1771. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  1772. // Adds a listener function (`fn`) to a particular DOM event type of the
  1773. // element `el`. You can optionally specify the context of the listener
  1774. // (object the `this` keyword will point to). You can also pass several
  1775. // space-separated types (e.g. `'click dblclick'`).
  1776. // @alternative
  1777. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  1778. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  1779. function on(obj, types, fn, context) {
  1780. if (typeof types === 'object') {
  1781. for (var type in types) {
  1782. addOne(obj, type, types[type], fn);
  1783. }
  1784. } else {
  1785. types = splitWords(types);
  1786. for (var i = 0, len = types.length; i < len; i++) {
  1787. addOne(obj, types[i], fn, context);
  1788. }
  1789. }
  1790. return this;
  1791. }
  1792. var eventsKey = '_leaflet_events';
  1793. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  1794. // Removes a previously added listener function. If no function is specified,
  1795. // it will remove all the listeners of that particular DOM event from the element.
  1796. // Note that if you passed a custom context to on, you must pass the same
  1797. // context to `off` in order to remove the listener.
  1798. // @alternative
  1799. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  1800. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  1801. // @alternative
  1802. // @function off(el: HTMLElement): this
  1803. // Removes all known event listeners
  1804. function off(obj, types, fn, context) {
  1805. if (typeof types === 'object') {
  1806. for (var type in types) {
  1807. removeOne(obj, type, types[type], fn);
  1808. }
  1809. } else if (types) {
  1810. types = splitWords(types);
  1811. for (var i = 0, len = types.length; i < len; i++) {
  1812. removeOne(obj, types[i], fn, context);
  1813. }
  1814. } else {
  1815. for (var j in obj[eventsKey]) {
  1816. removeOne(obj, j, obj[eventsKey][j]);
  1817. }
  1818. delete obj[eventsKey];
  1819. }
  1820. return this;
  1821. }
  1822. function addOne(obj, type, fn, context) {
  1823. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  1824. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  1825. var handler = function (e) {
  1826. return fn.call(context || obj, e || window.event);
  1827. };
  1828. var originalHandler = handler;
  1829. if (pointer && type.indexOf('touch') === 0) {
  1830. // Needs DomEvent.Pointer.js
  1831. addPointerListener(obj, type, handler, id);
  1832. } else if (touch && (type === 'dblclick') && addDoubleTapListener &&
  1833. !(pointer && chrome)) {
  1834. // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener
  1835. // See #5180
  1836. addDoubleTapListener(obj, handler, id);
  1837. } else if ('addEventListener' in obj) {
  1838. if (type === 'mousewheel') {
  1839. obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  1840. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  1841. handler = function (e) {
  1842. e = e || window.event;
  1843. if (isExternalTarget(obj, e)) {
  1844. originalHandler(e);
  1845. }
  1846. };
  1847. obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
  1848. } else {
  1849. if (type === 'click' && android) {
  1850. handler = function (e) {
  1851. filterClick(e, originalHandler);
  1852. };
  1853. }
  1854. obj.addEventListener(type, handler, false);
  1855. }
  1856. } else if ('attachEvent' in obj) {
  1857. obj.attachEvent('on' + type, handler);
  1858. }
  1859. obj[eventsKey] = obj[eventsKey] || {};
  1860. obj[eventsKey][id] = handler;
  1861. }
  1862. function removeOne(obj, type, fn, context) {
  1863. var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),
  1864. handler = obj[eventsKey] && obj[eventsKey][id];
  1865. if (!handler) { return this; }
  1866. if (pointer && type.indexOf('touch') === 0) {
  1867. removePointerListener(obj, type, id);
  1868. } else if (touch && (type === 'dblclick') && removeDoubleTapListener) {
  1869. removeDoubleTapListener(obj, id);
  1870. } else if ('removeEventListener' in obj) {
  1871. if (type === 'mousewheel') {
  1872. obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  1873. } else {
  1874. obj.removeEventListener(
  1875. type === 'mouseenter' ? 'mouseover' :
  1876. type === 'mouseleave' ? 'mouseout' : type, handler, false);
  1877. }
  1878. } else if ('detachEvent' in obj) {
  1879. obj.detachEvent('on' + type, handler);
  1880. }
  1881. obj[eventsKey][id] = null;
  1882. }
  1883. // @function stopPropagation(ev: DOMEvent): this
  1884. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  1885. // ```js
  1886. // L.DomEvent.on(div, 'click', function (ev) {
  1887. // L.DomEvent.stopPropagation(ev);
  1888. // });
  1889. // ```
  1890. function stopPropagation(e) {
  1891. if (e.stopPropagation) {
  1892. e.stopPropagation();
  1893. } else if (e.originalEvent) { // In case of Leaflet event.
  1894. e.originalEvent._stopped = true;
  1895. } else {
  1896. e.cancelBubble = true;
  1897. }
  1898. skipped(e);
  1899. return this;
  1900. }
  1901. // @function disableScrollPropagation(el: HTMLElement): this
  1902. // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
  1903. function disableScrollPropagation(el) {
  1904. addOne(el, 'mousewheel', stopPropagation);
  1905. return this;
  1906. }
  1907. // @function disableClickPropagation(el: HTMLElement): this
  1908. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  1909. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  1910. function disableClickPropagation(el) {
  1911. on(el, 'mousedown touchstart dblclick', stopPropagation);
  1912. addOne(el, 'click', fakeStop);
  1913. return this;
  1914. }
  1915. // @function preventDefault(ev: DOMEvent): this
  1916. // Prevents the default action of the DOM Event `ev` from happening (such as
  1917. // following a link in the href of the a element, or doing a POST request
  1918. // with page reload when a `<form>` is submitted).
  1919. // Use it inside listener functions.
  1920. function preventDefault(e) {
  1921. if (e.preventDefault) {
  1922. e.preventDefault();
  1923. } else {
  1924. e.returnValue = false;
  1925. }
  1926. return this;
  1927. }
  1928. // @function stop(ev): this
  1929. // Does `stopPropagation` and `preventDefault` at the same time.
  1930. function stop(e) {
  1931. preventDefault(e);
  1932. stopPropagation(e);
  1933. return this;
  1934. }
  1935. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  1936. // Gets normalized mouse position from a DOM event relative to the
  1937. // `container` or to the whole page if not specified.
  1938. function getMousePosition(e, container) {
  1939. if (!container) {
  1940. return new Point(e.clientX, e.clientY);
  1941. }
  1942. var rect = container.getBoundingClientRect();
  1943. return new Point(
  1944. e.clientX - rect.left - container.clientLeft,
  1945. e.clientY - rect.top - container.clientTop);
  1946. }
  1947. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  1948. // and Firefox scrolls device pixels, not CSS pixels
  1949. var wheelPxFactor =
  1950. (win && chrome) ? 2 * window.devicePixelRatio :
  1951. gecko ? window.devicePixelRatio : 1;
  1952. // @function getWheelDelta(ev: DOMEvent): Number
  1953. // Gets normalized wheel delta from a mousewheel DOM event, in vertical
  1954. // pixels scrolled (negative if scrolling down).
  1955. // Events from pointing devices without precise scrolling are mapped to
  1956. // a best guess of 60 pixels.
  1957. function getWheelDelta(e) {
  1958. return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  1959. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  1960. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  1961. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  1962. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  1963. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  1964. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  1965. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  1966. 0;
  1967. }
  1968. var skipEvents = {};
  1969. function fakeStop(e) {
  1970. // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)
  1971. skipEvents[e.type] = true;
  1972. }
  1973. function skipped(e) {
  1974. var events = skipEvents[e.type];
  1975. // reset when checking, as it's only used in map container and propagates outside of the map
  1976. skipEvents[e.type] = false;
  1977. return events;
  1978. }
  1979. // check if element really left/entered the event target (for mouseenter/mouseleave)
  1980. function isExternalTarget(el, e) {
  1981. var related = e.relatedTarget;
  1982. if (!related) { return true; }
  1983. try {
  1984. while (related && (related !== el)) {
  1985. related = related.parentNode;
  1986. }
  1987. } catch (err) {
  1988. return false;
  1989. }
  1990. return (related !== el);
  1991. }
  1992. var lastClick;
  1993. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  1994. function filterClick(e, handler) {
  1995. var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
  1996. elapsed = lastClick && (timeStamp - lastClick);
  1997. // are they closer together than 500ms yet more than 100ms?
  1998. // Android typically triggers them ~300ms apart while multiple listeners
  1999. // on the same event should be triggered far faster;
  2000. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  2001. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  2002. stop(e);
  2003. return;
  2004. }
  2005. lastClick = timeStamp;
  2006. handler(e);
  2007. }
  2008. var DomEvent = (Object.freeze || Object)({
  2009. on: on,
  2010. off: off,
  2011. stopPropagation: stopPropagation,
  2012. disableScrollPropagation: disableScrollPropagation,
  2013. disableClickPropagation: disableClickPropagation,
  2014. preventDefault: preventDefault,
  2015. stop: stop,
  2016. getMousePosition: getMousePosition,
  2017. getWheelDelta: getWheelDelta,
  2018. fakeStop: fakeStop,
  2019. skipped: skipped,
  2020. isExternalTarget: isExternalTarget,
  2021. addListener: on,
  2022. removeListener: off
  2023. });
  2024. /*
  2025. * @namespace DomUtil
  2026. *
  2027. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  2028. * tree, used by Leaflet internally.
  2029. *
  2030. * Most functions expecting or returning a `HTMLElement` also work for
  2031. * SVG elements. The only difference is that classes refer to CSS classes
  2032. * in HTML and SVG classes in SVG.
  2033. */
  2034. // @property TRANSFORM: String
  2035. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  2036. var TRANSFORM = testProp(
  2037. ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  2038. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  2039. // the same for the transitionend event, in particular the Android 4.1 stock browser
  2040. // @property TRANSITION: String
  2041. // Vendor-prefixed transition style name.
  2042. var TRANSITION = testProp(
  2043. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  2044. // @property TRANSITION_END: String
  2045. // Vendor-prefixed transitionend event name.
  2046. var TRANSITION_END =
  2047. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  2048. // @function get(id: String|HTMLElement): HTMLElement
  2049. // Returns an element given its DOM id, or returns the element itself
  2050. // if it was passed directly.
  2051. function get(id) {
  2052. return typeof id === 'string' ? document.getElementById(id) : id;
  2053. }
  2054. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  2055. // Returns the value for a certain style attribute on an element,
  2056. // including computed values or values set through CSS.
  2057. function getStyle(el, style) {
  2058. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  2059. if ((!value || value === 'auto') && document.defaultView) {
  2060. var css = document.defaultView.getComputedStyle(el, null);
  2061. value = css ? css[style] : null;
  2062. }
  2063. return value === 'auto' ? null : value;
  2064. }
  2065. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  2066. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  2067. function create$1(tagName, className, container) {
  2068. var el = document.createElement(tagName);
  2069. el.className = className || '';
  2070. if (container) {
  2071. container.appendChild(el);
  2072. }
  2073. return el;
  2074. }
  2075. // @function remove(el: HTMLElement)
  2076. // Removes `el` from its parent element
  2077. function remove(el) {
  2078. var parent = el.parentNode;
  2079. if (parent) {
  2080. parent.removeChild(el);
  2081. }
  2082. }
  2083. // @function empty(el: HTMLElement)
  2084. // Removes all of `el`'s children elements from `el`
  2085. function empty(el) {
  2086. while (el.firstChild) {
  2087. el.removeChild(el.firstChild);
  2088. }
  2089. }
  2090. // @function toFront(el: HTMLElement)
  2091. // Makes `el` the last child of its parent, so it renders in front of the other children.
  2092. function toFront(el) {
  2093. var parent = el.parentNode;
  2094. if (parent.lastChild !== el) {
  2095. parent.appendChild(el);
  2096. }
  2097. }
  2098. // @function toBack(el: HTMLElement)
  2099. // Makes `el` the first child of its parent, so it renders behind the other children.
  2100. function toBack(el) {
  2101. var parent = el.parentNode;
  2102. if (parent.firstChild !== el) {
  2103. parent.insertBefore(el, parent.firstChild);
  2104. }
  2105. }
  2106. // @function hasClass(el: HTMLElement, name: String): Boolean
  2107. // Returns `true` if the element's class attribute contains `name`.
  2108. function hasClass(el, name) {
  2109. if (el.classList !== undefined) {
  2110. return el.classList.contains(name);
  2111. }
  2112. var className = getClass(el);
  2113. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  2114. }
  2115. // @function addClass(el: HTMLElement, name: String)
  2116. // Adds `name` to the element's class attribute.
  2117. function addClass(el, name) {
  2118. if (el.classList !== undefined) {
  2119. var classes = splitWords(name);
  2120. for (var i = 0, len = classes.length; i < len; i++) {
  2121. el.classList.add(classes[i]);
  2122. }
  2123. } else if (!hasClass(el, name)) {
  2124. var className = getClass(el);
  2125. setClass(el, (className ? className + ' ' : '') + name);
  2126. }
  2127. }
  2128. // @function removeClass(el: HTMLElement, name: String)
  2129. // Removes `name` from the element's class attribute.
  2130. function removeClass(el, name) {
  2131. if (el.classList !== undefined) {
  2132. el.classList.remove(name);
  2133. } else {
  2134. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  2135. }
  2136. }
  2137. // @function setClass(el: HTMLElement, name: String)
  2138. // Sets the element's class.
  2139. function setClass(el, name) {
  2140. if (el.className.baseVal === undefined) {
  2141. el.className = name;
  2142. } else {
  2143. // in case of SVG element
  2144. el.className.baseVal = name;
  2145. }
  2146. }
  2147. // @function getClass(el: HTMLElement): String
  2148. // Returns the element's class.
  2149. function getClass(el) {
  2150. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  2151. }
  2152. // @function setOpacity(el: HTMLElement, opacity: Number)
  2153. // Set the opacity of an element (including old IE support).
  2154. // `opacity` must be a number from `0` to `1`.
  2155. function setOpacity(el, value) {
  2156. if ('opacity' in el.style) {
  2157. el.style.opacity = value;
  2158. } else if ('filter' in el.style) {
  2159. _setOpacityIE(el, value);
  2160. }
  2161. }
  2162. function _setOpacityIE(el, value) {
  2163. var filter = false,
  2164. filterName = 'DXImageTransform.Microsoft.Alpha';
  2165. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  2166. try {
  2167. filter = el.filters.item(filterName);
  2168. } catch (e) {
  2169. // don't set opacity to 1 if we haven't already set an opacity,
  2170. // it isn't needed and breaks transparent pngs.
  2171. if (value === 1) { return; }
  2172. }
  2173. value = Math.round(value * 100);
  2174. if (filter) {
  2175. filter.Enabled = (value !== 100);
  2176. filter.Opacity = value;
  2177. } else {
  2178. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  2179. }
  2180. }
  2181. // @function testProp(props: String[]): String|false
  2182. // Goes through the array of style names and returns the first name
  2183. // that is a valid style name for an element. If no such name is found,
  2184. // it returns false. Useful for vendor-prefixed styles like `transform`.
  2185. function testProp(props) {
  2186. var style = document.documentElement.style;
  2187. for (var i = 0; i < props.length; i++) {
  2188. if (props[i] in style) {
  2189. return props[i];
  2190. }
  2191. }
  2192. return false;
  2193. }
  2194. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  2195. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  2196. // and optionally scaled by `scale`. Does not have an effect if the
  2197. // browser doesn't support 3D CSS transforms.
  2198. function setTransform(el, offset, scale) {
  2199. var pos = offset || new Point(0, 0);
  2200. el.style[TRANSFORM] =
  2201. (ie3d ?
  2202. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2203. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2204. (scale ? ' scale(' + scale + ')' : '');
  2205. }
  2206. // @function setPosition(el: HTMLElement, position: Point)
  2207. // Sets the position of `el` to coordinates specified by `position`,
  2208. // using CSS translate or top/left positioning depending on the browser
  2209. // (used by Leaflet internally to position its layers).
  2210. function setPosition(el, point) {
  2211. /*eslint-disable */
  2212. el._leaflet_pos = point;
  2213. /*eslint-enable */
  2214. if (any3d) {
  2215. setTransform(el, point);
  2216. } else {
  2217. el.style.left = point.x + 'px';
  2218. el.style.top = point.y + 'px';
  2219. }
  2220. }
  2221. // @function getPosition(el: HTMLElement): Point
  2222. // Returns the coordinates of an element previously positioned with setPosition.
  2223. function getPosition(el) {
  2224. // this method is only used for elements previously positioned using setPosition,
  2225. // so it's safe to cache the position for performance
  2226. return el._leaflet_pos || new Point(0, 0);
  2227. }
  2228. // @function disableTextSelection()
  2229. // Prevents the user from generating `selectstart` DOM events, usually generated
  2230. // when the user drags the mouse through a page with text. Used internally
  2231. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2232. // the map. Affects drag interactions on the whole document.
  2233. // @function enableTextSelection()
  2234. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2235. var disableTextSelection;
  2236. var enableTextSelection;
  2237. var _userSelect;
  2238. if ('onselectstart' in document) {
  2239. disableTextSelection = function () {
  2240. on(window, 'selectstart', preventDefault);
  2241. };
  2242. enableTextSelection = function () {
  2243. off(window, 'selectstart', preventDefault);
  2244. };
  2245. } else {
  2246. var userSelectProperty = testProp(
  2247. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2248. disableTextSelection = function () {
  2249. if (userSelectProperty) {
  2250. var style = document.documentElement.style;
  2251. _userSelect = style[userSelectProperty];
  2252. style[userSelectProperty] = 'none';
  2253. }
  2254. };
  2255. enableTextSelection = function () {
  2256. if (userSelectProperty) {
  2257. document.documentElement.style[userSelectProperty] = _userSelect;
  2258. _userSelect = undefined;
  2259. }
  2260. };
  2261. }
  2262. // @function disableImageDrag()
  2263. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2264. // for `dragstart` DOM events, usually generated when the user drags an image.
  2265. function disableImageDrag() {
  2266. on(window, 'dragstart', preventDefault);
  2267. }
  2268. // @function enableImageDrag()
  2269. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2270. function enableImageDrag() {
  2271. off(window, 'dragstart', preventDefault);
  2272. }
  2273. var _outlineElement;
  2274. var _outlineStyle;
  2275. // @function preventOutline(el: HTMLElement)
  2276. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2277. // of the element `el` invisible. Used internally by Leaflet to prevent
  2278. // focusable elements from displaying an outline when the user performs a
  2279. // drag interaction on them.
  2280. function preventOutline(element) {
  2281. while (element.tabIndex === -1) {
  2282. element = element.parentNode;
  2283. }
  2284. if (!element.style) { return; }
  2285. restoreOutline();
  2286. _outlineElement = element;
  2287. _outlineStyle = element.style.outline;
  2288. element.style.outline = 'none';
  2289. on(window, 'keydown', restoreOutline);
  2290. }
  2291. // @function restoreOutline()
  2292. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2293. function restoreOutline() {
  2294. if (!_outlineElement) { return; }
  2295. _outlineElement.style.outline = _outlineStyle;
  2296. _outlineElement = undefined;
  2297. _outlineStyle = undefined;
  2298. off(window, 'keydown', restoreOutline);
  2299. }
  2300. var DomUtil = (Object.freeze || Object)({
  2301. TRANSFORM: TRANSFORM,
  2302. TRANSITION: TRANSITION,
  2303. TRANSITION_END: TRANSITION_END,
  2304. get: get,
  2305. getStyle: getStyle,
  2306. create: create$1,
  2307. remove: remove,
  2308. empty: empty,
  2309. toFront: toFront,
  2310. toBack: toBack,
  2311. hasClass: hasClass,
  2312. addClass: addClass,
  2313. removeClass: removeClass,
  2314. setClass: setClass,
  2315. getClass: getClass,
  2316. setOpacity: setOpacity,
  2317. testProp: testProp,
  2318. setTransform: setTransform,
  2319. setPosition: setPosition,
  2320. getPosition: getPosition,
  2321. disableTextSelection: disableTextSelection,
  2322. enableTextSelection: enableTextSelection,
  2323. disableImageDrag: disableImageDrag,
  2324. enableImageDrag: enableImageDrag,
  2325. preventOutline: preventOutline,
  2326. restoreOutline: restoreOutline
  2327. });
  2328. /*
  2329. * @class PosAnimation
  2330. * @aka L.PosAnimation
  2331. * @inherits Evented
  2332. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2333. *
  2334. * @example
  2335. * ```js
  2336. * var fx = new L.PosAnimation();
  2337. * fx.run(el, [300, 500], 0.5);
  2338. * ```
  2339. *
  2340. * @constructor L.PosAnimation()
  2341. * Creates a `PosAnimation` object.
  2342. *
  2343. */
  2344. var PosAnimation = Evented.extend({
  2345. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2346. // Run an animation of a given element to a new position, optionally setting
  2347. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2348. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  2349. // `0.5` by default).
  2350. run: function (el, newPos, duration, easeLinearity) {
  2351. this.stop();
  2352. this._el = el;
  2353. this._inProgress = true;
  2354. this._duration = duration || 0.25;
  2355. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2356. this._startPos = getPosition(el);
  2357. this._offset = newPos.subtract(this._startPos);
  2358. this._startTime = +new Date();
  2359. // @event start: Event
  2360. // Fired when the animation starts
  2361. this.fire('start');
  2362. this._animate();
  2363. },
  2364. // @method stop()
  2365. // Stops the animation (if currently running).
  2366. stop: function () {
  2367. if (!this._inProgress) { return; }
  2368. this._step(true);
  2369. this._complete();
  2370. },
  2371. _animate: function () {
  2372. // animation loop
  2373. this._animId = requestAnimFrame(this._animate, this);
  2374. this._step();
  2375. },
  2376. _step: function (round) {
  2377. var elapsed = (+new Date()) - this._startTime,
  2378. duration = this._duration * 1000;
  2379. if (elapsed < duration) {
  2380. this._runFrame(this._easeOut(elapsed / duration), round);
  2381. } else {
  2382. this._runFrame(1);
  2383. this._complete();
  2384. }
  2385. },
  2386. _runFrame: function (progress, round) {
  2387. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2388. if (round) {
  2389. pos._round();
  2390. }
  2391. setPosition(this._el, pos);
  2392. // @event step: Event
  2393. // Fired continuously during the animation.
  2394. this.fire('step');
  2395. },
  2396. _complete: function () {
  2397. cancelAnimFrame(this._animId);
  2398. this._inProgress = false;
  2399. // @event end: Event
  2400. // Fired when the animation ends.
  2401. this.fire('end');
  2402. },
  2403. _easeOut: function (t) {
  2404. return 1 - Math.pow(1 - t, this._easeOutPower);
  2405. }
  2406. });
  2407. /*
  2408. * @class Map
  2409. * @aka L.Map
  2410. * @inherits Evented
  2411. *
  2412. * The central class of the API — it is used to create a map on a page and manipulate it.
  2413. *
  2414. * @example
  2415. *
  2416. * ```js
  2417. * // initialize the map on the "map" div with a given center and zoom
  2418. * var map = L.map('map', {
  2419. * center: [51.505, -0.09],
  2420. * zoom: 13
  2421. * });
  2422. * ```
  2423. *
  2424. */
  2425. var Map = Evented.extend({
  2426. options: {
  2427. // @section Map State Options
  2428. // @option crs: CRS = L.CRS.EPSG3857
  2429. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2430. // sure what it means.
  2431. crs: EPSG3857,
  2432. // @option center: LatLng = undefined
  2433. // Initial geographic center of the map
  2434. center: undefined,
  2435. // @option zoom: Number = undefined
  2436. // Initial map zoom level
  2437. zoom: undefined,
  2438. // @option minZoom: Number = *
  2439. // Minimum zoom level of the map.
  2440. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2441. // the lowest of their `minZoom` options will be used instead.
  2442. minZoom: undefined,
  2443. // @option maxZoom: Number = *
  2444. // Maximum zoom level of the map.
  2445. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2446. // the highest of their `maxZoom` options will be used instead.
  2447. maxZoom: undefined,
  2448. // @option layers: Layer[] = []
  2449. // Array of layers that will be added to the map initially
  2450. layers: [],
  2451. // @option maxBounds: LatLngBounds = null
  2452. // When this option is set, the map restricts the view to the given
  2453. // geographical bounds, bouncing the user back if the user tries to pan
  2454. // outside the view. To set the restriction dynamically, use
  2455. // [`setMaxBounds`](#map-setmaxbounds) method.
  2456. maxBounds: undefined,
  2457. // @option renderer: Renderer = *
  2458. // The default method for drawing vector layers on the map. `L.SVG`
  2459. // or `L.Canvas` by default depending on browser support.
  2460. renderer: undefined,
  2461. // @section Animation Options
  2462. // @option zoomAnimation: Boolean = true
  2463. // Whether the map zoom animation is enabled. By default it's enabled
  2464. // in all browsers that support CSS3 Transitions except Android.
  2465. zoomAnimation: true,
  2466. // @option zoomAnimationThreshold: Number = 4
  2467. // Won't animate zoom if the zoom difference exceeds this value.
  2468. zoomAnimationThreshold: 4,
  2469. // @option fadeAnimation: Boolean = true
  2470. // Whether the tile fade animation is enabled. By default it's enabled
  2471. // in all browsers that support CSS3 Transitions except Android.
  2472. fadeAnimation: true,
  2473. // @option markerZoomAnimation: Boolean = true
  2474. // Whether markers animate their zoom with the zoom animation, if disabled
  2475. // they will disappear for the length of the animation. By default it's
  2476. // enabled in all browsers that support CSS3 Transitions except Android.
  2477. markerZoomAnimation: true,
  2478. // @option transform3DLimit: Number = 2^23
  2479. // Defines the maximum size of a CSS translation transform. The default
  2480. // value should not be changed unless a web browser positions layers in
  2481. // the wrong place after doing a large `panBy`.
  2482. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2483. // @section Interaction Options
  2484. // @option zoomSnap: Number = 1
  2485. // Forces the map's zoom level to always be a multiple of this, particularly
  2486. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2487. // By default, the zoom level snaps to the nearest integer; lower values
  2488. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2489. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2490. zoomSnap: 1,
  2491. // @option zoomDelta: Number = 1
  2492. // Controls how much the map's zoom level will change after a
  2493. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2494. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2495. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2496. zoomDelta: 1,
  2497. // @option trackResize: Boolean = true
  2498. // Whether the map automatically handles browser window resize to update itself.
  2499. trackResize: true
  2500. },
  2501. initialize: function (id, options) { // (HTMLElement or String, Object)
  2502. options = setOptions(this, options);
  2503. this._initContainer(id);
  2504. this._initLayout();
  2505. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2506. this._onResize = bind(this._onResize, this);
  2507. this._initEvents();
  2508. if (options.maxBounds) {
  2509. this.setMaxBounds(options.maxBounds);
  2510. }
  2511. if (options.zoom !== undefined) {
  2512. this._zoom = this._limitZoom(options.zoom);
  2513. }
  2514. if (options.center && options.zoom !== undefined) {
  2515. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2516. }
  2517. this._handlers = [];
  2518. this._layers = {};
  2519. this._zoomBoundLayers = {};
  2520. this._sizeChanged = true;
  2521. this.callInitHooks();
  2522. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2523. this._zoomAnimated = TRANSITION && any3d && !mobileOpera &&
  2524. this.options.zoomAnimation;
  2525. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2526. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2527. if (this._zoomAnimated) {
  2528. this._createAnimProxy();
  2529. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2530. }
  2531. this._addLayers(this.options.layers);
  2532. },
  2533. // @section Methods for modifying map state
  2534. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2535. // Sets the view of the map (geographical center and zoom) with the given
  2536. // animation options.
  2537. setView: function (center, zoom, options) {
  2538. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2539. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2540. options = options || {};
  2541. this._stop();
  2542. if (this._loaded && !options.reset && options !== true) {
  2543. if (options.animate !== undefined) {
  2544. options.zoom = extend({animate: options.animate}, options.zoom);
  2545. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2546. }
  2547. // try animating pan or zoom
  2548. var moved = (this._zoom !== zoom) ?
  2549. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2550. this._tryAnimatedPan(center, options.pan);
  2551. if (moved) {
  2552. // prevent resize handler call, the view will refresh after animation anyway
  2553. clearTimeout(this._sizeTimer);
  2554. return this;
  2555. }
  2556. }
  2557. // animation didn't start, just reset the map view
  2558. this._resetView(center, zoom);
  2559. return this;
  2560. },
  2561. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2562. // Sets the zoom of the map.
  2563. setZoom: function (zoom, options) {
  2564. if (!this._loaded) {
  2565. this._zoom = zoom;
  2566. return this;
  2567. }
  2568. return this.setView(this.getCenter(), zoom, {zoom: options});
  2569. },
  2570. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2571. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2572. zoomIn: function (delta, options) {
  2573. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2574. return this.setZoom(this._zoom + delta, options);
  2575. },
  2576. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2577. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2578. zoomOut: function (delta, options) {
  2579. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2580. return this.setZoom(this._zoom - delta, options);
  2581. },
  2582. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2583. // Zooms the map while keeping a specified geographical point on the map
  2584. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2585. // @alternative
  2586. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2587. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2588. setZoomAround: function (latlng, zoom, options) {
  2589. var scale = this.getZoomScale(zoom),
  2590. viewHalf = this.getSize().divideBy(2),
  2591. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2592. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2593. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2594. return this.setView(newCenter, zoom, {zoom: options});
  2595. },
  2596. _getBoundsCenterZoom: function (bounds, options) {
  2597. options = options || {};
  2598. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2599. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2600. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2601. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2602. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2603. if (zoom === Infinity) {
  2604. return {
  2605. center: bounds.getCenter(),
  2606. zoom: zoom
  2607. };
  2608. }
  2609. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2610. swPoint = this.project(bounds.getSouthWest(), zoom),
  2611. nePoint = this.project(bounds.getNorthEast(), zoom),
  2612. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2613. return {
  2614. center: center,
  2615. zoom: zoom
  2616. };
  2617. },
  2618. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2619. // Sets a map view that contains the given geographical bounds with the
  2620. // maximum zoom level possible.
  2621. fitBounds: function (bounds, options) {
  2622. bounds = toLatLngBounds(bounds);
  2623. if (!bounds.isValid()) {
  2624. throw new Error('Bounds are not valid.');
  2625. }
  2626. var target = this._getBoundsCenterZoom(bounds, options);
  2627. return this.setView(target.center, target.zoom, options);
  2628. },
  2629. // @method fitWorld(options?: fitBounds options): this
  2630. // Sets a map view that mostly contains the whole world with the maximum
  2631. // zoom level possible.
  2632. fitWorld: function (options) {
  2633. return this.fitBounds([[-90, -180], [90, 180]], options);
  2634. },
  2635. // @method panTo(latlng: LatLng, options?: Pan options): this
  2636. // Pans the map to a given center.
  2637. panTo: function (center, options) { // (LatLng)
  2638. return this.setView(center, this._zoom, {pan: options});
  2639. },
  2640. // @method panBy(offset: Point, options?: Pan options): this
  2641. // Pans the map by a given number of pixels (animated).
  2642. panBy: function (offset, options) {
  2643. offset = toPoint(offset).round();
  2644. options = options || {};
  2645. if (!offset.x && !offset.y) {
  2646. return this.fire('moveend');
  2647. }
  2648. // If we pan too far, Chrome gets issues with tiles
  2649. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2650. if (options.animate !== true && !this.getSize().contains(offset)) {
  2651. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2652. return this;
  2653. }
  2654. if (!this._panAnim) {
  2655. this._panAnim = new PosAnimation();
  2656. this._panAnim.on({
  2657. 'step': this._onPanTransitionStep,
  2658. 'end': this._onPanTransitionEnd
  2659. }, this);
  2660. }
  2661. // don't fire movestart if animating inertia
  2662. if (!options.noMoveStart) {
  2663. this.fire('movestart');
  2664. }
  2665. // animate pan unless animate: false specified
  2666. if (options.animate !== false) {
  2667. addClass(this._mapPane, 'leaflet-pan-anim');
  2668. var newPos = this._getMapPanePos().subtract(offset).round();
  2669. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2670. } else {
  2671. this._rawPanBy(offset);
  2672. this.fire('move').fire('moveend');
  2673. }
  2674. return this;
  2675. },
  2676. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2677. // Sets the view of the map (geographical center and zoom) performing a smooth
  2678. // pan-zoom animation.
  2679. flyTo: function (targetCenter, targetZoom, options) {
  2680. options = options || {};
  2681. if (options.animate === false || !any3d) {
  2682. return this.setView(targetCenter, targetZoom, options);
  2683. }
  2684. this._stop();
  2685. var from = this.project(this.getCenter()),
  2686. to = this.project(targetCenter),
  2687. size = this.getSize(),
  2688. startZoom = this._zoom;
  2689. targetCenter = toLatLng(targetCenter);
  2690. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2691. var w0 = Math.max(size.x, size.y),
  2692. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2693. u1 = (to.distanceTo(from)) || 1,
  2694. rho = 1.42,
  2695. rho2 = rho * rho;
  2696. function r(i) {
  2697. var s1 = i ? -1 : 1,
  2698. s2 = i ? w1 : w0,
  2699. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2700. b1 = 2 * s2 * rho2 * u1,
  2701. b = t1 / b1,
  2702. sq = Math.sqrt(b * b + 1) - b;
  2703. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2704. // thus triggering an infinite loop in flyTo
  2705. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2706. return log;
  2707. }
  2708. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2709. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2710. function tanh(n) { return sinh(n) / cosh(n); }
  2711. var r0 = r(0);
  2712. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2713. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2714. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2715. var start = Date.now(),
  2716. S = (r(1) - r0) / rho,
  2717. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2718. function frame() {
  2719. var t = (Date.now() - start) / duration,
  2720. s = easeOut(t) * S;
  2721. if (t <= 1) {
  2722. this._flyToFrame = requestAnimFrame(frame, this);
  2723. this._move(
  2724. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2725. this.getScaleZoom(w0 / w(s), startZoom),
  2726. {flyTo: true});
  2727. } else {
  2728. this
  2729. ._move(targetCenter, targetZoom)
  2730. ._moveEnd(true);
  2731. }
  2732. }
  2733. this._moveStart(true);
  2734. frame.call(this);
  2735. return this;
  2736. },
  2737. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2738. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2739. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2740. flyToBounds: function (bounds, options) {
  2741. var target = this._getBoundsCenterZoom(bounds, options);
  2742. return this.flyTo(target.center, target.zoom, options);
  2743. },
  2744. // @method setMaxBounds(bounds: Bounds): this
  2745. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2746. setMaxBounds: function (bounds) {
  2747. bounds = toLatLngBounds(bounds);
  2748. if (!bounds.isValid()) {
  2749. this.options.maxBounds = null;
  2750. return this.off('moveend', this._panInsideMaxBounds);
  2751. } else if (this.options.maxBounds) {
  2752. this.off('moveend', this._panInsideMaxBounds);
  2753. }
  2754. this.options.maxBounds = bounds;
  2755. if (this._loaded) {
  2756. this._panInsideMaxBounds();
  2757. }
  2758. return this.on('moveend', this._panInsideMaxBounds);
  2759. },
  2760. // @method setMinZoom(zoom: Number): this
  2761. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2762. setMinZoom: function (zoom) {
  2763. this.options.minZoom = zoom;
  2764. if (this._loaded && this.getZoom() < this.options.minZoom) {
  2765. return this.setZoom(zoom);
  2766. }
  2767. return this;
  2768. },
  2769. // @method setMaxZoom(zoom: Number): this
  2770. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2771. setMaxZoom: function (zoom) {
  2772. this.options.maxZoom = zoom;
  2773. if (this._loaded && (this.getZoom() > this.options.maxZoom)) {
  2774. return this.setZoom(zoom);
  2775. }
  2776. return this;
  2777. },
  2778. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2779. // Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.
  2780. panInsideBounds: function (bounds, options) {
  2781. this._enforcingBounds = true;
  2782. var center = this.getCenter(),
  2783. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2784. if (!center.equals(newCenter)) {
  2785. this.panTo(newCenter, options);
  2786. }
  2787. this._enforcingBounds = false;
  2788. return this;
  2789. },
  2790. // @method invalidateSize(options: Zoom/Pan options): this
  2791. // Checks if the map container size changed and updates the map if so —
  2792. // call it after you've changed the map size dynamically, also animating
  2793. // pan by default. If `options.pan` is `false`, panning will not occur.
  2794. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2795. // that it doesn't happen often even if the method is called many
  2796. // times in a row.
  2797. // @alternative
  2798. // @method invalidateSize(animate: Boolean): this
  2799. // Checks if the map container size changed and updates the map if so —
  2800. // call it after you've changed the map size dynamically, also animating
  2801. // pan by default.
  2802. invalidateSize: function (options) {
  2803. if (!this._loaded) { return this; }
  2804. options = extend({
  2805. animate: false,
  2806. pan: true
  2807. }, options === true ? {animate: true} : options);
  2808. var oldSize = this.getSize();
  2809. this._sizeChanged = true;
  2810. this._lastCenter = null;
  2811. var newSize = this.getSize(),
  2812. oldCenter = oldSize.divideBy(2).round(),
  2813. newCenter = newSize.divideBy(2).round(),
  2814. offset = oldCenter.subtract(newCenter);
  2815. if (!offset.x && !offset.y) { return this; }
  2816. if (options.animate && options.pan) {
  2817. this.panBy(offset);
  2818. } else {
  2819. if (options.pan) {
  2820. this._rawPanBy(offset);
  2821. }
  2822. this.fire('move');
  2823. if (options.debounceMoveend) {
  2824. clearTimeout(this._sizeTimer);
  2825. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  2826. } else {
  2827. this.fire('moveend');
  2828. }
  2829. }
  2830. // @section Map state change events
  2831. // @event resize: ResizeEvent
  2832. // Fired when the map is resized.
  2833. return this.fire('resize', {
  2834. oldSize: oldSize,
  2835. newSize: newSize
  2836. });
  2837. },
  2838. // @section Methods for modifying map state
  2839. // @method stop(): this
  2840. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2841. stop: function () {
  2842. this.setZoom(this._limitZoom(this._zoom));
  2843. if (!this.options.zoomSnap) {
  2844. this.fire('viewreset');
  2845. }
  2846. return this._stop();
  2847. },
  2848. // @section Geolocation methods
  2849. // @method locate(options?: Locate options): this
  2850. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  2851. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  2852. // and optionally sets the map view to the user's location with respect to
  2853. // detection accuracy (or to the world view if geolocation failed).
  2854. // Note that, if your page doesn't use HTTPS, this method will fail in
  2855. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  2856. // See `Locate options` for more details.
  2857. locate: function (options) {
  2858. options = this._locateOptions = extend({
  2859. timeout: 10000,
  2860. watch: false
  2861. // setView: false
  2862. // maxZoom: <Number>
  2863. // maximumAge: 0
  2864. // enableHighAccuracy: false
  2865. }, options);
  2866. if (!('geolocation' in navigator)) {
  2867. this._handleGeolocationError({
  2868. code: 0,
  2869. message: 'Geolocation not supported.'
  2870. });
  2871. return this;
  2872. }
  2873. var onResponse = bind(this._handleGeolocationResponse, this),
  2874. onError = bind(this._handleGeolocationError, this);
  2875. if (options.watch) {
  2876. this._locationWatchId =
  2877. navigator.geolocation.watchPosition(onResponse, onError, options);
  2878. } else {
  2879. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  2880. }
  2881. return this;
  2882. },
  2883. // @method stopLocate(): this
  2884. // Stops watching location previously initiated by `map.locate({watch: true})`
  2885. // and aborts resetting the map view if map.locate was called with
  2886. // `{setView: true}`.
  2887. stopLocate: function () {
  2888. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  2889. navigator.geolocation.clearWatch(this._locationWatchId);
  2890. }
  2891. if (this._locateOptions) {
  2892. this._locateOptions.setView = false;
  2893. }
  2894. return this;
  2895. },
  2896. _handleGeolocationError: function (error) {
  2897. var c = error.code,
  2898. message = error.message ||
  2899. (c === 1 ? 'permission denied' :
  2900. (c === 2 ? 'position unavailable' : 'timeout'));
  2901. if (this._locateOptions.setView && !this._loaded) {
  2902. this.fitWorld();
  2903. }
  2904. // @section Location events
  2905. // @event locationerror: ErrorEvent
  2906. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  2907. this.fire('locationerror', {
  2908. code: c,
  2909. message: 'Geolocation error: ' + message + '.'
  2910. });
  2911. },
  2912. _handleGeolocationResponse: function (pos) {
  2913. var lat = pos.coords.latitude,
  2914. lng = pos.coords.longitude,
  2915. latlng = new LatLng(lat, lng),
  2916. bounds = latlng.toBounds(pos.coords.accuracy),
  2917. options = this._locateOptions;
  2918. if (options.setView) {
  2919. var zoom = this.getBoundsZoom(bounds);
  2920. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  2921. }
  2922. var data = {
  2923. latlng: latlng,
  2924. bounds: bounds,
  2925. timestamp: pos.timestamp
  2926. };
  2927. for (var i in pos.coords) {
  2928. if (typeof pos.coords[i] === 'number') {
  2929. data[i] = pos.coords[i];
  2930. }
  2931. }
  2932. // @event locationfound: LocationEvent
  2933. // Fired when geolocation (using the [`locate`](#map-locate) method)
  2934. // went successfully.
  2935. this.fire('locationfound', data);
  2936. },
  2937. // TODO handler.addTo
  2938. // TODO Appropiate docs section?
  2939. // @section Other Methods
  2940. // @method addHandler(name: String, HandlerClass: Function): this
  2941. // Adds a new `Handler` to the map, given its name and constructor function.
  2942. addHandler: function (name, HandlerClass) {
  2943. if (!HandlerClass) { return this; }
  2944. var handler = this[name] = new HandlerClass(this);
  2945. this._handlers.push(handler);
  2946. if (this.options[name]) {
  2947. handler.enable();
  2948. }
  2949. return this;
  2950. },
  2951. // @method remove(): this
  2952. // Destroys the map and clears all related event listeners.
  2953. remove: function () {
  2954. this._initEvents(true);
  2955. if (this._containerId !== this._container._leaflet_id) {
  2956. throw new Error('Map container is being reused by another instance');
  2957. }
  2958. try {
  2959. // throws error in IE6-8
  2960. delete this._container._leaflet_id;
  2961. delete this._containerId;
  2962. } catch (e) {
  2963. /*eslint-disable */
  2964. this._container._leaflet_id = undefined;
  2965. /*eslint-enable */
  2966. this._containerId = undefined;
  2967. }
  2968. remove(this._mapPane);
  2969. if (this._clearControlPos) {
  2970. this._clearControlPos();
  2971. }
  2972. this._clearHandlers();
  2973. if (this._loaded) {
  2974. // @section Map state change events
  2975. // @event unload: Event
  2976. // Fired when the map is destroyed with [remove](#map-remove) method.
  2977. this.fire('unload');
  2978. }
  2979. var i;
  2980. for (i in this._layers) {
  2981. this._layers[i].remove();
  2982. }
  2983. for (i in this._panes) {
  2984. remove(this._panes[i]);
  2985. }
  2986. this._layers = [];
  2987. this._panes = [];
  2988. delete this._mapPane;
  2989. delete this._renderer;
  2990. return this;
  2991. },
  2992. // @section Other Methods
  2993. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  2994. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  2995. // then returns it. The pane is created as a child of `container`, or
  2996. // as a child of the main map pane if not set.
  2997. createPane: function (name, container) {
  2998. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  2999. pane = create$1('div', className, container || this._mapPane);
  3000. if (name) {
  3001. this._panes[name] = pane;
  3002. }
  3003. return pane;
  3004. },
  3005. // @section Methods for Getting Map State
  3006. // @method getCenter(): LatLng
  3007. // Returns the geographical center of the map view
  3008. getCenter: function () {
  3009. this._checkIfLoaded();
  3010. if (this._lastCenter && !this._moved()) {
  3011. return this._lastCenter;
  3012. }
  3013. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3014. },
  3015. // @method getZoom(): Number
  3016. // Returns the current zoom level of the map view
  3017. getZoom: function () {
  3018. return this._zoom;
  3019. },
  3020. // @method getBounds(): LatLngBounds
  3021. // Returns the geographical bounds visible in the current map view
  3022. getBounds: function () {
  3023. var bounds = this.getPixelBounds(),
  3024. sw = this.unproject(bounds.getBottomLeft()),
  3025. ne = this.unproject(bounds.getTopRight());
  3026. return new LatLngBounds(sw, ne);
  3027. },
  3028. // @method getMinZoom(): Number
  3029. // Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default.
  3030. getMinZoom: function () {
  3031. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3032. },
  3033. // @method getMaxZoom(): Number
  3034. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3035. getMaxZoom: function () {
  3036. return this.options.maxZoom === undefined ?
  3037. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3038. this.options.maxZoom;
  3039. },
  3040. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean): Number
  3041. // Returns the maximum zoom level on which the given bounds fit to the map
  3042. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3043. // instead returns the minimum zoom level on which the map view fits into
  3044. // the given bounds in its entirety.
  3045. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3046. bounds = toLatLngBounds(bounds);
  3047. padding = toPoint(padding || [0, 0]);
  3048. var zoom = this.getZoom() || 0,
  3049. min = this.getMinZoom(),
  3050. max = this.getMaxZoom(),
  3051. nw = bounds.getNorthWest(),
  3052. se = bounds.getSouthEast(),
  3053. size = this.getSize().subtract(padding),
  3054. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3055. snap = any3d ? this.options.zoomSnap : 1,
  3056. scalex = size.x / boundsSize.x,
  3057. scaley = size.y / boundsSize.y,
  3058. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3059. zoom = this.getScaleZoom(scale, zoom);
  3060. if (snap) {
  3061. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3062. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3063. }
  3064. return Math.max(min, Math.min(max, zoom));
  3065. },
  3066. // @method getSize(): Point
  3067. // Returns the current size of the map container (in pixels).
  3068. getSize: function () {
  3069. if (!this._size || this._sizeChanged) {
  3070. this._size = new Point(
  3071. this._container.clientWidth || 0,
  3072. this._container.clientHeight || 0);
  3073. this._sizeChanged = false;
  3074. }
  3075. return this._size.clone();
  3076. },
  3077. // @method getPixelBounds(): Bounds
  3078. // Returns the bounds of the current map view in projected pixel
  3079. // coordinates (sometimes useful in layer and overlay implementations).
  3080. getPixelBounds: function (center, zoom) {
  3081. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3082. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3083. },
  3084. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3085. // the map pane? "left point of the map layer" can be confusing, specially
  3086. // since there can be negative offsets.
  3087. // @method getPixelOrigin(): Point
  3088. // Returns the projected pixel coordinates of the top left point of
  3089. // the map layer (useful in custom layer and overlay implementations).
  3090. getPixelOrigin: function () {
  3091. this._checkIfLoaded();
  3092. return this._pixelOrigin;
  3093. },
  3094. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3095. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3096. // If `zoom` is omitted, the map's current zoom level is used.
  3097. getPixelWorldBounds: function (zoom) {
  3098. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3099. },
  3100. // @section Other Methods
  3101. // @method getPane(pane: String|HTMLElement): HTMLElement
  3102. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3103. getPane: function (pane) {
  3104. return typeof pane === 'string' ? this._panes[pane] : pane;
  3105. },
  3106. // @method getPanes(): Object
  3107. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3108. // the panes as values.
  3109. getPanes: function () {
  3110. return this._panes;
  3111. },
  3112. // @method getContainer: HTMLElement
  3113. // Returns the HTML element that contains the map.
  3114. getContainer: function () {
  3115. return this._container;
  3116. },
  3117. // @section Conversion Methods
  3118. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3119. // Returns the scale factor to be applied to a map transition from zoom level
  3120. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3121. getZoomScale: function (toZoom, fromZoom) {
  3122. // TODO replace with universal implementation after refactoring projections
  3123. var crs = this.options.crs;
  3124. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3125. return crs.scale(toZoom) / crs.scale(fromZoom);
  3126. },
  3127. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3128. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3129. // level and everything is scaled by a factor of `scale`. Inverse of
  3130. // [`getZoomScale`](#map-getZoomScale).
  3131. getScaleZoom: function (scale, fromZoom) {
  3132. var crs = this.options.crs;
  3133. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3134. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3135. return isNaN(zoom) ? Infinity : zoom;
  3136. },
  3137. // @method project(latlng: LatLng, zoom: Number): Point
  3138. // Projects a geographical coordinate `LatLng` according to the projection
  3139. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3140. // `Transformation`. The result is pixel coordinate relative to
  3141. // the CRS origin.
  3142. project: function (latlng, zoom) {
  3143. zoom = zoom === undefined ? this._zoom : zoom;
  3144. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3145. },
  3146. // @method unproject(point: Point, zoom: Number): LatLng
  3147. // Inverse of [`project`](#map-project).
  3148. unproject: function (point, zoom) {
  3149. zoom = zoom === undefined ? this._zoom : zoom;
  3150. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3151. },
  3152. // @method layerPointToLatLng(point: Point): LatLng
  3153. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3154. // returns the corresponding geographical coordinate (for the current zoom level).
  3155. layerPointToLatLng: function (point) {
  3156. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3157. return this.unproject(projectedPoint);
  3158. },
  3159. // @method latLngToLayerPoint(latlng: LatLng): Point
  3160. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3161. // relative to the [origin pixel](#map-getpixelorigin).
  3162. latLngToLayerPoint: function (latlng) {
  3163. var projectedPoint = this.project(toLatLng(latlng))._round();
  3164. return projectedPoint._subtract(this.getPixelOrigin());
  3165. },
  3166. // @method wrapLatLng(latlng: LatLng): LatLng
  3167. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3168. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3169. // CRS's bounds.
  3170. // By default this means longitude is wrapped around the dateline so its
  3171. // value is between -180 and +180 degrees.
  3172. wrapLatLng: function (latlng) {
  3173. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3174. },
  3175. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3176. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3177. // its center is within the CRS's bounds.
  3178. // By default this means the center longitude is wrapped around the dateline so its
  3179. // value is between -180 and +180 degrees, and the majority of the bounds
  3180. // overlaps the CRS's bounds.
  3181. wrapLatLngBounds: function (latlng) {
  3182. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3183. },
  3184. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3185. // Returns the distance between two geographical coordinates according to
  3186. // the map's CRS. By default this measures distance in meters.
  3187. distance: function (latlng1, latlng2) {
  3188. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3189. },
  3190. // @method containerPointToLayerPoint(point: Point): Point
  3191. // Given a pixel coordinate relative to the map container, returns the corresponding
  3192. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3193. containerPointToLayerPoint: function (point) { // (Point)
  3194. return toPoint(point).subtract(this._getMapPanePos());
  3195. },
  3196. // @method layerPointToContainerPoint(point: Point): Point
  3197. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3198. // returns the corresponding pixel coordinate relative to the map container.
  3199. layerPointToContainerPoint: function (point) { // (Point)
  3200. return toPoint(point).add(this._getMapPanePos());
  3201. },
  3202. // @method containerPointToLatLng(point: Point): LatLng
  3203. // Given a pixel coordinate relative to the map container, returns
  3204. // the corresponding geographical coordinate (for the current zoom level).
  3205. containerPointToLatLng: function (point) {
  3206. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3207. return this.layerPointToLatLng(layerPoint);
  3208. },
  3209. // @method latLngToContainerPoint(latlng: LatLng): Point
  3210. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3211. // relative to the map container.
  3212. latLngToContainerPoint: function (latlng) {
  3213. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3214. },
  3215. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3216. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3217. // map container where the event took place.
  3218. mouseEventToContainerPoint: function (e) {
  3219. return getMousePosition(e, this._container);
  3220. },
  3221. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3222. // Given a MouseEvent object, returns the pixel coordinate relative to
  3223. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3224. mouseEventToLayerPoint: function (e) {
  3225. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3226. },
  3227. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3228. // Given a MouseEvent object, returns geographical coordinate where the
  3229. // event took place.
  3230. mouseEventToLatLng: function (e) { // (MouseEvent)
  3231. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3232. },
  3233. // map initialization methods
  3234. _initContainer: function (id) {
  3235. var container = this._container = get(id);
  3236. if (!container) {
  3237. throw new Error('Map container not found.');
  3238. } else if (container._leaflet_id) {
  3239. throw new Error('Map container is already initialized.');
  3240. }
  3241. on(container, 'scroll', this._onScroll, this);
  3242. this._containerId = stamp(container);
  3243. },
  3244. _initLayout: function () {
  3245. var container = this._container;
  3246. this._fadeAnimated = this.options.fadeAnimation && any3d;
  3247. addClass(container, 'leaflet-container' +
  3248. (touch ? ' leaflet-touch' : '') +
  3249. (retina ? ' leaflet-retina' : '') +
  3250. (ielt9 ? ' leaflet-oldie' : '') +
  3251. (safari ? ' leaflet-safari' : '') +
  3252. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3253. var position = getStyle(container, 'position');
  3254. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  3255. container.style.position = 'relative';
  3256. }
  3257. this._initPanes();
  3258. if (this._initControlPos) {
  3259. this._initControlPos();
  3260. }
  3261. },
  3262. _initPanes: function () {
  3263. var panes = this._panes = {};
  3264. this._paneRenderers = {};
  3265. // @section
  3266. //
  3267. // Panes are DOM elements used to control the ordering of layers on the map. You
  3268. // can access panes with [`map.getPane`](#map-getpane) or
  3269. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3270. // [`map.createPane`](#map-createpane) method.
  3271. //
  3272. // Every map has the following default panes that differ only in zIndex.
  3273. //
  3274. // @pane mapPane: HTMLElement = 'auto'
  3275. // Pane that contains all other map panes
  3276. this._mapPane = this.createPane('mapPane', this._container);
  3277. setPosition(this._mapPane, new Point(0, 0));
  3278. // @pane tilePane: HTMLElement = 200
  3279. // Pane for `GridLayer`s and `TileLayer`s
  3280. this.createPane('tilePane');
  3281. // @pane overlayPane: HTMLElement = 400
  3282. // Pane for vector overlays (`Path`s), like `Polyline`s and `Polygon`s
  3283. this.createPane('shadowPane');
  3284. // @pane shadowPane: HTMLElement = 500
  3285. // Pane for overlay shadows (e.g. `Marker` shadows)
  3286. this.createPane('overlayPane');
  3287. // @pane markerPane: HTMLElement = 600
  3288. // Pane for `Icon`s of `Marker`s
  3289. this.createPane('markerPane');
  3290. // @pane tooltipPane: HTMLElement = 650
  3291. // Pane for tooltip.
  3292. this.createPane('tooltipPane');
  3293. // @pane popupPane: HTMLElement = 700
  3294. // Pane for `Popup`s.
  3295. this.createPane('popupPane');
  3296. if (!this.options.markerZoomAnimation) {
  3297. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3298. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3299. }
  3300. },
  3301. // private methods that modify map state
  3302. // @section Map state change events
  3303. _resetView: function (center, zoom) {
  3304. setPosition(this._mapPane, new Point(0, 0));
  3305. var loading = !this._loaded;
  3306. this._loaded = true;
  3307. zoom = this._limitZoom(zoom);
  3308. this.fire('viewprereset');
  3309. var zoomChanged = this._zoom !== zoom;
  3310. this
  3311. ._moveStart(zoomChanged)
  3312. ._move(center, zoom)
  3313. ._moveEnd(zoomChanged);
  3314. // @event viewreset: Event
  3315. // Fired when the map needs to redraw its content (this usually happens
  3316. // on map zoom or load). Very useful for creating custom overlays.
  3317. this.fire('viewreset');
  3318. // @event load: Event
  3319. // Fired when the map is initialized (when its center and zoom are set
  3320. // for the first time).
  3321. if (loading) {
  3322. this.fire('load');
  3323. }
  3324. },
  3325. _moveStart: function (zoomChanged) {
  3326. // @event zoomstart: Event
  3327. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3328. // @event movestart: Event
  3329. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3330. if (zoomChanged) {
  3331. this.fire('zoomstart');
  3332. }
  3333. return this.fire('movestart');
  3334. },
  3335. _move: function (center, zoom, data) {
  3336. if (zoom === undefined) {
  3337. zoom = this._zoom;
  3338. }
  3339. var zoomChanged = this._zoom !== zoom;
  3340. this._zoom = zoom;
  3341. this._lastCenter = center;
  3342. this._pixelOrigin = this._getNewPixelOrigin(center);
  3343. // @event zoom: Event
  3344. // Fired repeatedly during any change in zoom level, including zoom
  3345. // and fly animations.
  3346. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3347. this.fire('zoom', data);
  3348. }
  3349. // @event move: Event
  3350. // Fired repeatedly during any movement of the map, including pan and
  3351. // fly animations.
  3352. return this.fire('move', data);
  3353. },
  3354. _moveEnd: function (zoomChanged) {
  3355. // @event zoomend: Event
  3356. // Fired when the map has changed, after any animations.
  3357. if (zoomChanged) {
  3358. this.fire('zoomend');
  3359. }
  3360. // @event moveend: Event
  3361. // Fired when the center of the map stops changing (e.g. user stopped
  3362. // dragging the map).
  3363. return this.fire('moveend');
  3364. },
  3365. _stop: function () {
  3366. cancelAnimFrame(this._flyToFrame);
  3367. if (this._panAnim) {
  3368. this._panAnim.stop();
  3369. }
  3370. return this;
  3371. },
  3372. _rawPanBy: function (offset) {
  3373. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3374. },
  3375. _getZoomSpan: function () {
  3376. return this.getMaxZoom() - this.getMinZoom();
  3377. },
  3378. _panInsideMaxBounds: function () {
  3379. if (!this._enforcingBounds) {
  3380. this.panInsideBounds(this.options.maxBounds);
  3381. }
  3382. },
  3383. _checkIfLoaded: function () {
  3384. if (!this._loaded) {
  3385. throw new Error('Set map center and zoom first.');
  3386. }
  3387. },
  3388. // DOM event handling
  3389. // @section Interaction events
  3390. _initEvents: function (remove$$1) {
  3391. this._targets = {};
  3392. this._targets[stamp(this._container)] = this;
  3393. var onOff = remove$$1 ? off : on;
  3394. // @event click: MouseEvent
  3395. // Fired when the user clicks (or taps) the map.
  3396. // @event dblclick: MouseEvent
  3397. // Fired when the user double-clicks (or double-taps) the map.
  3398. // @event mousedown: MouseEvent
  3399. // Fired when the user pushes the mouse button on the map.
  3400. // @event mouseup: MouseEvent
  3401. // Fired when the user releases the mouse button on the map.
  3402. // @event mouseover: MouseEvent
  3403. // Fired when the mouse enters the map.
  3404. // @event mouseout: MouseEvent
  3405. // Fired when the mouse leaves the map.
  3406. // @event mousemove: MouseEvent
  3407. // Fired while the mouse moves over the map.
  3408. // @event contextmenu: MouseEvent
  3409. // Fired when the user pushes the right mouse button on the map, prevents
  3410. // default browser context menu from showing if there are listeners on
  3411. // this event. Also fired on mobile when the user holds a single touch
  3412. // for a second (also called long press).
  3413. // @event keypress: KeyboardEvent
  3414. // Fired when the user presses a key from the keyboard while the map is focused.
  3415. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3416. 'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this);
  3417. if (this.options.trackResize) {
  3418. onOff(window, 'resize', this._onResize, this);
  3419. }
  3420. if (any3d && this.options.transform3DLimit) {
  3421. (remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3422. }
  3423. },
  3424. _onResize: function () {
  3425. cancelAnimFrame(this._resizeRequest);
  3426. this._resizeRequest = requestAnimFrame(
  3427. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3428. },
  3429. _onScroll: function () {
  3430. this._container.scrollTop = 0;
  3431. this._container.scrollLeft = 0;
  3432. },
  3433. _onMoveEnd: function () {
  3434. var pos = this._getMapPanePos();
  3435. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3436. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3437. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  3438. this._resetView(this.getCenter(), this.getZoom());
  3439. }
  3440. },
  3441. _findEventTargets: function (e, type) {
  3442. var targets = [],
  3443. target,
  3444. isHover = type === 'mouseout' || type === 'mouseover',
  3445. src = e.target || e.srcElement,
  3446. dragging = false;
  3447. while (src) {
  3448. target = this._targets[stamp(src)];
  3449. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  3450. // Prevent firing click after you just dragged an object.
  3451. dragging = true;
  3452. break;
  3453. }
  3454. if (target && target.listens(type, true)) {
  3455. if (isHover && !isExternalTarget(src, e)) { break; }
  3456. targets.push(target);
  3457. if (isHover) { break; }
  3458. }
  3459. if (src === this._container) { break; }
  3460. src = src.parentNode;
  3461. }
  3462. if (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {
  3463. targets = [this];
  3464. }
  3465. return targets;
  3466. },
  3467. _handleDOMEvent: function (e) {
  3468. if (!this._loaded || skipped(e)) { return; }
  3469. var type = e.type;
  3470. if (type === 'mousedown' || type === 'keypress') {
  3471. // prevents outline when clicking on keyboard-focusable element
  3472. preventOutline(e.target || e.srcElement);
  3473. }
  3474. this._fireDOMEvent(e, type);
  3475. },
  3476. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3477. _fireDOMEvent: function (e, type, targets) {
  3478. if (e.type === 'click') {
  3479. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3480. // @event preclick: MouseEvent
  3481. // Fired before mouse click on the map (sometimes useful when you
  3482. // want something to happen on click before any existing click
  3483. // handlers start running).
  3484. var synth = extend({}, e);
  3485. synth.type = 'preclick';
  3486. this._fireDOMEvent(synth, synth.type, targets);
  3487. }
  3488. if (e._stopped) { return; }
  3489. // Find the layer the event is propagating from and its parents.
  3490. targets = (targets || []).concat(this._findEventTargets(e, type));
  3491. if (!targets.length) { return; }
  3492. var target = targets[0];
  3493. if (type === 'contextmenu' && target.listens(type, true)) {
  3494. preventDefault(e);
  3495. }
  3496. var data = {
  3497. originalEvent: e
  3498. };
  3499. if (e.type !== 'keypress') {
  3500. var isMarker = (target.options && 'icon' in target.options);
  3501. data.containerPoint = isMarker ?
  3502. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3503. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3504. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3505. }
  3506. for (var i = 0; i < targets.length; i++) {
  3507. targets[i].fire(type, data, true);
  3508. if (data.originalEvent._stopped ||
  3509. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3510. }
  3511. },
  3512. _draggableMoved: function (obj) {
  3513. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3514. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3515. },
  3516. _clearHandlers: function () {
  3517. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3518. this._handlers[i].disable();
  3519. }
  3520. },
  3521. // @section Other Methods
  3522. // @method whenReady(fn: Function, context?: Object): this
  3523. // Runs the given function `fn` when the map gets initialized with
  3524. // a view (center and zoom) and at least one layer, or immediately
  3525. // if it's already initialized, optionally passing a function context.
  3526. whenReady: function (callback, context) {
  3527. if (this._loaded) {
  3528. callback.call(context || this, {target: this});
  3529. } else {
  3530. this.on('load', callback, context);
  3531. }
  3532. return this;
  3533. },
  3534. // private methods for getting map state
  3535. _getMapPanePos: function () {
  3536. return getPosition(this._mapPane) || new Point(0, 0);
  3537. },
  3538. _moved: function () {
  3539. var pos = this._getMapPanePos();
  3540. return pos && !pos.equals([0, 0]);
  3541. },
  3542. _getTopLeftPoint: function (center, zoom) {
  3543. var pixelOrigin = center && zoom !== undefined ?
  3544. this._getNewPixelOrigin(center, zoom) :
  3545. this.getPixelOrigin();
  3546. return pixelOrigin.subtract(this._getMapPanePos());
  3547. },
  3548. _getNewPixelOrigin: function (center, zoom) {
  3549. var viewHalf = this.getSize()._divideBy(2);
  3550. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3551. },
  3552. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3553. var topLeft = this._getNewPixelOrigin(center, zoom);
  3554. return this.project(latlng, zoom)._subtract(topLeft);
  3555. },
  3556. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3557. var topLeft = this._getNewPixelOrigin(center, zoom);
  3558. return toBounds([
  3559. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3560. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3561. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3562. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3563. ]);
  3564. },
  3565. // layer point of the current center
  3566. _getCenterLayerPoint: function () {
  3567. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3568. },
  3569. // offset of the specified place to the current center in pixels
  3570. _getCenterOffset: function (latlng) {
  3571. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3572. },
  3573. // adjust center for view to get inside bounds
  3574. _limitCenter: function (center, zoom, bounds) {
  3575. if (!bounds) { return center; }
  3576. var centerPoint = this.project(center, zoom),
  3577. viewHalf = this.getSize().divideBy(2),
  3578. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3579. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3580. // If offset is less than a pixel, ignore.
  3581. // This prevents unstable projections from getting into
  3582. // an infinite loop of tiny offsets.
  3583. if (offset.round().equals([0, 0])) {
  3584. return center;
  3585. }
  3586. return this.unproject(centerPoint.add(offset), zoom);
  3587. },
  3588. // adjust offset for view to get inside bounds
  3589. _limitOffset: function (offset, bounds) {
  3590. if (!bounds) { return offset; }
  3591. var viewBounds = this.getPixelBounds(),
  3592. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3593. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3594. },
  3595. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3596. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3597. var projectedMaxBounds = toBounds(
  3598. this.project(maxBounds.getNorthEast(), zoom),
  3599. this.project(maxBounds.getSouthWest(), zoom)
  3600. ),
  3601. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3602. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3603. dx = this._rebound(minOffset.x, -maxOffset.x),
  3604. dy = this._rebound(minOffset.y, -maxOffset.y);
  3605. return new Point(dx, dy);
  3606. },
  3607. _rebound: function (left, right) {
  3608. return left + right > 0 ?
  3609. Math.round(left - right) / 2 :
  3610. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3611. },
  3612. _limitZoom: function (zoom) {
  3613. var min = this.getMinZoom(),
  3614. max = this.getMaxZoom(),
  3615. snap = any3d ? this.options.zoomSnap : 1;
  3616. if (snap) {
  3617. zoom = Math.round(zoom / snap) * snap;
  3618. }
  3619. return Math.max(min, Math.min(max, zoom));
  3620. },
  3621. _onPanTransitionStep: function () {
  3622. this.fire('move');
  3623. },
  3624. _onPanTransitionEnd: function () {
  3625. removeClass(this._mapPane, 'leaflet-pan-anim');
  3626. this.fire('moveend');
  3627. },
  3628. _tryAnimatedPan: function (center, options) {
  3629. // difference between the new and current centers in pixels
  3630. var offset = this._getCenterOffset(center)._floor();
  3631. // don't animate too far unless animate: true specified in options
  3632. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3633. this.panBy(offset, options);
  3634. return true;
  3635. },
  3636. _createAnimProxy: function () {
  3637. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3638. this._panes.mapPane.appendChild(proxy);
  3639. this.on('zoomanim', function (e) {
  3640. var prop = TRANSFORM,
  3641. transform = this._proxy.style[prop];
  3642. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3643. // workaround for case when transform is the same and so transitionend event is not fired
  3644. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3645. this._onZoomTransitionEnd();
  3646. }
  3647. }, this);
  3648. this.on('load moveend', function () {
  3649. var c = this.getCenter(),
  3650. z = this.getZoom();
  3651. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3652. }, this);
  3653. this._on('unload', this._destroyAnimProxy, this);
  3654. },
  3655. _destroyAnimProxy: function () {
  3656. remove(this._proxy);
  3657. delete this._proxy;
  3658. },
  3659. _catchTransitionEnd: function (e) {
  3660. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3661. this._onZoomTransitionEnd();
  3662. }
  3663. },
  3664. _nothingToAnimate: function () {
  3665. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3666. },
  3667. _tryAnimatedZoom: function (center, zoom, options) {
  3668. if (this._animatingZoom) { return true; }
  3669. options = options || {};
  3670. // don't animate if disabled, not supported or zoom difference is too large
  3671. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3672. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3673. // offset is the pixel coords of the zoom origin relative to the current center
  3674. var scale = this.getZoomScale(zoom),
  3675. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3676. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3677. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3678. requestAnimFrame(function () {
  3679. this
  3680. ._moveStart(true)
  3681. ._animateZoom(center, zoom, true);
  3682. }, this);
  3683. return true;
  3684. },
  3685. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3686. if (startAnim) {
  3687. this._animatingZoom = true;
  3688. // remember what center/zoom to set after animation
  3689. this._animateToCenter = center;
  3690. this._animateToZoom = zoom;
  3691. addClass(this._mapPane, 'leaflet-zoom-anim');
  3692. }
  3693. // @event zoomanim: ZoomAnimEvent
  3694. // Fired on every frame of a zoom animation
  3695. this.fire('zoomanim', {
  3696. center: center,
  3697. zoom: zoom,
  3698. noUpdate: noUpdate
  3699. });
  3700. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3701. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3702. },
  3703. _onZoomTransitionEnd: function () {
  3704. if (!this._animatingZoom) { return; }
  3705. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3706. this._animatingZoom = false;
  3707. this._move(this._animateToCenter, this._animateToZoom);
  3708. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  3709. requestAnimFrame(function () {
  3710. this._moveEnd(true);
  3711. }, this);
  3712. }
  3713. });
  3714. // @section
  3715. // @factory L.map(id: String, options?: Map options)
  3716. // Instantiates a map object given the DOM ID of a `<div>` element
  3717. // and optionally an object literal with `Map options`.
  3718. //
  3719. // @alternative
  3720. // @factory L.map(el: HTMLElement, options?: Map options)
  3721. // Instantiates a map object given an instance of a `<div>` HTML element
  3722. // and optionally an object literal with `Map options`.
  3723. function createMap(id, options) {
  3724. return new Map(id, options);
  3725. }
  3726. /*
  3727. * @class Control
  3728. * @aka L.Control
  3729. * @inherits Class
  3730. *
  3731. * L.Control is a base class for implementing map controls. Handles positioning.
  3732. * All other controls extend from this class.
  3733. */
  3734. var Control = Class.extend({
  3735. // @section
  3736. // @aka Control options
  3737. options: {
  3738. // @option position: String = 'topright'
  3739. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  3740. // `'topright'`, `'bottomleft'` or `'bottomright'`
  3741. position: 'topright'
  3742. },
  3743. initialize: function (options) {
  3744. setOptions(this, options);
  3745. },
  3746. /* @section
  3747. * Classes extending L.Control will inherit the following methods:
  3748. *
  3749. * @method getPosition: string
  3750. * Returns the position of the control.
  3751. */
  3752. getPosition: function () {
  3753. return this.options.position;
  3754. },
  3755. // @method setPosition(position: string): this
  3756. // Sets the position of the control.
  3757. setPosition: function (position) {
  3758. var map = this._map;
  3759. if (map) {
  3760. map.removeControl(this);
  3761. }
  3762. this.options.position = position;
  3763. if (map) {
  3764. map.addControl(this);
  3765. }
  3766. return this;
  3767. },
  3768. // @method getContainer: HTMLElement
  3769. // Returns the HTMLElement that contains the control.
  3770. getContainer: function () {
  3771. return this._container;
  3772. },
  3773. // @method addTo(map: Map): this
  3774. // Adds the control to the given map.
  3775. addTo: function (map) {
  3776. this.remove();
  3777. this._map = map;
  3778. var container = this._container = this.onAdd(map),
  3779. pos = this.getPosition(),
  3780. corner = map._controlCorners[pos];
  3781. addClass(container, 'leaflet-control');
  3782. if (pos.indexOf('bottom') !== -1) {
  3783. corner.insertBefore(container, corner.firstChild);
  3784. } else {
  3785. corner.appendChild(container);
  3786. }
  3787. return this;
  3788. },
  3789. // @method remove: this
  3790. // Removes the control from the map it is currently active on.
  3791. remove: function () {
  3792. if (!this._map) {
  3793. return this;
  3794. }
  3795. remove(this._container);
  3796. if (this.onRemove) {
  3797. this.onRemove(this._map);
  3798. }
  3799. this._map = null;
  3800. return this;
  3801. },
  3802. _refocusOnMap: function (e) {
  3803. // if map exists and event is not a keyboard event
  3804. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  3805. this._map.getContainer().focus();
  3806. }
  3807. }
  3808. });
  3809. var control = function (options) {
  3810. return new Control(options);
  3811. };
  3812. /* @section Extension methods
  3813. * @uninheritable
  3814. *
  3815. * Every control should extend from `L.Control` and (re-)implement the following methods.
  3816. *
  3817. * @method onAdd(map: Map): HTMLElement
  3818. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  3819. *
  3820. * @method onRemove(map: Map)
  3821. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  3822. */
  3823. /* @namespace Map
  3824. * @section Methods for Layers and Controls
  3825. */
  3826. Map.include({
  3827. // @method addControl(control: Control): this
  3828. // Adds the given control to the map
  3829. addControl: function (control) {
  3830. control.addTo(this);
  3831. return this;
  3832. },
  3833. // @method removeControl(control: Control): this
  3834. // Removes the given control from the map
  3835. removeControl: function (control) {
  3836. control.remove();
  3837. return this;
  3838. },
  3839. _initControlPos: function () {
  3840. var corners = this._controlCorners = {},
  3841. l = 'leaflet-',
  3842. container = this._controlContainer =
  3843. create$1('div', l + 'control-container', this._container);
  3844. function createCorner(vSide, hSide) {
  3845. var className = l + vSide + ' ' + l + hSide;
  3846. corners[vSide + hSide] = create$1('div', className, container);
  3847. }
  3848. createCorner('top', 'left');
  3849. createCorner('top', 'right');
  3850. createCorner('bottom', 'left');
  3851. createCorner('bottom', 'right');
  3852. },
  3853. _clearControlPos: function () {
  3854. for (var i in this._controlCorners) {
  3855. remove(this._controlCorners[i]);
  3856. }
  3857. remove(this._controlContainer);
  3858. delete this._controlCorners;
  3859. delete this._controlContainer;
  3860. }
  3861. });
  3862. /*
  3863. * @class Control.Layers
  3864. * @aka L.Control.Layers
  3865. * @inherits Control
  3866. *
  3867. * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control/)). Extends `Control`.
  3868. *
  3869. * @example
  3870. *
  3871. * ```js
  3872. * var baseLayers = {
  3873. * "Mapbox": mapbox,
  3874. * "OpenStreetMap": osm
  3875. * };
  3876. *
  3877. * var overlays = {
  3878. * "Marker": marker,
  3879. * "Roads": roadsLayer
  3880. * };
  3881. *
  3882. * L.control.layers(baseLayers, overlays).addTo(map);
  3883. * ```
  3884. *
  3885. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  3886. *
  3887. * ```js
  3888. * {
  3889. * "<someName1>": layer1,
  3890. * "<someName2>": layer2
  3891. * }
  3892. * ```
  3893. *
  3894. * The layer names can contain HTML, which allows you to add additional styling to the items:
  3895. *
  3896. * ```js
  3897. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  3898. * ```
  3899. */
  3900. var Layers = Control.extend({
  3901. // @section
  3902. // @aka Control.Layers options
  3903. options: {
  3904. // @option collapsed: Boolean = true
  3905. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  3906. collapsed: true,
  3907. position: 'topright',
  3908. // @option autoZIndex: Boolean = true
  3909. // If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.
  3910. autoZIndex: true,
  3911. // @option hideSingleBase: Boolean = false
  3912. // If `true`, the base layers in the control will be hidden when there is only one.
  3913. hideSingleBase: false,
  3914. // @option sortLayers: Boolean = false
  3915. // Whether to sort the layers. When `false`, layers will keep the order
  3916. // in which they were added to the control.
  3917. sortLayers: false,
  3918. // @option sortFunction: Function = *
  3919. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  3920. // that will be used for sorting the layers, when `sortLayers` is `true`.
  3921. // The function receives both the `L.Layer` instances and their names, as in
  3922. // `sortFunction(layerA, layerB, nameA, nameB)`.
  3923. // By default, it sorts layers alphabetically by their name.
  3924. sortFunction: function (layerA, layerB, nameA, nameB) {
  3925. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  3926. }
  3927. },
  3928. initialize: function (baseLayers, overlays, options) {
  3929. setOptions(this, options);
  3930. this._layerControlInputs = [];
  3931. this._layers = [];
  3932. this._lastZIndex = 0;
  3933. this._handlingClick = false;
  3934. for (var i in baseLayers) {
  3935. this._addLayer(baseLayers[i], i);
  3936. }
  3937. for (i in overlays) {
  3938. this._addLayer(overlays[i], i, true);
  3939. }
  3940. },
  3941. onAdd: function (map) {
  3942. this._initLayout();
  3943. this._update();
  3944. this._map = map;
  3945. map.on('zoomend', this._checkDisabledLayers, this);
  3946. for (var i = 0; i < this._layers.length; i++) {
  3947. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  3948. }
  3949. return this._container;
  3950. },
  3951. addTo: function (map) {
  3952. Control.prototype.addTo.call(this, map);
  3953. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  3954. return this._expandIfNotCollapsed();
  3955. },
  3956. onRemove: function () {
  3957. this._map.off('zoomend', this._checkDisabledLayers, this);
  3958. for (var i = 0; i < this._layers.length; i++) {
  3959. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  3960. }
  3961. },
  3962. // @method addBaseLayer(layer: Layer, name: String): this
  3963. // Adds a base layer (radio button entry) with the given name to the control.
  3964. addBaseLayer: function (layer, name) {
  3965. this._addLayer(layer, name);
  3966. return (this._map) ? this._update() : this;
  3967. },
  3968. // @method addOverlay(layer: Layer, name: String): this
  3969. // Adds an overlay (checkbox entry) with the given name to the control.
  3970. addOverlay: function (layer, name) {
  3971. this._addLayer(layer, name, true);
  3972. return (this._map) ? this._update() : this;
  3973. },
  3974. // @method removeLayer(layer: Layer): this
  3975. // Remove the given layer from the control.
  3976. removeLayer: function (layer) {
  3977. layer.off('add remove', this._onLayerChange, this);
  3978. var obj = this._getLayer(stamp(layer));
  3979. if (obj) {
  3980. this._layers.splice(this._layers.indexOf(obj), 1);
  3981. }
  3982. return (this._map) ? this._update() : this;
  3983. },
  3984. // @method expand(): this
  3985. // Expand the control container if collapsed.
  3986. expand: function () {
  3987. addClass(this._container, 'leaflet-control-layers-expanded');
  3988. this._form.style.height = null;
  3989. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  3990. if (acceptableHeight < this._form.clientHeight) {
  3991. addClass(this._form, 'leaflet-control-layers-scrollbar');
  3992. this._form.style.height = acceptableHeight + 'px';
  3993. } else {
  3994. removeClass(this._form, 'leaflet-control-layers-scrollbar');
  3995. }
  3996. this._checkDisabledLayers();
  3997. return this;
  3998. },
  3999. // @method collapse(): this
  4000. // Collapse the control container if expanded.
  4001. collapse: function () {
  4002. removeClass(this._container, 'leaflet-control-layers-expanded');
  4003. return this;
  4004. },
  4005. _initLayout: function () {
  4006. var className = 'leaflet-control-layers',
  4007. container = this._container = create$1('div', className),
  4008. collapsed = this.options.collapsed;
  4009. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4010. container.setAttribute('aria-haspopup', true);
  4011. disableClickPropagation(container);
  4012. disableScrollPropagation(container);
  4013. var form = this._form = create$1('form', className + '-list');
  4014. if (collapsed) {
  4015. this._map.on('click', this.collapse, this);
  4016. if (!android) {
  4017. on(container, {
  4018. mouseenter: this.expand,
  4019. mouseleave: this.collapse
  4020. }, this);
  4021. }
  4022. }
  4023. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4024. link.href = '#';
  4025. link.title = 'Layers';
  4026. if (touch) {
  4027. on(link, 'click', stop);
  4028. on(link, 'click', this.expand, this);
  4029. } else {
  4030. on(link, 'focus', this.expand, this);
  4031. }
  4032. if (!collapsed) {
  4033. this.expand();
  4034. }
  4035. this._baseLayersList = create$1('div', className + '-base', form);
  4036. this._separator = create$1('div', className + '-separator', form);
  4037. this._overlaysList = create$1('div', className + '-overlays', form);
  4038. container.appendChild(form);
  4039. },
  4040. _getLayer: function (id) {
  4041. for (var i = 0; i < this._layers.length; i++) {
  4042. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4043. return this._layers[i];
  4044. }
  4045. }
  4046. },
  4047. _addLayer: function (layer, name, overlay) {
  4048. if (this._map) {
  4049. layer.on('add remove', this._onLayerChange, this);
  4050. }
  4051. this._layers.push({
  4052. layer: layer,
  4053. name: name,
  4054. overlay: overlay
  4055. });
  4056. if (this.options.sortLayers) {
  4057. this._layers.sort(bind(function (a, b) {
  4058. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4059. }, this));
  4060. }
  4061. if (this.options.autoZIndex && layer.setZIndex) {
  4062. this._lastZIndex++;
  4063. layer.setZIndex(this._lastZIndex);
  4064. }
  4065. this._expandIfNotCollapsed();
  4066. },
  4067. _update: function () {
  4068. if (!this._container) { return this; }
  4069. empty(this._baseLayersList);
  4070. empty(this._overlaysList);
  4071. this._layerControlInputs = [];
  4072. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4073. for (i = 0; i < this._layers.length; i++) {
  4074. obj = this._layers[i];
  4075. this._addItem(obj);
  4076. overlaysPresent = overlaysPresent || obj.overlay;
  4077. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4078. baseLayersCount += !obj.overlay ? 1 : 0;
  4079. }
  4080. // Hide base layers section if there's only one layer.
  4081. if (this.options.hideSingleBase) {
  4082. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4083. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4084. }
  4085. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4086. return this;
  4087. },
  4088. _onLayerChange: function (e) {
  4089. if (!this._handlingClick) {
  4090. this._update();
  4091. }
  4092. var obj = this._getLayer(stamp(e.target));
  4093. // @namespace Map
  4094. // @section Layer events
  4095. // @event baselayerchange: LayersControlEvent
  4096. // Fired when the base layer is changed through the [layer control](#control-layers).
  4097. // @event overlayadd: LayersControlEvent
  4098. // Fired when an overlay is selected through the [layer control](#control-layers).
  4099. // @event overlayremove: LayersControlEvent
  4100. // Fired when an overlay is deselected through the [layer control](#control-layers).
  4101. // @namespace Control.Layers
  4102. var type = obj.overlay ?
  4103. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4104. (e.type === 'add' ? 'baselayerchange' : null);
  4105. if (type) {
  4106. this._map.fire(type, obj);
  4107. }
  4108. },
  4109. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  4110. _createRadioElement: function (name, checked) {
  4111. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4112. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4113. var radioFragment = document.createElement('div');
  4114. radioFragment.innerHTML = radioHtml;
  4115. return radioFragment.firstChild;
  4116. },
  4117. _addItem: function (obj) {
  4118. var label = document.createElement('label'),
  4119. checked = this._map.hasLayer(obj.layer),
  4120. input;
  4121. if (obj.overlay) {
  4122. input = document.createElement('input');
  4123. input.type = 'checkbox';
  4124. input.className = 'leaflet-control-layers-selector';
  4125. input.defaultChecked = checked;
  4126. } else {
  4127. input = this._createRadioElement('leaflet-base-layers', checked);
  4128. }
  4129. this._layerControlInputs.push(input);
  4130. input.layerId = stamp(obj.layer);
  4131. on(input, 'click', this._onInputClick, this);
  4132. var name = document.createElement('span');
  4133. name.innerHTML = ' ' + obj.name;
  4134. // Helps from preventing layer control flicker when checkboxes are disabled
  4135. // https://github.com/Leaflet/Leaflet/issues/2771
  4136. var holder = document.createElement('div');
  4137. label.appendChild(holder);
  4138. holder.appendChild(input);
  4139. holder.appendChild(name);
  4140. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4141. container.appendChild(label);
  4142. this._checkDisabledLayers();
  4143. return label;
  4144. },
  4145. _onInputClick: function () {
  4146. var inputs = this._layerControlInputs,
  4147. input, layer;
  4148. var addedLayers = [],
  4149. removedLayers = [];
  4150. this._handlingClick = true;
  4151. for (var i = inputs.length - 1; i >= 0; i--) {
  4152. input = inputs[i];
  4153. layer = this._getLayer(input.layerId).layer;
  4154. if (input.checked) {
  4155. addedLayers.push(layer);
  4156. } else if (!input.checked) {
  4157. removedLayers.push(layer);
  4158. }
  4159. }
  4160. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4161. for (i = 0; i < removedLayers.length; i++) {
  4162. if (this._map.hasLayer(removedLayers[i])) {
  4163. this._map.removeLayer(removedLayers[i]);
  4164. }
  4165. }
  4166. for (i = 0; i < addedLayers.length; i++) {
  4167. if (!this._map.hasLayer(addedLayers[i])) {
  4168. this._map.addLayer(addedLayers[i]);
  4169. }
  4170. }
  4171. this._handlingClick = false;
  4172. this._refocusOnMap();
  4173. },
  4174. _checkDisabledLayers: function () {
  4175. var inputs = this._layerControlInputs,
  4176. input,
  4177. layer,
  4178. zoom = this._map.getZoom();
  4179. for (var i = inputs.length - 1; i >= 0; i--) {
  4180. input = inputs[i];
  4181. layer = this._getLayer(input.layerId).layer;
  4182. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4183. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4184. }
  4185. },
  4186. _expandIfNotCollapsed: function () {
  4187. if (this._map && !this.options.collapsed) {
  4188. this.expand();
  4189. }
  4190. return this;
  4191. },
  4192. _expand: function () {
  4193. // Backward compatibility, remove me in 1.1.
  4194. return this.expand();
  4195. },
  4196. _collapse: function () {
  4197. // Backward compatibility, remove me in 1.1.
  4198. return this.collapse();
  4199. }
  4200. });
  4201. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4202. // Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
  4203. var layers = function (baseLayers, overlays, options) {
  4204. return new Layers(baseLayers, overlays, options);
  4205. };
  4206. /*
  4207. * @class Control.Zoom
  4208. * @aka L.Control.Zoom
  4209. * @inherits Control
  4210. *
  4211. * A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`.
  4212. */
  4213. var Zoom = Control.extend({
  4214. // @section
  4215. // @aka Control.Zoom options
  4216. options: {
  4217. position: 'topleft',
  4218. // @option zoomInText: String = '+'
  4219. // The text set on the 'zoom in' button.
  4220. zoomInText: '+',
  4221. // @option zoomInTitle: String = 'Zoom in'
  4222. // The title set on the 'zoom in' button.
  4223. zoomInTitle: 'Zoom in',
  4224. // @option zoomOutText: String = '&#x2212;'
  4225. // The text set on the 'zoom out' button.
  4226. zoomOutText: '&#x2212;',
  4227. // @option zoomOutTitle: String = 'Zoom out'
  4228. // The title set on the 'zoom out' button.
  4229. zoomOutTitle: 'Zoom out'
  4230. },
  4231. onAdd: function (map) {
  4232. var zoomName = 'leaflet-control-zoom',
  4233. container = create$1('div', zoomName + ' leaflet-bar'),
  4234. options = this.options;
  4235. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4236. zoomName + '-in', container, this._zoomIn);
  4237. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4238. zoomName + '-out', container, this._zoomOut);
  4239. this._updateDisabled();
  4240. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4241. return container;
  4242. },
  4243. onRemove: function (map) {
  4244. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4245. },
  4246. disable: function () {
  4247. this._disabled = true;
  4248. this._updateDisabled();
  4249. return this;
  4250. },
  4251. enable: function () {
  4252. this._disabled = false;
  4253. this._updateDisabled();
  4254. return this;
  4255. },
  4256. _zoomIn: function (e) {
  4257. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4258. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4259. }
  4260. },
  4261. _zoomOut: function (e) {
  4262. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4263. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4264. }
  4265. },
  4266. _createButton: function (html, title, className, container, fn) {
  4267. var link = create$1('a', className, container);
  4268. link.innerHTML = html;
  4269. link.href = '#';
  4270. link.title = title;
  4271. /*
  4272. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4273. */
  4274. link.setAttribute('role', 'button');
  4275. link.setAttribute('aria-label', title);
  4276. disableClickPropagation(link);
  4277. on(link, 'click', stop);
  4278. on(link, 'click', fn, this);
  4279. on(link, 'click', this._refocusOnMap, this);
  4280. return link;
  4281. },
  4282. _updateDisabled: function () {
  4283. var map = this._map,
  4284. className = 'leaflet-disabled';
  4285. removeClass(this._zoomInButton, className);
  4286. removeClass(this._zoomOutButton, className);
  4287. if (this._disabled || map._zoom === map.getMinZoom()) {
  4288. addClass(this._zoomOutButton, className);
  4289. }
  4290. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4291. addClass(this._zoomInButton, className);
  4292. }
  4293. }
  4294. });
  4295. // @namespace Map
  4296. // @section Control options
  4297. // @option zoomControl: Boolean = true
  4298. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4299. Map.mergeOptions({
  4300. zoomControl: true
  4301. });
  4302. Map.addInitHook(function () {
  4303. if (this.options.zoomControl) {
  4304. this.zoomControl = new Zoom();
  4305. this.addControl(this.zoomControl);
  4306. }
  4307. });
  4308. // @namespace Control.Zoom
  4309. // @factory L.control.zoom(options: Control.Zoom options)
  4310. // Creates a zoom control
  4311. var zoom = function (options) {
  4312. return new Zoom(options);
  4313. };
  4314. /*
  4315. * @class Control.Scale
  4316. * @aka L.Control.Scale
  4317. * @inherits Control
  4318. *
  4319. * A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends `Control`.
  4320. *
  4321. * @example
  4322. *
  4323. * ```js
  4324. * L.control.scale().addTo(map);
  4325. * ```
  4326. */
  4327. var Scale = Control.extend({
  4328. // @section
  4329. // @aka Control.Scale options
  4330. options: {
  4331. position: 'bottomleft',
  4332. // @option maxWidth: Number = 100
  4333. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4334. maxWidth: 100,
  4335. // @option metric: Boolean = True
  4336. // Whether to show the metric scale line (m/km).
  4337. metric: true,
  4338. // @option imperial: Boolean = True
  4339. // Whether to show the imperial scale line (mi/ft).
  4340. imperial: true
  4341. // @option updateWhenIdle: Boolean = false
  4342. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4343. },
  4344. onAdd: function (map) {
  4345. var className = 'leaflet-control-scale',
  4346. container = create$1('div', className),
  4347. options = this.options;
  4348. this._addScales(options, className + '-line', container);
  4349. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4350. map.whenReady(this._update, this);
  4351. return container;
  4352. },
  4353. onRemove: function (map) {
  4354. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4355. },
  4356. _addScales: function (options, className, container) {
  4357. if (options.metric) {
  4358. this._mScale = create$1('div', className, container);
  4359. }
  4360. if (options.imperial) {
  4361. this._iScale = create$1('div', className, container);
  4362. }
  4363. },
  4364. _update: function () {
  4365. var map = this._map,
  4366. y = map.getSize().y / 2;
  4367. var maxMeters = map.distance(
  4368. map.containerPointToLatLng([0, y]),
  4369. map.containerPointToLatLng([this.options.maxWidth, y]));
  4370. this._updateScales(maxMeters);
  4371. },
  4372. _updateScales: function (maxMeters) {
  4373. if (this.options.metric && maxMeters) {
  4374. this._updateMetric(maxMeters);
  4375. }
  4376. if (this.options.imperial && maxMeters) {
  4377. this._updateImperial(maxMeters);
  4378. }
  4379. },
  4380. _updateMetric: function (maxMeters) {
  4381. var meters = this._getRoundNum(maxMeters),
  4382. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4383. this._updateScale(this._mScale, label, meters / maxMeters);
  4384. },
  4385. _updateImperial: function (maxMeters) {
  4386. var maxFeet = maxMeters * 3.2808399,
  4387. maxMiles, miles, feet;
  4388. if (maxFeet > 5280) {
  4389. maxMiles = maxFeet / 5280;
  4390. miles = this._getRoundNum(maxMiles);
  4391. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4392. } else {
  4393. feet = this._getRoundNum(maxFeet);
  4394. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4395. }
  4396. },
  4397. _updateScale: function (scale, text, ratio) {
  4398. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4399. scale.innerHTML = text;
  4400. },
  4401. _getRoundNum: function (num) {
  4402. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4403. d = num / pow10;
  4404. d = d >= 10 ? 10 :
  4405. d >= 5 ? 5 :
  4406. d >= 3 ? 3 :
  4407. d >= 2 ? 2 : 1;
  4408. return pow10 * d;
  4409. }
  4410. });
  4411. // @factory L.control.scale(options?: Control.Scale options)
  4412. // Creates an scale control with the given options.
  4413. var scale = function (options) {
  4414. return new Scale(options);
  4415. };
  4416. /*
  4417. * @class Control.Attribution
  4418. * @aka L.Control.Attribution
  4419. * @inherits Control
  4420. *
  4421. * The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its [`attributionControl` option](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control.
  4422. */
  4423. var Attribution = Control.extend({
  4424. // @section
  4425. // @aka Control.Attribution options
  4426. // options: {
  4427. // position: 'bottomright',
  4428. //
  4429. // // @option prefix: String = 'Leaflet'
  4430. // // The HTML text shown before the attributions. Pass `false` to disable.
  4431. // prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  4432. // },
  4433. initialize: function (options) {
  4434. setOptions(this, options);
  4435. this._attributions = {};
  4436. },
  4437. onAdd: function (map) {
  4438. map.attributionControl = this;
  4439. this._container = create$1('div', 'leaflet-control-attribution');
  4440. disableClickPropagation(this._container);
  4441. // TODO ugly, refactor
  4442. for (var i in map._layers) {
  4443. if (map._layers[i].getAttribution) {
  4444. this.addAttribution(map._layers[i].getAttribution());
  4445. }
  4446. }
  4447. this._update();
  4448. return this._container;
  4449. },
  4450. // @method setPrefix(prefix: String): this
  4451. // Sets the text before the attributions.
  4452. setPrefix: function (prefix) {
  4453. this.options.prefix = prefix;
  4454. this._update();
  4455. return this;
  4456. },
  4457. // @method addAttribution(text: String): this
  4458. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  4459. addAttribution: function (text) {
  4460. if (!text) { return this; }
  4461. if (!this._attributions[text]) {
  4462. this._attributions[text] = 0;
  4463. }
  4464. this._attributions[text]++;
  4465. this._update();
  4466. return this;
  4467. },
  4468. // @method removeAttribution(text: String): this
  4469. // Removes an attribution text.
  4470. removeAttribution: function (text) {
  4471. if (!text) { return this; }
  4472. if (this._attributions[text]) {
  4473. this._attributions[text]--;
  4474. this._update();
  4475. }
  4476. return this;
  4477. },
  4478. _update: function () {
  4479. if (!this._map) { return; }
  4480. var attribs = [];
  4481. for (var i in this._attributions) {
  4482. if (this._attributions[i]) {
  4483. attribs.push(i);
  4484. }
  4485. }
  4486. var prefixAndAttribs = [];
  4487. if (this.options.prefix) {
  4488. prefixAndAttribs.push(this.options.prefix);
  4489. }
  4490. if (attribs.length) {
  4491. prefixAndAttribs.push(attribs.join(', '));
  4492. }
  4493. this._container.innerHTML = prefixAndAttribs.join(' | ');
  4494. }
  4495. });
  4496. // @namespace Map
  4497. // @section Control options
  4498. // @option attributionControl: Boolean = true
  4499. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4500. Map.mergeOptions({
  4501. attributionControl: true
  4502. });
  4503. Map.addInitHook(function () {
  4504. if (this.options.attributionControl) {
  4505. new Attribution().addTo(this);
  4506. }
  4507. });
  4508. // @namespace Control.Attribution
  4509. // @factory L.control.attribution(options: Control.Attribution options)
  4510. // Creates an attribution control.
  4511. var attribution = function (options) {
  4512. return new Attribution(options);
  4513. };
  4514. Control.Layers = Layers;
  4515. Control.Zoom = Zoom;
  4516. Control.Scale = Scale;
  4517. Control.Attribution = Attribution;
  4518. control.layers = layers;
  4519. control.zoom = zoom;
  4520. control.scale = scale;
  4521. control.attribution = attribution;
  4522. /*
  4523. L.Handler is a base class for handler classes that are used internally to inject
  4524. interaction features like dragging to classes like Map and Marker.
  4525. */
  4526. // @class Handler
  4527. // @aka L.Handler
  4528. // Abstract class for map interaction handlers
  4529. var Handler = Class.extend({
  4530. initialize: function (map) {
  4531. this._map = map;
  4532. },
  4533. // @method enable(): this
  4534. // Enables the handler
  4535. enable: function () {
  4536. if (this._enabled) { return this; }
  4537. this._enabled = true;
  4538. this.addHooks();
  4539. return this;
  4540. },
  4541. // @method disable(): this
  4542. // Disables the handler
  4543. disable: function () {
  4544. if (!this._enabled) { return this; }
  4545. this._enabled = false;
  4546. this.removeHooks();
  4547. return this;
  4548. },
  4549. // @method enabled(): Boolean
  4550. // Returns `true` if the handler is enabled
  4551. enabled: function () {
  4552. return !!this._enabled;
  4553. }
  4554. // @section Extension methods
  4555. // Classes inheriting from `Handler` must implement the two following methods:
  4556. // @method addHooks()
  4557. // Called when the handler is enabled, should add event hooks.
  4558. // @method removeHooks()
  4559. // Called when the handler is disabled, should remove the event hooks added previously.
  4560. });
  4561. var Mixin = {Events: Events};
  4562. /*
  4563. * @class Draggable
  4564. * @aka L.Draggable
  4565. * @inherits Evented
  4566. *
  4567. * A class for making DOM elements draggable (including touch support).
  4568. * Used internally for map and marker dragging. Only works for elements
  4569. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4570. *
  4571. * @example
  4572. * ```js
  4573. * var draggable = new L.Draggable(elementToDrag);
  4574. * draggable.enable();
  4575. * ```
  4576. */
  4577. var START = touch ? 'touchstart mousedown' : 'mousedown';
  4578. var END = {
  4579. mousedown: 'mouseup',
  4580. touchstart: 'touchend',
  4581. pointerdown: 'touchend',
  4582. MSPointerDown: 'touchend'
  4583. };
  4584. var MOVE = {
  4585. mousedown: 'mousemove',
  4586. touchstart: 'touchmove',
  4587. pointerdown: 'touchmove',
  4588. MSPointerDown: 'touchmove'
  4589. };
  4590. var Draggable = Evented.extend({
  4591. options: {
  4592. // @section
  4593. // @aka Draggable options
  4594. // @option clickTolerance: Number = 3
  4595. // The max number of pixels a user can shift the mouse pointer during a click
  4596. // for it to be considered a valid click (as opposed to a mouse drag).
  4597. clickTolerance: 3
  4598. },
  4599. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4600. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4601. initialize: function (element, dragStartTarget, preventOutline$$1, options) {
  4602. setOptions(this, options);
  4603. this._element = element;
  4604. this._dragStartTarget = dragStartTarget || element;
  4605. this._preventOutline = preventOutline$$1;
  4606. },
  4607. // @method enable()
  4608. // Enables the dragging ability
  4609. enable: function () {
  4610. if (this._enabled) { return; }
  4611. on(this._dragStartTarget, START, this._onDown, this);
  4612. this._enabled = true;
  4613. },
  4614. // @method disable()
  4615. // Disables the dragging ability
  4616. disable: function () {
  4617. if (!this._enabled) { return; }
  4618. // If we're currently dragging this draggable,
  4619. // disabling it counts as first ending the drag.
  4620. if (Draggable._dragging === this) {
  4621. this.finishDrag();
  4622. }
  4623. off(this._dragStartTarget, START, this._onDown, this);
  4624. this._enabled = false;
  4625. this._moved = false;
  4626. },
  4627. _onDown: function (e) {
  4628. // Ignore simulated events, since we handle both touch and
  4629. // mouse explicitly; otherwise we risk getting duplicates of
  4630. // touch events, see #4315.
  4631. // Also ignore the event if disabled; this happens in IE11
  4632. // under some circumstances, see #3666.
  4633. if (e._simulated || !this._enabled) { return; }
  4634. this._moved = false;
  4635. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4636. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4637. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4638. if (this._preventOutline) {
  4639. preventOutline(this._element);
  4640. }
  4641. disableImageDrag();
  4642. disableTextSelection();
  4643. if (this._moving) { return; }
  4644. // @event down: Event
  4645. // Fired when a drag is about to start.
  4646. this.fire('down');
  4647. var first = e.touches ? e.touches[0] : e;
  4648. this._startPoint = new Point(first.clientX, first.clientY);
  4649. on(document, MOVE[e.type], this._onMove, this);
  4650. on(document, END[e.type], this._onUp, this);
  4651. },
  4652. _onMove: function (e) {
  4653. // Ignore simulated events, since we handle both touch and
  4654. // mouse explicitly; otherwise we risk getting duplicates of
  4655. // touch events, see #4315.
  4656. // Also ignore the event if disabled; this happens in IE11
  4657. // under some circumstances, see #3666.
  4658. if (e._simulated || !this._enabled) { return; }
  4659. if (e.touches && e.touches.length > 1) {
  4660. this._moved = true;
  4661. return;
  4662. }
  4663. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4664. newPoint = new Point(first.clientX, first.clientY),
  4665. offset = newPoint.subtract(this._startPoint);
  4666. if (!offset.x && !offset.y) { return; }
  4667. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4668. preventDefault(e);
  4669. if (!this._moved) {
  4670. // @event dragstart: Event
  4671. // Fired when a drag starts
  4672. this.fire('dragstart');
  4673. this._moved = true;
  4674. this._startPos = getPosition(this._element).subtract(offset);
  4675. addClass(document.body, 'leaflet-dragging');
  4676. this._lastTarget = e.target || e.srcElement;
  4677. // IE and Edge do not give the <use> element, so fetch it
  4678. // if necessary
  4679. if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
  4680. this._lastTarget = this._lastTarget.correspondingUseElement;
  4681. }
  4682. addClass(this._lastTarget, 'leaflet-drag-target');
  4683. }
  4684. this._newPos = this._startPos.add(offset);
  4685. this._moving = true;
  4686. cancelAnimFrame(this._animRequest);
  4687. this._lastEvent = e;
  4688. this._animRequest = requestAnimFrame(this._updatePosition, this, true);
  4689. },
  4690. _updatePosition: function () {
  4691. var e = {originalEvent: this._lastEvent};
  4692. // @event predrag: Event
  4693. // Fired continuously during dragging *before* each corresponding
  4694. // update of the element's position.
  4695. this.fire('predrag', e);
  4696. setPosition(this._element, this._newPos);
  4697. // @event drag: Event
  4698. // Fired continuously during dragging.
  4699. this.fire('drag', e);
  4700. },
  4701. _onUp: function (e) {
  4702. // Ignore simulated events, since we handle both touch and
  4703. // mouse explicitly; otherwise we risk getting duplicates of
  4704. // touch events, see #4315.
  4705. // Also ignore the event if disabled; this happens in IE11
  4706. // under some circumstances, see #3666.
  4707. if (e._simulated || !this._enabled) { return; }
  4708. this.finishDrag();
  4709. },
  4710. finishDrag: function () {
  4711. removeClass(document.body, 'leaflet-dragging');
  4712. if (this._lastTarget) {
  4713. removeClass(this._lastTarget, 'leaflet-drag-target');
  4714. this._lastTarget = null;
  4715. }
  4716. for (var i in MOVE) {
  4717. off(document, MOVE[i], this._onMove, this);
  4718. off(document, END[i], this._onUp, this);
  4719. }
  4720. enableImageDrag();
  4721. enableTextSelection();
  4722. if (this._moved && this._moving) {
  4723. // ensure drag is not fired after dragend
  4724. cancelAnimFrame(this._animRequest);
  4725. // @event dragend: DragEndEvent
  4726. // Fired when the drag ends.
  4727. this.fire('dragend', {
  4728. distance: this._newPos.distanceTo(this._startPos)
  4729. });
  4730. }
  4731. this._moving = false;
  4732. Draggable._dragging = false;
  4733. }
  4734. });
  4735. /*
  4736. * @namespace LineUtil
  4737. *
  4738. * Various utility functions for polyine points processing, used by Leaflet internally to make polylines lightning-fast.
  4739. */
  4740. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  4741. // Improves rendering performance dramatically by lessening the number of points to draw.
  4742. // @function simplify(points: Point[], tolerance: Number): Point[]
  4743. // Dramatically reduces the number of points in a polyline while retaining
  4744. // its shape and returns a new array of simplified points, using the
  4745. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  4746. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  4747. // each zoom level and also reducing visual noise. tolerance affects the amount of
  4748. // simplification (lesser value means higher quality but slower and with more points).
  4749. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  4750. function simplify(points, tolerance) {
  4751. if (!tolerance || !points.length) {
  4752. return points.slice();
  4753. }
  4754. var sqTolerance = tolerance * tolerance;
  4755. // stage 1: vertex reduction
  4756. points = _reducePoints(points, sqTolerance);
  4757. // stage 2: Douglas-Peucker simplification
  4758. points = _simplifyDP(points, sqTolerance);
  4759. return points;
  4760. }
  4761. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  4762. // Returns the distance between point `p` and segment `p1` to `p2`.
  4763. function pointToSegmentDistance(p, p1, p2) {
  4764. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  4765. }
  4766. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  4767. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  4768. function closestPointOnSegment(p, p1, p2) {
  4769. return _sqClosestPointOnSegment(p, p1, p2);
  4770. }
  4771. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  4772. function _simplifyDP(points, sqTolerance) {
  4773. var len = points.length,
  4774. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  4775. markers = new ArrayConstructor(len);
  4776. markers[0] = markers[len - 1] = 1;
  4777. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  4778. var i,
  4779. newPoints = [];
  4780. for (i = 0; i < len; i++) {
  4781. if (markers[i]) {
  4782. newPoints.push(points[i]);
  4783. }
  4784. }
  4785. return newPoints;
  4786. }
  4787. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  4788. var maxSqDist = 0,
  4789. index, i, sqDist;
  4790. for (i = first + 1; i <= last - 1; i++) {
  4791. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  4792. if (sqDist > maxSqDist) {
  4793. index = i;
  4794. maxSqDist = sqDist;
  4795. }
  4796. }
  4797. if (maxSqDist > sqTolerance) {
  4798. markers[index] = 1;
  4799. _simplifyDPStep(points, markers, sqTolerance, first, index);
  4800. _simplifyDPStep(points, markers, sqTolerance, index, last);
  4801. }
  4802. }
  4803. // reduce points that are too close to each other to a single point
  4804. function _reducePoints(points, sqTolerance) {
  4805. var reducedPoints = [points[0]];
  4806. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  4807. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  4808. reducedPoints.push(points[i]);
  4809. prev = i;
  4810. }
  4811. }
  4812. if (prev < len - 1) {
  4813. reducedPoints.push(points[len - 1]);
  4814. }
  4815. return reducedPoints;
  4816. }
  4817. var _lastCode;
  4818. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  4819. // Clips the segment a to b by rectangular bounds with the
  4820. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  4821. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  4822. // points that are on the screen or near, increasing performance.
  4823. function clipSegment(a, b, bounds, useLastCode, round) {
  4824. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  4825. codeB = _getBitCode(b, bounds),
  4826. codeOut, p, newCode;
  4827. // save 2nd code to avoid calculating it on the next segment
  4828. _lastCode = codeB;
  4829. while (true) {
  4830. // if a,b is inside the clip window (trivial accept)
  4831. if (!(codeA | codeB)) {
  4832. return [a, b];
  4833. }
  4834. // if a,b is outside the clip window (trivial reject)
  4835. if (codeA & codeB) {
  4836. return false;
  4837. }
  4838. // other cases
  4839. codeOut = codeA || codeB;
  4840. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  4841. newCode = _getBitCode(p, bounds);
  4842. if (codeOut === codeA) {
  4843. a = p;
  4844. codeA = newCode;
  4845. } else {
  4846. b = p;
  4847. codeB = newCode;
  4848. }
  4849. }
  4850. }
  4851. function _getEdgeIntersection(a, b, code, bounds, round) {
  4852. var dx = b.x - a.x,
  4853. dy = b.y - a.y,
  4854. min = bounds.min,
  4855. max = bounds.max,
  4856. x, y;
  4857. if (code & 8) { // top
  4858. x = a.x + dx * (max.y - a.y) / dy;
  4859. y = max.y;
  4860. } else if (code & 4) { // bottom
  4861. x = a.x + dx * (min.y - a.y) / dy;
  4862. y = min.y;
  4863. } else if (code & 2) { // right
  4864. x = max.x;
  4865. y = a.y + dy * (max.x - a.x) / dx;
  4866. } else if (code & 1) { // left
  4867. x = min.x;
  4868. y = a.y + dy * (min.x - a.x) / dx;
  4869. }
  4870. return new Point(x, y, round);
  4871. }
  4872. function _getBitCode(p, bounds) {
  4873. var code = 0;
  4874. if (p.x < bounds.min.x) { // left
  4875. code |= 1;
  4876. } else if (p.x > bounds.max.x) { // right
  4877. code |= 2;
  4878. }
  4879. if (p.y < bounds.min.y) { // bottom
  4880. code |= 4;
  4881. } else if (p.y > bounds.max.y) { // top
  4882. code |= 8;
  4883. }
  4884. return code;
  4885. }
  4886. // square distance (to avoid unnecessary Math.sqrt calls)
  4887. function _sqDist(p1, p2) {
  4888. var dx = p2.x - p1.x,
  4889. dy = p2.y - p1.y;
  4890. return dx * dx + dy * dy;
  4891. }
  4892. // return closest point on segment or distance to that point
  4893. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  4894. var x = p1.x,
  4895. y = p1.y,
  4896. dx = p2.x - x,
  4897. dy = p2.y - y,
  4898. dot = dx * dx + dy * dy,
  4899. t;
  4900. if (dot > 0) {
  4901. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  4902. if (t > 1) {
  4903. x = p2.x;
  4904. y = p2.y;
  4905. } else if (t > 0) {
  4906. x += dx * t;
  4907. y += dy * t;
  4908. }
  4909. }
  4910. dx = p.x - x;
  4911. dy = p.y - y;
  4912. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  4913. }
  4914. // @function isFlat(latlngs: LatLng[]): Boolean
  4915. // Returns true if `latlngs` is a flat array, false is nested.
  4916. function isFlat(latlngs) {
  4917. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  4918. }
  4919. function _flat(latlngs) {
  4920. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  4921. return isFlat(latlngs);
  4922. }
  4923. var LineUtil = (Object.freeze || Object)({
  4924. simplify: simplify,
  4925. pointToSegmentDistance: pointToSegmentDistance,
  4926. closestPointOnSegment: closestPointOnSegment,
  4927. clipSegment: clipSegment,
  4928. _getEdgeIntersection: _getEdgeIntersection,
  4929. _getBitCode: _getBitCode,
  4930. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  4931. isFlat: isFlat,
  4932. _flat: _flat
  4933. });
  4934. /*
  4935. * @namespace PolyUtil
  4936. * Various utility functions for polygon geometries.
  4937. */
  4938. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  4939. * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgeman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).
  4940. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  4941. * performance. Note that polygon points needs different algorithm for clipping
  4942. * than polyline, so there's a seperate method for it.
  4943. */
  4944. function clipPolygon(points, bounds, round) {
  4945. var clippedPoints,
  4946. edges = [1, 4, 2, 8],
  4947. i, j, k,
  4948. a, b,
  4949. len, edge, p;
  4950. for (i = 0, len = points.length; i < len; i++) {
  4951. points[i]._code = _getBitCode(points[i], bounds);
  4952. }
  4953. // for each edge (left, bottom, right, top)
  4954. for (k = 0; k < 4; k++) {
  4955. edge = edges[k];
  4956. clippedPoints = [];
  4957. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  4958. a = points[i];
  4959. b = points[j];
  4960. // if a is inside the clip window
  4961. if (!(a._code & edge)) {
  4962. // if b is outside the clip window (a->b goes out of screen)
  4963. if (b._code & edge) {
  4964. p = _getEdgeIntersection(b, a, edge, bounds, round);
  4965. p._code = _getBitCode(p, bounds);
  4966. clippedPoints.push(p);
  4967. }
  4968. clippedPoints.push(a);
  4969. // else if b is inside the clip window (a->b enters the screen)
  4970. } else if (!(b._code & edge)) {
  4971. p = _getEdgeIntersection(b, a, edge, bounds, round);
  4972. p._code = _getBitCode(p, bounds);
  4973. clippedPoints.push(p);
  4974. }
  4975. }
  4976. points = clippedPoints;
  4977. }
  4978. return points;
  4979. }
  4980. var PolyUtil = (Object.freeze || Object)({
  4981. clipPolygon: clipPolygon
  4982. });
  4983. /*
  4984. * @namespace Projection
  4985. * @section
  4986. * Leaflet comes with a set of already defined Projections out of the box:
  4987. *
  4988. * @projection L.Projection.LonLat
  4989. *
  4990. * Equirectangular, or Plate Carree projection — the most simple projection,
  4991. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  4992. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  4993. * `EPSG:4326` and `Simple` CRS.
  4994. */
  4995. var LonLat = {
  4996. project: function (latlng) {
  4997. return new Point(latlng.lng, latlng.lat);
  4998. },
  4999. unproject: function (point) {
  5000. return new LatLng(point.y, point.x);
  5001. },
  5002. bounds: new Bounds([-180, -90], [180, 90])
  5003. };
  5004. /*
  5005. * @namespace Projection
  5006. * @projection L.Projection.Mercator
  5007. *
  5008. * Elliptical Mercator projection — more complex than Spherical Mercator. Takes into account that Earth is a geoid, not a perfect sphere. Used by the EPSG:3395 CRS.
  5009. */
  5010. var Mercator = {
  5011. R: 6378137,
  5012. R_MINOR: 6356752.314245179,
  5013. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5014. project: function (latlng) {
  5015. var d = Math.PI / 180,
  5016. r = this.R,
  5017. y = latlng.lat * d,
  5018. tmp = this.R_MINOR / r,
  5019. e = Math.sqrt(1 - tmp * tmp),
  5020. con = e * Math.sin(y);
  5021. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5022. y = -r * Math.log(Math.max(ts, 1E-10));
  5023. return new Point(latlng.lng * d * r, y);
  5024. },
  5025. unproject: function (point) {
  5026. var d = 180 / Math.PI,
  5027. r = this.R,
  5028. tmp = this.R_MINOR / r,
  5029. e = Math.sqrt(1 - tmp * tmp),
  5030. ts = Math.exp(-point.y / r),
  5031. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5032. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5033. con = e * Math.sin(phi);
  5034. con = Math.pow((1 - con) / (1 + con), e / 2);
  5035. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5036. phi += dphi;
  5037. }
  5038. return new LatLng(phi * d, point.x * d / r);
  5039. }
  5040. };
  5041. /*
  5042. * @class Projection
  5043. * An object with methods for projecting geographical coordinates of the world onto
  5044. * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).
  5045. * @property bounds: Bounds
  5046. * The bounds (specified in CRS units) where the projection is valid
  5047. * @method project(latlng: LatLng): Point
  5048. * Projects geographical coordinates into a 2D point.
  5049. * Only accepts actual `L.LatLng` instances, not arrays.
  5050. * @method unproject(point: Point): LatLng
  5051. * The inverse of `project`. Projects a 2D point into a geographical location.
  5052. * Only accepts actual `L.Point` instances, not arrays.
  5053. */
  5054. var index = (Object.freeze || Object)({
  5055. LonLat: LonLat,
  5056. Mercator: Mercator,
  5057. SphericalMercator: SphericalMercator
  5058. });
  5059. /*
  5060. * @namespace CRS
  5061. * @crs L.CRS.EPSG3395
  5062. *
  5063. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5064. */
  5065. var EPSG3395 = extend({}, Earth, {
  5066. code: 'EPSG:3395',
  5067. projection: Mercator,
  5068. transformation: (function () {
  5069. var scale = 0.5 / (Math.PI * Mercator.R);
  5070. return toTransformation(scale, 0.5, -scale, 0.5);
  5071. }())
  5072. });
  5073. /*
  5074. * @namespace CRS
  5075. * @crs L.CRS.EPSG4326
  5076. *
  5077. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5078. *
  5079. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5080. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5081. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5082. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5083. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5084. */
  5085. var EPSG4326 = extend({}, Earth, {
  5086. code: 'EPSG:4326',
  5087. projection: LonLat,
  5088. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5089. });
  5090. /*
  5091. * @namespace CRS
  5092. * @crs L.CRS.Simple
  5093. *
  5094. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5095. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5096. * axis should still be inverted (going from bottom to top). `distance()` returns
  5097. * simple euclidean distance.
  5098. */
  5099. var Simple = extend({}, CRS, {
  5100. projection: LonLat,
  5101. transformation: toTransformation(1, 0, -1, 0),
  5102. scale: function (zoom) {
  5103. return Math.pow(2, zoom);
  5104. },
  5105. zoom: function (scale) {
  5106. return Math.log(scale) / Math.LN2;
  5107. },
  5108. distance: function (latlng1, latlng2) {
  5109. var dx = latlng2.lng - latlng1.lng,
  5110. dy = latlng2.lat - latlng1.lat;
  5111. return Math.sqrt(dx * dx + dy * dy);
  5112. },
  5113. infinite: true
  5114. });
  5115. CRS.Earth = Earth;
  5116. CRS.EPSG3395 = EPSG3395;
  5117. CRS.EPSG3857 = EPSG3857;
  5118. CRS.EPSG900913 = EPSG900913;
  5119. CRS.EPSG4326 = EPSG4326;
  5120. CRS.Simple = Simple;
  5121. /*
  5122. * @class Layer
  5123. * @inherits Evented
  5124. * @aka L.Layer
  5125. * @aka ILayer
  5126. *
  5127. * A set of methods from the Layer base class that all Leaflet layers use.
  5128. * Inherits all methods, options and events from `L.Evented`.
  5129. *
  5130. * @example
  5131. *
  5132. * ```js
  5133. * var layer = L.Marker(latlng).addTo(map);
  5134. * layer.addTo(map);
  5135. * layer.remove();
  5136. * ```
  5137. *
  5138. * @event add: Event
  5139. * Fired after the layer is added to a map
  5140. *
  5141. * @event remove: Event
  5142. * Fired after the layer is removed from a map
  5143. */
  5144. var Layer = Evented.extend({
  5145. // Classes extending `L.Layer` will inherit the following options:
  5146. options: {
  5147. // @option pane: String = 'overlayPane'
  5148. // By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default.
  5149. pane: 'overlayPane',
  5150. // @option attribution: String = null
  5151. // String to be shown in the attribution control, describes the layer data, e.g. "© Mapbox".
  5152. attribution: null,
  5153. bubblingMouseEvents: true
  5154. },
  5155. /* @section
  5156. * Classes extending `L.Layer` will inherit the following methods:
  5157. *
  5158. * @method addTo(map: Map|LayerGroup): this
  5159. * Adds the layer to the given map or layer group.
  5160. */
  5161. addTo: function (map) {
  5162. map.addLayer(this);
  5163. return this;
  5164. },
  5165. // @method remove: this
  5166. // Removes the layer from the map it is currently active on.
  5167. remove: function () {
  5168. return this.removeFrom(this._map || this._mapToAdd);
  5169. },
  5170. // @method removeFrom(map: Map): this
  5171. // Removes the layer from the given map
  5172. removeFrom: function (obj) {
  5173. if (obj) {
  5174. obj.removeLayer(this);
  5175. }
  5176. return this;
  5177. },
  5178. // @method getPane(name? : String): HTMLElement
  5179. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5180. getPane: function (name) {
  5181. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5182. },
  5183. addInteractiveTarget: function (targetEl) {
  5184. this._map._targets[stamp(targetEl)] = this;
  5185. return this;
  5186. },
  5187. removeInteractiveTarget: function (targetEl) {
  5188. delete this._map._targets[stamp(targetEl)];
  5189. return this;
  5190. },
  5191. // @method getAttribution: String
  5192. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5193. getAttribution: function () {
  5194. return this.options.attribution;
  5195. },
  5196. _layerAdd: function (e) {
  5197. var map = e.target;
  5198. // check in case layer gets added and then removed before the map is ready
  5199. if (!map.hasLayer(this)) { return; }
  5200. this._map = map;
  5201. this._zoomAnimated = map._zoomAnimated;
  5202. if (this.getEvents) {
  5203. var events = this.getEvents();
  5204. map.on(events, this);
  5205. this.once('remove', function () {
  5206. map.off(events, this);
  5207. }, this);
  5208. }
  5209. this.onAdd(map);
  5210. if (this.getAttribution && map.attributionControl) {
  5211. map.attributionControl.addAttribution(this.getAttribution());
  5212. }
  5213. this.fire('add');
  5214. map.fire('layeradd', {layer: this});
  5215. }
  5216. });
  5217. /* @section Extension methods
  5218. * @uninheritable
  5219. *
  5220. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5221. *
  5222. * @method onAdd(map: Map): this
  5223. * Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer).
  5224. *
  5225. * @method onRemove(map: Map): this
  5226. * Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer).
  5227. *
  5228. * @method getEvents(): Object
  5229. * This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#evented-addeventlistener). The event handlers in this object will be automatically added and removed from the map with your layer.
  5230. *
  5231. * @method getAttribution(): String
  5232. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5233. *
  5234. * @method beforeAdd(map: Map): this
  5235. * Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only.
  5236. */
  5237. /* @namespace Map
  5238. * @section Layer events
  5239. *
  5240. * @event layeradd: LayerEvent
  5241. * Fired when a new layer is added to the map.
  5242. *
  5243. * @event layerremove: LayerEvent
  5244. * Fired when some layer is removed from the map
  5245. *
  5246. * @section Methods for Layers and Controls
  5247. */
  5248. Map.include({
  5249. // @method addLayer(layer: Layer): this
  5250. // Adds the given layer to the map
  5251. addLayer: function (layer) {
  5252. if (!layer._layerAdd) {
  5253. throw new Error('The provided object is not a Layer.');
  5254. }
  5255. var id = stamp(layer);
  5256. if (this._layers[id]) { return this; }
  5257. this._layers[id] = layer;
  5258. layer._mapToAdd = this;
  5259. if (layer.beforeAdd) {
  5260. layer.beforeAdd(this);
  5261. }
  5262. this.whenReady(layer._layerAdd, layer);
  5263. return this;
  5264. },
  5265. // @method removeLayer(layer: Layer): this
  5266. // Removes the given layer from the map.
  5267. removeLayer: function (layer) {
  5268. var id = stamp(layer);
  5269. if (!this._layers[id]) { return this; }
  5270. if (this._loaded) {
  5271. layer.onRemove(this);
  5272. }
  5273. if (layer.getAttribution && this.attributionControl) {
  5274. this.attributionControl.removeAttribution(layer.getAttribution());
  5275. }
  5276. delete this._layers[id];
  5277. if (this._loaded) {
  5278. this.fire('layerremove', {layer: layer});
  5279. layer.fire('remove');
  5280. }
  5281. layer._map = layer._mapToAdd = null;
  5282. return this;
  5283. },
  5284. // @method hasLayer(layer: Layer): Boolean
  5285. // Returns `true` if the given layer is currently added to the map
  5286. hasLayer: function (layer) {
  5287. return !!layer && (stamp(layer) in this._layers);
  5288. },
  5289. /* @method eachLayer(fn: Function, context?: Object): this
  5290. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5291. * ```
  5292. * map.eachLayer(function(layer){
  5293. * layer.bindPopup('Hello');
  5294. * });
  5295. * ```
  5296. */
  5297. eachLayer: function (method, context) {
  5298. for (var i in this._layers) {
  5299. method.call(context, this._layers[i]);
  5300. }
  5301. return this;
  5302. },
  5303. _addLayers: function (layers) {
  5304. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5305. for (var i = 0, len = layers.length; i < len; i++) {
  5306. this.addLayer(layers[i]);
  5307. }
  5308. },
  5309. _addZoomLimit: function (layer) {
  5310. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5311. this._zoomBoundLayers[stamp(layer)] = layer;
  5312. this._updateZoomLevels();
  5313. }
  5314. },
  5315. _removeZoomLimit: function (layer) {
  5316. var id = stamp(layer);
  5317. if (this._zoomBoundLayers[id]) {
  5318. delete this._zoomBoundLayers[id];
  5319. this._updateZoomLevels();
  5320. }
  5321. },
  5322. _updateZoomLevels: function () {
  5323. var minZoom = Infinity,
  5324. maxZoom = -Infinity,
  5325. oldZoomSpan = this._getZoomSpan();
  5326. for (var i in this._zoomBoundLayers) {
  5327. var options = this._zoomBoundLayers[i].options;
  5328. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5329. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5330. }
  5331. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5332. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5333. // @section Map state change events
  5334. // @event zoomlevelschange: Event
  5335. // Fired when the number of zoomlevels on the map is changed due
  5336. // to adding or removing a layer.
  5337. if (oldZoomSpan !== this._getZoomSpan()) {
  5338. this.fire('zoomlevelschange');
  5339. }
  5340. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5341. this.setZoom(this._layersMaxZoom);
  5342. }
  5343. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5344. this.setZoom(this._layersMinZoom);
  5345. }
  5346. }
  5347. });
  5348. /*
  5349. * @class LayerGroup
  5350. * @aka L.LayerGroup
  5351. * @inherits Layer
  5352. *
  5353. * Used to group several layers and handle them as one. If you add it to the map,
  5354. * any layers added or removed from the group will be added/removed on the map as
  5355. * well. Extends `Layer`.
  5356. *
  5357. * @example
  5358. *
  5359. * ```js
  5360. * L.layerGroup([marker1, marker2])
  5361. * .addLayer(polyline)
  5362. * .addTo(map);
  5363. * ```
  5364. */
  5365. var LayerGroup = Layer.extend({
  5366. initialize: function (layers) {
  5367. this._layers = {};
  5368. var i, len;
  5369. if (layers) {
  5370. for (i = 0, len = layers.length; i < len; i++) {
  5371. this.addLayer(layers[i]);
  5372. }
  5373. }
  5374. },
  5375. // @method addLayer(layer: Layer): this
  5376. // Adds the given layer to the group.
  5377. addLayer: function (layer) {
  5378. var id = this.getLayerId(layer);
  5379. this._layers[id] = layer;
  5380. if (this._map) {
  5381. this._map.addLayer(layer);
  5382. }
  5383. return this;
  5384. },
  5385. // @method removeLayer(layer: Layer): this
  5386. // Removes the given layer from the group.
  5387. // @alternative
  5388. // @method removeLayer(id: Number): this
  5389. // Removes the layer with the given internal ID from the group.
  5390. removeLayer: function (layer) {
  5391. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5392. if (this._map && this._layers[id]) {
  5393. this._map.removeLayer(this._layers[id]);
  5394. }
  5395. delete this._layers[id];
  5396. return this;
  5397. },
  5398. // @method hasLayer(layer: Layer): Boolean
  5399. // Returns `true` if the given layer is currently added to the group.
  5400. // @alternative
  5401. // @method hasLayer(id: Number): Boolean
  5402. // Returns `true` if the given internal ID is currently added to the group.
  5403. hasLayer: function (layer) {
  5404. return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
  5405. },
  5406. // @method clearLayers(): this
  5407. // Removes all the layers from the group.
  5408. clearLayers: function () {
  5409. for (var i in this._layers) {
  5410. this.removeLayer(this._layers[i]);
  5411. }
  5412. return this;
  5413. },
  5414. // @method invoke(methodName: String, …): this
  5415. // Calls `methodName` on every layer contained in this group, passing any
  5416. // additional parameters. Has no effect if the layers contained do not
  5417. // implement `methodName`.
  5418. invoke: function (methodName) {
  5419. var args = Array.prototype.slice.call(arguments, 1),
  5420. i, layer;
  5421. for (i in this._layers) {
  5422. layer = this._layers[i];
  5423. if (layer[methodName]) {
  5424. layer[methodName].apply(layer, args);
  5425. }
  5426. }
  5427. return this;
  5428. },
  5429. onAdd: function (map) {
  5430. for (var i in this._layers) {
  5431. map.addLayer(this._layers[i]);
  5432. }
  5433. },
  5434. onRemove: function (map) {
  5435. for (var i in this._layers) {
  5436. map.removeLayer(this._layers[i]);
  5437. }
  5438. },
  5439. // @method eachLayer(fn: Function, context?: Object): this
  5440. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5441. // ```js
  5442. // group.eachLayer(function (layer) {
  5443. // layer.bindPopup('Hello');
  5444. // });
  5445. // ```
  5446. eachLayer: function (method, context) {
  5447. for (var i in this._layers) {
  5448. method.call(context, this._layers[i]);
  5449. }
  5450. return this;
  5451. },
  5452. // @method getLayer(id: Number): Layer
  5453. // Returns the layer with the given internal ID.
  5454. getLayer: function (id) {
  5455. return this._layers[id];
  5456. },
  5457. // @method getLayers(): Layer[]
  5458. // Returns an array of all the layers added to the group.
  5459. getLayers: function () {
  5460. var layers = [];
  5461. for (var i in this._layers) {
  5462. layers.push(this._layers[i]);
  5463. }
  5464. return layers;
  5465. },
  5466. // @method setZIndex(zIndex: Number): this
  5467. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5468. setZIndex: function (zIndex) {
  5469. return this.invoke('setZIndex', zIndex);
  5470. },
  5471. // @method getLayerId(layer: Layer): Number
  5472. // Returns the internal ID for a layer
  5473. getLayerId: function (layer) {
  5474. return stamp(layer);
  5475. }
  5476. });
  5477. // @factory L.layerGroup(layers?: Layer[])
  5478. // Create a layer group, optionally given an initial set of layers.
  5479. var layerGroup = function (layers) {
  5480. return new LayerGroup(layers);
  5481. };
  5482. /*
  5483. * @class FeatureGroup
  5484. * @aka L.FeatureGroup
  5485. * @inherits LayerGroup
  5486. *
  5487. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5488. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5489. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5490. * handler, it will handle events from any of the layers. This includes mouse events
  5491. * and custom events.
  5492. * * Has `layeradd` and `layerremove` events
  5493. *
  5494. * @example
  5495. *
  5496. * ```js
  5497. * L.featureGroup([marker1, marker2, polyline])
  5498. * .bindPopup('Hello world!')
  5499. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5500. * .addTo(map);
  5501. * ```
  5502. */
  5503. var FeatureGroup = LayerGroup.extend({
  5504. addLayer: function (layer) {
  5505. if (this.hasLayer(layer)) {
  5506. return this;
  5507. }
  5508. layer.addEventParent(this);
  5509. LayerGroup.prototype.addLayer.call(this, layer);
  5510. // @event layeradd: LayerEvent
  5511. // Fired when a layer is added to this `FeatureGroup`
  5512. return this.fire('layeradd', {layer: layer});
  5513. },
  5514. removeLayer: function (layer) {
  5515. if (!this.hasLayer(layer)) {
  5516. return this;
  5517. }
  5518. if (layer in this._layers) {
  5519. layer = this._layers[layer];
  5520. }
  5521. layer.removeEventParent(this);
  5522. LayerGroup.prototype.removeLayer.call(this, layer);
  5523. // @event layerremove: LayerEvent
  5524. // Fired when a layer is removed from this `FeatureGroup`
  5525. return this.fire('layerremove', {layer: layer});
  5526. },
  5527. // @method setStyle(style: Path options): this
  5528. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5529. setStyle: function (style) {
  5530. return this.invoke('setStyle', style);
  5531. },
  5532. // @method bringToFront(): this
  5533. // Brings the layer group to the top of all other layers
  5534. bringToFront: function () {
  5535. return this.invoke('bringToFront');
  5536. },
  5537. // @method bringToBack(): this
  5538. // Brings the layer group to the top of all other layers
  5539. bringToBack: function () {
  5540. return this.invoke('bringToBack');
  5541. },
  5542. // @method getBounds(): LatLngBounds
  5543. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5544. getBounds: function () {
  5545. var bounds = new LatLngBounds();
  5546. for (var id in this._layers) {
  5547. var layer = this._layers[id];
  5548. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5549. }
  5550. return bounds;
  5551. }
  5552. });
  5553. // @factory L.featureGroup(layers: Layer[])
  5554. // Create a feature group, optionally given an initial set of layers.
  5555. var featureGroup = function (layers) {
  5556. return new FeatureGroup(layers);
  5557. };
  5558. /*
  5559. * @class Icon
  5560. * @aka L.Icon
  5561. *
  5562. * Represents an icon to provide when creating a marker.
  5563. *
  5564. * @example
  5565. *
  5566. * ```js
  5567. * var myIcon = L.icon({
  5568. * iconUrl: 'my-icon.png',
  5569. * iconRetinaUrl: 'my-icon@2x.png',
  5570. * iconSize: [38, 95],
  5571. * iconAnchor: [22, 94],
  5572. * popupAnchor: [-3, -76],
  5573. * shadowUrl: 'my-icon-shadow.png',
  5574. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5575. * shadowSize: [68, 95],
  5576. * shadowAnchor: [22, 94]
  5577. * });
  5578. *
  5579. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5580. * ```
  5581. *
  5582. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5583. *
  5584. */
  5585. var Icon = Class.extend({
  5586. /* @section
  5587. * @aka Icon options
  5588. *
  5589. * @option iconUrl: String = null
  5590. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5591. *
  5592. * @option iconRetinaUrl: String = null
  5593. * The URL to a retina sized version of the icon image (absolute or relative to your
  5594. * script path). Used for Retina screen devices.
  5595. *
  5596. * @option iconSize: Point = null
  5597. * Size of the icon image in pixels.
  5598. *
  5599. * @option iconAnchor: Point = null
  5600. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5601. * will be aligned so that this point is at the marker's geographical location. Centered
  5602. * by default if size is specified, also can be set in CSS with negative margins.
  5603. *
  5604. * @option popupAnchor: Point = null
  5605. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5606. *
  5607. * @option shadowUrl: String = null
  5608. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  5609. *
  5610. * @option shadowRetinaUrl: String = null
  5611. *
  5612. * @option shadowSize: Point = null
  5613. * Size of the shadow image in pixels.
  5614. *
  5615. * @option shadowAnchor: Point = null
  5616. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  5617. * as iconAnchor if not specified).
  5618. *
  5619. * @option className: String = ''
  5620. * A custom class name to assign to both icon and shadow images. Empty by default.
  5621. */
  5622. initialize: function (options) {
  5623. setOptions(this, options);
  5624. },
  5625. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  5626. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  5627. // styled according to the options.
  5628. createIcon: function (oldIcon) {
  5629. return this._createIcon('icon', oldIcon);
  5630. },
  5631. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  5632. // As `createIcon`, but for the shadow beneath it.
  5633. createShadow: function (oldIcon) {
  5634. return this._createIcon('shadow', oldIcon);
  5635. },
  5636. _createIcon: function (name, oldIcon) {
  5637. var src = this._getIconUrl(name);
  5638. if (!src) {
  5639. if (name === 'icon') {
  5640. throw new Error('iconUrl not set in Icon options (see the docs).');
  5641. }
  5642. return null;
  5643. }
  5644. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  5645. this._setIconStyles(img, name);
  5646. return img;
  5647. },
  5648. _setIconStyles: function (img, name) {
  5649. var options = this.options;
  5650. var sizeOption = options[name + 'Size'];
  5651. if (typeof sizeOption === 'number') {
  5652. sizeOption = [sizeOption, sizeOption];
  5653. }
  5654. var size = toPoint(sizeOption),
  5655. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  5656. size && size.divideBy(2, true));
  5657. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  5658. if (anchor) {
  5659. img.style.marginLeft = (-anchor.x) + 'px';
  5660. img.style.marginTop = (-anchor.y) + 'px';
  5661. }
  5662. if (size) {
  5663. img.style.width = size.x + 'px';
  5664. img.style.height = size.y + 'px';
  5665. }
  5666. },
  5667. _createImg: function (src, el) {
  5668. el = el || document.createElement('img');
  5669. el.src = src;
  5670. return el;
  5671. },
  5672. _getIconUrl: function (name) {
  5673. return retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  5674. }
  5675. });
  5676. // @factory L.icon(options: Icon options)
  5677. // Creates an icon instance with the given options.
  5678. function icon(options) {
  5679. return new Icon(options);
  5680. }
  5681. /*
  5682. * @miniclass Icon.Default (Icon)
  5683. * @aka L.Icon.Default
  5684. * @section
  5685. *
  5686. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  5687. * no icon is specified. Points to the blue marker image distributed with Leaflet
  5688. * releases.
  5689. *
  5690. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  5691. * (which is a set of `Icon options`).
  5692. *
  5693. * If you want to _completely_ replace the default icon, override the
  5694. * `L.Marker.prototype.options.icon` with your own icon instead.
  5695. */
  5696. var IconDefault = Icon.extend({
  5697. options: {
  5698. iconUrl: 'marker-icon.png',
  5699. iconRetinaUrl: 'marker-icon-2x.png',
  5700. shadowUrl: 'marker-shadow.png',
  5701. iconSize: [25, 41],
  5702. iconAnchor: [12, 41],
  5703. popupAnchor: [1, -34],
  5704. tooltipAnchor: [16, -28],
  5705. shadowSize: [41, 41]
  5706. },
  5707. _getIconUrl: function (name) {
  5708. if (!IconDefault.imagePath) { // Deprecated, backwards-compatibility only
  5709. IconDefault.imagePath = this._detectIconPath();
  5710. }
  5711. // @option imagePath: String
  5712. // `Icon.Default` will try to auto-detect the absolute location of the
  5713. // blue icon images. If you are placing these images in a non-standard
  5714. // way, set this option to point to the right absolute path.
  5715. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  5716. },
  5717. _detectIconPath: function () {
  5718. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  5719. var path = getStyle(el, 'background-image') ||
  5720. getStyle(el, 'backgroundImage'); // IE8
  5721. document.body.removeChild(el);
  5722. if (path === null || path.indexOf('url') !== 0) {
  5723. path = '';
  5724. } else {
  5725. path = path.replace(/^url\([\"\']?/, '').replace(/marker-icon\.png[\"\']?\)$/, '');
  5726. }
  5727. return path;
  5728. }
  5729. });
  5730. /*
  5731. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  5732. */
  5733. /* @namespace Marker
  5734. * @section Interaction handlers
  5735. *
  5736. * Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see `Handler` methods). Example:
  5737. *
  5738. * ```js
  5739. * marker.dragging.disable();
  5740. * ```
  5741. *
  5742. * @property dragging: Handler
  5743. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  5744. */
  5745. var MarkerDrag = Handler.extend({
  5746. initialize: function (marker) {
  5747. this._marker = marker;
  5748. },
  5749. addHooks: function () {
  5750. var icon = this._marker._icon;
  5751. if (!this._draggable) {
  5752. this._draggable = new Draggable(icon, icon, true);
  5753. }
  5754. this._draggable.on({
  5755. dragstart: this._onDragStart,
  5756. drag: this._onDrag,
  5757. dragend: this._onDragEnd
  5758. }, this).enable();
  5759. addClass(icon, 'leaflet-marker-draggable');
  5760. },
  5761. removeHooks: function () {
  5762. this._draggable.off({
  5763. dragstart: this._onDragStart,
  5764. drag: this._onDrag,
  5765. dragend: this._onDragEnd
  5766. }, this).disable();
  5767. if (this._marker._icon) {
  5768. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  5769. }
  5770. },
  5771. moved: function () {
  5772. return this._draggable && this._draggable._moved;
  5773. },
  5774. _onDragStart: function () {
  5775. // @section Dragging events
  5776. // @event dragstart: Event
  5777. // Fired when the user starts dragging the marker.
  5778. // @event movestart: Event
  5779. // Fired when the marker starts moving (because of dragging).
  5780. this._oldLatLng = this._marker.getLatLng();
  5781. this._marker
  5782. .closePopup()
  5783. .fire('movestart')
  5784. .fire('dragstart');
  5785. },
  5786. _onDrag: function (e) {
  5787. var marker = this._marker,
  5788. shadow = marker._shadow,
  5789. iconPos = getPosition(marker._icon),
  5790. latlng = marker._map.layerPointToLatLng(iconPos);
  5791. // update shadow position
  5792. if (shadow) {
  5793. setPosition(shadow, iconPos);
  5794. }
  5795. marker._latlng = latlng;
  5796. e.latlng = latlng;
  5797. e.oldLatLng = this._oldLatLng;
  5798. // @event drag: Event
  5799. // Fired repeatedly while the user drags the marker.
  5800. marker
  5801. .fire('move', e)
  5802. .fire('drag', e);
  5803. },
  5804. _onDragEnd: function (e) {
  5805. // @event dragend: DragEndEvent
  5806. // Fired when the user stops dragging the marker.
  5807. // @event moveend: Event
  5808. // Fired when the marker stops moving (because of dragging).
  5809. delete this._oldLatLng;
  5810. this._marker
  5811. .fire('moveend')
  5812. .fire('dragend', e);
  5813. }
  5814. });
  5815. /*
  5816. * @class Marker
  5817. * @inherits Interactive layer
  5818. * @aka L.Marker
  5819. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  5820. *
  5821. * @example
  5822. *
  5823. * ```js
  5824. * L.marker([50.5, 30.5]).addTo(map);
  5825. * ```
  5826. */
  5827. var Marker = Layer.extend({
  5828. // @section
  5829. // @aka Marker options
  5830. options: {
  5831. // @option icon: Icon = *
  5832. // Icon instance to use for rendering the marker.
  5833. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  5834. // If not specified, a common instance of `L.Icon.Default` is used.
  5835. icon: new IconDefault(),
  5836. // Option inherited from "Interactive layer" abstract class
  5837. interactive: true,
  5838. // @option draggable: Boolean = false
  5839. // Whether the marker is draggable with mouse/touch or not.
  5840. draggable: false,
  5841. // @option keyboard: Boolean = true
  5842. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  5843. keyboard: true,
  5844. // @option title: String = ''
  5845. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  5846. title: '',
  5847. // @option alt: String = ''
  5848. // Text for the `alt` attribute of the icon image (useful for accessibility).
  5849. alt: '',
  5850. // @option zIndexOffset: Number = 0
  5851. // By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively).
  5852. zIndexOffset: 0,
  5853. // @option opacity: Number = 1.0
  5854. // The opacity of the marker.
  5855. opacity: 1,
  5856. // @option riseOnHover: Boolean = false
  5857. // If `true`, the marker will get on top of others when you hover the mouse over it.
  5858. riseOnHover: false,
  5859. // @option riseOffset: Number = 250
  5860. // The z-index offset used for the `riseOnHover` feature.
  5861. riseOffset: 250,
  5862. // @option pane: String = 'markerPane'
  5863. // `Map pane` where the markers icon will be added.
  5864. pane: 'markerPane',
  5865. // @option bubblingMouseEvents: Boolean = false
  5866. // When `true`, a mouse event on this marker will trigger the same event on the map
  5867. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  5868. bubblingMouseEvents: false
  5869. },
  5870. /* @section
  5871. *
  5872. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  5873. */
  5874. initialize: function (latlng, options) {
  5875. setOptions(this, options);
  5876. this._latlng = toLatLng(latlng);
  5877. },
  5878. onAdd: function (map) {
  5879. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  5880. if (this._zoomAnimated) {
  5881. map.on('zoomanim', this._animateZoom, this);
  5882. }
  5883. this._initIcon();
  5884. this.update();
  5885. },
  5886. onRemove: function (map) {
  5887. if (this.dragging && this.dragging.enabled()) {
  5888. this.options.draggable = true;
  5889. this.dragging.removeHooks();
  5890. }
  5891. delete this.dragging;
  5892. if (this._zoomAnimated) {
  5893. map.off('zoomanim', this._animateZoom, this);
  5894. }
  5895. this._removeIcon();
  5896. this._removeShadow();
  5897. },
  5898. getEvents: function () {
  5899. return {
  5900. zoom: this.update,
  5901. viewreset: this.update
  5902. };
  5903. },
  5904. // @method getLatLng: LatLng
  5905. // Returns the current geographical position of the marker.
  5906. getLatLng: function () {
  5907. return this._latlng;
  5908. },
  5909. // @method setLatLng(latlng: LatLng): this
  5910. // Changes the marker position to the given point.
  5911. setLatLng: function (latlng) {
  5912. var oldLatLng = this._latlng;
  5913. this._latlng = toLatLng(latlng);
  5914. this.update();
  5915. // @event move: Event
  5916. // Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
  5917. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  5918. },
  5919. // @method setZIndexOffset(offset: Number): this
  5920. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  5921. setZIndexOffset: function (offset) {
  5922. this.options.zIndexOffset = offset;
  5923. return this.update();
  5924. },
  5925. // @method setIcon(icon: Icon): this
  5926. // Changes the marker icon.
  5927. setIcon: function (icon) {
  5928. this.options.icon = icon;
  5929. if (this._map) {
  5930. this._initIcon();
  5931. this.update();
  5932. }
  5933. if (this._popup) {
  5934. this.bindPopup(this._popup, this._popup.options);
  5935. }
  5936. return this;
  5937. },
  5938. getElement: function () {
  5939. return this._icon;
  5940. },
  5941. update: function () {
  5942. if (this._icon) {
  5943. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  5944. this._setPos(pos);
  5945. }
  5946. return this;
  5947. },
  5948. _initIcon: function () {
  5949. var options = this.options,
  5950. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  5951. var icon = options.icon.createIcon(this._icon),
  5952. addIcon = false;
  5953. // if we're not reusing the icon, remove the old one and init new one
  5954. if (icon !== this._icon) {
  5955. if (this._icon) {
  5956. this._removeIcon();
  5957. }
  5958. addIcon = true;
  5959. if (options.title) {
  5960. icon.title = options.title;
  5961. }
  5962. if (options.alt) {
  5963. icon.alt = options.alt;
  5964. }
  5965. }
  5966. addClass(icon, classToAdd);
  5967. if (options.keyboard) {
  5968. icon.tabIndex = '0';
  5969. }
  5970. this._icon = icon;
  5971. if (options.riseOnHover) {
  5972. this.on({
  5973. mouseover: this._bringToFront,
  5974. mouseout: this._resetZIndex
  5975. });
  5976. }
  5977. var newShadow = options.icon.createShadow(this._shadow),
  5978. addShadow = false;
  5979. if (newShadow !== this._shadow) {
  5980. this._removeShadow();
  5981. addShadow = true;
  5982. }
  5983. if (newShadow) {
  5984. addClass(newShadow, classToAdd);
  5985. newShadow.alt = '';
  5986. }
  5987. this._shadow = newShadow;
  5988. if (options.opacity < 1) {
  5989. this._updateOpacity();
  5990. }
  5991. if (addIcon) {
  5992. this.getPane().appendChild(this._icon);
  5993. }
  5994. this._initInteraction();
  5995. if (newShadow && addShadow) {
  5996. this.getPane('shadowPane').appendChild(this._shadow);
  5997. }
  5998. },
  5999. _removeIcon: function () {
  6000. if (this.options.riseOnHover) {
  6001. this.off({
  6002. mouseover: this._bringToFront,
  6003. mouseout: this._resetZIndex
  6004. });
  6005. }
  6006. remove(this._icon);
  6007. this.removeInteractiveTarget(this._icon);
  6008. this._icon = null;
  6009. },
  6010. _removeShadow: function () {
  6011. if (this._shadow) {
  6012. remove(this._shadow);
  6013. }
  6014. this._shadow = null;
  6015. },
  6016. _setPos: function (pos) {
  6017. setPosition(this._icon, pos);
  6018. if (this._shadow) {
  6019. setPosition(this._shadow, pos);
  6020. }
  6021. this._zIndex = pos.y + this.options.zIndexOffset;
  6022. this._resetZIndex();
  6023. },
  6024. _updateZIndex: function (offset) {
  6025. this._icon.style.zIndex = this._zIndex + offset;
  6026. },
  6027. _animateZoom: function (opt) {
  6028. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6029. this._setPos(pos);
  6030. },
  6031. _initInteraction: function () {
  6032. if (!this.options.interactive) { return; }
  6033. addClass(this._icon, 'leaflet-interactive');
  6034. this.addInteractiveTarget(this._icon);
  6035. if (MarkerDrag) {
  6036. var draggable = this.options.draggable;
  6037. if (this.dragging) {
  6038. draggable = this.dragging.enabled();
  6039. this.dragging.disable();
  6040. }
  6041. this.dragging = new MarkerDrag(this);
  6042. if (draggable) {
  6043. this.dragging.enable();
  6044. }
  6045. }
  6046. },
  6047. // @method setOpacity(opacity: Number): this
  6048. // Changes the opacity of the marker.
  6049. setOpacity: function (opacity) {
  6050. this.options.opacity = opacity;
  6051. if (this._map) {
  6052. this._updateOpacity();
  6053. }
  6054. return this;
  6055. },
  6056. _updateOpacity: function () {
  6057. var opacity = this.options.opacity;
  6058. setOpacity(this._icon, opacity);
  6059. if (this._shadow) {
  6060. setOpacity(this._shadow, opacity);
  6061. }
  6062. },
  6063. _bringToFront: function () {
  6064. this._updateZIndex(this.options.riseOffset);
  6065. },
  6066. _resetZIndex: function () {
  6067. this._updateZIndex(0);
  6068. },
  6069. _getPopupAnchor: function () {
  6070. return this.options.icon.options.popupAnchor || [0, 0];
  6071. },
  6072. _getTooltipAnchor: function () {
  6073. return this.options.icon.options.tooltipAnchor || [0, 0];
  6074. }
  6075. });
  6076. // factory L.marker(latlng: LatLng, options? : Marker options)
  6077. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6078. // Instantiates a Marker object given a geographical point and optionally an options object.
  6079. function marker(latlng, options) {
  6080. return new Marker(latlng, options);
  6081. }
  6082. /*
  6083. * @class Path
  6084. * @aka L.Path
  6085. * @inherits Interactive layer
  6086. *
  6087. * An abstract class that contains options and constants shared between vector
  6088. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6089. */
  6090. var Path = Layer.extend({
  6091. // @section
  6092. // @aka Path options
  6093. options: {
  6094. // @option stroke: Boolean = true
  6095. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6096. stroke: true,
  6097. // @option color: String = '#3388ff'
  6098. // Stroke color
  6099. color: '#3388ff',
  6100. // @option weight: Number = 3
  6101. // Stroke width in pixels
  6102. weight: 3,
  6103. // @option opacity: Number = 1.0
  6104. // Stroke opacity
  6105. opacity: 1,
  6106. // @option lineCap: String= 'round'
  6107. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6108. lineCap: 'round',
  6109. // @option lineJoin: String = 'round'
  6110. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6111. lineJoin: 'round',
  6112. // @option dashArray: String = null
  6113. // A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
  6114. dashArray: null,
  6115. // @option dashOffset: String = null
  6116. // A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
  6117. dashOffset: null,
  6118. // @option fill: Boolean = depends
  6119. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6120. fill: false,
  6121. // @option fillColor: String = *
  6122. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6123. fillColor: null,
  6124. // @option fillOpacity: Number = 0.2
  6125. // Fill opacity.
  6126. fillOpacity: 0.2,
  6127. // @option fillRule: String = 'evenodd'
  6128. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6129. fillRule: 'evenodd',
  6130. // className: '',
  6131. // Option inherited from "Interactive layer" abstract class
  6132. interactive: true,
  6133. // @option bubblingMouseEvents: Boolean = true
  6134. // When `true`, a mouse event on this path will trigger the same event on the map
  6135. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6136. bubblingMouseEvents: true
  6137. },
  6138. beforeAdd: function (map) {
  6139. // Renderer is set here because we need to call renderer.getEvents
  6140. // before this.getEvents.
  6141. this._renderer = map.getRenderer(this);
  6142. },
  6143. onAdd: function () {
  6144. this._renderer._initPath(this);
  6145. this._reset();
  6146. this._renderer._addPath(this);
  6147. },
  6148. onRemove: function () {
  6149. this._renderer._removePath(this);
  6150. },
  6151. // @method redraw(): this
  6152. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6153. redraw: function () {
  6154. if (this._map) {
  6155. this._renderer._updatePath(this);
  6156. }
  6157. return this;
  6158. },
  6159. // @method setStyle(style: Path options): this
  6160. // Changes the appearance of a Path based on the options in the `Path options` object.
  6161. setStyle: function (style) {
  6162. setOptions(this, style);
  6163. if (this._renderer) {
  6164. this._renderer._updateStyle(this);
  6165. }
  6166. return this;
  6167. },
  6168. // @method bringToFront(): this
  6169. // Brings the layer to the top of all path layers.
  6170. bringToFront: function () {
  6171. if (this._renderer) {
  6172. this._renderer._bringToFront(this);
  6173. }
  6174. return this;
  6175. },
  6176. // @method bringToBack(): this
  6177. // Brings the layer to the bottom of all path layers.
  6178. bringToBack: function () {
  6179. if (this._renderer) {
  6180. this._renderer._bringToBack(this);
  6181. }
  6182. return this;
  6183. },
  6184. getElement: function () {
  6185. return this._path;
  6186. },
  6187. _reset: function () {
  6188. // defined in child classes
  6189. this._project();
  6190. this._update();
  6191. },
  6192. _clickTolerance: function () {
  6193. // used when doing hit detection for Canvas layers
  6194. return (this.options.stroke ? this.options.weight / 2 : 0) + (touch ? 10 : 0);
  6195. }
  6196. });
  6197. /*
  6198. * @class CircleMarker
  6199. * @aka L.CircleMarker
  6200. * @inherits Path
  6201. *
  6202. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6203. */
  6204. var CircleMarker = Path.extend({
  6205. // @section
  6206. // @aka CircleMarker options
  6207. options: {
  6208. fill: true,
  6209. // @option radius: Number = 10
  6210. // Radius of the circle marker, in pixels
  6211. radius: 10
  6212. },
  6213. initialize: function (latlng, options) {
  6214. setOptions(this, options);
  6215. this._latlng = toLatLng(latlng);
  6216. this._radius = this.options.radius;
  6217. },
  6218. // @method setLatLng(latLng: LatLng): this
  6219. // Sets the position of a circle marker to a new location.
  6220. setLatLng: function (latlng) {
  6221. this._latlng = toLatLng(latlng);
  6222. this.redraw();
  6223. return this.fire('move', {latlng: this._latlng});
  6224. },
  6225. // @method getLatLng(): LatLng
  6226. // Returns the current geographical position of the circle marker
  6227. getLatLng: function () {
  6228. return this._latlng;
  6229. },
  6230. // @method setRadius(radius: Number): this
  6231. // Sets the radius of a circle marker. Units are in pixels.
  6232. setRadius: function (radius) {
  6233. this.options.radius = this._radius = radius;
  6234. return this.redraw();
  6235. },
  6236. // @method getRadius(): Number
  6237. // Returns the current radius of the circle
  6238. getRadius: function () {
  6239. return this._radius;
  6240. },
  6241. setStyle : function (options) {
  6242. var radius = options && options.radius || this._radius;
  6243. Path.prototype.setStyle.call(this, options);
  6244. this.setRadius(radius);
  6245. return this;
  6246. },
  6247. _project: function () {
  6248. this._point = this._map.latLngToLayerPoint(this._latlng);
  6249. this._updateBounds();
  6250. },
  6251. _updateBounds: function () {
  6252. var r = this._radius,
  6253. r2 = this._radiusY || r,
  6254. w = this._clickTolerance(),
  6255. p = [r + w, r2 + w];
  6256. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6257. },
  6258. _update: function () {
  6259. if (this._map) {
  6260. this._updatePath();
  6261. }
  6262. },
  6263. _updatePath: function () {
  6264. this._renderer._updateCircle(this);
  6265. },
  6266. _empty: function () {
  6267. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6268. },
  6269. // Needed by the `Canvas` renderer for interactivity
  6270. _containsPoint: function (p) {
  6271. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6272. }
  6273. });
  6274. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6275. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6276. function circleMarker(latlng, options) {
  6277. return new CircleMarker(latlng, options);
  6278. }
  6279. /*
  6280. * @class Circle
  6281. * @aka L.Circle
  6282. * @inherits CircleMarker
  6283. *
  6284. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6285. *
  6286. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6287. *
  6288. * @example
  6289. *
  6290. * ```js
  6291. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6292. * ```
  6293. */
  6294. var Circle = CircleMarker.extend({
  6295. initialize: function (latlng, options, legacyOptions) {
  6296. if (typeof options === 'number') {
  6297. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6298. options = extend({}, legacyOptions, {radius: options});
  6299. }
  6300. setOptions(this, options);
  6301. this._latlng = toLatLng(latlng);
  6302. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6303. // @section
  6304. // @aka Circle options
  6305. // @option radius: Number; Radius of the circle, in meters.
  6306. this._mRadius = this.options.radius;
  6307. },
  6308. // @method setRadius(radius: Number): this
  6309. // Sets the radius of a circle. Units are in meters.
  6310. setRadius: function (radius) {
  6311. this._mRadius = radius;
  6312. return this.redraw();
  6313. },
  6314. // @method getRadius(): Number
  6315. // Returns the current radius of a circle. Units are in meters.
  6316. getRadius: function () {
  6317. return this._mRadius;
  6318. },
  6319. // @method getBounds(): LatLngBounds
  6320. // Returns the `LatLngBounds` of the path.
  6321. getBounds: function () {
  6322. var half = [this._radius, this._radiusY || this._radius];
  6323. return new LatLngBounds(
  6324. this._map.layerPointToLatLng(this._point.subtract(half)),
  6325. this._map.layerPointToLatLng(this._point.add(half)));
  6326. },
  6327. setStyle: Path.prototype.setStyle,
  6328. _project: function () {
  6329. var lng = this._latlng.lng,
  6330. lat = this._latlng.lat,
  6331. map = this._map,
  6332. crs = map.options.crs;
  6333. if (crs.distance === Earth.distance) {
  6334. var d = Math.PI / 180,
  6335. latR = (this._mRadius / Earth.R) / d,
  6336. top = map.project([lat + latR, lng]),
  6337. bottom = map.project([lat - latR, lng]),
  6338. p = top.add(bottom).divideBy(2),
  6339. lat2 = map.unproject(p).lat,
  6340. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6341. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6342. if (isNaN(lngR) || lngR === 0) {
  6343. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6344. }
  6345. this._point = p.subtract(map.getPixelOrigin());
  6346. this._radius = isNaN(lngR) ? 0 : Math.max(Math.round(p.x - map.project([lat2, lng - lngR]).x), 1);
  6347. this._radiusY = Math.max(Math.round(p.y - top.y), 1);
  6348. } else {
  6349. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6350. this._point = map.latLngToLayerPoint(this._latlng);
  6351. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6352. }
  6353. this._updateBounds();
  6354. }
  6355. });
  6356. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6357. // Instantiates a circle object given a geographical point, and an options object
  6358. // which contains the circle radius.
  6359. // @alternative
  6360. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6361. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6362. // Do not use in new applications or plugins.
  6363. function circle(latlng, options, legacyOptions) {
  6364. return new Circle(latlng, options, legacyOptions);
  6365. }
  6366. /*
  6367. * @class Polyline
  6368. * @aka L.Polyline
  6369. * @inherits Path
  6370. *
  6371. * A class for drawing polyline overlays on a map. Extends `Path`.
  6372. *
  6373. * @example
  6374. *
  6375. * ```js
  6376. * // create a red polyline from an array of LatLng points
  6377. * var latlngs = [
  6378. * [45.51, -122.68],
  6379. * [37.77, -122.43],
  6380. * [34.04, -118.2]
  6381. * ];
  6382. *
  6383. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6384. *
  6385. * // zoom the map to the polyline
  6386. * map.fitBounds(polyline.getBounds());
  6387. * ```
  6388. *
  6389. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6390. *
  6391. * ```js
  6392. * // create a red polyline from an array of arrays of LatLng points
  6393. * var latlngs = [
  6394. * [[45.51, -122.68],
  6395. * [37.77, -122.43],
  6396. * [34.04, -118.2]],
  6397. * [[40.78, -73.91],
  6398. * [41.83, -87.62],
  6399. * [32.76, -96.72]]
  6400. * ];
  6401. * ```
  6402. */
  6403. var Polyline = Path.extend({
  6404. // @section
  6405. // @aka Polyline options
  6406. options: {
  6407. // @option smoothFactor: Number = 1.0
  6408. // How much to simplify the polyline on each zoom level. More means
  6409. // better performance and smoother look, and less means more accurate representation.
  6410. smoothFactor: 1.0,
  6411. // @option noClip: Boolean = false
  6412. // Disable polyline clipping.
  6413. noClip: false
  6414. },
  6415. initialize: function (latlngs, options) {
  6416. setOptions(this, options);
  6417. this._setLatLngs(latlngs);
  6418. },
  6419. // @method getLatLngs(): LatLng[]
  6420. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6421. getLatLngs: function () {
  6422. return this._latlngs;
  6423. },
  6424. // @method setLatLngs(latlngs: LatLng[]): this
  6425. // Replaces all the points in the polyline with the given array of geographical points.
  6426. setLatLngs: function (latlngs) {
  6427. this._setLatLngs(latlngs);
  6428. return this.redraw();
  6429. },
  6430. // @method isEmpty(): Boolean
  6431. // Returns `true` if the Polyline has no LatLngs.
  6432. isEmpty: function () {
  6433. return !this._latlngs.length;
  6434. },
  6435. closestLayerPoint: function (p) {
  6436. var minDistance = Infinity,
  6437. minPoint = null,
  6438. closest = _sqClosestPointOnSegment,
  6439. p1, p2;
  6440. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6441. var points = this._parts[j];
  6442. for (var i = 1, len = points.length; i < len; i++) {
  6443. p1 = points[i - 1];
  6444. p2 = points[i];
  6445. var sqDist = closest(p, p1, p2, true);
  6446. if (sqDist < minDistance) {
  6447. minDistance = sqDist;
  6448. minPoint = closest(p, p1, p2);
  6449. }
  6450. }
  6451. }
  6452. if (minPoint) {
  6453. minPoint.distance = Math.sqrt(minDistance);
  6454. }
  6455. return minPoint;
  6456. },
  6457. // @method getCenter(): LatLng
  6458. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6459. getCenter: function () {
  6460. // throws error when not yet added to map as this center calculation requires projected coordinates
  6461. if (!this._map) {
  6462. throw new Error('Must add layer to map before using getCenter()');
  6463. }
  6464. var i, halfDist, segDist, dist, p1, p2, ratio,
  6465. points = this._rings[0],
  6466. len = points.length;
  6467. if (!len) { return null; }
  6468. // polyline centroid algorithm; only uses the first ring if there are multiple
  6469. for (i = 0, halfDist = 0; i < len - 1; i++) {
  6470. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  6471. }
  6472. // The line is so small in the current view that all points are on the same pixel.
  6473. if (halfDist === 0) {
  6474. return this._map.layerPointToLatLng(points[0]);
  6475. }
  6476. for (i = 0, dist = 0; i < len - 1; i++) {
  6477. p1 = points[i];
  6478. p2 = points[i + 1];
  6479. segDist = p1.distanceTo(p2);
  6480. dist += segDist;
  6481. if (dist > halfDist) {
  6482. ratio = (dist - halfDist) / segDist;
  6483. return this._map.layerPointToLatLng([
  6484. p2.x - ratio * (p2.x - p1.x),
  6485. p2.y - ratio * (p2.y - p1.y)
  6486. ]);
  6487. }
  6488. }
  6489. },
  6490. // @method getBounds(): LatLngBounds
  6491. // Returns the `LatLngBounds` of the path.
  6492. getBounds: function () {
  6493. return this._bounds;
  6494. },
  6495. // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
  6496. // Adds a given point to the polyline. By default, adds to the first ring of
  6497. // the polyline in case of a multi-polyline, but can be overridden by passing
  6498. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6499. addLatLng: function (latlng, latlngs) {
  6500. latlngs = latlngs || this._defaultShape();
  6501. latlng = toLatLng(latlng);
  6502. latlngs.push(latlng);
  6503. this._bounds.extend(latlng);
  6504. return this.redraw();
  6505. },
  6506. _setLatLngs: function (latlngs) {
  6507. this._bounds = new LatLngBounds();
  6508. this._latlngs = this._convertLatLngs(latlngs);
  6509. },
  6510. _defaultShape: function () {
  6511. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6512. },
  6513. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6514. _convertLatLngs: function (latlngs) {
  6515. var result = [],
  6516. flat = isFlat(latlngs);
  6517. for (var i = 0, len = latlngs.length; i < len; i++) {
  6518. if (flat) {
  6519. result[i] = toLatLng(latlngs[i]);
  6520. this._bounds.extend(result[i]);
  6521. } else {
  6522. result[i] = this._convertLatLngs(latlngs[i]);
  6523. }
  6524. }
  6525. return result;
  6526. },
  6527. _project: function () {
  6528. var pxBounds = new Bounds();
  6529. this._rings = [];
  6530. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  6531. var w = this._clickTolerance(),
  6532. p = new Point(w, w);
  6533. if (this._bounds.isValid() && pxBounds.isValid()) {
  6534. pxBounds.min._subtract(p);
  6535. pxBounds.max._add(p);
  6536. this._pxBounds = pxBounds;
  6537. }
  6538. },
  6539. // recursively turns latlngs into a set of rings with projected coordinates
  6540. _projectLatlngs: function (latlngs, result, projectedBounds) {
  6541. var flat = latlngs[0] instanceof LatLng,
  6542. len = latlngs.length,
  6543. i, ring;
  6544. if (flat) {
  6545. ring = [];
  6546. for (i = 0; i < len; i++) {
  6547. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  6548. projectedBounds.extend(ring[i]);
  6549. }
  6550. result.push(ring);
  6551. } else {
  6552. for (i = 0; i < len; i++) {
  6553. this._projectLatlngs(latlngs[i], result, projectedBounds);
  6554. }
  6555. }
  6556. },
  6557. // clip polyline by renderer bounds so that we have less to render for performance
  6558. _clipPoints: function () {
  6559. var bounds = this._renderer._bounds;
  6560. this._parts = [];
  6561. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6562. return;
  6563. }
  6564. if (this.options.noClip) {
  6565. this._parts = this._rings;
  6566. return;
  6567. }
  6568. var parts = this._parts,
  6569. i, j, k, len, len2, segment, points;
  6570. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  6571. points = this._rings[i];
  6572. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  6573. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  6574. if (!segment) { continue; }
  6575. parts[k] = parts[k] || [];
  6576. parts[k].push(segment[0]);
  6577. // if segment goes out of screen, or it's the last one, it's the end of the line part
  6578. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  6579. parts[k].push(segment[1]);
  6580. k++;
  6581. }
  6582. }
  6583. }
  6584. },
  6585. // simplify each clipped part of the polyline for performance
  6586. _simplifyPoints: function () {
  6587. var parts = this._parts,
  6588. tolerance = this.options.smoothFactor;
  6589. for (var i = 0, len = parts.length; i < len; i++) {
  6590. parts[i] = simplify(parts[i], tolerance);
  6591. }
  6592. },
  6593. _update: function () {
  6594. if (!this._map) { return; }
  6595. this._clipPoints();
  6596. this._simplifyPoints();
  6597. this._updatePath();
  6598. },
  6599. _updatePath: function () {
  6600. this._renderer._updatePoly(this);
  6601. },
  6602. // Needed by the `Canvas` renderer for interactivity
  6603. _containsPoint: function (p, closed) {
  6604. var i, j, k, len, len2, part,
  6605. w = this._clickTolerance();
  6606. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  6607. // hit detection for polylines
  6608. for (i = 0, len = this._parts.length; i < len; i++) {
  6609. part = this._parts[i];
  6610. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6611. if (!closed && (j === 0)) { continue; }
  6612. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  6613. return true;
  6614. }
  6615. }
  6616. }
  6617. return false;
  6618. }
  6619. });
  6620. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  6621. // Instantiates a polyline object given an array of geographical points and
  6622. // optionally an options object. You can create a `Polyline` object with
  6623. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  6624. // of geographic points.
  6625. function polyline(latlngs, options) {
  6626. return new Polyline(latlngs, options);
  6627. }
  6628. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  6629. Polyline._flat = _flat;
  6630. /*
  6631. * @class Polygon
  6632. * @aka L.Polygon
  6633. * @inherits Polyline
  6634. *
  6635. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  6636. *
  6637. * Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points.
  6638. *
  6639. *
  6640. * @example
  6641. *
  6642. * ```js
  6643. * // create a red polygon from an array of LatLng points
  6644. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  6645. *
  6646. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  6647. *
  6648. * // zoom the map to the polygon
  6649. * map.fitBounds(polygon.getBounds());
  6650. * ```
  6651. *
  6652. * You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape:
  6653. *
  6654. * ```js
  6655. * var latlngs = [
  6656. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6657. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6658. * ];
  6659. * ```
  6660. *
  6661. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  6662. *
  6663. * ```js
  6664. * var latlngs = [
  6665. * [ // first polygon
  6666. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6667. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6668. * ],
  6669. * [ // second polygon
  6670. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  6671. * ]
  6672. * ];
  6673. * ```
  6674. */
  6675. var Polygon = Polyline.extend({
  6676. options: {
  6677. fill: true
  6678. },
  6679. isEmpty: function () {
  6680. return !this._latlngs.length || !this._latlngs[0].length;
  6681. },
  6682. getCenter: function () {
  6683. // throws error when not yet added to map as this center calculation requires projected coordinates
  6684. if (!this._map) {
  6685. throw new Error('Must add layer to map before using getCenter()');
  6686. }
  6687. var i, j, p1, p2, f, area, x, y, center,
  6688. points = this._rings[0],
  6689. len = points.length;
  6690. if (!len) { return null; }
  6691. // polygon centroid algorithm; only uses the first ring if there are multiple
  6692. area = x = y = 0;
  6693. for (i = 0, j = len - 1; i < len; j = i++) {
  6694. p1 = points[i];
  6695. p2 = points[j];
  6696. f = p1.y * p2.x - p2.y * p1.x;
  6697. x += (p1.x + p2.x) * f;
  6698. y += (p1.y + p2.y) * f;
  6699. area += f * 3;
  6700. }
  6701. if (area === 0) {
  6702. // Polygon is so small that all points are on same pixel.
  6703. center = points[0];
  6704. } else {
  6705. center = [x / area, y / area];
  6706. }
  6707. return this._map.layerPointToLatLng(center);
  6708. },
  6709. _convertLatLngs: function (latlngs) {
  6710. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  6711. len = result.length;
  6712. // remove last point if it equals first one
  6713. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  6714. result.pop();
  6715. }
  6716. return result;
  6717. },
  6718. _setLatLngs: function (latlngs) {
  6719. Polyline.prototype._setLatLngs.call(this, latlngs);
  6720. if (isFlat(this._latlngs)) {
  6721. this._latlngs = [this._latlngs];
  6722. }
  6723. },
  6724. _defaultShape: function () {
  6725. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  6726. },
  6727. _clipPoints: function () {
  6728. // polygons need a different clipping algorithm so we redefine that
  6729. var bounds = this._renderer._bounds,
  6730. w = this.options.weight,
  6731. p = new Point(w, w);
  6732. // increase clip padding by stroke width to avoid stroke on clip edges
  6733. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  6734. this._parts = [];
  6735. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6736. return;
  6737. }
  6738. if (this.options.noClip) {
  6739. this._parts = this._rings;
  6740. return;
  6741. }
  6742. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  6743. clipped = clipPolygon(this._rings[i], bounds, true);
  6744. if (clipped.length) {
  6745. this._parts.push(clipped);
  6746. }
  6747. }
  6748. },
  6749. _updatePath: function () {
  6750. this._renderer._updatePoly(this, true);
  6751. },
  6752. // Needed by the `Canvas` renderer for interactivity
  6753. _containsPoint: function (p) {
  6754. var inside = false,
  6755. part, p1, p2, i, j, k, len, len2;
  6756. if (!this._pxBounds.contains(p)) { return false; }
  6757. // ray casting algorithm for detecting if point is in polygon
  6758. for (i = 0, len = this._parts.length; i < len; i++) {
  6759. part = this._parts[i];
  6760. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6761. p1 = part[j];
  6762. p2 = part[k];
  6763. if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
  6764. inside = !inside;
  6765. }
  6766. }
  6767. }
  6768. // also check if it's on polygon stroke
  6769. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  6770. }
  6771. });
  6772. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  6773. function polygon(latlngs, options) {
  6774. return new Polygon(latlngs, options);
  6775. }
  6776. /*
  6777. * @class GeoJSON
  6778. * @aka L.GeoJSON
  6779. * @inherits FeatureGroup
  6780. *
  6781. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  6782. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  6783. *
  6784. * @example
  6785. *
  6786. * ```js
  6787. * L.geoJSON(data, {
  6788. * style: function (feature) {
  6789. * return {color: feature.properties.color};
  6790. * }
  6791. * }).bindPopup(function (layer) {
  6792. * return layer.feature.properties.description;
  6793. * }).addTo(map);
  6794. * ```
  6795. */
  6796. var GeoJSON = FeatureGroup.extend({
  6797. /* @section
  6798. * @aka GeoJSON options
  6799. *
  6800. * @option pointToLayer: Function = *
  6801. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  6802. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  6803. * The default is to spawn a default `Marker`:
  6804. * ```js
  6805. * function(geoJsonPoint, latlng) {
  6806. * return L.marker(latlng);
  6807. * }
  6808. * ```
  6809. *
  6810. * @option style: Function = *
  6811. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  6812. * called internally when data is added.
  6813. * The default value is to not override any defaults:
  6814. * ```js
  6815. * function (geoJsonFeature) {
  6816. * return {}
  6817. * }
  6818. * ```
  6819. *
  6820. * @option onEachFeature: Function = *
  6821. * A `Function` that will be called once for each created `Feature`, after it has
  6822. * been created and styled. Useful for attaching events and popups to features.
  6823. * The default is to do nothing with the newly created layers:
  6824. * ```js
  6825. * function (feature, layer) {}
  6826. * ```
  6827. *
  6828. * @option filter: Function = *
  6829. * A `Function` that will be used to decide whether to include a feature or not.
  6830. * The default is to include all features:
  6831. * ```js
  6832. * function (geoJsonFeature) {
  6833. * return true;
  6834. * }
  6835. * ```
  6836. * Note: dynamically changing the `filter` option will have effect only on newly
  6837. * added data. It will _not_ re-evaluate already included features.
  6838. *
  6839. * @option coordsToLatLng: Function = *
  6840. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  6841. * The default is the `coordsToLatLng` static method.
  6842. */
  6843. initialize: function (geojson, options) {
  6844. setOptions(this, options);
  6845. this._layers = {};
  6846. if (geojson) {
  6847. this.addData(geojson);
  6848. }
  6849. },
  6850. // @method addData( <GeoJSON> data ): this
  6851. // Adds a GeoJSON object to the layer.
  6852. addData: function (geojson) {
  6853. var features = isArray(geojson) ? geojson : geojson.features,
  6854. i, len, feature;
  6855. if (features) {
  6856. for (i = 0, len = features.length; i < len; i++) {
  6857. // only add this if geometry or geometries are set and not null
  6858. feature = features[i];
  6859. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  6860. this.addData(feature);
  6861. }
  6862. }
  6863. return this;
  6864. }
  6865. var options = this.options;
  6866. if (options.filter && !options.filter(geojson)) { return this; }
  6867. var layer = geometryToLayer(geojson, options);
  6868. if (!layer) {
  6869. return this;
  6870. }
  6871. layer.feature = asFeature(geojson);
  6872. layer.defaultOptions = layer.options;
  6873. this.resetStyle(layer);
  6874. if (options.onEachFeature) {
  6875. options.onEachFeature(geojson, layer);
  6876. }
  6877. return this.addLayer(layer);
  6878. },
  6879. // @method resetStyle( <Path> layer ): this
  6880. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  6881. resetStyle: function (layer) {
  6882. // reset any custom styles
  6883. layer.options = extend({}, layer.defaultOptions);
  6884. this._setLayerStyle(layer, this.options.style);
  6885. return this;
  6886. },
  6887. // @method setStyle( <Function> style ): this
  6888. // Changes styles of GeoJSON vector layers with the given style function.
  6889. setStyle: function (style) {
  6890. return this.eachLayer(function (layer) {
  6891. this._setLayerStyle(layer, style);
  6892. }, this);
  6893. },
  6894. _setLayerStyle: function (layer, style) {
  6895. if (typeof style === 'function') {
  6896. style = style(layer.feature);
  6897. }
  6898. if (layer.setStyle) {
  6899. layer.setStyle(style);
  6900. }
  6901. }
  6902. });
  6903. // @section
  6904. // There are several static functions which can be called without instantiating L.GeoJSON:
  6905. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  6906. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  6907. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  6908. // functions if provided as options.
  6909. function geometryToLayer(geojson, options) {
  6910. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  6911. coords = geometry ? geometry.coordinates : null,
  6912. layers = [],
  6913. pointToLayer = options && options.pointToLayer,
  6914. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  6915. latlng, latlngs, i, len;
  6916. if (!coords && !geometry) {
  6917. return null;
  6918. }
  6919. switch (geometry.type) {
  6920. case 'Point':
  6921. latlng = _coordsToLatLng(coords);
  6922. return pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng);
  6923. case 'MultiPoint':
  6924. for (i = 0, len = coords.length; i < len; i++) {
  6925. latlng = _coordsToLatLng(coords[i]);
  6926. layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng));
  6927. }
  6928. return new FeatureGroup(layers);
  6929. case 'LineString':
  6930. case 'MultiLineString':
  6931. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  6932. return new Polyline(latlngs, options);
  6933. case 'Polygon':
  6934. case 'MultiPolygon':
  6935. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  6936. return new Polygon(latlngs, options);
  6937. case 'GeometryCollection':
  6938. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  6939. var layer = geometryToLayer({
  6940. geometry: geometry.geometries[i],
  6941. type: 'Feature',
  6942. properties: geojson.properties
  6943. }, options);
  6944. if (layer) {
  6945. layers.push(layer);
  6946. }
  6947. }
  6948. return new FeatureGroup(layers);
  6949. default:
  6950. throw new Error('Invalid GeoJSON object.');
  6951. }
  6952. }
  6953. // @function coordsToLatLng(coords: Array): LatLng
  6954. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  6955. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  6956. function coordsToLatLng(coords) {
  6957. return new LatLng(coords[1], coords[0], coords[2]);
  6958. }
  6959. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  6960. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  6961. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  6962. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  6963. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  6964. var latlngs = [];
  6965. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  6966. latlng = levelsDeep ?
  6967. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  6968. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  6969. latlngs.push(latlng);
  6970. }
  6971. return latlngs;
  6972. }
  6973. // @function latLngToCoords(latlng: LatLng, precision?: Number): Array
  6974. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  6975. function latLngToCoords(latlng, precision) {
  6976. precision = typeof precision === 'number' ? precision : 6;
  6977. return latlng.alt !== undefined ?
  6978. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  6979. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  6980. }
  6981. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  6982. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  6983. // `closed` determines whether the first point should be appended to the end of the array to close the feature, only used when `levelsDeep` is 0. False by default.
  6984. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  6985. var coords = [];
  6986. for (var i = 0, len = latlngs.length; i < len; i++) {
  6987. coords.push(levelsDeep ?
  6988. latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :
  6989. latLngToCoords(latlngs[i], precision));
  6990. }
  6991. if (!levelsDeep && closed) {
  6992. coords.push(coords[0]);
  6993. }
  6994. return coords;
  6995. }
  6996. function getFeature(layer, newGeometry) {
  6997. return layer.feature ?
  6998. extend({}, layer.feature, {geometry: newGeometry}) :
  6999. asFeature(newGeometry);
  7000. }
  7001. // @function asFeature(geojson: Object): Object
  7002. // Normalize GeoJSON geometries/features into GeoJSON features.
  7003. function asFeature(geojson) {
  7004. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7005. return geojson;
  7006. }
  7007. return {
  7008. type: 'Feature',
  7009. properties: {},
  7010. geometry: geojson
  7011. };
  7012. }
  7013. var PointToGeoJSON = {
  7014. toGeoJSON: function (precision) {
  7015. return getFeature(this, {
  7016. type: 'Point',
  7017. coordinates: latLngToCoords(this.getLatLng(), precision)
  7018. });
  7019. }
  7020. };
  7021. // @namespace Marker
  7022. // @method toGeoJSON(): Object
  7023. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7024. Marker.include(PointToGeoJSON);
  7025. // @namespace CircleMarker
  7026. // @method toGeoJSON(): Object
  7027. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7028. Circle.include(PointToGeoJSON);
  7029. CircleMarker.include(PointToGeoJSON);
  7030. // @namespace Polyline
  7031. // @method toGeoJSON(): Object
  7032. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7033. Polyline.include({
  7034. toGeoJSON: function (precision) {
  7035. var multi = !isFlat(this._latlngs);
  7036. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7037. return getFeature(this, {
  7038. type: (multi ? 'Multi' : '') + 'LineString',
  7039. coordinates: coords
  7040. });
  7041. }
  7042. });
  7043. // @namespace Polygon
  7044. // @method toGeoJSON(): Object
  7045. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7046. Polygon.include({
  7047. toGeoJSON: function (precision) {
  7048. var holes = !isFlat(this._latlngs),
  7049. multi = holes && !isFlat(this._latlngs[0]);
  7050. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7051. if (!holes) {
  7052. coords = [coords];
  7053. }
  7054. return getFeature(this, {
  7055. type: (multi ? 'Multi' : '') + 'Polygon',
  7056. coordinates: coords
  7057. });
  7058. }
  7059. });
  7060. // @namespace LayerGroup
  7061. LayerGroup.include({
  7062. toMultiPoint: function (precision) {
  7063. var coords = [];
  7064. this.eachLayer(function (layer) {
  7065. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7066. });
  7067. return getFeature(this, {
  7068. type: 'MultiPoint',
  7069. coordinates: coords
  7070. });
  7071. },
  7072. // @method toGeoJSON(): Object
  7073. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7074. toGeoJSON: function (precision) {
  7075. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7076. if (type === 'MultiPoint') {
  7077. return this.toMultiPoint(precision);
  7078. }
  7079. var isGeometryCollection = type === 'GeometryCollection',
  7080. jsons = [];
  7081. this.eachLayer(function (layer) {
  7082. if (layer.toGeoJSON) {
  7083. var json = layer.toGeoJSON(precision);
  7084. if (isGeometryCollection) {
  7085. jsons.push(json.geometry);
  7086. } else {
  7087. var feature = asFeature(json);
  7088. // Squash nested feature collections
  7089. if (feature.type === 'FeatureCollection') {
  7090. jsons.push.apply(jsons, feature.features);
  7091. } else {
  7092. jsons.push(feature);
  7093. }
  7094. }
  7095. }
  7096. });
  7097. if (isGeometryCollection) {
  7098. return getFeature(this, {
  7099. geometries: jsons,
  7100. type: 'GeometryCollection'
  7101. });
  7102. }
  7103. return {
  7104. type: 'FeatureCollection',
  7105. features: jsons
  7106. };
  7107. }
  7108. });
  7109. // @namespace GeoJSON
  7110. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7111. // Creates a GeoJSON layer. Optionally accepts an object in
  7112. // [GeoJSON format](http://geojson.org/geojson-spec.html) to display on the map
  7113. // (you can alternatively add it later with `addData` method) and an `options` object.
  7114. function geoJSON(geojson, options) {
  7115. return new GeoJSON(geojson, options);
  7116. }
  7117. // Backward compatibility.
  7118. var geoJson = geoJSON;
  7119. /*
  7120. * @class ImageOverlay
  7121. * @aka L.ImageOverlay
  7122. * @inherits Interactive layer
  7123. *
  7124. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7125. *
  7126. * @example
  7127. *
  7128. * ```js
  7129. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7130. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7131. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7132. * ```
  7133. */
  7134. var ImageOverlay = Layer.extend({
  7135. // @section
  7136. // @aka ImageOverlay options
  7137. options: {
  7138. // @option opacity: Number = 1.0
  7139. // The opacity of the image overlay.
  7140. opacity: 1,
  7141. // @option alt: String = ''
  7142. // Text for the `alt` attribute of the image (useful for accessibility).
  7143. alt: '',
  7144. // @option interactive: Boolean = false
  7145. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7146. interactive: false,
  7147. // @option crossOrigin: Boolean = false
  7148. // If true, the image will have its crossOrigin attribute set to ''. This is needed if you want to access image pixel data.
  7149. crossOrigin: false,
  7150. // @option errorOverlayUrl: String = ''
  7151. // URL to the overlay image to show in place of the overlay that failed to load.
  7152. errorOverlayUrl: '',
  7153. // @option zIndex: Number = 1
  7154. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the tile layer.
  7155. zIndex: 1,
  7156. // @option className: String = ''
  7157. // A custom class name to assign to the image. Empty by default.
  7158. className: '',
  7159. },
  7160. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7161. this._url = url;
  7162. this._bounds = toLatLngBounds(bounds);
  7163. setOptions(this, options);
  7164. },
  7165. onAdd: function () {
  7166. if (!this._image) {
  7167. this._initImage();
  7168. if (this.options.opacity < 1) {
  7169. this._updateOpacity();
  7170. }
  7171. }
  7172. if (this.options.interactive) {
  7173. addClass(this._image, 'leaflet-interactive');
  7174. this.addInteractiveTarget(this._image);
  7175. }
  7176. this.getPane().appendChild(this._image);
  7177. this._reset();
  7178. },
  7179. onRemove: function () {
  7180. remove(this._image);
  7181. if (this.options.interactive) {
  7182. this.removeInteractiveTarget(this._image);
  7183. }
  7184. },
  7185. // @method setOpacity(opacity: Number): this
  7186. // Sets the opacity of the overlay.
  7187. setOpacity: function (opacity) {
  7188. this.options.opacity = opacity;
  7189. if (this._image) {
  7190. this._updateOpacity();
  7191. }
  7192. return this;
  7193. },
  7194. setStyle: function (styleOpts) {
  7195. if (styleOpts.opacity) {
  7196. this.setOpacity(styleOpts.opacity);
  7197. }
  7198. return this;
  7199. },
  7200. // @method bringToFront(): this
  7201. // Brings the layer to the top of all overlays.
  7202. bringToFront: function () {
  7203. if (this._map) {
  7204. toFront(this._image);
  7205. }
  7206. return this;
  7207. },
  7208. // @method bringToBack(): this
  7209. // Brings the layer to the bottom of all overlays.
  7210. bringToBack: function () {
  7211. if (this._map) {
  7212. toBack(this._image);
  7213. }
  7214. return this;
  7215. },
  7216. // @method setUrl(url: String): this
  7217. // Changes the URL of the image.
  7218. setUrl: function (url) {
  7219. this._url = url;
  7220. if (this._image) {
  7221. this._image.src = url;
  7222. }
  7223. return this;
  7224. },
  7225. // @method setBounds(bounds: LatLngBounds): this
  7226. // Update the bounds that this ImageOverlay covers
  7227. setBounds: function (bounds) {
  7228. this._bounds = toLatLngBounds(bounds);
  7229. if (this._map) {
  7230. this._reset();
  7231. }
  7232. return this;
  7233. },
  7234. getEvents: function () {
  7235. var events = {
  7236. zoom: this._reset,
  7237. viewreset: this._reset
  7238. };
  7239. if (this._zoomAnimated) {
  7240. events.zoomanim = this._animateZoom;
  7241. }
  7242. return events;
  7243. },
  7244. // @method: setZIndex(value: Number) : this
  7245. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7246. setZIndex: function (value) {
  7247. this.options.zIndex = value;
  7248. this._updateZIndex();
  7249. return this;
  7250. },
  7251. // @method getBounds(): LatLngBounds
  7252. // Get the bounds that this ImageOverlay covers
  7253. getBounds: function () {
  7254. return this._bounds;
  7255. },
  7256. // @method getElement(): HTMLElement
  7257. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7258. // used by this overlay.
  7259. getElement: function () {
  7260. return this._image;
  7261. },
  7262. _initImage: function () {
  7263. var img = this._image = create$1('img',
  7264. 'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated' : '') +
  7265. (this.options.className || ''));
  7266. img.onselectstart = falseFn;
  7267. img.onmousemove = falseFn;
  7268. // @event load: Event
  7269. // Fired when the ImageOverlay layer has loaded its image
  7270. img.onload = bind(this.fire, this, 'load');
  7271. img.onerror = bind(this._overlayOnError, this, 'error');
  7272. if (this.options.crossOrigin) {
  7273. img.crossOrigin = '';
  7274. }
  7275. if (this.options.zIndex) {
  7276. this._updateZIndex();
  7277. }
  7278. img.src = this._url;
  7279. img.alt = this.options.alt;
  7280. },
  7281. _animateZoom: function (e) {
  7282. var scale = this._map.getZoomScale(e.zoom),
  7283. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7284. setTransform(this._image, offset, scale);
  7285. },
  7286. _reset: function () {
  7287. var image = this._image,
  7288. bounds = new Bounds(
  7289. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7290. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7291. size = bounds.getSize();
  7292. setPosition(image, bounds.min);
  7293. image.style.width = size.x + 'px';
  7294. image.style.height = size.y + 'px';
  7295. },
  7296. _updateOpacity: function () {
  7297. setOpacity(this._image, this.options.opacity);
  7298. },
  7299. _updateZIndex: function () {
  7300. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7301. this._image.style.zIndex = this.options.zIndex;
  7302. }
  7303. },
  7304. _overlayOnError: function () {
  7305. // @event error: Event
  7306. // Fired when the ImageOverlay layer has loaded its image
  7307. this.fire('error');
  7308. var errorUrl = this.options.errorOverlayUrl;
  7309. if (errorUrl && this._url !== errorUrl) {
  7310. this._url = errorUrl;
  7311. this._image.src = errorUrl;
  7312. }
  7313. }
  7314. });
  7315. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7316. // Instantiates an image overlay object given the URL of the image and the
  7317. // geographical bounds it is tied to.
  7318. var imageOverlay = function (url, bounds, options) {
  7319. return new ImageOverlay(url, bounds, options);
  7320. };
  7321. /*
  7322. * @class VideoOverlay
  7323. * @aka L.VideoOverlay
  7324. * @inherits ImageOverlay
  7325. *
  7326. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7327. *
  7328. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7329. * HTML5 element.
  7330. *
  7331. * @example
  7332. *
  7333. * ```js
  7334. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7335. * videoBounds = [[ 32, -130], [ 13, -100]];
  7336. * L.VideoOverlay(videoUrl, videoBounds ).addTo(map);
  7337. * ```
  7338. */
  7339. var VideoOverlay = ImageOverlay.extend({
  7340. // @section
  7341. // @aka VideoOverlay options
  7342. options: {
  7343. // @option autoplay: Boolean = true
  7344. // Whether the video starts playing automatically when loaded.
  7345. autoplay: true,
  7346. // @option loop: Boolean = true
  7347. // Whether the video will loop back to the beginning when played.
  7348. loop: true
  7349. },
  7350. _initImage: function () {
  7351. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7352. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7353. vid.class = vid.class || '';
  7354. vid.class += 'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated' : '');
  7355. vid.onselectstart = falseFn;
  7356. vid.onmousemove = falseFn;
  7357. // @event load: Event
  7358. // Fired when the video has finished loading the first frame
  7359. vid.onloadeddata = bind(this.fire, this, 'load');
  7360. if (wasElementSupplied) { return; }
  7361. if (!isArray(this._url)) { this._url = [this._url]; }
  7362. vid.autoplay = !!this.options.autoplay;
  7363. vid.loop = !!this.options.loop;
  7364. for (var i = 0; i < this._url.length; i++) {
  7365. var source = create$1('source');
  7366. source.src = this._url[i];
  7367. vid.appendChild(source);
  7368. }
  7369. }
  7370. // @method getElement(): HTMLVideoElement
  7371. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7372. // used by this overlay.
  7373. });
  7374. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7375. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7376. // geographical bounds it is tied to.
  7377. function videoOverlay(video, bounds, options) {
  7378. return new VideoOverlay(video, bounds, options);
  7379. }
  7380. /*
  7381. * @class DivOverlay
  7382. * @inherits Layer
  7383. * @aka L.DivOverlay
  7384. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  7385. */
  7386. // @namespace DivOverlay
  7387. var DivOverlay = Layer.extend({
  7388. // @section
  7389. // @aka DivOverlay options
  7390. options: {
  7391. // @option offset: Point = Point(0, 7)
  7392. // The offset of the popup position. Useful to control the anchor
  7393. // of the popup when opening it on some overlays.
  7394. offset: [0, 7],
  7395. // @option className: String = ''
  7396. // A custom CSS class name to assign to the popup.
  7397. className: '',
  7398. // @option pane: String = 'popupPane'
  7399. // `Map pane` where the popup will be added.
  7400. pane: 'popupPane'
  7401. },
  7402. initialize: function (options, source) {
  7403. setOptions(this, options);
  7404. this._source = source;
  7405. },
  7406. onAdd: function (map) {
  7407. this._zoomAnimated = map._zoomAnimated;
  7408. if (!this._container) {
  7409. this._initLayout();
  7410. }
  7411. if (map._fadeAnimated) {
  7412. setOpacity(this._container, 0);
  7413. }
  7414. clearTimeout(this._removeTimeout);
  7415. this.getPane().appendChild(this._container);
  7416. this.update();
  7417. if (map._fadeAnimated) {
  7418. setOpacity(this._container, 1);
  7419. }
  7420. this.bringToFront();
  7421. },
  7422. onRemove: function (map) {
  7423. if (map._fadeAnimated) {
  7424. setOpacity(this._container, 0);
  7425. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  7426. } else {
  7427. remove(this._container);
  7428. }
  7429. },
  7430. // @namespace Popup
  7431. // @method getLatLng: LatLng
  7432. // Returns the geographical point of popup.
  7433. getLatLng: function () {
  7434. return this._latlng;
  7435. },
  7436. // @method setLatLng(latlng: LatLng): this
  7437. // Sets the geographical point where the popup will open.
  7438. setLatLng: function (latlng) {
  7439. this._latlng = toLatLng(latlng);
  7440. if (this._map) {
  7441. this._updatePosition();
  7442. this._adjustPan();
  7443. }
  7444. return this;
  7445. },
  7446. // @method getContent: String|HTMLElement
  7447. // Returns the content of the popup.
  7448. getContent: function () {
  7449. return this._content;
  7450. },
  7451. // @method setContent(htmlContent: String|HTMLElement|Function): this
  7452. // Sets the HTML content of the popup. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the popup.
  7453. setContent: function (content) {
  7454. this._content = content;
  7455. this.update();
  7456. return this;
  7457. },
  7458. // @method getElement: String|HTMLElement
  7459. // Alias for [getContent()](#popup-getcontent)
  7460. getElement: function () {
  7461. return this._container;
  7462. },
  7463. // @method update: null
  7464. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  7465. update: function () {
  7466. if (!this._map) { return; }
  7467. this._container.style.visibility = 'hidden';
  7468. this._updateContent();
  7469. this._updateLayout();
  7470. this._updatePosition();
  7471. this._container.style.visibility = '';
  7472. this._adjustPan();
  7473. },
  7474. getEvents: function () {
  7475. var events = {
  7476. zoom: this._updatePosition,
  7477. viewreset: this._updatePosition
  7478. };
  7479. if (this._zoomAnimated) {
  7480. events.zoomanim = this._animateZoom;
  7481. }
  7482. return events;
  7483. },
  7484. // @method isOpen: Boolean
  7485. // Returns `true` when the popup is visible on the map.
  7486. isOpen: function () {
  7487. return !!this._map && this._map.hasLayer(this);
  7488. },
  7489. // @method bringToFront: this
  7490. // Brings this popup in front of other popups (in the same map pane).
  7491. bringToFront: function () {
  7492. if (this._map) {
  7493. toFront(this._container);
  7494. }
  7495. return this;
  7496. },
  7497. // @method bringToBack: this
  7498. // Brings this popup to the back of other popups (in the same map pane).
  7499. bringToBack: function () {
  7500. if (this._map) {
  7501. toBack(this._container);
  7502. }
  7503. return this;
  7504. },
  7505. _updateContent: function () {
  7506. if (!this._content) { return; }
  7507. var node = this._contentNode;
  7508. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  7509. if (typeof content === 'string') {
  7510. node.innerHTML = content;
  7511. } else {
  7512. while (node.hasChildNodes()) {
  7513. node.removeChild(node.firstChild);
  7514. }
  7515. node.appendChild(content);
  7516. }
  7517. this.fire('contentupdate');
  7518. },
  7519. _updatePosition: function () {
  7520. if (!this._map) { return; }
  7521. var pos = this._map.latLngToLayerPoint(this._latlng),
  7522. offset = toPoint(this.options.offset),
  7523. anchor = this._getAnchor();
  7524. if (this._zoomAnimated) {
  7525. setPosition(this._container, pos.add(anchor));
  7526. } else {
  7527. offset = offset.add(pos).add(anchor);
  7528. }
  7529. var bottom = this._containerBottom = -offset.y,
  7530. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  7531. // bottom position the popup in case the height of the popup changes (images loading etc)
  7532. this._container.style.bottom = bottom + 'px';
  7533. this._container.style.left = left + 'px';
  7534. },
  7535. _getAnchor: function () {
  7536. return [0, 0];
  7537. }
  7538. });
  7539. /*
  7540. * @class Popup
  7541. * @inherits DivOverlay
  7542. * @aka L.Popup
  7543. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  7544. * open popups while making sure that only one popup is open at one time
  7545. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  7546. *
  7547. * @example
  7548. *
  7549. * If you want to just bind a popup to marker click and then open it, it's really easy:
  7550. *
  7551. * ```js
  7552. * marker.bindPopup(popupContent).openPopup();
  7553. * ```
  7554. * Path overlays like polylines also have a `bindPopup` method.
  7555. * Here's a more complicated way to open a popup on a map:
  7556. *
  7557. * ```js
  7558. * var popup = L.popup()
  7559. * .setLatLng(latlng)
  7560. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  7561. * .openOn(map);
  7562. * ```
  7563. */
  7564. // @namespace Popup
  7565. var Popup = DivOverlay.extend({
  7566. // @section
  7567. // @aka Popup options
  7568. options: {
  7569. // @option maxWidth: Number = 300
  7570. // Max width of the popup, in pixels.
  7571. maxWidth: 300,
  7572. // @option minWidth: Number = 50
  7573. // Min width of the popup, in pixels.
  7574. minWidth: 50,
  7575. // @option maxHeight: Number = null
  7576. // If set, creates a scrollable container of the given height
  7577. // inside a popup if its content exceeds it.
  7578. maxHeight: null,
  7579. // @option autoPan: Boolean = true
  7580. // Set it to `false` if you don't want the map to do panning animation
  7581. // to fit the opened popup.
  7582. autoPan: true,
  7583. // @option autoPanPaddingTopLeft: Point = null
  7584. // The margin between the popup and the top left corner of the map
  7585. // view after autopanning was performed.
  7586. autoPanPaddingTopLeft: null,
  7587. // @option autoPanPaddingBottomRight: Point = null
  7588. // The margin between the popup and the bottom right corner of the map
  7589. // view after autopanning was performed.
  7590. autoPanPaddingBottomRight: null,
  7591. // @option autoPanPadding: Point = Point(5, 5)
  7592. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  7593. autoPanPadding: [5, 5],
  7594. // @option keepInView: Boolean = false
  7595. // Set it to `true` if you want to prevent users from panning the popup
  7596. // off of the screen while it is open.
  7597. keepInView: false,
  7598. // @option closeButton: Boolean = true
  7599. // Controls the presence of a close button in the popup.
  7600. closeButton: true,
  7601. // @option autoClose: Boolean = true
  7602. // Set it to `false` if you want to override the default behavior of
  7603. // the popup closing when another popup is opened.
  7604. autoClose: true,
  7605. // @option closeOnClick: Boolean = *
  7606. // Set it if you want to override the default behavior of the popup closing when user clicks
  7607. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  7608. // @option className: String = ''
  7609. // A custom CSS class name to assign to the popup.
  7610. className: ''
  7611. },
  7612. // @namespace Popup
  7613. // @method openOn(map: Map): this
  7614. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  7615. openOn: function (map) {
  7616. map.openPopup(this);
  7617. return this;
  7618. },
  7619. onAdd: function (map) {
  7620. DivOverlay.prototype.onAdd.call(this, map);
  7621. // @namespace Map
  7622. // @section Popup events
  7623. // @event popupopen: PopupEvent
  7624. // Fired when a popup is opened in the map
  7625. map.fire('popupopen', {popup: this});
  7626. if (this._source) {
  7627. // @namespace Layer
  7628. // @section Popup events
  7629. // @event popupopen: PopupEvent
  7630. // Fired when a popup bound to this layer is opened
  7631. this._source.fire('popupopen', {popup: this}, true);
  7632. // For non-path layers, we toggle the popup when clicking
  7633. // again the layer, so prevent the map to reopen it.
  7634. if (!(this._source instanceof Path)) {
  7635. this._source.on('preclick', stopPropagation);
  7636. }
  7637. }
  7638. },
  7639. onRemove: function (map) {
  7640. DivOverlay.prototype.onRemove.call(this, map);
  7641. // @namespace Map
  7642. // @section Popup events
  7643. // @event popupclose: PopupEvent
  7644. // Fired when a popup in the map is closed
  7645. map.fire('popupclose', {popup: this});
  7646. if (this._source) {
  7647. // @namespace Layer
  7648. // @section Popup events
  7649. // @event popupclose: PopupEvent
  7650. // Fired when a popup bound to this layer is closed
  7651. this._source.fire('popupclose', {popup: this}, true);
  7652. if (!(this._source instanceof Path)) {
  7653. this._source.off('preclick', stopPropagation);
  7654. }
  7655. }
  7656. },
  7657. getEvents: function () {
  7658. var events = DivOverlay.prototype.getEvents.call(this);
  7659. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  7660. events.preclick = this._close;
  7661. }
  7662. if (this.options.keepInView) {
  7663. events.moveend = this._adjustPan;
  7664. }
  7665. return events;
  7666. },
  7667. _close: function () {
  7668. if (this._map) {
  7669. this._map.closePopup(this);
  7670. }
  7671. },
  7672. _initLayout: function () {
  7673. var prefix = 'leaflet-popup',
  7674. container = this._container = create$1('div',
  7675. prefix + ' ' + (this.options.className || '') +
  7676. ' leaflet-zoom-animated');
  7677. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  7678. this._contentNode = create$1('div', prefix + '-content', wrapper);
  7679. disableClickPropagation(wrapper);
  7680. disableScrollPropagation(this._contentNode);
  7681. on(wrapper, 'contextmenu', stopPropagation);
  7682. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  7683. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  7684. if (this.options.closeButton) {
  7685. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  7686. closeButton.href = '#close';
  7687. closeButton.innerHTML = '&#215;';
  7688. on(closeButton, 'click', this._onCloseButtonClick, this);
  7689. }
  7690. },
  7691. _updateLayout: function () {
  7692. var container = this._contentNode,
  7693. style = container.style;
  7694. style.width = '';
  7695. style.whiteSpace = 'nowrap';
  7696. var width = container.offsetWidth;
  7697. width = Math.min(width, this.options.maxWidth);
  7698. width = Math.max(width, this.options.minWidth);
  7699. style.width = (width + 1) + 'px';
  7700. style.whiteSpace = '';
  7701. style.height = '';
  7702. var height = container.offsetHeight,
  7703. maxHeight = this.options.maxHeight,
  7704. scrolledClass = 'leaflet-popup-scrolled';
  7705. if (maxHeight && height > maxHeight) {
  7706. style.height = maxHeight + 'px';
  7707. addClass(container, scrolledClass);
  7708. } else {
  7709. removeClass(container, scrolledClass);
  7710. }
  7711. this._containerWidth = this._container.offsetWidth;
  7712. },
  7713. _animateZoom: function (e) {
  7714. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  7715. anchor = this._getAnchor();
  7716. setPosition(this._container, pos.add(anchor));
  7717. },
  7718. _adjustPan: function () {
  7719. if (!this.options.autoPan || (this._map._panAnim && this._map._panAnim._inProgress)) { return; }
  7720. var map = this._map,
  7721. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  7722. containerHeight = this._container.offsetHeight + marginBottom,
  7723. containerWidth = this._containerWidth,
  7724. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  7725. layerPos._add(getPosition(this._container));
  7726. var containerPos = map.layerPointToContainerPoint(layerPos),
  7727. padding = toPoint(this.options.autoPanPadding),
  7728. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  7729. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  7730. size = map.getSize(),
  7731. dx = 0,
  7732. dy = 0;
  7733. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  7734. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  7735. }
  7736. if (containerPos.x - dx - paddingTL.x < 0) { // left
  7737. dx = containerPos.x - paddingTL.x;
  7738. }
  7739. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  7740. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  7741. }
  7742. if (containerPos.y - dy - paddingTL.y < 0) { // top
  7743. dy = containerPos.y - paddingTL.y;
  7744. }
  7745. // @namespace Map
  7746. // @section Popup events
  7747. // @event autopanstart: Event
  7748. // Fired when the map starts autopanning when opening a popup.
  7749. if (dx || dy) {
  7750. map
  7751. .fire('autopanstart')
  7752. .panBy([dx, dy]);
  7753. }
  7754. },
  7755. _onCloseButtonClick: function (e) {
  7756. this._close();
  7757. stop(e);
  7758. },
  7759. _getAnchor: function () {
  7760. // Where should we anchor the popup on the source layer?
  7761. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  7762. }
  7763. });
  7764. // @namespace Popup
  7765. // @factory L.popup(options?: Popup options, source?: Layer)
  7766. // Instantiates a `Popup` object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the popup with a reference to the Layer to which it refers.
  7767. var popup = function (options, source) {
  7768. return new Popup(options, source);
  7769. };
  7770. /* @namespace Map
  7771. * @section Interaction Options
  7772. * @option closePopupOnClick: Boolean = true
  7773. * Set it to `false` if you don't want popups to close when user clicks the map.
  7774. */
  7775. Map.mergeOptions({
  7776. closePopupOnClick: true
  7777. });
  7778. // @namespace Map
  7779. // @section Methods for Layers and Controls
  7780. Map.include({
  7781. // @method openPopup(popup: Popup): this
  7782. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  7783. // @alternative
  7784. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  7785. // Creates a popup with the specified content and options and opens it in the given point on a map.
  7786. openPopup: function (popup, latlng, options) {
  7787. if (!(popup instanceof Popup)) {
  7788. popup = new Popup(options).setContent(popup);
  7789. }
  7790. if (latlng) {
  7791. popup.setLatLng(latlng);
  7792. }
  7793. if (this.hasLayer(popup)) {
  7794. return this;
  7795. }
  7796. if (this._popup && this._popup.options.autoClose) {
  7797. this.closePopup();
  7798. }
  7799. this._popup = popup;
  7800. return this.addLayer(popup);
  7801. },
  7802. // @method closePopup(popup?: Popup): this
  7803. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  7804. closePopup: function (popup) {
  7805. if (!popup || popup === this._popup) {
  7806. popup = this._popup;
  7807. this._popup = null;
  7808. }
  7809. if (popup) {
  7810. this.removeLayer(popup);
  7811. }
  7812. return this;
  7813. }
  7814. });
  7815. /*
  7816. * @namespace Layer
  7817. * @section Popup methods example
  7818. *
  7819. * All layers share a set of methods convenient for binding popups to it.
  7820. *
  7821. * ```js
  7822. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  7823. * layer.openPopup();
  7824. * layer.closePopup();
  7825. * ```
  7826. *
  7827. * Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened.
  7828. */
  7829. // @section Popup methods
  7830. Layer.include({
  7831. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  7832. // Binds a popup to the layer with the passed `content` and sets up the
  7833. // necessary event listeners. If a `Function` is passed it will receive
  7834. // the layer as the first argument and should return a `String` or `HTMLElement`.
  7835. bindPopup: function (content, options) {
  7836. if (content instanceof Popup) {
  7837. setOptions(content, options);
  7838. this._popup = content;
  7839. content._source = this;
  7840. } else {
  7841. if (!this._popup || options) {
  7842. this._popup = new Popup(options, this);
  7843. }
  7844. this._popup.setContent(content);
  7845. }
  7846. if (!this._popupHandlersAdded) {
  7847. this.on({
  7848. click: this._openPopup,
  7849. keypress: this._onKeyPress,
  7850. remove: this.closePopup,
  7851. move: this._movePopup
  7852. });
  7853. this._popupHandlersAdded = true;
  7854. }
  7855. return this;
  7856. },
  7857. // @method unbindPopup(): this
  7858. // Removes the popup previously bound with `bindPopup`.
  7859. unbindPopup: function () {
  7860. if (this._popup) {
  7861. this.off({
  7862. click: this._openPopup,
  7863. keypress: this._onKeyPress,
  7864. remove: this.closePopup,
  7865. move: this._movePopup
  7866. });
  7867. this._popupHandlersAdded = false;
  7868. this._popup = null;
  7869. }
  7870. return this;
  7871. },
  7872. // @method openPopup(latlng?: LatLng): this
  7873. // Opens the bound popup at the specificed `latlng` or at the default popup anchor if no `latlng` is passed.
  7874. openPopup: function (layer, latlng) {
  7875. if (!(layer instanceof Layer)) {
  7876. latlng = layer;
  7877. layer = this;
  7878. }
  7879. if (layer instanceof FeatureGroup) {
  7880. for (var id in this._layers) {
  7881. layer = this._layers[id];
  7882. break;
  7883. }
  7884. }
  7885. if (!latlng) {
  7886. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  7887. }
  7888. if (this._popup && this._map) {
  7889. // set popup source to this layer
  7890. this._popup._source = layer;
  7891. // update the popup (content, layout, ect...)
  7892. this._popup.update();
  7893. // open the popup on the map
  7894. this._map.openPopup(this._popup, latlng);
  7895. }
  7896. return this;
  7897. },
  7898. // @method closePopup(): this
  7899. // Closes the popup bound to this layer if it is open.
  7900. closePopup: function () {
  7901. if (this._popup) {
  7902. this._popup._close();
  7903. }
  7904. return this;
  7905. },
  7906. // @method togglePopup(): this
  7907. // Opens or closes the popup bound to this layer depending on its current state.
  7908. togglePopup: function (target) {
  7909. if (this._popup) {
  7910. if (this._popup._map) {
  7911. this.closePopup();
  7912. } else {
  7913. this.openPopup(target);
  7914. }
  7915. }
  7916. return this;
  7917. },
  7918. // @method isPopupOpen(): boolean
  7919. // Returns `true` if the popup bound to this layer is currently open.
  7920. isPopupOpen: function () {
  7921. return (this._popup ? this._popup.isOpen() : false);
  7922. },
  7923. // @method setPopupContent(content: String|HTMLElement|Popup): this
  7924. // Sets the content of the popup bound to this layer.
  7925. setPopupContent: function (content) {
  7926. if (this._popup) {
  7927. this._popup.setContent(content);
  7928. }
  7929. return this;
  7930. },
  7931. // @method getPopup(): Popup
  7932. // Returns the popup bound to this layer.
  7933. getPopup: function () {
  7934. return this._popup;
  7935. },
  7936. _openPopup: function (e) {
  7937. var layer = e.layer || e.target;
  7938. if (!this._popup) {
  7939. return;
  7940. }
  7941. if (!this._map) {
  7942. return;
  7943. }
  7944. // prevent map click
  7945. stop(e);
  7946. // if this inherits from Path its a vector and we can just
  7947. // open the popup at the new location
  7948. if (layer instanceof Path) {
  7949. this.openPopup(e.layer || e.target, e.latlng);
  7950. return;
  7951. }
  7952. // otherwise treat it like a marker and figure out
  7953. // if we should toggle it open/closed
  7954. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  7955. this.closePopup();
  7956. } else {
  7957. this.openPopup(layer, e.latlng);
  7958. }
  7959. },
  7960. _movePopup: function (e) {
  7961. this._popup.setLatLng(e.latlng);
  7962. },
  7963. _onKeyPress: function (e) {
  7964. if (e.originalEvent.keyCode === 13) {
  7965. this._openPopup(e);
  7966. }
  7967. }
  7968. });
  7969. /*
  7970. * @class Tooltip
  7971. * @inherits DivOverlay
  7972. * @aka L.Tooltip
  7973. * Used to display small texts on top of map layers.
  7974. *
  7975. * @example
  7976. *
  7977. * ```js
  7978. * marker.bindTooltip("my tooltip text").openTooltip();
  7979. * ```
  7980. * Note about tooltip offset. Leaflet takes two options in consideration
  7981. * for computing tooltip offseting:
  7982. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  7983. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  7984. * move it to the bottom. Negatives will move to the left and top.
  7985. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  7986. * should adapt this value if you use a custom icon.
  7987. */
  7988. // @namespace Tooltip
  7989. var Tooltip = DivOverlay.extend({
  7990. // @section
  7991. // @aka Tooltip options
  7992. options: {
  7993. // @option pane: String = 'tooltipPane'
  7994. // `Map pane` where the tooltip will be added.
  7995. pane: 'tooltipPane',
  7996. // @option offset: Point = Point(0, 0)
  7997. // Optional offset of the tooltip position.
  7998. offset: [0, 0],
  7999. // @option direction: String = 'auto'
  8000. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8001. // `top`, `bottom`, `center`, `auto`.
  8002. // `auto` will dynamicaly switch between `right` and `left` according to the tooltip
  8003. // position on the map.
  8004. direction: 'auto',
  8005. // @option permanent: Boolean = false
  8006. // Whether to open the tooltip permanently or only on mouseover.
  8007. permanent: false,
  8008. // @option sticky: Boolean = false
  8009. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8010. sticky: false,
  8011. // @option interactive: Boolean = false
  8012. // If true, the tooltip will listen to the feature events.
  8013. interactive: false,
  8014. // @option opacity: Number = 0.9
  8015. // Tooltip container opacity.
  8016. opacity: 0.9
  8017. },
  8018. onAdd: function (map) {
  8019. DivOverlay.prototype.onAdd.call(this, map);
  8020. this.setOpacity(this.options.opacity);
  8021. // @namespace Map
  8022. // @section Tooltip events
  8023. // @event tooltipopen: TooltipEvent
  8024. // Fired when a tooltip is opened in the map.
  8025. map.fire('tooltipopen', {tooltip: this});
  8026. if (this._source) {
  8027. // @namespace Layer
  8028. // @section Tooltip events
  8029. // @event tooltipopen: TooltipEvent
  8030. // Fired when a tooltip bound to this layer is opened.
  8031. this._source.fire('tooltipopen', {tooltip: this}, true);
  8032. }
  8033. },
  8034. onRemove: function (map) {
  8035. DivOverlay.prototype.onRemove.call(this, map);
  8036. // @namespace Map
  8037. // @section Tooltip events
  8038. // @event tooltipclose: TooltipEvent
  8039. // Fired when a tooltip in the map is closed.
  8040. map.fire('tooltipclose', {tooltip: this});
  8041. if (this._source) {
  8042. // @namespace Layer
  8043. // @section Tooltip events
  8044. // @event tooltipclose: TooltipEvent
  8045. // Fired when a tooltip bound to this layer is closed.
  8046. this._source.fire('tooltipclose', {tooltip: this}, true);
  8047. }
  8048. },
  8049. getEvents: function () {
  8050. var events = DivOverlay.prototype.getEvents.call(this);
  8051. if (touch && !this.options.permanent) {
  8052. events.preclick = this._close;
  8053. }
  8054. return events;
  8055. },
  8056. _close: function () {
  8057. if (this._map) {
  8058. this._map.closeTooltip(this);
  8059. }
  8060. },
  8061. _initLayout: function () {
  8062. var prefix = 'leaflet-tooltip',
  8063. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8064. this._contentNode = this._container = create$1('div', className);
  8065. },
  8066. _updateLayout: function () {},
  8067. _adjustPan: function () {},
  8068. _setPosition: function (pos) {
  8069. var map = this._map,
  8070. container = this._container,
  8071. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8072. tooltipPoint = map.layerPointToContainerPoint(pos),
  8073. direction = this.options.direction,
  8074. tooltipWidth = container.offsetWidth,
  8075. tooltipHeight = container.offsetHeight,
  8076. offset = toPoint(this.options.offset),
  8077. anchor = this._getAnchor();
  8078. if (direction === 'top') {
  8079. pos = pos.add(toPoint(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true));
  8080. } else if (direction === 'bottom') {
  8081. pos = pos.subtract(toPoint(tooltipWidth / 2 - offset.x, -offset.y, true));
  8082. } else if (direction === 'center') {
  8083. pos = pos.subtract(toPoint(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true));
  8084. } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
  8085. direction = 'right';
  8086. pos = pos.add(toPoint(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true));
  8087. } else {
  8088. direction = 'left';
  8089. pos = pos.subtract(toPoint(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true));
  8090. }
  8091. removeClass(container, 'leaflet-tooltip-right');
  8092. removeClass(container, 'leaflet-tooltip-left');
  8093. removeClass(container, 'leaflet-tooltip-top');
  8094. removeClass(container, 'leaflet-tooltip-bottom');
  8095. addClass(container, 'leaflet-tooltip-' + direction);
  8096. setPosition(container, pos);
  8097. },
  8098. _updatePosition: function () {
  8099. var pos = this._map.latLngToLayerPoint(this._latlng);
  8100. this._setPosition(pos);
  8101. },
  8102. setOpacity: function (opacity) {
  8103. this.options.opacity = opacity;
  8104. if (this._container) {
  8105. setOpacity(this._container, opacity);
  8106. }
  8107. },
  8108. _animateZoom: function (e) {
  8109. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8110. this._setPosition(pos);
  8111. },
  8112. _getAnchor: function () {
  8113. // Where should we anchor the tooltip on the source layer?
  8114. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8115. }
  8116. });
  8117. // @namespace Tooltip
  8118. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8119. // Instantiates a Tooltip object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the tooltip with a reference to the Layer to which it refers.
  8120. var tooltip = function (options, source) {
  8121. return new Tooltip(options, source);
  8122. };
  8123. // @namespace Map
  8124. // @section Methods for Layers and Controls
  8125. Map.include({
  8126. // @method openTooltip(tooltip: Tooltip): this
  8127. // Opens the specified tooltip.
  8128. // @alternative
  8129. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8130. // Creates a tooltip with the specified content and options and open it.
  8131. openTooltip: function (tooltip, latlng, options) {
  8132. if (!(tooltip instanceof Tooltip)) {
  8133. tooltip = new Tooltip(options).setContent(tooltip);
  8134. }
  8135. if (latlng) {
  8136. tooltip.setLatLng(latlng);
  8137. }
  8138. if (this.hasLayer(tooltip)) {
  8139. return this;
  8140. }
  8141. return this.addLayer(tooltip);
  8142. },
  8143. // @method closeTooltip(tooltip?: Tooltip): this
  8144. // Closes the tooltip given as parameter.
  8145. closeTooltip: function (tooltip) {
  8146. if (tooltip) {
  8147. this.removeLayer(tooltip);
  8148. }
  8149. return this;
  8150. }
  8151. });
  8152. /*
  8153. * @namespace Layer
  8154. * @section Tooltip methods example
  8155. *
  8156. * All layers share a set of methods convenient for binding tooltips to it.
  8157. *
  8158. * ```js
  8159. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8160. * layer.openTooltip();
  8161. * layer.closeTooltip();
  8162. * ```
  8163. */
  8164. // @section Tooltip methods
  8165. Layer.include({
  8166. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8167. // Binds a tooltip to the layer with the passed `content` and sets up the
  8168. // necessary event listeners. If a `Function` is passed it will receive
  8169. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8170. bindTooltip: function (content, options) {
  8171. if (content instanceof Tooltip) {
  8172. setOptions(content, options);
  8173. this._tooltip = content;
  8174. content._source = this;
  8175. } else {
  8176. if (!this._tooltip || options) {
  8177. this._tooltip = new Tooltip(options, this);
  8178. }
  8179. this._tooltip.setContent(content);
  8180. }
  8181. this._initTooltipInteractions();
  8182. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8183. this.openTooltip();
  8184. }
  8185. return this;
  8186. },
  8187. // @method unbindTooltip(): this
  8188. // Removes the tooltip previously bound with `bindTooltip`.
  8189. unbindTooltip: function () {
  8190. if (this._tooltip) {
  8191. this._initTooltipInteractions(true);
  8192. this.closeTooltip();
  8193. this._tooltip = null;
  8194. }
  8195. return this;
  8196. },
  8197. _initTooltipInteractions: function (remove$$1) {
  8198. if (!remove$$1 && this._tooltipHandlersAdded) { return; }
  8199. var onOff = remove$$1 ? 'off' : 'on',
  8200. events = {
  8201. remove: this.closeTooltip,
  8202. move: this._moveTooltip
  8203. };
  8204. if (!this._tooltip.options.permanent) {
  8205. events.mouseover = this._openTooltip;
  8206. events.mouseout = this.closeTooltip;
  8207. if (this._tooltip.options.sticky) {
  8208. events.mousemove = this._moveTooltip;
  8209. }
  8210. if (touch) {
  8211. events.click = this._openTooltip;
  8212. }
  8213. } else {
  8214. events.add = this._openTooltip;
  8215. }
  8216. this[onOff](events);
  8217. this._tooltipHandlersAdded = !remove$$1;
  8218. },
  8219. // @method openTooltip(latlng?: LatLng): this
  8220. // Opens the bound tooltip at the specificed `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8221. openTooltip: function (layer, latlng) {
  8222. if (!(layer instanceof Layer)) {
  8223. latlng = layer;
  8224. layer = this;
  8225. }
  8226. if (layer instanceof FeatureGroup) {
  8227. for (var id in this._layers) {
  8228. layer = this._layers[id];
  8229. break;
  8230. }
  8231. }
  8232. if (!latlng) {
  8233. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  8234. }
  8235. if (this._tooltip && this._map) {
  8236. // set tooltip source to this layer
  8237. this._tooltip._source = layer;
  8238. // update the tooltip (content, layout, ect...)
  8239. this._tooltip.update();
  8240. // open the tooltip on the map
  8241. this._map.openTooltip(this._tooltip, latlng);
  8242. // Tooltip container may not be defined if not permanent and never
  8243. // opened.
  8244. if (this._tooltip.options.interactive && this._tooltip._container) {
  8245. addClass(this._tooltip._container, 'leaflet-clickable');
  8246. this.addInteractiveTarget(this._tooltip._container);
  8247. }
  8248. }
  8249. return this;
  8250. },
  8251. // @method closeTooltip(): this
  8252. // Closes the tooltip bound to this layer if it is open.
  8253. closeTooltip: function () {
  8254. if (this._tooltip) {
  8255. this._tooltip._close();
  8256. if (this._tooltip.options.interactive && this._tooltip._container) {
  8257. removeClass(this._tooltip._container, 'leaflet-clickable');
  8258. this.removeInteractiveTarget(this._tooltip._container);
  8259. }
  8260. }
  8261. return this;
  8262. },
  8263. // @method toggleTooltip(): this
  8264. // Opens or closes the tooltip bound to this layer depending on its current state.
  8265. toggleTooltip: function (target) {
  8266. if (this._tooltip) {
  8267. if (this._tooltip._map) {
  8268. this.closeTooltip();
  8269. } else {
  8270. this.openTooltip(target);
  8271. }
  8272. }
  8273. return this;
  8274. },
  8275. // @method isTooltipOpen(): boolean
  8276. // Returns `true` if the tooltip bound to this layer is currently open.
  8277. isTooltipOpen: function () {
  8278. return this._tooltip.isOpen();
  8279. },
  8280. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8281. // Sets the content of the tooltip bound to this layer.
  8282. setTooltipContent: function (content) {
  8283. if (this._tooltip) {
  8284. this._tooltip.setContent(content);
  8285. }
  8286. return this;
  8287. },
  8288. // @method getTooltip(): Tooltip
  8289. // Returns the tooltip bound to this layer.
  8290. getTooltip: function () {
  8291. return this._tooltip;
  8292. },
  8293. _openTooltip: function (e) {
  8294. var layer = e.layer || e.target;
  8295. if (!this._tooltip || !this._map) {
  8296. return;
  8297. }
  8298. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  8299. },
  8300. _moveTooltip: function (e) {
  8301. var latlng = e.latlng, containerPoint, layerPoint;
  8302. if (this._tooltip.options.sticky && e.originalEvent) {
  8303. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  8304. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  8305. latlng = this._map.layerPointToLatLng(layerPoint);
  8306. }
  8307. this._tooltip.setLatLng(latlng);
  8308. }
  8309. });
  8310. /*
  8311. * @class DivIcon
  8312. * @aka L.DivIcon
  8313. * @inherits Icon
  8314. *
  8315. * Represents a lightweight icon for markers that uses a simple `<div>`
  8316. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  8317. *
  8318. * @example
  8319. * ```js
  8320. * var myIcon = L.divIcon({className: 'my-div-icon'});
  8321. * // you can set .my-div-icon styles in CSS
  8322. *
  8323. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  8324. * ```
  8325. *
  8326. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  8327. */
  8328. var DivIcon = Icon.extend({
  8329. options: {
  8330. // @section
  8331. // @aka DivIcon options
  8332. iconSize: [12, 12], // also can be set through CSS
  8333. // iconAnchor: (Point),
  8334. // popupAnchor: (Point),
  8335. // @option html: String = ''
  8336. // Custom HTML code to put inside the div element, empty by default.
  8337. html: false,
  8338. // @option bgPos: Point = [0, 0]
  8339. // Optional relative position of the background, in pixels
  8340. bgPos: null,
  8341. className: 'leaflet-div-icon'
  8342. },
  8343. createIcon: function (oldIcon) {
  8344. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  8345. options = this.options;
  8346. div.innerHTML = options.html !== false ? options.html : '';
  8347. if (options.bgPos) {
  8348. var bgPos = toPoint(options.bgPos);
  8349. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  8350. }
  8351. this._setIconStyles(div, 'icon');
  8352. return div;
  8353. },
  8354. createShadow: function () {
  8355. return null;
  8356. }
  8357. });
  8358. // @factory L.divIcon(options: DivIcon options)
  8359. // Creates a `DivIcon` instance with the given options.
  8360. function divIcon(options) {
  8361. return new DivIcon(options);
  8362. }
  8363. Icon.Default = IconDefault;
  8364. /*
  8365. * @class GridLayer
  8366. * @inherits Layer
  8367. * @aka L.GridLayer
  8368. *
  8369. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  8370. * GridLayer can be extended to create a tiled grid of HTML elements like `<canvas>`, `<img>` or `<div>`. GridLayer will handle creating and animating these DOM elements for you.
  8371. *
  8372. *
  8373. * @section Synchronous usage
  8374. * @example
  8375. *
  8376. * To create a custom layer, extend GridLayer and implement the `createTile()` method, which will be passed a `Point` object with the `x`, `y`, and `z` (zoom level) coordinates to draw your tile.
  8377. *
  8378. * ```js
  8379. * var CanvasLayer = L.GridLayer.extend({
  8380. * createTile: function(coords){
  8381. * // create a <canvas> element for drawing
  8382. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8383. *
  8384. * // setup tile width and height according to the options
  8385. * var size = this.getTileSize();
  8386. * tile.width = size.x;
  8387. * tile.height = size.y;
  8388. *
  8389. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  8390. * var ctx = tile.getContext('2d');
  8391. *
  8392. * // return the tile so it can be rendered on screen
  8393. * return tile;
  8394. * }
  8395. * });
  8396. * ```
  8397. *
  8398. * @section Asynchronous usage
  8399. * @example
  8400. *
  8401. * Tile creation can also be asynchronous, this is useful when using a third-party drawing library. Once the tile is finished drawing it can be passed to the `done()` callback.
  8402. *
  8403. * ```js
  8404. * var CanvasLayer = L.GridLayer.extend({
  8405. * createTile: function(coords, done){
  8406. * var error;
  8407. *
  8408. * // create a <canvas> element for drawing
  8409. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8410. *
  8411. * // setup tile width and height according to the options
  8412. * var size = this.getTileSize();
  8413. * tile.width = size.x;
  8414. * tile.height = size.y;
  8415. *
  8416. * // draw something asynchronously and pass the tile to the done() callback
  8417. * setTimeout(function() {
  8418. * done(error, tile);
  8419. * }, 1000);
  8420. *
  8421. * return tile;
  8422. * }
  8423. * });
  8424. * ```
  8425. *
  8426. * @section
  8427. */
  8428. var GridLayer = Layer.extend({
  8429. // @section
  8430. // @aka GridLayer options
  8431. options: {
  8432. // @option tileSize: Number|Point = 256
  8433. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  8434. tileSize: 256,
  8435. // @option opacity: Number = 1.0
  8436. // Opacity of the tiles. Can be used in the `createTile()` function.
  8437. opacity: 1,
  8438. // @option updateWhenIdle: Boolean = (depends)
  8439. // Load new tiles only when panning ends.
  8440. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  8441. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  8442. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  8443. updateWhenIdle: mobile,
  8444. // @option updateWhenZooming: Boolean = true
  8445. // By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends.
  8446. updateWhenZooming: true,
  8447. // @option updateInterval: Number = 200
  8448. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  8449. updateInterval: 200,
  8450. // @option zIndex: Number = 1
  8451. // The explicit zIndex of the tile layer.
  8452. zIndex: 1,
  8453. // @option bounds: LatLngBounds = undefined
  8454. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  8455. bounds: null,
  8456. // @option minZoom: Number = 0
  8457. // The minimum zoom level down to which this layer will be displayed (inclusive).
  8458. minZoom: 0,
  8459. // @option maxZoom: Number = undefined
  8460. // The maximum zoom level up to which this layer will be displayed (inclusive).
  8461. maxZoom: undefined,
  8462. // @option maxNativeZoom: Number = undefined
  8463. // Maximum zoom number the tile source has available. If it is specified,
  8464. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  8465. // from `maxNativeZoom` level and auto-scaled.
  8466. maxNativeZoom: undefined,
  8467. // @option minNativeZoom: Number = undefined
  8468. // Minimum zoom number the tile source has available. If it is specified,
  8469. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  8470. // from `minNativeZoom` level and auto-scaled.
  8471. minNativeZoom: undefined,
  8472. // @option noWrap: Boolean = false
  8473. // Whether the layer is wrapped around the antimeridian. If `true`, the
  8474. // GridLayer will only be displayed once at low zoom levels. Has no
  8475. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  8476. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  8477. // tiles outside the CRS limits.
  8478. noWrap: false,
  8479. // @option pane: String = 'tilePane'
  8480. // `Map pane` where the grid layer will be added.
  8481. pane: 'tilePane',
  8482. // @option className: String = ''
  8483. // A custom class name to assign to the tile layer. Empty by default.
  8484. className: '',
  8485. // @option keepBuffer: Number = 2
  8486. // When panning the map, keep this many rows and columns of tiles before unloading them.
  8487. keepBuffer: 2
  8488. },
  8489. initialize: function (options) {
  8490. setOptions(this, options);
  8491. },
  8492. onAdd: function () {
  8493. this._initContainer();
  8494. this._levels = {};
  8495. this._tiles = {};
  8496. this._resetView();
  8497. this._update();
  8498. },
  8499. beforeAdd: function (map) {
  8500. map._addZoomLimit(this);
  8501. },
  8502. onRemove: function (map) {
  8503. this._removeAllTiles();
  8504. remove(this._container);
  8505. map._removeZoomLimit(this);
  8506. this._container = null;
  8507. this._tileZoom = null;
  8508. },
  8509. // @method bringToFront: this
  8510. // Brings the tile layer to the top of all tile layers.
  8511. bringToFront: function () {
  8512. if (this._map) {
  8513. toFront(this._container);
  8514. this._setAutoZIndex(Math.max);
  8515. }
  8516. return this;
  8517. },
  8518. // @method bringToBack: this
  8519. // Brings the tile layer to the bottom of all tile layers.
  8520. bringToBack: function () {
  8521. if (this._map) {
  8522. toBack(this._container);
  8523. this._setAutoZIndex(Math.min);
  8524. }
  8525. return this;
  8526. },
  8527. // @method getContainer: HTMLElement
  8528. // Returns the HTML element that contains the tiles for this layer.
  8529. getContainer: function () {
  8530. return this._container;
  8531. },
  8532. // @method setOpacity(opacity: Number): this
  8533. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  8534. setOpacity: function (opacity) {
  8535. this.options.opacity = opacity;
  8536. this._updateOpacity();
  8537. return this;
  8538. },
  8539. // @method setZIndex(zIndex: Number): this
  8540. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  8541. setZIndex: function (zIndex) {
  8542. this.options.zIndex = zIndex;
  8543. this._updateZIndex();
  8544. return this;
  8545. },
  8546. // @method isLoading: Boolean
  8547. // Returns `true` if any tile in the grid layer has not finished loading.
  8548. isLoading: function () {
  8549. return this._loading;
  8550. },
  8551. // @method redraw: this
  8552. // Causes the layer to clear all the tiles and request them again.
  8553. redraw: function () {
  8554. if (this._map) {
  8555. this._removeAllTiles();
  8556. this._update();
  8557. }
  8558. return this;
  8559. },
  8560. getEvents: function () {
  8561. var events = {
  8562. viewprereset: this._invalidateAll,
  8563. viewreset: this._resetView,
  8564. zoom: this._resetView,
  8565. moveend: this._onMoveEnd
  8566. };
  8567. if (!this.options.updateWhenIdle) {
  8568. // update tiles on move, but not more often than once per given interval
  8569. if (!this._onMove) {
  8570. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  8571. }
  8572. events.move = this._onMove;
  8573. }
  8574. if (this._zoomAnimated) {
  8575. events.zoomanim = this._animateZoom;
  8576. }
  8577. return events;
  8578. },
  8579. // @section Extension methods
  8580. // Layers extending `GridLayer` shall reimplement the following method.
  8581. // @method createTile(coords: Object, done?: Function): HTMLElement
  8582. // Called only internally, must be overriden by classes extending `GridLayer`.
  8583. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  8584. // is specified, it must be called when the tile has finished loading and drawing.
  8585. createTile: function () {
  8586. return document.createElement('div');
  8587. },
  8588. // @section
  8589. // @method getTileSize: Point
  8590. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  8591. getTileSize: function () {
  8592. var s = this.options.tileSize;
  8593. return s instanceof Point ? s : new Point(s, s);
  8594. },
  8595. _updateZIndex: function () {
  8596. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  8597. this._container.style.zIndex = this.options.zIndex;
  8598. }
  8599. },
  8600. _setAutoZIndex: function (compare) {
  8601. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  8602. var layers = this.getPane().children,
  8603. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  8604. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  8605. zIndex = layers[i].style.zIndex;
  8606. if (layers[i] !== this._container && zIndex) {
  8607. edgeZIndex = compare(edgeZIndex, +zIndex);
  8608. }
  8609. }
  8610. if (isFinite(edgeZIndex)) {
  8611. this.options.zIndex = edgeZIndex + compare(-1, 1);
  8612. this._updateZIndex();
  8613. }
  8614. },
  8615. _updateOpacity: function () {
  8616. if (!this._map) { return; }
  8617. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  8618. if (ielt9) { return; }
  8619. setOpacity(this._container, this.options.opacity);
  8620. var now = +new Date(),
  8621. nextFrame = false,
  8622. willPrune = false;
  8623. for (var key in this._tiles) {
  8624. var tile = this._tiles[key];
  8625. if (!tile.current || !tile.loaded) { continue; }
  8626. var fade = Math.min(1, (now - tile.loaded) / 200);
  8627. setOpacity(tile.el, fade);
  8628. if (fade < 1) {
  8629. nextFrame = true;
  8630. } else {
  8631. if (tile.active) {
  8632. willPrune = true;
  8633. } else {
  8634. this._onOpaqueTile(tile);
  8635. }
  8636. tile.active = true;
  8637. }
  8638. }
  8639. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  8640. if (nextFrame) {
  8641. cancelAnimFrame(this._fadeFrame);
  8642. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  8643. }
  8644. },
  8645. _onOpaqueTile: falseFn,
  8646. _initContainer: function () {
  8647. if (this._container) { return; }
  8648. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  8649. this._updateZIndex();
  8650. if (this.options.opacity < 1) {
  8651. this._updateOpacity();
  8652. }
  8653. this.getPane().appendChild(this._container);
  8654. },
  8655. _updateLevels: function () {
  8656. var zoom = this._tileZoom,
  8657. maxZoom = this.options.maxZoom;
  8658. if (zoom === undefined) { return undefined; }
  8659. for (var z in this._levels) {
  8660. if (this._levels[z].el.children.length || z === zoom) {
  8661. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  8662. this._onUpdateLevel(z);
  8663. } else {
  8664. remove(this._levels[z].el);
  8665. this._removeTilesAtZoom(z);
  8666. this._onRemoveLevel(z);
  8667. delete this._levels[z];
  8668. }
  8669. }
  8670. var level = this._levels[zoom],
  8671. map = this._map;
  8672. if (!level) {
  8673. level = this._levels[zoom] = {};
  8674. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  8675. level.el.style.zIndex = maxZoom;
  8676. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  8677. level.zoom = zoom;
  8678. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  8679. // force the browser to consider the newly added element for transition
  8680. falseFn(level.el.offsetWidth);
  8681. this._onCreateLevel(level);
  8682. }
  8683. this._level = level;
  8684. return level;
  8685. },
  8686. _onUpdateLevel: falseFn,
  8687. _onRemoveLevel: falseFn,
  8688. _onCreateLevel: falseFn,
  8689. _pruneTiles: function () {
  8690. if (!this._map) {
  8691. return;
  8692. }
  8693. var key, tile;
  8694. var zoom = this._map.getZoom();
  8695. if (zoom > this.options.maxZoom ||
  8696. zoom < this.options.minZoom) {
  8697. this._removeAllTiles();
  8698. return;
  8699. }
  8700. for (key in this._tiles) {
  8701. tile = this._tiles[key];
  8702. tile.retain = tile.current;
  8703. }
  8704. for (key in this._tiles) {
  8705. tile = this._tiles[key];
  8706. if (tile.current && !tile.active) {
  8707. var coords = tile.coords;
  8708. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  8709. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  8710. }
  8711. }
  8712. }
  8713. for (key in this._tiles) {
  8714. if (!this._tiles[key].retain) {
  8715. this._removeTile(key);
  8716. }
  8717. }
  8718. },
  8719. _removeTilesAtZoom: function (zoom) {
  8720. for (var key in this._tiles) {
  8721. if (this._tiles[key].coords.z !== zoom) {
  8722. continue;
  8723. }
  8724. this._removeTile(key);
  8725. }
  8726. },
  8727. _removeAllTiles: function () {
  8728. for (var key in this._tiles) {
  8729. this._removeTile(key);
  8730. }
  8731. },
  8732. _invalidateAll: function () {
  8733. for (var z in this._levels) {
  8734. remove(this._levels[z].el);
  8735. this._onRemoveLevel(z);
  8736. delete this._levels[z];
  8737. }
  8738. this._removeAllTiles();
  8739. this._tileZoom = null;
  8740. },
  8741. _retainParent: function (x, y, z, minZoom) {
  8742. var x2 = Math.floor(x / 2),
  8743. y2 = Math.floor(y / 2),
  8744. z2 = z - 1,
  8745. coords2 = new Point(+x2, +y2);
  8746. coords2.z = +z2;
  8747. var key = this._tileCoordsToKey(coords2),
  8748. tile = this._tiles[key];
  8749. if (tile && tile.active) {
  8750. tile.retain = true;
  8751. return true;
  8752. } else if (tile && tile.loaded) {
  8753. tile.retain = true;
  8754. }
  8755. if (z2 > minZoom) {
  8756. return this._retainParent(x2, y2, z2, minZoom);
  8757. }
  8758. return false;
  8759. },
  8760. _retainChildren: function (x, y, z, maxZoom) {
  8761. for (var i = 2 * x; i < 2 * x + 2; i++) {
  8762. for (var j = 2 * y; j < 2 * y + 2; j++) {
  8763. var coords = new Point(i, j);
  8764. coords.z = z + 1;
  8765. var key = this._tileCoordsToKey(coords),
  8766. tile = this._tiles[key];
  8767. if (tile && tile.active) {
  8768. tile.retain = true;
  8769. continue;
  8770. } else if (tile && tile.loaded) {
  8771. tile.retain = true;
  8772. }
  8773. if (z + 1 < maxZoom) {
  8774. this._retainChildren(i, j, z + 1, maxZoom);
  8775. }
  8776. }
  8777. }
  8778. },
  8779. _resetView: function (e) {
  8780. var animating = e && (e.pinch || e.flyTo);
  8781. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  8782. },
  8783. _animateZoom: function (e) {
  8784. this._setView(e.center, e.zoom, true, e.noUpdate);
  8785. },
  8786. _clampZoom: function (zoom) {
  8787. var options = this.options;
  8788. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  8789. return options.minNativeZoom;
  8790. }
  8791. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  8792. return options.maxNativeZoom;
  8793. }
  8794. return zoom;
  8795. },
  8796. _setView: function (center, zoom, noPrune, noUpdate) {
  8797. var tileZoom = this._clampZoom(Math.round(zoom));
  8798. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  8799. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  8800. tileZoom = undefined;
  8801. }
  8802. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  8803. if (!noUpdate || tileZoomChanged) {
  8804. this._tileZoom = tileZoom;
  8805. if (this._abortLoading) {
  8806. this._abortLoading();
  8807. }
  8808. this._updateLevels();
  8809. this._resetGrid();
  8810. if (tileZoom !== undefined) {
  8811. this._update(center);
  8812. }
  8813. if (!noPrune) {
  8814. this._pruneTiles();
  8815. }
  8816. // Flag to prevent _updateOpacity from pruning tiles during
  8817. // a zoom anim or a pinch gesture
  8818. this._noPrune = !!noPrune;
  8819. }
  8820. this._setZoomTransforms(center, zoom);
  8821. },
  8822. _setZoomTransforms: function (center, zoom) {
  8823. for (var i in this._levels) {
  8824. this._setZoomTransform(this._levels[i], center, zoom);
  8825. }
  8826. },
  8827. _setZoomTransform: function (level, center, zoom) {
  8828. var scale = this._map.getZoomScale(zoom, level.zoom),
  8829. translate = level.origin.multiplyBy(scale)
  8830. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  8831. if (any3d) {
  8832. setTransform(level.el, translate, scale);
  8833. } else {
  8834. setPosition(level.el, translate);
  8835. }
  8836. },
  8837. _resetGrid: function () {
  8838. var map = this._map,
  8839. crs = map.options.crs,
  8840. tileSize = this._tileSize = this.getTileSize(),
  8841. tileZoom = this._tileZoom;
  8842. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  8843. if (bounds) {
  8844. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  8845. }
  8846. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  8847. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  8848. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  8849. ];
  8850. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  8851. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  8852. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  8853. ];
  8854. },
  8855. _onMoveEnd: function () {
  8856. if (!this._map || this._map._animatingZoom) { return; }
  8857. this._update();
  8858. },
  8859. _getTiledPixelBounds: function (center) {
  8860. var map = this._map,
  8861. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  8862. scale = map.getZoomScale(mapZoom, this._tileZoom),
  8863. pixelCenter = map.project(center, this._tileZoom).floor(),
  8864. halfSize = map.getSize().divideBy(scale * 2);
  8865. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  8866. },
  8867. // Private method to load tiles in the grid's active zoom level according to map bounds
  8868. _update: function (center) {
  8869. var map = this._map;
  8870. if (!map) { return; }
  8871. var zoom = this._clampZoom(map.getZoom());
  8872. if (center === undefined) { center = map.getCenter(); }
  8873. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  8874. var pixelBounds = this._getTiledPixelBounds(center),
  8875. tileRange = this._pxBoundsToTileRange(pixelBounds),
  8876. tileCenter = tileRange.getCenter(),
  8877. queue = [],
  8878. margin = this.options.keepBuffer,
  8879. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  8880. tileRange.getTopRight().add([margin, -margin]));
  8881. // Sanity check: panic if the tile range contains Infinity somewhere.
  8882. if (!(isFinite(tileRange.min.x) &&
  8883. isFinite(tileRange.min.y) &&
  8884. isFinite(tileRange.max.x) &&
  8885. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  8886. for (var key in this._tiles) {
  8887. var c = this._tiles[key].coords;
  8888. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  8889. this._tiles[key].current = false;
  8890. }
  8891. }
  8892. // _update just loads more tiles. If the tile zoom level differs too much
  8893. // from the map's, let _setView reset levels and prune old tiles.
  8894. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  8895. // create a queue of coordinates to load tiles from
  8896. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  8897. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  8898. var coords = new Point(i, j);
  8899. coords.z = this._tileZoom;
  8900. if (!this._isValidTile(coords)) { continue; }
  8901. if (!this._tiles[this._tileCoordsToKey(coords)]) {
  8902. queue.push(coords);
  8903. }
  8904. }
  8905. }
  8906. // sort tile queue to load tiles in order of their distance to center
  8907. queue.sort(function (a, b) {
  8908. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  8909. });
  8910. if (queue.length !== 0) {
  8911. // if it's the first batch of tiles to load
  8912. if (!this._loading) {
  8913. this._loading = true;
  8914. // @event loading: Event
  8915. // Fired when the grid layer starts loading tiles.
  8916. this.fire('loading');
  8917. }
  8918. // create DOM fragment to append tiles in one batch
  8919. var fragment = document.createDocumentFragment();
  8920. for (i = 0; i < queue.length; i++) {
  8921. this._addTile(queue[i], fragment);
  8922. }
  8923. this._level.el.appendChild(fragment);
  8924. }
  8925. },
  8926. _isValidTile: function (coords) {
  8927. var crs = this._map.options.crs;
  8928. if (!crs.infinite) {
  8929. // don't load tile if it's out of bounds and not wrapped
  8930. var bounds = this._globalTileRange;
  8931. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  8932. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  8933. }
  8934. if (!this.options.bounds) { return true; }
  8935. // don't load tile if it doesn't intersect the bounds in options
  8936. var tileBounds = this._tileCoordsToBounds(coords);
  8937. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  8938. },
  8939. _keyToBounds: function (key) {
  8940. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  8941. },
  8942. // converts tile coordinates to its geographical bounds
  8943. _tileCoordsToBounds: function (coords) {
  8944. var map = this._map,
  8945. tileSize = this.getTileSize(),
  8946. nwPoint = coords.scaleBy(tileSize),
  8947. sePoint = nwPoint.add(tileSize),
  8948. nw = map.unproject(nwPoint, coords.z),
  8949. se = map.unproject(sePoint, coords.z),
  8950. bounds = new LatLngBounds(nw, se);
  8951. if (!this.options.noWrap) {
  8952. map.wrapLatLngBounds(bounds);
  8953. }
  8954. return bounds;
  8955. },
  8956. // converts tile coordinates to key for the tile cache
  8957. _tileCoordsToKey: function (coords) {
  8958. return coords.x + ':' + coords.y + ':' + coords.z;
  8959. },
  8960. // converts tile cache key to coordinates
  8961. _keyToTileCoords: function (key) {
  8962. var k = key.split(':'),
  8963. coords = new Point(+k[0], +k[1]);
  8964. coords.z = +k[2];
  8965. return coords;
  8966. },
  8967. _removeTile: function (key) {
  8968. var tile = this._tiles[key];
  8969. if (!tile) { return; }
  8970. remove(tile.el);
  8971. delete this._tiles[key];
  8972. // @event tileunload: TileEvent
  8973. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  8974. this.fire('tileunload', {
  8975. tile: tile.el,
  8976. coords: this._keyToTileCoords(key)
  8977. });
  8978. },
  8979. _initTile: function (tile) {
  8980. addClass(tile, 'leaflet-tile');
  8981. var tileSize = this.getTileSize();
  8982. tile.style.width = tileSize.x + 'px';
  8983. tile.style.height = tileSize.y + 'px';
  8984. tile.onselectstart = falseFn;
  8985. tile.onmousemove = falseFn;
  8986. // update opacity on tiles in IE7-8 because of filter inheritance problems
  8987. if (ielt9 && this.options.opacity < 1) {
  8988. setOpacity(tile, this.options.opacity);
  8989. }
  8990. // without this hack, tiles disappear after zoom on Chrome for Android
  8991. // https://github.com/Leaflet/Leaflet/issues/2078
  8992. if (android && !android23) {
  8993. tile.style.WebkitBackfaceVisibility = 'hidden';
  8994. }
  8995. },
  8996. _addTile: function (coords, container) {
  8997. var tilePos = this._getTilePos(coords),
  8998. key = this._tileCoordsToKey(coords);
  8999. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9000. this._initTile(tile);
  9001. // if createTile is defined with a second argument ("done" callback),
  9002. // we know that tile is async and will be ready later; otherwise
  9003. if (this.createTile.length < 2) {
  9004. // mark tile as ready, but delay one frame for opacity animation to happen
  9005. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9006. }
  9007. setPosition(tile, tilePos);
  9008. // save tile in cache
  9009. this._tiles[key] = {
  9010. el: tile,
  9011. coords: coords,
  9012. current: true
  9013. };
  9014. container.appendChild(tile);
  9015. // @event tileloadstart: TileEvent
  9016. // Fired when a tile is requested and starts loading.
  9017. this.fire('tileloadstart', {
  9018. tile: tile,
  9019. coords: coords
  9020. });
  9021. },
  9022. _tileReady: function (coords, err, tile) {
  9023. if (!this._map) { return; }
  9024. if (err) {
  9025. // @event tileerror: TileErrorEvent
  9026. // Fired when there is an error loading a tile.
  9027. this.fire('tileerror', {
  9028. error: err,
  9029. tile: tile,
  9030. coords: coords
  9031. });
  9032. }
  9033. var key = this._tileCoordsToKey(coords);
  9034. tile = this._tiles[key];
  9035. if (!tile) { return; }
  9036. tile.loaded = +new Date();
  9037. if (this._map._fadeAnimated) {
  9038. setOpacity(tile.el, 0);
  9039. cancelAnimFrame(this._fadeFrame);
  9040. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9041. } else {
  9042. tile.active = true;
  9043. this._pruneTiles();
  9044. }
  9045. if (!err) {
  9046. addClass(tile.el, 'leaflet-tile-loaded');
  9047. // @event tileload: TileEvent
  9048. // Fired when a tile loads.
  9049. this.fire('tileload', {
  9050. tile: tile.el,
  9051. coords: coords
  9052. });
  9053. }
  9054. if (this._noTilesToLoad()) {
  9055. this._loading = false;
  9056. // @event load: Event
  9057. // Fired when the grid layer loaded all visible tiles.
  9058. this.fire('load');
  9059. if (ielt9 || !this._map._fadeAnimated) {
  9060. requestAnimFrame(this._pruneTiles, this);
  9061. } else {
  9062. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9063. // to trigger a pruning.
  9064. setTimeout(bind(this._pruneTiles, this), 250);
  9065. }
  9066. }
  9067. },
  9068. _getTilePos: function (coords) {
  9069. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9070. },
  9071. _wrapCoords: function (coords) {
  9072. var newCoords = new Point(
  9073. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9074. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9075. newCoords.z = coords.z;
  9076. return newCoords;
  9077. },
  9078. _pxBoundsToTileRange: function (bounds) {
  9079. var tileSize = this.getTileSize();
  9080. return new Bounds(
  9081. bounds.min.unscaleBy(tileSize).floor(),
  9082. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9083. },
  9084. _noTilesToLoad: function () {
  9085. for (var key in this._tiles) {
  9086. if (!this._tiles[key].loaded) { return false; }
  9087. }
  9088. return true;
  9089. }
  9090. });
  9091. // @factory L.gridLayer(options?: GridLayer options)
  9092. // Creates a new instance of GridLayer with the supplied options.
  9093. function gridLayer(options) {
  9094. return new GridLayer(options);
  9095. }
  9096. /*
  9097. * @class TileLayer
  9098. * @inherits GridLayer
  9099. * @aka L.TileLayer
  9100. * Used to load and display tile layers on the map. Extends `GridLayer`.
  9101. *
  9102. * @example
  9103. *
  9104. * ```js
  9105. * L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map);
  9106. * ```
  9107. *
  9108. * @section URL template
  9109. * @example
  9110. *
  9111. * A string of the following form:
  9112. *
  9113. * ```
  9114. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9115. * ```
  9116. *
  9117. * `{s}` means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; `a`, `b` or `c` by default, can be omitted), `{z}` — zoom level, `{x}` and `{y}` — tile coordinates. `{r}` can be used to add "&commat;2x" to the URL to load retina tiles.
  9118. *
  9119. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9120. *
  9121. * ```
  9122. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9123. * ```
  9124. */
  9125. var TileLayer = GridLayer.extend({
  9126. // @section
  9127. // @aka TileLayer options
  9128. options: {
  9129. // @option minZoom: Number = 0
  9130. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9131. minZoom: 0,
  9132. // @option maxZoom: Number = 18
  9133. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9134. maxZoom: 18,
  9135. // @option subdomains: String|String[] = 'abc'
  9136. // Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.
  9137. subdomains: 'abc',
  9138. // @option errorTileUrl: String = ''
  9139. // URL to the tile image to show in place of the tile that failed to load.
  9140. errorTileUrl: '',
  9141. // @option zoomOffset: Number = 0
  9142. // The zoom number used in tile URLs will be offset with this value.
  9143. zoomOffset: 0,
  9144. // @option tms: Boolean = false
  9145. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9146. tms: false,
  9147. // @option zoomReverse: Boolean = false
  9148. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9149. zoomReverse: false,
  9150. // @option detectRetina: Boolean = false
  9151. // If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.
  9152. detectRetina: false,
  9153. // @option crossOrigin: Boolean = false
  9154. // If true, all tiles will have their crossOrigin attribute set to ''. This is needed if you want to access tile pixel data.
  9155. crossOrigin: false
  9156. },
  9157. initialize: function (url, options) {
  9158. this._url = url;
  9159. options = setOptions(this, options);
  9160. // detecting retina displays, adjusting tileSize and zoom levels
  9161. if (options.detectRetina && retina && options.maxZoom > 0) {
  9162. options.tileSize = Math.floor(options.tileSize / 2);
  9163. if (!options.zoomReverse) {
  9164. options.zoomOffset++;
  9165. options.maxZoom--;
  9166. } else {
  9167. options.zoomOffset--;
  9168. options.minZoom++;
  9169. }
  9170. options.minZoom = Math.max(0, options.minZoom);
  9171. }
  9172. if (typeof options.subdomains === 'string') {
  9173. options.subdomains = options.subdomains.split('');
  9174. }
  9175. // for https://github.com/Leaflet/Leaflet/issues/137
  9176. if (!android) {
  9177. this.on('tileunload', this._onTileRemove);
  9178. }
  9179. },
  9180. // @method setUrl(url: String, noRedraw?: Boolean): this
  9181. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9182. setUrl: function (url, noRedraw) {
  9183. this._url = url;
  9184. if (!noRedraw) {
  9185. this.redraw();
  9186. }
  9187. return this;
  9188. },
  9189. // @method createTile(coords: Object, done?: Function): HTMLElement
  9190. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9191. // to return an `<img>` HTML element with the appropiate image URL given `coords`. The `done`
  9192. // callback is called when the tile has been loaded.
  9193. createTile: function (coords, done) {
  9194. var tile = document.createElement('img');
  9195. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9196. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9197. if (this.options.crossOrigin) {
  9198. tile.crossOrigin = '';
  9199. }
  9200. /*
  9201. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  9202. http://www.w3.org/TR/WCAG20-TECHS/H67
  9203. */
  9204. tile.alt = '';
  9205. /*
  9206. Set role="presentation" to force screen readers to ignore this
  9207. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  9208. */
  9209. tile.setAttribute('role', 'presentation');
  9210. tile.src = this.getTileUrl(coords);
  9211. return tile;
  9212. },
  9213. // @section Extension methods
  9214. // @uninheritable
  9215. // Layers extending `TileLayer` might reimplement the following method.
  9216. // @method getTileUrl(coords: Object): String
  9217. // Called only internally, returns the URL for a tile given its coordinates.
  9218. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9219. getTileUrl: function (coords) {
  9220. var data = {
  9221. r: retina ? '@2x' : '',
  9222. s: this._getSubdomain(coords),
  9223. x: coords.x,
  9224. y: coords.y,
  9225. z: this._getZoomForUrl()
  9226. };
  9227. if (this._map && !this._map.options.crs.infinite) {
  9228. var invertedY = this._globalTileRange.max.y - coords.y;
  9229. if (this.options.tms) {
  9230. data['y'] = invertedY;
  9231. }
  9232. data['-y'] = invertedY;
  9233. }
  9234. return template(this._url, extend(data, this.options));
  9235. },
  9236. _tileOnLoad: function (done, tile) {
  9237. // For https://github.com/Leaflet/Leaflet/issues/3332
  9238. if (ielt9) {
  9239. setTimeout(bind(done, this, null, tile), 0);
  9240. } else {
  9241. done(null, tile);
  9242. }
  9243. },
  9244. _tileOnError: function (done, tile, e) {
  9245. var errorUrl = this.options.errorTileUrl;
  9246. if (errorUrl && tile.src !== errorUrl) {
  9247. tile.src = errorUrl;
  9248. }
  9249. done(e, tile);
  9250. },
  9251. _onTileRemove: function (e) {
  9252. e.tile.onload = null;
  9253. },
  9254. _getZoomForUrl: function () {
  9255. var zoom = this._tileZoom,
  9256. maxZoom = this.options.maxZoom,
  9257. zoomReverse = this.options.zoomReverse,
  9258. zoomOffset = this.options.zoomOffset;
  9259. if (zoomReverse) {
  9260. zoom = maxZoom - zoom;
  9261. }
  9262. return zoom + zoomOffset;
  9263. },
  9264. _getSubdomain: function (tilePoint) {
  9265. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  9266. return this.options.subdomains[index];
  9267. },
  9268. // stops loading all tiles in the background layer
  9269. _abortLoading: function () {
  9270. var i, tile;
  9271. for (i in this._tiles) {
  9272. if (this._tiles[i].coords.z !== this._tileZoom) {
  9273. tile = this._tiles[i].el;
  9274. tile.onload = falseFn;
  9275. tile.onerror = falseFn;
  9276. if (!tile.complete) {
  9277. tile.src = emptyImageUrl;
  9278. remove(tile);
  9279. }
  9280. }
  9281. }
  9282. }
  9283. });
  9284. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  9285. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  9286. function tileLayer(url, options) {
  9287. return new TileLayer(url, options);
  9288. }
  9289. /*
  9290. * @class TileLayer.WMS
  9291. * @inherits TileLayer
  9292. * @aka L.TileLayer.WMS
  9293. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  9294. *
  9295. * @example
  9296. *
  9297. * ```js
  9298. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  9299. * layers: 'nexrad-n0r-900913',
  9300. * format: 'image/png',
  9301. * transparent: true,
  9302. * attribution: "Weather data © 2012 IEM Nexrad"
  9303. * });
  9304. * ```
  9305. */
  9306. var TileLayerWMS = TileLayer.extend({
  9307. // @section
  9308. // @aka TileLayer.WMS options
  9309. // If any custom options not documented here are used, they will be sent to the
  9310. // WMS server as extra parameters in each request URL. This can be useful for
  9311. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  9312. defaultWmsParams: {
  9313. service: 'WMS',
  9314. request: 'GetMap',
  9315. // @option layers: String = ''
  9316. // **(required)** Comma-separated list of WMS layers to show.
  9317. layers: '',
  9318. // @option styles: String = ''
  9319. // Comma-separated list of WMS styles.
  9320. styles: '',
  9321. // @option format: String = 'image/jpeg'
  9322. // WMS image format (use `'image/png'` for layers with transparency).
  9323. format: 'image/jpeg',
  9324. // @option transparent: Boolean = false
  9325. // If `true`, the WMS service will return images with transparency.
  9326. transparent: false,
  9327. // @option version: String = '1.1.1'
  9328. // Version of the WMS service to use
  9329. version: '1.1.1'
  9330. },
  9331. options: {
  9332. // @option crs: CRS = null
  9333. // Coordinate Reference System to use for the WMS requests, defaults to
  9334. // map CRS. Don't change this if you're not sure what it means.
  9335. crs: null,
  9336. // @option uppercase: Boolean = false
  9337. // If `true`, WMS request parameter keys will be uppercase.
  9338. uppercase: false
  9339. },
  9340. initialize: function (url, options) {
  9341. this._url = url;
  9342. var wmsParams = extend({}, this.defaultWmsParams);
  9343. // all keys that are not TileLayer options go to WMS params
  9344. for (var i in options) {
  9345. if (!(i in this.options)) {
  9346. wmsParams[i] = options[i];
  9347. }
  9348. }
  9349. options = setOptions(this, options);
  9350. wmsParams.width = wmsParams.height = options.tileSize * (options.detectRetina && retina ? 2 : 1);
  9351. this.wmsParams = wmsParams;
  9352. },
  9353. onAdd: function (map) {
  9354. this._crs = this.options.crs || map.options.crs;
  9355. this._wmsVersion = parseFloat(this.wmsParams.version);
  9356. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  9357. this.wmsParams[projectionKey] = this._crs.code;
  9358. TileLayer.prototype.onAdd.call(this, map);
  9359. },
  9360. getTileUrl: function (coords) {
  9361. var tileBounds = this._tileCoordsToBounds(coords),
  9362. nw = this._crs.project(tileBounds.getNorthWest()),
  9363. se = this._crs.project(tileBounds.getSouthEast()),
  9364. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  9365. [se.y, nw.x, nw.y, se.x] :
  9366. [nw.x, se.y, se.x, nw.y]).join(','),
  9367. url = TileLayer.prototype.getTileUrl.call(this, coords);
  9368. return url +
  9369. getParamString(this.wmsParams, url, this.options.uppercase) +
  9370. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  9371. },
  9372. // @method setParams(params: Object, noRedraw?: Boolean): this
  9373. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  9374. setParams: function (params, noRedraw) {
  9375. extend(this.wmsParams, params);
  9376. if (!noRedraw) {
  9377. this.redraw();
  9378. }
  9379. return this;
  9380. }
  9381. });
  9382. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  9383. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  9384. function tileLayerWMS(url, options) {
  9385. return new TileLayerWMS(url, options);
  9386. }
  9387. TileLayer.WMS = TileLayerWMS;
  9388. tileLayer.wms = tileLayerWMS;
  9389. /*
  9390. * @class Renderer
  9391. * @inherits Layer
  9392. * @aka L.Renderer
  9393. *
  9394. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  9395. * DOM container of the renderer, its bounds, and its zoom animation.
  9396. *
  9397. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  9398. * itself can be added or removed to the map. All paths use a renderer, which can
  9399. * be implicit (the map will decide the type of renderer and use it automatically)
  9400. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  9401. *
  9402. * Do not use this class directly, use `SVG` and `Canvas` instead.
  9403. *
  9404. * @event update: Event
  9405. * Fired when the renderer updates its bounds, center and zoom, for example when
  9406. * its map has moved
  9407. */
  9408. var Renderer = Layer.extend({
  9409. // @section
  9410. // @aka Renderer options
  9411. options: {
  9412. // @option padding: Number = 0.1
  9413. // How much to extend the clip area around the map view (relative to its size)
  9414. // e.g. 0.1 would be 10% of map view in each direction
  9415. padding: 0.1
  9416. },
  9417. initialize: function (options) {
  9418. setOptions(this, options);
  9419. stamp(this);
  9420. this._layers = this._layers || {};
  9421. },
  9422. onAdd: function () {
  9423. if (!this._container) {
  9424. this._initContainer(); // defined by renderer implementations
  9425. if (this._zoomAnimated) {
  9426. addClass(this._container, 'leaflet-zoom-animated');
  9427. }
  9428. }
  9429. this.getPane().appendChild(this._container);
  9430. this._update();
  9431. this.on('update', this._updatePaths, this);
  9432. },
  9433. onRemove: function () {
  9434. this.off('update', this._updatePaths, this);
  9435. this._destroyContainer();
  9436. },
  9437. getEvents: function () {
  9438. var events = {
  9439. viewreset: this._reset,
  9440. zoom: this._onZoom,
  9441. moveend: this._update,
  9442. zoomend: this._onZoomEnd
  9443. };
  9444. if (this._zoomAnimated) {
  9445. events.zoomanim = this._onAnimZoom;
  9446. }
  9447. return events;
  9448. },
  9449. _onAnimZoom: function (ev) {
  9450. this._updateTransform(ev.center, ev.zoom);
  9451. },
  9452. _onZoom: function () {
  9453. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  9454. },
  9455. _updateTransform: function (center, zoom) {
  9456. var scale = this._map.getZoomScale(zoom, this._zoom),
  9457. position = getPosition(this._container),
  9458. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  9459. currentCenterPoint = this._map.project(this._center, zoom),
  9460. destCenterPoint = this._map.project(center, zoom),
  9461. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  9462. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  9463. if (any3d) {
  9464. setTransform(this._container, topLeftOffset, scale);
  9465. } else {
  9466. setPosition(this._container, topLeftOffset);
  9467. }
  9468. },
  9469. _reset: function () {
  9470. this._update();
  9471. this._updateTransform(this._center, this._zoom);
  9472. for (var id in this._layers) {
  9473. this._layers[id]._reset();
  9474. }
  9475. },
  9476. _onZoomEnd: function () {
  9477. for (var id in this._layers) {
  9478. this._layers[id]._project();
  9479. }
  9480. },
  9481. _updatePaths: function () {
  9482. for (var id in this._layers) {
  9483. this._layers[id]._update();
  9484. }
  9485. },
  9486. _update: function () {
  9487. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  9488. // Subclasses are responsible of firing the 'update' event.
  9489. var p = this.options.padding,
  9490. size = this._map.getSize(),
  9491. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  9492. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  9493. this._center = this._map.getCenter();
  9494. this._zoom = this._map.getZoom();
  9495. }
  9496. });
  9497. /*
  9498. * @class Canvas
  9499. * @inherits Renderer
  9500. * @aka L.Canvas
  9501. *
  9502. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  9503. * Inherits `Renderer`.
  9504. *
  9505. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  9506. * available in all web browsers, notably IE8, and overlapping geometries might
  9507. * not display properly in some edge cases.
  9508. *
  9509. * @example
  9510. *
  9511. * Use Canvas by default for all paths in the map:
  9512. *
  9513. * ```js
  9514. * var map = L.map('map', {
  9515. * renderer: L.canvas()
  9516. * });
  9517. * ```
  9518. *
  9519. * Use a Canvas renderer with extra padding for specific vector geometries:
  9520. *
  9521. * ```js
  9522. * var map = L.map('map');
  9523. * var myRenderer = L.canvas({ padding: 0.5 });
  9524. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  9525. * var circle = L.circle( center, { renderer: myRenderer } );
  9526. * ```
  9527. */
  9528. var Canvas = Renderer.extend({
  9529. getEvents: function () {
  9530. var events = Renderer.prototype.getEvents.call(this);
  9531. events.viewprereset = this._onViewPreReset;
  9532. return events;
  9533. },
  9534. _onViewPreReset: function () {
  9535. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  9536. this._postponeUpdatePaths = true;
  9537. },
  9538. onAdd: function () {
  9539. Renderer.prototype.onAdd.call(this);
  9540. // Redraw vectors since canvas is cleared upon removal,
  9541. // in case of removing the renderer itself from the map.
  9542. this._draw();
  9543. },
  9544. _initContainer: function () {
  9545. var container = this._container = document.createElement('canvas');
  9546. on(container, 'mousemove', throttle(this._onMouseMove, 32, this), this);
  9547. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  9548. on(container, 'mouseout', this._handleMouseOut, this);
  9549. this._ctx = container.getContext('2d');
  9550. },
  9551. _destroyContainer: function () {
  9552. delete this._ctx;
  9553. remove(this._container);
  9554. off(this._container);
  9555. delete this._container;
  9556. },
  9557. _updatePaths: function () {
  9558. if (this._postponeUpdatePaths) { return; }
  9559. var layer;
  9560. this._redrawBounds = null;
  9561. for (var id in this._layers) {
  9562. layer = this._layers[id];
  9563. layer._update();
  9564. }
  9565. this._redraw();
  9566. },
  9567. _update: function () {
  9568. if (this._map._animatingZoom && this._bounds) { return; }
  9569. this._drawnLayers = {};
  9570. Renderer.prototype._update.call(this);
  9571. var b = this._bounds,
  9572. container = this._container,
  9573. size = b.getSize(),
  9574. m = retina ? 2 : 1;
  9575. setPosition(container, b.min);
  9576. // set canvas size (also clearing it); use double size on retina
  9577. container.width = m * size.x;
  9578. container.height = m * size.y;
  9579. container.style.width = size.x + 'px';
  9580. container.style.height = size.y + 'px';
  9581. if (retina) {
  9582. this._ctx.scale(2, 2);
  9583. }
  9584. // translate so we use the same path coordinates after canvas element moves
  9585. this._ctx.translate(-b.min.x, -b.min.y);
  9586. // Tell paths to redraw themselves
  9587. this.fire('update');
  9588. },
  9589. _reset: function () {
  9590. Renderer.prototype._reset.call(this);
  9591. if (this._postponeUpdatePaths) {
  9592. this._postponeUpdatePaths = false;
  9593. this._updatePaths();
  9594. }
  9595. },
  9596. _initPath: function (layer) {
  9597. this._updateDashArray(layer);
  9598. this._layers[stamp(layer)] = layer;
  9599. var order = layer._order = {
  9600. layer: layer,
  9601. prev: this._drawLast,
  9602. next: null
  9603. };
  9604. if (this._drawLast) { this._drawLast.next = order; }
  9605. this._drawLast = order;
  9606. this._drawFirst = this._drawFirst || this._drawLast;
  9607. },
  9608. _addPath: function (layer) {
  9609. this._requestRedraw(layer);
  9610. },
  9611. _removePath: function (layer) {
  9612. var order = layer._order;
  9613. var next = order.next;
  9614. var prev = order.prev;
  9615. if (next) {
  9616. next.prev = prev;
  9617. } else {
  9618. this._drawLast = prev;
  9619. }
  9620. if (prev) {
  9621. prev.next = next;
  9622. } else {
  9623. this._drawFirst = next;
  9624. }
  9625. delete layer._order;
  9626. delete this._layers[L.stamp(layer)];
  9627. this._requestRedraw(layer);
  9628. },
  9629. _updatePath: function (layer) {
  9630. // Redraw the union of the layer's old pixel
  9631. // bounds and the new pixel bounds.
  9632. this._extendRedrawBounds(layer);
  9633. layer._project();
  9634. layer._update();
  9635. // The redraw will extend the redraw bounds
  9636. // with the new pixel bounds.
  9637. this._requestRedraw(layer);
  9638. },
  9639. _updateStyle: function (layer) {
  9640. this._updateDashArray(layer);
  9641. this._requestRedraw(layer);
  9642. },
  9643. _updateDashArray: function (layer) {
  9644. if (layer.options.dashArray) {
  9645. var parts = layer.options.dashArray.split(','),
  9646. dashArray = [],
  9647. i;
  9648. for (i = 0; i < parts.length; i++) {
  9649. dashArray.push(Number(parts[i]));
  9650. }
  9651. layer.options._dashArray = dashArray;
  9652. }
  9653. },
  9654. _requestRedraw: function (layer) {
  9655. if (!this._map) { return; }
  9656. this._extendRedrawBounds(layer);
  9657. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  9658. },
  9659. _extendRedrawBounds: function (layer) {
  9660. if (layer._pxBounds) {
  9661. var padding = (layer.options.weight || 0) + 1;
  9662. this._redrawBounds = this._redrawBounds || new Bounds();
  9663. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  9664. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  9665. }
  9666. },
  9667. _redraw: function () {
  9668. this._redrawRequest = null;
  9669. if (this._redrawBounds) {
  9670. this._redrawBounds.min._floor();
  9671. this._redrawBounds.max._ceil();
  9672. }
  9673. this._clear(); // clear layers in redraw bounds
  9674. this._draw(); // draw layers
  9675. this._redrawBounds = null;
  9676. },
  9677. _clear: function () {
  9678. var bounds = this._redrawBounds;
  9679. if (bounds) {
  9680. var size = bounds.getSize();
  9681. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  9682. } else {
  9683. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  9684. }
  9685. },
  9686. _draw: function () {
  9687. var layer, bounds = this._redrawBounds;
  9688. this._ctx.save();
  9689. if (bounds) {
  9690. var size = bounds.getSize();
  9691. this._ctx.beginPath();
  9692. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  9693. this._ctx.clip();
  9694. }
  9695. this._drawing = true;
  9696. for (var order = this._drawFirst; order; order = order.next) {
  9697. layer = order.layer;
  9698. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  9699. layer._updatePath();
  9700. }
  9701. }
  9702. this._drawing = false;
  9703. this._ctx.restore(); // Restore state before clipping.
  9704. },
  9705. _updatePoly: function (layer, closed) {
  9706. if (!this._drawing) { return; }
  9707. var i, j, len2, p,
  9708. parts = layer._parts,
  9709. len = parts.length,
  9710. ctx = this._ctx;
  9711. if (!len) { return; }
  9712. this._drawnLayers[layer._leaflet_id] = layer;
  9713. ctx.beginPath();
  9714. for (i = 0; i < len; i++) {
  9715. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  9716. p = parts[i][j];
  9717. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  9718. }
  9719. if (closed) {
  9720. ctx.closePath();
  9721. }
  9722. }
  9723. this._fillStroke(ctx, layer);
  9724. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  9725. },
  9726. _updateCircle: function (layer) {
  9727. if (!this._drawing || layer._empty()) { return; }
  9728. var p = layer._point,
  9729. ctx = this._ctx,
  9730. r = layer._radius,
  9731. s = (layer._radiusY || r) / r;
  9732. this._drawnLayers[layer._leaflet_id] = layer;
  9733. if (s !== 1) {
  9734. ctx.save();
  9735. ctx.scale(1, s);
  9736. }
  9737. ctx.beginPath();
  9738. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  9739. if (s !== 1) {
  9740. ctx.restore();
  9741. }
  9742. this._fillStroke(ctx, layer);
  9743. },
  9744. _fillStroke: function (ctx, layer) {
  9745. var options = layer.options;
  9746. if (options.fill) {
  9747. ctx.globalAlpha = options.fillOpacity;
  9748. ctx.fillStyle = options.fillColor || options.color;
  9749. ctx.fill(options.fillRule || 'evenodd');
  9750. }
  9751. if (options.stroke && options.weight !== 0) {
  9752. if (ctx.setLineDash) {
  9753. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  9754. }
  9755. ctx.globalAlpha = options.opacity;
  9756. ctx.lineWidth = options.weight;
  9757. ctx.strokeStyle = options.color;
  9758. ctx.lineCap = options.lineCap;
  9759. ctx.lineJoin = options.lineJoin;
  9760. ctx.stroke();
  9761. }
  9762. },
  9763. // Canvas obviously doesn't have mouse events for individual drawn objects,
  9764. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  9765. _onClick: function (e) {
  9766. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  9767. for (var order = this._drawFirst; order; order = order.next) {
  9768. layer = order.layer;
  9769. if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
  9770. clickedLayer = layer;
  9771. }
  9772. }
  9773. if (clickedLayer) {
  9774. fakeStop(e);
  9775. this._fireEvent([clickedLayer], e);
  9776. }
  9777. },
  9778. _onMouseMove: function (e) {
  9779. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  9780. var point = this._map.mouseEventToLayerPoint(e);
  9781. this._handleMouseHover(e, point);
  9782. },
  9783. _handleMouseOut: function (e) {
  9784. var layer = this._hoveredLayer;
  9785. if (layer) {
  9786. // if we're leaving the layer, fire mouseout
  9787. removeClass(this._container, 'leaflet-interactive');
  9788. this._fireEvent([layer], e, 'mouseout');
  9789. this._hoveredLayer = null;
  9790. }
  9791. },
  9792. _handleMouseHover: function (e, point) {
  9793. var layer, candidateHoveredLayer;
  9794. for (var order = this._drawFirst; order; order = order.next) {
  9795. layer = order.layer;
  9796. if (layer.options.interactive && layer._containsPoint(point)) {
  9797. candidateHoveredLayer = layer;
  9798. }
  9799. }
  9800. if (candidateHoveredLayer !== this._hoveredLayer) {
  9801. this._handleMouseOut(e);
  9802. if (candidateHoveredLayer) {
  9803. addClass(this._container, 'leaflet-interactive'); // change cursor
  9804. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  9805. this._hoveredLayer = candidateHoveredLayer;
  9806. }
  9807. }
  9808. if (this._hoveredLayer) {
  9809. this._fireEvent([this._hoveredLayer], e);
  9810. }
  9811. },
  9812. _fireEvent: function (layers, e, type) {
  9813. this._map._fireDOMEvent(e, type || e.type, layers);
  9814. },
  9815. _bringToFront: function (layer) {
  9816. var order = layer._order;
  9817. var next = order.next;
  9818. var prev = order.prev;
  9819. if (next) {
  9820. next.prev = prev;
  9821. } else {
  9822. // Already last
  9823. return;
  9824. }
  9825. if (prev) {
  9826. prev.next = next;
  9827. } else if (next) {
  9828. // Update first entry unless this is the
  9829. // signle entry
  9830. this._drawFirst = next;
  9831. }
  9832. order.prev = this._drawLast;
  9833. this._drawLast.next = order;
  9834. order.next = null;
  9835. this._drawLast = order;
  9836. this._requestRedraw(layer);
  9837. },
  9838. _bringToBack: function (layer) {
  9839. var order = layer._order;
  9840. var next = order.next;
  9841. var prev = order.prev;
  9842. if (prev) {
  9843. prev.next = next;
  9844. } else {
  9845. // Already first
  9846. return;
  9847. }
  9848. if (next) {
  9849. next.prev = prev;
  9850. } else if (prev) {
  9851. // Update last entry unless this is the
  9852. // signle entry
  9853. this._drawLast = prev;
  9854. }
  9855. order.prev = null;
  9856. order.next = this._drawFirst;
  9857. this._drawFirst.prev = order;
  9858. this._drawFirst = order;
  9859. this._requestRedraw(layer);
  9860. }
  9861. });
  9862. // @factory L.canvas(options?: Renderer options)
  9863. // Creates a Canvas renderer with the given options.
  9864. function canvas$1(options) {
  9865. return canvas ? new Canvas(options) : null;
  9866. }
  9867. /*
  9868. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  9869. */
  9870. var vmlCreate = (function () {
  9871. try {
  9872. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  9873. return function (name) {
  9874. return document.createElement('<lvml:' + name + ' class="lvml">');
  9875. };
  9876. } catch (e) {
  9877. return function (name) {
  9878. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  9879. };
  9880. }
  9881. })();
  9882. /*
  9883. * @class SVG
  9884. *
  9885. * Although SVG is not available on IE7 and IE8, these browsers support [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language), and the SVG renderer will fall back to VML in this case.
  9886. *
  9887. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  9888. * with old versions of Internet Explorer.
  9889. */
  9890. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  9891. var vmlMixin = {
  9892. _initContainer: function () {
  9893. this._container = create$1('div', 'leaflet-vml-container');
  9894. },
  9895. _update: function () {
  9896. if (this._map._animatingZoom) { return; }
  9897. Renderer.prototype._update.call(this);
  9898. this.fire('update');
  9899. },
  9900. _initPath: function (layer) {
  9901. var container = layer._container = vmlCreate('shape');
  9902. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  9903. container.coordsize = '1 1';
  9904. layer._path = vmlCreate('path');
  9905. container.appendChild(layer._path);
  9906. this._updateStyle(layer);
  9907. this._layers[stamp(layer)] = layer;
  9908. },
  9909. _addPath: function (layer) {
  9910. var container = layer._container;
  9911. this._container.appendChild(container);
  9912. if (layer.options.interactive) {
  9913. layer.addInteractiveTarget(container);
  9914. }
  9915. },
  9916. _removePath: function (layer) {
  9917. var container = layer._container;
  9918. remove(container);
  9919. layer.removeInteractiveTarget(container);
  9920. delete this._layers[stamp(layer)];
  9921. },
  9922. _updateStyle: function (layer) {
  9923. var stroke = layer._stroke,
  9924. fill = layer._fill,
  9925. options = layer.options,
  9926. container = layer._container;
  9927. container.stroked = !!options.stroke;
  9928. container.filled = !!options.fill;
  9929. if (options.stroke) {
  9930. if (!stroke) {
  9931. stroke = layer._stroke = vmlCreate('stroke');
  9932. }
  9933. container.appendChild(stroke);
  9934. stroke.weight = options.weight + 'px';
  9935. stroke.color = options.color;
  9936. stroke.opacity = options.opacity;
  9937. if (options.dashArray) {
  9938. stroke.dashStyle = isArray(options.dashArray) ?
  9939. options.dashArray.join(' ') :
  9940. options.dashArray.replace(/( *, *)/g, ' ');
  9941. } else {
  9942. stroke.dashStyle = '';
  9943. }
  9944. stroke.endcap = options.lineCap.replace('butt', 'flat');
  9945. stroke.joinstyle = options.lineJoin;
  9946. } else if (stroke) {
  9947. container.removeChild(stroke);
  9948. layer._stroke = null;
  9949. }
  9950. if (options.fill) {
  9951. if (!fill) {
  9952. fill = layer._fill = vmlCreate('fill');
  9953. }
  9954. container.appendChild(fill);
  9955. fill.color = options.fillColor || options.color;
  9956. fill.opacity = options.fillOpacity;
  9957. } else if (fill) {
  9958. container.removeChild(fill);
  9959. layer._fill = null;
  9960. }
  9961. },
  9962. _updateCircle: function (layer) {
  9963. var p = layer._point.round(),
  9964. r = Math.round(layer._radius),
  9965. r2 = Math.round(layer._radiusY || r);
  9966. this._setPath(layer, layer._empty() ? 'M0 0' :
  9967. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  9968. },
  9969. _setPath: function (layer, path) {
  9970. layer._path.v = path;
  9971. },
  9972. _bringToFront: function (layer) {
  9973. toFront(layer._container);
  9974. },
  9975. _bringToBack: function (layer) {
  9976. toBack(layer._container);
  9977. }
  9978. };
  9979. var create$2 = vml ? vmlCreate : svgCreate;
  9980. /*
  9981. * @class SVG
  9982. * @inherits Renderer
  9983. * @aka L.SVG
  9984. *
  9985. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  9986. * Inherits `Renderer`.
  9987. *
  9988. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  9989. * available in all web browsers, notably Android 2.x and 3.x.
  9990. *
  9991. * Although SVG is not available on IE7 and IE8, these browsers support
  9992. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  9993. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  9994. * this case.
  9995. *
  9996. * @example
  9997. *
  9998. * Use SVG by default for all paths in the map:
  9999. *
  10000. * ```js
  10001. * var map = L.map('map', {
  10002. * renderer: L.svg()
  10003. * });
  10004. * ```
  10005. *
  10006. * Use a SVG renderer with extra padding for specific vector geometries:
  10007. *
  10008. * ```js
  10009. * var map = L.map('map');
  10010. * var myRenderer = L.svg({ padding: 0.5 });
  10011. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10012. * var circle = L.circle( center, { renderer: myRenderer } );
  10013. * ```
  10014. */
  10015. var SVG = Renderer.extend({
  10016. getEvents: function () {
  10017. var events = Renderer.prototype.getEvents.call(this);
  10018. events.zoomstart = this._onZoomStart;
  10019. return events;
  10020. },
  10021. _initContainer: function () {
  10022. this._container = create$2('svg');
  10023. // makes it possible to click through svg root; we'll reset it back in individual paths
  10024. this._container.setAttribute('pointer-events', 'none');
  10025. this._rootGroup = create$2('g');
  10026. this._container.appendChild(this._rootGroup);
  10027. },
  10028. _destroyContainer: function () {
  10029. remove(this._container);
  10030. off(this._container);
  10031. delete this._container;
  10032. delete this._rootGroup;
  10033. },
  10034. _onZoomStart: function () {
  10035. // Drag-then-pinch interactions might mess up the center and zoom.
  10036. // In this case, the easiest way to prevent this is re-do the renderer
  10037. // bounds and padding when the zooming starts.
  10038. this._update();
  10039. },
  10040. _update: function () {
  10041. if (this._map._animatingZoom && this._bounds) { return; }
  10042. Renderer.prototype._update.call(this);
  10043. var b = this._bounds,
  10044. size = b.getSize(),
  10045. container = this._container;
  10046. // set size of svg-container if changed
  10047. if (!this._svgSize || !this._svgSize.equals(size)) {
  10048. this._svgSize = size;
  10049. container.setAttribute('width', size.x);
  10050. container.setAttribute('height', size.y);
  10051. }
  10052. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10053. setPosition(container, b.min);
  10054. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10055. this.fire('update');
  10056. },
  10057. // methods below are called by vector layers implementations
  10058. _initPath: function (layer) {
  10059. var path = layer._path = create$2('path');
  10060. // @namespace Path
  10061. // @option className: String = null
  10062. // Custom class name set on an element. Only for SVG renderer.
  10063. if (layer.options.className) {
  10064. addClass(path, layer.options.className);
  10065. }
  10066. if (layer.options.interactive) {
  10067. addClass(path, 'leaflet-interactive');
  10068. }
  10069. this._updateStyle(layer);
  10070. this._layers[stamp(layer)] = layer;
  10071. },
  10072. _addPath: function (layer) {
  10073. if (!this._rootGroup) { this._initContainer(); }
  10074. this._rootGroup.appendChild(layer._path);
  10075. layer.addInteractiveTarget(layer._path);
  10076. },
  10077. _removePath: function (layer) {
  10078. remove(layer._path);
  10079. layer.removeInteractiveTarget(layer._path);
  10080. delete this._layers[stamp(layer)];
  10081. },
  10082. _updatePath: function (layer) {
  10083. layer._project();
  10084. layer._update();
  10085. },
  10086. _updateStyle: function (layer) {
  10087. var path = layer._path,
  10088. options = layer.options;
  10089. if (!path) { return; }
  10090. if (options.stroke) {
  10091. path.setAttribute('stroke', options.color);
  10092. path.setAttribute('stroke-opacity', options.opacity);
  10093. path.setAttribute('stroke-width', options.weight);
  10094. path.setAttribute('stroke-linecap', options.lineCap);
  10095. path.setAttribute('stroke-linejoin', options.lineJoin);
  10096. if (options.dashArray) {
  10097. path.setAttribute('stroke-dasharray', options.dashArray);
  10098. } else {
  10099. path.removeAttribute('stroke-dasharray');
  10100. }
  10101. if (options.dashOffset) {
  10102. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10103. } else {
  10104. path.removeAttribute('stroke-dashoffset');
  10105. }
  10106. } else {
  10107. path.setAttribute('stroke', 'none');
  10108. }
  10109. if (options.fill) {
  10110. path.setAttribute('fill', options.fillColor || options.color);
  10111. path.setAttribute('fill-opacity', options.fillOpacity);
  10112. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10113. } else {
  10114. path.setAttribute('fill', 'none');
  10115. }
  10116. },
  10117. _updatePoly: function (layer, closed) {
  10118. this._setPath(layer, pointsToPath(layer._parts, closed));
  10119. },
  10120. _updateCircle: function (layer) {
  10121. var p = layer._point,
  10122. r = layer._radius,
  10123. r2 = layer._radiusY || r,
  10124. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10125. // drawing a circle with two half-arcs
  10126. var d = layer._empty() ? 'M0 0' :
  10127. 'M' + (p.x - r) + ',' + p.y +
  10128. arc + (r * 2) + ',0 ' +
  10129. arc + (-r * 2) + ',0 ';
  10130. this._setPath(layer, d);
  10131. },
  10132. _setPath: function (layer, path) {
  10133. layer._path.setAttribute('d', path);
  10134. },
  10135. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10136. _bringToFront: function (layer) {
  10137. toFront(layer._path);
  10138. },
  10139. _bringToBack: function (layer) {
  10140. toBack(layer._path);
  10141. }
  10142. });
  10143. if (vml) {
  10144. SVG.include(vmlMixin);
  10145. }
  10146. // @factory L.svg(options?: Renderer options)
  10147. // Creates a SVG renderer with the given options.
  10148. function svg$1(options) {
  10149. return svg || vml ? new SVG(options) : null;
  10150. }
  10151. Map.include({
  10152. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10153. // Returns the instance of `Renderer` that should be used to render the given
  10154. // `Path`. It will ensure that the `renderer` options of the map and paths
  10155. // are respected, and that the renderers do exist on the map.
  10156. getRenderer: function (layer) {
  10157. // @namespace Path; @option renderer: Renderer
  10158. // Use this specific instance of `Renderer` for this path. Takes
  10159. // precedence over the map's [default renderer](#map-renderer).
  10160. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10161. if (!renderer) {
  10162. // @namespace Map; @option preferCanvas: Boolean = false
  10163. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10164. // By default, all `Path`s are rendered in a `SVG` renderer.
  10165. renderer = this._renderer = (this.options.preferCanvas && canvas$1()) || svg$1();
  10166. }
  10167. if (!this.hasLayer(renderer)) {
  10168. this.addLayer(renderer);
  10169. }
  10170. return renderer;
  10171. },
  10172. _getPaneRenderer: function (name) {
  10173. if (name === 'overlayPane' || name === undefined) {
  10174. return false;
  10175. }
  10176. var renderer = this._paneRenderers[name];
  10177. if (renderer === undefined) {
  10178. renderer = (SVG && svg$1({pane: name})) || (Canvas && canvas$1({pane: name}));
  10179. this._paneRenderers[name] = renderer;
  10180. }
  10181. return renderer;
  10182. }
  10183. });
  10184. /*
  10185. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10186. */
  10187. /*
  10188. * @class Rectangle
  10189. * @aka L.Retangle
  10190. * @inherits Polygon
  10191. *
  10192. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10193. *
  10194. * @example
  10195. *
  10196. * ```js
  10197. * // define rectangle geographical bounds
  10198. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10199. *
  10200. * // create an orange rectangle
  10201. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10202. *
  10203. * // zoom the map to the rectangle bounds
  10204. * map.fitBounds(bounds);
  10205. * ```
  10206. *
  10207. */
  10208. var Rectangle = Polygon.extend({
  10209. initialize: function (latLngBounds, options) {
  10210. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10211. },
  10212. // @method setBounds(latLngBounds: LatLngBounds): this
  10213. // Redraws the rectangle with the passed bounds.
  10214. setBounds: function (latLngBounds) {
  10215. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  10216. },
  10217. _boundsToLatLngs: function (latLngBounds) {
  10218. latLngBounds = toLatLngBounds(latLngBounds);
  10219. return [
  10220. latLngBounds.getSouthWest(),
  10221. latLngBounds.getNorthWest(),
  10222. latLngBounds.getNorthEast(),
  10223. latLngBounds.getSouthEast()
  10224. ];
  10225. }
  10226. });
  10227. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  10228. function rectangle(latLngBounds, options) {
  10229. return new Rectangle(latLngBounds, options);
  10230. }
  10231. SVG.create = create$2;
  10232. SVG.pointsToPath = pointsToPath;
  10233. GeoJSON.geometryToLayer = geometryToLayer;
  10234. GeoJSON.coordsToLatLng = coordsToLatLng;
  10235. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  10236. GeoJSON.latLngToCoords = latLngToCoords;
  10237. GeoJSON.latLngsToCoords = latLngsToCoords;
  10238. GeoJSON.getFeature = getFeature;
  10239. GeoJSON.asFeature = asFeature;
  10240. /*
  10241. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  10242. * (zoom to a selected bounding box), enabled by default.
  10243. */
  10244. // @namespace Map
  10245. // @section Interaction Options
  10246. Map.mergeOptions({
  10247. // @option boxZoom: Boolean = true
  10248. // Whether the map can be zoomed to a rectangular area specified by
  10249. // dragging the mouse while pressing the shift key.
  10250. boxZoom: true
  10251. });
  10252. var BoxZoom = Handler.extend({
  10253. initialize: function (map) {
  10254. this._map = map;
  10255. this._container = map._container;
  10256. this._pane = map._panes.overlayPane;
  10257. this._resetStateTimeout = 0;
  10258. map.on('unload', this._destroy, this);
  10259. },
  10260. addHooks: function () {
  10261. on(this._container, 'mousedown', this._onMouseDown, this);
  10262. },
  10263. removeHooks: function () {
  10264. off(this._container, 'mousedown', this._onMouseDown, this);
  10265. },
  10266. moved: function () {
  10267. return this._moved;
  10268. },
  10269. _destroy: function () {
  10270. remove(this._pane);
  10271. delete this._pane;
  10272. },
  10273. _resetState: function () {
  10274. this._resetStateTimeout = 0;
  10275. this._moved = false;
  10276. },
  10277. _clearDeferredResetState: function () {
  10278. if (this._resetStateTimeout !== 0) {
  10279. clearTimeout(this._resetStateTimeout);
  10280. this._resetStateTimeout = 0;
  10281. }
  10282. },
  10283. _onMouseDown: function (e) {
  10284. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  10285. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  10286. // will interrupt the interaction and orphan a box element in the container.
  10287. this._clearDeferredResetState();
  10288. this._resetState();
  10289. disableTextSelection();
  10290. disableImageDrag();
  10291. this._startPoint = this._map.mouseEventToContainerPoint(e);
  10292. on(document, {
  10293. contextmenu: stop,
  10294. mousemove: this._onMouseMove,
  10295. mouseup: this._onMouseUp,
  10296. keydown: this._onKeyDown
  10297. }, this);
  10298. },
  10299. _onMouseMove: function (e) {
  10300. if (!this._moved) {
  10301. this._moved = true;
  10302. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  10303. addClass(this._container, 'leaflet-crosshair');
  10304. this._map.fire('boxzoomstart');
  10305. }
  10306. this._point = this._map.mouseEventToContainerPoint(e);
  10307. var bounds = new Bounds(this._point, this._startPoint),
  10308. size = bounds.getSize();
  10309. setPosition(this._box, bounds.min);
  10310. this._box.style.width = size.x + 'px';
  10311. this._box.style.height = size.y + 'px';
  10312. },
  10313. _finish: function () {
  10314. if (this._moved) {
  10315. remove(this._box);
  10316. removeClass(this._container, 'leaflet-crosshair');
  10317. }
  10318. enableTextSelection();
  10319. enableImageDrag();
  10320. off(document, {
  10321. contextmenu: stop,
  10322. mousemove: this._onMouseMove,
  10323. mouseup: this._onMouseUp,
  10324. keydown: this._onKeyDown
  10325. }, this);
  10326. },
  10327. _onMouseUp: function (e) {
  10328. if ((e.which !== 1) && (e.button !== 1)) { return; }
  10329. this._finish();
  10330. if (!this._moved) { return; }
  10331. // Postpone to next JS tick so internal click event handling
  10332. // still see it as "moved".
  10333. this._clearDeferredResetState();
  10334. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  10335. var bounds = new LatLngBounds(
  10336. this._map.containerPointToLatLng(this._startPoint),
  10337. this._map.containerPointToLatLng(this._point));
  10338. this._map
  10339. .fitBounds(bounds)
  10340. .fire('boxzoomend', {boxZoomBounds: bounds});
  10341. },
  10342. _onKeyDown: function (e) {
  10343. if (e.keyCode === 27) {
  10344. this._finish();
  10345. }
  10346. }
  10347. });
  10348. // @section Handlers
  10349. // @property boxZoom: Handler
  10350. // Box (shift-drag with mouse) zoom handler.
  10351. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  10352. /*
  10353. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  10354. */
  10355. // @namespace Map
  10356. // @section Interaction Options
  10357. Map.mergeOptions({
  10358. // @option doubleClickZoom: Boolean|String = true
  10359. // Whether the map can be zoomed in by double clicking on it and
  10360. // zoomed out by double clicking while holding shift. If passed
  10361. // `'center'`, double-click zoom will zoom to the center of the
  10362. // view regardless of where the mouse was.
  10363. doubleClickZoom: true
  10364. });
  10365. var DoubleClickZoom = Handler.extend({
  10366. addHooks: function () {
  10367. this._map.on('dblclick', this._onDoubleClick, this);
  10368. },
  10369. removeHooks: function () {
  10370. this._map.off('dblclick', this._onDoubleClick, this);
  10371. },
  10372. _onDoubleClick: function (e) {
  10373. var map = this._map,
  10374. oldZoom = map.getZoom(),
  10375. delta = map.options.zoomDelta,
  10376. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  10377. if (map.options.doubleClickZoom === 'center') {
  10378. map.setZoom(zoom);
  10379. } else {
  10380. map.setZoomAround(e.containerPoint, zoom);
  10381. }
  10382. }
  10383. });
  10384. // @section Handlers
  10385. //
  10386. // Map properties include interaction handlers that allow you to control
  10387. // interaction behavior in runtime, enabling or disabling certain features such
  10388. // as dragging or touch zoom (see `Handler` methods). For example:
  10389. //
  10390. // ```js
  10391. // map.doubleClickZoom.disable();
  10392. // ```
  10393. //
  10394. // @property doubleClickZoom: Handler
  10395. // Double click zoom handler.
  10396. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  10397. /*
  10398. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  10399. */
  10400. // @namespace Map
  10401. // @section Interaction Options
  10402. Map.mergeOptions({
  10403. // @option dragging: Boolean = true
  10404. // Whether the map be draggable with mouse/touch or not.
  10405. dragging: true,
  10406. // @section Panning Inertia Options
  10407. // @option inertia: Boolean = *
  10408. // If enabled, panning of the map will have an inertia effect where
  10409. // the map builds momentum while dragging and continues moving in
  10410. // the same direction for some time. Feels especially nice on touch
  10411. // devices. Enabled by default unless running on old Android devices.
  10412. inertia: !android23,
  10413. // @option inertiaDeceleration: Number = 3000
  10414. // The rate with which the inertial movement slows down, in pixels/second².
  10415. inertiaDeceleration: 3400, // px/s^2
  10416. // @option inertiaMaxSpeed: Number = Infinity
  10417. // Max speed of the inertial movement, in pixels/second.
  10418. inertiaMaxSpeed: Infinity, // px/s
  10419. // @option easeLinearity: Number = 0.2
  10420. easeLinearity: 0.2,
  10421. // TODO refactor, move to CRS
  10422. // @option worldCopyJump: Boolean = false
  10423. // With this option enabled, the map tracks when you pan to another "copy"
  10424. // of the world and seamlessly jumps to the original one so that all overlays
  10425. // like markers and vector layers are still visible.
  10426. worldCopyJump: false,
  10427. // @option maxBoundsViscosity: Number = 0.0
  10428. // If `maxBounds` is set, this option will control how solid the bounds
  10429. // are when dragging the map around. The default value of `0.0` allows the
  10430. // user to drag outside the bounds at normal speed, higher values will
  10431. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  10432. // solid, preventing the user from dragging outside the bounds.
  10433. maxBoundsViscosity: 0.0
  10434. });
  10435. var Drag = Handler.extend({
  10436. addHooks: function () {
  10437. if (!this._draggable) {
  10438. var map = this._map;
  10439. this._draggable = new Draggable(map._mapPane, map._container);
  10440. this._draggable.on({
  10441. dragstart: this._onDragStart,
  10442. drag: this._onDrag,
  10443. dragend: this._onDragEnd
  10444. }, this);
  10445. this._draggable.on('predrag', this._onPreDragLimit, this);
  10446. if (map.options.worldCopyJump) {
  10447. this._draggable.on('predrag', this._onPreDragWrap, this);
  10448. map.on('zoomend', this._onZoomEnd, this);
  10449. map.whenReady(this._onZoomEnd, this);
  10450. }
  10451. }
  10452. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  10453. this._draggable.enable();
  10454. this._positions = [];
  10455. this._times = [];
  10456. },
  10457. removeHooks: function () {
  10458. removeClass(this._map._container, 'leaflet-grab');
  10459. removeClass(this._map._container, 'leaflet-touch-drag');
  10460. this._draggable.disable();
  10461. },
  10462. moved: function () {
  10463. return this._draggable && this._draggable._moved;
  10464. },
  10465. moving: function () {
  10466. return this._draggable && this._draggable._moving;
  10467. },
  10468. _onDragStart: function () {
  10469. var map = this._map;
  10470. map._stop();
  10471. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  10472. var bounds = toLatLngBounds(this._map.options.maxBounds);
  10473. this._offsetLimit = toBounds(
  10474. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  10475. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  10476. .add(this._map.getSize()));
  10477. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  10478. } else {
  10479. this._offsetLimit = null;
  10480. }
  10481. map
  10482. .fire('movestart')
  10483. .fire('dragstart');
  10484. if (map.options.inertia) {
  10485. this._positions = [];
  10486. this._times = [];
  10487. }
  10488. },
  10489. _onDrag: function (e) {
  10490. if (this._map.options.inertia) {
  10491. var time = this._lastTime = +new Date(),
  10492. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  10493. this._positions.push(pos);
  10494. this._times.push(time);
  10495. if (time - this._times[0] > 50) {
  10496. this._positions.shift();
  10497. this._times.shift();
  10498. }
  10499. }
  10500. this._map
  10501. .fire('move', e)
  10502. .fire('drag', e);
  10503. },
  10504. _onZoomEnd: function () {
  10505. var pxCenter = this._map.getSize().divideBy(2),
  10506. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  10507. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  10508. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  10509. },
  10510. _viscousLimit: function (value, threshold) {
  10511. return value - (value - threshold) * this._viscosity;
  10512. },
  10513. _onPreDragLimit: function () {
  10514. if (!this._viscosity || !this._offsetLimit) { return; }
  10515. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  10516. var limit = this._offsetLimit;
  10517. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  10518. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  10519. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  10520. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  10521. this._draggable._newPos = this._draggable._startPos.add(offset);
  10522. },
  10523. _onPreDragWrap: function () {
  10524. // TODO refactor to be able to adjust map pane position after zoom
  10525. var worldWidth = this._worldWidth,
  10526. halfWidth = Math.round(worldWidth / 2),
  10527. dx = this._initialWorldOffset,
  10528. x = this._draggable._newPos.x,
  10529. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  10530. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  10531. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  10532. this._draggable._absPos = this._draggable._newPos.clone();
  10533. this._draggable._newPos.x = newX;
  10534. },
  10535. _onDragEnd: function (e) {
  10536. var map = this._map,
  10537. options = map.options,
  10538. noInertia = !options.inertia || this._times.length < 2;
  10539. map.fire('dragend', e);
  10540. if (noInertia) {
  10541. map.fire('moveend');
  10542. } else {
  10543. var direction = this._lastPos.subtract(this._positions[0]),
  10544. duration = (this._lastTime - this._times[0]) / 1000,
  10545. ease = options.easeLinearity,
  10546. speedVector = direction.multiplyBy(ease / duration),
  10547. speed = speedVector.distanceTo([0, 0]),
  10548. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  10549. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  10550. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  10551. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  10552. if (!offset.x && !offset.y) {
  10553. map.fire('moveend');
  10554. } else {
  10555. offset = map._limitOffset(offset, map.options.maxBounds);
  10556. requestAnimFrame(function () {
  10557. map.panBy(offset, {
  10558. duration: decelerationDuration,
  10559. easeLinearity: ease,
  10560. noMoveStart: true,
  10561. animate: true
  10562. });
  10563. });
  10564. }
  10565. }
  10566. }
  10567. });
  10568. // @section Handlers
  10569. // @property dragging: Handler
  10570. // Map dragging handler (by both mouse and touch).
  10571. Map.addInitHook('addHandler', 'dragging', Drag);
  10572. /*
  10573. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  10574. */
  10575. // @namespace Map
  10576. // @section Keyboard Navigation Options
  10577. Map.mergeOptions({
  10578. // @option keyboard: Boolean = true
  10579. // Makes the map focusable and allows users to navigate the map with keyboard
  10580. // arrows and `+`/`-` keys.
  10581. keyboard: true,
  10582. // @option keyboardPanDelta: Number = 80
  10583. // Amount of pixels to pan when pressing an arrow key.
  10584. keyboardPanDelta: 80
  10585. });
  10586. var Keyboard = Handler.extend({
  10587. keyCodes: {
  10588. left: [37],
  10589. right: [39],
  10590. down: [40],
  10591. up: [38],
  10592. zoomIn: [187, 107, 61, 171],
  10593. zoomOut: [189, 109, 54, 173]
  10594. },
  10595. initialize: function (map) {
  10596. this._map = map;
  10597. this._setPanDelta(map.options.keyboardPanDelta);
  10598. this._setZoomDelta(map.options.zoomDelta);
  10599. },
  10600. addHooks: function () {
  10601. var container = this._map._container;
  10602. // make the container focusable by tabbing
  10603. if (container.tabIndex <= 0) {
  10604. container.tabIndex = '0';
  10605. }
  10606. on(container, {
  10607. focus: this._onFocus,
  10608. blur: this._onBlur,
  10609. mousedown: this._onMouseDown
  10610. }, this);
  10611. this._map.on({
  10612. focus: this._addHooks,
  10613. blur: this._removeHooks
  10614. }, this);
  10615. },
  10616. removeHooks: function () {
  10617. this._removeHooks();
  10618. off(this._map._container, {
  10619. focus: this._onFocus,
  10620. blur: this._onBlur,
  10621. mousedown: this._onMouseDown
  10622. }, this);
  10623. this._map.off({
  10624. focus: this._addHooks,
  10625. blur: this._removeHooks
  10626. }, this);
  10627. },
  10628. _onMouseDown: function () {
  10629. if (this._focused) { return; }
  10630. var body = document.body,
  10631. docEl = document.documentElement,
  10632. top = body.scrollTop || docEl.scrollTop,
  10633. left = body.scrollLeft || docEl.scrollLeft;
  10634. this._map._container.focus();
  10635. window.scrollTo(left, top);
  10636. },
  10637. _onFocus: function () {
  10638. this._focused = true;
  10639. this._map.fire('focus');
  10640. },
  10641. _onBlur: function () {
  10642. this._focused = false;
  10643. this._map.fire('blur');
  10644. },
  10645. _setPanDelta: function (panDelta) {
  10646. var keys = this._panKeys = {},
  10647. codes = this.keyCodes,
  10648. i, len;
  10649. for (i = 0, len = codes.left.length; i < len; i++) {
  10650. keys[codes.left[i]] = [-1 * panDelta, 0];
  10651. }
  10652. for (i = 0, len = codes.right.length; i < len; i++) {
  10653. keys[codes.right[i]] = [panDelta, 0];
  10654. }
  10655. for (i = 0, len = codes.down.length; i < len; i++) {
  10656. keys[codes.down[i]] = [0, panDelta];
  10657. }
  10658. for (i = 0, len = codes.up.length; i < len; i++) {
  10659. keys[codes.up[i]] = [0, -1 * panDelta];
  10660. }
  10661. },
  10662. _setZoomDelta: function (zoomDelta) {
  10663. var keys = this._zoomKeys = {},
  10664. codes = this.keyCodes,
  10665. i, len;
  10666. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  10667. keys[codes.zoomIn[i]] = zoomDelta;
  10668. }
  10669. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  10670. keys[codes.zoomOut[i]] = -zoomDelta;
  10671. }
  10672. },
  10673. _addHooks: function () {
  10674. on(document, 'keydown', this._onKeyDown, this);
  10675. },
  10676. _removeHooks: function () {
  10677. off(document, 'keydown', this._onKeyDown, this);
  10678. },
  10679. _onKeyDown: function (e) {
  10680. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  10681. var key = e.keyCode,
  10682. map = this._map,
  10683. offset;
  10684. if (key in this._panKeys) {
  10685. if (map._panAnim && map._panAnim._inProgress) { return; }
  10686. offset = this._panKeys[key];
  10687. if (e.shiftKey) {
  10688. offset = toPoint(offset).multiplyBy(3);
  10689. }
  10690. map.panBy(offset);
  10691. if (map.options.maxBounds) {
  10692. map.panInsideBounds(map.options.maxBounds);
  10693. }
  10694. } else if (key in this._zoomKeys) {
  10695. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  10696. } else if (key === 27 && map._popup) {
  10697. map.closePopup();
  10698. } else {
  10699. return;
  10700. }
  10701. stop(e);
  10702. }
  10703. });
  10704. // @section Handlers
  10705. // @section Handlers
  10706. // @property keyboard: Handler
  10707. // Keyboard navigation handler.
  10708. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  10709. /*
  10710. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  10711. */
  10712. // @namespace Map
  10713. // @section Interaction Options
  10714. Map.mergeOptions({
  10715. // @section Mousewheel options
  10716. // @option scrollWheelZoom: Boolean|String = true
  10717. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  10718. // it will zoom to the center of the view regardless of where the mouse was.
  10719. scrollWheelZoom: true,
  10720. // @option wheelDebounceTime: Number = 40
  10721. // Limits the rate at which a wheel can fire (in milliseconds). By default
  10722. // user can't zoom via wheel more often than once per 40 ms.
  10723. wheelDebounceTime: 40,
  10724. // @option wheelPxPerZoomLevel: Number = 60
  10725. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  10726. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  10727. // faster (and vice versa).
  10728. wheelPxPerZoomLevel: 60
  10729. });
  10730. var ScrollWheelZoom = Handler.extend({
  10731. addHooks: function () {
  10732. on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  10733. this._delta = 0;
  10734. },
  10735. removeHooks: function () {
  10736. off(this._map._container, 'mousewheel', this._onWheelScroll, this);
  10737. },
  10738. _onWheelScroll: function (e) {
  10739. var delta = getWheelDelta(e);
  10740. var debounce = this._map.options.wheelDebounceTime;
  10741. this._delta += delta;
  10742. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  10743. if (!this._startTime) {
  10744. this._startTime = +new Date();
  10745. }
  10746. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  10747. clearTimeout(this._timer);
  10748. this._timer = setTimeout(bind(this._performZoom, this), left);
  10749. stop(e);
  10750. },
  10751. _performZoom: function () {
  10752. var map = this._map,
  10753. zoom = map.getZoom(),
  10754. snap = this._map.options.zoomSnap || 0;
  10755. map._stop(); // stop panning and fly animations if any
  10756. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  10757. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  10758. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  10759. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  10760. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  10761. this._delta = 0;
  10762. this._startTime = null;
  10763. if (!delta) { return; }
  10764. if (map.options.scrollWheelZoom === 'center') {
  10765. map.setZoom(zoom + delta);
  10766. } else {
  10767. map.setZoomAround(this._lastMousePos, zoom + delta);
  10768. }
  10769. }
  10770. });
  10771. // @section Handlers
  10772. // @property scrollWheelZoom: Handler
  10773. // Scroll wheel zoom handler.
  10774. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  10775. /*
  10776. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  10777. */
  10778. // @namespace Map
  10779. // @section Interaction Options
  10780. Map.mergeOptions({
  10781. // @section Touch interaction options
  10782. // @option tap: Boolean = true
  10783. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  10784. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  10785. tap: true,
  10786. // @option tapTolerance: Number = 15
  10787. // The max number of pixels a user can shift his finger during touch
  10788. // for it to be considered a valid tap.
  10789. tapTolerance: 15
  10790. });
  10791. var Tap = Handler.extend({
  10792. addHooks: function () {
  10793. on(this._map._container, 'touchstart', this._onDown, this);
  10794. },
  10795. removeHooks: function () {
  10796. off(this._map._container, 'touchstart', this._onDown, this);
  10797. },
  10798. _onDown: function (e) {
  10799. if (!e.touches) { return; }
  10800. preventDefault(e);
  10801. this._fireClick = true;
  10802. // don't simulate click or track longpress if more than 1 touch
  10803. if (e.touches.length > 1) {
  10804. this._fireClick = false;
  10805. clearTimeout(this._holdTimeout);
  10806. return;
  10807. }
  10808. var first = e.touches[0],
  10809. el = first.target;
  10810. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  10811. // if touching a link, highlight it
  10812. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  10813. addClass(el, 'leaflet-active');
  10814. }
  10815. // simulate long hold but setting a timeout
  10816. this._holdTimeout = setTimeout(bind(function () {
  10817. if (this._isTapValid()) {
  10818. this._fireClick = false;
  10819. this._onUp();
  10820. this._simulateEvent('contextmenu', first);
  10821. }
  10822. }, this), 1000);
  10823. this._simulateEvent('mousedown', first);
  10824. on(document, {
  10825. touchmove: this._onMove,
  10826. touchend: this._onUp
  10827. }, this);
  10828. },
  10829. _onUp: function (e) {
  10830. clearTimeout(this._holdTimeout);
  10831. off(document, {
  10832. touchmove: this._onMove,
  10833. touchend: this._onUp
  10834. }, this);
  10835. if (this._fireClick && e && e.changedTouches) {
  10836. var first = e.changedTouches[0],
  10837. el = first.target;
  10838. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  10839. removeClass(el, 'leaflet-active');
  10840. }
  10841. this._simulateEvent('mouseup', first);
  10842. // simulate click if the touch didn't move too much
  10843. if (this._isTapValid()) {
  10844. this._simulateEvent('click', first);
  10845. }
  10846. }
  10847. },
  10848. _isTapValid: function () {
  10849. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  10850. },
  10851. _onMove: function (e) {
  10852. var first = e.touches[0];
  10853. this._newPos = new Point(first.clientX, first.clientY);
  10854. this._simulateEvent('mousemove', first);
  10855. },
  10856. _simulateEvent: function (type, e) {
  10857. var simulatedEvent = document.createEvent('MouseEvents');
  10858. simulatedEvent._simulated = true;
  10859. e.target._simulatedClick = true;
  10860. simulatedEvent.initMouseEvent(
  10861. type, true, true, window, 1,
  10862. e.screenX, e.screenY,
  10863. e.clientX, e.clientY,
  10864. false, false, false, false, 0, null);
  10865. e.target.dispatchEvent(simulatedEvent);
  10866. }
  10867. });
  10868. // @section Handlers
  10869. // @property tap: Handler
  10870. // Mobile touch hacks (quick tap and touch hold) handler.
  10871. if (touch && !pointer) {
  10872. Map.addInitHook('addHandler', 'tap', Tap);
  10873. }
  10874. /*
  10875. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  10876. */
  10877. // @namespace Map
  10878. // @section Interaction Options
  10879. Map.mergeOptions({
  10880. // @section Touch interaction options
  10881. // @option touchZoom: Boolean|String = *
  10882. // Whether the map can be zoomed by touch-dragging with two fingers. If
  10883. // passed `'center'`, it will zoom to the center of the view regardless of
  10884. // where the touch events (fingers) were. Enabled for touch-capable web
  10885. // browsers except for old Androids.
  10886. touchZoom: touch && !android23,
  10887. // @option bounceAtZoomLimits: Boolean = true
  10888. // Set it to false if you don't want the map to zoom beyond min/max zoom
  10889. // and then bounce back when pinch-zooming.
  10890. bounceAtZoomLimits: true
  10891. });
  10892. var TouchZoom = Handler.extend({
  10893. addHooks: function () {
  10894. addClass(this._map._container, 'leaflet-touch-zoom');
  10895. on(this._map._container, 'touchstart', this._onTouchStart, this);
  10896. },
  10897. removeHooks: function () {
  10898. removeClass(this._map._container, 'leaflet-touch-zoom');
  10899. off(this._map._container, 'touchstart', this._onTouchStart, this);
  10900. },
  10901. _onTouchStart: function (e) {
  10902. var map = this._map;
  10903. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  10904. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  10905. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  10906. this._centerPoint = map.getSize()._divideBy(2);
  10907. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  10908. if (map.options.touchZoom !== 'center') {
  10909. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  10910. }
  10911. this._startDist = p1.distanceTo(p2);
  10912. this._startZoom = map.getZoom();
  10913. this._moved = false;
  10914. this._zooming = true;
  10915. map._stop();
  10916. on(document, 'touchmove', this._onTouchMove, this);
  10917. on(document, 'touchend', this._onTouchEnd, this);
  10918. preventDefault(e);
  10919. },
  10920. _onTouchMove: function (e) {
  10921. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  10922. var map = this._map,
  10923. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  10924. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  10925. scale = p1.distanceTo(p2) / this._startDist;
  10926. this._zoom = map.getScaleZoom(scale, this._startZoom);
  10927. if (!map.options.bounceAtZoomLimits && (
  10928. (this._zoom < map.getMinZoom() && scale < 1) ||
  10929. (this._zoom > map.getMaxZoom() && scale > 1))) {
  10930. this._zoom = map._limitZoom(this._zoom);
  10931. }
  10932. if (map.options.touchZoom === 'center') {
  10933. this._center = this._startLatLng;
  10934. if (scale === 1) { return; }
  10935. } else {
  10936. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  10937. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  10938. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  10939. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  10940. }
  10941. if (!this._moved) {
  10942. map._moveStart(true);
  10943. this._moved = true;
  10944. }
  10945. cancelAnimFrame(this._animRequest);
  10946. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  10947. this._animRequest = requestAnimFrame(moveFn, this, true);
  10948. preventDefault(e);
  10949. },
  10950. _onTouchEnd: function () {
  10951. if (!this._moved || !this._zooming) {
  10952. this._zooming = false;
  10953. return;
  10954. }
  10955. this._zooming = false;
  10956. cancelAnimFrame(this._animRequest);
  10957. off(document, 'touchmove', this._onTouchMove);
  10958. off(document, 'touchend', this._onTouchEnd);
  10959. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  10960. if (this._map.options.zoomAnimation) {
  10961. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  10962. } else {
  10963. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  10964. }
  10965. }
  10966. });
  10967. // @section Handlers
  10968. // @property touchZoom: Handler
  10969. // Touch zoom handler.
  10970. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  10971. Map.BoxZoom = BoxZoom;
  10972. Map.DoubleClickZoom = DoubleClickZoom;
  10973. Map.Drag = Drag;
  10974. Map.Keyboard = Keyboard;
  10975. Map.ScrollWheelZoom = ScrollWheelZoom;
  10976. Map.Tap = Tap;
  10977. Map.TouchZoom = TouchZoom;
  10978. // misc
  10979. var oldL = window.L;
  10980. function noConflict() {
  10981. window.L = oldL;
  10982. return this;
  10983. }
  10984. // Always export us to window global (see #2364)
  10985. window.L = exports;
  10986. Object.freeze = freeze;
  10987. exports.version = version;
  10988. exports.noConflict = noConflict;
  10989. exports.Control = Control;
  10990. exports.control = control;
  10991. exports.Browser = Browser;
  10992. exports.Evented = Evented;
  10993. exports.Mixin = Mixin;
  10994. exports.Util = Util;
  10995. exports.Class = Class;
  10996. exports.Handler = Handler;
  10997. exports.extend = extend;
  10998. exports.bind = bind;
  10999. exports.stamp = stamp;
  11000. exports.setOptions = setOptions;
  11001. exports.DomEvent = DomEvent;
  11002. exports.DomUtil = DomUtil;
  11003. exports.PosAnimation = PosAnimation;
  11004. exports.Draggable = Draggable;
  11005. exports.LineUtil = LineUtil;
  11006. exports.PolyUtil = PolyUtil;
  11007. exports.Point = Point;
  11008. exports.point = toPoint;
  11009. exports.Bounds = Bounds;
  11010. exports.bounds = toBounds;
  11011. exports.Transformation = Transformation;
  11012. exports.transformation = toTransformation;
  11013. exports.Projection = index;
  11014. exports.LatLng = LatLng;
  11015. exports.latLng = toLatLng;
  11016. exports.LatLngBounds = LatLngBounds;
  11017. exports.latLngBounds = toLatLngBounds;
  11018. exports.CRS = CRS;
  11019. exports.GeoJSON = GeoJSON;
  11020. exports.geoJSON = geoJSON;
  11021. exports.geoJson = geoJson;
  11022. exports.Layer = Layer;
  11023. exports.LayerGroup = LayerGroup;
  11024. exports.layerGroup = layerGroup;
  11025. exports.FeatureGroup = FeatureGroup;
  11026. exports.featureGroup = featureGroup;
  11027. exports.ImageOverlay = ImageOverlay;
  11028. exports.imageOverlay = imageOverlay;
  11029. exports.VideoOverlay = VideoOverlay;
  11030. exports.videoOverlay = videoOverlay;
  11031. exports.DivOverlay = DivOverlay;
  11032. exports.Popup = Popup;
  11033. exports.popup = popup;
  11034. exports.Tooltip = Tooltip;
  11035. exports.tooltip = tooltip;
  11036. exports.Icon = Icon;
  11037. exports.icon = icon;
  11038. exports.DivIcon = DivIcon;
  11039. exports.divIcon = divIcon;
  11040. exports.Marker = Marker;
  11041. exports.marker = marker;
  11042. exports.TileLayer = TileLayer;
  11043. exports.tileLayer = tileLayer;
  11044. exports.GridLayer = GridLayer;
  11045. exports.gridLayer = gridLayer;
  11046. exports.SVG = SVG;
  11047. exports.svg = svg$1;
  11048. exports.Renderer = Renderer;
  11049. exports.Canvas = Canvas;
  11050. exports.canvas = canvas$1;
  11051. exports.Path = Path;
  11052. exports.CircleMarker = CircleMarker;
  11053. exports.circleMarker = circleMarker;
  11054. exports.Circle = Circle;
  11055. exports.circle = circle;
  11056. exports.Polyline = Polyline;
  11057. exports.polyline = polyline;
  11058. exports.Polygon = Polygon;
  11059. exports.polygon = polygon;
  11060. exports.Rectangle = Rectangle;
  11061. exports.rectangle = rectangle;
  11062. exports.Map = Map;
  11063. exports.map = createMap;
  11064. })));
  11065. //# sourceMappingURL=leaflet-src.js.map