leaflet-src.js 427 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409
  1. /* @preserve
  2. * Leaflet 1.9.2, a JS library for interactive maps. https://leafletjs.com
  3. * (c) 2010-2022 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. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.leaflet = {}));
  9. })(this, (function (exports) { 'use strict';
  10. var version = "1.9.2";
  11. /*
  12. * @namespace Util
  13. *
  14. * Various utility functions, used by Leaflet internally.
  15. */
  16. // @function extend(dest: Object, src?: Object): Object
  17. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  18. function extend(dest) {
  19. var i, j, len, src;
  20. for (j = 1, len = arguments.length; j < len; j++) {
  21. src = arguments[j];
  22. for (i in src) {
  23. dest[i] = src[i];
  24. }
  25. }
  26. return dest;
  27. }
  28. // @function create(proto: Object, properties?: Object): Object
  29. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  30. var create$2 = Object.create || (function () {
  31. function F() {}
  32. return function (proto) {
  33. F.prototype = proto;
  34. return new F();
  35. };
  36. })();
  37. // @function bind(fn: Function, …): Function
  38. // 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).
  39. // Has a `L.bind()` shortcut.
  40. function bind(fn, obj) {
  41. var slice = Array.prototype.slice;
  42. if (fn.bind) {
  43. return fn.bind.apply(fn, slice.call(arguments, 1));
  44. }
  45. var args = slice.call(arguments, 2);
  46. return function () {
  47. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  48. };
  49. }
  50. // @property lastId: Number
  51. // Last unique ID used by [`stamp()`](#util-stamp)
  52. var lastId = 0;
  53. // @function stamp(obj: Object): Number
  54. // Returns the unique ID of an object, assigning it one if it doesn't have it.
  55. function stamp(obj) {
  56. if (!('_leaflet_id' in obj)) {
  57. obj['_leaflet_id'] = ++lastId;
  58. }
  59. return obj._leaflet_id;
  60. }
  61. // @function throttle(fn: Function, time: Number, context: Object): Function
  62. // Returns a function which executes function `fn` with the given scope `context`
  63. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  64. // `fn` will be called no more than one time per given amount of `time`. The arguments
  65. // received by the bound function will be any arguments passed when binding the
  66. // function, followed by any arguments passed when invoking the bound function.
  67. // Has an `L.throttle` shortcut.
  68. function throttle(fn, time, context) {
  69. var lock, args, wrapperFn, later;
  70. later = function () {
  71. // reset lock and call if queued
  72. lock = false;
  73. if (args) {
  74. wrapperFn.apply(context, args);
  75. args = false;
  76. }
  77. };
  78. wrapperFn = function () {
  79. if (lock) {
  80. // called too soon, queue to call later
  81. args = arguments;
  82. } else {
  83. // call and lock until later
  84. fn.apply(context, arguments);
  85. setTimeout(later, time);
  86. lock = true;
  87. }
  88. };
  89. return wrapperFn;
  90. }
  91. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  92. // Returns the number `num` modulo `range` in such a way so it lies within
  93. // `range[0]` and `range[1]`. The returned value will be always smaller than
  94. // `range[1]` unless `includeMax` is set to `true`.
  95. function wrapNum(x, range, includeMax) {
  96. var max = range[1],
  97. min = range[0],
  98. d = max - min;
  99. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  100. }
  101. // @function falseFn(): Function
  102. // Returns a function which always returns `false`.
  103. function falseFn() { return false; }
  104. // @function formatNum(num: Number, precision?: Number|false): Number
  105. // Returns the number `num` rounded with specified `precision`.
  106. // The default `precision` value is 6 decimal places.
  107. // `false` can be passed to skip any processing (can be useful to avoid round-off errors).
  108. function formatNum(num, precision) {
  109. if (precision === false) { return num; }
  110. var pow = Math.pow(10, precision === undefined ? 6 : precision);
  111. return Math.round(num * pow) / pow;
  112. }
  113. // @function trim(str: String): String
  114. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  115. function trim(str) {
  116. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  117. }
  118. // @function splitWords(str: String): String[]
  119. // Trims and splits the string on whitespace and returns the array of parts.
  120. function splitWords(str) {
  121. return trim(str).split(/\s+/);
  122. }
  123. // @function setOptions(obj: Object, options: Object): Object
  124. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  125. function setOptions(obj, options) {
  126. if (!Object.prototype.hasOwnProperty.call(obj, 'options')) {
  127. obj.options = obj.options ? create$2(obj.options) : {};
  128. }
  129. for (var i in options) {
  130. obj.options[i] = options[i];
  131. }
  132. return obj.options;
  133. }
  134. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  135. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  136. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  137. // be appended at the end. If `uppercase` is `true`, the parameter names will
  138. // be uppercased (e.g. `'?A=foo&B=bar'`)
  139. function getParamString(obj, existingUrl, uppercase) {
  140. var params = [];
  141. for (var i in obj) {
  142. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  143. }
  144. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  145. }
  146. var templateRe = /\{ *([\w_ -]+) *\}/g;
  147. // @function template(str: String, data: Object): String
  148. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  149. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  150. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  151. // data values — they will be evaluated passing `data` as an argument.
  152. function template(str, data) {
  153. return str.replace(templateRe, function (str, key) {
  154. var value = data[key];
  155. if (value === undefined) {
  156. throw new Error('No value provided for variable ' + str);
  157. } else if (typeof value === 'function') {
  158. value = value(data);
  159. }
  160. return value;
  161. });
  162. }
  163. // @function isArray(obj): Boolean
  164. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  165. var isArray = Array.isArray || function (obj) {
  166. return (Object.prototype.toString.call(obj) === '[object Array]');
  167. };
  168. // @function indexOf(array: Array, el: Object): Number
  169. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  170. function indexOf(array, el) {
  171. for (var i = 0; i < array.length; i++) {
  172. if (array[i] === el) { return i; }
  173. }
  174. return -1;
  175. }
  176. // @property emptyImageUrl: String
  177. // Data URI string containing a base64-encoded empty GIF image.
  178. // Used as a hack to free memory from unused images on WebKit-powered
  179. // mobile devices (by setting image `src` to this string).
  180. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  181. // inspired by https://paulirish.com/2011/requestanimationframe-for-smart-animating/
  182. function getPrefixed(name) {
  183. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  184. }
  185. var lastTime = 0;
  186. // fallback for IE 7-8
  187. function timeoutDefer(fn) {
  188. var time = +new Date(),
  189. timeToCall = Math.max(0, 16 - (time - lastTime));
  190. lastTime = time + timeToCall;
  191. return window.setTimeout(fn, timeToCall);
  192. }
  193. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  194. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  195. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  196. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  197. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  198. // `context` if given. When `immediate` is set, `fn` is called immediately if
  199. // the browser doesn't have native support for
  200. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  201. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  202. function requestAnimFrame(fn, context, immediate) {
  203. if (immediate && requestFn === timeoutDefer) {
  204. fn.call(context);
  205. } else {
  206. return requestFn.call(window, bind(fn, context));
  207. }
  208. }
  209. // @function cancelAnimFrame(id: Number): undefined
  210. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  211. function cancelAnimFrame(id) {
  212. if (id) {
  213. cancelFn.call(window, id);
  214. }
  215. }
  216. var Util = {
  217. __proto__: null,
  218. extend: extend,
  219. create: create$2,
  220. bind: bind,
  221. get lastId () { return lastId; },
  222. stamp: stamp,
  223. throttle: throttle,
  224. wrapNum: wrapNum,
  225. falseFn: falseFn,
  226. formatNum: formatNum,
  227. trim: trim,
  228. splitWords: splitWords,
  229. setOptions: setOptions,
  230. getParamString: getParamString,
  231. template: template,
  232. isArray: isArray,
  233. indexOf: indexOf,
  234. emptyImageUrl: emptyImageUrl,
  235. requestFn: requestFn,
  236. cancelFn: cancelFn,
  237. requestAnimFrame: requestAnimFrame,
  238. cancelAnimFrame: cancelAnimFrame
  239. };
  240. // @class Class
  241. // @aka L.Class
  242. // @section
  243. // @uninheritable
  244. // Thanks to John Resig and Dean Edwards for inspiration!
  245. function Class() {}
  246. Class.extend = function (props) {
  247. // @function extend(props: Object): Function
  248. // [Extends the current class](#class-inheritance) given the properties to be included.
  249. // Returns a Javascript function that is a class constructor (to be called with `new`).
  250. var NewClass = function () {
  251. setOptions(this);
  252. // call the constructor
  253. if (this.initialize) {
  254. this.initialize.apply(this, arguments);
  255. }
  256. // call all constructor hooks
  257. this.callInitHooks();
  258. };
  259. var parentProto = NewClass.__super__ = this.prototype;
  260. var proto = create$2(parentProto);
  261. proto.constructor = NewClass;
  262. NewClass.prototype = proto;
  263. // inherit parent's statics
  264. for (var i in this) {
  265. if (Object.prototype.hasOwnProperty.call(this, i) && i !== 'prototype' && i !== '__super__') {
  266. NewClass[i] = this[i];
  267. }
  268. }
  269. // mix static properties into the class
  270. if (props.statics) {
  271. extend(NewClass, props.statics);
  272. }
  273. // mix includes into the prototype
  274. if (props.includes) {
  275. checkDeprecatedMixinEvents(props.includes);
  276. extend.apply(null, [proto].concat(props.includes));
  277. }
  278. // mix given properties into the prototype
  279. extend(proto, props);
  280. delete proto.statics;
  281. delete proto.includes;
  282. // merge options
  283. if (proto.options) {
  284. proto.options = parentProto.options ? create$2(parentProto.options) : {};
  285. extend(proto.options, props.options);
  286. }
  287. proto._initHooks = [];
  288. // add method for calling all hooks
  289. proto.callInitHooks = function () {
  290. if (this._initHooksCalled) { return; }
  291. if (parentProto.callInitHooks) {
  292. parentProto.callInitHooks.call(this);
  293. }
  294. this._initHooksCalled = true;
  295. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  296. proto._initHooks[i].call(this);
  297. }
  298. };
  299. return NewClass;
  300. };
  301. // @function include(properties: Object): this
  302. // [Includes a mixin](#class-includes) into the current class.
  303. Class.include = function (props) {
  304. var parentOptions = this.prototype.options;
  305. extend(this.prototype, props);
  306. if (props.options) {
  307. this.prototype.options = parentOptions;
  308. this.mergeOptions(props.options);
  309. }
  310. return this;
  311. };
  312. // @function mergeOptions(options: Object): this
  313. // [Merges `options`](#class-options) into the defaults of the class.
  314. Class.mergeOptions = function (options) {
  315. extend(this.prototype.options, options);
  316. return this;
  317. };
  318. // @function addInitHook(fn: Function): this
  319. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  320. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  321. var args = Array.prototype.slice.call(arguments, 1);
  322. var init = typeof fn === 'function' ? fn : function () {
  323. this[fn].apply(this, args);
  324. };
  325. this.prototype._initHooks = this.prototype._initHooks || [];
  326. this.prototype._initHooks.push(init);
  327. return this;
  328. };
  329. function checkDeprecatedMixinEvents(includes) {
  330. if (typeof L === 'undefined' || !L || !L.Mixin) { return; }
  331. includes = isArray(includes) ? includes : [includes];
  332. for (var i = 0; i < includes.length; i++) {
  333. if (includes[i] === L.Mixin.Events) {
  334. console.warn('Deprecated include of L.Mixin.Events: ' +
  335. 'this property will be removed in future releases, ' +
  336. 'please inherit from L.Evented instead.', new Error().stack);
  337. }
  338. }
  339. }
  340. /*
  341. * @class Evented
  342. * @aka L.Evented
  343. * @inherits Class
  344. *
  345. * 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).
  346. *
  347. * @example
  348. *
  349. * ```js
  350. * map.on('click', function(e) {
  351. * alert(e.latlng);
  352. * } );
  353. * ```
  354. *
  355. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  356. *
  357. * ```js
  358. * function onClick(e) { ... }
  359. *
  360. * map.on('click', onClick);
  361. * map.off('click', onClick);
  362. * ```
  363. */
  364. var Events = {
  365. /* @method on(type: String, fn: Function, context?: Object): this
  366. * 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'`).
  367. *
  368. * @alternative
  369. * @method on(eventMap: Object): this
  370. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  371. */
  372. on: function (types, fn, context) {
  373. // types can be a map of types/handlers
  374. if (typeof types === 'object') {
  375. for (var type in types) {
  376. // we don't process space-separated events here for performance;
  377. // it's a hot path since Layer uses the on(obj) syntax
  378. this._on(type, types[type], fn);
  379. }
  380. } else {
  381. // types can be a string of space-separated words
  382. types = splitWords(types);
  383. for (var i = 0, len = types.length; i < len; i++) {
  384. this._on(types[i], fn, context);
  385. }
  386. }
  387. return this;
  388. },
  389. /* @method off(type: String, fn?: Function, context?: Object): this
  390. * 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.
  391. *
  392. * @alternative
  393. * @method off(eventMap: Object): this
  394. * Removes a set of type/listener pairs.
  395. *
  396. * @alternative
  397. * @method off: this
  398. * Removes all listeners to all events on the object. This includes implicitly attached events.
  399. */
  400. off: function (types, fn, context) {
  401. if (!arguments.length) {
  402. // clear all listeners if called without arguments
  403. delete this._events;
  404. } else if (typeof types === 'object') {
  405. for (var type in types) {
  406. this._off(type, types[type], fn);
  407. }
  408. } else {
  409. types = splitWords(types);
  410. var removeAll = arguments.length === 1;
  411. for (var i = 0, len = types.length; i < len; i++) {
  412. if (removeAll) {
  413. this._off(types[i]);
  414. } else {
  415. this._off(types[i], fn, context);
  416. }
  417. }
  418. }
  419. return this;
  420. },
  421. // attach listener (without syntactic sugar now)
  422. _on: function (type, fn, context, _once) {
  423. if (typeof fn !== 'function') {
  424. console.warn('wrong listener type: ' + typeof fn);
  425. return;
  426. }
  427. // check if fn already there
  428. if (this._listens(type, fn, context) !== false) {
  429. return;
  430. }
  431. if (context === this) {
  432. // Less memory footprint.
  433. context = undefined;
  434. }
  435. var newListener = {fn: fn, ctx: context};
  436. if (_once) {
  437. newListener.once = true;
  438. }
  439. this._events = this._events || {};
  440. this._events[type] = this._events[type] || [];
  441. this._events[type].push(newListener);
  442. },
  443. _off: function (type, fn, context) {
  444. var listeners,
  445. i,
  446. len;
  447. if (!this._events) {
  448. return;
  449. }
  450. listeners = this._events[type];
  451. if (!listeners) {
  452. return;
  453. }
  454. if (arguments.length === 1) { // remove all
  455. if (this._firingCount) {
  456. // Set all removed listeners to noop
  457. // so they are not called if remove happens in fire
  458. for (i = 0, len = listeners.length; i < len; i++) {
  459. listeners[i].fn = falseFn;
  460. }
  461. }
  462. // clear all listeners for a type if function isn't specified
  463. delete this._events[type];
  464. return;
  465. }
  466. if (typeof fn !== 'function') {
  467. console.warn('wrong listener type: ' + typeof fn);
  468. return;
  469. }
  470. // find fn and remove it
  471. var index = this._listens(type, fn, context);
  472. if (index !== false) {
  473. var listener = listeners[index];
  474. if (this._firingCount) {
  475. // set the removed listener to noop so that's not called if remove happens in fire
  476. listener.fn = falseFn;
  477. /* copy array in case events are being fired */
  478. this._events[type] = listeners = listeners.slice();
  479. }
  480. listeners.splice(index, 1);
  481. }
  482. },
  483. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  484. // Fires an event of the specified type. You can optionally provide a data
  485. // object — the first argument of the listener function will contain its
  486. // properties. The event can optionally be propagated to event parents.
  487. fire: function (type, data, propagate) {
  488. if (!this.listens(type, propagate)) { return this; }
  489. var event = extend({}, data, {
  490. type: type,
  491. target: this,
  492. sourceTarget: data && data.sourceTarget || this
  493. });
  494. if (this._events) {
  495. var listeners = this._events[type];
  496. if (listeners) {
  497. this._firingCount = (this._firingCount + 1) || 1;
  498. for (var i = 0, len = listeners.length; i < len; i++) {
  499. var l = listeners[i];
  500. // off overwrites l.fn, so we need to copy fn to a var
  501. var fn = l.fn;
  502. if (l.once) {
  503. this.off(type, fn, l.ctx);
  504. }
  505. fn.call(l.ctx || this, event);
  506. }
  507. this._firingCount--;
  508. }
  509. }
  510. if (propagate) {
  511. // propagate the event to parents (set with addEventParent)
  512. this._propagateEvent(event);
  513. }
  514. return this;
  515. },
  516. // @method listens(type: String, propagate?: Boolean): Boolean
  517. // @method listens(type: String, fn: Function, context?: Object, propagate?: Boolean): Boolean
  518. // Returns `true` if a particular event type has any listeners attached to it.
  519. // The verification can optionally be propagated, it will return `true` if parents have the listener attached to it.
  520. listens: function (type, fn, context, propagate) {
  521. if (typeof type !== 'string') {
  522. console.warn('"string" type argument expected');
  523. }
  524. // we don't overwrite the input `fn` value, because we need to use it for propagation
  525. var _fn = fn;
  526. if (typeof fn !== 'function') {
  527. propagate = !!fn;
  528. _fn = undefined;
  529. context = undefined;
  530. }
  531. var listeners = this._events && this._events[type];
  532. if (listeners && listeners.length) {
  533. if (this._listens(type, _fn, context) !== false) {
  534. return true;
  535. }
  536. }
  537. if (propagate) {
  538. // also check parents for listeners if event propagates
  539. for (var id in this._eventParents) {
  540. if (this._eventParents[id].listens(type, fn, context, propagate)) { return true; }
  541. }
  542. }
  543. return false;
  544. },
  545. // returns the index (number) or false
  546. _listens: function (type, fn, context) {
  547. if (!this._events) {
  548. return false;
  549. }
  550. var listeners = this._events[type] || [];
  551. if (!fn) {
  552. return !!listeners.length;
  553. }
  554. if (context === this) {
  555. // Less memory footprint.
  556. context = undefined;
  557. }
  558. for (var i = 0, len = listeners.length; i < len; i++) {
  559. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  560. return i;
  561. }
  562. }
  563. return false;
  564. },
  565. // @method once(…): this
  566. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  567. once: function (types, fn, context) {
  568. // types can be a map of types/handlers
  569. if (typeof types === 'object') {
  570. for (var type in types) {
  571. // we don't process space-separated events here for performance;
  572. // it's a hot path since Layer uses the on(obj) syntax
  573. this._on(type, types[type], fn, true);
  574. }
  575. } else {
  576. // types can be a string of space-separated words
  577. types = splitWords(types);
  578. for (var i = 0, len = types.length; i < len; i++) {
  579. this._on(types[i], fn, context, true);
  580. }
  581. }
  582. return this;
  583. },
  584. // @method addEventParent(obj: Evented): this
  585. // Adds an event parent - an `Evented` that will receive propagated events
  586. addEventParent: function (obj) {
  587. this._eventParents = this._eventParents || {};
  588. this._eventParents[stamp(obj)] = obj;
  589. return this;
  590. },
  591. // @method removeEventParent(obj: Evented): this
  592. // Removes an event parent, so it will stop receiving propagated events
  593. removeEventParent: function (obj) {
  594. if (this._eventParents) {
  595. delete this._eventParents[stamp(obj)];
  596. }
  597. return this;
  598. },
  599. _propagateEvent: function (e) {
  600. for (var id in this._eventParents) {
  601. this._eventParents[id].fire(e.type, extend({
  602. layer: e.target,
  603. propagatedFrom: e.target
  604. }, e), true);
  605. }
  606. }
  607. };
  608. // aliases; we should ditch those eventually
  609. // @method addEventListener(…): this
  610. // Alias to [`on(…)`](#evented-on)
  611. Events.addEventListener = Events.on;
  612. // @method removeEventListener(…): this
  613. // Alias to [`off(…)`](#evented-off)
  614. // @method clearAllEventListeners(…): this
  615. // Alias to [`off()`](#evented-off)
  616. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  617. // @method addOneTimeEventListener(…): this
  618. // Alias to [`once(…)`](#evented-once)
  619. Events.addOneTimeEventListener = Events.once;
  620. // @method fireEvent(…): this
  621. // Alias to [`fire(…)`](#evented-fire)
  622. Events.fireEvent = Events.fire;
  623. // @method hasEventListeners(…): Boolean
  624. // Alias to [`listens(…)`](#evented-listens)
  625. Events.hasEventListeners = Events.listens;
  626. var Evented = Class.extend(Events);
  627. /*
  628. * @class Point
  629. * @aka L.Point
  630. *
  631. * Represents a point with `x` and `y` coordinates in pixels.
  632. *
  633. * @example
  634. *
  635. * ```js
  636. * var point = L.point(200, 300);
  637. * ```
  638. *
  639. * 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:
  640. *
  641. * ```js
  642. * map.panBy([200, 300]);
  643. * map.panBy(L.point(200, 300));
  644. * ```
  645. *
  646. * Note that `Point` does not inherit from Leaflet's `Class` object,
  647. * which means new classes can't inherit from it, and new methods
  648. * can't be added to it with the `include` function.
  649. */
  650. function Point(x, y, round) {
  651. // @property x: Number; The `x` coordinate of the point
  652. this.x = (round ? Math.round(x) : x);
  653. // @property y: Number; The `y` coordinate of the point
  654. this.y = (round ? Math.round(y) : y);
  655. }
  656. var trunc = Math.trunc || function (v) {
  657. return v > 0 ? Math.floor(v) : Math.ceil(v);
  658. };
  659. Point.prototype = {
  660. // @method clone(): Point
  661. // Returns a copy of the current point.
  662. clone: function () {
  663. return new Point(this.x, this.y);
  664. },
  665. // @method add(otherPoint: Point): Point
  666. // Returns the result of addition of the current and the given points.
  667. add: function (point) {
  668. // non-destructive, returns a new point
  669. return this.clone()._add(toPoint(point));
  670. },
  671. _add: function (point) {
  672. // destructive, used directly for performance in situations where it's safe to modify existing point
  673. this.x += point.x;
  674. this.y += point.y;
  675. return this;
  676. },
  677. // @method subtract(otherPoint: Point): Point
  678. // Returns the result of subtraction of the given point from the current.
  679. subtract: function (point) {
  680. return this.clone()._subtract(toPoint(point));
  681. },
  682. _subtract: function (point) {
  683. this.x -= point.x;
  684. this.y -= point.y;
  685. return this;
  686. },
  687. // @method divideBy(num: Number): Point
  688. // Returns the result of division of the current point by the given number.
  689. divideBy: function (num) {
  690. return this.clone()._divideBy(num);
  691. },
  692. _divideBy: function (num) {
  693. this.x /= num;
  694. this.y /= num;
  695. return this;
  696. },
  697. // @method multiplyBy(num: Number): Point
  698. // Returns the result of multiplication of the current point by the given number.
  699. multiplyBy: function (num) {
  700. return this.clone()._multiplyBy(num);
  701. },
  702. _multiplyBy: function (num) {
  703. this.x *= num;
  704. this.y *= num;
  705. return this;
  706. },
  707. // @method scaleBy(scale: Point): Point
  708. // Multiply each coordinate of the current point by each coordinate of
  709. // `scale`. In linear algebra terms, multiply the point by the
  710. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  711. // defined by `scale`.
  712. scaleBy: function (point) {
  713. return new Point(this.x * point.x, this.y * point.y);
  714. },
  715. // @method unscaleBy(scale: Point): Point
  716. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  717. // each coordinate of `scale`.
  718. unscaleBy: function (point) {
  719. return new Point(this.x / point.x, this.y / point.y);
  720. },
  721. // @method round(): Point
  722. // Returns a copy of the current point with rounded coordinates.
  723. round: function () {
  724. return this.clone()._round();
  725. },
  726. _round: function () {
  727. this.x = Math.round(this.x);
  728. this.y = Math.round(this.y);
  729. return this;
  730. },
  731. // @method floor(): Point
  732. // Returns a copy of the current point with floored coordinates (rounded down).
  733. floor: function () {
  734. return this.clone()._floor();
  735. },
  736. _floor: function () {
  737. this.x = Math.floor(this.x);
  738. this.y = Math.floor(this.y);
  739. return this;
  740. },
  741. // @method ceil(): Point
  742. // Returns a copy of the current point with ceiled coordinates (rounded up).
  743. ceil: function () {
  744. return this.clone()._ceil();
  745. },
  746. _ceil: function () {
  747. this.x = Math.ceil(this.x);
  748. this.y = Math.ceil(this.y);
  749. return this;
  750. },
  751. // @method trunc(): Point
  752. // Returns a copy of the current point with truncated coordinates (rounded towards zero).
  753. trunc: function () {
  754. return this.clone()._trunc();
  755. },
  756. _trunc: function () {
  757. this.x = trunc(this.x);
  758. this.y = trunc(this.y);
  759. return this;
  760. },
  761. // @method distanceTo(otherPoint: Point): Number
  762. // Returns the cartesian distance between the current and the given points.
  763. distanceTo: function (point) {
  764. point = toPoint(point);
  765. var x = point.x - this.x,
  766. y = point.y - this.y;
  767. return Math.sqrt(x * x + y * y);
  768. },
  769. // @method equals(otherPoint: Point): Boolean
  770. // Returns `true` if the given point has the same coordinates.
  771. equals: function (point) {
  772. point = toPoint(point);
  773. return point.x === this.x &&
  774. point.y === this.y;
  775. },
  776. // @method contains(otherPoint: Point): Boolean
  777. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  778. contains: function (point) {
  779. point = toPoint(point);
  780. return Math.abs(point.x) <= Math.abs(this.x) &&
  781. Math.abs(point.y) <= Math.abs(this.y);
  782. },
  783. // @method toString(): String
  784. // Returns a string representation of the point for debugging purposes.
  785. toString: function () {
  786. return 'Point(' +
  787. formatNum(this.x) + ', ' +
  788. formatNum(this.y) + ')';
  789. }
  790. };
  791. // @factory L.point(x: Number, y: Number, round?: Boolean)
  792. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  793. // @alternative
  794. // @factory L.point(coords: Number[])
  795. // Expects an array of the form `[x, y]` instead.
  796. // @alternative
  797. // @factory L.point(coords: Object)
  798. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  799. function toPoint(x, y, round) {
  800. if (x instanceof Point) {
  801. return x;
  802. }
  803. if (isArray(x)) {
  804. return new Point(x[0], x[1]);
  805. }
  806. if (x === undefined || x === null) {
  807. return x;
  808. }
  809. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  810. return new Point(x.x, x.y);
  811. }
  812. return new Point(x, y, round);
  813. }
  814. /*
  815. * @class Bounds
  816. * @aka L.Bounds
  817. *
  818. * Represents a rectangular area in pixel coordinates.
  819. *
  820. * @example
  821. *
  822. * ```js
  823. * var p1 = L.point(10, 10),
  824. * p2 = L.point(40, 60),
  825. * bounds = L.bounds(p1, p2);
  826. * ```
  827. *
  828. * 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:
  829. *
  830. * ```js
  831. * otherBounds.intersects([[10, 10], [40, 60]]);
  832. * ```
  833. *
  834. * Note that `Bounds` does not inherit from Leaflet's `Class` object,
  835. * which means new classes can't inherit from it, and new methods
  836. * can't be added to it with the `include` function.
  837. */
  838. function Bounds(a, b) {
  839. if (!a) { return; }
  840. var points = b ? [a, b] : a;
  841. for (var i = 0, len = points.length; i < len; i++) {
  842. this.extend(points[i]);
  843. }
  844. }
  845. Bounds.prototype = {
  846. // @method extend(point: Point): this
  847. // Extends the bounds to contain the given point.
  848. // @alternative
  849. // @method extend(otherBounds: Bounds): this
  850. // Extend the bounds to contain the given bounds
  851. extend: function (obj) {
  852. var min2, max2;
  853. if (!obj) { return this; }
  854. if (obj instanceof Point || typeof obj[0] === 'number' || 'x' in obj) {
  855. min2 = max2 = toPoint(obj);
  856. } else {
  857. obj = toBounds(obj);
  858. min2 = obj.min;
  859. max2 = obj.max;
  860. if (!min2 || !max2) { return this; }
  861. }
  862. // @property min: Point
  863. // The top left corner of the rectangle.
  864. // @property max: Point
  865. // The bottom right corner of the rectangle.
  866. if (!this.min && !this.max) {
  867. this.min = min2.clone();
  868. this.max = max2.clone();
  869. } else {
  870. this.min.x = Math.min(min2.x, this.min.x);
  871. this.max.x = Math.max(max2.x, this.max.x);
  872. this.min.y = Math.min(min2.y, this.min.y);
  873. this.max.y = Math.max(max2.y, this.max.y);
  874. }
  875. return this;
  876. },
  877. // @method getCenter(round?: Boolean): Point
  878. // Returns the center point of the bounds.
  879. getCenter: function (round) {
  880. return toPoint(
  881. (this.min.x + this.max.x) / 2,
  882. (this.min.y + this.max.y) / 2, round);
  883. },
  884. // @method getBottomLeft(): Point
  885. // Returns the bottom-left point of the bounds.
  886. getBottomLeft: function () {
  887. return toPoint(this.min.x, this.max.y);
  888. },
  889. // @method getTopRight(): Point
  890. // Returns the top-right point of the bounds.
  891. getTopRight: function () { // -> Point
  892. return toPoint(this.max.x, this.min.y);
  893. },
  894. // @method getTopLeft(): Point
  895. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  896. getTopLeft: function () {
  897. return this.min; // left, top
  898. },
  899. // @method getBottomRight(): Point
  900. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  901. getBottomRight: function () {
  902. return this.max; // right, bottom
  903. },
  904. // @method getSize(): Point
  905. // Returns the size of the given bounds
  906. getSize: function () {
  907. return this.max.subtract(this.min);
  908. },
  909. // @method contains(otherBounds: Bounds): Boolean
  910. // Returns `true` if the rectangle contains the given one.
  911. // @alternative
  912. // @method contains(point: Point): Boolean
  913. // Returns `true` if the rectangle contains the given point.
  914. contains: function (obj) {
  915. var min, max;
  916. if (typeof obj[0] === 'number' || obj instanceof Point) {
  917. obj = toPoint(obj);
  918. } else {
  919. obj = toBounds(obj);
  920. }
  921. if (obj instanceof Bounds) {
  922. min = obj.min;
  923. max = obj.max;
  924. } else {
  925. min = max = obj;
  926. }
  927. return (min.x >= this.min.x) &&
  928. (max.x <= this.max.x) &&
  929. (min.y >= this.min.y) &&
  930. (max.y <= this.max.y);
  931. },
  932. // @method intersects(otherBounds: Bounds): Boolean
  933. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  934. // intersect if they have at least one point in common.
  935. intersects: function (bounds) { // (Bounds) -> Boolean
  936. bounds = toBounds(bounds);
  937. var min = this.min,
  938. max = this.max,
  939. min2 = bounds.min,
  940. max2 = bounds.max,
  941. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  942. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  943. return xIntersects && yIntersects;
  944. },
  945. // @method overlaps(otherBounds: Bounds): Boolean
  946. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  947. // overlap if their intersection is an area.
  948. overlaps: function (bounds) { // (Bounds) -> Boolean
  949. bounds = toBounds(bounds);
  950. var min = this.min,
  951. max = this.max,
  952. min2 = bounds.min,
  953. max2 = bounds.max,
  954. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  955. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  956. return xOverlaps && yOverlaps;
  957. },
  958. // @method isValid(): Boolean
  959. // Returns `true` if the bounds are properly initialized.
  960. isValid: function () {
  961. return !!(this.min && this.max);
  962. },
  963. // @method pad(bufferRatio: Number): Bounds
  964. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  965. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  966. // Negative values will retract the bounds.
  967. pad: function (bufferRatio) {
  968. var min = this.min,
  969. max = this.max,
  970. heightBuffer = Math.abs(min.x - max.x) * bufferRatio,
  971. widthBuffer = Math.abs(min.y - max.y) * bufferRatio;
  972. return toBounds(
  973. toPoint(min.x - heightBuffer, min.y - widthBuffer),
  974. toPoint(max.x + heightBuffer, max.y + widthBuffer));
  975. },
  976. // @method equals(otherBounds: Bounds): Boolean
  977. // Returns `true` if the rectangle is equivalent to the given bounds.
  978. equals: function (bounds) {
  979. if (!bounds) { return false; }
  980. bounds = toBounds(bounds);
  981. return this.min.equals(bounds.getTopLeft()) &&
  982. this.max.equals(bounds.getBottomRight());
  983. },
  984. };
  985. // @factory L.bounds(corner1: Point, corner2: Point)
  986. // Creates a Bounds object from two corners coordinate pairs.
  987. // @alternative
  988. // @factory L.bounds(points: Point[])
  989. // Creates a Bounds object from the given array of points.
  990. function toBounds(a, b) {
  991. if (!a || a instanceof Bounds) {
  992. return a;
  993. }
  994. return new Bounds(a, b);
  995. }
  996. /*
  997. * @class LatLngBounds
  998. * @aka L.LatLngBounds
  999. *
  1000. * Represents a rectangular geographical area on a map.
  1001. *
  1002. * @example
  1003. *
  1004. * ```js
  1005. * var corner1 = L.latLng(40.712, -74.227),
  1006. * corner2 = L.latLng(40.774, -74.125),
  1007. * bounds = L.latLngBounds(corner1, corner2);
  1008. * ```
  1009. *
  1010. * 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:
  1011. *
  1012. * ```js
  1013. * map.fitBounds([
  1014. * [40.712, -74.227],
  1015. * [40.774, -74.125]
  1016. * ]);
  1017. * ```
  1018. *
  1019. * 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.
  1020. *
  1021. * Note that `LatLngBounds` does not inherit from Leaflet's `Class` object,
  1022. * which means new classes can't inherit from it, and new methods
  1023. * can't be added to it with the `include` function.
  1024. */
  1025. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  1026. if (!corner1) { return; }
  1027. var latlngs = corner2 ? [corner1, corner2] : corner1;
  1028. for (var i = 0, len = latlngs.length; i < len; i++) {
  1029. this.extend(latlngs[i]);
  1030. }
  1031. }
  1032. LatLngBounds.prototype = {
  1033. // @method extend(latlng: LatLng): this
  1034. // Extend the bounds to contain the given point
  1035. // @alternative
  1036. // @method extend(otherBounds: LatLngBounds): this
  1037. // Extend the bounds to contain the given bounds
  1038. extend: function (obj) {
  1039. var sw = this._southWest,
  1040. ne = this._northEast,
  1041. sw2, ne2;
  1042. if (obj instanceof LatLng) {
  1043. sw2 = obj;
  1044. ne2 = obj;
  1045. } else if (obj instanceof LatLngBounds) {
  1046. sw2 = obj._southWest;
  1047. ne2 = obj._northEast;
  1048. if (!sw2 || !ne2) { return this; }
  1049. } else {
  1050. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  1051. }
  1052. if (!sw && !ne) {
  1053. this._southWest = new LatLng(sw2.lat, sw2.lng);
  1054. this._northEast = new LatLng(ne2.lat, ne2.lng);
  1055. } else {
  1056. sw.lat = Math.min(sw2.lat, sw.lat);
  1057. sw.lng = Math.min(sw2.lng, sw.lng);
  1058. ne.lat = Math.max(ne2.lat, ne.lat);
  1059. ne.lng = Math.max(ne2.lng, ne.lng);
  1060. }
  1061. return this;
  1062. },
  1063. // @method pad(bufferRatio: Number): LatLngBounds
  1064. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  1065. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  1066. // Negative values will retract the bounds.
  1067. pad: function (bufferRatio) {
  1068. var sw = this._southWest,
  1069. ne = this._northEast,
  1070. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  1071. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  1072. return new LatLngBounds(
  1073. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  1074. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  1075. },
  1076. // @method getCenter(): LatLng
  1077. // Returns the center point of the bounds.
  1078. getCenter: function () {
  1079. return new LatLng(
  1080. (this._southWest.lat + this._northEast.lat) / 2,
  1081. (this._southWest.lng + this._northEast.lng) / 2);
  1082. },
  1083. // @method getSouthWest(): LatLng
  1084. // Returns the south-west point of the bounds.
  1085. getSouthWest: function () {
  1086. return this._southWest;
  1087. },
  1088. // @method getNorthEast(): LatLng
  1089. // Returns the north-east point of the bounds.
  1090. getNorthEast: function () {
  1091. return this._northEast;
  1092. },
  1093. // @method getNorthWest(): LatLng
  1094. // Returns the north-west point of the bounds.
  1095. getNorthWest: function () {
  1096. return new LatLng(this.getNorth(), this.getWest());
  1097. },
  1098. // @method getSouthEast(): LatLng
  1099. // Returns the south-east point of the bounds.
  1100. getSouthEast: function () {
  1101. return new LatLng(this.getSouth(), this.getEast());
  1102. },
  1103. // @method getWest(): Number
  1104. // Returns the west longitude of the bounds
  1105. getWest: function () {
  1106. return this._southWest.lng;
  1107. },
  1108. // @method getSouth(): Number
  1109. // Returns the south latitude of the bounds
  1110. getSouth: function () {
  1111. return this._southWest.lat;
  1112. },
  1113. // @method getEast(): Number
  1114. // Returns the east longitude of the bounds
  1115. getEast: function () {
  1116. return this._northEast.lng;
  1117. },
  1118. // @method getNorth(): Number
  1119. // Returns the north latitude of the bounds
  1120. getNorth: function () {
  1121. return this._northEast.lat;
  1122. },
  1123. // @method contains(otherBounds: LatLngBounds): Boolean
  1124. // Returns `true` if the rectangle contains the given one.
  1125. // @alternative
  1126. // @method contains (latlng: LatLng): Boolean
  1127. // Returns `true` if the rectangle contains the given point.
  1128. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1129. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1130. obj = toLatLng(obj);
  1131. } else {
  1132. obj = toLatLngBounds(obj);
  1133. }
  1134. var sw = this._southWest,
  1135. ne = this._northEast,
  1136. sw2, ne2;
  1137. if (obj instanceof LatLngBounds) {
  1138. sw2 = obj.getSouthWest();
  1139. ne2 = obj.getNorthEast();
  1140. } else {
  1141. sw2 = ne2 = obj;
  1142. }
  1143. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1144. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1145. },
  1146. // @method intersects(otherBounds: LatLngBounds): Boolean
  1147. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1148. intersects: function (bounds) {
  1149. bounds = toLatLngBounds(bounds);
  1150. var sw = this._southWest,
  1151. ne = this._northEast,
  1152. sw2 = bounds.getSouthWest(),
  1153. ne2 = bounds.getNorthEast(),
  1154. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1155. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1156. return latIntersects && lngIntersects;
  1157. },
  1158. // @method overlaps(otherBounds: LatLngBounds): Boolean
  1159. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1160. overlaps: function (bounds) {
  1161. bounds = toLatLngBounds(bounds);
  1162. var sw = this._southWest,
  1163. ne = this._northEast,
  1164. sw2 = bounds.getSouthWest(),
  1165. ne2 = bounds.getNorthEast(),
  1166. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1167. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1168. return latOverlaps && lngOverlaps;
  1169. },
  1170. // @method toBBoxString(): String
  1171. // 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.
  1172. toBBoxString: function () {
  1173. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1174. },
  1175. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1176. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.
  1177. equals: function (bounds, maxMargin) {
  1178. if (!bounds) { return false; }
  1179. bounds = toLatLngBounds(bounds);
  1180. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1181. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1182. },
  1183. // @method isValid(): Boolean
  1184. // Returns `true` if the bounds are properly initialized.
  1185. isValid: function () {
  1186. return !!(this._southWest && this._northEast);
  1187. }
  1188. };
  1189. // TODO International date line?
  1190. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1191. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1192. // @alternative
  1193. // @factory L.latLngBounds(latlngs: LatLng[])
  1194. // 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).
  1195. function toLatLngBounds(a, b) {
  1196. if (a instanceof LatLngBounds) {
  1197. return a;
  1198. }
  1199. return new LatLngBounds(a, b);
  1200. }
  1201. /* @class LatLng
  1202. * @aka L.LatLng
  1203. *
  1204. * Represents a geographical point with a certain latitude and longitude.
  1205. *
  1206. * @example
  1207. *
  1208. * ```
  1209. * var latlng = L.latLng(50.5, 30.5);
  1210. * ```
  1211. *
  1212. * 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:
  1213. *
  1214. * ```
  1215. * map.panTo([50, 30]);
  1216. * map.panTo({lon: 30, lat: 50});
  1217. * map.panTo({lat: 50, lng: 30});
  1218. * map.panTo(L.latLng(50, 30));
  1219. * ```
  1220. *
  1221. * Note that `LatLng` does not inherit from Leaflet's `Class` object,
  1222. * which means new classes can't inherit from it, and new methods
  1223. * can't be added to it with the `include` function.
  1224. */
  1225. function LatLng(lat, lng, alt) {
  1226. if (isNaN(lat) || isNaN(lng)) {
  1227. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1228. }
  1229. // @property lat: Number
  1230. // Latitude in degrees
  1231. this.lat = +lat;
  1232. // @property lng: Number
  1233. // Longitude in degrees
  1234. this.lng = +lng;
  1235. // @property alt: Number
  1236. // Altitude in meters (optional)
  1237. if (alt !== undefined) {
  1238. this.alt = +alt;
  1239. }
  1240. }
  1241. LatLng.prototype = {
  1242. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1243. // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.
  1244. equals: function (obj, maxMargin) {
  1245. if (!obj) { return false; }
  1246. obj = toLatLng(obj);
  1247. var margin = Math.max(
  1248. Math.abs(this.lat - obj.lat),
  1249. Math.abs(this.lng - obj.lng));
  1250. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1251. },
  1252. // @method toString(): String
  1253. // Returns a string representation of the point (for debugging purposes).
  1254. toString: function (precision) {
  1255. return 'LatLng(' +
  1256. formatNum(this.lat, precision) + ', ' +
  1257. formatNum(this.lng, precision) + ')';
  1258. },
  1259. // @method distanceTo(otherLatLng: LatLng): Number
  1260. // Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).
  1261. distanceTo: function (other) {
  1262. return Earth.distance(this, toLatLng(other));
  1263. },
  1264. // @method wrap(): LatLng
  1265. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1266. wrap: function () {
  1267. return Earth.wrapLatLng(this);
  1268. },
  1269. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1270. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1271. toBounds: function (sizeInMeters) {
  1272. var latAccuracy = 180 * sizeInMeters / 40075017,
  1273. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1274. return toLatLngBounds(
  1275. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1276. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1277. },
  1278. clone: function () {
  1279. return new LatLng(this.lat, this.lng, this.alt);
  1280. }
  1281. };
  1282. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1283. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1284. // @alternative
  1285. // @factory L.latLng(coords: Array): LatLng
  1286. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1287. // @alternative
  1288. // @factory L.latLng(coords: Object): LatLng
  1289. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1290. function toLatLng(a, b, c) {
  1291. if (a instanceof LatLng) {
  1292. return a;
  1293. }
  1294. if (isArray(a) && typeof a[0] !== 'object') {
  1295. if (a.length === 3) {
  1296. return new LatLng(a[0], a[1], a[2]);
  1297. }
  1298. if (a.length === 2) {
  1299. return new LatLng(a[0], a[1]);
  1300. }
  1301. return null;
  1302. }
  1303. if (a === undefined || a === null) {
  1304. return a;
  1305. }
  1306. if (typeof a === 'object' && 'lat' in a) {
  1307. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1308. }
  1309. if (b === undefined) {
  1310. return null;
  1311. }
  1312. return new LatLng(a, b, c);
  1313. }
  1314. /*
  1315. * @namespace CRS
  1316. * @crs L.CRS.Base
  1317. * Object that defines coordinate reference systems for projecting
  1318. * geographical points into pixel (screen) coordinates and back (and to
  1319. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1320. * [spatial reference system](https://en.wikipedia.org/wiki/Spatial_reference_system).
  1321. *
  1322. * Leaflet defines the most usual CRSs by default. If you want to use a
  1323. * CRS not defined by default, take a look at the
  1324. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1325. *
  1326. * Note that the CRS instances do not inherit from Leaflet's `Class` object,
  1327. * and can't be instantiated. Also, new classes can't inherit from them,
  1328. * and methods can't be added to them with the `include` function.
  1329. */
  1330. var CRS = {
  1331. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1332. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1333. latLngToPoint: function (latlng, zoom) {
  1334. var projectedPoint = this.projection.project(latlng),
  1335. scale = this.scale(zoom);
  1336. return this.transformation._transform(projectedPoint, scale);
  1337. },
  1338. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1339. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1340. // zoom into geographical coordinates.
  1341. pointToLatLng: function (point, zoom) {
  1342. var scale = this.scale(zoom),
  1343. untransformedPoint = this.transformation.untransform(point, scale);
  1344. return this.projection.unproject(untransformedPoint);
  1345. },
  1346. // @method project(latlng: LatLng): Point
  1347. // Projects geographical coordinates into coordinates in units accepted for
  1348. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1349. project: function (latlng) {
  1350. return this.projection.project(latlng);
  1351. },
  1352. // @method unproject(point: Point): LatLng
  1353. // Given a projected coordinate returns the corresponding LatLng.
  1354. // The inverse of `project`.
  1355. unproject: function (point) {
  1356. return this.projection.unproject(point);
  1357. },
  1358. // @method scale(zoom: Number): Number
  1359. // Returns the scale used when transforming projected coordinates into
  1360. // pixel coordinates for a particular zoom. For example, it returns
  1361. // `256 * 2^zoom` for Mercator-based CRS.
  1362. scale: function (zoom) {
  1363. return 256 * Math.pow(2, zoom);
  1364. },
  1365. // @method zoom(scale: Number): Number
  1366. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1367. // factor of `scale`.
  1368. zoom: function (scale) {
  1369. return Math.log(scale / 256) / Math.LN2;
  1370. },
  1371. // @method getProjectedBounds(zoom: Number): Bounds
  1372. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1373. getProjectedBounds: function (zoom) {
  1374. if (this.infinite) { return null; }
  1375. var b = this.projection.bounds,
  1376. s = this.scale(zoom),
  1377. min = this.transformation.transform(b.min, s),
  1378. max = this.transformation.transform(b.max, s);
  1379. return new Bounds(min, max);
  1380. },
  1381. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1382. // Returns the distance between two geographical coordinates.
  1383. // @property code: String
  1384. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1385. //
  1386. // @property wrapLng: Number[]
  1387. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1388. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1389. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1390. //
  1391. // @property wrapLat: Number[]
  1392. // Like `wrapLng`, but for the latitude (vertical) axis.
  1393. // wrapLng: [min, max],
  1394. // wrapLat: [min, max],
  1395. // @property infinite: Boolean
  1396. // If true, the coordinate space will be unbounded (infinite in both axes)
  1397. infinite: false,
  1398. // @method wrapLatLng(latlng: LatLng): LatLng
  1399. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1400. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1401. wrapLatLng: function (latlng) {
  1402. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1403. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1404. alt = latlng.alt;
  1405. return new LatLng(lat, lng, alt);
  1406. },
  1407. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1408. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1409. // that its center is within the CRS's bounds.
  1410. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1411. wrapLatLngBounds: function (bounds) {
  1412. var center = bounds.getCenter(),
  1413. newCenter = this.wrapLatLng(center),
  1414. latShift = center.lat - newCenter.lat,
  1415. lngShift = center.lng - newCenter.lng;
  1416. if (latShift === 0 && lngShift === 0) {
  1417. return bounds;
  1418. }
  1419. var sw = bounds.getSouthWest(),
  1420. ne = bounds.getNorthEast(),
  1421. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1422. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1423. return new LatLngBounds(newSw, newNe);
  1424. }
  1425. };
  1426. /*
  1427. * @namespace CRS
  1428. * @crs L.CRS.Earth
  1429. *
  1430. * Serves as the base for CRS that are global such that they cover the earth.
  1431. * Can only be used as the base for other CRS and cannot be used directly,
  1432. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1433. * meters.
  1434. */
  1435. var Earth = extend({}, CRS, {
  1436. wrapLng: [-180, 180],
  1437. // Mean Earth Radius, as recommended for use by
  1438. // the International Union of Geodesy and Geophysics,
  1439. // see https://rosettacode.org/wiki/Haversine_formula
  1440. R: 6371000,
  1441. // distance between two geographical points using spherical law of cosines approximation
  1442. distance: function (latlng1, latlng2) {
  1443. var rad = Math.PI / 180,
  1444. lat1 = latlng1.lat * rad,
  1445. lat2 = latlng2.lat * rad,
  1446. sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
  1447. sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
  1448. a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
  1449. c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1450. return this.R * c;
  1451. }
  1452. });
  1453. /*
  1454. * @namespace Projection
  1455. * @projection L.Projection.SphericalMercator
  1456. *
  1457. * Spherical Mercator projection — the most common projection for online maps,
  1458. * used by almost all free and commercial tile providers. Assumes that Earth is
  1459. * a sphere. Used by the `EPSG:3857` CRS.
  1460. */
  1461. var earthRadius = 6378137;
  1462. var SphericalMercator = {
  1463. R: earthRadius,
  1464. MAX_LATITUDE: 85.0511287798,
  1465. project: function (latlng) {
  1466. var d = Math.PI / 180,
  1467. max = this.MAX_LATITUDE,
  1468. lat = Math.max(Math.min(max, latlng.lat), -max),
  1469. sin = Math.sin(lat * d);
  1470. return new Point(
  1471. this.R * latlng.lng * d,
  1472. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1473. },
  1474. unproject: function (point) {
  1475. var d = 180 / Math.PI;
  1476. return new LatLng(
  1477. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1478. point.x * d / this.R);
  1479. },
  1480. bounds: (function () {
  1481. var d = earthRadius * Math.PI;
  1482. return new Bounds([-d, -d], [d, d]);
  1483. })()
  1484. };
  1485. /*
  1486. * @class Transformation
  1487. * @aka L.Transformation
  1488. *
  1489. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1490. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1491. * the reverse. Used by Leaflet in its projections code.
  1492. *
  1493. * @example
  1494. *
  1495. * ```js
  1496. * var transformation = L.transformation(2, 5, -1, 10),
  1497. * p = L.point(1, 2),
  1498. * p2 = transformation.transform(p), // L.point(7, 8)
  1499. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1500. * ```
  1501. */
  1502. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1503. // Creates a `Transformation` object with the given coefficients.
  1504. function Transformation(a, b, c, d) {
  1505. if (isArray(a)) {
  1506. // use array properties
  1507. this._a = a[0];
  1508. this._b = a[1];
  1509. this._c = a[2];
  1510. this._d = a[3];
  1511. return;
  1512. }
  1513. this._a = a;
  1514. this._b = b;
  1515. this._c = c;
  1516. this._d = d;
  1517. }
  1518. Transformation.prototype = {
  1519. // @method transform(point: Point, scale?: Number): Point
  1520. // Returns a transformed point, optionally multiplied by the given scale.
  1521. // Only accepts actual `L.Point` instances, not arrays.
  1522. transform: function (point, scale) { // (Point, Number) -> Point
  1523. return this._transform(point.clone(), scale);
  1524. },
  1525. // destructive transform (faster)
  1526. _transform: function (point, scale) {
  1527. scale = scale || 1;
  1528. point.x = scale * (this._a * point.x + this._b);
  1529. point.y = scale * (this._c * point.y + this._d);
  1530. return point;
  1531. },
  1532. // @method untransform(point: Point, scale?: Number): Point
  1533. // Returns the reverse transformation of the given point, optionally divided
  1534. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1535. untransform: function (point, scale) {
  1536. scale = scale || 1;
  1537. return new Point(
  1538. (point.x / scale - this._b) / this._a,
  1539. (point.y / scale - this._d) / this._c);
  1540. }
  1541. };
  1542. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1543. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1544. // Instantiates a Transformation object with the given coefficients.
  1545. // @alternative
  1546. // @factory L.transformation(coefficients: Array): Transformation
  1547. // Expects an coefficients array of the form
  1548. // `[a: Number, b: Number, c: Number, d: Number]`.
  1549. function toTransformation(a, b, c, d) {
  1550. return new Transformation(a, b, c, d);
  1551. }
  1552. /*
  1553. * @namespace CRS
  1554. * @crs L.CRS.EPSG3857
  1555. *
  1556. * The most common CRS for online maps, used by almost all free and commercial
  1557. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1558. * Map's `crs` option.
  1559. */
  1560. var EPSG3857 = extend({}, Earth, {
  1561. code: 'EPSG:3857',
  1562. projection: SphericalMercator,
  1563. transformation: (function () {
  1564. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1565. return toTransformation(scale, 0.5, -scale, 0.5);
  1566. }())
  1567. });
  1568. var EPSG900913 = extend({}, EPSG3857, {
  1569. code: 'EPSG:900913'
  1570. });
  1571. // @namespace SVG; @section
  1572. // There are several static functions which can be called without instantiating L.SVG:
  1573. // @function create(name: String): SVGElement
  1574. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1575. // corresponding to the class name passed. For example, using 'line' will return
  1576. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1577. function svgCreate(name) {
  1578. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1579. }
  1580. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1581. // Generates a SVG path string for multiple rings, with each ring turning
  1582. // into "M..L..L.." instructions
  1583. function pointsToPath(rings, closed) {
  1584. var str = '',
  1585. i, j, len, len2, points, p;
  1586. for (i = 0, len = rings.length; i < len; i++) {
  1587. points = rings[i];
  1588. for (j = 0, len2 = points.length; j < len2; j++) {
  1589. p = points[j];
  1590. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1591. }
  1592. // closes the ring for polygons; "x" is VML syntax
  1593. str += closed ? (Browser.svg ? 'z' : 'x') : '';
  1594. }
  1595. // SVG complains about empty path strings
  1596. return str || 'M0 0';
  1597. }
  1598. /*
  1599. * @namespace Browser
  1600. * @aka L.Browser
  1601. *
  1602. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1603. *
  1604. * @example
  1605. *
  1606. * ```js
  1607. * if (L.Browser.ielt9) {
  1608. * alert('Upgrade your browser, dude!');
  1609. * }
  1610. * ```
  1611. */
  1612. var style = document.documentElement.style;
  1613. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1614. var ie = 'ActiveXObject' in window;
  1615. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1616. var ielt9 = ie && !document.addEventListener;
  1617. // @property edge: Boolean; `true` for the Edge web browser.
  1618. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1619. // @property webkit: Boolean;
  1620. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1621. var webkit = userAgentContains('webkit');
  1622. // @property android: Boolean
  1623. // **Deprecated.** `true` for any browser running on an Android platform.
  1624. var android = userAgentContains('android');
  1625. // @property android23: Boolean; **Deprecated.** `true` for browsers running on Android 2 or Android 3.
  1626. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1627. /* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */
  1628. var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit
  1629. // @property androidStock: Boolean; **Deprecated.** `true` for the Android stock browser (i.e. not Chrome)
  1630. var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);
  1631. // @property opera: Boolean; `true` for the Opera browser
  1632. var opera = !!window.opera;
  1633. // @property chrome: Boolean; `true` for the Chrome browser.
  1634. var chrome = !edge && userAgentContains('chrome');
  1635. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1636. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1637. // @property safari: Boolean; `true` for the Safari browser.
  1638. var safari = !chrome && userAgentContains('safari');
  1639. var phantom = userAgentContains('phantom');
  1640. // @property opera12: Boolean
  1641. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1642. var opera12 = 'OTransition' in style;
  1643. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1644. var win = navigator.platform.indexOf('Win') === 0;
  1645. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1646. var ie3d = ie && ('transition' in style);
  1647. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1648. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1649. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1650. var gecko3d = 'MozPerspective' in style;
  1651. // @property any3d: Boolean
  1652. // `true` for all browsers supporting CSS transforms.
  1653. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1654. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1655. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1656. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1657. var mobileWebkit = mobile && webkit;
  1658. // @property mobileWebkit3d: Boolean
  1659. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1660. var mobileWebkit3d = mobile && webkit3d;
  1661. // @property msPointer: Boolean
  1662. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1663. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1664. // @property pointer: Boolean
  1665. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1666. var pointer = !!(window.PointerEvent || msPointer);
  1667. // @property touchNative: Boolean
  1668. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1669. // **This does not necessarily mean** that the browser is running in a computer with
  1670. // a touchscreen, it only means that the browser is capable of understanding
  1671. // touch events.
  1672. var touchNative = 'ontouchstart' in window || !!window.TouchEvent;
  1673. // @property touch: Boolean
  1674. // `true` for all browsers supporting either [touch](#browser-touch) or [pointer](#browser-pointer) events.
  1675. // Note: pointer events will be preferred (if available), and processed for all `touch*` listeners.
  1676. var touch = !window.L_NO_TOUCH && (touchNative || pointer);
  1677. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1678. var mobileOpera = mobile && opera;
  1679. // @property mobileGecko: Boolean
  1680. // `true` for gecko-based browsers running in a mobile device.
  1681. var mobileGecko = mobile && gecko;
  1682. // @property retina: Boolean
  1683. // `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%.
  1684. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1685. // @property passiveEvents: Boolean
  1686. // `true` for browsers that support passive events.
  1687. var passiveEvents = (function () {
  1688. var supportsPassiveOption = false;
  1689. try {
  1690. var opts = Object.defineProperty({}, 'passive', {
  1691. get: function () { // eslint-disable-line getter-return
  1692. supportsPassiveOption = true;
  1693. }
  1694. });
  1695. window.addEventListener('testPassiveEventSupport', falseFn, opts);
  1696. window.removeEventListener('testPassiveEventSupport', falseFn, opts);
  1697. } catch (e) {
  1698. // Errors can safely be ignored since this is only a browser support test.
  1699. }
  1700. return supportsPassiveOption;
  1701. }());
  1702. // @property canvas: Boolean
  1703. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1704. var canvas$1 = (function () {
  1705. return !!document.createElement('canvas').getContext;
  1706. }());
  1707. // @property svg: Boolean
  1708. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1709. var svg$1 = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1710. var inlineSvg = !!svg$1 && (function () {
  1711. var div = document.createElement('div');
  1712. div.innerHTML = '<svg/>';
  1713. return (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg';
  1714. })();
  1715. // @property vml: Boolean
  1716. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1717. var vml = !svg$1 && (function () {
  1718. try {
  1719. var div = document.createElement('div');
  1720. div.innerHTML = '<v:shape adj="1"/>';
  1721. var shape = div.firstChild;
  1722. shape.style.behavior = 'url(#default#VML)';
  1723. return shape && (typeof shape.adj === 'object');
  1724. } catch (e) {
  1725. return false;
  1726. }
  1727. }());
  1728. // @property mac: Boolean; `true` when the browser is running in a Mac platform
  1729. var mac = navigator.platform.indexOf('Mac') === 0;
  1730. // @property mac: Boolean; `true` when the browser is running in a Linux platform
  1731. var linux = navigator.platform.indexOf('Linux') === 0;
  1732. function userAgentContains(str) {
  1733. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1734. }
  1735. var Browser = {
  1736. ie: ie,
  1737. ielt9: ielt9,
  1738. edge: edge,
  1739. webkit: webkit,
  1740. android: android,
  1741. android23: android23,
  1742. androidStock: androidStock,
  1743. opera: opera,
  1744. chrome: chrome,
  1745. gecko: gecko,
  1746. safari: safari,
  1747. phantom: phantom,
  1748. opera12: opera12,
  1749. win: win,
  1750. ie3d: ie3d,
  1751. webkit3d: webkit3d,
  1752. gecko3d: gecko3d,
  1753. any3d: any3d,
  1754. mobile: mobile,
  1755. mobileWebkit: mobileWebkit,
  1756. mobileWebkit3d: mobileWebkit3d,
  1757. msPointer: msPointer,
  1758. pointer: pointer,
  1759. touch: touch,
  1760. touchNative: touchNative,
  1761. mobileOpera: mobileOpera,
  1762. mobileGecko: mobileGecko,
  1763. retina: retina,
  1764. passiveEvents: passiveEvents,
  1765. canvas: canvas$1,
  1766. svg: svg$1,
  1767. vml: vml,
  1768. inlineSvg: inlineSvg,
  1769. mac: mac,
  1770. linux: linux
  1771. };
  1772. /*
  1773. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1774. */
  1775. var POINTER_DOWN = Browser.msPointer ? 'MSPointerDown' : 'pointerdown';
  1776. var POINTER_MOVE = Browser.msPointer ? 'MSPointerMove' : 'pointermove';
  1777. var POINTER_UP = Browser.msPointer ? 'MSPointerUp' : 'pointerup';
  1778. var POINTER_CANCEL = Browser.msPointer ? 'MSPointerCancel' : 'pointercancel';
  1779. var pEvent = {
  1780. touchstart : POINTER_DOWN,
  1781. touchmove : POINTER_MOVE,
  1782. touchend : POINTER_UP,
  1783. touchcancel : POINTER_CANCEL
  1784. };
  1785. var handle = {
  1786. touchstart : _onPointerStart,
  1787. touchmove : _handlePointer,
  1788. touchend : _handlePointer,
  1789. touchcancel : _handlePointer
  1790. };
  1791. var _pointers = {};
  1792. var _pointerDocListener = false;
  1793. // Provides a touch events wrapper for (ms)pointer events.
  1794. // ref https://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1795. function addPointerListener(obj, type, handler) {
  1796. if (type === 'touchstart') {
  1797. _addPointerDocListener();
  1798. }
  1799. if (!handle[type]) {
  1800. console.warn('wrong event specified:', type);
  1801. return L.Util.falseFn;
  1802. }
  1803. handler = handle[type].bind(this, handler);
  1804. obj.addEventListener(pEvent[type], handler, false);
  1805. return handler;
  1806. }
  1807. function removePointerListener(obj, type, handler) {
  1808. if (!pEvent[type]) {
  1809. console.warn('wrong event specified:', type);
  1810. return;
  1811. }
  1812. obj.removeEventListener(pEvent[type], handler, false);
  1813. }
  1814. function _globalPointerDown(e) {
  1815. _pointers[e.pointerId] = e;
  1816. }
  1817. function _globalPointerMove(e) {
  1818. if (_pointers[e.pointerId]) {
  1819. _pointers[e.pointerId] = e;
  1820. }
  1821. }
  1822. function _globalPointerUp(e) {
  1823. delete _pointers[e.pointerId];
  1824. }
  1825. function _addPointerDocListener() {
  1826. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1827. if (!_pointerDocListener) {
  1828. // we listen document as any drags that end by moving the touch off the screen get fired there
  1829. document.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1830. document.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1831. document.addEventListener(POINTER_UP, _globalPointerUp, true);
  1832. document.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1833. _pointerDocListener = true;
  1834. }
  1835. }
  1836. function _handlePointer(handler, e) {
  1837. if (e.pointerType === (e.MSPOINTER_TYPE_MOUSE || 'mouse')) { return; }
  1838. e.touches = [];
  1839. for (var i in _pointers) {
  1840. e.touches.push(_pointers[i]);
  1841. }
  1842. e.changedTouches = [e];
  1843. handler(e);
  1844. }
  1845. function _onPointerStart(handler, e) {
  1846. // IE10 specific: MsTouch needs preventDefault. See #2000
  1847. if (e.MSPOINTER_TYPE_TOUCH && e.pointerType === e.MSPOINTER_TYPE_TOUCH) {
  1848. preventDefault(e);
  1849. }
  1850. _handlePointer(handler, e);
  1851. }
  1852. /*
  1853. * Extends the event handling code with double tap support for mobile browsers.
  1854. *
  1855. * Note: currently most browsers fire native dblclick, with only a few exceptions
  1856. * (see https://github.com/Leaflet/Leaflet/issues/7012#issuecomment-595087386)
  1857. */
  1858. function makeDblclick(event) {
  1859. // in modern browsers `type` cannot be just overridden:
  1860. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only
  1861. var newEvent = {},
  1862. prop, i;
  1863. for (i in event) {
  1864. prop = event[i];
  1865. newEvent[i] = prop && prop.bind ? prop.bind(event) : prop;
  1866. }
  1867. event = newEvent;
  1868. newEvent.type = 'dblclick';
  1869. newEvent.detail = 2;
  1870. newEvent.isTrusted = false;
  1871. newEvent._simulated = true; // for debug purposes
  1872. return newEvent;
  1873. }
  1874. var delay = 200;
  1875. function addDoubleTapListener(obj, handler) {
  1876. // Most browsers handle double tap natively
  1877. obj.addEventListener('dblclick', handler);
  1878. // On some platforms the browser doesn't fire native dblclicks for touch events.
  1879. // It seems that in all such cases `detail` property of `click` event is always `1`.
  1880. // So here we rely on that fact to avoid excessive 'dblclick' simulation when not needed.
  1881. var last = 0,
  1882. detail;
  1883. function simDblclick(e) {
  1884. if (e.detail !== 1) {
  1885. detail = e.detail; // keep in sync to avoid false dblclick in some cases
  1886. return;
  1887. }
  1888. if (e.pointerType === 'mouse' ||
  1889. (e.sourceCapabilities && !e.sourceCapabilities.firesTouchEvents)) {
  1890. return;
  1891. }
  1892. // When clicking on an <input>, the browser generates a click on its
  1893. // <label> (and vice versa) triggering two clicks in quick succession.
  1894. // This ignores clicks on elements which are a label with a 'for'
  1895. // attribute (or children of such a label), but not children of
  1896. // a <input>.
  1897. var path = getPropagationPath(e);
  1898. if (path.some(function (el) {
  1899. return el instanceof HTMLLabelElement && el.attributes.for;
  1900. }) &&
  1901. !path.some(function (el) {
  1902. return (
  1903. el instanceof HTMLInputElement ||
  1904. el instanceof HTMLSelectElement
  1905. );
  1906. })
  1907. ) {
  1908. return;
  1909. }
  1910. var now = Date.now();
  1911. if (now - last <= delay) {
  1912. detail++;
  1913. if (detail === 2) {
  1914. handler(makeDblclick(e));
  1915. }
  1916. } else {
  1917. detail = 1;
  1918. }
  1919. last = now;
  1920. }
  1921. obj.addEventListener('click', simDblclick);
  1922. return {
  1923. dblclick: handler,
  1924. simDblclick: simDblclick
  1925. };
  1926. }
  1927. function removeDoubleTapListener(obj, handlers) {
  1928. obj.removeEventListener('dblclick', handlers.dblclick);
  1929. obj.removeEventListener('click', handlers.simDblclick);
  1930. }
  1931. /*
  1932. * @namespace DomUtil
  1933. *
  1934. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1935. * tree, used by Leaflet internally.
  1936. *
  1937. * Most functions expecting or returning a `HTMLElement` also work for
  1938. * SVG elements. The only difference is that classes refer to CSS classes
  1939. * in HTML and SVG classes in SVG.
  1940. */
  1941. // @property TRANSFORM: String
  1942. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  1943. var TRANSFORM = testProp(
  1944. ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1945. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1946. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1947. // @property TRANSITION: String
  1948. // Vendor-prefixed transition style name.
  1949. var TRANSITION = testProp(
  1950. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1951. // @property TRANSITION_END: String
  1952. // Vendor-prefixed transitionend event name.
  1953. var TRANSITION_END =
  1954. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  1955. // @function get(id: String|HTMLElement): HTMLElement
  1956. // Returns an element given its DOM id, or returns the element itself
  1957. // if it was passed directly.
  1958. function get(id) {
  1959. return typeof id === 'string' ? document.getElementById(id) : id;
  1960. }
  1961. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1962. // Returns the value for a certain style attribute on an element,
  1963. // including computed values or values set through CSS.
  1964. function getStyle(el, style) {
  1965. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1966. if ((!value || value === 'auto') && document.defaultView) {
  1967. var css = document.defaultView.getComputedStyle(el, null);
  1968. value = css ? css[style] : null;
  1969. }
  1970. return value === 'auto' ? null : value;
  1971. }
  1972. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1973. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1974. function create$1(tagName, className, container) {
  1975. var el = document.createElement(tagName);
  1976. el.className = className || '';
  1977. if (container) {
  1978. container.appendChild(el);
  1979. }
  1980. return el;
  1981. }
  1982. // @function remove(el: HTMLElement)
  1983. // Removes `el` from its parent element
  1984. function remove(el) {
  1985. var parent = el.parentNode;
  1986. if (parent) {
  1987. parent.removeChild(el);
  1988. }
  1989. }
  1990. // @function empty(el: HTMLElement)
  1991. // Removes all of `el`'s children elements from `el`
  1992. function empty(el) {
  1993. while (el.firstChild) {
  1994. el.removeChild(el.firstChild);
  1995. }
  1996. }
  1997. // @function toFront(el: HTMLElement)
  1998. // Makes `el` the last child of its parent, so it renders in front of the other children.
  1999. function toFront(el) {
  2000. var parent = el.parentNode;
  2001. if (parent && parent.lastChild !== el) {
  2002. parent.appendChild(el);
  2003. }
  2004. }
  2005. // @function toBack(el: HTMLElement)
  2006. // Makes `el` the first child of its parent, so it renders behind the other children.
  2007. function toBack(el) {
  2008. var parent = el.parentNode;
  2009. if (parent && parent.firstChild !== el) {
  2010. parent.insertBefore(el, parent.firstChild);
  2011. }
  2012. }
  2013. // @function hasClass(el: HTMLElement, name: String): Boolean
  2014. // Returns `true` if the element's class attribute contains `name`.
  2015. function hasClass(el, name) {
  2016. if (el.classList !== undefined) {
  2017. return el.classList.contains(name);
  2018. }
  2019. var className = getClass(el);
  2020. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  2021. }
  2022. // @function addClass(el: HTMLElement, name: String)
  2023. // Adds `name` to the element's class attribute.
  2024. function addClass(el, name) {
  2025. if (el.classList !== undefined) {
  2026. var classes = splitWords(name);
  2027. for (var i = 0, len = classes.length; i < len; i++) {
  2028. el.classList.add(classes[i]);
  2029. }
  2030. } else if (!hasClass(el, name)) {
  2031. var className = getClass(el);
  2032. setClass(el, (className ? className + ' ' : '') + name);
  2033. }
  2034. }
  2035. // @function removeClass(el: HTMLElement, name: String)
  2036. // Removes `name` from the element's class attribute.
  2037. function removeClass(el, name) {
  2038. if (el.classList !== undefined) {
  2039. el.classList.remove(name);
  2040. } else {
  2041. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  2042. }
  2043. }
  2044. // @function setClass(el: HTMLElement, name: String)
  2045. // Sets the element's class.
  2046. function setClass(el, name) {
  2047. if (el.className.baseVal === undefined) {
  2048. el.className = name;
  2049. } else {
  2050. // in case of SVG element
  2051. el.className.baseVal = name;
  2052. }
  2053. }
  2054. // @function getClass(el: HTMLElement): String
  2055. // Returns the element's class.
  2056. function getClass(el) {
  2057. // Check if the element is an SVGElementInstance and use the correspondingElement instead
  2058. // (Required for linked SVG elements in IE11.)
  2059. if (el.correspondingElement) {
  2060. el = el.correspondingElement;
  2061. }
  2062. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  2063. }
  2064. // @function setOpacity(el: HTMLElement, opacity: Number)
  2065. // Set the opacity of an element (including old IE support).
  2066. // `opacity` must be a number from `0` to `1`.
  2067. function setOpacity(el, value) {
  2068. if ('opacity' in el.style) {
  2069. el.style.opacity = value;
  2070. } else if ('filter' in el.style) {
  2071. _setOpacityIE(el, value);
  2072. }
  2073. }
  2074. function _setOpacityIE(el, value) {
  2075. var filter = false,
  2076. filterName = 'DXImageTransform.Microsoft.Alpha';
  2077. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  2078. try {
  2079. filter = el.filters.item(filterName);
  2080. } catch (e) {
  2081. // don't set opacity to 1 if we haven't already set an opacity,
  2082. // it isn't needed and breaks transparent pngs.
  2083. if (value === 1) { return; }
  2084. }
  2085. value = Math.round(value * 100);
  2086. if (filter) {
  2087. filter.Enabled = (value !== 100);
  2088. filter.Opacity = value;
  2089. } else {
  2090. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  2091. }
  2092. }
  2093. // @function testProp(props: String[]): String|false
  2094. // Goes through the array of style names and returns the first name
  2095. // that is a valid style name for an element. If no such name is found,
  2096. // it returns false. Useful for vendor-prefixed styles like `transform`.
  2097. function testProp(props) {
  2098. var style = document.documentElement.style;
  2099. for (var i = 0; i < props.length; i++) {
  2100. if (props[i] in style) {
  2101. return props[i];
  2102. }
  2103. }
  2104. return false;
  2105. }
  2106. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  2107. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  2108. // and optionally scaled by `scale`. Does not have an effect if the
  2109. // browser doesn't support 3D CSS transforms.
  2110. function setTransform(el, offset, scale) {
  2111. var pos = offset || new Point(0, 0);
  2112. el.style[TRANSFORM] =
  2113. (Browser.ie3d ?
  2114. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2115. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2116. (scale ? ' scale(' + scale + ')' : '');
  2117. }
  2118. // @function setPosition(el: HTMLElement, position: Point)
  2119. // Sets the position of `el` to coordinates specified by `position`,
  2120. // using CSS translate or top/left positioning depending on the browser
  2121. // (used by Leaflet internally to position its layers).
  2122. function setPosition(el, point) {
  2123. /*eslint-disable */
  2124. el._leaflet_pos = point;
  2125. /* eslint-enable */
  2126. if (Browser.any3d) {
  2127. setTransform(el, point);
  2128. } else {
  2129. el.style.left = point.x + 'px';
  2130. el.style.top = point.y + 'px';
  2131. }
  2132. }
  2133. // @function getPosition(el: HTMLElement): Point
  2134. // Returns the coordinates of an element previously positioned with setPosition.
  2135. function getPosition(el) {
  2136. // this method is only used for elements previously positioned using setPosition,
  2137. // so it's safe to cache the position for performance
  2138. return el._leaflet_pos || new Point(0, 0);
  2139. }
  2140. // @function disableTextSelection()
  2141. // Prevents the user from generating `selectstart` DOM events, usually generated
  2142. // when the user drags the mouse through a page with text. Used internally
  2143. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2144. // the map. Affects drag interactions on the whole document.
  2145. // @function enableTextSelection()
  2146. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2147. var disableTextSelection;
  2148. var enableTextSelection;
  2149. var _userSelect;
  2150. if ('onselectstart' in document) {
  2151. disableTextSelection = function () {
  2152. on(window, 'selectstart', preventDefault);
  2153. };
  2154. enableTextSelection = function () {
  2155. off(window, 'selectstart', preventDefault);
  2156. };
  2157. } else {
  2158. var userSelectProperty = testProp(
  2159. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2160. disableTextSelection = function () {
  2161. if (userSelectProperty) {
  2162. var style = document.documentElement.style;
  2163. _userSelect = style[userSelectProperty];
  2164. style[userSelectProperty] = 'none';
  2165. }
  2166. };
  2167. enableTextSelection = function () {
  2168. if (userSelectProperty) {
  2169. document.documentElement.style[userSelectProperty] = _userSelect;
  2170. _userSelect = undefined;
  2171. }
  2172. };
  2173. }
  2174. // @function disableImageDrag()
  2175. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2176. // for `dragstart` DOM events, usually generated when the user drags an image.
  2177. function disableImageDrag() {
  2178. on(window, 'dragstart', preventDefault);
  2179. }
  2180. // @function enableImageDrag()
  2181. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2182. function enableImageDrag() {
  2183. off(window, 'dragstart', preventDefault);
  2184. }
  2185. var _outlineElement, _outlineStyle;
  2186. // @function preventOutline(el: HTMLElement)
  2187. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2188. // of the element `el` invisible. Used internally by Leaflet to prevent
  2189. // focusable elements from displaying an outline when the user performs a
  2190. // drag interaction on them.
  2191. function preventOutline(element) {
  2192. while (element.tabIndex === -1) {
  2193. element = element.parentNode;
  2194. }
  2195. if (!element.style) { return; }
  2196. restoreOutline();
  2197. _outlineElement = element;
  2198. _outlineStyle = element.style.outline;
  2199. element.style.outline = 'none';
  2200. on(window, 'keydown', restoreOutline);
  2201. }
  2202. // @function restoreOutline()
  2203. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2204. function restoreOutline() {
  2205. if (!_outlineElement) { return; }
  2206. _outlineElement.style.outline = _outlineStyle;
  2207. _outlineElement = undefined;
  2208. _outlineStyle = undefined;
  2209. off(window, 'keydown', restoreOutline);
  2210. }
  2211. // @function getSizedParentNode(el: HTMLElement): HTMLElement
  2212. // Finds the closest parent node which size (width and height) is not null.
  2213. function getSizedParentNode(element) {
  2214. do {
  2215. element = element.parentNode;
  2216. } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);
  2217. return element;
  2218. }
  2219. // @function getScale(el: HTMLElement): Object
  2220. // Computes the CSS scale currently applied on the element.
  2221. // Returns an object with `x` and `y` members as horizontal and vertical scales respectively,
  2222. // and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2223. function getScale(element) {
  2224. var rect = element.getBoundingClientRect(); // Read-only in old browsers.
  2225. return {
  2226. x: rect.width / element.offsetWidth || 1,
  2227. y: rect.height / element.offsetHeight || 1,
  2228. boundingClientRect: rect
  2229. };
  2230. }
  2231. var DomUtil = {
  2232. __proto__: null,
  2233. TRANSFORM: TRANSFORM,
  2234. TRANSITION: TRANSITION,
  2235. TRANSITION_END: TRANSITION_END,
  2236. get: get,
  2237. getStyle: getStyle,
  2238. create: create$1,
  2239. remove: remove,
  2240. empty: empty,
  2241. toFront: toFront,
  2242. toBack: toBack,
  2243. hasClass: hasClass,
  2244. addClass: addClass,
  2245. removeClass: removeClass,
  2246. setClass: setClass,
  2247. getClass: getClass,
  2248. setOpacity: setOpacity,
  2249. testProp: testProp,
  2250. setTransform: setTransform,
  2251. setPosition: setPosition,
  2252. getPosition: getPosition,
  2253. get disableTextSelection () { return disableTextSelection; },
  2254. get enableTextSelection () { return enableTextSelection; },
  2255. disableImageDrag: disableImageDrag,
  2256. enableImageDrag: enableImageDrag,
  2257. preventOutline: preventOutline,
  2258. restoreOutline: restoreOutline,
  2259. getSizedParentNode: getSizedParentNode,
  2260. getScale: getScale
  2261. };
  2262. /*
  2263. * @namespace DomEvent
  2264. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  2265. */
  2266. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  2267. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2268. // Adds a listener function (`fn`) to a particular DOM event type of the
  2269. // element `el`. You can optionally specify the context of the listener
  2270. // (object the `this` keyword will point to). You can also pass several
  2271. // space-separated types (e.g. `'click dblclick'`).
  2272. // @alternative
  2273. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  2274. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2275. function on(obj, types, fn, context) {
  2276. if (types && typeof types === 'object') {
  2277. for (var type in types) {
  2278. addOne(obj, type, types[type], fn);
  2279. }
  2280. } else {
  2281. types = splitWords(types);
  2282. for (var i = 0, len = types.length; i < len; i++) {
  2283. addOne(obj, types[i], fn, context);
  2284. }
  2285. }
  2286. return this;
  2287. }
  2288. var eventsKey = '_leaflet_events';
  2289. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2290. // Removes a previously added listener function.
  2291. // Note that if you passed a custom context to on, you must pass the same
  2292. // context to `off` in order to remove the listener.
  2293. // @alternative
  2294. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  2295. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2296. // @alternative
  2297. // @function off(el: HTMLElement, types: String): this
  2298. // Removes all previously added listeners of given types.
  2299. // @alternative
  2300. // @function off(el: HTMLElement): this
  2301. // Removes all previously added listeners from given HTMLElement
  2302. function off(obj, types, fn, context) {
  2303. if (arguments.length === 1) {
  2304. batchRemove(obj);
  2305. delete obj[eventsKey];
  2306. } else if (types && typeof types === 'object') {
  2307. for (var type in types) {
  2308. removeOne(obj, type, types[type], fn);
  2309. }
  2310. } else {
  2311. types = splitWords(types);
  2312. if (arguments.length === 2) {
  2313. batchRemove(obj, function (type) {
  2314. return indexOf(types, type) !== -1;
  2315. });
  2316. } else {
  2317. for (var i = 0, len = types.length; i < len; i++) {
  2318. removeOne(obj, types[i], fn, context);
  2319. }
  2320. }
  2321. }
  2322. return this;
  2323. }
  2324. function batchRemove(obj, filterFn) {
  2325. for (var id in obj[eventsKey]) {
  2326. var type = id.split(/\d/)[0];
  2327. if (!filterFn || filterFn(type)) {
  2328. removeOne(obj, type, null, null, id);
  2329. }
  2330. }
  2331. }
  2332. var mouseSubst = {
  2333. mouseenter: 'mouseover',
  2334. mouseleave: 'mouseout',
  2335. wheel: !('onwheel' in window) && 'mousewheel'
  2336. };
  2337. function addOne(obj, type, fn, context) {
  2338. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2339. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  2340. var handler = function (e) {
  2341. return fn.call(context || obj, e || window.event);
  2342. };
  2343. var originalHandler = handler;
  2344. if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {
  2345. // Needs DomEvent.Pointer.js
  2346. handler = addPointerListener(obj, type, handler);
  2347. } else if (Browser.touch && (type === 'dblclick')) {
  2348. handler = addDoubleTapListener(obj, handler);
  2349. } else if ('addEventListener' in obj) {
  2350. if (type === 'touchstart' || type === 'touchmove' || type === 'wheel' || type === 'mousewheel') {
  2351. obj.addEventListener(mouseSubst[type] || type, handler, Browser.passiveEvents ? {passive: false} : false);
  2352. } else if (type === 'mouseenter' || type === 'mouseleave') {
  2353. handler = function (e) {
  2354. e = e || window.event;
  2355. if (isExternalTarget(obj, e)) {
  2356. originalHandler(e);
  2357. }
  2358. };
  2359. obj.addEventListener(mouseSubst[type], handler, false);
  2360. } else {
  2361. obj.addEventListener(type, originalHandler, false);
  2362. }
  2363. } else {
  2364. obj.attachEvent('on' + type, handler);
  2365. }
  2366. obj[eventsKey] = obj[eventsKey] || {};
  2367. obj[eventsKey][id] = handler;
  2368. }
  2369. function removeOne(obj, type, fn, context, id) {
  2370. id = id || type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2371. var handler = obj[eventsKey] && obj[eventsKey][id];
  2372. if (!handler) { return this; }
  2373. if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {
  2374. removePointerListener(obj, type, handler);
  2375. } else if (Browser.touch && (type === 'dblclick')) {
  2376. removeDoubleTapListener(obj, handler);
  2377. } else if ('removeEventListener' in obj) {
  2378. obj.removeEventListener(mouseSubst[type] || type, handler, false);
  2379. } else {
  2380. obj.detachEvent('on' + type, handler);
  2381. }
  2382. obj[eventsKey][id] = null;
  2383. }
  2384. // @function stopPropagation(ev: DOMEvent): this
  2385. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  2386. // ```js
  2387. // L.DomEvent.on(div, 'click', function (ev) {
  2388. // L.DomEvent.stopPropagation(ev);
  2389. // });
  2390. // ```
  2391. function stopPropagation(e) {
  2392. if (e.stopPropagation) {
  2393. e.stopPropagation();
  2394. } else if (e.originalEvent) { // In case of Leaflet event.
  2395. e.originalEvent._stopped = true;
  2396. } else {
  2397. e.cancelBubble = true;
  2398. }
  2399. return this;
  2400. }
  2401. // @function disableScrollPropagation(el: HTMLElement): this
  2402. // Adds `stopPropagation` to the element's `'wheel'` events (plus browser variants).
  2403. function disableScrollPropagation(el) {
  2404. addOne(el, 'wheel', stopPropagation);
  2405. return this;
  2406. }
  2407. // @function disableClickPropagation(el: HTMLElement): this
  2408. // Adds `stopPropagation` to the element's `'click'`, `'dblclick'`, `'contextmenu'`,
  2409. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  2410. function disableClickPropagation(el) {
  2411. on(el, 'mousedown touchstart dblclick contextmenu', stopPropagation);
  2412. el['_leaflet_disable_click'] = true;
  2413. return this;
  2414. }
  2415. // @function preventDefault(ev: DOMEvent): this
  2416. // Prevents the default action of the DOM Event `ev` from happening (such as
  2417. // following a link in the href of the a element, or doing a POST request
  2418. // with page reload when a `<form>` is submitted).
  2419. // Use it inside listener functions.
  2420. function preventDefault(e) {
  2421. if (e.preventDefault) {
  2422. e.preventDefault();
  2423. } else {
  2424. e.returnValue = false;
  2425. }
  2426. return this;
  2427. }
  2428. // @function stop(ev: DOMEvent): this
  2429. // Does `stopPropagation` and `preventDefault` at the same time.
  2430. function stop(e) {
  2431. preventDefault(e);
  2432. stopPropagation(e);
  2433. return this;
  2434. }
  2435. // @function getPropagationPath(ev: DOMEvent): Array
  2436. // Compatibility polyfill for [`Event.composedPath()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath).
  2437. // Returns an array containing the `HTMLElement`s that the given DOM event
  2438. // should propagate to (if not stopped).
  2439. function getPropagationPath(ev) {
  2440. if (ev.composedPath) {
  2441. return ev.composedPath();
  2442. }
  2443. var path = [];
  2444. var el = ev.target;
  2445. while (el) {
  2446. path.push(el);
  2447. el = el.parentNode;
  2448. }
  2449. return path;
  2450. }
  2451. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  2452. // Gets normalized mouse position from a DOM event relative to the
  2453. // `container` (border excluded) or to the whole page if not specified.
  2454. function getMousePosition(e, container) {
  2455. if (!container) {
  2456. return new Point(e.clientX, e.clientY);
  2457. }
  2458. var scale = getScale(container),
  2459. offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)
  2460. return new Point(
  2461. // offset.left/top values are in page scale (like clientX/Y),
  2462. // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
  2463. (e.clientX - offset.left) / scale.x - container.clientLeft,
  2464. (e.clientY - offset.top) / scale.y - container.clientTop
  2465. );
  2466. }
  2467. // except , Safari and
  2468. // We need double the scroll pixels (see #7403 and #4538) for all Browsers
  2469. // except OSX (Mac) -> 3x, Chrome running on Linux 1x
  2470. var wheelPxFactor =
  2471. (Browser.linux && Browser.chrome) ? window.devicePixelRatio :
  2472. Browser.mac ? window.devicePixelRatio * 3 :
  2473. window.devicePixelRatio > 0 ? 2 * window.devicePixelRatio : 1;
  2474. // @function getWheelDelta(ev: DOMEvent): Number
  2475. // Gets normalized wheel delta from a wheel DOM event, in vertical
  2476. // pixels scrolled (negative if scrolling down).
  2477. // Events from pointing devices without precise scrolling are mapped to
  2478. // a best guess of 60 pixels.
  2479. function getWheelDelta(e) {
  2480. return (Browser.edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2481. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2482. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2483. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2484. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2485. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2486. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2487. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2488. 0;
  2489. }
  2490. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2491. function isExternalTarget(el, e) {
  2492. var related = e.relatedTarget;
  2493. if (!related) { return true; }
  2494. try {
  2495. while (related && (related !== el)) {
  2496. related = related.parentNode;
  2497. }
  2498. } catch (err) {
  2499. return false;
  2500. }
  2501. return (related !== el);
  2502. }
  2503. var DomEvent = {
  2504. __proto__: null,
  2505. on: on,
  2506. off: off,
  2507. stopPropagation: stopPropagation,
  2508. disableScrollPropagation: disableScrollPropagation,
  2509. disableClickPropagation: disableClickPropagation,
  2510. preventDefault: preventDefault,
  2511. stop: stop,
  2512. getPropagationPath: getPropagationPath,
  2513. getMousePosition: getMousePosition,
  2514. getWheelDelta: getWheelDelta,
  2515. isExternalTarget: isExternalTarget,
  2516. addListener: on,
  2517. removeListener: off
  2518. };
  2519. /*
  2520. * @class PosAnimation
  2521. * @aka L.PosAnimation
  2522. * @inherits Evented
  2523. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2524. *
  2525. * @example
  2526. * ```js
  2527. * var myPositionMarker = L.marker([48.864716, 2.294694]).addTo(map);
  2528. *
  2529. * myPositionMarker.on("click", function() {
  2530. * var pos = map.latLngToLayerPoint(myPositionMarker.getLatLng());
  2531. * pos.y -= 25;
  2532. * var fx = new L.PosAnimation();
  2533. *
  2534. * fx.once('end',function() {
  2535. * pos.y += 25;
  2536. * fx.run(myPositionMarker._icon, pos, 0.8);
  2537. * });
  2538. *
  2539. * fx.run(myPositionMarker._icon, pos, 0.3);
  2540. * });
  2541. *
  2542. * ```
  2543. *
  2544. * @constructor L.PosAnimation()
  2545. * Creates a `PosAnimation` object.
  2546. *
  2547. */
  2548. var PosAnimation = Evented.extend({
  2549. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2550. // Run an animation of a given element to a new position, optionally setting
  2551. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2552. // argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1),
  2553. // `0.5` by default).
  2554. run: function (el, newPos, duration, easeLinearity) {
  2555. this.stop();
  2556. this._el = el;
  2557. this._inProgress = true;
  2558. this._duration = duration || 0.25;
  2559. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2560. this._startPos = getPosition(el);
  2561. this._offset = newPos.subtract(this._startPos);
  2562. this._startTime = +new Date();
  2563. // @event start: Event
  2564. // Fired when the animation starts
  2565. this.fire('start');
  2566. this._animate();
  2567. },
  2568. // @method stop()
  2569. // Stops the animation (if currently running).
  2570. stop: function () {
  2571. if (!this._inProgress) { return; }
  2572. this._step(true);
  2573. this._complete();
  2574. },
  2575. _animate: function () {
  2576. // animation loop
  2577. this._animId = requestAnimFrame(this._animate, this);
  2578. this._step();
  2579. },
  2580. _step: function (round) {
  2581. var elapsed = (+new Date()) - this._startTime,
  2582. duration = this._duration * 1000;
  2583. if (elapsed < duration) {
  2584. this._runFrame(this._easeOut(elapsed / duration), round);
  2585. } else {
  2586. this._runFrame(1);
  2587. this._complete();
  2588. }
  2589. },
  2590. _runFrame: function (progress, round) {
  2591. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2592. if (round) {
  2593. pos._round();
  2594. }
  2595. setPosition(this._el, pos);
  2596. // @event step: Event
  2597. // Fired continuously during the animation.
  2598. this.fire('step');
  2599. },
  2600. _complete: function () {
  2601. cancelAnimFrame(this._animId);
  2602. this._inProgress = false;
  2603. // @event end: Event
  2604. // Fired when the animation ends.
  2605. this.fire('end');
  2606. },
  2607. _easeOut: function (t) {
  2608. return 1 - Math.pow(1 - t, this._easeOutPower);
  2609. }
  2610. });
  2611. /*
  2612. * @class Map
  2613. * @aka L.Map
  2614. * @inherits Evented
  2615. *
  2616. * The central class of the API — it is used to create a map on a page and manipulate it.
  2617. *
  2618. * @example
  2619. *
  2620. * ```js
  2621. * // initialize the map on the "map" div with a given center and zoom
  2622. * var map = L.map('map', {
  2623. * center: [51.505, -0.09],
  2624. * zoom: 13
  2625. * });
  2626. * ```
  2627. *
  2628. */
  2629. var Map = Evented.extend({
  2630. options: {
  2631. // @section Map State Options
  2632. // @option crs: CRS = L.CRS.EPSG3857
  2633. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2634. // sure what it means.
  2635. crs: EPSG3857,
  2636. // @option center: LatLng = undefined
  2637. // Initial geographic center of the map
  2638. center: undefined,
  2639. // @option zoom: Number = undefined
  2640. // Initial map zoom level
  2641. zoom: undefined,
  2642. // @option minZoom: Number = *
  2643. // Minimum zoom level of the map.
  2644. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2645. // the lowest of their `minZoom` options will be used instead.
  2646. minZoom: undefined,
  2647. // @option maxZoom: Number = *
  2648. // Maximum zoom level of the map.
  2649. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2650. // the highest of their `maxZoom` options will be used instead.
  2651. maxZoom: undefined,
  2652. // @option layers: Layer[] = []
  2653. // Array of layers that will be added to the map initially
  2654. layers: [],
  2655. // @option maxBounds: LatLngBounds = null
  2656. // When this option is set, the map restricts the view to the given
  2657. // geographical bounds, bouncing the user back if the user tries to pan
  2658. // outside the view. To set the restriction dynamically, use
  2659. // [`setMaxBounds`](#map-setmaxbounds) method.
  2660. maxBounds: undefined,
  2661. // @option renderer: Renderer = *
  2662. // The default method for drawing vector layers on the map. `L.SVG`
  2663. // or `L.Canvas` by default depending on browser support.
  2664. renderer: undefined,
  2665. // @section Animation Options
  2666. // @option zoomAnimation: Boolean = true
  2667. // Whether the map zoom animation is enabled. By default it's enabled
  2668. // in all browsers that support CSS3 Transitions except Android.
  2669. zoomAnimation: true,
  2670. // @option zoomAnimationThreshold: Number = 4
  2671. // Won't animate zoom if the zoom difference exceeds this value.
  2672. zoomAnimationThreshold: 4,
  2673. // @option fadeAnimation: Boolean = true
  2674. // Whether the tile fade animation is enabled. By default it's enabled
  2675. // in all browsers that support CSS3 Transitions except Android.
  2676. fadeAnimation: true,
  2677. // @option markerZoomAnimation: Boolean = true
  2678. // Whether markers animate their zoom with the zoom animation, if disabled
  2679. // they will disappear for the length of the animation. By default it's
  2680. // enabled in all browsers that support CSS3 Transitions except Android.
  2681. markerZoomAnimation: true,
  2682. // @option transform3DLimit: Number = 2^23
  2683. // Defines the maximum size of a CSS translation transform. The default
  2684. // value should not be changed unless a web browser positions layers in
  2685. // the wrong place after doing a large `panBy`.
  2686. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2687. // @section Interaction Options
  2688. // @option zoomSnap: Number = 1
  2689. // Forces the map's zoom level to always be a multiple of this, particularly
  2690. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2691. // By default, the zoom level snaps to the nearest integer; lower values
  2692. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2693. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2694. zoomSnap: 1,
  2695. // @option zoomDelta: Number = 1
  2696. // Controls how much the map's zoom level will change after a
  2697. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2698. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2699. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2700. zoomDelta: 1,
  2701. // @option trackResize: Boolean = true
  2702. // Whether the map automatically handles browser window resize to update itself.
  2703. trackResize: true
  2704. },
  2705. initialize: function (id, options) { // (HTMLElement or String, Object)
  2706. options = setOptions(this, options);
  2707. // Make sure to assign internal flags at the beginning,
  2708. // to avoid inconsistent state in some edge cases.
  2709. this._handlers = [];
  2710. this._layers = {};
  2711. this._zoomBoundLayers = {};
  2712. this._sizeChanged = true;
  2713. this._initContainer(id);
  2714. this._initLayout();
  2715. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2716. this._onResize = bind(this._onResize, this);
  2717. this._initEvents();
  2718. if (options.maxBounds) {
  2719. this.setMaxBounds(options.maxBounds);
  2720. }
  2721. if (options.zoom !== undefined) {
  2722. this._zoom = this._limitZoom(options.zoom);
  2723. }
  2724. if (options.center && options.zoom !== undefined) {
  2725. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2726. }
  2727. this.callInitHooks();
  2728. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2729. this._zoomAnimated = TRANSITION && Browser.any3d && !Browser.mobileOpera &&
  2730. this.options.zoomAnimation;
  2731. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2732. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2733. if (this._zoomAnimated) {
  2734. this._createAnimProxy();
  2735. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2736. }
  2737. this._addLayers(this.options.layers);
  2738. },
  2739. // @section Methods for modifying map state
  2740. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2741. // Sets the view of the map (geographical center and zoom) with the given
  2742. // animation options.
  2743. setView: function (center, zoom, options) {
  2744. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2745. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2746. options = options || {};
  2747. this._stop();
  2748. if (this._loaded && !options.reset && options !== true) {
  2749. if (options.animate !== undefined) {
  2750. options.zoom = extend({animate: options.animate}, options.zoom);
  2751. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2752. }
  2753. // try animating pan or zoom
  2754. var moved = (this._zoom !== zoom) ?
  2755. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2756. this._tryAnimatedPan(center, options.pan);
  2757. if (moved) {
  2758. // prevent resize handler call, the view will refresh after animation anyway
  2759. clearTimeout(this._sizeTimer);
  2760. return this;
  2761. }
  2762. }
  2763. // animation didn't start, just reset the map view
  2764. this._resetView(center, zoom, options.pan && options.pan.noMoveStart);
  2765. return this;
  2766. },
  2767. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2768. // Sets the zoom of the map.
  2769. setZoom: function (zoom, options) {
  2770. if (!this._loaded) {
  2771. this._zoom = zoom;
  2772. return this;
  2773. }
  2774. return this.setView(this.getCenter(), zoom, {zoom: options});
  2775. },
  2776. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2777. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2778. zoomIn: function (delta, options) {
  2779. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  2780. return this.setZoom(this._zoom + delta, options);
  2781. },
  2782. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2783. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2784. zoomOut: function (delta, options) {
  2785. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  2786. return this.setZoom(this._zoom - delta, options);
  2787. },
  2788. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2789. // Zooms the map while keeping a specified geographical point on the map
  2790. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2791. // @alternative
  2792. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2793. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2794. setZoomAround: function (latlng, zoom, options) {
  2795. var scale = this.getZoomScale(zoom),
  2796. viewHalf = this.getSize().divideBy(2),
  2797. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2798. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2799. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2800. return this.setView(newCenter, zoom, {zoom: options});
  2801. },
  2802. _getBoundsCenterZoom: function (bounds, options) {
  2803. options = options || {};
  2804. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2805. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2806. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2807. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2808. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2809. if (zoom === Infinity) {
  2810. return {
  2811. center: bounds.getCenter(),
  2812. zoom: zoom
  2813. };
  2814. }
  2815. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2816. swPoint = this.project(bounds.getSouthWest(), zoom),
  2817. nePoint = this.project(bounds.getNorthEast(), zoom),
  2818. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2819. return {
  2820. center: center,
  2821. zoom: zoom
  2822. };
  2823. },
  2824. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2825. // Sets a map view that contains the given geographical bounds with the
  2826. // maximum zoom level possible.
  2827. fitBounds: function (bounds, options) {
  2828. bounds = toLatLngBounds(bounds);
  2829. if (!bounds.isValid()) {
  2830. throw new Error('Bounds are not valid.');
  2831. }
  2832. var target = this._getBoundsCenterZoom(bounds, options);
  2833. return this.setView(target.center, target.zoom, options);
  2834. },
  2835. // @method fitWorld(options?: fitBounds options): this
  2836. // Sets a map view that mostly contains the whole world with the maximum
  2837. // zoom level possible.
  2838. fitWorld: function (options) {
  2839. return this.fitBounds([[-90, -180], [90, 180]], options);
  2840. },
  2841. // @method panTo(latlng: LatLng, options?: Pan options): this
  2842. // Pans the map to a given center.
  2843. panTo: function (center, options) { // (LatLng)
  2844. return this.setView(center, this._zoom, {pan: options});
  2845. },
  2846. // @method panBy(offset: Point, options?: Pan options): this
  2847. // Pans the map by a given number of pixels (animated).
  2848. panBy: function (offset, options) {
  2849. offset = toPoint(offset).round();
  2850. options = options || {};
  2851. if (!offset.x && !offset.y) {
  2852. return this.fire('moveend');
  2853. }
  2854. // If we pan too far, Chrome gets issues with tiles
  2855. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2856. if (options.animate !== true && !this.getSize().contains(offset)) {
  2857. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2858. return this;
  2859. }
  2860. if (!this._panAnim) {
  2861. this._panAnim = new PosAnimation();
  2862. this._panAnim.on({
  2863. 'step': this._onPanTransitionStep,
  2864. 'end': this._onPanTransitionEnd
  2865. }, this);
  2866. }
  2867. // don't fire movestart if animating inertia
  2868. if (!options.noMoveStart) {
  2869. this.fire('movestart');
  2870. }
  2871. // animate pan unless animate: false specified
  2872. if (options.animate !== false) {
  2873. addClass(this._mapPane, 'leaflet-pan-anim');
  2874. var newPos = this._getMapPanePos().subtract(offset).round();
  2875. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2876. } else {
  2877. this._rawPanBy(offset);
  2878. this.fire('move').fire('moveend');
  2879. }
  2880. return this;
  2881. },
  2882. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2883. // Sets the view of the map (geographical center and zoom) performing a smooth
  2884. // pan-zoom animation.
  2885. flyTo: function (targetCenter, targetZoom, options) {
  2886. options = options || {};
  2887. if (options.animate === false || !Browser.any3d) {
  2888. return this.setView(targetCenter, targetZoom, options);
  2889. }
  2890. this._stop();
  2891. var from = this.project(this.getCenter()),
  2892. to = this.project(targetCenter),
  2893. size = this.getSize(),
  2894. startZoom = this._zoom;
  2895. targetCenter = toLatLng(targetCenter);
  2896. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2897. var w0 = Math.max(size.x, size.y),
  2898. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2899. u1 = (to.distanceTo(from)) || 1,
  2900. rho = 1.42,
  2901. rho2 = rho * rho;
  2902. function r(i) {
  2903. var s1 = i ? -1 : 1,
  2904. s2 = i ? w1 : w0,
  2905. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2906. b1 = 2 * s2 * rho2 * u1,
  2907. b = t1 / b1,
  2908. sq = Math.sqrt(b * b + 1) - b;
  2909. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2910. // thus triggering an infinite loop in flyTo
  2911. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2912. return log;
  2913. }
  2914. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2915. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2916. function tanh(n) { return sinh(n) / cosh(n); }
  2917. var r0 = r(0);
  2918. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2919. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2920. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2921. var start = Date.now(),
  2922. S = (r(1) - r0) / rho,
  2923. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2924. function frame() {
  2925. var t = (Date.now() - start) / duration,
  2926. s = easeOut(t) * S;
  2927. if (t <= 1) {
  2928. this._flyToFrame = requestAnimFrame(frame, this);
  2929. this._move(
  2930. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2931. this.getScaleZoom(w0 / w(s), startZoom),
  2932. {flyTo: true});
  2933. } else {
  2934. this
  2935. ._move(targetCenter, targetZoom)
  2936. ._moveEnd(true);
  2937. }
  2938. }
  2939. this._moveStart(true, options.noMoveStart);
  2940. frame.call(this);
  2941. return this;
  2942. },
  2943. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2944. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2945. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2946. flyToBounds: function (bounds, options) {
  2947. var target = this._getBoundsCenterZoom(bounds, options);
  2948. return this.flyTo(target.center, target.zoom, options);
  2949. },
  2950. // @method setMaxBounds(bounds: LatLngBounds): this
  2951. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2952. setMaxBounds: function (bounds) {
  2953. bounds = toLatLngBounds(bounds);
  2954. if (this.listens('moveend', this._panInsideMaxBounds)) {
  2955. this.off('moveend', this._panInsideMaxBounds);
  2956. }
  2957. if (!bounds.isValid()) {
  2958. this.options.maxBounds = null;
  2959. return this;
  2960. }
  2961. this.options.maxBounds = bounds;
  2962. if (this._loaded) {
  2963. this._panInsideMaxBounds();
  2964. }
  2965. return this.on('moveend', this._panInsideMaxBounds);
  2966. },
  2967. // @method setMinZoom(zoom: Number): this
  2968. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2969. setMinZoom: function (zoom) {
  2970. var oldZoom = this.options.minZoom;
  2971. this.options.minZoom = zoom;
  2972. if (this._loaded && oldZoom !== zoom) {
  2973. this.fire('zoomlevelschange');
  2974. if (this.getZoom() < this.options.minZoom) {
  2975. return this.setZoom(zoom);
  2976. }
  2977. }
  2978. return this;
  2979. },
  2980. // @method setMaxZoom(zoom: Number): this
  2981. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2982. setMaxZoom: function (zoom) {
  2983. var oldZoom = this.options.maxZoom;
  2984. this.options.maxZoom = zoom;
  2985. if (this._loaded && oldZoom !== zoom) {
  2986. this.fire('zoomlevelschange');
  2987. if (this.getZoom() > this.options.maxZoom) {
  2988. return this.setZoom(zoom);
  2989. }
  2990. }
  2991. return this;
  2992. },
  2993. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2994. // 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.
  2995. panInsideBounds: function (bounds, options) {
  2996. this._enforcingBounds = true;
  2997. var center = this.getCenter(),
  2998. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2999. if (!center.equals(newCenter)) {
  3000. this.panTo(newCenter, options);
  3001. }
  3002. this._enforcingBounds = false;
  3003. return this;
  3004. },
  3005. // @method panInside(latlng: LatLng, options?: padding options): this
  3006. // Pans the map the minimum amount to make the `latlng` visible. Use
  3007. // padding options to fit the display to more restricted bounds.
  3008. // If `latlng` is already within the (optionally padded) display bounds,
  3009. // the map will not be panned.
  3010. panInside: function (latlng, options) {
  3011. options = options || {};
  3012. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  3013. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  3014. pixelCenter = this.project(this.getCenter()),
  3015. pixelPoint = this.project(latlng),
  3016. pixelBounds = this.getPixelBounds(),
  3017. paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]),
  3018. paddedSize = paddedBounds.getSize();
  3019. if (!paddedBounds.contains(pixelPoint)) {
  3020. this._enforcingBounds = true;
  3021. var centerOffset = pixelPoint.subtract(paddedBounds.getCenter());
  3022. var offset = paddedBounds.extend(pixelPoint).getSize().subtract(paddedSize);
  3023. pixelCenter.x += centerOffset.x < 0 ? -offset.x : offset.x;
  3024. pixelCenter.y += centerOffset.y < 0 ? -offset.y : offset.y;
  3025. this.panTo(this.unproject(pixelCenter), options);
  3026. this._enforcingBounds = false;
  3027. }
  3028. return this;
  3029. },
  3030. // @method invalidateSize(options: Zoom/pan options): this
  3031. // Checks if the map container size changed and updates the map if so —
  3032. // call it after you've changed the map size dynamically, also animating
  3033. // pan by default. If `options.pan` is `false`, panning will not occur.
  3034. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  3035. // that it doesn't happen often even if the method is called many
  3036. // times in a row.
  3037. // @alternative
  3038. // @method invalidateSize(animate: Boolean): this
  3039. // Checks if the map container size changed and updates the map if so —
  3040. // call it after you've changed the map size dynamically, also animating
  3041. // pan by default.
  3042. invalidateSize: function (options) {
  3043. if (!this._loaded) { return this; }
  3044. options = extend({
  3045. animate: false,
  3046. pan: true
  3047. }, options === true ? {animate: true} : options);
  3048. var oldSize = this.getSize();
  3049. this._sizeChanged = true;
  3050. this._lastCenter = null;
  3051. var newSize = this.getSize(),
  3052. oldCenter = oldSize.divideBy(2).round(),
  3053. newCenter = newSize.divideBy(2).round(),
  3054. offset = oldCenter.subtract(newCenter);
  3055. if (!offset.x && !offset.y) { return this; }
  3056. if (options.animate && options.pan) {
  3057. this.panBy(offset);
  3058. } else {
  3059. if (options.pan) {
  3060. this._rawPanBy(offset);
  3061. }
  3062. this.fire('move');
  3063. if (options.debounceMoveend) {
  3064. clearTimeout(this._sizeTimer);
  3065. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  3066. } else {
  3067. this.fire('moveend');
  3068. }
  3069. }
  3070. // @section Map state change events
  3071. // @event resize: ResizeEvent
  3072. // Fired when the map is resized.
  3073. return this.fire('resize', {
  3074. oldSize: oldSize,
  3075. newSize: newSize
  3076. });
  3077. },
  3078. // @section Methods for modifying map state
  3079. // @method stop(): this
  3080. // Stops the currently running `panTo` or `flyTo` animation, if any.
  3081. stop: function () {
  3082. this.setZoom(this._limitZoom(this._zoom));
  3083. if (!this.options.zoomSnap) {
  3084. this.fire('viewreset');
  3085. }
  3086. return this._stop();
  3087. },
  3088. // @section Geolocation methods
  3089. // @method locate(options?: Locate options): this
  3090. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  3091. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  3092. // and optionally sets the map view to the user's location with respect to
  3093. // detection accuracy (or to the world view if geolocation failed).
  3094. // Note that, if your page doesn't use HTTPS, this method will fail in
  3095. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  3096. // See `Locate options` for more details.
  3097. locate: function (options) {
  3098. options = this._locateOptions = extend({
  3099. timeout: 10000,
  3100. watch: false
  3101. // setView: false
  3102. // maxZoom: <Number>
  3103. // maximumAge: 0
  3104. // enableHighAccuracy: false
  3105. }, options);
  3106. if (!('geolocation' in navigator)) {
  3107. this._handleGeolocationError({
  3108. code: 0,
  3109. message: 'Geolocation not supported.'
  3110. });
  3111. return this;
  3112. }
  3113. var onResponse = bind(this._handleGeolocationResponse, this),
  3114. onError = bind(this._handleGeolocationError, this);
  3115. if (options.watch) {
  3116. this._locationWatchId =
  3117. navigator.geolocation.watchPosition(onResponse, onError, options);
  3118. } else {
  3119. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  3120. }
  3121. return this;
  3122. },
  3123. // @method stopLocate(): this
  3124. // Stops watching location previously initiated by `map.locate({watch: true})`
  3125. // and aborts resetting the map view if map.locate was called with
  3126. // `{setView: true}`.
  3127. stopLocate: function () {
  3128. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  3129. navigator.geolocation.clearWatch(this._locationWatchId);
  3130. }
  3131. if (this._locateOptions) {
  3132. this._locateOptions.setView = false;
  3133. }
  3134. return this;
  3135. },
  3136. _handleGeolocationError: function (error) {
  3137. if (!this._container._leaflet_id) { return; }
  3138. var c = error.code,
  3139. message = error.message ||
  3140. (c === 1 ? 'permission denied' :
  3141. (c === 2 ? 'position unavailable' : 'timeout'));
  3142. if (this._locateOptions.setView && !this._loaded) {
  3143. this.fitWorld();
  3144. }
  3145. // @section Location events
  3146. // @event locationerror: ErrorEvent
  3147. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  3148. this.fire('locationerror', {
  3149. code: c,
  3150. message: 'Geolocation error: ' + message + '.'
  3151. });
  3152. },
  3153. _handleGeolocationResponse: function (pos) {
  3154. if (!this._container._leaflet_id) { return; }
  3155. var lat = pos.coords.latitude,
  3156. lng = pos.coords.longitude,
  3157. latlng = new LatLng(lat, lng),
  3158. bounds = latlng.toBounds(pos.coords.accuracy * 2),
  3159. options = this._locateOptions;
  3160. if (options.setView) {
  3161. var zoom = this.getBoundsZoom(bounds);
  3162. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  3163. }
  3164. var data = {
  3165. latlng: latlng,
  3166. bounds: bounds,
  3167. timestamp: pos.timestamp
  3168. };
  3169. for (var i in pos.coords) {
  3170. if (typeof pos.coords[i] === 'number') {
  3171. data[i] = pos.coords[i];
  3172. }
  3173. }
  3174. // @event locationfound: LocationEvent
  3175. // Fired when geolocation (using the [`locate`](#map-locate) method)
  3176. // went successfully.
  3177. this.fire('locationfound', data);
  3178. },
  3179. // TODO Appropriate docs section?
  3180. // @section Other Methods
  3181. // @method addHandler(name: String, HandlerClass: Function): this
  3182. // Adds a new `Handler` to the map, given its name and constructor function.
  3183. addHandler: function (name, HandlerClass) {
  3184. if (!HandlerClass) { return this; }
  3185. var handler = this[name] = new HandlerClass(this);
  3186. this._handlers.push(handler);
  3187. if (this.options[name]) {
  3188. handler.enable();
  3189. }
  3190. return this;
  3191. },
  3192. // @method remove(): this
  3193. // Destroys the map and clears all related event listeners.
  3194. remove: function () {
  3195. this._initEvents(true);
  3196. if (this.options.maxBounds) { this.off('moveend', this._panInsideMaxBounds); }
  3197. if (this._containerId !== this._container._leaflet_id) {
  3198. throw new Error('Map container is being reused by another instance');
  3199. }
  3200. try {
  3201. // throws error in IE6-8
  3202. delete this._container._leaflet_id;
  3203. delete this._containerId;
  3204. } catch (e) {
  3205. /*eslint-disable */
  3206. this._container._leaflet_id = undefined;
  3207. /* eslint-enable */
  3208. this._containerId = undefined;
  3209. }
  3210. if (this._locationWatchId !== undefined) {
  3211. this.stopLocate();
  3212. }
  3213. this._stop();
  3214. remove(this._mapPane);
  3215. if (this._clearControlPos) {
  3216. this._clearControlPos();
  3217. }
  3218. if (this._resizeRequest) {
  3219. cancelAnimFrame(this._resizeRequest);
  3220. this._resizeRequest = null;
  3221. }
  3222. this._clearHandlers();
  3223. if (this._loaded) {
  3224. // @section Map state change events
  3225. // @event unload: Event
  3226. // Fired when the map is destroyed with [remove](#map-remove) method.
  3227. this.fire('unload');
  3228. }
  3229. var i;
  3230. for (i in this._layers) {
  3231. this._layers[i].remove();
  3232. }
  3233. for (i in this._panes) {
  3234. remove(this._panes[i]);
  3235. }
  3236. this._layers = [];
  3237. this._panes = [];
  3238. delete this._mapPane;
  3239. delete this._renderer;
  3240. return this;
  3241. },
  3242. // @section Other Methods
  3243. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3244. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3245. // then returns it. The pane is created as a child of `container`, or
  3246. // as a child of the main map pane if not set.
  3247. createPane: function (name, container) {
  3248. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3249. pane = create$1('div', className, container || this._mapPane);
  3250. if (name) {
  3251. this._panes[name] = pane;
  3252. }
  3253. return pane;
  3254. },
  3255. // @section Methods for Getting Map State
  3256. // @method getCenter(): LatLng
  3257. // Returns the geographical center of the map view
  3258. getCenter: function () {
  3259. this._checkIfLoaded();
  3260. if (this._lastCenter && !this._moved()) {
  3261. return this._lastCenter.clone();
  3262. }
  3263. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3264. },
  3265. // @method getZoom(): Number
  3266. // Returns the current zoom level of the map view
  3267. getZoom: function () {
  3268. return this._zoom;
  3269. },
  3270. // @method getBounds(): LatLngBounds
  3271. // Returns the geographical bounds visible in the current map view
  3272. getBounds: function () {
  3273. var bounds = this.getPixelBounds(),
  3274. sw = this.unproject(bounds.getBottomLeft()),
  3275. ne = this.unproject(bounds.getTopRight());
  3276. return new LatLngBounds(sw, ne);
  3277. },
  3278. // @method getMinZoom(): Number
  3279. // 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.
  3280. getMinZoom: function () {
  3281. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3282. },
  3283. // @method getMaxZoom(): Number
  3284. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3285. getMaxZoom: function () {
  3286. return this.options.maxZoom === undefined ?
  3287. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3288. this.options.maxZoom;
  3289. },
  3290. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
  3291. // Returns the maximum zoom level on which the given bounds fit to the map
  3292. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3293. // instead returns the minimum zoom level on which the map view fits into
  3294. // the given bounds in its entirety.
  3295. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3296. bounds = toLatLngBounds(bounds);
  3297. padding = toPoint(padding || [0, 0]);
  3298. var zoom = this.getZoom() || 0,
  3299. min = this.getMinZoom(),
  3300. max = this.getMaxZoom(),
  3301. nw = bounds.getNorthWest(),
  3302. se = bounds.getSouthEast(),
  3303. size = this.getSize().subtract(padding),
  3304. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3305. snap = Browser.any3d ? this.options.zoomSnap : 1,
  3306. scalex = size.x / boundsSize.x,
  3307. scaley = size.y / boundsSize.y,
  3308. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3309. zoom = this.getScaleZoom(scale, zoom);
  3310. if (snap) {
  3311. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3312. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3313. }
  3314. return Math.max(min, Math.min(max, zoom));
  3315. },
  3316. // @method getSize(): Point
  3317. // Returns the current size of the map container (in pixels).
  3318. getSize: function () {
  3319. if (!this._size || this._sizeChanged) {
  3320. this._size = new Point(
  3321. this._container.clientWidth || 0,
  3322. this._container.clientHeight || 0);
  3323. this._sizeChanged = false;
  3324. }
  3325. return this._size.clone();
  3326. },
  3327. // @method getPixelBounds(): Bounds
  3328. // Returns the bounds of the current map view in projected pixel
  3329. // coordinates (sometimes useful in layer and overlay implementations).
  3330. getPixelBounds: function (center, zoom) {
  3331. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3332. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3333. },
  3334. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3335. // the map pane? "left point of the map layer" can be confusing, specially
  3336. // since there can be negative offsets.
  3337. // @method getPixelOrigin(): Point
  3338. // Returns the projected pixel coordinates of the top left point of
  3339. // the map layer (useful in custom layer and overlay implementations).
  3340. getPixelOrigin: function () {
  3341. this._checkIfLoaded();
  3342. return this._pixelOrigin;
  3343. },
  3344. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3345. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3346. // If `zoom` is omitted, the map's current zoom level is used.
  3347. getPixelWorldBounds: function (zoom) {
  3348. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3349. },
  3350. // @section Other Methods
  3351. // @method getPane(pane: String|HTMLElement): HTMLElement
  3352. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3353. getPane: function (pane) {
  3354. return typeof pane === 'string' ? this._panes[pane] : pane;
  3355. },
  3356. // @method getPanes(): Object
  3357. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3358. // the panes as values.
  3359. getPanes: function () {
  3360. return this._panes;
  3361. },
  3362. // @method getContainer: HTMLElement
  3363. // Returns the HTML element that contains the map.
  3364. getContainer: function () {
  3365. return this._container;
  3366. },
  3367. // @section Conversion Methods
  3368. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3369. // Returns the scale factor to be applied to a map transition from zoom level
  3370. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3371. getZoomScale: function (toZoom, fromZoom) {
  3372. // TODO replace with universal implementation after refactoring projections
  3373. var crs = this.options.crs;
  3374. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3375. return crs.scale(toZoom) / crs.scale(fromZoom);
  3376. },
  3377. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3378. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3379. // level and everything is scaled by a factor of `scale`. Inverse of
  3380. // [`getZoomScale`](#map-getZoomScale).
  3381. getScaleZoom: function (scale, fromZoom) {
  3382. var crs = this.options.crs;
  3383. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3384. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3385. return isNaN(zoom) ? Infinity : zoom;
  3386. },
  3387. // @method project(latlng: LatLng, zoom: Number): Point
  3388. // Projects a geographical coordinate `LatLng` according to the projection
  3389. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3390. // `Transformation`. The result is pixel coordinate relative to
  3391. // the CRS origin.
  3392. project: function (latlng, zoom) {
  3393. zoom = zoom === undefined ? this._zoom : zoom;
  3394. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3395. },
  3396. // @method unproject(point: Point, zoom: Number): LatLng
  3397. // Inverse of [`project`](#map-project).
  3398. unproject: function (point, zoom) {
  3399. zoom = zoom === undefined ? this._zoom : zoom;
  3400. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3401. },
  3402. // @method layerPointToLatLng(point: Point): LatLng
  3403. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3404. // returns the corresponding geographical coordinate (for the current zoom level).
  3405. layerPointToLatLng: function (point) {
  3406. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3407. return this.unproject(projectedPoint);
  3408. },
  3409. // @method latLngToLayerPoint(latlng: LatLng): Point
  3410. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3411. // relative to the [origin pixel](#map-getpixelorigin).
  3412. latLngToLayerPoint: function (latlng) {
  3413. var projectedPoint = this.project(toLatLng(latlng))._round();
  3414. return projectedPoint._subtract(this.getPixelOrigin());
  3415. },
  3416. // @method wrapLatLng(latlng: LatLng): LatLng
  3417. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3418. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3419. // CRS's bounds.
  3420. // By default this means longitude is wrapped around the dateline so its
  3421. // value is between -180 and +180 degrees.
  3422. wrapLatLng: function (latlng) {
  3423. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3424. },
  3425. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3426. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3427. // its center is within the CRS's bounds.
  3428. // By default this means the center longitude is wrapped around the dateline so its
  3429. // value is between -180 and +180 degrees, and the majority of the bounds
  3430. // overlaps the CRS's bounds.
  3431. wrapLatLngBounds: function (latlng) {
  3432. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3433. },
  3434. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3435. // Returns the distance between two geographical coordinates according to
  3436. // the map's CRS. By default this measures distance in meters.
  3437. distance: function (latlng1, latlng2) {
  3438. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3439. },
  3440. // @method containerPointToLayerPoint(point: Point): Point
  3441. // Given a pixel coordinate relative to the map container, returns the corresponding
  3442. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3443. containerPointToLayerPoint: function (point) { // (Point)
  3444. return toPoint(point).subtract(this._getMapPanePos());
  3445. },
  3446. // @method layerPointToContainerPoint(point: Point): Point
  3447. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3448. // returns the corresponding pixel coordinate relative to the map container.
  3449. layerPointToContainerPoint: function (point) { // (Point)
  3450. return toPoint(point).add(this._getMapPanePos());
  3451. },
  3452. // @method containerPointToLatLng(point: Point): LatLng
  3453. // Given a pixel coordinate relative to the map container, returns
  3454. // the corresponding geographical coordinate (for the current zoom level).
  3455. containerPointToLatLng: function (point) {
  3456. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3457. return this.layerPointToLatLng(layerPoint);
  3458. },
  3459. // @method latLngToContainerPoint(latlng: LatLng): Point
  3460. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3461. // relative to the map container.
  3462. latLngToContainerPoint: function (latlng) {
  3463. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3464. },
  3465. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3466. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3467. // map container where the event took place.
  3468. mouseEventToContainerPoint: function (e) {
  3469. return getMousePosition(e, this._container);
  3470. },
  3471. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3472. // Given a MouseEvent object, returns the pixel coordinate relative to
  3473. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3474. mouseEventToLayerPoint: function (e) {
  3475. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3476. },
  3477. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3478. // Given a MouseEvent object, returns geographical coordinate where the
  3479. // event took place.
  3480. mouseEventToLatLng: function (e) { // (MouseEvent)
  3481. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3482. },
  3483. // map initialization methods
  3484. _initContainer: function (id) {
  3485. var container = this._container = get(id);
  3486. if (!container) {
  3487. throw new Error('Map container not found.');
  3488. } else if (container._leaflet_id) {
  3489. throw new Error('Map container is already initialized.');
  3490. }
  3491. on(container, 'scroll', this._onScroll, this);
  3492. this._containerId = stamp(container);
  3493. },
  3494. _initLayout: function () {
  3495. var container = this._container;
  3496. this._fadeAnimated = this.options.fadeAnimation && Browser.any3d;
  3497. addClass(container, 'leaflet-container' +
  3498. (Browser.touch ? ' leaflet-touch' : '') +
  3499. (Browser.retina ? ' leaflet-retina' : '') +
  3500. (Browser.ielt9 ? ' leaflet-oldie' : '') +
  3501. (Browser.safari ? ' leaflet-safari' : '') +
  3502. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3503. var position = getStyle(container, 'position');
  3504. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  3505. container.style.position = 'relative';
  3506. }
  3507. this._initPanes();
  3508. if (this._initControlPos) {
  3509. this._initControlPos();
  3510. }
  3511. },
  3512. _initPanes: function () {
  3513. var panes = this._panes = {};
  3514. this._paneRenderers = {};
  3515. // @section
  3516. //
  3517. // Panes are DOM elements used to control the ordering of layers on the map. You
  3518. // can access panes with [`map.getPane`](#map-getpane) or
  3519. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3520. // [`map.createPane`](#map-createpane) method.
  3521. //
  3522. // Every map has the following default panes that differ only in zIndex.
  3523. //
  3524. // @pane mapPane: HTMLElement = 'auto'
  3525. // Pane that contains all other map panes
  3526. this._mapPane = this.createPane('mapPane', this._container);
  3527. setPosition(this._mapPane, new Point(0, 0));
  3528. // @pane tilePane: HTMLElement = 200
  3529. // Pane for `GridLayer`s and `TileLayer`s
  3530. this.createPane('tilePane');
  3531. // @pane overlayPane: HTMLElement = 400
  3532. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  3533. this.createPane('overlayPane');
  3534. // @pane shadowPane: HTMLElement = 500
  3535. // Pane for overlay shadows (e.g. `Marker` shadows)
  3536. this.createPane('shadowPane');
  3537. // @pane markerPane: HTMLElement = 600
  3538. // Pane for `Icon`s of `Marker`s
  3539. this.createPane('markerPane');
  3540. // @pane tooltipPane: HTMLElement = 650
  3541. // Pane for `Tooltip`s.
  3542. this.createPane('tooltipPane');
  3543. // @pane popupPane: HTMLElement = 700
  3544. // Pane for `Popup`s.
  3545. this.createPane('popupPane');
  3546. if (!this.options.markerZoomAnimation) {
  3547. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3548. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3549. }
  3550. },
  3551. // private methods that modify map state
  3552. // @section Map state change events
  3553. _resetView: function (center, zoom, noMoveStart) {
  3554. setPosition(this._mapPane, new Point(0, 0));
  3555. var loading = !this._loaded;
  3556. this._loaded = true;
  3557. zoom = this._limitZoom(zoom);
  3558. this.fire('viewprereset');
  3559. var zoomChanged = this._zoom !== zoom;
  3560. this
  3561. ._moveStart(zoomChanged, noMoveStart)
  3562. ._move(center, zoom)
  3563. ._moveEnd(zoomChanged);
  3564. // @event viewreset: Event
  3565. // Fired when the map needs to redraw its content (this usually happens
  3566. // on map zoom or load). Very useful for creating custom overlays.
  3567. this.fire('viewreset');
  3568. // @event load: Event
  3569. // Fired when the map is initialized (when its center and zoom are set
  3570. // for the first time).
  3571. if (loading) {
  3572. this.fire('load');
  3573. }
  3574. },
  3575. _moveStart: function (zoomChanged, noMoveStart) {
  3576. // @event zoomstart: Event
  3577. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3578. // @event movestart: Event
  3579. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3580. if (zoomChanged) {
  3581. this.fire('zoomstart');
  3582. }
  3583. if (!noMoveStart) {
  3584. this.fire('movestart');
  3585. }
  3586. return this;
  3587. },
  3588. _move: function (center, zoom, data, supressEvent) {
  3589. if (zoom === undefined) {
  3590. zoom = this._zoom;
  3591. }
  3592. var zoomChanged = this._zoom !== zoom;
  3593. this._zoom = zoom;
  3594. this._lastCenter = center;
  3595. this._pixelOrigin = this._getNewPixelOrigin(center);
  3596. if (!supressEvent) {
  3597. // @event zoom: Event
  3598. // Fired repeatedly during any change in zoom level,
  3599. // including zoom and fly animations.
  3600. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3601. this.fire('zoom', data);
  3602. }
  3603. // @event move: Event
  3604. // Fired repeatedly during any movement of the map,
  3605. // including pan and fly animations.
  3606. this.fire('move', data);
  3607. } else if (data && data.pinch) { // Always fire 'zoom' if pinching because #3530
  3608. this.fire('zoom', data);
  3609. }
  3610. return this;
  3611. },
  3612. _moveEnd: function (zoomChanged) {
  3613. // @event zoomend: Event
  3614. // Fired when the map zoom changed, after any animations.
  3615. if (zoomChanged) {
  3616. this.fire('zoomend');
  3617. }
  3618. // @event moveend: Event
  3619. // Fired when the center of the map stops changing
  3620. // (e.g. user stopped dragging the map or after non-centered zoom).
  3621. return this.fire('moveend');
  3622. },
  3623. _stop: function () {
  3624. cancelAnimFrame(this._flyToFrame);
  3625. if (this._panAnim) {
  3626. this._panAnim.stop();
  3627. }
  3628. return this;
  3629. },
  3630. _rawPanBy: function (offset) {
  3631. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3632. },
  3633. _getZoomSpan: function () {
  3634. return this.getMaxZoom() - this.getMinZoom();
  3635. },
  3636. _panInsideMaxBounds: function () {
  3637. if (!this._enforcingBounds) {
  3638. this.panInsideBounds(this.options.maxBounds);
  3639. }
  3640. },
  3641. _checkIfLoaded: function () {
  3642. if (!this._loaded) {
  3643. throw new Error('Set map center and zoom first.');
  3644. }
  3645. },
  3646. // DOM event handling
  3647. // @section Interaction events
  3648. _initEvents: function (remove) {
  3649. this._targets = {};
  3650. this._targets[stamp(this._container)] = this;
  3651. var onOff = remove ? off : on;
  3652. // @event click: MouseEvent
  3653. // Fired when the user clicks (or taps) the map.
  3654. // @event dblclick: MouseEvent
  3655. // Fired when the user double-clicks (or double-taps) the map.
  3656. // @event mousedown: MouseEvent
  3657. // Fired when the user pushes the mouse button on the map.
  3658. // @event mouseup: MouseEvent
  3659. // Fired when the user releases the mouse button on the map.
  3660. // @event mouseover: MouseEvent
  3661. // Fired when the mouse enters the map.
  3662. // @event mouseout: MouseEvent
  3663. // Fired when the mouse leaves the map.
  3664. // @event mousemove: MouseEvent
  3665. // Fired while the mouse moves over the map.
  3666. // @event contextmenu: MouseEvent
  3667. // Fired when the user pushes the right mouse button on the map, prevents
  3668. // default browser context menu from showing if there are listeners on
  3669. // this event. Also fired on mobile when the user holds a single touch
  3670. // for a second (also called long press).
  3671. // @event keypress: KeyboardEvent
  3672. // Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
  3673. // @event keydown: KeyboardEvent
  3674. // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
  3675. // the `keydown` event is fired for keys that produce a character value and for keys
  3676. // that do not produce a character value.
  3677. // @event keyup: KeyboardEvent
  3678. // Fired when the user releases a key from the keyboard while the map is focused.
  3679. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3680. 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
  3681. if (this.options.trackResize) {
  3682. onOff(window, 'resize', this._onResize, this);
  3683. }
  3684. if (Browser.any3d && this.options.transform3DLimit) {
  3685. (remove ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3686. }
  3687. },
  3688. _onResize: function () {
  3689. cancelAnimFrame(this._resizeRequest);
  3690. this._resizeRequest = requestAnimFrame(
  3691. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3692. },
  3693. _onScroll: function () {
  3694. this._container.scrollTop = 0;
  3695. this._container.scrollLeft = 0;
  3696. },
  3697. _onMoveEnd: function () {
  3698. var pos = this._getMapPanePos();
  3699. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3700. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3701. // a pixel offset on very high values, see: https://jsfiddle.net/dg6r5hhb/
  3702. this._resetView(this.getCenter(), this.getZoom());
  3703. }
  3704. },
  3705. _findEventTargets: function (e, type) {
  3706. var targets = [],
  3707. target,
  3708. isHover = type === 'mouseout' || type === 'mouseover',
  3709. src = e.target || e.srcElement,
  3710. dragging = false;
  3711. while (src) {
  3712. target = this._targets[stamp(src)];
  3713. if (target && (type === 'click' || type === 'preclick') && this._draggableMoved(target)) {
  3714. // Prevent firing click after you just dragged an object.
  3715. dragging = true;
  3716. break;
  3717. }
  3718. if (target && target.listens(type, true)) {
  3719. if (isHover && !isExternalTarget(src, e)) { break; }
  3720. targets.push(target);
  3721. if (isHover) { break; }
  3722. }
  3723. if (src === this._container) { break; }
  3724. src = src.parentNode;
  3725. }
  3726. if (!targets.length && !dragging && !isHover && this.listens(type, true)) {
  3727. targets = [this];
  3728. }
  3729. return targets;
  3730. },
  3731. _isClickDisabled: function (el) {
  3732. while (el && el !== this._container) {
  3733. if (el['_leaflet_disable_click']) { return true; }
  3734. el = el.parentNode;
  3735. }
  3736. },
  3737. _handleDOMEvent: function (e) {
  3738. var el = (e.target || e.srcElement);
  3739. if (!this._loaded || el['_leaflet_disable_events'] || e.type === 'click' && this._isClickDisabled(el)) {
  3740. return;
  3741. }
  3742. var type = e.type;
  3743. if (type === 'mousedown') {
  3744. // prevents outline when clicking on keyboard-focusable element
  3745. preventOutline(el);
  3746. }
  3747. this._fireDOMEvent(e, type);
  3748. },
  3749. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3750. _fireDOMEvent: function (e, type, canvasTargets) {
  3751. if (e.type === 'click') {
  3752. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3753. // @event preclick: MouseEvent
  3754. // Fired before mouse click on the map (sometimes useful when you
  3755. // want something to happen on click before any existing click
  3756. // handlers start running).
  3757. var synth = extend({}, e);
  3758. synth.type = 'preclick';
  3759. this._fireDOMEvent(synth, synth.type, canvasTargets);
  3760. }
  3761. // Find the layer the event is propagating from and its parents.
  3762. var targets = this._findEventTargets(e, type);
  3763. if (canvasTargets) {
  3764. var filtered = []; // pick only targets with listeners
  3765. for (var i = 0; i < canvasTargets.length; i++) {
  3766. if (canvasTargets[i].listens(type, true)) {
  3767. filtered.push(canvasTargets[i]);
  3768. }
  3769. }
  3770. targets = filtered.concat(targets);
  3771. }
  3772. if (!targets.length) { return; }
  3773. if (type === 'contextmenu') {
  3774. preventDefault(e);
  3775. }
  3776. var target = targets[0];
  3777. var data = {
  3778. originalEvent: e
  3779. };
  3780. if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
  3781. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  3782. data.containerPoint = isMarker ?
  3783. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3784. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3785. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3786. }
  3787. for (i = 0; i < targets.length; i++) {
  3788. targets[i].fire(type, data, true);
  3789. if (data.originalEvent._stopped ||
  3790. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3791. }
  3792. },
  3793. _draggableMoved: function (obj) {
  3794. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3795. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3796. },
  3797. _clearHandlers: function () {
  3798. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3799. this._handlers[i].disable();
  3800. }
  3801. },
  3802. // @section Other Methods
  3803. // @method whenReady(fn: Function, context?: Object): this
  3804. // Runs the given function `fn` when the map gets initialized with
  3805. // a view (center and zoom) and at least one layer, or immediately
  3806. // if it's already initialized, optionally passing a function context.
  3807. whenReady: function (callback, context) {
  3808. if (this._loaded) {
  3809. callback.call(context || this, {target: this});
  3810. } else {
  3811. this.on('load', callback, context);
  3812. }
  3813. return this;
  3814. },
  3815. // private methods for getting map state
  3816. _getMapPanePos: function () {
  3817. return getPosition(this._mapPane) || new Point(0, 0);
  3818. },
  3819. _moved: function () {
  3820. var pos = this._getMapPanePos();
  3821. return pos && !pos.equals([0, 0]);
  3822. },
  3823. _getTopLeftPoint: function (center, zoom) {
  3824. var pixelOrigin = center && zoom !== undefined ?
  3825. this._getNewPixelOrigin(center, zoom) :
  3826. this.getPixelOrigin();
  3827. return pixelOrigin.subtract(this._getMapPanePos());
  3828. },
  3829. _getNewPixelOrigin: function (center, zoom) {
  3830. var viewHalf = this.getSize()._divideBy(2);
  3831. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3832. },
  3833. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3834. var topLeft = this._getNewPixelOrigin(center, zoom);
  3835. return this.project(latlng, zoom)._subtract(topLeft);
  3836. },
  3837. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3838. var topLeft = this._getNewPixelOrigin(center, zoom);
  3839. return toBounds([
  3840. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3841. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3842. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3843. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3844. ]);
  3845. },
  3846. // layer point of the current center
  3847. _getCenterLayerPoint: function () {
  3848. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3849. },
  3850. // offset of the specified place to the current center in pixels
  3851. _getCenterOffset: function (latlng) {
  3852. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3853. },
  3854. // adjust center for view to get inside bounds
  3855. _limitCenter: function (center, zoom, bounds) {
  3856. if (!bounds) { return center; }
  3857. var centerPoint = this.project(center, zoom),
  3858. viewHalf = this.getSize().divideBy(2),
  3859. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3860. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3861. // If offset is less than a pixel, ignore.
  3862. // This prevents unstable projections from getting into
  3863. // an infinite loop of tiny offsets.
  3864. if (offset.round().equals([0, 0])) {
  3865. return center;
  3866. }
  3867. return this.unproject(centerPoint.add(offset), zoom);
  3868. },
  3869. // adjust offset for view to get inside bounds
  3870. _limitOffset: function (offset, bounds) {
  3871. if (!bounds) { return offset; }
  3872. var viewBounds = this.getPixelBounds(),
  3873. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3874. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3875. },
  3876. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3877. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3878. var projectedMaxBounds = toBounds(
  3879. this.project(maxBounds.getNorthEast(), zoom),
  3880. this.project(maxBounds.getSouthWest(), zoom)
  3881. ),
  3882. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3883. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3884. dx = this._rebound(minOffset.x, -maxOffset.x),
  3885. dy = this._rebound(minOffset.y, -maxOffset.y);
  3886. return new Point(dx, dy);
  3887. },
  3888. _rebound: function (left, right) {
  3889. return left + right > 0 ?
  3890. Math.round(left - right) / 2 :
  3891. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3892. },
  3893. _limitZoom: function (zoom) {
  3894. var min = this.getMinZoom(),
  3895. max = this.getMaxZoom(),
  3896. snap = Browser.any3d ? this.options.zoomSnap : 1;
  3897. if (snap) {
  3898. zoom = Math.round(zoom / snap) * snap;
  3899. }
  3900. return Math.max(min, Math.min(max, zoom));
  3901. },
  3902. _onPanTransitionStep: function () {
  3903. this.fire('move');
  3904. },
  3905. _onPanTransitionEnd: function () {
  3906. removeClass(this._mapPane, 'leaflet-pan-anim');
  3907. this.fire('moveend');
  3908. },
  3909. _tryAnimatedPan: function (center, options) {
  3910. // difference between the new and current centers in pixels
  3911. var offset = this._getCenterOffset(center)._trunc();
  3912. // don't animate too far unless animate: true specified in options
  3913. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3914. this.panBy(offset, options);
  3915. return true;
  3916. },
  3917. _createAnimProxy: function () {
  3918. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3919. this._panes.mapPane.appendChild(proxy);
  3920. this.on('zoomanim', function (e) {
  3921. var prop = TRANSFORM,
  3922. transform = this._proxy.style[prop];
  3923. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3924. // workaround for case when transform is the same and so transitionend event is not fired
  3925. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3926. this._onZoomTransitionEnd();
  3927. }
  3928. }, this);
  3929. this.on('load moveend', this._animMoveEnd, this);
  3930. this._on('unload', this._destroyAnimProxy, this);
  3931. },
  3932. _destroyAnimProxy: function () {
  3933. remove(this._proxy);
  3934. this.off('load moveend', this._animMoveEnd, this);
  3935. delete this._proxy;
  3936. },
  3937. _animMoveEnd: function () {
  3938. var c = this.getCenter(),
  3939. z = this.getZoom();
  3940. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3941. },
  3942. _catchTransitionEnd: function (e) {
  3943. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3944. this._onZoomTransitionEnd();
  3945. }
  3946. },
  3947. _nothingToAnimate: function () {
  3948. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3949. },
  3950. _tryAnimatedZoom: function (center, zoom, options) {
  3951. if (this._animatingZoom) { return true; }
  3952. options = options || {};
  3953. // don't animate if disabled, not supported or zoom difference is too large
  3954. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3955. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3956. // offset is the pixel coords of the zoom origin relative to the current center
  3957. var scale = this.getZoomScale(zoom),
  3958. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3959. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3960. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3961. requestAnimFrame(function () {
  3962. this
  3963. ._moveStart(true, false)
  3964. ._animateZoom(center, zoom, true);
  3965. }, this);
  3966. return true;
  3967. },
  3968. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3969. if (!this._mapPane) { return; }
  3970. if (startAnim) {
  3971. this._animatingZoom = true;
  3972. // remember what center/zoom to set after animation
  3973. this._animateToCenter = center;
  3974. this._animateToZoom = zoom;
  3975. addClass(this._mapPane, 'leaflet-zoom-anim');
  3976. }
  3977. // @section Other Events
  3978. // @event zoomanim: ZoomAnimEvent
  3979. // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
  3980. this.fire('zoomanim', {
  3981. center: center,
  3982. zoom: zoom,
  3983. noUpdate: noUpdate
  3984. });
  3985. if (!this._tempFireZoomEvent) {
  3986. this._tempFireZoomEvent = this._zoom !== this._animateToZoom;
  3987. }
  3988. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  3989. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3990. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3991. },
  3992. _onZoomTransitionEnd: function () {
  3993. if (!this._animatingZoom) { return; }
  3994. if (this._mapPane) {
  3995. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3996. }
  3997. this._animatingZoom = false;
  3998. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  3999. if (this._tempFireZoomEvent) {
  4000. this.fire('zoom');
  4001. }
  4002. delete this._tempFireZoomEvent;
  4003. this.fire('move');
  4004. this._moveEnd(true);
  4005. }
  4006. });
  4007. // @section
  4008. // @factory L.map(id: String, options?: Map options)
  4009. // Instantiates a map object given the DOM ID of a `<div>` element
  4010. // and optionally an object literal with `Map options`.
  4011. //
  4012. // @alternative
  4013. // @factory L.map(el: HTMLElement, options?: Map options)
  4014. // Instantiates a map object given an instance of a `<div>` HTML element
  4015. // and optionally an object literal with `Map options`.
  4016. function createMap(id, options) {
  4017. return new Map(id, options);
  4018. }
  4019. /*
  4020. * @class Control
  4021. * @aka L.Control
  4022. * @inherits Class
  4023. *
  4024. * L.Control is a base class for implementing map controls. Handles positioning.
  4025. * All other controls extend from this class.
  4026. */
  4027. var Control = Class.extend({
  4028. // @section
  4029. // @aka Control Options
  4030. options: {
  4031. // @option position: String = 'topright'
  4032. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  4033. // `'topright'`, `'bottomleft'` or `'bottomright'`
  4034. position: 'topright'
  4035. },
  4036. initialize: function (options) {
  4037. setOptions(this, options);
  4038. },
  4039. /* @section
  4040. * Classes extending L.Control will inherit the following methods:
  4041. *
  4042. * @method getPosition: string
  4043. * Returns the position of the control.
  4044. */
  4045. getPosition: function () {
  4046. return this.options.position;
  4047. },
  4048. // @method setPosition(position: string): this
  4049. // Sets the position of the control.
  4050. setPosition: function (position) {
  4051. var map = this._map;
  4052. if (map) {
  4053. map.removeControl(this);
  4054. }
  4055. this.options.position = position;
  4056. if (map) {
  4057. map.addControl(this);
  4058. }
  4059. return this;
  4060. },
  4061. // @method getContainer: HTMLElement
  4062. // Returns the HTMLElement that contains the control.
  4063. getContainer: function () {
  4064. return this._container;
  4065. },
  4066. // @method addTo(map: Map): this
  4067. // Adds the control to the given map.
  4068. addTo: function (map) {
  4069. this.remove();
  4070. this._map = map;
  4071. var container = this._container = this.onAdd(map),
  4072. pos = this.getPosition(),
  4073. corner = map._controlCorners[pos];
  4074. addClass(container, 'leaflet-control');
  4075. if (pos.indexOf('bottom') !== -1) {
  4076. corner.insertBefore(container, corner.firstChild);
  4077. } else {
  4078. corner.appendChild(container);
  4079. }
  4080. this._map.on('unload', this.remove, this);
  4081. return this;
  4082. },
  4083. // @method remove: this
  4084. // Removes the control from the map it is currently active on.
  4085. remove: function () {
  4086. if (!this._map) {
  4087. return this;
  4088. }
  4089. remove(this._container);
  4090. if (this.onRemove) {
  4091. this.onRemove(this._map);
  4092. }
  4093. this._map.off('unload', this.remove, this);
  4094. this._map = null;
  4095. return this;
  4096. },
  4097. _refocusOnMap: function (e) {
  4098. // if map exists and event is not a keyboard event
  4099. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  4100. this._map.getContainer().focus();
  4101. }
  4102. }
  4103. });
  4104. var control = function (options) {
  4105. return new Control(options);
  4106. };
  4107. /* @section Extension methods
  4108. * @uninheritable
  4109. *
  4110. * Every control should extend from `L.Control` and (re-)implement the following methods.
  4111. *
  4112. * @method onAdd(map: Map): HTMLElement
  4113. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  4114. *
  4115. * @method onRemove(map: Map)
  4116. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  4117. */
  4118. /* @namespace Map
  4119. * @section Methods for Layers and Controls
  4120. */
  4121. Map.include({
  4122. // @method addControl(control: Control): this
  4123. // Adds the given control to the map
  4124. addControl: function (control) {
  4125. control.addTo(this);
  4126. return this;
  4127. },
  4128. // @method removeControl(control: Control): this
  4129. // Removes the given control from the map
  4130. removeControl: function (control) {
  4131. control.remove();
  4132. return this;
  4133. },
  4134. _initControlPos: function () {
  4135. var corners = this._controlCorners = {},
  4136. l = 'leaflet-',
  4137. container = this._controlContainer =
  4138. create$1('div', l + 'control-container', this._container);
  4139. function createCorner(vSide, hSide) {
  4140. var className = l + vSide + ' ' + l + hSide;
  4141. corners[vSide + hSide] = create$1('div', className, container);
  4142. }
  4143. createCorner('top', 'left');
  4144. createCorner('top', 'right');
  4145. createCorner('bottom', 'left');
  4146. createCorner('bottom', 'right');
  4147. },
  4148. _clearControlPos: function () {
  4149. for (var i in this._controlCorners) {
  4150. remove(this._controlCorners[i]);
  4151. }
  4152. remove(this._controlContainer);
  4153. delete this._controlCorners;
  4154. delete this._controlContainer;
  4155. }
  4156. });
  4157. /*
  4158. * @class Control.Layers
  4159. * @aka L.Control.Layers
  4160. * @inherits Control
  4161. *
  4162. * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](https://leafletjs.com/examples/layers-control/)). Extends `Control`.
  4163. *
  4164. * @example
  4165. *
  4166. * ```js
  4167. * var baseLayers = {
  4168. * "Mapbox": mapbox,
  4169. * "OpenStreetMap": osm
  4170. * };
  4171. *
  4172. * var overlays = {
  4173. * "Marker": marker,
  4174. * "Roads": roadsLayer
  4175. * };
  4176. *
  4177. * L.control.layers(baseLayers, overlays).addTo(map);
  4178. * ```
  4179. *
  4180. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  4181. *
  4182. * ```js
  4183. * {
  4184. * "<someName1>": layer1,
  4185. * "<someName2>": layer2
  4186. * }
  4187. * ```
  4188. *
  4189. * The layer names can contain HTML, which allows you to add additional styling to the items:
  4190. *
  4191. * ```js
  4192. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  4193. * ```
  4194. */
  4195. var Layers = Control.extend({
  4196. // @section
  4197. // @aka Control.Layers options
  4198. options: {
  4199. // @option collapsed: Boolean = true
  4200. // If `true`, the control will be collapsed into an icon and expanded on mouse hover, touch, or keyboard activation.
  4201. collapsed: true,
  4202. position: 'topright',
  4203. // @option autoZIndex: Boolean = true
  4204. // 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.
  4205. autoZIndex: true,
  4206. // @option hideSingleBase: Boolean = false
  4207. // If `true`, the base layers in the control will be hidden when there is only one.
  4208. hideSingleBase: false,
  4209. // @option sortLayers: Boolean = false
  4210. // Whether to sort the layers. When `false`, layers will keep the order
  4211. // in which they were added to the control.
  4212. sortLayers: false,
  4213. // @option sortFunction: Function = *
  4214. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  4215. // that will be used for sorting the layers, when `sortLayers` is `true`.
  4216. // The function receives both the `L.Layer` instances and their names, as in
  4217. // `sortFunction(layerA, layerB, nameA, nameB)`.
  4218. // By default, it sorts layers alphabetically by their name.
  4219. sortFunction: function (layerA, layerB, nameA, nameB) {
  4220. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  4221. }
  4222. },
  4223. initialize: function (baseLayers, overlays, options) {
  4224. setOptions(this, options);
  4225. this._layerControlInputs = [];
  4226. this._layers = [];
  4227. this._lastZIndex = 0;
  4228. this._handlingClick = false;
  4229. for (var i in baseLayers) {
  4230. this._addLayer(baseLayers[i], i);
  4231. }
  4232. for (i in overlays) {
  4233. this._addLayer(overlays[i], i, true);
  4234. }
  4235. },
  4236. onAdd: function (map) {
  4237. this._initLayout();
  4238. this._update();
  4239. this._map = map;
  4240. map.on('zoomend', this._checkDisabledLayers, this);
  4241. for (var i = 0; i < this._layers.length; i++) {
  4242. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4243. }
  4244. return this._container;
  4245. },
  4246. addTo: function (map) {
  4247. Control.prototype.addTo.call(this, map);
  4248. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4249. return this._expandIfNotCollapsed();
  4250. },
  4251. onRemove: function () {
  4252. this._map.off('zoomend', this._checkDisabledLayers, this);
  4253. for (var i = 0; i < this._layers.length; i++) {
  4254. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4255. }
  4256. },
  4257. // @method addBaseLayer(layer: Layer, name: String): this
  4258. // Adds a base layer (radio button entry) with the given name to the control.
  4259. addBaseLayer: function (layer, name) {
  4260. this._addLayer(layer, name);
  4261. return (this._map) ? this._update() : this;
  4262. },
  4263. // @method addOverlay(layer: Layer, name: String): this
  4264. // Adds an overlay (checkbox entry) with the given name to the control.
  4265. addOverlay: function (layer, name) {
  4266. this._addLayer(layer, name, true);
  4267. return (this._map) ? this._update() : this;
  4268. },
  4269. // @method removeLayer(layer: Layer): this
  4270. // Remove the given layer from the control.
  4271. removeLayer: function (layer) {
  4272. layer.off('add remove', this._onLayerChange, this);
  4273. var obj = this._getLayer(stamp(layer));
  4274. if (obj) {
  4275. this._layers.splice(this._layers.indexOf(obj), 1);
  4276. }
  4277. return (this._map) ? this._update() : this;
  4278. },
  4279. // @method expand(): this
  4280. // Expand the control container if collapsed.
  4281. expand: function () {
  4282. addClass(this._container, 'leaflet-control-layers-expanded');
  4283. this._section.style.height = null;
  4284. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4285. if (acceptableHeight < this._section.clientHeight) {
  4286. addClass(this._section, 'leaflet-control-layers-scrollbar');
  4287. this._section.style.height = acceptableHeight + 'px';
  4288. } else {
  4289. removeClass(this._section, 'leaflet-control-layers-scrollbar');
  4290. }
  4291. this._checkDisabledLayers();
  4292. return this;
  4293. },
  4294. // @method collapse(): this
  4295. // Collapse the control container if expanded.
  4296. collapse: function () {
  4297. removeClass(this._container, 'leaflet-control-layers-expanded');
  4298. return this;
  4299. },
  4300. _initLayout: function () {
  4301. var className = 'leaflet-control-layers',
  4302. container = this._container = create$1('div', className),
  4303. collapsed = this.options.collapsed;
  4304. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4305. container.setAttribute('aria-haspopup', true);
  4306. disableClickPropagation(container);
  4307. disableScrollPropagation(container);
  4308. var section = this._section = create$1('section', className + '-list');
  4309. if (collapsed) {
  4310. this._map.on('click', this.collapse, this);
  4311. on(container, {
  4312. mouseenter: function () {
  4313. on(section, 'click', preventDefault);
  4314. this.expand();
  4315. setTimeout(function () {
  4316. off(section, 'click', preventDefault);
  4317. });
  4318. },
  4319. mouseleave: this.collapse
  4320. }, this);
  4321. }
  4322. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4323. link.href = '#';
  4324. link.title = 'Layers';
  4325. link.setAttribute('role', 'button');
  4326. on(link, 'click', preventDefault); // prevent link function
  4327. on(link, 'focus', this.expand, this);
  4328. if (!collapsed) {
  4329. this.expand();
  4330. }
  4331. this._baseLayersList = create$1('div', className + '-base', section);
  4332. this._separator = create$1('div', className + '-separator', section);
  4333. this._overlaysList = create$1('div', className + '-overlays', section);
  4334. container.appendChild(section);
  4335. },
  4336. _getLayer: function (id) {
  4337. for (var i = 0; i < this._layers.length; i++) {
  4338. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4339. return this._layers[i];
  4340. }
  4341. }
  4342. },
  4343. _addLayer: function (layer, name, overlay) {
  4344. if (this._map) {
  4345. layer.on('add remove', this._onLayerChange, this);
  4346. }
  4347. this._layers.push({
  4348. layer: layer,
  4349. name: name,
  4350. overlay: overlay
  4351. });
  4352. if (this.options.sortLayers) {
  4353. this._layers.sort(bind(function (a, b) {
  4354. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4355. }, this));
  4356. }
  4357. if (this.options.autoZIndex && layer.setZIndex) {
  4358. this._lastZIndex++;
  4359. layer.setZIndex(this._lastZIndex);
  4360. }
  4361. this._expandIfNotCollapsed();
  4362. },
  4363. _update: function () {
  4364. if (!this._container) { return this; }
  4365. empty(this._baseLayersList);
  4366. empty(this._overlaysList);
  4367. this._layerControlInputs = [];
  4368. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4369. for (i = 0; i < this._layers.length; i++) {
  4370. obj = this._layers[i];
  4371. this._addItem(obj);
  4372. overlaysPresent = overlaysPresent || obj.overlay;
  4373. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4374. baseLayersCount += !obj.overlay ? 1 : 0;
  4375. }
  4376. // Hide base layers section if there's only one layer.
  4377. if (this.options.hideSingleBase) {
  4378. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4379. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4380. }
  4381. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4382. return this;
  4383. },
  4384. _onLayerChange: function (e) {
  4385. if (!this._handlingClick) {
  4386. this._update();
  4387. }
  4388. var obj = this._getLayer(stamp(e.target));
  4389. // @namespace Map
  4390. // @section Layer events
  4391. // @event baselayerchange: LayersControlEvent
  4392. // Fired when the base layer is changed through the [layers control](#control-layers).
  4393. // @event overlayadd: LayersControlEvent
  4394. // Fired when an overlay is selected through the [layers control](#control-layers).
  4395. // @event overlayremove: LayersControlEvent
  4396. // Fired when an overlay is deselected through the [layers control](#control-layers).
  4397. // @namespace Control.Layers
  4398. var type = obj.overlay ?
  4399. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4400. (e.type === 'add' ? 'baselayerchange' : null);
  4401. if (type) {
  4402. this._map.fire(type, obj);
  4403. }
  4404. },
  4405. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see https://stackoverflow.com/a/119079)
  4406. _createRadioElement: function (name, checked) {
  4407. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4408. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4409. var radioFragment = document.createElement('div');
  4410. radioFragment.innerHTML = radioHtml;
  4411. return radioFragment.firstChild;
  4412. },
  4413. _addItem: function (obj) {
  4414. var label = document.createElement('label'),
  4415. checked = this._map.hasLayer(obj.layer),
  4416. input;
  4417. if (obj.overlay) {
  4418. input = document.createElement('input');
  4419. input.type = 'checkbox';
  4420. input.className = 'leaflet-control-layers-selector';
  4421. input.defaultChecked = checked;
  4422. } else {
  4423. input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);
  4424. }
  4425. this._layerControlInputs.push(input);
  4426. input.layerId = stamp(obj.layer);
  4427. on(input, 'click', this._onInputClick, this);
  4428. var name = document.createElement('span');
  4429. name.innerHTML = ' ' + obj.name;
  4430. // Helps from preventing layer control flicker when checkboxes are disabled
  4431. // https://github.com/Leaflet/Leaflet/issues/2771
  4432. var holder = document.createElement('span');
  4433. label.appendChild(holder);
  4434. holder.appendChild(input);
  4435. holder.appendChild(name);
  4436. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4437. container.appendChild(label);
  4438. this._checkDisabledLayers();
  4439. return label;
  4440. },
  4441. _onInputClick: function () {
  4442. var inputs = this._layerControlInputs,
  4443. input, layer;
  4444. var addedLayers = [],
  4445. removedLayers = [];
  4446. this._handlingClick = true;
  4447. for (var i = inputs.length - 1; i >= 0; i--) {
  4448. input = inputs[i];
  4449. layer = this._getLayer(input.layerId).layer;
  4450. if (input.checked) {
  4451. addedLayers.push(layer);
  4452. } else if (!input.checked) {
  4453. removedLayers.push(layer);
  4454. }
  4455. }
  4456. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4457. for (i = 0; i < removedLayers.length; i++) {
  4458. if (this._map.hasLayer(removedLayers[i])) {
  4459. this._map.removeLayer(removedLayers[i]);
  4460. }
  4461. }
  4462. for (i = 0; i < addedLayers.length; i++) {
  4463. if (!this._map.hasLayer(addedLayers[i])) {
  4464. this._map.addLayer(addedLayers[i]);
  4465. }
  4466. }
  4467. this._handlingClick = false;
  4468. this._refocusOnMap();
  4469. },
  4470. _checkDisabledLayers: function () {
  4471. var inputs = this._layerControlInputs,
  4472. input,
  4473. layer,
  4474. zoom = this._map.getZoom();
  4475. for (var i = inputs.length - 1; i >= 0; i--) {
  4476. input = inputs[i];
  4477. layer = this._getLayer(input.layerId).layer;
  4478. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4479. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4480. }
  4481. },
  4482. _expandIfNotCollapsed: function () {
  4483. if (this._map && !this.options.collapsed) {
  4484. this.expand();
  4485. }
  4486. return this;
  4487. }
  4488. });
  4489. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4490. // Creates a layers 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.
  4491. var layers = function (baseLayers, overlays, options) {
  4492. return new Layers(baseLayers, overlays, options);
  4493. };
  4494. /*
  4495. * @class Control.Zoom
  4496. * @aka L.Control.Zoom
  4497. * @inherits Control
  4498. *
  4499. * 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`.
  4500. */
  4501. var Zoom = Control.extend({
  4502. // @section
  4503. // @aka Control.Zoom options
  4504. options: {
  4505. position: 'topleft',
  4506. // @option zoomInText: String = '<span aria-hidden="true">+</span>'
  4507. // The text set on the 'zoom in' button.
  4508. zoomInText: '<span aria-hidden="true">+</span>',
  4509. // @option zoomInTitle: String = 'Zoom in'
  4510. // The title set on the 'zoom in' button.
  4511. zoomInTitle: 'Zoom in',
  4512. // @option zoomOutText: String = '<span aria-hidden="true">&#x2212;</span>'
  4513. // The text set on the 'zoom out' button.
  4514. zoomOutText: '<span aria-hidden="true">&#x2212;</span>',
  4515. // @option zoomOutTitle: String = 'Zoom out'
  4516. // The title set on the 'zoom out' button.
  4517. zoomOutTitle: 'Zoom out'
  4518. },
  4519. onAdd: function (map) {
  4520. var zoomName = 'leaflet-control-zoom',
  4521. container = create$1('div', zoomName + ' leaflet-bar'),
  4522. options = this.options;
  4523. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4524. zoomName + '-in', container, this._zoomIn);
  4525. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4526. zoomName + '-out', container, this._zoomOut);
  4527. this._updateDisabled();
  4528. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4529. return container;
  4530. },
  4531. onRemove: function (map) {
  4532. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4533. },
  4534. disable: function () {
  4535. this._disabled = true;
  4536. this._updateDisabled();
  4537. return this;
  4538. },
  4539. enable: function () {
  4540. this._disabled = false;
  4541. this._updateDisabled();
  4542. return this;
  4543. },
  4544. _zoomIn: function (e) {
  4545. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4546. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4547. }
  4548. },
  4549. _zoomOut: function (e) {
  4550. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4551. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4552. }
  4553. },
  4554. _createButton: function (html, title, className, container, fn) {
  4555. var link = create$1('a', className, container);
  4556. link.innerHTML = html;
  4557. link.href = '#';
  4558. link.title = title;
  4559. /*
  4560. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4561. */
  4562. link.setAttribute('role', 'button');
  4563. link.setAttribute('aria-label', title);
  4564. disableClickPropagation(link);
  4565. on(link, 'click', stop);
  4566. on(link, 'click', fn, this);
  4567. on(link, 'click', this._refocusOnMap, this);
  4568. return link;
  4569. },
  4570. _updateDisabled: function () {
  4571. var map = this._map,
  4572. className = 'leaflet-disabled';
  4573. removeClass(this._zoomInButton, className);
  4574. removeClass(this._zoomOutButton, className);
  4575. this._zoomInButton.setAttribute('aria-disabled', 'false');
  4576. this._zoomOutButton.setAttribute('aria-disabled', 'false');
  4577. if (this._disabled || map._zoom === map.getMinZoom()) {
  4578. addClass(this._zoomOutButton, className);
  4579. this._zoomOutButton.setAttribute('aria-disabled', 'true');
  4580. }
  4581. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4582. addClass(this._zoomInButton, className);
  4583. this._zoomInButton.setAttribute('aria-disabled', 'true');
  4584. }
  4585. }
  4586. });
  4587. // @namespace Map
  4588. // @section Control options
  4589. // @option zoomControl: Boolean = true
  4590. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4591. Map.mergeOptions({
  4592. zoomControl: true
  4593. });
  4594. Map.addInitHook(function () {
  4595. if (this.options.zoomControl) {
  4596. // @section Controls
  4597. // @property zoomControl: Control.Zoom
  4598. // The default zoom control (only available if the
  4599. // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
  4600. this.zoomControl = new Zoom();
  4601. this.addControl(this.zoomControl);
  4602. }
  4603. });
  4604. // @namespace Control.Zoom
  4605. // @factory L.control.zoom(options: Control.Zoom options)
  4606. // Creates a zoom control
  4607. var zoom = function (options) {
  4608. return new Zoom(options);
  4609. };
  4610. /*
  4611. * @class Control.Scale
  4612. * @aka L.Control.Scale
  4613. * @inherits Control
  4614. *
  4615. * 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`.
  4616. *
  4617. * @example
  4618. *
  4619. * ```js
  4620. * L.control.scale().addTo(map);
  4621. * ```
  4622. */
  4623. var Scale = Control.extend({
  4624. // @section
  4625. // @aka Control.Scale options
  4626. options: {
  4627. position: 'bottomleft',
  4628. // @option maxWidth: Number = 100
  4629. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4630. maxWidth: 100,
  4631. // @option metric: Boolean = True
  4632. // Whether to show the metric scale line (m/km).
  4633. metric: true,
  4634. // @option imperial: Boolean = True
  4635. // Whether to show the imperial scale line (mi/ft).
  4636. imperial: true
  4637. // @option updateWhenIdle: Boolean = false
  4638. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4639. },
  4640. onAdd: function (map) {
  4641. var className = 'leaflet-control-scale',
  4642. container = create$1('div', className),
  4643. options = this.options;
  4644. this._addScales(options, className + '-line', container);
  4645. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4646. map.whenReady(this._update, this);
  4647. return container;
  4648. },
  4649. onRemove: function (map) {
  4650. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4651. },
  4652. _addScales: function (options, className, container) {
  4653. if (options.metric) {
  4654. this._mScale = create$1('div', className, container);
  4655. }
  4656. if (options.imperial) {
  4657. this._iScale = create$1('div', className, container);
  4658. }
  4659. },
  4660. _update: function () {
  4661. var map = this._map,
  4662. y = map.getSize().y / 2;
  4663. var maxMeters = map.distance(
  4664. map.containerPointToLatLng([0, y]),
  4665. map.containerPointToLatLng([this.options.maxWidth, y]));
  4666. this._updateScales(maxMeters);
  4667. },
  4668. _updateScales: function (maxMeters) {
  4669. if (this.options.metric && maxMeters) {
  4670. this._updateMetric(maxMeters);
  4671. }
  4672. if (this.options.imperial && maxMeters) {
  4673. this._updateImperial(maxMeters);
  4674. }
  4675. },
  4676. _updateMetric: function (maxMeters) {
  4677. var meters = this._getRoundNum(maxMeters),
  4678. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4679. this._updateScale(this._mScale, label, meters / maxMeters);
  4680. },
  4681. _updateImperial: function (maxMeters) {
  4682. var maxFeet = maxMeters * 3.2808399,
  4683. maxMiles, miles, feet;
  4684. if (maxFeet > 5280) {
  4685. maxMiles = maxFeet / 5280;
  4686. miles = this._getRoundNum(maxMiles);
  4687. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4688. } else {
  4689. feet = this._getRoundNum(maxFeet);
  4690. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4691. }
  4692. },
  4693. _updateScale: function (scale, text, ratio) {
  4694. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4695. scale.innerHTML = text;
  4696. },
  4697. _getRoundNum: function (num) {
  4698. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4699. d = num / pow10;
  4700. d = d >= 10 ? 10 :
  4701. d >= 5 ? 5 :
  4702. d >= 3 ? 3 :
  4703. d >= 2 ? 2 : 1;
  4704. return pow10 * d;
  4705. }
  4706. });
  4707. // @factory L.control.scale(options?: Control.Scale options)
  4708. // Creates an scale control with the given options.
  4709. var scale = function (options) {
  4710. return new Scale(options);
  4711. };
  4712. var ukrainianFlag = '<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="12" height="8" viewBox="0 0 12 8" class="leaflet-attribution-flag"><path fill="#4C7BE1" d="M0 0h12v4H0z"/><path fill="#FFD500" d="M0 4h12v3H0z"/><path fill="#E0BC00" d="M0 7h12v1H0z"/></svg>';
  4713. /*
  4714. * @class Control.Attribution
  4715. * @aka L.Control.Attribution
  4716. * @inherits Control
  4717. *
  4718. * 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.
  4719. */
  4720. var Attribution = Control.extend({
  4721. // @section
  4722. // @aka Control.Attribution options
  4723. options: {
  4724. position: 'bottomright',
  4725. // @option prefix: String|false = 'Leaflet'
  4726. // The HTML text shown before the attributions. Pass `false` to disable.
  4727. prefix: '<a href="https://leafletjs.com" title="A JavaScript library for interactive maps">' + (Browser.inlineSvg ? ukrainianFlag + ' ' : '') + 'Leaflet</a>'
  4728. },
  4729. initialize: function (options) {
  4730. setOptions(this, options);
  4731. this._attributions = {};
  4732. },
  4733. onAdd: function (map) {
  4734. map.attributionControl = this;
  4735. this._container = create$1('div', 'leaflet-control-attribution');
  4736. disableClickPropagation(this._container);
  4737. // TODO ugly, refactor
  4738. for (var i in map._layers) {
  4739. if (map._layers[i].getAttribution) {
  4740. this.addAttribution(map._layers[i].getAttribution());
  4741. }
  4742. }
  4743. this._update();
  4744. map.on('layeradd', this._addAttribution, this);
  4745. return this._container;
  4746. },
  4747. onRemove: function (map) {
  4748. map.off('layeradd', this._addAttribution, this);
  4749. },
  4750. _addAttribution: function (ev) {
  4751. if (ev.layer.getAttribution) {
  4752. this.addAttribution(ev.layer.getAttribution());
  4753. ev.layer.once('remove', function () {
  4754. this.removeAttribution(ev.layer.getAttribution());
  4755. }, this);
  4756. }
  4757. },
  4758. // @method setPrefix(prefix: String|false): this
  4759. // The HTML text shown before the attributions. Pass `false` to disable.
  4760. setPrefix: function (prefix) {
  4761. this.options.prefix = prefix;
  4762. this._update();
  4763. return this;
  4764. },
  4765. // @method addAttribution(text: String): this
  4766. // Adds an attribution text (e.g. `'&copy; OpenStreetMap contributors'`).
  4767. addAttribution: function (text) {
  4768. if (!text) { return this; }
  4769. if (!this._attributions[text]) {
  4770. this._attributions[text] = 0;
  4771. }
  4772. this._attributions[text]++;
  4773. this._update();
  4774. return this;
  4775. },
  4776. // @method removeAttribution(text: String): this
  4777. // Removes an attribution text.
  4778. removeAttribution: function (text) {
  4779. if (!text) { return this; }
  4780. if (this._attributions[text]) {
  4781. this._attributions[text]--;
  4782. this._update();
  4783. }
  4784. return this;
  4785. },
  4786. _update: function () {
  4787. if (!this._map) { return; }
  4788. var attribs = [];
  4789. for (var i in this._attributions) {
  4790. if (this._attributions[i]) {
  4791. attribs.push(i);
  4792. }
  4793. }
  4794. var prefixAndAttribs = [];
  4795. if (this.options.prefix) {
  4796. prefixAndAttribs.push(this.options.prefix);
  4797. }
  4798. if (attribs.length) {
  4799. prefixAndAttribs.push(attribs.join(', '));
  4800. }
  4801. this._container.innerHTML = prefixAndAttribs.join(' <span aria-hidden="true">|</span> ');
  4802. }
  4803. });
  4804. // @namespace Map
  4805. // @section Control options
  4806. // @option attributionControl: Boolean = true
  4807. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4808. Map.mergeOptions({
  4809. attributionControl: true
  4810. });
  4811. Map.addInitHook(function () {
  4812. if (this.options.attributionControl) {
  4813. new Attribution().addTo(this);
  4814. }
  4815. });
  4816. // @namespace Control.Attribution
  4817. // @factory L.control.attribution(options: Control.Attribution options)
  4818. // Creates an attribution control.
  4819. var attribution = function (options) {
  4820. return new Attribution(options);
  4821. };
  4822. Control.Layers = Layers;
  4823. Control.Zoom = Zoom;
  4824. Control.Scale = Scale;
  4825. Control.Attribution = Attribution;
  4826. control.layers = layers;
  4827. control.zoom = zoom;
  4828. control.scale = scale;
  4829. control.attribution = attribution;
  4830. /*
  4831. L.Handler is a base class for handler classes that are used internally to inject
  4832. interaction features like dragging to classes like Map and Marker.
  4833. */
  4834. // @class Handler
  4835. // @aka L.Handler
  4836. // Abstract class for map interaction handlers
  4837. var Handler = Class.extend({
  4838. initialize: function (map) {
  4839. this._map = map;
  4840. },
  4841. // @method enable(): this
  4842. // Enables the handler
  4843. enable: function () {
  4844. if (this._enabled) { return this; }
  4845. this._enabled = true;
  4846. this.addHooks();
  4847. return this;
  4848. },
  4849. // @method disable(): this
  4850. // Disables the handler
  4851. disable: function () {
  4852. if (!this._enabled) { return this; }
  4853. this._enabled = false;
  4854. this.removeHooks();
  4855. return this;
  4856. },
  4857. // @method enabled(): Boolean
  4858. // Returns `true` if the handler is enabled
  4859. enabled: function () {
  4860. return !!this._enabled;
  4861. }
  4862. // @section Extension methods
  4863. // Classes inheriting from `Handler` must implement the two following methods:
  4864. // @method addHooks()
  4865. // Called when the handler is enabled, should add event hooks.
  4866. // @method removeHooks()
  4867. // Called when the handler is disabled, should remove the event hooks added previously.
  4868. });
  4869. // @section There is static function which can be called without instantiating L.Handler:
  4870. // @function addTo(map: Map, name: String): this
  4871. // Adds a new Handler to the given map with the given name.
  4872. Handler.addTo = function (map, name) {
  4873. map.addHandler(name, this);
  4874. return this;
  4875. };
  4876. var Mixin = {Events: Events};
  4877. /*
  4878. * @class Draggable
  4879. * @aka L.Draggable
  4880. * @inherits Evented
  4881. *
  4882. * A class for making DOM elements draggable (including touch support).
  4883. * Used internally for map and marker dragging. Only works for elements
  4884. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4885. *
  4886. * @example
  4887. * ```js
  4888. * var draggable = new L.Draggable(elementToDrag);
  4889. * draggable.enable();
  4890. * ```
  4891. */
  4892. var START = Browser.touch ? 'touchstart mousedown' : 'mousedown';
  4893. var Draggable = Evented.extend({
  4894. options: {
  4895. // @section
  4896. // @aka Draggable options
  4897. // @option clickTolerance: Number = 3
  4898. // The max number of pixels a user can shift the mouse pointer during a click
  4899. // for it to be considered a valid click (as opposed to a mouse drag).
  4900. clickTolerance: 3
  4901. },
  4902. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4903. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4904. initialize: function (element, dragStartTarget, preventOutline, options) {
  4905. setOptions(this, options);
  4906. this._element = element;
  4907. this._dragStartTarget = dragStartTarget || element;
  4908. this._preventOutline = preventOutline;
  4909. },
  4910. // @method enable()
  4911. // Enables the dragging ability
  4912. enable: function () {
  4913. if (this._enabled) { return; }
  4914. on(this._dragStartTarget, START, this._onDown, this);
  4915. this._enabled = true;
  4916. },
  4917. // @method disable()
  4918. // Disables the dragging ability
  4919. disable: function () {
  4920. if (!this._enabled) { return; }
  4921. // If we're currently dragging this draggable,
  4922. // disabling it counts as first ending the drag.
  4923. if (Draggable._dragging === this) {
  4924. this.finishDrag(true);
  4925. }
  4926. off(this._dragStartTarget, START, this._onDown, this);
  4927. this._enabled = false;
  4928. this._moved = false;
  4929. },
  4930. _onDown: function (e) {
  4931. // Ignore the event if disabled; this happens in IE11
  4932. // under some circumstances, see #3666.
  4933. if (!this._enabled) { return; }
  4934. this._moved = false;
  4935. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4936. if (e.touches && e.touches.length !== 1) {
  4937. // Finish dragging to avoid conflict with touchZoom
  4938. if (Draggable._dragging === this) {
  4939. this.finishDrag();
  4940. }
  4941. return;
  4942. }
  4943. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4944. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4945. if (this._preventOutline) {
  4946. preventOutline(this._element);
  4947. }
  4948. disableImageDrag();
  4949. disableTextSelection();
  4950. if (this._moving) { return; }
  4951. // @event down: Event
  4952. // Fired when a drag is about to start.
  4953. this.fire('down');
  4954. var first = e.touches ? e.touches[0] : e,
  4955. sizedParent = getSizedParentNode(this._element);
  4956. this._startPoint = new Point(first.clientX, first.clientY);
  4957. this._startPos = getPosition(this._element);
  4958. // Cache the scale, so that we can continuously compensate for it during drag (_onMove).
  4959. this._parentScale = getScale(sizedParent);
  4960. var mouseevent = e.type === 'mousedown';
  4961. on(document, mouseevent ? 'mousemove' : 'touchmove', this._onMove, this);
  4962. on(document, mouseevent ? 'mouseup' : 'touchend touchcancel', this._onUp, this);
  4963. },
  4964. _onMove: function (e) {
  4965. // Ignore the event if disabled; this happens in IE11
  4966. // under some circumstances, see #3666.
  4967. if (!this._enabled) { return; }
  4968. if (e.touches && e.touches.length > 1) {
  4969. this._moved = true;
  4970. return;
  4971. }
  4972. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4973. offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);
  4974. if (!offset.x && !offset.y) { return; }
  4975. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4976. // We assume that the parent container's position, border and scale do not change for the duration of the drag.
  4977. // Therefore there is no need to account for the position and border (they are eliminated by the subtraction)
  4978. // and we can use the cached value for the scale.
  4979. offset.x /= this._parentScale.x;
  4980. offset.y /= this._parentScale.y;
  4981. preventDefault(e);
  4982. if (!this._moved) {
  4983. // @event dragstart: Event
  4984. // Fired when a drag starts
  4985. this.fire('dragstart');
  4986. this._moved = true;
  4987. addClass(document.body, 'leaflet-dragging');
  4988. this._lastTarget = e.target || e.srcElement;
  4989. // IE and Edge do not give the <use> element, so fetch it
  4990. // if necessary
  4991. if (window.SVGElementInstance && this._lastTarget instanceof window.SVGElementInstance) {
  4992. this._lastTarget = this._lastTarget.correspondingUseElement;
  4993. }
  4994. addClass(this._lastTarget, 'leaflet-drag-target');
  4995. }
  4996. this._newPos = this._startPos.add(offset);
  4997. this._moving = true;
  4998. this._lastEvent = e;
  4999. this._updatePosition();
  5000. },
  5001. _updatePosition: function () {
  5002. var e = {originalEvent: this._lastEvent};
  5003. // @event predrag: Event
  5004. // Fired continuously during dragging *before* each corresponding
  5005. // update of the element's position.
  5006. this.fire('predrag', e);
  5007. setPosition(this._element, this._newPos);
  5008. // @event drag: Event
  5009. // Fired continuously during dragging.
  5010. this.fire('drag', e);
  5011. },
  5012. _onUp: function () {
  5013. // Ignore the event if disabled; this happens in IE11
  5014. // under some circumstances, see #3666.
  5015. if (!this._enabled) { return; }
  5016. this.finishDrag();
  5017. },
  5018. finishDrag: function (noInertia) {
  5019. removeClass(document.body, 'leaflet-dragging');
  5020. if (this._lastTarget) {
  5021. removeClass(this._lastTarget, 'leaflet-drag-target');
  5022. this._lastTarget = null;
  5023. }
  5024. off(document, 'mousemove touchmove', this._onMove, this);
  5025. off(document, 'mouseup touchend touchcancel', this._onUp, this);
  5026. enableImageDrag();
  5027. enableTextSelection();
  5028. if (this._moved && this._moving) {
  5029. // @event dragend: DragEndEvent
  5030. // Fired when the drag ends.
  5031. this.fire('dragend', {
  5032. noInertia: noInertia,
  5033. distance: this._newPos.distanceTo(this._startPos)
  5034. });
  5035. }
  5036. this._moving = false;
  5037. Draggable._dragging = false;
  5038. }
  5039. });
  5040. /*
  5041. * @namespace LineUtil
  5042. *
  5043. * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
  5044. */
  5045. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  5046. // Improves rendering performance dramatically by lessening the number of points to draw.
  5047. // @function simplify(points: Point[], tolerance: Number): Point[]
  5048. // Dramatically reduces the number of points in a polyline while retaining
  5049. // its shape and returns a new array of simplified points, using the
  5050. // [Ramer-Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm).
  5051. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  5052. // each zoom level and also reducing visual noise. tolerance affects the amount of
  5053. // simplification (lesser value means higher quality but slower and with more points).
  5054. // Also released as a separated micro-library [Simplify.js](https://mourner.github.io/simplify-js/).
  5055. function simplify(points, tolerance) {
  5056. if (!tolerance || !points.length) {
  5057. return points.slice();
  5058. }
  5059. var sqTolerance = tolerance * tolerance;
  5060. // stage 1: vertex reduction
  5061. points = _reducePoints(points, sqTolerance);
  5062. // stage 2: Douglas-Peucker simplification
  5063. points = _simplifyDP(points, sqTolerance);
  5064. return points;
  5065. }
  5066. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  5067. // Returns the distance between point `p` and segment `p1` to `p2`.
  5068. function pointToSegmentDistance(p, p1, p2) {
  5069. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  5070. }
  5071. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  5072. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  5073. function closestPointOnSegment(p, p1, p2) {
  5074. return _sqClosestPointOnSegment(p, p1, p2);
  5075. }
  5076. // Ramer-Douglas-Peucker simplification, see https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
  5077. function _simplifyDP(points, sqTolerance) {
  5078. var len = points.length,
  5079. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  5080. markers = new ArrayConstructor(len);
  5081. markers[0] = markers[len - 1] = 1;
  5082. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  5083. var i,
  5084. newPoints = [];
  5085. for (i = 0; i < len; i++) {
  5086. if (markers[i]) {
  5087. newPoints.push(points[i]);
  5088. }
  5089. }
  5090. return newPoints;
  5091. }
  5092. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  5093. var maxSqDist = 0,
  5094. index, i, sqDist;
  5095. for (i = first + 1; i <= last - 1; i++) {
  5096. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  5097. if (sqDist > maxSqDist) {
  5098. index = i;
  5099. maxSqDist = sqDist;
  5100. }
  5101. }
  5102. if (maxSqDist > sqTolerance) {
  5103. markers[index] = 1;
  5104. _simplifyDPStep(points, markers, sqTolerance, first, index);
  5105. _simplifyDPStep(points, markers, sqTolerance, index, last);
  5106. }
  5107. }
  5108. // reduce points that are too close to each other to a single point
  5109. function _reducePoints(points, sqTolerance) {
  5110. var reducedPoints = [points[0]];
  5111. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  5112. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  5113. reducedPoints.push(points[i]);
  5114. prev = i;
  5115. }
  5116. }
  5117. if (prev < len - 1) {
  5118. reducedPoints.push(points[len - 1]);
  5119. }
  5120. return reducedPoints;
  5121. }
  5122. var _lastCode;
  5123. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  5124. // Clips the segment a to b by rectangular bounds with the
  5125. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  5126. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  5127. // points that are on the screen or near, increasing performance.
  5128. function clipSegment(a, b, bounds, useLastCode, round) {
  5129. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  5130. codeB = _getBitCode(b, bounds),
  5131. codeOut, p, newCode;
  5132. // save 2nd code to avoid calculating it on the next segment
  5133. _lastCode = codeB;
  5134. while (true) {
  5135. // if a,b is inside the clip window (trivial accept)
  5136. if (!(codeA | codeB)) {
  5137. return [a, b];
  5138. }
  5139. // if a,b is outside the clip window (trivial reject)
  5140. if (codeA & codeB) {
  5141. return false;
  5142. }
  5143. // other cases
  5144. codeOut = codeA || codeB;
  5145. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  5146. newCode = _getBitCode(p, bounds);
  5147. if (codeOut === codeA) {
  5148. a = p;
  5149. codeA = newCode;
  5150. } else {
  5151. b = p;
  5152. codeB = newCode;
  5153. }
  5154. }
  5155. }
  5156. function _getEdgeIntersection(a, b, code, bounds, round) {
  5157. var dx = b.x - a.x,
  5158. dy = b.y - a.y,
  5159. min = bounds.min,
  5160. max = bounds.max,
  5161. x, y;
  5162. if (code & 8) { // top
  5163. x = a.x + dx * (max.y - a.y) / dy;
  5164. y = max.y;
  5165. } else if (code & 4) { // bottom
  5166. x = a.x + dx * (min.y - a.y) / dy;
  5167. y = min.y;
  5168. } else if (code & 2) { // right
  5169. x = max.x;
  5170. y = a.y + dy * (max.x - a.x) / dx;
  5171. } else if (code & 1) { // left
  5172. x = min.x;
  5173. y = a.y + dy * (min.x - a.x) / dx;
  5174. }
  5175. return new Point(x, y, round);
  5176. }
  5177. function _getBitCode(p, bounds) {
  5178. var code = 0;
  5179. if (p.x < bounds.min.x) { // left
  5180. code |= 1;
  5181. } else if (p.x > bounds.max.x) { // right
  5182. code |= 2;
  5183. }
  5184. if (p.y < bounds.min.y) { // bottom
  5185. code |= 4;
  5186. } else if (p.y > bounds.max.y) { // top
  5187. code |= 8;
  5188. }
  5189. return code;
  5190. }
  5191. // square distance (to avoid unnecessary Math.sqrt calls)
  5192. function _sqDist(p1, p2) {
  5193. var dx = p2.x - p1.x,
  5194. dy = p2.y - p1.y;
  5195. return dx * dx + dy * dy;
  5196. }
  5197. // return closest point on segment or distance to that point
  5198. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  5199. var x = p1.x,
  5200. y = p1.y,
  5201. dx = p2.x - x,
  5202. dy = p2.y - y,
  5203. dot = dx * dx + dy * dy,
  5204. t;
  5205. if (dot > 0) {
  5206. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  5207. if (t > 1) {
  5208. x = p2.x;
  5209. y = p2.y;
  5210. } else if (t > 0) {
  5211. x += dx * t;
  5212. y += dy * t;
  5213. }
  5214. }
  5215. dx = p.x - x;
  5216. dy = p.y - y;
  5217. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  5218. }
  5219. // @function isFlat(latlngs: LatLng[]): Boolean
  5220. // Returns true if `latlngs` is a flat array, false is nested.
  5221. function isFlat(latlngs) {
  5222. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  5223. }
  5224. function _flat(latlngs) {
  5225. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  5226. return isFlat(latlngs);
  5227. }
  5228. /* @function polylineCenter(latlngs: LatLng[], crs: CRS): LatLng
  5229. * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polyline.
  5230. */
  5231. function polylineCenter(latlngs, crs) {
  5232. var i, halfDist, segDist, dist, p1, p2, ratio, center;
  5233. if (!latlngs || latlngs.length === 0) {
  5234. throw new Error('latlngs not passed');
  5235. }
  5236. if (!isFlat(latlngs)) {
  5237. console.warn('latlngs are not flat! Only the first ring will be used');
  5238. latlngs = latlngs[0];
  5239. }
  5240. var points = [];
  5241. for (var j in latlngs) {
  5242. points.push(crs.project(toLatLng(latlngs[j])));
  5243. }
  5244. var len = points.length;
  5245. for (i = 0, halfDist = 0; i < len - 1; i++) {
  5246. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  5247. }
  5248. // The line is so small in the current view that all points are on the same pixel.
  5249. if (halfDist === 0) {
  5250. center = points[0];
  5251. } else {
  5252. for (i = 0, dist = 0; i < len - 1; i++) {
  5253. p1 = points[i];
  5254. p2 = points[i + 1];
  5255. segDist = p1.distanceTo(p2);
  5256. dist += segDist;
  5257. if (dist > halfDist) {
  5258. ratio = (dist - halfDist) / segDist;
  5259. center = [
  5260. p2.x - ratio * (p2.x - p1.x),
  5261. p2.y - ratio * (p2.y - p1.y)
  5262. ];
  5263. break;
  5264. }
  5265. }
  5266. }
  5267. return crs.unproject(toPoint(center));
  5268. }
  5269. var LineUtil = {
  5270. __proto__: null,
  5271. simplify: simplify,
  5272. pointToSegmentDistance: pointToSegmentDistance,
  5273. closestPointOnSegment: closestPointOnSegment,
  5274. clipSegment: clipSegment,
  5275. _getEdgeIntersection: _getEdgeIntersection,
  5276. _getBitCode: _getBitCode,
  5277. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5278. isFlat: isFlat,
  5279. _flat: _flat,
  5280. polylineCenter: polylineCenter
  5281. };
  5282. /*
  5283. * @namespace PolyUtil
  5284. * Various utility functions for polygon geometries.
  5285. */
  5286. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5287. * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).
  5288. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5289. * performance. Note that polygon points needs different algorithm for clipping
  5290. * than polyline, so there's a separate method for it.
  5291. */
  5292. function clipPolygon(points, bounds, round) {
  5293. var clippedPoints,
  5294. edges = [1, 4, 2, 8],
  5295. i, j, k,
  5296. a, b,
  5297. len, edge, p;
  5298. for (i = 0, len = points.length; i < len; i++) {
  5299. points[i]._code = _getBitCode(points[i], bounds);
  5300. }
  5301. // for each edge (left, bottom, right, top)
  5302. for (k = 0; k < 4; k++) {
  5303. edge = edges[k];
  5304. clippedPoints = [];
  5305. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5306. a = points[i];
  5307. b = points[j];
  5308. // if a is inside the clip window
  5309. if (!(a._code & edge)) {
  5310. // if b is outside the clip window (a->b goes out of screen)
  5311. if (b._code & edge) {
  5312. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5313. p._code = _getBitCode(p, bounds);
  5314. clippedPoints.push(p);
  5315. }
  5316. clippedPoints.push(a);
  5317. // else if b is inside the clip window (a->b enters the screen)
  5318. } else if (!(b._code & edge)) {
  5319. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5320. p._code = _getBitCode(p, bounds);
  5321. clippedPoints.push(p);
  5322. }
  5323. }
  5324. points = clippedPoints;
  5325. }
  5326. return points;
  5327. }
  5328. /* @function polygonCenter(latlngs: LatLng[] crs: CRS): LatLng
  5329. * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polygon.
  5330. */
  5331. function polygonCenter(latlngs, crs) {
  5332. var i, j, p1, p2, f, area, x, y, center;
  5333. if (!latlngs || latlngs.length === 0) {
  5334. throw new Error('latlngs not passed');
  5335. }
  5336. if (!isFlat(latlngs)) {
  5337. console.warn('latlngs are not flat! Only the first ring will be used');
  5338. latlngs = latlngs[0];
  5339. }
  5340. var points = [];
  5341. for (var k in latlngs) {
  5342. points.push(crs.project(toLatLng(latlngs[k])));
  5343. }
  5344. var len = points.length;
  5345. area = x = y = 0;
  5346. // polygon centroid algorithm;
  5347. for (i = 0, j = len - 1; i < len; j = i++) {
  5348. p1 = points[i];
  5349. p2 = points[j];
  5350. f = p1.y * p2.x - p2.y * p1.x;
  5351. x += (p1.x + p2.x) * f;
  5352. y += (p1.y + p2.y) * f;
  5353. area += f * 3;
  5354. }
  5355. if (area === 0) {
  5356. // Polygon is so small that all points are on same pixel.
  5357. center = points[0];
  5358. } else {
  5359. center = [x / area, y / area];
  5360. }
  5361. return crs.unproject(toPoint(center));
  5362. }
  5363. var PolyUtil = {
  5364. __proto__: null,
  5365. clipPolygon: clipPolygon,
  5366. polygonCenter: polygonCenter
  5367. };
  5368. /*
  5369. * @namespace Projection
  5370. * @section
  5371. * Leaflet comes with a set of already defined Projections out of the box:
  5372. *
  5373. * @projection L.Projection.LonLat
  5374. *
  5375. * Equirectangular, or Plate Carree projection — the most simple projection,
  5376. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5377. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5378. * `EPSG:4326` and `Simple` CRS.
  5379. */
  5380. var LonLat = {
  5381. project: function (latlng) {
  5382. return new Point(latlng.lng, latlng.lat);
  5383. },
  5384. unproject: function (point) {
  5385. return new LatLng(point.y, point.x);
  5386. },
  5387. bounds: new Bounds([-180, -90], [180, 90])
  5388. };
  5389. /*
  5390. * @namespace Projection
  5391. * @projection L.Projection.Mercator
  5392. *
  5393. * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.
  5394. */
  5395. var Mercator = {
  5396. R: 6378137,
  5397. R_MINOR: 6356752.314245179,
  5398. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5399. project: function (latlng) {
  5400. var d = Math.PI / 180,
  5401. r = this.R,
  5402. y = latlng.lat * d,
  5403. tmp = this.R_MINOR / r,
  5404. e = Math.sqrt(1 - tmp * tmp),
  5405. con = e * Math.sin(y);
  5406. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5407. y = -r * Math.log(Math.max(ts, 1E-10));
  5408. return new Point(latlng.lng * d * r, y);
  5409. },
  5410. unproject: function (point) {
  5411. var d = 180 / Math.PI,
  5412. r = this.R,
  5413. tmp = this.R_MINOR / r,
  5414. e = Math.sqrt(1 - tmp * tmp),
  5415. ts = Math.exp(-point.y / r),
  5416. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5417. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5418. con = e * Math.sin(phi);
  5419. con = Math.pow((1 - con) / (1 + con), e / 2);
  5420. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5421. phi += dphi;
  5422. }
  5423. return new LatLng(phi * d, point.x * d / r);
  5424. }
  5425. };
  5426. /*
  5427. * @class Projection
  5428. * An object with methods for projecting geographical coordinates of the world onto
  5429. * a flat surface (and back). See [Map projection](https://en.wikipedia.org/wiki/Map_projection).
  5430. * @property bounds: Bounds
  5431. * The bounds (specified in CRS units) where the projection is valid
  5432. * @method project(latlng: LatLng): Point
  5433. * Projects geographical coordinates into a 2D point.
  5434. * Only accepts actual `L.LatLng` instances, not arrays.
  5435. * @method unproject(point: Point): LatLng
  5436. * The inverse of `project`. Projects a 2D point into a geographical location.
  5437. * Only accepts actual `L.Point` instances, not arrays.
  5438. * Note that the projection instances do not inherit from Leaflet's `Class` object,
  5439. * and can't be instantiated. Also, new classes can't inherit from them,
  5440. * and methods can't be added to them with the `include` function.
  5441. */
  5442. var index = {
  5443. __proto__: null,
  5444. LonLat: LonLat,
  5445. Mercator: Mercator,
  5446. SphericalMercator: SphericalMercator
  5447. };
  5448. /*
  5449. * @namespace CRS
  5450. * @crs L.CRS.EPSG3395
  5451. *
  5452. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5453. */
  5454. var EPSG3395 = extend({}, Earth, {
  5455. code: 'EPSG:3395',
  5456. projection: Mercator,
  5457. transformation: (function () {
  5458. var scale = 0.5 / (Math.PI * Mercator.R);
  5459. return toTransformation(scale, 0.5, -scale, 0.5);
  5460. }())
  5461. });
  5462. /*
  5463. * @namespace CRS
  5464. * @crs L.CRS.EPSG4326
  5465. *
  5466. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5467. *
  5468. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5469. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5470. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5471. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5472. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5473. */
  5474. var EPSG4326 = extend({}, Earth, {
  5475. code: 'EPSG:4326',
  5476. projection: LonLat,
  5477. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5478. });
  5479. /*
  5480. * @namespace CRS
  5481. * @crs L.CRS.Simple
  5482. *
  5483. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5484. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5485. * axis should still be inverted (going from bottom to top). `distance()` returns
  5486. * simple euclidean distance.
  5487. */
  5488. var Simple = extend({}, CRS, {
  5489. projection: LonLat,
  5490. transformation: toTransformation(1, 0, -1, 0),
  5491. scale: function (zoom) {
  5492. return Math.pow(2, zoom);
  5493. },
  5494. zoom: function (scale) {
  5495. return Math.log(scale) / Math.LN2;
  5496. },
  5497. distance: function (latlng1, latlng2) {
  5498. var dx = latlng2.lng - latlng1.lng,
  5499. dy = latlng2.lat - latlng1.lat;
  5500. return Math.sqrt(dx * dx + dy * dy);
  5501. },
  5502. infinite: true
  5503. });
  5504. CRS.Earth = Earth;
  5505. CRS.EPSG3395 = EPSG3395;
  5506. CRS.EPSG3857 = EPSG3857;
  5507. CRS.EPSG900913 = EPSG900913;
  5508. CRS.EPSG4326 = EPSG4326;
  5509. CRS.Simple = Simple;
  5510. /*
  5511. * @class Layer
  5512. * @inherits Evented
  5513. * @aka L.Layer
  5514. * @aka ILayer
  5515. *
  5516. * A set of methods from the Layer base class that all Leaflet layers use.
  5517. * Inherits all methods, options and events from `L.Evented`.
  5518. *
  5519. * @example
  5520. *
  5521. * ```js
  5522. * var layer = L.marker(latlng).addTo(map);
  5523. * layer.addTo(map);
  5524. * layer.remove();
  5525. * ```
  5526. *
  5527. * @event add: Event
  5528. * Fired after the layer is added to a map
  5529. *
  5530. * @event remove: Event
  5531. * Fired after the layer is removed from a map
  5532. */
  5533. var Layer = Evented.extend({
  5534. // Classes extending `L.Layer` will inherit the following options:
  5535. options: {
  5536. // @option pane: String = 'overlayPane'
  5537. // 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.
  5538. pane: 'overlayPane',
  5539. // @option attribution: String = null
  5540. // String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.
  5541. attribution: null,
  5542. bubblingMouseEvents: true
  5543. },
  5544. /* @section
  5545. * Classes extending `L.Layer` will inherit the following methods:
  5546. *
  5547. * @method addTo(map: Map|LayerGroup): this
  5548. * Adds the layer to the given map or layer group.
  5549. */
  5550. addTo: function (map) {
  5551. map.addLayer(this);
  5552. return this;
  5553. },
  5554. // @method remove: this
  5555. // Removes the layer from the map it is currently active on.
  5556. remove: function () {
  5557. return this.removeFrom(this._map || this._mapToAdd);
  5558. },
  5559. // @method removeFrom(map: Map): this
  5560. // Removes the layer from the given map
  5561. //
  5562. // @alternative
  5563. // @method removeFrom(group: LayerGroup): this
  5564. // Removes the layer from the given `LayerGroup`
  5565. removeFrom: function (obj) {
  5566. if (obj) {
  5567. obj.removeLayer(this);
  5568. }
  5569. return this;
  5570. },
  5571. // @method getPane(name? : String): HTMLElement
  5572. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5573. getPane: function (name) {
  5574. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5575. },
  5576. addInteractiveTarget: function (targetEl) {
  5577. this._map._targets[stamp(targetEl)] = this;
  5578. return this;
  5579. },
  5580. removeInteractiveTarget: function (targetEl) {
  5581. delete this._map._targets[stamp(targetEl)];
  5582. return this;
  5583. },
  5584. // @method getAttribution: String
  5585. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5586. getAttribution: function () {
  5587. return this.options.attribution;
  5588. },
  5589. _layerAdd: function (e) {
  5590. var map = e.target;
  5591. // check in case layer gets added and then removed before the map is ready
  5592. if (!map.hasLayer(this)) { return; }
  5593. this._map = map;
  5594. this._zoomAnimated = map._zoomAnimated;
  5595. if (this.getEvents) {
  5596. var events = this.getEvents();
  5597. map.on(events, this);
  5598. this.once('remove', function () {
  5599. map.off(events, this);
  5600. }, this);
  5601. }
  5602. this.onAdd(map);
  5603. this.fire('add');
  5604. map.fire('layeradd', {layer: this});
  5605. }
  5606. });
  5607. /* @section Extension methods
  5608. * @uninheritable
  5609. *
  5610. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5611. *
  5612. * @method onAdd(map: Map): this
  5613. * 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).
  5614. *
  5615. * @method onRemove(map: Map): this
  5616. * 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).
  5617. *
  5618. * @method getEvents(): Object
  5619. * 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.
  5620. *
  5621. * @method getAttribution(): String
  5622. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5623. *
  5624. * @method beforeAdd(map: Map): this
  5625. * 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.
  5626. */
  5627. /* @namespace Map
  5628. * @section Layer events
  5629. *
  5630. * @event layeradd: LayerEvent
  5631. * Fired when a new layer is added to the map.
  5632. *
  5633. * @event layerremove: LayerEvent
  5634. * Fired when some layer is removed from the map
  5635. *
  5636. * @section Methods for Layers and Controls
  5637. */
  5638. Map.include({
  5639. // @method addLayer(layer: Layer): this
  5640. // Adds the given layer to the map
  5641. addLayer: function (layer) {
  5642. if (!layer._layerAdd) {
  5643. throw new Error('The provided object is not a Layer.');
  5644. }
  5645. var id = stamp(layer);
  5646. if (this._layers[id]) { return this; }
  5647. this._layers[id] = layer;
  5648. layer._mapToAdd = this;
  5649. if (layer.beforeAdd) {
  5650. layer.beforeAdd(this);
  5651. }
  5652. this.whenReady(layer._layerAdd, layer);
  5653. return this;
  5654. },
  5655. // @method removeLayer(layer: Layer): this
  5656. // Removes the given layer from the map.
  5657. removeLayer: function (layer) {
  5658. var id = stamp(layer);
  5659. if (!this._layers[id]) { return this; }
  5660. if (this._loaded) {
  5661. layer.onRemove(this);
  5662. }
  5663. delete this._layers[id];
  5664. if (this._loaded) {
  5665. this.fire('layerremove', {layer: layer});
  5666. layer.fire('remove');
  5667. }
  5668. layer._map = layer._mapToAdd = null;
  5669. return this;
  5670. },
  5671. // @method hasLayer(layer: Layer): Boolean
  5672. // Returns `true` if the given layer is currently added to the map
  5673. hasLayer: function (layer) {
  5674. return stamp(layer) in this._layers;
  5675. },
  5676. /* @method eachLayer(fn: Function, context?: Object): this
  5677. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5678. * ```
  5679. * map.eachLayer(function(layer){
  5680. * layer.bindPopup('Hello');
  5681. * });
  5682. * ```
  5683. */
  5684. eachLayer: function (method, context) {
  5685. for (var i in this._layers) {
  5686. method.call(context, this._layers[i]);
  5687. }
  5688. return this;
  5689. },
  5690. _addLayers: function (layers) {
  5691. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5692. for (var i = 0, len = layers.length; i < len; i++) {
  5693. this.addLayer(layers[i]);
  5694. }
  5695. },
  5696. _addZoomLimit: function (layer) {
  5697. if (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5698. this._zoomBoundLayers[stamp(layer)] = layer;
  5699. this._updateZoomLevels();
  5700. }
  5701. },
  5702. _removeZoomLimit: function (layer) {
  5703. var id = stamp(layer);
  5704. if (this._zoomBoundLayers[id]) {
  5705. delete this._zoomBoundLayers[id];
  5706. this._updateZoomLevels();
  5707. }
  5708. },
  5709. _updateZoomLevels: function () {
  5710. var minZoom = Infinity,
  5711. maxZoom = -Infinity,
  5712. oldZoomSpan = this._getZoomSpan();
  5713. for (var i in this._zoomBoundLayers) {
  5714. var options = this._zoomBoundLayers[i].options;
  5715. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5716. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5717. }
  5718. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5719. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5720. // @section Map state change events
  5721. // @event zoomlevelschange: Event
  5722. // Fired when the number of zoomlevels on the map is changed due
  5723. // to adding or removing a layer.
  5724. if (oldZoomSpan !== this._getZoomSpan()) {
  5725. this.fire('zoomlevelschange');
  5726. }
  5727. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5728. this.setZoom(this._layersMaxZoom);
  5729. }
  5730. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5731. this.setZoom(this._layersMinZoom);
  5732. }
  5733. }
  5734. });
  5735. /*
  5736. * @class LayerGroup
  5737. * @aka L.LayerGroup
  5738. * @inherits Interactive layer
  5739. *
  5740. * Used to group several layers and handle them as one. If you add it to the map,
  5741. * any layers added or removed from the group will be added/removed on the map as
  5742. * well. Extends `Layer`.
  5743. *
  5744. * @example
  5745. *
  5746. * ```js
  5747. * L.layerGroup([marker1, marker2])
  5748. * .addLayer(polyline)
  5749. * .addTo(map);
  5750. * ```
  5751. */
  5752. var LayerGroup = Layer.extend({
  5753. initialize: function (layers, options) {
  5754. setOptions(this, options);
  5755. this._layers = {};
  5756. var i, len;
  5757. if (layers) {
  5758. for (i = 0, len = layers.length; i < len; i++) {
  5759. this.addLayer(layers[i]);
  5760. }
  5761. }
  5762. },
  5763. // @method addLayer(layer: Layer): this
  5764. // Adds the given layer to the group.
  5765. addLayer: function (layer) {
  5766. var id = this.getLayerId(layer);
  5767. this._layers[id] = layer;
  5768. if (this._map) {
  5769. this._map.addLayer(layer);
  5770. }
  5771. return this;
  5772. },
  5773. // @method removeLayer(layer: Layer): this
  5774. // Removes the given layer from the group.
  5775. // @alternative
  5776. // @method removeLayer(id: Number): this
  5777. // Removes the layer with the given internal ID from the group.
  5778. removeLayer: function (layer) {
  5779. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5780. if (this._map && this._layers[id]) {
  5781. this._map.removeLayer(this._layers[id]);
  5782. }
  5783. delete this._layers[id];
  5784. return this;
  5785. },
  5786. // @method hasLayer(layer: Layer): Boolean
  5787. // Returns `true` if the given layer is currently added to the group.
  5788. // @alternative
  5789. // @method hasLayer(id: Number): Boolean
  5790. // Returns `true` if the given internal ID is currently added to the group.
  5791. hasLayer: function (layer) {
  5792. var layerId = typeof layer === 'number' ? layer : this.getLayerId(layer);
  5793. return layerId in this._layers;
  5794. },
  5795. // @method clearLayers(): this
  5796. // Removes all the layers from the group.
  5797. clearLayers: function () {
  5798. return this.eachLayer(this.removeLayer, this);
  5799. },
  5800. // @method invoke(methodName: String, …): this
  5801. // Calls `methodName` on every layer contained in this group, passing any
  5802. // additional parameters. Has no effect if the layers contained do not
  5803. // implement `methodName`.
  5804. invoke: function (methodName) {
  5805. var args = Array.prototype.slice.call(arguments, 1),
  5806. i, layer;
  5807. for (i in this._layers) {
  5808. layer = this._layers[i];
  5809. if (layer[methodName]) {
  5810. layer[methodName].apply(layer, args);
  5811. }
  5812. }
  5813. return this;
  5814. },
  5815. onAdd: function (map) {
  5816. this.eachLayer(map.addLayer, map);
  5817. },
  5818. onRemove: function (map) {
  5819. this.eachLayer(map.removeLayer, map);
  5820. },
  5821. // @method eachLayer(fn: Function, context?: Object): this
  5822. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5823. // ```js
  5824. // group.eachLayer(function (layer) {
  5825. // layer.bindPopup('Hello');
  5826. // });
  5827. // ```
  5828. eachLayer: function (method, context) {
  5829. for (var i in this._layers) {
  5830. method.call(context, this._layers[i]);
  5831. }
  5832. return this;
  5833. },
  5834. // @method getLayer(id: Number): Layer
  5835. // Returns the layer with the given internal ID.
  5836. getLayer: function (id) {
  5837. return this._layers[id];
  5838. },
  5839. // @method getLayers(): Layer[]
  5840. // Returns an array of all the layers added to the group.
  5841. getLayers: function () {
  5842. var layers = [];
  5843. this.eachLayer(layers.push, layers);
  5844. return layers;
  5845. },
  5846. // @method setZIndex(zIndex: Number): this
  5847. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5848. setZIndex: function (zIndex) {
  5849. return this.invoke('setZIndex', zIndex);
  5850. },
  5851. // @method getLayerId(layer: Layer): Number
  5852. // Returns the internal ID for a layer
  5853. getLayerId: function (layer) {
  5854. return stamp(layer);
  5855. }
  5856. });
  5857. // @factory L.layerGroup(layers?: Layer[], options?: Object)
  5858. // Create a layer group, optionally given an initial set of layers and an `options` object.
  5859. var layerGroup = function (layers, options) {
  5860. return new LayerGroup(layers, options);
  5861. };
  5862. /*
  5863. * @class FeatureGroup
  5864. * @aka L.FeatureGroup
  5865. * @inherits LayerGroup
  5866. *
  5867. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5868. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5869. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5870. * handler, it will handle events from any of the layers. This includes mouse events
  5871. * and custom events.
  5872. * * Has `layeradd` and `layerremove` events
  5873. *
  5874. * @example
  5875. *
  5876. * ```js
  5877. * L.featureGroup([marker1, marker2, polyline])
  5878. * .bindPopup('Hello world!')
  5879. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5880. * .addTo(map);
  5881. * ```
  5882. */
  5883. var FeatureGroup = LayerGroup.extend({
  5884. addLayer: function (layer) {
  5885. if (this.hasLayer(layer)) {
  5886. return this;
  5887. }
  5888. layer.addEventParent(this);
  5889. LayerGroup.prototype.addLayer.call(this, layer);
  5890. // @event layeradd: LayerEvent
  5891. // Fired when a layer is added to this `FeatureGroup`
  5892. return this.fire('layeradd', {layer: layer});
  5893. },
  5894. removeLayer: function (layer) {
  5895. if (!this.hasLayer(layer)) {
  5896. return this;
  5897. }
  5898. if (layer in this._layers) {
  5899. layer = this._layers[layer];
  5900. }
  5901. layer.removeEventParent(this);
  5902. LayerGroup.prototype.removeLayer.call(this, layer);
  5903. // @event layerremove: LayerEvent
  5904. // Fired when a layer is removed from this `FeatureGroup`
  5905. return this.fire('layerremove', {layer: layer});
  5906. },
  5907. // @method setStyle(style: Path options): this
  5908. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5909. setStyle: function (style) {
  5910. return this.invoke('setStyle', style);
  5911. },
  5912. // @method bringToFront(): this
  5913. // Brings the layer group to the top of all other layers
  5914. bringToFront: function () {
  5915. return this.invoke('bringToFront');
  5916. },
  5917. // @method bringToBack(): this
  5918. // Brings the layer group to the back of all other layers
  5919. bringToBack: function () {
  5920. return this.invoke('bringToBack');
  5921. },
  5922. // @method getBounds(): LatLngBounds
  5923. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5924. getBounds: function () {
  5925. var bounds = new LatLngBounds();
  5926. for (var id in this._layers) {
  5927. var layer = this._layers[id];
  5928. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5929. }
  5930. return bounds;
  5931. }
  5932. });
  5933. // @factory L.featureGroup(layers?: Layer[], options?: Object)
  5934. // Create a feature group, optionally given an initial set of layers and an `options` object.
  5935. var featureGroup = function (layers, options) {
  5936. return new FeatureGroup(layers, options);
  5937. };
  5938. /*
  5939. * @class Icon
  5940. * @aka L.Icon
  5941. *
  5942. * Represents an icon to provide when creating a marker.
  5943. *
  5944. * @example
  5945. *
  5946. * ```js
  5947. * var myIcon = L.icon({
  5948. * iconUrl: 'my-icon.png',
  5949. * iconRetinaUrl: 'my-icon@2x.png',
  5950. * iconSize: [38, 95],
  5951. * iconAnchor: [22, 94],
  5952. * popupAnchor: [-3, -76],
  5953. * shadowUrl: 'my-icon-shadow.png',
  5954. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5955. * shadowSize: [68, 95],
  5956. * shadowAnchor: [22, 94]
  5957. * });
  5958. *
  5959. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5960. * ```
  5961. *
  5962. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5963. *
  5964. */
  5965. var Icon = Class.extend({
  5966. /* @section
  5967. * @aka Icon options
  5968. *
  5969. * @option iconUrl: String = null
  5970. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5971. *
  5972. * @option iconRetinaUrl: String = null
  5973. * The URL to a retina sized version of the icon image (absolute or relative to your
  5974. * script path). Used for Retina screen devices.
  5975. *
  5976. * @option iconSize: Point = null
  5977. * Size of the icon image in pixels.
  5978. *
  5979. * @option iconAnchor: Point = null
  5980. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5981. * will be aligned so that this point is at the marker's geographical location. Centered
  5982. * by default if size is specified, also can be set in CSS with negative margins.
  5983. *
  5984. * @option popupAnchor: Point = [0, 0]
  5985. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5986. *
  5987. * @option tooltipAnchor: Point = [0, 0]
  5988. * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
  5989. *
  5990. * @option shadowUrl: String = null
  5991. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  5992. *
  5993. * @option shadowRetinaUrl: String = null
  5994. *
  5995. * @option shadowSize: Point = null
  5996. * Size of the shadow image in pixels.
  5997. *
  5998. * @option shadowAnchor: Point = null
  5999. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  6000. * as iconAnchor if not specified).
  6001. *
  6002. * @option className: String = ''
  6003. * A custom class name to assign to both icon and shadow images. Empty by default.
  6004. */
  6005. options: {
  6006. popupAnchor: [0, 0],
  6007. tooltipAnchor: [0, 0],
  6008. // @option crossOrigin: Boolean|String = false
  6009. // Whether the crossOrigin attribute will be added to the tiles.
  6010. // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
  6011. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  6012. crossOrigin: false
  6013. },
  6014. initialize: function (options) {
  6015. setOptions(this, options);
  6016. },
  6017. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  6018. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  6019. // styled according to the options.
  6020. createIcon: function (oldIcon) {
  6021. return this._createIcon('icon', oldIcon);
  6022. },
  6023. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  6024. // As `createIcon`, but for the shadow beneath it.
  6025. createShadow: function (oldIcon) {
  6026. return this._createIcon('shadow', oldIcon);
  6027. },
  6028. _createIcon: function (name, oldIcon) {
  6029. var src = this._getIconUrl(name);
  6030. if (!src) {
  6031. if (name === 'icon') {
  6032. throw new Error('iconUrl not set in Icon options (see the docs).');
  6033. }
  6034. return null;
  6035. }
  6036. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  6037. this._setIconStyles(img, name);
  6038. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  6039. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  6040. }
  6041. return img;
  6042. },
  6043. _setIconStyles: function (img, name) {
  6044. var options = this.options;
  6045. var sizeOption = options[name + 'Size'];
  6046. if (typeof sizeOption === 'number') {
  6047. sizeOption = [sizeOption, sizeOption];
  6048. }
  6049. var size = toPoint(sizeOption),
  6050. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  6051. size && size.divideBy(2, true));
  6052. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  6053. if (anchor) {
  6054. img.style.marginLeft = (-anchor.x) + 'px';
  6055. img.style.marginTop = (-anchor.y) + 'px';
  6056. }
  6057. if (size) {
  6058. img.style.width = size.x + 'px';
  6059. img.style.height = size.y + 'px';
  6060. }
  6061. },
  6062. _createImg: function (src, el) {
  6063. el = el || document.createElement('img');
  6064. el.src = src;
  6065. return el;
  6066. },
  6067. _getIconUrl: function (name) {
  6068. return Browser.retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  6069. }
  6070. });
  6071. // @factory L.icon(options: Icon options)
  6072. // Creates an icon instance with the given options.
  6073. function icon(options) {
  6074. return new Icon(options);
  6075. }
  6076. /*
  6077. * @miniclass Icon.Default (Icon)
  6078. * @aka L.Icon.Default
  6079. * @section
  6080. *
  6081. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  6082. * no icon is specified. Points to the blue marker image distributed with Leaflet
  6083. * releases.
  6084. *
  6085. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  6086. * (which is a set of `Icon options`).
  6087. *
  6088. * If you want to _completely_ replace the default icon, override the
  6089. * `L.Marker.prototype.options.icon` with your own icon instead.
  6090. */
  6091. var IconDefault = Icon.extend({
  6092. options: {
  6093. iconUrl: 'marker-icon.png',
  6094. iconRetinaUrl: 'marker-icon-2x.png',
  6095. shadowUrl: 'marker-shadow.png',
  6096. iconSize: [25, 41],
  6097. iconAnchor: [12, 41],
  6098. popupAnchor: [1, -34],
  6099. tooltipAnchor: [16, -28],
  6100. shadowSize: [41, 41]
  6101. },
  6102. _getIconUrl: function (name) {
  6103. if (typeof IconDefault.imagePath !== 'string') { // Deprecated, backwards-compatibility only
  6104. IconDefault.imagePath = this._detectIconPath();
  6105. }
  6106. // @option imagePath: String
  6107. // `Icon.Default` will try to auto-detect the location of the
  6108. // blue icon images. If you are placing these images in a non-standard
  6109. // way, set this option to point to the right path.
  6110. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  6111. },
  6112. _stripUrl: function (path) { // separate function to use in tests
  6113. var strip = function (str, re, idx) {
  6114. var match = re.exec(str);
  6115. return match && match[idx];
  6116. };
  6117. path = strip(path, /^url\((['"])?(.+)\1\)$/, 2);
  6118. return path && strip(path, /^(.*)marker-icon\.png$/, 1);
  6119. },
  6120. _detectIconPath: function () {
  6121. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  6122. var path = getStyle(el, 'background-image') ||
  6123. getStyle(el, 'backgroundImage'); // IE8
  6124. document.body.removeChild(el);
  6125. path = this._stripUrl(path);
  6126. if (path) { return path; }
  6127. var link = document.querySelector('link[href$="leaflet.css"]');
  6128. if (!link) { return ''; }
  6129. return link.href.substring(0, link.href.length - 'leaflet.css'.length - 1);
  6130. }
  6131. });
  6132. /*
  6133. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  6134. */
  6135. /* @namespace Marker
  6136. * @section Interaction handlers
  6137. *
  6138. * 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:
  6139. *
  6140. * ```js
  6141. * marker.dragging.disable();
  6142. * ```
  6143. *
  6144. * @property dragging: Handler
  6145. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  6146. */
  6147. var MarkerDrag = Handler.extend({
  6148. initialize: function (marker) {
  6149. this._marker = marker;
  6150. },
  6151. addHooks: function () {
  6152. var icon = this._marker._icon;
  6153. if (!this._draggable) {
  6154. this._draggable = new Draggable(icon, icon, true);
  6155. }
  6156. this._draggable.on({
  6157. dragstart: this._onDragStart,
  6158. predrag: this._onPreDrag,
  6159. drag: this._onDrag,
  6160. dragend: this._onDragEnd
  6161. }, this).enable();
  6162. addClass(icon, 'leaflet-marker-draggable');
  6163. },
  6164. removeHooks: function () {
  6165. this._draggable.off({
  6166. dragstart: this._onDragStart,
  6167. predrag: this._onPreDrag,
  6168. drag: this._onDrag,
  6169. dragend: this._onDragEnd
  6170. }, this).disable();
  6171. if (this._marker._icon) {
  6172. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  6173. }
  6174. },
  6175. moved: function () {
  6176. return this._draggable && this._draggable._moved;
  6177. },
  6178. _adjustPan: function (e) {
  6179. var marker = this._marker,
  6180. map = marker._map,
  6181. speed = this._marker.options.autoPanSpeed,
  6182. padding = this._marker.options.autoPanPadding,
  6183. iconPos = getPosition(marker._icon),
  6184. bounds = map.getPixelBounds(),
  6185. origin = map.getPixelOrigin();
  6186. var panBounds = toBounds(
  6187. bounds.min._subtract(origin).add(padding),
  6188. bounds.max._subtract(origin).subtract(padding)
  6189. );
  6190. if (!panBounds.contains(iconPos)) {
  6191. // Compute incremental movement
  6192. var movement = toPoint(
  6193. (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
  6194. (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
  6195. (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
  6196. (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
  6197. ).multiplyBy(speed);
  6198. map.panBy(movement, {animate: false});
  6199. this._draggable._newPos._add(movement);
  6200. this._draggable._startPos._add(movement);
  6201. setPosition(marker._icon, this._draggable._newPos);
  6202. this._onDrag(e);
  6203. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  6204. }
  6205. },
  6206. _onDragStart: function () {
  6207. // @section Dragging events
  6208. // @event dragstart: Event
  6209. // Fired when the user starts dragging the marker.
  6210. // @event movestart: Event
  6211. // Fired when the marker starts moving (because of dragging).
  6212. this._oldLatLng = this._marker.getLatLng();
  6213. // When using ES6 imports it could not be set when `Popup` was not imported as well
  6214. this._marker.closePopup && this._marker.closePopup();
  6215. this._marker
  6216. .fire('movestart')
  6217. .fire('dragstart');
  6218. },
  6219. _onPreDrag: function (e) {
  6220. if (this._marker.options.autoPan) {
  6221. cancelAnimFrame(this._panRequest);
  6222. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  6223. }
  6224. },
  6225. _onDrag: function (e) {
  6226. var marker = this._marker,
  6227. shadow = marker._shadow,
  6228. iconPos = getPosition(marker._icon),
  6229. latlng = marker._map.layerPointToLatLng(iconPos);
  6230. // update shadow position
  6231. if (shadow) {
  6232. setPosition(shadow, iconPos);
  6233. }
  6234. marker._latlng = latlng;
  6235. e.latlng = latlng;
  6236. e.oldLatLng = this._oldLatLng;
  6237. // @event drag: Event
  6238. // Fired repeatedly while the user drags the marker.
  6239. marker
  6240. .fire('move', e)
  6241. .fire('drag', e);
  6242. },
  6243. _onDragEnd: function (e) {
  6244. // @event dragend: DragEndEvent
  6245. // Fired when the user stops dragging the marker.
  6246. cancelAnimFrame(this._panRequest);
  6247. // @event moveend: Event
  6248. // Fired when the marker stops moving (because of dragging).
  6249. delete this._oldLatLng;
  6250. this._marker
  6251. .fire('moveend')
  6252. .fire('dragend', e);
  6253. }
  6254. });
  6255. /*
  6256. * @class Marker
  6257. * @inherits Interactive layer
  6258. * @aka L.Marker
  6259. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  6260. *
  6261. * @example
  6262. *
  6263. * ```js
  6264. * L.marker([50.5, 30.5]).addTo(map);
  6265. * ```
  6266. */
  6267. var Marker = Layer.extend({
  6268. // @section
  6269. // @aka Marker options
  6270. options: {
  6271. // @option icon: Icon = *
  6272. // Icon instance to use for rendering the marker.
  6273. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  6274. // If not specified, a common instance of `L.Icon.Default` is used.
  6275. icon: new IconDefault(),
  6276. // Option inherited from "Interactive layer" abstract class
  6277. interactive: true,
  6278. // @option keyboard: Boolean = true
  6279. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  6280. keyboard: true,
  6281. // @option title: String = ''
  6282. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  6283. // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
  6284. title: '',
  6285. // @option alt: String = 'Marker'
  6286. // Text for the `alt` attribute of the icon image.
  6287. // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
  6288. alt: 'Marker',
  6289. // @option zIndexOffset: Number = 0
  6290. // 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).
  6291. zIndexOffset: 0,
  6292. // @option opacity: Number = 1.0
  6293. // The opacity of the marker.
  6294. opacity: 1,
  6295. // @option riseOnHover: Boolean = false
  6296. // If `true`, the marker will get on top of others when you hover the mouse over it.
  6297. riseOnHover: false,
  6298. // @option riseOffset: Number = 250
  6299. // The z-index offset used for the `riseOnHover` feature.
  6300. riseOffset: 250,
  6301. // @option pane: String = 'markerPane'
  6302. // `Map pane` where the markers icon will be added.
  6303. pane: 'markerPane',
  6304. // @option shadowPane: String = 'shadowPane'
  6305. // `Map pane` where the markers shadow will be added.
  6306. shadowPane: 'shadowPane',
  6307. // @option bubblingMouseEvents: Boolean = false
  6308. // When `true`, a mouse event on this marker will trigger the same event on the map
  6309. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6310. bubblingMouseEvents: false,
  6311. // @option autoPanOnFocus: Boolean = true
  6312. // When `true`, the map will pan whenever the marker is focused (via
  6313. // e.g. pressing `tab` on the keyboard) to ensure the marker is
  6314. // visible within the map's bounds
  6315. autoPanOnFocus: true,
  6316. // @section Draggable marker options
  6317. // @option draggable: Boolean = false
  6318. // Whether the marker is draggable with mouse/touch or not.
  6319. draggable: false,
  6320. // @option autoPan: Boolean = false
  6321. // Whether to pan the map when dragging this marker near its edge or not.
  6322. autoPan: false,
  6323. // @option autoPanPadding: Point = Point(50, 50)
  6324. // Distance (in pixels to the left/right and to the top/bottom) of the
  6325. // map edge to start panning the map.
  6326. autoPanPadding: [50, 50],
  6327. // @option autoPanSpeed: Number = 10
  6328. // Number of pixels the map should pan by.
  6329. autoPanSpeed: 10
  6330. },
  6331. /* @section
  6332. *
  6333. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  6334. */
  6335. initialize: function (latlng, options) {
  6336. setOptions(this, options);
  6337. this._latlng = toLatLng(latlng);
  6338. },
  6339. onAdd: function (map) {
  6340. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  6341. if (this._zoomAnimated) {
  6342. map.on('zoomanim', this._animateZoom, this);
  6343. }
  6344. this._initIcon();
  6345. this.update();
  6346. },
  6347. onRemove: function (map) {
  6348. if (this.dragging && this.dragging.enabled()) {
  6349. this.options.draggable = true;
  6350. this.dragging.removeHooks();
  6351. }
  6352. delete this.dragging;
  6353. if (this._zoomAnimated) {
  6354. map.off('zoomanim', this._animateZoom, this);
  6355. }
  6356. this._removeIcon();
  6357. this._removeShadow();
  6358. },
  6359. getEvents: function () {
  6360. return {
  6361. zoom: this.update,
  6362. viewreset: this.update
  6363. };
  6364. },
  6365. // @method getLatLng: LatLng
  6366. // Returns the current geographical position of the marker.
  6367. getLatLng: function () {
  6368. return this._latlng;
  6369. },
  6370. // @method setLatLng(latlng: LatLng): this
  6371. // Changes the marker position to the given point.
  6372. setLatLng: function (latlng) {
  6373. var oldLatLng = this._latlng;
  6374. this._latlng = toLatLng(latlng);
  6375. this.update();
  6376. // @event move: Event
  6377. // 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`.
  6378. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6379. },
  6380. // @method setZIndexOffset(offset: Number): this
  6381. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6382. setZIndexOffset: function (offset) {
  6383. this.options.zIndexOffset = offset;
  6384. return this.update();
  6385. },
  6386. // @method getIcon: Icon
  6387. // Returns the current icon used by the marker
  6388. getIcon: function () {
  6389. return this.options.icon;
  6390. },
  6391. // @method setIcon(icon: Icon): this
  6392. // Changes the marker icon.
  6393. setIcon: function (icon) {
  6394. this.options.icon = icon;
  6395. if (this._map) {
  6396. this._initIcon();
  6397. this.update();
  6398. }
  6399. if (this._popup) {
  6400. this.bindPopup(this._popup, this._popup.options);
  6401. }
  6402. return this;
  6403. },
  6404. getElement: function () {
  6405. return this._icon;
  6406. },
  6407. update: function () {
  6408. if (this._icon && this._map) {
  6409. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6410. this._setPos(pos);
  6411. }
  6412. return this;
  6413. },
  6414. _initIcon: function () {
  6415. var options = this.options,
  6416. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6417. var icon = options.icon.createIcon(this._icon),
  6418. addIcon = false;
  6419. // if we're not reusing the icon, remove the old one and init new one
  6420. if (icon !== this._icon) {
  6421. if (this._icon) {
  6422. this._removeIcon();
  6423. }
  6424. addIcon = true;
  6425. if (options.title) {
  6426. icon.title = options.title;
  6427. }
  6428. if (icon.tagName === 'IMG') {
  6429. icon.alt = options.alt || '';
  6430. }
  6431. }
  6432. addClass(icon, classToAdd);
  6433. if (options.keyboard) {
  6434. icon.tabIndex = '0';
  6435. icon.setAttribute('role', 'button');
  6436. }
  6437. this._icon = icon;
  6438. if (options.riseOnHover) {
  6439. this.on({
  6440. mouseover: this._bringToFront,
  6441. mouseout: this._resetZIndex
  6442. });
  6443. }
  6444. if (this.options.autoPanOnFocus) {
  6445. on(icon, 'focus', this._panOnFocus, this);
  6446. }
  6447. var newShadow = options.icon.createShadow(this._shadow),
  6448. addShadow = false;
  6449. if (newShadow !== this._shadow) {
  6450. this._removeShadow();
  6451. addShadow = true;
  6452. }
  6453. if (newShadow) {
  6454. addClass(newShadow, classToAdd);
  6455. newShadow.alt = '';
  6456. }
  6457. this._shadow = newShadow;
  6458. if (options.opacity < 1) {
  6459. this._updateOpacity();
  6460. }
  6461. if (addIcon) {
  6462. this.getPane().appendChild(this._icon);
  6463. }
  6464. this._initInteraction();
  6465. if (newShadow && addShadow) {
  6466. this.getPane(options.shadowPane).appendChild(this._shadow);
  6467. }
  6468. },
  6469. _removeIcon: function () {
  6470. if (this.options.riseOnHover) {
  6471. this.off({
  6472. mouseover: this._bringToFront,
  6473. mouseout: this._resetZIndex
  6474. });
  6475. }
  6476. if (this.options.autoPanOnFocus) {
  6477. off(this._icon, 'focus', this._panOnFocus, this);
  6478. }
  6479. remove(this._icon);
  6480. this.removeInteractiveTarget(this._icon);
  6481. this._icon = null;
  6482. },
  6483. _removeShadow: function () {
  6484. if (this._shadow) {
  6485. remove(this._shadow);
  6486. }
  6487. this._shadow = null;
  6488. },
  6489. _setPos: function (pos) {
  6490. if (this._icon) {
  6491. setPosition(this._icon, pos);
  6492. }
  6493. if (this._shadow) {
  6494. setPosition(this._shadow, pos);
  6495. }
  6496. this._zIndex = pos.y + this.options.zIndexOffset;
  6497. this._resetZIndex();
  6498. },
  6499. _updateZIndex: function (offset) {
  6500. if (this._icon) {
  6501. this._icon.style.zIndex = this._zIndex + offset;
  6502. }
  6503. },
  6504. _animateZoom: function (opt) {
  6505. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6506. this._setPos(pos);
  6507. },
  6508. _initInteraction: function () {
  6509. if (!this.options.interactive) { return; }
  6510. addClass(this._icon, 'leaflet-interactive');
  6511. this.addInteractiveTarget(this._icon);
  6512. if (MarkerDrag) {
  6513. var draggable = this.options.draggable;
  6514. if (this.dragging) {
  6515. draggable = this.dragging.enabled();
  6516. this.dragging.disable();
  6517. }
  6518. this.dragging = new MarkerDrag(this);
  6519. if (draggable) {
  6520. this.dragging.enable();
  6521. }
  6522. }
  6523. },
  6524. // @method setOpacity(opacity: Number): this
  6525. // Changes the opacity of the marker.
  6526. setOpacity: function (opacity) {
  6527. this.options.opacity = opacity;
  6528. if (this._map) {
  6529. this._updateOpacity();
  6530. }
  6531. return this;
  6532. },
  6533. _updateOpacity: function () {
  6534. var opacity = this.options.opacity;
  6535. if (this._icon) {
  6536. setOpacity(this._icon, opacity);
  6537. }
  6538. if (this._shadow) {
  6539. setOpacity(this._shadow, opacity);
  6540. }
  6541. },
  6542. _bringToFront: function () {
  6543. this._updateZIndex(this.options.riseOffset);
  6544. },
  6545. _resetZIndex: function () {
  6546. this._updateZIndex(0);
  6547. },
  6548. _panOnFocus: function () {
  6549. var map = this._map;
  6550. if (!map) { return; }
  6551. var iconOpts = this.options.icon.options;
  6552. var size = iconOpts.iconSize ? toPoint(iconOpts.iconSize) : toPoint(0, 0);
  6553. var anchor = iconOpts.iconAnchor ? toPoint(iconOpts.iconAnchor) : toPoint(0, 0);
  6554. map.panInside(this._latlng, {
  6555. paddingTopLeft: anchor,
  6556. paddingBottomRight: size.subtract(anchor)
  6557. });
  6558. },
  6559. _getPopupAnchor: function () {
  6560. return this.options.icon.options.popupAnchor;
  6561. },
  6562. _getTooltipAnchor: function () {
  6563. return this.options.icon.options.tooltipAnchor;
  6564. }
  6565. });
  6566. // factory L.marker(latlng: LatLng, options? : Marker options)
  6567. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6568. // Instantiates a Marker object given a geographical point and optionally an options object.
  6569. function marker(latlng, options) {
  6570. return new Marker(latlng, options);
  6571. }
  6572. /*
  6573. * @class Path
  6574. * @aka L.Path
  6575. * @inherits Interactive layer
  6576. *
  6577. * An abstract class that contains options and constants shared between vector
  6578. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6579. */
  6580. var Path = Layer.extend({
  6581. // @section
  6582. // @aka Path options
  6583. options: {
  6584. // @option stroke: Boolean = true
  6585. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6586. stroke: true,
  6587. // @option color: String = '#3388ff'
  6588. // Stroke color
  6589. color: '#3388ff',
  6590. // @option weight: Number = 3
  6591. // Stroke width in pixels
  6592. weight: 3,
  6593. // @option opacity: Number = 1.0
  6594. // Stroke opacity
  6595. opacity: 1,
  6596. // @option lineCap: String= 'round'
  6597. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6598. lineCap: 'round',
  6599. // @option lineJoin: String = 'round'
  6600. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6601. lineJoin: 'round',
  6602. // @option dashArray: String = null
  6603. // 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).
  6604. dashArray: null,
  6605. // @option dashOffset: String = null
  6606. // 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).
  6607. dashOffset: null,
  6608. // @option fill: Boolean = depends
  6609. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6610. fill: false,
  6611. // @option fillColor: String = *
  6612. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6613. fillColor: null,
  6614. // @option fillOpacity: Number = 0.2
  6615. // Fill opacity.
  6616. fillOpacity: 0.2,
  6617. // @option fillRule: String = 'evenodd'
  6618. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6619. fillRule: 'evenodd',
  6620. // className: '',
  6621. // Option inherited from "Interactive layer" abstract class
  6622. interactive: true,
  6623. // @option bubblingMouseEvents: Boolean = true
  6624. // When `true`, a mouse event on this path will trigger the same event on the map
  6625. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6626. bubblingMouseEvents: true
  6627. },
  6628. beforeAdd: function (map) {
  6629. // Renderer is set here because we need to call renderer.getEvents
  6630. // before this.getEvents.
  6631. this._renderer = map.getRenderer(this);
  6632. },
  6633. onAdd: function () {
  6634. this._renderer._initPath(this);
  6635. this._reset();
  6636. this._renderer._addPath(this);
  6637. },
  6638. onRemove: function () {
  6639. this._renderer._removePath(this);
  6640. },
  6641. // @method redraw(): this
  6642. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6643. redraw: function () {
  6644. if (this._map) {
  6645. this._renderer._updatePath(this);
  6646. }
  6647. return this;
  6648. },
  6649. // @method setStyle(style: Path options): this
  6650. // Changes the appearance of a Path based on the options in the `Path options` object.
  6651. setStyle: function (style) {
  6652. setOptions(this, style);
  6653. if (this._renderer) {
  6654. this._renderer._updateStyle(this);
  6655. if (this.options.stroke && style && Object.prototype.hasOwnProperty.call(style, 'weight')) {
  6656. this._updateBounds();
  6657. }
  6658. }
  6659. return this;
  6660. },
  6661. // @method bringToFront(): this
  6662. // Brings the layer to the top of all path layers.
  6663. bringToFront: function () {
  6664. if (this._renderer) {
  6665. this._renderer._bringToFront(this);
  6666. }
  6667. return this;
  6668. },
  6669. // @method bringToBack(): this
  6670. // Brings the layer to the bottom of all path layers.
  6671. bringToBack: function () {
  6672. if (this._renderer) {
  6673. this._renderer._bringToBack(this);
  6674. }
  6675. return this;
  6676. },
  6677. getElement: function () {
  6678. return this._path;
  6679. },
  6680. _reset: function () {
  6681. // defined in child classes
  6682. this._project();
  6683. this._update();
  6684. },
  6685. _clickTolerance: function () {
  6686. // used when doing hit detection for Canvas layers
  6687. return (this.options.stroke ? this.options.weight / 2 : 0) +
  6688. (this._renderer.options.tolerance || 0);
  6689. }
  6690. });
  6691. /*
  6692. * @class CircleMarker
  6693. * @aka L.CircleMarker
  6694. * @inherits Path
  6695. *
  6696. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6697. */
  6698. var CircleMarker = Path.extend({
  6699. // @section
  6700. // @aka CircleMarker options
  6701. options: {
  6702. fill: true,
  6703. // @option radius: Number = 10
  6704. // Radius of the circle marker, in pixels
  6705. radius: 10
  6706. },
  6707. initialize: function (latlng, options) {
  6708. setOptions(this, options);
  6709. this._latlng = toLatLng(latlng);
  6710. this._radius = this.options.radius;
  6711. },
  6712. // @method setLatLng(latLng: LatLng): this
  6713. // Sets the position of a circle marker to a new location.
  6714. setLatLng: function (latlng) {
  6715. var oldLatLng = this._latlng;
  6716. this._latlng = toLatLng(latlng);
  6717. this.redraw();
  6718. // @event move: Event
  6719. // Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
  6720. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6721. },
  6722. // @method getLatLng(): LatLng
  6723. // Returns the current geographical position of the circle marker
  6724. getLatLng: function () {
  6725. return this._latlng;
  6726. },
  6727. // @method setRadius(radius: Number): this
  6728. // Sets the radius of a circle marker. Units are in pixels.
  6729. setRadius: function (radius) {
  6730. this.options.radius = this._radius = radius;
  6731. return this.redraw();
  6732. },
  6733. // @method getRadius(): Number
  6734. // Returns the current radius of the circle
  6735. getRadius: function () {
  6736. return this._radius;
  6737. },
  6738. setStyle : function (options) {
  6739. var radius = options && options.radius || this._radius;
  6740. Path.prototype.setStyle.call(this, options);
  6741. this.setRadius(radius);
  6742. return this;
  6743. },
  6744. _project: function () {
  6745. this._point = this._map.latLngToLayerPoint(this._latlng);
  6746. this._updateBounds();
  6747. },
  6748. _updateBounds: function () {
  6749. var r = this._radius,
  6750. r2 = this._radiusY || r,
  6751. w = this._clickTolerance(),
  6752. p = [r + w, r2 + w];
  6753. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6754. },
  6755. _update: function () {
  6756. if (this._map) {
  6757. this._updatePath();
  6758. }
  6759. },
  6760. _updatePath: function () {
  6761. this._renderer._updateCircle(this);
  6762. },
  6763. _empty: function () {
  6764. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6765. },
  6766. // Needed by the `Canvas` renderer for interactivity
  6767. _containsPoint: function (p) {
  6768. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6769. }
  6770. });
  6771. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6772. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6773. function circleMarker(latlng, options) {
  6774. return new CircleMarker(latlng, options);
  6775. }
  6776. /*
  6777. * @class Circle
  6778. * @aka L.Circle
  6779. * @inherits CircleMarker
  6780. *
  6781. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6782. *
  6783. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6784. *
  6785. * @example
  6786. *
  6787. * ```js
  6788. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6789. * ```
  6790. */
  6791. var Circle = CircleMarker.extend({
  6792. initialize: function (latlng, options, legacyOptions) {
  6793. if (typeof options === 'number') {
  6794. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6795. options = extend({}, legacyOptions, {radius: options});
  6796. }
  6797. setOptions(this, options);
  6798. this._latlng = toLatLng(latlng);
  6799. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6800. // @section
  6801. // @aka Circle options
  6802. // @option radius: Number; Radius of the circle, in meters.
  6803. this._mRadius = this.options.radius;
  6804. },
  6805. // @method setRadius(radius: Number): this
  6806. // Sets the radius of a circle. Units are in meters.
  6807. setRadius: function (radius) {
  6808. this._mRadius = radius;
  6809. return this.redraw();
  6810. },
  6811. // @method getRadius(): Number
  6812. // Returns the current radius of a circle. Units are in meters.
  6813. getRadius: function () {
  6814. return this._mRadius;
  6815. },
  6816. // @method getBounds(): LatLngBounds
  6817. // Returns the `LatLngBounds` of the path.
  6818. getBounds: function () {
  6819. var half = [this._radius, this._radiusY || this._radius];
  6820. return new LatLngBounds(
  6821. this._map.layerPointToLatLng(this._point.subtract(half)),
  6822. this._map.layerPointToLatLng(this._point.add(half)));
  6823. },
  6824. setStyle: Path.prototype.setStyle,
  6825. _project: function () {
  6826. var lng = this._latlng.lng,
  6827. lat = this._latlng.lat,
  6828. map = this._map,
  6829. crs = map.options.crs;
  6830. if (crs.distance === Earth.distance) {
  6831. var d = Math.PI / 180,
  6832. latR = (this._mRadius / Earth.R) / d,
  6833. top = map.project([lat + latR, lng]),
  6834. bottom = map.project([lat - latR, lng]),
  6835. p = top.add(bottom).divideBy(2),
  6836. lat2 = map.unproject(p).lat,
  6837. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6838. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6839. if (isNaN(lngR) || lngR === 0) {
  6840. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6841. }
  6842. this._point = p.subtract(map.getPixelOrigin());
  6843. this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
  6844. this._radiusY = p.y - top.y;
  6845. } else {
  6846. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6847. this._point = map.latLngToLayerPoint(this._latlng);
  6848. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6849. }
  6850. this._updateBounds();
  6851. }
  6852. });
  6853. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6854. // Instantiates a circle object given a geographical point, and an options object
  6855. // which contains the circle radius.
  6856. // @alternative
  6857. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6858. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6859. // Do not use in new applications or plugins.
  6860. function circle(latlng, options, legacyOptions) {
  6861. return new Circle(latlng, options, legacyOptions);
  6862. }
  6863. /*
  6864. * @class Polyline
  6865. * @aka L.Polyline
  6866. * @inherits Path
  6867. *
  6868. * A class for drawing polyline overlays on a map. Extends `Path`.
  6869. *
  6870. * @example
  6871. *
  6872. * ```js
  6873. * // create a red polyline from an array of LatLng points
  6874. * var latlngs = [
  6875. * [45.51, -122.68],
  6876. * [37.77, -122.43],
  6877. * [34.04, -118.2]
  6878. * ];
  6879. *
  6880. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6881. *
  6882. * // zoom the map to the polyline
  6883. * map.fitBounds(polyline.getBounds());
  6884. * ```
  6885. *
  6886. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6887. *
  6888. * ```js
  6889. * // create a red polyline from an array of arrays of LatLng points
  6890. * var latlngs = [
  6891. * [[45.51, -122.68],
  6892. * [37.77, -122.43],
  6893. * [34.04, -118.2]],
  6894. * [[40.78, -73.91],
  6895. * [41.83, -87.62],
  6896. * [32.76, -96.72]]
  6897. * ];
  6898. * ```
  6899. */
  6900. var Polyline = Path.extend({
  6901. // @section
  6902. // @aka Polyline options
  6903. options: {
  6904. // @option smoothFactor: Number = 1.0
  6905. // How much to simplify the polyline on each zoom level. More means
  6906. // better performance and smoother look, and less means more accurate representation.
  6907. smoothFactor: 1.0,
  6908. // @option noClip: Boolean = false
  6909. // Disable polyline clipping.
  6910. noClip: false
  6911. },
  6912. initialize: function (latlngs, options) {
  6913. setOptions(this, options);
  6914. this._setLatLngs(latlngs);
  6915. },
  6916. // @method getLatLngs(): LatLng[]
  6917. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6918. getLatLngs: function () {
  6919. return this._latlngs;
  6920. },
  6921. // @method setLatLngs(latlngs: LatLng[]): this
  6922. // Replaces all the points in the polyline with the given array of geographical points.
  6923. setLatLngs: function (latlngs) {
  6924. this._setLatLngs(latlngs);
  6925. return this.redraw();
  6926. },
  6927. // @method isEmpty(): Boolean
  6928. // Returns `true` if the Polyline has no LatLngs.
  6929. isEmpty: function () {
  6930. return !this._latlngs.length;
  6931. },
  6932. // @method closestLayerPoint(p: Point): Point
  6933. // Returns the point closest to `p` on the Polyline.
  6934. closestLayerPoint: function (p) {
  6935. var minDistance = Infinity,
  6936. minPoint = null,
  6937. closest = _sqClosestPointOnSegment,
  6938. p1, p2;
  6939. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6940. var points = this._parts[j];
  6941. for (var i = 1, len = points.length; i < len; i++) {
  6942. p1 = points[i - 1];
  6943. p2 = points[i];
  6944. var sqDist = closest(p, p1, p2, true);
  6945. if (sqDist < minDistance) {
  6946. minDistance = sqDist;
  6947. minPoint = closest(p, p1, p2);
  6948. }
  6949. }
  6950. }
  6951. if (minPoint) {
  6952. minPoint.distance = Math.sqrt(minDistance);
  6953. }
  6954. return minPoint;
  6955. },
  6956. // @method getCenter(): LatLng
  6957. // Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6958. getCenter: function () {
  6959. // throws error when not yet added to map as this center calculation requires projected coordinates
  6960. if (!this._map) {
  6961. throw new Error('Must add layer to map before using getCenter()');
  6962. }
  6963. return polylineCenter(this._defaultShape(), this._map.options.crs);
  6964. },
  6965. // @method getBounds(): LatLngBounds
  6966. // Returns the `LatLngBounds` of the path.
  6967. getBounds: function () {
  6968. return this._bounds;
  6969. },
  6970. // @method addLatLng(latlng: LatLng, latlngs?: LatLng[]): this
  6971. // Adds a given point to the polyline. By default, adds to the first ring of
  6972. // the polyline in case of a multi-polyline, but can be overridden by passing
  6973. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6974. addLatLng: function (latlng, latlngs) {
  6975. latlngs = latlngs || this._defaultShape();
  6976. latlng = toLatLng(latlng);
  6977. latlngs.push(latlng);
  6978. this._bounds.extend(latlng);
  6979. return this.redraw();
  6980. },
  6981. _setLatLngs: function (latlngs) {
  6982. this._bounds = new LatLngBounds();
  6983. this._latlngs = this._convertLatLngs(latlngs);
  6984. },
  6985. _defaultShape: function () {
  6986. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6987. },
  6988. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6989. _convertLatLngs: function (latlngs) {
  6990. var result = [],
  6991. flat = isFlat(latlngs);
  6992. for (var i = 0, len = latlngs.length; i < len; i++) {
  6993. if (flat) {
  6994. result[i] = toLatLng(latlngs[i]);
  6995. this._bounds.extend(result[i]);
  6996. } else {
  6997. result[i] = this._convertLatLngs(latlngs[i]);
  6998. }
  6999. }
  7000. return result;
  7001. },
  7002. _project: function () {
  7003. var pxBounds = new Bounds();
  7004. this._rings = [];
  7005. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  7006. if (this._bounds.isValid() && pxBounds.isValid()) {
  7007. this._rawPxBounds = pxBounds;
  7008. this._updateBounds();
  7009. }
  7010. },
  7011. _updateBounds: function () {
  7012. var w = this._clickTolerance(),
  7013. p = new Point(w, w);
  7014. if (!this._rawPxBounds) {
  7015. return;
  7016. }
  7017. this._pxBounds = new Bounds([
  7018. this._rawPxBounds.min.subtract(p),
  7019. this._rawPxBounds.max.add(p)
  7020. ]);
  7021. },
  7022. // recursively turns latlngs into a set of rings with projected coordinates
  7023. _projectLatlngs: function (latlngs, result, projectedBounds) {
  7024. var flat = latlngs[0] instanceof LatLng,
  7025. len = latlngs.length,
  7026. i, ring;
  7027. if (flat) {
  7028. ring = [];
  7029. for (i = 0; i < len; i++) {
  7030. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  7031. projectedBounds.extend(ring[i]);
  7032. }
  7033. result.push(ring);
  7034. } else {
  7035. for (i = 0; i < len; i++) {
  7036. this._projectLatlngs(latlngs[i], result, projectedBounds);
  7037. }
  7038. }
  7039. },
  7040. // clip polyline by renderer bounds so that we have less to render for performance
  7041. _clipPoints: function () {
  7042. var bounds = this._renderer._bounds;
  7043. this._parts = [];
  7044. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7045. return;
  7046. }
  7047. if (this.options.noClip) {
  7048. this._parts = this._rings;
  7049. return;
  7050. }
  7051. var parts = this._parts,
  7052. i, j, k, len, len2, segment, points;
  7053. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  7054. points = this._rings[i];
  7055. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  7056. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  7057. if (!segment) { continue; }
  7058. parts[k] = parts[k] || [];
  7059. parts[k].push(segment[0]);
  7060. // if segment goes out of screen, or it's the last one, it's the end of the line part
  7061. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  7062. parts[k].push(segment[1]);
  7063. k++;
  7064. }
  7065. }
  7066. }
  7067. },
  7068. // simplify each clipped part of the polyline for performance
  7069. _simplifyPoints: function () {
  7070. var parts = this._parts,
  7071. tolerance = this.options.smoothFactor;
  7072. for (var i = 0, len = parts.length; i < len; i++) {
  7073. parts[i] = simplify(parts[i], tolerance);
  7074. }
  7075. },
  7076. _update: function () {
  7077. if (!this._map) { return; }
  7078. this._clipPoints();
  7079. this._simplifyPoints();
  7080. this._updatePath();
  7081. },
  7082. _updatePath: function () {
  7083. this._renderer._updatePoly(this);
  7084. },
  7085. // Needed by the `Canvas` renderer for interactivity
  7086. _containsPoint: function (p, closed) {
  7087. var i, j, k, len, len2, part,
  7088. w = this._clickTolerance();
  7089. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  7090. // hit detection for polylines
  7091. for (i = 0, len = this._parts.length; i < len; i++) {
  7092. part = this._parts[i];
  7093. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7094. if (!closed && (j === 0)) { continue; }
  7095. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  7096. return true;
  7097. }
  7098. }
  7099. }
  7100. return false;
  7101. }
  7102. });
  7103. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  7104. // Instantiates a polyline object given an array of geographical points and
  7105. // optionally an options object. You can create a `Polyline` object with
  7106. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  7107. // of geographic points.
  7108. function polyline(latlngs, options) {
  7109. return new Polyline(latlngs, options);
  7110. }
  7111. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  7112. Polyline._flat = _flat;
  7113. /*
  7114. * @class Polygon
  7115. * @aka L.Polygon
  7116. * @inherits Polyline
  7117. *
  7118. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  7119. *
  7120. * 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.
  7121. *
  7122. *
  7123. * @example
  7124. *
  7125. * ```js
  7126. * // create a red polygon from an array of LatLng points
  7127. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  7128. *
  7129. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  7130. *
  7131. * // zoom the map to the polygon
  7132. * map.fitBounds(polygon.getBounds());
  7133. * ```
  7134. *
  7135. * 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:
  7136. *
  7137. * ```js
  7138. * var latlngs = [
  7139. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7140. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7141. * ];
  7142. * ```
  7143. *
  7144. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  7145. *
  7146. * ```js
  7147. * var latlngs = [
  7148. * [ // first polygon
  7149. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7150. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7151. * ],
  7152. * [ // second polygon
  7153. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  7154. * ]
  7155. * ];
  7156. * ```
  7157. */
  7158. var Polygon = Polyline.extend({
  7159. options: {
  7160. fill: true
  7161. },
  7162. isEmpty: function () {
  7163. return !this._latlngs.length || !this._latlngs[0].length;
  7164. },
  7165. // @method getCenter(): LatLng
  7166. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the Polygon.
  7167. getCenter: function () {
  7168. // throws error when not yet added to map as this center calculation requires projected coordinates
  7169. if (!this._map) {
  7170. throw new Error('Must add layer to map before using getCenter()');
  7171. }
  7172. return polygonCenter(this._defaultShape(), this._map.options.crs);
  7173. },
  7174. _convertLatLngs: function (latlngs) {
  7175. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  7176. len = result.length;
  7177. // remove last point if it equals first one
  7178. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  7179. result.pop();
  7180. }
  7181. return result;
  7182. },
  7183. _setLatLngs: function (latlngs) {
  7184. Polyline.prototype._setLatLngs.call(this, latlngs);
  7185. if (isFlat(this._latlngs)) {
  7186. this._latlngs = [this._latlngs];
  7187. }
  7188. },
  7189. _defaultShape: function () {
  7190. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  7191. },
  7192. _clipPoints: function () {
  7193. // polygons need a different clipping algorithm so we redefine that
  7194. var bounds = this._renderer._bounds,
  7195. w = this.options.weight,
  7196. p = new Point(w, w);
  7197. // increase clip padding by stroke width to avoid stroke on clip edges
  7198. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  7199. this._parts = [];
  7200. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7201. return;
  7202. }
  7203. if (this.options.noClip) {
  7204. this._parts = this._rings;
  7205. return;
  7206. }
  7207. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  7208. clipped = clipPolygon(this._rings[i], bounds, true);
  7209. if (clipped.length) {
  7210. this._parts.push(clipped);
  7211. }
  7212. }
  7213. },
  7214. _updatePath: function () {
  7215. this._renderer._updatePoly(this, true);
  7216. },
  7217. // Needed by the `Canvas` renderer for interactivity
  7218. _containsPoint: function (p) {
  7219. var inside = false,
  7220. part, p1, p2, i, j, k, len, len2;
  7221. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  7222. // ray casting algorithm for detecting if point is in polygon
  7223. for (i = 0, len = this._parts.length; i < len; i++) {
  7224. part = this._parts[i];
  7225. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7226. p1 = part[j];
  7227. p2 = part[k];
  7228. 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)) {
  7229. inside = !inside;
  7230. }
  7231. }
  7232. }
  7233. // also check if it's on polygon stroke
  7234. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  7235. }
  7236. });
  7237. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  7238. function polygon(latlngs, options) {
  7239. return new Polygon(latlngs, options);
  7240. }
  7241. /*
  7242. * @class GeoJSON
  7243. * @aka L.GeoJSON
  7244. * @inherits FeatureGroup
  7245. *
  7246. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  7247. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  7248. *
  7249. * @example
  7250. *
  7251. * ```js
  7252. * L.geoJSON(data, {
  7253. * style: function (feature) {
  7254. * return {color: feature.properties.color};
  7255. * }
  7256. * }).bindPopup(function (layer) {
  7257. * return layer.feature.properties.description;
  7258. * }).addTo(map);
  7259. * ```
  7260. */
  7261. var GeoJSON = FeatureGroup.extend({
  7262. /* @section
  7263. * @aka GeoJSON options
  7264. *
  7265. * @option pointToLayer: Function = *
  7266. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  7267. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  7268. * The default is to spawn a default `Marker`:
  7269. * ```js
  7270. * function(geoJsonPoint, latlng) {
  7271. * return L.marker(latlng);
  7272. * }
  7273. * ```
  7274. *
  7275. * @option style: Function = *
  7276. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  7277. * called internally when data is added.
  7278. * The default value is to not override any defaults:
  7279. * ```js
  7280. * function (geoJsonFeature) {
  7281. * return {}
  7282. * }
  7283. * ```
  7284. *
  7285. * @option onEachFeature: Function = *
  7286. * A `Function` that will be called once for each created `Feature`, after it has
  7287. * been created and styled. Useful for attaching events and popups to features.
  7288. * The default is to do nothing with the newly created layers:
  7289. * ```js
  7290. * function (feature, layer) {}
  7291. * ```
  7292. *
  7293. * @option filter: Function = *
  7294. * A `Function` that will be used to decide whether to include a feature or not.
  7295. * The default is to include all features:
  7296. * ```js
  7297. * function (geoJsonFeature) {
  7298. * return true;
  7299. * }
  7300. * ```
  7301. * Note: dynamically changing the `filter` option will have effect only on newly
  7302. * added data. It will _not_ re-evaluate already included features.
  7303. *
  7304. * @option coordsToLatLng: Function = *
  7305. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  7306. * The default is the `coordsToLatLng` static method.
  7307. *
  7308. * @option markersInheritOptions: Boolean = false
  7309. * Whether default Markers for "Point" type Features inherit from group options.
  7310. */
  7311. initialize: function (geojson, options) {
  7312. setOptions(this, options);
  7313. this._layers = {};
  7314. if (geojson) {
  7315. this.addData(geojson);
  7316. }
  7317. },
  7318. // @method addData( <GeoJSON> data ): this
  7319. // Adds a GeoJSON object to the layer.
  7320. addData: function (geojson) {
  7321. var features = isArray(geojson) ? geojson : geojson.features,
  7322. i, len, feature;
  7323. if (features) {
  7324. for (i = 0, len = features.length; i < len; i++) {
  7325. // only add this if geometry or geometries are set and not null
  7326. feature = features[i];
  7327. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  7328. this.addData(feature);
  7329. }
  7330. }
  7331. return this;
  7332. }
  7333. var options = this.options;
  7334. if (options.filter && !options.filter(geojson)) { return this; }
  7335. var layer = geometryToLayer(geojson, options);
  7336. if (!layer) {
  7337. return this;
  7338. }
  7339. layer.feature = asFeature(geojson);
  7340. layer.defaultOptions = layer.options;
  7341. this.resetStyle(layer);
  7342. if (options.onEachFeature) {
  7343. options.onEachFeature(geojson, layer);
  7344. }
  7345. return this.addLayer(layer);
  7346. },
  7347. // @method resetStyle( <Path> layer? ): this
  7348. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7349. // If `layer` is omitted, the style of all features in the current layer is reset.
  7350. resetStyle: function (layer) {
  7351. if (layer === undefined) {
  7352. return this.eachLayer(this.resetStyle, this);
  7353. }
  7354. // reset any custom styles
  7355. layer.options = extend({}, layer.defaultOptions);
  7356. this._setLayerStyle(layer, this.options.style);
  7357. return this;
  7358. },
  7359. // @method setStyle( <Function> style ): this
  7360. // Changes styles of GeoJSON vector layers with the given style function.
  7361. setStyle: function (style) {
  7362. return this.eachLayer(function (layer) {
  7363. this._setLayerStyle(layer, style);
  7364. }, this);
  7365. },
  7366. _setLayerStyle: function (layer, style) {
  7367. if (layer.setStyle) {
  7368. if (typeof style === 'function') {
  7369. style = style(layer.feature);
  7370. }
  7371. layer.setStyle(style);
  7372. }
  7373. }
  7374. });
  7375. // @section
  7376. // There are several static functions which can be called without instantiating L.GeoJSON:
  7377. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7378. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7379. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7380. // functions if provided as options.
  7381. function geometryToLayer(geojson, options) {
  7382. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7383. coords = geometry ? geometry.coordinates : null,
  7384. layers = [],
  7385. pointToLayer = options && options.pointToLayer,
  7386. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7387. latlng, latlngs, i, len;
  7388. if (!coords && !geometry) {
  7389. return null;
  7390. }
  7391. switch (geometry.type) {
  7392. case 'Point':
  7393. latlng = _coordsToLatLng(coords);
  7394. return _pointToLayer(pointToLayer, geojson, latlng, options);
  7395. case 'MultiPoint':
  7396. for (i = 0, len = coords.length; i < len; i++) {
  7397. latlng = _coordsToLatLng(coords[i]);
  7398. layers.push(_pointToLayer(pointToLayer, geojson, latlng, options));
  7399. }
  7400. return new FeatureGroup(layers);
  7401. case 'LineString':
  7402. case 'MultiLineString':
  7403. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7404. return new Polyline(latlngs, options);
  7405. case 'Polygon':
  7406. case 'MultiPolygon':
  7407. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7408. return new Polygon(latlngs, options);
  7409. case 'GeometryCollection':
  7410. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7411. var geoLayer = geometryToLayer({
  7412. geometry: geometry.geometries[i],
  7413. type: 'Feature',
  7414. properties: geojson.properties
  7415. }, options);
  7416. if (geoLayer) {
  7417. layers.push(geoLayer);
  7418. }
  7419. }
  7420. return new FeatureGroup(layers);
  7421. case 'FeatureCollection':
  7422. for (i = 0, len = geometry.features.length; i < len; i++) {
  7423. var featureLayer = geometryToLayer(geometry.features[i], options);
  7424. if (featureLayer) {
  7425. layers.push(featureLayer);
  7426. }
  7427. }
  7428. return new FeatureGroup(layers);
  7429. default:
  7430. throw new Error('Invalid GeoJSON object.');
  7431. }
  7432. }
  7433. function _pointToLayer(pointToLayerFn, geojson, latlng, options) {
  7434. return pointToLayerFn ?
  7435. pointToLayerFn(geojson, latlng) :
  7436. new Marker(latlng, options && options.markersInheritOptions && options);
  7437. }
  7438. // @function coordsToLatLng(coords: Array): LatLng
  7439. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7440. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7441. function coordsToLatLng(coords) {
  7442. return new LatLng(coords[1], coords[0], coords[2]);
  7443. }
  7444. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7445. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7446. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7447. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7448. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7449. var latlngs = [];
  7450. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7451. latlng = levelsDeep ?
  7452. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7453. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7454. latlngs.push(latlng);
  7455. }
  7456. return latlngs;
  7457. }
  7458. // @function latLngToCoords(latlng: LatLng, precision?: Number|false): Array
  7459. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7460. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function.
  7461. function latLngToCoords(latlng, precision) {
  7462. latlng = toLatLng(latlng);
  7463. return latlng.alt !== undefined ?
  7464. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7465. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7466. }
  7467. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean, precision?: Number|false): Array
  7468. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7469. // `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.
  7470. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function.
  7471. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7472. var coords = [];
  7473. for (var i = 0, len = latlngs.length; i < len; i++) {
  7474. // Check for flat arrays required to ensure unbalanced arrays are correctly converted in recursion
  7475. coords.push(levelsDeep ?
  7476. latLngsToCoords(latlngs[i], isFlat(latlngs[i]) ? 0 : levelsDeep - 1, closed, precision) :
  7477. latLngToCoords(latlngs[i], precision));
  7478. }
  7479. if (!levelsDeep && closed) {
  7480. coords.push(coords[0]);
  7481. }
  7482. return coords;
  7483. }
  7484. function getFeature(layer, newGeometry) {
  7485. return layer.feature ?
  7486. extend({}, layer.feature, {geometry: newGeometry}) :
  7487. asFeature(newGeometry);
  7488. }
  7489. // @function asFeature(geojson: Object): Object
  7490. // Normalize GeoJSON geometries/features into GeoJSON features.
  7491. function asFeature(geojson) {
  7492. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7493. return geojson;
  7494. }
  7495. return {
  7496. type: 'Feature',
  7497. properties: {},
  7498. geometry: geojson
  7499. };
  7500. }
  7501. var PointToGeoJSON = {
  7502. toGeoJSON: function (precision) {
  7503. return getFeature(this, {
  7504. type: 'Point',
  7505. coordinates: latLngToCoords(this.getLatLng(), precision)
  7506. });
  7507. }
  7508. };
  7509. // @namespace Marker
  7510. // @section Other methods
  7511. // @method toGeoJSON(precision?: Number|false): Object
  7512. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7513. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7514. Marker.include(PointToGeoJSON);
  7515. // @namespace CircleMarker
  7516. // @method toGeoJSON(precision?: Number|false): Object
  7517. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7518. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7519. Circle.include(PointToGeoJSON);
  7520. CircleMarker.include(PointToGeoJSON);
  7521. // @namespace Polyline
  7522. // @method toGeoJSON(precision?: Number|false): Object
  7523. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7524. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7525. Polyline.include({
  7526. toGeoJSON: function (precision) {
  7527. var multi = !isFlat(this._latlngs);
  7528. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7529. return getFeature(this, {
  7530. type: (multi ? 'Multi' : '') + 'LineString',
  7531. coordinates: coords
  7532. });
  7533. }
  7534. });
  7535. // @namespace Polygon
  7536. // @method toGeoJSON(precision?: Number|false): Object
  7537. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7538. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7539. Polygon.include({
  7540. toGeoJSON: function (precision) {
  7541. var holes = !isFlat(this._latlngs),
  7542. multi = holes && !isFlat(this._latlngs[0]);
  7543. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7544. if (!holes) {
  7545. coords = [coords];
  7546. }
  7547. return getFeature(this, {
  7548. type: (multi ? 'Multi' : '') + 'Polygon',
  7549. coordinates: coords
  7550. });
  7551. }
  7552. });
  7553. // @namespace LayerGroup
  7554. LayerGroup.include({
  7555. toMultiPoint: function (precision) {
  7556. var coords = [];
  7557. this.eachLayer(function (layer) {
  7558. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7559. });
  7560. return getFeature(this, {
  7561. type: 'MultiPoint',
  7562. coordinates: coords
  7563. });
  7564. },
  7565. // @method toGeoJSON(precision?: Number|false): Object
  7566. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7567. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7568. toGeoJSON: function (precision) {
  7569. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7570. if (type === 'MultiPoint') {
  7571. return this.toMultiPoint(precision);
  7572. }
  7573. var isGeometryCollection = type === 'GeometryCollection',
  7574. jsons = [];
  7575. this.eachLayer(function (layer) {
  7576. if (layer.toGeoJSON) {
  7577. var json = layer.toGeoJSON(precision);
  7578. if (isGeometryCollection) {
  7579. jsons.push(json.geometry);
  7580. } else {
  7581. var feature = asFeature(json);
  7582. // Squash nested feature collections
  7583. if (feature.type === 'FeatureCollection') {
  7584. jsons.push.apply(jsons, feature.features);
  7585. } else {
  7586. jsons.push(feature);
  7587. }
  7588. }
  7589. }
  7590. });
  7591. if (isGeometryCollection) {
  7592. return getFeature(this, {
  7593. geometries: jsons,
  7594. type: 'GeometryCollection'
  7595. });
  7596. }
  7597. return {
  7598. type: 'FeatureCollection',
  7599. features: jsons
  7600. };
  7601. }
  7602. });
  7603. // @namespace GeoJSON
  7604. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7605. // Creates a GeoJSON layer. Optionally accepts an object in
  7606. // [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map
  7607. // (you can alternatively add it later with `addData` method) and an `options` object.
  7608. function geoJSON(geojson, options) {
  7609. return new GeoJSON(geojson, options);
  7610. }
  7611. // Backward compatibility.
  7612. var geoJson = geoJSON;
  7613. /*
  7614. * @class ImageOverlay
  7615. * @aka L.ImageOverlay
  7616. * @inherits Interactive layer
  7617. *
  7618. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7619. *
  7620. * @example
  7621. *
  7622. * ```js
  7623. * var imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7624. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7625. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7626. * ```
  7627. */
  7628. var ImageOverlay = Layer.extend({
  7629. // @section
  7630. // @aka ImageOverlay options
  7631. options: {
  7632. // @option opacity: Number = 1.0
  7633. // The opacity of the image overlay.
  7634. opacity: 1,
  7635. // @option alt: String = ''
  7636. // Text for the `alt` attribute of the image (useful for accessibility).
  7637. alt: '',
  7638. // @option interactive: Boolean = false
  7639. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7640. interactive: false,
  7641. // @option crossOrigin: Boolean|String = false
  7642. // Whether the crossOrigin attribute will be added to the image.
  7643. // If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data.
  7644. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  7645. crossOrigin: false,
  7646. // @option errorOverlayUrl: String = ''
  7647. // URL to the overlay image to show in place of the overlay that failed to load.
  7648. errorOverlayUrl: '',
  7649. // @option zIndex: Number = 1
  7650. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
  7651. zIndex: 1,
  7652. // @option className: String = ''
  7653. // A custom class name to assign to the image. Empty by default.
  7654. className: ''
  7655. },
  7656. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7657. this._url = url;
  7658. this._bounds = toLatLngBounds(bounds);
  7659. setOptions(this, options);
  7660. },
  7661. onAdd: function () {
  7662. if (!this._image) {
  7663. this._initImage();
  7664. if (this.options.opacity < 1) {
  7665. this._updateOpacity();
  7666. }
  7667. }
  7668. if (this.options.interactive) {
  7669. addClass(this._image, 'leaflet-interactive');
  7670. this.addInteractiveTarget(this._image);
  7671. }
  7672. this.getPane().appendChild(this._image);
  7673. this._reset();
  7674. },
  7675. onRemove: function () {
  7676. remove(this._image);
  7677. if (this.options.interactive) {
  7678. this.removeInteractiveTarget(this._image);
  7679. }
  7680. },
  7681. // @method setOpacity(opacity: Number): this
  7682. // Sets the opacity of the overlay.
  7683. setOpacity: function (opacity) {
  7684. this.options.opacity = opacity;
  7685. if (this._image) {
  7686. this._updateOpacity();
  7687. }
  7688. return this;
  7689. },
  7690. setStyle: function (styleOpts) {
  7691. if (styleOpts.opacity) {
  7692. this.setOpacity(styleOpts.opacity);
  7693. }
  7694. return this;
  7695. },
  7696. // @method bringToFront(): this
  7697. // Brings the layer to the top of all overlays.
  7698. bringToFront: function () {
  7699. if (this._map) {
  7700. toFront(this._image);
  7701. }
  7702. return this;
  7703. },
  7704. // @method bringToBack(): this
  7705. // Brings the layer to the bottom of all overlays.
  7706. bringToBack: function () {
  7707. if (this._map) {
  7708. toBack(this._image);
  7709. }
  7710. return this;
  7711. },
  7712. // @method setUrl(url: String): this
  7713. // Changes the URL of the image.
  7714. setUrl: function (url) {
  7715. this._url = url;
  7716. if (this._image) {
  7717. this._image.src = url;
  7718. }
  7719. return this;
  7720. },
  7721. // @method setBounds(bounds: LatLngBounds): this
  7722. // Update the bounds that this ImageOverlay covers
  7723. setBounds: function (bounds) {
  7724. this._bounds = toLatLngBounds(bounds);
  7725. if (this._map) {
  7726. this._reset();
  7727. }
  7728. return this;
  7729. },
  7730. getEvents: function () {
  7731. var events = {
  7732. zoom: this._reset,
  7733. viewreset: this._reset
  7734. };
  7735. if (this._zoomAnimated) {
  7736. events.zoomanim = this._animateZoom;
  7737. }
  7738. return events;
  7739. },
  7740. // @method setZIndex(value: Number): this
  7741. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7742. setZIndex: function (value) {
  7743. this.options.zIndex = value;
  7744. this._updateZIndex();
  7745. return this;
  7746. },
  7747. // @method getBounds(): LatLngBounds
  7748. // Get the bounds that this ImageOverlay covers
  7749. getBounds: function () {
  7750. return this._bounds;
  7751. },
  7752. // @method getElement(): HTMLElement
  7753. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7754. // used by this overlay.
  7755. getElement: function () {
  7756. return this._image;
  7757. },
  7758. _initImage: function () {
  7759. var wasElementSupplied = this._url.tagName === 'IMG';
  7760. var img = this._image = wasElementSupplied ? this._url : create$1('img');
  7761. addClass(img, 'leaflet-image-layer');
  7762. if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
  7763. if (this.options.className) { addClass(img, this.options.className); }
  7764. img.onselectstart = falseFn;
  7765. img.onmousemove = falseFn;
  7766. // @event load: Event
  7767. // Fired when the ImageOverlay layer has loaded its image
  7768. img.onload = bind(this.fire, this, 'load');
  7769. img.onerror = bind(this._overlayOnError, this, 'error');
  7770. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  7771. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  7772. }
  7773. if (this.options.zIndex) {
  7774. this._updateZIndex();
  7775. }
  7776. if (wasElementSupplied) {
  7777. this._url = img.src;
  7778. return;
  7779. }
  7780. img.src = this._url;
  7781. img.alt = this.options.alt;
  7782. },
  7783. _animateZoom: function (e) {
  7784. var scale = this._map.getZoomScale(e.zoom),
  7785. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7786. setTransform(this._image, offset, scale);
  7787. },
  7788. _reset: function () {
  7789. var image = this._image,
  7790. bounds = new Bounds(
  7791. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7792. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7793. size = bounds.getSize();
  7794. setPosition(image, bounds.min);
  7795. image.style.width = size.x + 'px';
  7796. image.style.height = size.y + 'px';
  7797. },
  7798. _updateOpacity: function () {
  7799. setOpacity(this._image, this.options.opacity);
  7800. },
  7801. _updateZIndex: function () {
  7802. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7803. this._image.style.zIndex = this.options.zIndex;
  7804. }
  7805. },
  7806. _overlayOnError: function () {
  7807. // @event error: Event
  7808. // Fired when the ImageOverlay layer fails to load its image
  7809. this.fire('error');
  7810. var errorUrl = this.options.errorOverlayUrl;
  7811. if (errorUrl && this._url !== errorUrl) {
  7812. this._url = errorUrl;
  7813. this._image.src = errorUrl;
  7814. }
  7815. },
  7816. // @method getCenter(): LatLng
  7817. // Returns the center of the ImageOverlay.
  7818. getCenter: function () {
  7819. return this._bounds.getCenter();
  7820. }
  7821. });
  7822. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7823. // Instantiates an image overlay object given the URL of the image and the
  7824. // geographical bounds it is tied to.
  7825. var imageOverlay = function (url, bounds, options) {
  7826. return new ImageOverlay(url, bounds, options);
  7827. };
  7828. /*
  7829. * @class VideoOverlay
  7830. * @aka L.VideoOverlay
  7831. * @inherits ImageOverlay
  7832. *
  7833. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7834. *
  7835. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7836. * HTML5 element.
  7837. *
  7838. * @example
  7839. *
  7840. * ```js
  7841. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7842. * videoBounds = [[ 32, -130], [ 13, -100]];
  7843. * L.videoOverlay(videoUrl, videoBounds ).addTo(map);
  7844. * ```
  7845. */
  7846. var VideoOverlay = ImageOverlay.extend({
  7847. // @section
  7848. // @aka VideoOverlay options
  7849. options: {
  7850. // @option autoplay: Boolean = true
  7851. // Whether the video starts playing automatically when loaded.
  7852. // On some browsers autoplay will only work with `muted: true`
  7853. autoplay: true,
  7854. // @option loop: Boolean = true
  7855. // Whether the video will loop back to the beginning when played.
  7856. loop: true,
  7857. // @option keepAspectRatio: Boolean = true
  7858. // Whether the video will save aspect ratio after the projection.
  7859. // Relevant for supported browsers. See [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
  7860. keepAspectRatio: true,
  7861. // @option muted: Boolean = false
  7862. // Whether the video starts on mute when loaded.
  7863. muted: false,
  7864. // @option playsInline: Boolean = true
  7865. // Mobile browsers will play the video right where it is instead of open it up in fullscreen mode.
  7866. playsInline: true
  7867. },
  7868. _initImage: function () {
  7869. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7870. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7871. addClass(vid, 'leaflet-image-layer');
  7872. if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
  7873. if (this.options.className) { addClass(vid, this.options.className); }
  7874. vid.onselectstart = falseFn;
  7875. vid.onmousemove = falseFn;
  7876. // @event load: Event
  7877. // Fired when the video has finished loading the first frame
  7878. vid.onloadeddata = bind(this.fire, this, 'load');
  7879. if (wasElementSupplied) {
  7880. var sourceElements = vid.getElementsByTagName('source');
  7881. var sources = [];
  7882. for (var j = 0; j < sourceElements.length; j++) {
  7883. sources.push(sourceElements[j].src);
  7884. }
  7885. this._url = (sourceElements.length > 0) ? sources : [vid.src];
  7886. return;
  7887. }
  7888. if (!isArray(this._url)) { this._url = [this._url]; }
  7889. if (!this.options.keepAspectRatio && Object.prototype.hasOwnProperty.call(vid.style, 'objectFit')) {
  7890. vid.style['objectFit'] = 'fill';
  7891. }
  7892. vid.autoplay = !!this.options.autoplay;
  7893. vid.loop = !!this.options.loop;
  7894. vid.muted = !!this.options.muted;
  7895. vid.playsInline = !!this.options.playsInline;
  7896. for (var i = 0; i < this._url.length; i++) {
  7897. var source = create$1('source');
  7898. source.src = this._url[i];
  7899. vid.appendChild(source);
  7900. }
  7901. }
  7902. // @method getElement(): HTMLVideoElement
  7903. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7904. // used by this overlay.
  7905. });
  7906. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7907. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7908. // geographical bounds it is tied to.
  7909. function videoOverlay(video, bounds, options) {
  7910. return new VideoOverlay(video, bounds, options);
  7911. }
  7912. /*
  7913. * @class SVGOverlay
  7914. * @aka L.SVGOverlay
  7915. * @inherits ImageOverlay
  7916. *
  7917. * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.
  7918. *
  7919. * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.
  7920. *
  7921. * @example
  7922. *
  7923. * ```js
  7924. * var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  7925. * svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
  7926. * svgElement.setAttribute('viewBox', "0 0 200 200");
  7927. * svgElement.innerHTML = '<rect width="200" height="200"/><rect x="75" y="23" width="50" height="50" style="fill:red"/><rect x="75" y="123" width="50" height="50" style="fill:#0013ff"/>';
  7928. * var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
  7929. * L.svgOverlay(svgElement, svgElementBounds).addTo(map);
  7930. * ```
  7931. */
  7932. var SVGOverlay = ImageOverlay.extend({
  7933. _initImage: function () {
  7934. var el = this._image = this._url;
  7935. addClass(el, 'leaflet-image-layer');
  7936. if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); }
  7937. if (this.options.className) { addClass(el, this.options.className); }
  7938. el.onselectstart = falseFn;
  7939. el.onmousemove = falseFn;
  7940. }
  7941. // @method getElement(): SVGElement
  7942. // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
  7943. // used by this overlay.
  7944. });
  7945. // @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)
  7946. // Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.
  7947. // A viewBox attribute is required on the SVG element to zoom in and out properly.
  7948. function svgOverlay(el, bounds, options) {
  7949. return new SVGOverlay(el, bounds, options);
  7950. }
  7951. /*
  7952. * @class DivOverlay
  7953. * @inherits Interactive layer
  7954. * @aka L.DivOverlay
  7955. * Base model for L.Popup and L.Tooltip. Inherit from it for custom overlays like plugins.
  7956. */
  7957. // @namespace DivOverlay
  7958. var DivOverlay = Layer.extend({
  7959. // @section
  7960. // @aka DivOverlay options
  7961. options: {
  7962. // @option interactive: Boolean = false
  7963. // If true, the popup/tooltip will listen to the mouse events.
  7964. interactive: false,
  7965. // @option offset: Point = Point(0, 0)
  7966. // The offset of the overlay position.
  7967. offset: [0, 0],
  7968. // @option className: String = ''
  7969. // A custom CSS class name to assign to the overlay.
  7970. className: '',
  7971. // @option pane: String = undefined
  7972. // `Map pane` where the overlay will be added.
  7973. pane: undefined,
  7974. // @option content: String|HTMLElement|Function = ''
  7975. // Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be
  7976. // passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay.
  7977. content: ''
  7978. },
  7979. initialize: function (options, source) {
  7980. if (options && (options instanceof L.LatLng || isArray(options))) {
  7981. this._latlng = toLatLng(options);
  7982. setOptions(this, source);
  7983. } else {
  7984. setOptions(this, options);
  7985. this._source = source;
  7986. }
  7987. if (this.options.content) {
  7988. this._content = this.options.content;
  7989. }
  7990. },
  7991. // @method openOn(map: Map): this
  7992. // Adds the overlay to the map.
  7993. // Alternative to `map.openPopup(popup)`/`.openTooltip(tooltip)`.
  7994. openOn: function (map) {
  7995. map = arguments.length ? map : this._source._map; // experimental, not the part of public api
  7996. if (!map.hasLayer(this)) {
  7997. map.addLayer(this);
  7998. }
  7999. return this;
  8000. },
  8001. // @method close(): this
  8002. // Closes the overlay.
  8003. // Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)`
  8004. // and `layer.closePopup()`/`.closeTooltip()`.
  8005. close: function () {
  8006. if (this._map) {
  8007. this._map.removeLayer(this);
  8008. }
  8009. return this;
  8010. },
  8011. // @method toggle(layer?: Layer): this
  8012. // Opens or closes the overlay bound to layer depending on its current state.
  8013. // Argument may be omitted only for overlay bound to layer.
  8014. // Alternative to `layer.togglePopup()`/`.toggleTooltip()`.
  8015. toggle: function (layer) {
  8016. if (this._map) {
  8017. this.close();
  8018. } else {
  8019. if (arguments.length) {
  8020. this._source = layer;
  8021. } else {
  8022. layer = this._source;
  8023. }
  8024. this._prepareOpen();
  8025. // open the overlay on the map
  8026. this.openOn(layer._map);
  8027. }
  8028. return this;
  8029. },
  8030. onAdd: function (map) {
  8031. this._zoomAnimated = map._zoomAnimated;
  8032. if (!this._container) {
  8033. this._initLayout();
  8034. }
  8035. if (map._fadeAnimated) {
  8036. setOpacity(this._container, 0);
  8037. }
  8038. clearTimeout(this._removeTimeout);
  8039. this.getPane().appendChild(this._container);
  8040. this.update();
  8041. if (map._fadeAnimated) {
  8042. setOpacity(this._container, 1);
  8043. }
  8044. this.bringToFront();
  8045. if (this.options.interactive) {
  8046. addClass(this._container, 'leaflet-interactive');
  8047. this.addInteractiveTarget(this._container);
  8048. }
  8049. },
  8050. onRemove: function (map) {
  8051. if (map._fadeAnimated) {
  8052. setOpacity(this._container, 0);
  8053. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  8054. } else {
  8055. remove(this._container);
  8056. }
  8057. if (this.options.interactive) {
  8058. removeClass(this._container, 'leaflet-interactive');
  8059. this.removeInteractiveTarget(this._container);
  8060. }
  8061. },
  8062. // @namespace DivOverlay
  8063. // @method getLatLng: LatLng
  8064. // Returns the geographical point of the overlay.
  8065. getLatLng: function () {
  8066. return this._latlng;
  8067. },
  8068. // @method setLatLng(latlng: LatLng): this
  8069. // Sets the geographical point where the overlay will open.
  8070. setLatLng: function (latlng) {
  8071. this._latlng = toLatLng(latlng);
  8072. if (this._map) {
  8073. this._updatePosition();
  8074. this._adjustPan();
  8075. }
  8076. return this;
  8077. },
  8078. // @method getContent: String|HTMLElement
  8079. // Returns the content of the overlay.
  8080. getContent: function () {
  8081. return this._content;
  8082. },
  8083. // @method setContent(htmlContent: String|HTMLElement|Function): this
  8084. // Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function.
  8085. // The function should return a `String` or `HTMLElement` to be used in the overlay.
  8086. setContent: function (content) {
  8087. this._content = content;
  8088. this.update();
  8089. return this;
  8090. },
  8091. // @method getElement: String|HTMLElement
  8092. // Returns the HTML container of the overlay.
  8093. getElement: function () {
  8094. return this._container;
  8095. },
  8096. // @method update: null
  8097. // Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded.
  8098. update: function () {
  8099. if (!this._map) { return; }
  8100. this._container.style.visibility = 'hidden';
  8101. this._updateContent();
  8102. this._updateLayout();
  8103. this._updatePosition();
  8104. this._container.style.visibility = '';
  8105. this._adjustPan();
  8106. },
  8107. getEvents: function () {
  8108. var events = {
  8109. zoom: this._updatePosition,
  8110. viewreset: this._updatePosition
  8111. };
  8112. if (this._zoomAnimated) {
  8113. events.zoomanim = this._animateZoom;
  8114. }
  8115. return events;
  8116. },
  8117. // @method isOpen: Boolean
  8118. // Returns `true` when the overlay is visible on the map.
  8119. isOpen: function () {
  8120. return !!this._map && this._map.hasLayer(this);
  8121. },
  8122. // @method bringToFront: this
  8123. // Brings this overlay in front of other overlays (in the same map pane).
  8124. bringToFront: function () {
  8125. if (this._map) {
  8126. toFront(this._container);
  8127. }
  8128. return this;
  8129. },
  8130. // @method bringToBack: this
  8131. // Brings this overlay to the back of other overlays (in the same map pane).
  8132. bringToBack: function () {
  8133. if (this._map) {
  8134. toBack(this._container);
  8135. }
  8136. return this;
  8137. },
  8138. // prepare bound overlay to open: update latlng pos / content source (for FeatureGroup)
  8139. _prepareOpen: function (latlng) {
  8140. var source = this._source;
  8141. if (!source._map) { return false; }
  8142. if (source instanceof FeatureGroup) {
  8143. source = null;
  8144. var layers = this._source._layers;
  8145. for (var id in layers) {
  8146. if (layers[id]._map) {
  8147. source = layers[id];
  8148. break;
  8149. }
  8150. }
  8151. if (!source) { return false; } // Unable to get source layer.
  8152. // set overlay source to this layer
  8153. this._source = source;
  8154. }
  8155. if (!latlng) {
  8156. if (source.getCenter) {
  8157. latlng = source.getCenter();
  8158. } else if (source.getLatLng) {
  8159. latlng = source.getLatLng();
  8160. } else if (source.getBounds) {
  8161. latlng = source.getBounds().getCenter();
  8162. } else {
  8163. throw new Error('Unable to get source layer LatLng.');
  8164. }
  8165. }
  8166. this.setLatLng(latlng);
  8167. if (this._map) {
  8168. // update the overlay (content, layout, etc...)
  8169. this.update();
  8170. }
  8171. return true;
  8172. },
  8173. _updateContent: function () {
  8174. if (!this._content) { return; }
  8175. var node = this._contentNode;
  8176. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  8177. if (typeof content === 'string') {
  8178. node.innerHTML = content;
  8179. } else {
  8180. while (node.hasChildNodes()) {
  8181. node.removeChild(node.firstChild);
  8182. }
  8183. node.appendChild(content);
  8184. }
  8185. // @namespace DivOverlay
  8186. // @section DivOverlay events
  8187. // @event contentupdate: Event
  8188. // Fired when the content of the overlay is updated
  8189. this.fire('contentupdate');
  8190. },
  8191. _updatePosition: function () {
  8192. if (!this._map) { return; }
  8193. var pos = this._map.latLngToLayerPoint(this._latlng),
  8194. offset = toPoint(this.options.offset),
  8195. anchor = this._getAnchor();
  8196. if (this._zoomAnimated) {
  8197. setPosition(this._container, pos.add(anchor));
  8198. } else {
  8199. offset = offset.add(pos).add(anchor);
  8200. }
  8201. var bottom = this._containerBottom = -offset.y,
  8202. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  8203. // bottom position the overlay in case the height of the overlay changes (images loading etc)
  8204. this._container.style.bottom = bottom + 'px';
  8205. this._container.style.left = left + 'px';
  8206. },
  8207. _getAnchor: function () {
  8208. return [0, 0];
  8209. }
  8210. });
  8211. Map.include({
  8212. _initOverlay: function (OverlayClass, content, latlng, options) {
  8213. var overlay = content;
  8214. if (!(overlay instanceof OverlayClass)) {
  8215. overlay = new OverlayClass(options).setContent(content);
  8216. }
  8217. if (latlng) {
  8218. overlay.setLatLng(latlng);
  8219. }
  8220. return overlay;
  8221. }
  8222. });
  8223. Layer.include({
  8224. _initOverlay: function (OverlayClass, old, content, options) {
  8225. var overlay = content;
  8226. if (overlay instanceof OverlayClass) {
  8227. setOptions(overlay, options);
  8228. overlay._source = this;
  8229. } else {
  8230. overlay = (old && !options) ? old : new OverlayClass(options, this);
  8231. overlay.setContent(content);
  8232. }
  8233. return overlay;
  8234. }
  8235. });
  8236. /*
  8237. * @class Popup
  8238. * @inherits DivOverlay
  8239. * @aka L.Popup
  8240. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  8241. * open popups while making sure that only one popup is open at one time
  8242. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  8243. *
  8244. * @example
  8245. *
  8246. * If you want to just bind a popup to marker click and then open it, it's really easy:
  8247. *
  8248. * ```js
  8249. * marker.bindPopup(popupContent).openPopup();
  8250. * ```
  8251. * Path overlays like polylines also have a `bindPopup` method.
  8252. *
  8253. * A popup can be also standalone:
  8254. *
  8255. * ```js
  8256. * var popup = L.popup()
  8257. * .setLatLng(latlng)
  8258. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  8259. * .openOn(map);
  8260. * ```
  8261. * or
  8262. * ```js
  8263. * var popup = L.popup(latlng, {content: '<p>Hello world!<br />This is a nice popup.</p>')
  8264. * .openOn(map);
  8265. * ```
  8266. */
  8267. // @namespace Popup
  8268. var Popup = DivOverlay.extend({
  8269. // @section
  8270. // @aka Popup options
  8271. options: {
  8272. // @option pane: String = 'popupPane'
  8273. // `Map pane` where the popup will be added.
  8274. pane: 'popupPane',
  8275. // @option offset: Point = Point(0, 7)
  8276. // The offset of the popup position.
  8277. offset: [0, 7],
  8278. // @option maxWidth: Number = 300
  8279. // Max width of the popup, in pixels.
  8280. maxWidth: 300,
  8281. // @option minWidth: Number = 50
  8282. // Min width of the popup, in pixels.
  8283. minWidth: 50,
  8284. // @option maxHeight: Number = null
  8285. // If set, creates a scrollable container of the given height
  8286. // inside a popup if its content exceeds it.
  8287. // The scrollable container can be styled using the
  8288. // `leaflet-popup-scrolled` CSS class selector.
  8289. maxHeight: null,
  8290. // @option autoPan: Boolean = true
  8291. // Set it to `false` if you don't want the map to do panning animation
  8292. // to fit the opened popup.
  8293. autoPan: true,
  8294. // @option autoPanPaddingTopLeft: Point = null
  8295. // The margin between the popup and the top left corner of the map
  8296. // view after autopanning was performed.
  8297. autoPanPaddingTopLeft: null,
  8298. // @option autoPanPaddingBottomRight: Point = null
  8299. // The margin between the popup and the bottom right corner of the map
  8300. // view after autopanning was performed.
  8301. autoPanPaddingBottomRight: null,
  8302. // @option autoPanPadding: Point = Point(5, 5)
  8303. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  8304. autoPanPadding: [5, 5],
  8305. // @option keepInView: Boolean = false
  8306. // Set it to `true` if you want to prevent users from panning the popup
  8307. // off of the screen while it is open.
  8308. keepInView: false,
  8309. // @option closeButton: Boolean = true
  8310. // Controls the presence of a close button in the popup.
  8311. closeButton: true,
  8312. // @option autoClose: Boolean = true
  8313. // Set it to `false` if you want to override the default behavior of
  8314. // the popup closing when another popup is opened.
  8315. autoClose: true,
  8316. // @option closeOnEscapeKey: Boolean = true
  8317. // Set it to `false` if you want to override the default behavior of
  8318. // the ESC key for closing of the popup.
  8319. closeOnEscapeKey: true,
  8320. // @option closeOnClick: Boolean = *
  8321. // Set it if you want to override the default behavior of the popup closing when user clicks
  8322. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  8323. // @option className: String = ''
  8324. // A custom CSS class name to assign to the popup.
  8325. className: ''
  8326. },
  8327. // @namespace Popup
  8328. // @method openOn(map: Map): this
  8329. // Alternative to `map.openPopup(popup)`.
  8330. // Adds the popup to the map and closes the previous one.
  8331. openOn: function (map) {
  8332. map = arguments.length ? map : this._source._map; // experimental, not the part of public api
  8333. if (!map.hasLayer(this) && map._popup && map._popup.options.autoClose) {
  8334. map.removeLayer(map._popup);
  8335. }
  8336. map._popup = this;
  8337. return DivOverlay.prototype.openOn.call(this, map);
  8338. },
  8339. onAdd: function (map) {
  8340. DivOverlay.prototype.onAdd.call(this, map);
  8341. // @namespace Map
  8342. // @section Popup events
  8343. // @event popupopen: PopupEvent
  8344. // Fired when a popup is opened in the map
  8345. map.fire('popupopen', {popup: this});
  8346. if (this._source) {
  8347. // @namespace Layer
  8348. // @section Popup events
  8349. // @event popupopen: PopupEvent
  8350. // Fired when a popup bound to this layer is opened
  8351. this._source.fire('popupopen', {popup: this}, true);
  8352. // For non-path layers, we toggle the popup when clicking
  8353. // again the layer, so prevent the map to reopen it.
  8354. if (!(this._source instanceof Path)) {
  8355. this._source.on('preclick', stopPropagation);
  8356. }
  8357. }
  8358. },
  8359. onRemove: function (map) {
  8360. DivOverlay.prototype.onRemove.call(this, map);
  8361. // @namespace Map
  8362. // @section Popup events
  8363. // @event popupclose: PopupEvent
  8364. // Fired when a popup in the map is closed
  8365. map.fire('popupclose', {popup: this});
  8366. if (this._source) {
  8367. // @namespace Layer
  8368. // @section Popup events
  8369. // @event popupclose: PopupEvent
  8370. // Fired when a popup bound to this layer is closed
  8371. this._source.fire('popupclose', {popup: this}, true);
  8372. if (!(this._source instanceof Path)) {
  8373. this._source.off('preclick', stopPropagation);
  8374. }
  8375. }
  8376. },
  8377. getEvents: function () {
  8378. var events = DivOverlay.prototype.getEvents.call(this);
  8379. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  8380. events.preclick = this.close;
  8381. }
  8382. if (this.options.keepInView) {
  8383. events.moveend = this._adjustPan;
  8384. }
  8385. return events;
  8386. },
  8387. _initLayout: function () {
  8388. var prefix = 'leaflet-popup',
  8389. container = this._container = create$1('div',
  8390. prefix + ' ' + (this.options.className || '') +
  8391. ' leaflet-zoom-animated');
  8392. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  8393. this._contentNode = create$1('div', prefix + '-content', wrapper);
  8394. disableClickPropagation(container);
  8395. disableScrollPropagation(this._contentNode);
  8396. on(container, 'contextmenu', stopPropagation);
  8397. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  8398. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  8399. if (this.options.closeButton) {
  8400. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  8401. closeButton.setAttribute('role', 'button'); // overrides the implicit role=link of <a> elements #7399
  8402. closeButton.setAttribute('aria-label', 'Close popup');
  8403. closeButton.href = '#close';
  8404. closeButton.innerHTML = '<span aria-hidden="true">&#215;</span>';
  8405. on(closeButton, 'click', function (ev) {
  8406. preventDefault(ev);
  8407. this.close();
  8408. }, this);
  8409. }
  8410. },
  8411. _updateLayout: function () {
  8412. var container = this._contentNode,
  8413. style = container.style;
  8414. style.width = '';
  8415. style.whiteSpace = 'nowrap';
  8416. var width = container.offsetWidth;
  8417. width = Math.min(width, this.options.maxWidth);
  8418. width = Math.max(width, this.options.minWidth);
  8419. style.width = (width + 1) + 'px';
  8420. style.whiteSpace = '';
  8421. style.height = '';
  8422. var height = container.offsetHeight,
  8423. maxHeight = this.options.maxHeight,
  8424. scrolledClass = 'leaflet-popup-scrolled';
  8425. if (maxHeight && height > maxHeight) {
  8426. style.height = maxHeight + 'px';
  8427. addClass(container, scrolledClass);
  8428. } else {
  8429. removeClass(container, scrolledClass);
  8430. }
  8431. this._containerWidth = this._container.offsetWidth;
  8432. },
  8433. _animateZoom: function (e) {
  8434. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  8435. anchor = this._getAnchor();
  8436. setPosition(this._container, pos.add(anchor));
  8437. },
  8438. _adjustPan: function (e) {
  8439. if (!this.options.autoPan) { return; }
  8440. if (this._map._panAnim) { this._map._panAnim.stop(); }
  8441. var map = this._map,
  8442. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  8443. containerHeight = this._container.offsetHeight + marginBottom,
  8444. containerWidth = this._containerWidth,
  8445. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  8446. layerPos._add(getPosition(this._container));
  8447. var containerPos = map.layerPointToContainerPoint(layerPos),
  8448. padding = toPoint(this.options.autoPanPadding),
  8449. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  8450. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  8451. size = map.getSize(),
  8452. dx = 0,
  8453. dy = 0;
  8454. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  8455. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  8456. }
  8457. if (containerPos.x - dx - paddingTL.x < 0) { // left
  8458. dx = containerPos.x - paddingTL.x;
  8459. }
  8460. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  8461. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  8462. }
  8463. if (containerPos.y - dy - paddingTL.y < 0) { // top
  8464. dy = containerPos.y - paddingTL.y;
  8465. }
  8466. // @namespace Map
  8467. // @section Popup events
  8468. // @event autopanstart: Event
  8469. // Fired when the map starts autopanning when opening a popup.
  8470. if (dx || dy) {
  8471. map
  8472. .fire('autopanstart')
  8473. .panBy([dx, dy], {animate: e && e.type === 'moveend'});
  8474. }
  8475. },
  8476. _getAnchor: function () {
  8477. // Where should we anchor the popup on the source layer?
  8478. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  8479. }
  8480. });
  8481. // @namespace Popup
  8482. // @factory L.popup(options?: Popup options, source?: Layer)
  8483. // 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.
  8484. // @alternative
  8485. // @factory L.popup(latlng: LatLng, options?: Popup options)
  8486. // Instantiates a `Popup` object given `latlng` where the popup will open and an optional `options` object that describes its appearance and location.
  8487. var popup = function (options, source) {
  8488. return new Popup(options, source);
  8489. };
  8490. /* @namespace Map
  8491. * @section Interaction Options
  8492. * @option closePopupOnClick: Boolean = true
  8493. * Set it to `false` if you don't want popups to close when user clicks the map.
  8494. */
  8495. Map.mergeOptions({
  8496. closePopupOnClick: true
  8497. });
  8498. // @namespace Map
  8499. // @section Methods for Layers and Controls
  8500. Map.include({
  8501. // @method openPopup(popup: Popup): this
  8502. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  8503. // @alternative
  8504. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  8505. // Creates a popup with the specified content and options and opens it in the given point on a map.
  8506. openPopup: function (popup, latlng, options) {
  8507. this._initOverlay(Popup, popup, latlng, options)
  8508. .openOn(this);
  8509. return this;
  8510. },
  8511. // @method closePopup(popup?: Popup): this
  8512. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  8513. closePopup: function (popup) {
  8514. popup = arguments.length ? popup : this._popup;
  8515. if (popup) {
  8516. popup.close();
  8517. }
  8518. return this;
  8519. }
  8520. });
  8521. /*
  8522. * @namespace Layer
  8523. * @section Popup methods example
  8524. *
  8525. * All layers share a set of methods convenient for binding popups to it.
  8526. *
  8527. * ```js
  8528. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  8529. * layer.openPopup();
  8530. * layer.closePopup();
  8531. * ```
  8532. *
  8533. * 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.
  8534. */
  8535. // @section Popup methods
  8536. Layer.include({
  8537. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  8538. // Binds a popup to the layer with the passed `content` and sets up the
  8539. // necessary event listeners. If a `Function` is passed it will receive
  8540. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8541. bindPopup: function (content, options) {
  8542. this._popup = this._initOverlay(Popup, this._popup, content, options);
  8543. if (!this._popupHandlersAdded) {
  8544. this.on({
  8545. click: this._openPopup,
  8546. keypress: this._onKeyPress,
  8547. remove: this.closePopup,
  8548. move: this._movePopup
  8549. });
  8550. this._popupHandlersAdded = true;
  8551. }
  8552. return this;
  8553. },
  8554. // @method unbindPopup(): this
  8555. // Removes the popup previously bound with `bindPopup`.
  8556. unbindPopup: function () {
  8557. if (this._popup) {
  8558. this.off({
  8559. click: this._openPopup,
  8560. keypress: this._onKeyPress,
  8561. remove: this.closePopup,
  8562. move: this._movePopup
  8563. });
  8564. this._popupHandlersAdded = false;
  8565. this._popup = null;
  8566. }
  8567. return this;
  8568. },
  8569. // @method openPopup(latlng?: LatLng): this
  8570. // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
  8571. openPopup: function (latlng) {
  8572. if (this._popup && this._popup._prepareOpen(latlng || this._latlng)) {
  8573. // open the popup on the map
  8574. this._popup.openOn(this._map);
  8575. }
  8576. return this;
  8577. },
  8578. // @method closePopup(): this
  8579. // Closes the popup bound to this layer if it is open.
  8580. closePopup: function () {
  8581. if (this._popup) {
  8582. this._popup.close();
  8583. }
  8584. return this;
  8585. },
  8586. // @method togglePopup(): this
  8587. // Opens or closes the popup bound to this layer depending on its current state.
  8588. togglePopup: function () {
  8589. if (this._popup) {
  8590. this._popup.toggle(this);
  8591. }
  8592. return this;
  8593. },
  8594. // @method isPopupOpen(): boolean
  8595. // Returns `true` if the popup bound to this layer is currently open.
  8596. isPopupOpen: function () {
  8597. return (this._popup ? this._popup.isOpen() : false);
  8598. },
  8599. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8600. // Sets the content of the popup bound to this layer.
  8601. setPopupContent: function (content) {
  8602. if (this._popup) {
  8603. this._popup.setContent(content);
  8604. }
  8605. return this;
  8606. },
  8607. // @method getPopup(): Popup
  8608. // Returns the popup bound to this layer.
  8609. getPopup: function () {
  8610. return this._popup;
  8611. },
  8612. _openPopup: function (e) {
  8613. if (!this._popup || !this._map) {
  8614. return;
  8615. }
  8616. // prevent map click
  8617. stop(e);
  8618. var target = e.layer || e.target;
  8619. if (this._popup._source === target && !(target instanceof Path)) {
  8620. // treat it like a marker and figure out
  8621. // if we should toggle it open/closed
  8622. if (this._map.hasLayer(this._popup)) {
  8623. this.closePopup();
  8624. } else {
  8625. this.openPopup(e.latlng);
  8626. }
  8627. return;
  8628. }
  8629. this._popup._source = target;
  8630. this.openPopup(e.latlng);
  8631. },
  8632. _movePopup: function (e) {
  8633. this._popup.setLatLng(e.latlng);
  8634. },
  8635. _onKeyPress: function (e) {
  8636. if (e.originalEvent.keyCode === 13) {
  8637. this._openPopup(e);
  8638. }
  8639. }
  8640. });
  8641. /*
  8642. * @class Tooltip
  8643. * @inherits DivOverlay
  8644. * @aka L.Tooltip
  8645. * Used to display small texts on top of map layers.
  8646. *
  8647. * @example
  8648. * If you want to just bind a tooltip to marker:
  8649. *
  8650. * ```js
  8651. * marker.bindTooltip("my tooltip text").openTooltip();
  8652. * ```
  8653. * Path overlays like polylines also have a `bindTooltip` method.
  8654. *
  8655. * A tooltip can be also standalone:
  8656. *
  8657. * ```js
  8658. * var tooltip = L.tooltip()
  8659. * .setLatLng(latlng)
  8660. * .setContent('Hello world!<br />This is a nice tooltip.')
  8661. * .addTo(map);
  8662. * ```
  8663. * or
  8664. * ```js
  8665. * var tooltip = L.tooltip(latlng, {content: 'Hello world!<br />This is a nice tooltip.'})
  8666. * .addTo(map);
  8667. * ```
  8668. *
  8669. *
  8670. * Note about tooltip offset. Leaflet takes two options in consideration
  8671. * for computing tooltip offsetting:
  8672. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8673. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8674. * move it to the bottom. Negatives will move to the left and top.
  8675. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8676. * should adapt this value if you use a custom icon.
  8677. */
  8678. // @namespace Tooltip
  8679. var Tooltip = DivOverlay.extend({
  8680. // @section
  8681. // @aka Tooltip options
  8682. options: {
  8683. // @option pane: String = 'tooltipPane'
  8684. // `Map pane` where the tooltip will be added.
  8685. pane: 'tooltipPane',
  8686. // @option offset: Point = Point(0, 0)
  8687. // Optional offset of the tooltip position.
  8688. offset: [0, 0],
  8689. // @option direction: String = 'auto'
  8690. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8691. // `top`, `bottom`, `center`, `auto`.
  8692. // `auto` will dynamically switch between `right` and `left` according to the tooltip
  8693. // position on the map.
  8694. direction: 'auto',
  8695. // @option permanent: Boolean = false
  8696. // Whether to open the tooltip permanently or only on mouseover.
  8697. permanent: false,
  8698. // @option sticky: Boolean = false
  8699. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8700. sticky: false,
  8701. // @option opacity: Number = 0.9
  8702. // Tooltip container opacity.
  8703. opacity: 0.9
  8704. },
  8705. onAdd: function (map) {
  8706. DivOverlay.prototype.onAdd.call(this, map);
  8707. this.setOpacity(this.options.opacity);
  8708. // @namespace Map
  8709. // @section Tooltip events
  8710. // @event tooltipopen: TooltipEvent
  8711. // Fired when a tooltip is opened in the map.
  8712. map.fire('tooltipopen', {tooltip: this});
  8713. if (this._source) {
  8714. this.addEventParent(this._source);
  8715. // @namespace Layer
  8716. // @section Tooltip events
  8717. // @event tooltipopen: TooltipEvent
  8718. // Fired when a tooltip bound to this layer is opened.
  8719. this._source.fire('tooltipopen', {tooltip: this}, true);
  8720. }
  8721. },
  8722. onRemove: function (map) {
  8723. DivOverlay.prototype.onRemove.call(this, map);
  8724. // @namespace Map
  8725. // @section Tooltip events
  8726. // @event tooltipclose: TooltipEvent
  8727. // Fired when a tooltip in the map is closed.
  8728. map.fire('tooltipclose', {tooltip: this});
  8729. if (this._source) {
  8730. this.removeEventParent(this._source);
  8731. // @namespace Layer
  8732. // @section Tooltip events
  8733. // @event tooltipclose: TooltipEvent
  8734. // Fired when a tooltip bound to this layer is closed.
  8735. this._source.fire('tooltipclose', {tooltip: this}, true);
  8736. }
  8737. },
  8738. getEvents: function () {
  8739. var events = DivOverlay.prototype.getEvents.call(this);
  8740. if (!this.options.permanent) {
  8741. events.preclick = this.close;
  8742. }
  8743. return events;
  8744. },
  8745. _initLayout: function () {
  8746. var prefix = 'leaflet-tooltip',
  8747. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8748. this._contentNode = this._container = create$1('div', className);
  8749. this._container.setAttribute('role', 'tooltip');
  8750. this._container.setAttribute('id', 'leaflet-tooltip-' + stamp(this));
  8751. },
  8752. _updateLayout: function () {},
  8753. _adjustPan: function () {},
  8754. _setPosition: function (pos) {
  8755. var subX, subY,
  8756. map = this._map,
  8757. container = this._container,
  8758. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8759. tooltipPoint = map.layerPointToContainerPoint(pos),
  8760. direction = this.options.direction,
  8761. tooltipWidth = container.offsetWidth,
  8762. tooltipHeight = container.offsetHeight,
  8763. offset = toPoint(this.options.offset),
  8764. anchor = this._getAnchor();
  8765. if (direction === 'top') {
  8766. subX = tooltipWidth / 2;
  8767. subY = tooltipHeight;
  8768. } else if (direction === 'bottom') {
  8769. subX = tooltipWidth / 2;
  8770. subY = 0;
  8771. } else if (direction === 'center') {
  8772. subX = tooltipWidth / 2;
  8773. subY = tooltipHeight / 2;
  8774. } else if (direction === 'right') {
  8775. subX = 0;
  8776. subY = tooltipHeight / 2;
  8777. } else if (direction === 'left') {
  8778. subX = tooltipWidth;
  8779. subY = tooltipHeight / 2;
  8780. } else if (tooltipPoint.x < centerPoint.x) {
  8781. direction = 'right';
  8782. subX = 0;
  8783. subY = tooltipHeight / 2;
  8784. } else {
  8785. direction = 'left';
  8786. subX = tooltipWidth + (offset.x + anchor.x) * 2;
  8787. subY = tooltipHeight / 2;
  8788. }
  8789. pos = pos.subtract(toPoint(subX, subY, true)).add(offset).add(anchor);
  8790. removeClass(container, 'leaflet-tooltip-right');
  8791. removeClass(container, 'leaflet-tooltip-left');
  8792. removeClass(container, 'leaflet-tooltip-top');
  8793. removeClass(container, 'leaflet-tooltip-bottom');
  8794. addClass(container, 'leaflet-tooltip-' + direction);
  8795. setPosition(container, pos);
  8796. },
  8797. _updatePosition: function () {
  8798. var pos = this._map.latLngToLayerPoint(this._latlng);
  8799. this._setPosition(pos);
  8800. },
  8801. setOpacity: function (opacity) {
  8802. this.options.opacity = opacity;
  8803. if (this._container) {
  8804. setOpacity(this._container, opacity);
  8805. }
  8806. },
  8807. _animateZoom: function (e) {
  8808. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8809. this._setPosition(pos);
  8810. },
  8811. _getAnchor: function () {
  8812. // Where should we anchor the tooltip on the source layer?
  8813. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8814. }
  8815. });
  8816. // @namespace Tooltip
  8817. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8818. // 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.
  8819. // @alternative
  8820. // @factory L.tooltip(latlng: LatLng, options?: Tooltip options)
  8821. // Instantiates a `Tooltip` object given `latlng` where the tooltip will open and an optional `options` object that describes its appearance and location.
  8822. var tooltip = function (options, source) {
  8823. return new Tooltip(options, source);
  8824. };
  8825. // @namespace Map
  8826. // @section Methods for Layers and Controls
  8827. Map.include({
  8828. // @method openTooltip(tooltip: Tooltip): this
  8829. // Opens the specified tooltip.
  8830. // @alternative
  8831. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8832. // Creates a tooltip with the specified content and options and open it.
  8833. openTooltip: function (tooltip, latlng, options) {
  8834. this._initOverlay(Tooltip, tooltip, latlng, options)
  8835. .openOn(this);
  8836. return this;
  8837. },
  8838. // @method closeTooltip(tooltip: Tooltip): this
  8839. // Closes the tooltip given as parameter.
  8840. closeTooltip: function (tooltip) {
  8841. tooltip.close();
  8842. return this;
  8843. }
  8844. });
  8845. /*
  8846. * @namespace Layer
  8847. * @section Tooltip methods example
  8848. *
  8849. * All layers share a set of methods convenient for binding tooltips to it.
  8850. *
  8851. * ```js
  8852. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8853. * layer.openTooltip();
  8854. * layer.closeTooltip();
  8855. * ```
  8856. */
  8857. // @section Tooltip methods
  8858. Layer.include({
  8859. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8860. // Binds a tooltip to the layer with the passed `content` and sets up the
  8861. // necessary event listeners. If a `Function` is passed it will receive
  8862. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8863. bindTooltip: function (content, options) {
  8864. if (this._tooltip && this.isTooltipOpen()) {
  8865. this.unbindTooltip();
  8866. }
  8867. this._tooltip = this._initOverlay(Tooltip, this._tooltip, content, options);
  8868. this._initTooltipInteractions();
  8869. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8870. this.openTooltip();
  8871. }
  8872. return this;
  8873. },
  8874. // @method unbindTooltip(): this
  8875. // Removes the tooltip previously bound with `bindTooltip`.
  8876. unbindTooltip: function () {
  8877. if (this._tooltip) {
  8878. this._initTooltipInteractions(true);
  8879. this.closeTooltip();
  8880. this._tooltip = null;
  8881. }
  8882. return this;
  8883. },
  8884. _initTooltipInteractions: function (remove) {
  8885. if (!remove && this._tooltipHandlersAdded) { return; }
  8886. var onOff = remove ? 'off' : 'on',
  8887. events = {
  8888. remove: this.closeTooltip,
  8889. move: this._moveTooltip
  8890. };
  8891. if (!this._tooltip.options.permanent) {
  8892. events.mouseover = this._openTooltip;
  8893. events.mouseout = this.closeTooltip;
  8894. events.click = this._openTooltip;
  8895. if (this._map) {
  8896. this._addFocusListeners();
  8897. } else {
  8898. events.add = this._addFocusListeners;
  8899. }
  8900. } else {
  8901. events.add = this._openTooltip;
  8902. }
  8903. if (this._tooltip.options.sticky) {
  8904. events.mousemove = this._moveTooltip;
  8905. }
  8906. this[onOff](events);
  8907. this._tooltipHandlersAdded = !remove;
  8908. },
  8909. // @method openTooltip(latlng?: LatLng): this
  8910. // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8911. openTooltip: function (latlng) {
  8912. if (this._tooltip && this._tooltip._prepareOpen(latlng)) {
  8913. // open the tooltip on the map
  8914. this._tooltip.openOn(this._map);
  8915. if (this.getElement) {
  8916. this._setAriaDescribedByOnLayer(this);
  8917. } else if (this.eachLayer) {
  8918. this.eachLayer(this._setAriaDescribedByOnLayer, this);
  8919. }
  8920. }
  8921. return this;
  8922. },
  8923. // @method closeTooltip(): this
  8924. // Closes the tooltip bound to this layer if it is open.
  8925. closeTooltip: function () {
  8926. if (this._tooltip) {
  8927. return this._tooltip.close();
  8928. }
  8929. },
  8930. // @method toggleTooltip(): this
  8931. // Opens or closes the tooltip bound to this layer depending on its current state.
  8932. toggleTooltip: function () {
  8933. if (this._tooltip) {
  8934. this._tooltip.toggle(this);
  8935. }
  8936. return this;
  8937. },
  8938. // @method isTooltipOpen(): boolean
  8939. // Returns `true` if the tooltip bound to this layer is currently open.
  8940. isTooltipOpen: function () {
  8941. return this._tooltip.isOpen();
  8942. },
  8943. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8944. // Sets the content of the tooltip bound to this layer.
  8945. setTooltipContent: function (content) {
  8946. if (this._tooltip) {
  8947. this._tooltip.setContent(content);
  8948. }
  8949. return this;
  8950. },
  8951. // @method getTooltip(): Tooltip
  8952. // Returns the tooltip bound to this layer.
  8953. getTooltip: function () {
  8954. return this._tooltip;
  8955. },
  8956. _addFocusListeners: function () {
  8957. if (this.getElement) {
  8958. this._addFocusListenersOnLayer(this);
  8959. } else if (this.eachLayer) {
  8960. this.eachLayer(this._addFocusListenersOnLayer, this);
  8961. }
  8962. },
  8963. _addFocusListenersOnLayer: function (layer) {
  8964. var el = layer.getElement();
  8965. if (el) {
  8966. on(el, 'focus', function () {
  8967. this._tooltip._source = layer;
  8968. this.openTooltip();
  8969. }, this);
  8970. on(el, 'blur', this.closeTooltip, this);
  8971. }
  8972. },
  8973. _setAriaDescribedByOnLayer: function (layer) {
  8974. var el = layer.getElement();
  8975. if (el) {
  8976. el.setAttribute('aria-describedby', this._tooltip._container.id);
  8977. }
  8978. },
  8979. _openTooltip: function (e) {
  8980. if (!this._tooltip || !this._map || (this._map.dragging && this._map.dragging.moving())) {
  8981. return;
  8982. }
  8983. this._tooltip._source = e.layer || e.target;
  8984. this.openTooltip(this._tooltip.options.sticky ? e.latlng : undefined);
  8985. },
  8986. _moveTooltip: function (e) {
  8987. var latlng = e.latlng, containerPoint, layerPoint;
  8988. if (this._tooltip.options.sticky && e.originalEvent) {
  8989. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  8990. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  8991. latlng = this._map.layerPointToLatLng(layerPoint);
  8992. }
  8993. this._tooltip.setLatLng(latlng);
  8994. }
  8995. });
  8996. /*
  8997. * @class DivIcon
  8998. * @aka L.DivIcon
  8999. * @inherits Icon
  9000. *
  9001. * Represents a lightweight icon for markers that uses a simple `<div>`
  9002. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  9003. *
  9004. * @example
  9005. * ```js
  9006. * var myIcon = L.divIcon({className: 'my-div-icon'});
  9007. * // you can set .my-div-icon styles in CSS
  9008. *
  9009. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  9010. * ```
  9011. *
  9012. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  9013. */
  9014. var DivIcon = Icon.extend({
  9015. options: {
  9016. // @section
  9017. // @aka DivIcon options
  9018. iconSize: [12, 12], // also can be set through CSS
  9019. // iconAnchor: (Point),
  9020. // popupAnchor: (Point),
  9021. // @option html: String|HTMLElement = ''
  9022. // Custom HTML code to put inside the div element, empty by default. Alternatively,
  9023. // an instance of `HTMLElement`.
  9024. html: false,
  9025. // @option bgPos: Point = [0, 0]
  9026. // Optional relative position of the background, in pixels
  9027. bgPos: null,
  9028. className: 'leaflet-div-icon'
  9029. },
  9030. createIcon: function (oldIcon) {
  9031. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  9032. options = this.options;
  9033. if (options.html instanceof Element) {
  9034. empty(div);
  9035. div.appendChild(options.html);
  9036. } else {
  9037. div.innerHTML = options.html !== false ? options.html : '';
  9038. }
  9039. if (options.bgPos) {
  9040. var bgPos = toPoint(options.bgPos);
  9041. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  9042. }
  9043. this._setIconStyles(div, 'icon');
  9044. return div;
  9045. },
  9046. createShadow: function () {
  9047. return null;
  9048. }
  9049. });
  9050. // @factory L.divIcon(options: DivIcon options)
  9051. // Creates a `DivIcon` instance with the given options.
  9052. function divIcon(options) {
  9053. return new DivIcon(options);
  9054. }
  9055. Icon.Default = IconDefault;
  9056. /*
  9057. * @class GridLayer
  9058. * @inherits Layer
  9059. * @aka L.GridLayer
  9060. *
  9061. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  9062. * 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.
  9063. *
  9064. *
  9065. * @section Synchronous usage
  9066. * @example
  9067. *
  9068. * 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.
  9069. *
  9070. * ```js
  9071. * var CanvasLayer = L.GridLayer.extend({
  9072. * createTile: function(coords){
  9073. * // create a <canvas> element for drawing
  9074. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  9075. *
  9076. * // setup tile width and height according to the options
  9077. * var size = this.getTileSize();
  9078. * tile.width = size.x;
  9079. * tile.height = size.y;
  9080. *
  9081. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  9082. * var ctx = tile.getContext('2d');
  9083. *
  9084. * // return the tile so it can be rendered on screen
  9085. * return tile;
  9086. * }
  9087. * });
  9088. * ```
  9089. *
  9090. * @section Asynchronous usage
  9091. * @example
  9092. *
  9093. * 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.
  9094. *
  9095. * ```js
  9096. * var CanvasLayer = L.GridLayer.extend({
  9097. * createTile: function(coords, done){
  9098. * var error;
  9099. *
  9100. * // create a <canvas> element for drawing
  9101. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  9102. *
  9103. * // setup tile width and height according to the options
  9104. * var size = this.getTileSize();
  9105. * tile.width = size.x;
  9106. * tile.height = size.y;
  9107. *
  9108. * // draw something asynchronously and pass the tile to the done() callback
  9109. * setTimeout(function() {
  9110. * done(error, tile);
  9111. * }, 1000);
  9112. *
  9113. * return tile;
  9114. * }
  9115. * });
  9116. * ```
  9117. *
  9118. * @section
  9119. */
  9120. var GridLayer = Layer.extend({
  9121. // @section
  9122. // @aka GridLayer options
  9123. options: {
  9124. // @option tileSize: Number|Point = 256
  9125. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  9126. tileSize: 256,
  9127. // @option opacity: Number = 1.0
  9128. // Opacity of the tiles. Can be used in the `createTile()` function.
  9129. opacity: 1,
  9130. // @option updateWhenIdle: Boolean = (depends)
  9131. // Load new tiles only when panning ends.
  9132. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  9133. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  9134. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  9135. updateWhenIdle: Browser.mobile,
  9136. // @option updateWhenZooming: Boolean = true
  9137. // 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.
  9138. updateWhenZooming: true,
  9139. // @option updateInterval: Number = 200
  9140. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  9141. updateInterval: 200,
  9142. // @option zIndex: Number = 1
  9143. // The explicit zIndex of the tile layer.
  9144. zIndex: 1,
  9145. // @option bounds: LatLngBounds = undefined
  9146. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  9147. bounds: null,
  9148. // @option minZoom: Number = 0
  9149. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9150. minZoom: 0,
  9151. // @option maxZoom: Number = undefined
  9152. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9153. maxZoom: undefined,
  9154. // @option maxNativeZoom: Number = undefined
  9155. // Maximum zoom number the tile source has available. If it is specified,
  9156. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  9157. // from `maxNativeZoom` level and auto-scaled.
  9158. maxNativeZoom: undefined,
  9159. // @option minNativeZoom: Number = undefined
  9160. // Minimum zoom number the tile source has available. If it is specified,
  9161. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  9162. // from `minNativeZoom` level and auto-scaled.
  9163. minNativeZoom: undefined,
  9164. // @option noWrap: Boolean = false
  9165. // Whether the layer is wrapped around the antimeridian. If `true`, the
  9166. // GridLayer will only be displayed once at low zoom levels. Has no
  9167. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  9168. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  9169. // tiles outside the CRS limits.
  9170. noWrap: false,
  9171. // @option pane: String = 'tilePane'
  9172. // `Map pane` where the grid layer will be added.
  9173. pane: 'tilePane',
  9174. // @option className: String = ''
  9175. // A custom class name to assign to the tile layer. Empty by default.
  9176. className: '',
  9177. // @option keepBuffer: Number = 2
  9178. // When panning the map, keep this many rows and columns of tiles before unloading them.
  9179. keepBuffer: 2
  9180. },
  9181. initialize: function (options) {
  9182. setOptions(this, options);
  9183. },
  9184. onAdd: function () {
  9185. this._initContainer();
  9186. this._levels = {};
  9187. this._tiles = {};
  9188. this._resetView(); // implicit _update() call
  9189. },
  9190. beforeAdd: function (map) {
  9191. map._addZoomLimit(this);
  9192. },
  9193. onRemove: function (map) {
  9194. this._removeAllTiles();
  9195. remove(this._container);
  9196. map._removeZoomLimit(this);
  9197. this._container = null;
  9198. this._tileZoom = undefined;
  9199. },
  9200. // @method bringToFront: this
  9201. // Brings the tile layer to the top of all tile layers.
  9202. bringToFront: function () {
  9203. if (this._map) {
  9204. toFront(this._container);
  9205. this._setAutoZIndex(Math.max);
  9206. }
  9207. return this;
  9208. },
  9209. // @method bringToBack: this
  9210. // Brings the tile layer to the bottom of all tile layers.
  9211. bringToBack: function () {
  9212. if (this._map) {
  9213. toBack(this._container);
  9214. this._setAutoZIndex(Math.min);
  9215. }
  9216. return this;
  9217. },
  9218. // @method getContainer: HTMLElement
  9219. // Returns the HTML element that contains the tiles for this layer.
  9220. getContainer: function () {
  9221. return this._container;
  9222. },
  9223. // @method setOpacity(opacity: Number): this
  9224. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  9225. setOpacity: function (opacity) {
  9226. this.options.opacity = opacity;
  9227. this._updateOpacity();
  9228. return this;
  9229. },
  9230. // @method setZIndex(zIndex: Number): this
  9231. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  9232. setZIndex: function (zIndex) {
  9233. this.options.zIndex = zIndex;
  9234. this._updateZIndex();
  9235. return this;
  9236. },
  9237. // @method isLoading: Boolean
  9238. // Returns `true` if any tile in the grid layer has not finished loading.
  9239. isLoading: function () {
  9240. return this._loading;
  9241. },
  9242. // @method redraw: this
  9243. // Causes the layer to clear all the tiles and request them again.
  9244. redraw: function () {
  9245. if (this._map) {
  9246. this._removeAllTiles();
  9247. var tileZoom = this._clampZoom(this._map.getZoom());
  9248. if (tileZoom !== this._tileZoom) {
  9249. this._tileZoom = tileZoom;
  9250. this._updateLevels();
  9251. }
  9252. this._update();
  9253. }
  9254. return this;
  9255. },
  9256. getEvents: function () {
  9257. var events = {
  9258. viewprereset: this._invalidateAll,
  9259. viewreset: this._resetView,
  9260. zoom: this._resetView,
  9261. moveend: this._onMoveEnd
  9262. };
  9263. if (!this.options.updateWhenIdle) {
  9264. // update tiles on move, but not more often than once per given interval
  9265. if (!this._onMove) {
  9266. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  9267. }
  9268. events.move = this._onMove;
  9269. }
  9270. if (this._zoomAnimated) {
  9271. events.zoomanim = this._animateZoom;
  9272. }
  9273. return events;
  9274. },
  9275. // @section Extension methods
  9276. // Layers extending `GridLayer` shall reimplement the following method.
  9277. // @method createTile(coords: Object, done?: Function): HTMLElement
  9278. // Called only internally, must be overridden by classes extending `GridLayer`.
  9279. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  9280. // is specified, it must be called when the tile has finished loading and drawing.
  9281. createTile: function () {
  9282. return document.createElement('div');
  9283. },
  9284. // @section
  9285. // @method getTileSize: Point
  9286. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  9287. getTileSize: function () {
  9288. var s = this.options.tileSize;
  9289. return s instanceof Point ? s : new Point(s, s);
  9290. },
  9291. _updateZIndex: function () {
  9292. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  9293. this._container.style.zIndex = this.options.zIndex;
  9294. }
  9295. },
  9296. _setAutoZIndex: function (compare) {
  9297. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  9298. var layers = this.getPane().children,
  9299. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  9300. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  9301. zIndex = layers[i].style.zIndex;
  9302. if (layers[i] !== this._container && zIndex) {
  9303. edgeZIndex = compare(edgeZIndex, +zIndex);
  9304. }
  9305. }
  9306. if (isFinite(edgeZIndex)) {
  9307. this.options.zIndex = edgeZIndex + compare(-1, 1);
  9308. this._updateZIndex();
  9309. }
  9310. },
  9311. _updateOpacity: function () {
  9312. if (!this._map) { return; }
  9313. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  9314. if (Browser.ielt9) { return; }
  9315. setOpacity(this._container, this.options.opacity);
  9316. var now = +new Date(),
  9317. nextFrame = false,
  9318. willPrune = false;
  9319. for (var key in this._tiles) {
  9320. var tile = this._tiles[key];
  9321. if (!tile.current || !tile.loaded) { continue; }
  9322. var fade = Math.min(1, (now - tile.loaded) / 200);
  9323. setOpacity(tile.el, fade);
  9324. if (fade < 1) {
  9325. nextFrame = true;
  9326. } else {
  9327. if (tile.active) {
  9328. willPrune = true;
  9329. } else {
  9330. this._onOpaqueTile(tile);
  9331. }
  9332. tile.active = true;
  9333. }
  9334. }
  9335. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  9336. if (nextFrame) {
  9337. cancelAnimFrame(this._fadeFrame);
  9338. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9339. }
  9340. },
  9341. _onOpaqueTile: falseFn,
  9342. _initContainer: function () {
  9343. if (this._container) { return; }
  9344. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  9345. this._updateZIndex();
  9346. if (this.options.opacity < 1) {
  9347. this._updateOpacity();
  9348. }
  9349. this.getPane().appendChild(this._container);
  9350. },
  9351. _updateLevels: function () {
  9352. var zoom = this._tileZoom,
  9353. maxZoom = this.options.maxZoom;
  9354. if (zoom === undefined) { return undefined; }
  9355. for (var z in this._levels) {
  9356. z = Number(z);
  9357. if (this._levels[z].el.children.length || z === zoom) {
  9358. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  9359. this._onUpdateLevel(z);
  9360. } else {
  9361. remove(this._levels[z].el);
  9362. this._removeTilesAtZoom(z);
  9363. this._onRemoveLevel(z);
  9364. delete this._levels[z];
  9365. }
  9366. }
  9367. var level = this._levels[zoom],
  9368. map = this._map;
  9369. if (!level) {
  9370. level = this._levels[zoom] = {};
  9371. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  9372. level.el.style.zIndex = maxZoom;
  9373. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  9374. level.zoom = zoom;
  9375. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  9376. // force the browser to consider the newly added element for transition
  9377. falseFn(level.el.offsetWidth);
  9378. this._onCreateLevel(level);
  9379. }
  9380. this._level = level;
  9381. return level;
  9382. },
  9383. _onUpdateLevel: falseFn,
  9384. _onRemoveLevel: falseFn,
  9385. _onCreateLevel: falseFn,
  9386. _pruneTiles: function () {
  9387. if (!this._map) {
  9388. return;
  9389. }
  9390. var key, tile;
  9391. var zoom = this._map.getZoom();
  9392. if (zoom > this.options.maxZoom ||
  9393. zoom < this.options.minZoom) {
  9394. this._removeAllTiles();
  9395. return;
  9396. }
  9397. for (key in this._tiles) {
  9398. tile = this._tiles[key];
  9399. tile.retain = tile.current;
  9400. }
  9401. for (key in this._tiles) {
  9402. tile = this._tiles[key];
  9403. if (tile.current && !tile.active) {
  9404. var coords = tile.coords;
  9405. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  9406. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  9407. }
  9408. }
  9409. }
  9410. for (key in this._tiles) {
  9411. if (!this._tiles[key].retain) {
  9412. this._removeTile(key);
  9413. }
  9414. }
  9415. },
  9416. _removeTilesAtZoom: function (zoom) {
  9417. for (var key in this._tiles) {
  9418. if (this._tiles[key].coords.z !== zoom) {
  9419. continue;
  9420. }
  9421. this._removeTile(key);
  9422. }
  9423. },
  9424. _removeAllTiles: function () {
  9425. for (var key in this._tiles) {
  9426. this._removeTile(key);
  9427. }
  9428. },
  9429. _invalidateAll: function () {
  9430. for (var z in this._levels) {
  9431. remove(this._levels[z].el);
  9432. this._onRemoveLevel(Number(z));
  9433. delete this._levels[z];
  9434. }
  9435. this._removeAllTiles();
  9436. this._tileZoom = undefined;
  9437. },
  9438. _retainParent: function (x, y, z, minZoom) {
  9439. var x2 = Math.floor(x / 2),
  9440. y2 = Math.floor(y / 2),
  9441. z2 = z - 1,
  9442. coords2 = new Point(+x2, +y2);
  9443. coords2.z = +z2;
  9444. var key = this._tileCoordsToKey(coords2),
  9445. tile = this._tiles[key];
  9446. if (tile && tile.active) {
  9447. tile.retain = true;
  9448. return true;
  9449. } else if (tile && tile.loaded) {
  9450. tile.retain = true;
  9451. }
  9452. if (z2 > minZoom) {
  9453. return this._retainParent(x2, y2, z2, minZoom);
  9454. }
  9455. return false;
  9456. },
  9457. _retainChildren: function (x, y, z, maxZoom) {
  9458. for (var i = 2 * x; i < 2 * x + 2; i++) {
  9459. for (var j = 2 * y; j < 2 * y + 2; j++) {
  9460. var coords = new Point(i, j);
  9461. coords.z = z + 1;
  9462. var key = this._tileCoordsToKey(coords),
  9463. tile = this._tiles[key];
  9464. if (tile && tile.active) {
  9465. tile.retain = true;
  9466. continue;
  9467. } else if (tile && tile.loaded) {
  9468. tile.retain = true;
  9469. }
  9470. if (z + 1 < maxZoom) {
  9471. this._retainChildren(i, j, z + 1, maxZoom);
  9472. }
  9473. }
  9474. }
  9475. },
  9476. _resetView: function (e) {
  9477. var animating = e && (e.pinch || e.flyTo);
  9478. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  9479. },
  9480. _animateZoom: function (e) {
  9481. this._setView(e.center, e.zoom, true, e.noUpdate);
  9482. },
  9483. _clampZoom: function (zoom) {
  9484. var options = this.options;
  9485. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  9486. return options.minNativeZoom;
  9487. }
  9488. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  9489. return options.maxNativeZoom;
  9490. }
  9491. return zoom;
  9492. },
  9493. _setView: function (center, zoom, noPrune, noUpdate) {
  9494. var tileZoom = Math.round(zoom);
  9495. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  9496. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  9497. tileZoom = undefined;
  9498. } else {
  9499. tileZoom = this._clampZoom(tileZoom);
  9500. }
  9501. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  9502. if (!noUpdate || tileZoomChanged) {
  9503. this._tileZoom = tileZoom;
  9504. if (this._abortLoading) {
  9505. this._abortLoading();
  9506. }
  9507. this._updateLevels();
  9508. this._resetGrid();
  9509. if (tileZoom !== undefined) {
  9510. this._update(center);
  9511. }
  9512. if (!noPrune) {
  9513. this._pruneTiles();
  9514. }
  9515. // Flag to prevent _updateOpacity from pruning tiles during
  9516. // a zoom anim or a pinch gesture
  9517. this._noPrune = !!noPrune;
  9518. }
  9519. this._setZoomTransforms(center, zoom);
  9520. },
  9521. _setZoomTransforms: function (center, zoom) {
  9522. for (var i in this._levels) {
  9523. this._setZoomTransform(this._levels[i], center, zoom);
  9524. }
  9525. },
  9526. _setZoomTransform: function (level, center, zoom) {
  9527. var scale = this._map.getZoomScale(zoom, level.zoom),
  9528. translate = level.origin.multiplyBy(scale)
  9529. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  9530. if (Browser.any3d) {
  9531. setTransform(level.el, translate, scale);
  9532. } else {
  9533. setPosition(level.el, translate);
  9534. }
  9535. },
  9536. _resetGrid: function () {
  9537. var map = this._map,
  9538. crs = map.options.crs,
  9539. tileSize = this._tileSize = this.getTileSize(),
  9540. tileZoom = this._tileZoom;
  9541. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  9542. if (bounds) {
  9543. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  9544. }
  9545. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  9546. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  9547. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  9548. ];
  9549. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  9550. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  9551. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  9552. ];
  9553. },
  9554. _onMoveEnd: function () {
  9555. if (!this._map || this._map._animatingZoom) { return; }
  9556. this._update();
  9557. },
  9558. _getTiledPixelBounds: function (center) {
  9559. var map = this._map,
  9560. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9561. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9562. pixelCenter = map.project(center, this._tileZoom).floor(),
  9563. halfSize = map.getSize().divideBy(scale * 2);
  9564. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9565. },
  9566. // Private method to load tiles in the grid's active zoom level according to map bounds
  9567. _update: function (center) {
  9568. var map = this._map;
  9569. if (!map) { return; }
  9570. var zoom = this._clampZoom(map.getZoom());
  9571. if (center === undefined) { center = map.getCenter(); }
  9572. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  9573. var pixelBounds = this._getTiledPixelBounds(center),
  9574. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9575. tileCenter = tileRange.getCenter(),
  9576. queue = [],
  9577. margin = this.options.keepBuffer,
  9578. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9579. tileRange.getTopRight().add([margin, -margin]));
  9580. // Sanity check: panic if the tile range contains Infinity somewhere.
  9581. if (!(isFinite(tileRange.min.x) &&
  9582. isFinite(tileRange.min.y) &&
  9583. isFinite(tileRange.max.x) &&
  9584. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  9585. for (var key in this._tiles) {
  9586. var c = this._tiles[key].coords;
  9587. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9588. this._tiles[key].current = false;
  9589. }
  9590. }
  9591. // _update just loads more tiles. If the tile zoom level differs too much
  9592. // from the map's, let _setView reset levels and prune old tiles.
  9593. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  9594. // create a queue of coordinates to load tiles from
  9595. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9596. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9597. var coords = new Point(i, j);
  9598. coords.z = this._tileZoom;
  9599. if (!this._isValidTile(coords)) { continue; }
  9600. var tile = this._tiles[this._tileCoordsToKey(coords)];
  9601. if (tile) {
  9602. tile.current = true;
  9603. } else {
  9604. queue.push(coords);
  9605. }
  9606. }
  9607. }
  9608. // sort tile queue to load tiles in order of their distance to center
  9609. queue.sort(function (a, b) {
  9610. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9611. });
  9612. if (queue.length !== 0) {
  9613. // if it's the first batch of tiles to load
  9614. if (!this._loading) {
  9615. this._loading = true;
  9616. // @event loading: Event
  9617. // Fired when the grid layer starts loading tiles.
  9618. this.fire('loading');
  9619. }
  9620. // create DOM fragment to append tiles in one batch
  9621. var fragment = document.createDocumentFragment();
  9622. for (i = 0; i < queue.length; i++) {
  9623. this._addTile(queue[i], fragment);
  9624. }
  9625. this._level.el.appendChild(fragment);
  9626. }
  9627. },
  9628. _isValidTile: function (coords) {
  9629. var crs = this._map.options.crs;
  9630. if (!crs.infinite) {
  9631. // don't load tile if it's out of bounds and not wrapped
  9632. var bounds = this._globalTileRange;
  9633. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9634. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  9635. }
  9636. if (!this.options.bounds) { return true; }
  9637. // don't load tile if it doesn't intersect the bounds in options
  9638. var tileBounds = this._tileCoordsToBounds(coords);
  9639. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9640. },
  9641. _keyToBounds: function (key) {
  9642. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9643. },
  9644. _tileCoordsToNwSe: function (coords) {
  9645. var map = this._map,
  9646. tileSize = this.getTileSize(),
  9647. nwPoint = coords.scaleBy(tileSize),
  9648. sePoint = nwPoint.add(tileSize),
  9649. nw = map.unproject(nwPoint, coords.z),
  9650. se = map.unproject(sePoint, coords.z);
  9651. return [nw, se];
  9652. },
  9653. // converts tile coordinates to its geographical bounds
  9654. _tileCoordsToBounds: function (coords) {
  9655. var bp = this._tileCoordsToNwSe(coords),
  9656. bounds = new LatLngBounds(bp[0], bp[1]);
  9657. if (!this.options.noWrap) {
  9658. bounds = this._map.wrapLatLngBounds(bounds);
  9659. }
  9660. return bounds;
  9661. },
  9662. // converts tile coordinates to key for the tile cache
  9663. _tileCoordsToKey: function (coords) {
  9664. return coords.x + ':' + coords.y + ':' + coords.z;
  9665. },
  9666. // converts tile cache key to coordinates
  9667. _keyToTileCoords: function (key) {
  9668. var k = key.split(':'),
  9669. coords = new Point(+k[0], +k[1]);
  9670. coords.z = +k[2];
  9671. return coords;
  9672. },
  9673. _removeTile: function (key) {
  9674. var tile = this._tiles[key];
  9675. if (!tile) { return; }
  9676. remove(tile.el);
  9677. delete this._tiles[key];
  9678. // @event tileunload: TileEvent
  9679. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9680. this.fire('tileunload', {
  9681. tile: tile.el,
  9682. coords: this._keyToTileCoords(key)
  9683. });
  9684. },
  9685. _initTile: function (tile) {
  9686. addClass(tile, 'leaflet-tile');
  9687. var tileSize = this.getTileSize();
  9688. tile.style.width = tileSize.x + 'px';
  9689. tile.style.height = tileSize.y + 'px';
  9690. tile.onselectstart = falseFn;
  9691. tile.onmousemove = falseFn;
  9692. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9693. if (Browser.ielt9 && this.options.opacity < 1) {
  9694. setOpacity(tile, this.options.opacity);
  9695. }
  9696. },
  9697. _addTile: function (coords, container) {
  9698. var tilePos = this._getTilePos(coords),
  9699. key = this._tileCoordsToKey(coords);
  9700. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9701. this._initTile(tile);
  9702. // if createTile is defined with a second argument ("done" callback),
  9703. // we know that tile is async and will be ready later; otherwise
  9704. if (this.createTile.length < 2) {
  9705. // mark tile as ready, but delay one frame for opacity animation to happen
  9706. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9707. }
  9708. setPosition(tile, tilePos);
  9709. // save tile in cache
  9710. this._tiles[key] = {
  9711. el: tile,
  9712. coords: coords,
  9713. current: true
  9714. };
  9715. container.appendChild(tile);
  9716. // @event tileloadstart: TileEvent
  9717. // Fired when a tile is requested and starts loading.
  9718. this.fire('tileloadstart', {
  9719. tile: tile,
  9720. coords: coords
  9721. });
  9722. },
  9723. _tileReady: function (coords, err, tile) {
  9724. if (err) {
  9725. // @event tileerror: TileErrorEvent
  9726. // Fired when there is an error loading a tile.
  9727. this.fire('tileerror', {
  9728. error: err,
  9729. tile: tile,
  9730. coords: coords
  9731. });
  9732. }
  9733. var key = this._tileCoordsToKey(coords);
  9734. tile = this._tiles[key];
  9735. if (!tile) { return; }
  9736. tile.loaded = +new Date();
  9737. if (this._map._fadeAnimated) {
  9738. setOpacity(tile.el, 0);
  9739. cancelAnimFrame(this._fadeFrame);
  9740. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9741. } else {
  9742. tile.active = true;
  9743. this._pruneTiles();
  9744. }
  9745. if (!err) {
  9746. addClass(tile.el, 'leaflet-tile-loaded');
  9747. // @event tileload: TileEvent
  9748. // Fired when a tile loads.
  9749. this.fire('tileload', {
  9750. tile: tile.el,
  9751. coords: coords
  9752. });
  9753. }
  9754. if (this._noTilesToLoad()) {
  9755. this._loading = false;
  9756. // @event load: Event
  9757. // Fired when the grid layer loaded all visible tiles.
  9758. this.fire('load');
  9759. if (Browser.ielt9 || !this._map._fadeAnimated) {
  9760. requestAnimFrame(this._pruneTiles, this);
  9761. } else {
  9762. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9763. // to trigger a pruning.
  9764. setTimeout(bind(this._pruneTiles, this), 250);
  9765. }
  9766. }
  9767. },
  9768. _getTilePos: function (coords) {
  9769. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9770. },
  9771. _wrapCoords: function (coords) {
  9772. var newCoords = new Point(
  9773. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9774. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9775. newCoords.z = coords.z;
  9776. return newCoords;
  9777. },
  9778. _pxBoundsToTileRange: function (bounds) {
  9779. var tileSize = this.getTileSize();
  9780. return new Bounds(
  9781. bounds.min.unscaleBy(tileSize).floor(),
  9782. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9783. },
  9784. _noTilesToLoad: function () {
  9785. for (var key in this._tiles) {
  9786. if (!this._tiles[key].loaded) { return false; }
  9787. }
  9788. return true;
  9789. }
  9790. });
  9791. // @factory L.gridLayer(options?: GridLayer options)
  9792. // Creates a new instance of GridLayer with the supplied options.
  9793. function gridLayer(options) {
  9794. return new GridLayer(options);
  9795. }
  9796. /*
  9797. * @class TileLayer
  9798. * @inherits GridLayer
  9799. * @aka L.TileLayer
  9800. * Used to load and display tile layers on the map. Note that most tile servers require attribution, which you can set under `Layer`. Extends `GridLayer`.
  9801. *
  9802. * @example
  9803. *
  9804. * ```js
  9805. * L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);
  9806. * ```
  9807. *
  9808. * @section URL template
  9809. * @example
  9810. *
  9811. * A string of the following form:
  9812. *
  9813. * ```
  9814. * 'https://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9815. * ```
  9816. *
  9817. * `{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.
  9818. *
  9819. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9820. *
  9821. * ```
  9822. * L.tileLayer('https://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9823. * ```
  9824. */
  9825. var TileLayer = GridLayer.extend({
  9826. // @section
  9827. // @aka TileLayer options
  9828. options: {
  9829. // @option minZoom: Number = 0
  9830. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9831. minZoom: 0,
  9832. // @option maxZoom: Number = 18
  9833. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9834. maxZoom: 18,
  9835. // @option subdomains: String|String[] = 'abc'
  9836. // 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.
  9837. subdomains: 'abc',
  9838. // @option errorTileUrl: String = ''
  9839. // URL to the tile image to show in place of the tile that failed to load.
  9840. errorTileUrl: '',
  9841. // @option zoomOffset: Number = 0
  9842. // The zoom number used in tile URLs will be offset with this value.
  9843. zoomOffset: 0,
  9844. // @option tms: Boolean = false
  9845. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9846. tms: false,
  9847. // @option zoomReverse: Boolean = false
  9848. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9849. zoomReverse: false,
  9850. // @option detectRetina: Boolean = false
  9851. // 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.
  9852. detectRetina: false,
  9853. // @option crossOrigin: Boolean|String = false
  9854. // Whether the crossOrigin attribute will be added to the tiles.
  9855. // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
  9856. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  9857. crossOrigin: false,
  9858. // @option referrerPolicy: Boolean|String = false
  9859. // Whether the referrerPolicy attribute will be added to the tiles.
  9860. // If a String is provided, all tiles will have their referrerPolicy attribute set to the String provided.
  9861. // This may be needed if your map's rendering context has a strict default but your tile provider expects a valid referrer
  9862. // (e.g. to validate an API token).
  9863. // Refer to [HTMLImageElement.referrerPolicy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/referrerPolicy) for valid String values.
  9864. referrerPolicy: false
  9865. },
  9866. initialize: function (url, options) {
  9867. this._url = url;
  9868. options = setOptions(this, options);
  9869. // detecting retina displays, adjusting tileSize and zoom levels
  9870. if (options.detectRetina && Browser.retina && options.maxZoom > 0) {
  9871. options.tileSize = Math.floor(options.tileSize / 2);
  9872. if (!options.zoomReverse) {
  9873. options.zoomOffset++;
  9874. options.maxZoom = Math.max(options.minZoom, options.maxZoom - 1);
  9875. } else {
  9876. options.zoomOffset--;
  9877. options.minZoom = Math.min(options.maxZoom, options.minZoom + 1);
  9878. }
  9879. options.minZoom = Math.max(0, options.minZoom);
  9880. } else if (!options.zoomReverse) {
  9881. // make sure maxZoom is gte minZoom
  9882. options.maxZoom = Math.max(options.minZoom, options.maxZoom);
  9883. } else {
  9884. // make sure minZoom is lte maxZoom
  9885. options.minZoom = Math.min(options.maxZoom, options.minZoom);
  9886. }
  9887. if (typeof options.subdomains === 'string') {
  9888. options.subdomains = options.subdomains.split('');
  9889. }
  9890. this.on('tileunload', this._onTileRemove);
  9891. },
  9892. // @method setUrl(url: String, noRedraw?: Boolean): this
  9893. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9894. // If the URL does not change, the layer will not be redrawn unless
  9895. // the noRedraw parameter is set to false.
  9896. setUrl: function (url, noRedraw) {
  9897. if (this._url === url && noRedraw === undefined) {
  9898. noRedraw = true;
  9899. }
  9900. this._url = url;
  9901. if (!noRedraw) {
  9902. this.redraw();
  9903. }
  9904. return this;
  9905. },
  9906. // @method createTile(coords: Object, done?: Function): HTMLElement
  9907. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9908. // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
  9909. // callback is called when the tile has been loaded.
  9910. createTile: function (coords, done) {
  9911. var tile = document.createElement('img');
  9912. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9913. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9914. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  9915. tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  9916. }
  9917. // for this new option we follow the documented behavior
  9918. // more closely by only setting the property when string
  9919. if (typeof this.options.referrerPolicy === 'string') {
  9920. tile.referrerPolicy = this.options.referrerPolicy;
  9921. }
  9922. // The alt attribute is set to the empty string,
  9923. // allowing screen readers to ignore the decorative image tiles.
  9924. // https://www.w3.org/WAI/tutorials/images/decorative/
  9925. // https://www.w3.org/TR/html-aria/#el-img-empty-alt
  9926. tile.alt = '';
  9927. tile.src = this.getTileUrl(coords);
  9928. return tile;
  9929. },
  9930. // @section Extension methods
  9931. // @uninheritable
  9932. // Layers extending `TileLayer` might reimplement the following method.
  9933. // @method getTileUrl(coords: Object): String
  9934. // Called only internally, returns the URL for a tile given its coordinates.
  9935. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9936. getTileUrl: function (coords) {
  9937. var data = {
  9938. r: Browser.retina ? '@2x' : '',
  9939. s: this._getSubdomain(coords),
  9940. x: coords.x,
  9941. y: coords.y,
  9942. z: this._getZoomForUrl()
  9943. };
  9944. if (this._map && !this._map.options.crs.infinite) {
  9945. var invertedY = this._globalTileRange.max.y - coords.y;
  9946. if (this.options.tms) {
  9947. data['y'] = invertedY;
  9948. }
  9949. data['-y'] = invertedY;
  9950. }
  9951. return template(this._url, extend(data, this.options));
  9952. },
  9953. _tileOnLoad: function (done, tile) {
  9954. // For https://github.com/Leaflet/Leaflet/issues/3332
  9955. if (Browser.ielt9) {
  9956. setTimeout(bind(done, this, null, tile), 0);
  9957. } else {
  9958. done(null, tile);
  9959. }
  9960. },
  9961. _tileOnError: function (done, tile, e) {
  9962. var errorUrl = this.options.errorTileUrl;
  9963. if (errorUrl && tile.getAttribute('src') !== errorUrl) {
  9964. tile.src = errorUrl;
  9965. }
  9966. done(e, tile);
  9967. },
  9968. _onTileRemove: function (e) {
  9969. e.tile.onload = null;
  9970. },
  9971. _getZoomForUrl: function () {
  9972. var zoom = this._tileZoom,
  9973. maxZoom = this.options.maxZoom,
  9974. zoomReverse = this.options.zoomReverse,
  9975. zoomOffset = this.options.zoomOffset;
  9976. if (zoomReverse) {
  9977. zoom = maxZoom - zoom;
  9978. }
  9979. return zoom + zoomOffset;
  9980. },
  9981. _getSubdomain: function (tilePoint) {
  9982. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  9983. return this.options.subdomains[index];
  9984. },
  9985. // stops loading all tiles in the background layer
  9986. _abortLoading: function () {
  9987. var i, tile;
  9988. for (i in this._tiles) {
  9989. if (this._tiles[i].coords.z !== this._tileZoom) {
  9990. tile = this._tiles[i].el;
  9991. tile.onload = falseFn;
  9992. tile.onerror = falseFn;
  9993. if (!tile.complete) {
  9994. tile.src = emptyImageUrl;
  9995. var coords = this._tiles[i].coords;
  9996. remove(tile);
  9997. delete this._tiles[i];
  9998. // @event tileabort: TileEvent
  9999. // Fired when a tile was loading but is now not wanted.
  10000. this.fire('tileabort', {
  10001. tile: tile,
  10002. coords: coords
  10003. });
  10004. }
  10005. }
  10006. }
  10007. },
  10008. _removeTile: function (key) {
  10009. var tile = this._tiles[key];
  10010. if (!tile) { return; }
  10011. // Cancels any pending http requests associated with the tile
  10012. tile.el.setAttribute('src', emptyImageUrl);
  10013. return GridLayer.prototype._removeTile.call(this, key);
  10014. },
  10015. _tileReady: function (coords, err, tile) {
  10016. if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) {
  10017. return;
  10018. }
  10019. return GridLayer.prototype._tileReady.call(this, coords, err, tile);
  10020. }
  10021. });
  10022. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  10023. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  10024. function tileLayer(url, options) {
  10025. return new TileLayer(url, options);
  10026. }
  10027. /*
  10028. * @class TileLayer.WMS
  10029. * @inherits TileLayer
  10030. * @aka L.TileLayer.WMS
  10031. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  10032. *
  10033. * @example
  10034. *
  10035. * ```js
  10036. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  10037. * layers: 'nexrad-n0r-900913',
  10038. * format: 'image/png',
  10039. * transparent: true,
  10040. * attribution: "Weather data © 2012 IEM Nexrad"
  10041. * });
  10042. * ```
  10043. */
  10044. var TileLayerWMS = TileLayer.extend({
  10045. // @section
  10046. // @aka TileLayer.WMS options
  10047. // If any custom options not documented here are used, they will be sent to the
  10048. // WMS server as extra parameters in each request URL. This can be useful for
  10049. // [non-standard vendor WMS parameters](https://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  10050. defaultWmsParams: {
  10051. service: 'WMS',
  10052. request: 'GetMap',
  10053. // @option layers: String = ''
  10054. // **(required)** Comma-separated list of WMS layers to show.
  10055. layers: '',
  10056. // @option styles: String = ''
  10057. // Comma-separated list of WMS styles.
  10058. styles: '',
  10059. // @option format: String = 'image/jpeg'
  10060. // WMS image format (use `'image/png'` for layers with transparency).
  10061. format: 'image/jpeg',
  10062. // @option transparent: Boolean = false
  10063. // If `true`, the WMS service will return images with transparency.
  10064. transparent: false,
  10065. // @option version: String = '1.1.1'
  10066. // Version of the WMS service to use
  10067. version: '1.1.1'
  10068. },
  10069. options: {
  10070. // @option crs: CRS = null
  10071. // Coordinate Reference System to use for the WMS requests, defaults to
  10072. // map CRS. Don't change this if you're not sure what it means.
  10073. crs: null,
  10074. // @option uppercase: Boolean = false
  10075. // If `true`, WMS request parameter keys will be uppercase.
  10076. uppercase: false
  10077. },
  10078. initialize: function (url, options) {
  10079. this._url = url;
  10080. var wmsParams = extend({}, this.defaultWmsParams);
  10081. // all keys that are not TileLayer options go to WMS params
  10082. for (var i in options) {
  10083. if (!(i in this.options)) {
  10084. wmsParams[i] = options[i];
  10085. }
  10086. }
  10087. options = setOptions(this, options);
  10088. var realRetina = options.detectRetina && Browser.retina ? 2 : 1;
  10089. var tileSize = this.getTileSize();
  10090. wmsParams.width = tileSize.x * realRetina;
  10091. wmsParams.height = tileSize.y * realRetina;
  10092. this.wmsParams = wmsParams;
  10093. },
  10094. onAdd: function (map) {
  10095. this._crs = this.options.crs || map.options.crs;
  10096. this._wmsVersion = parseFloat(this.wmsParams.version);
  10097. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  10098. this.wmsParams[projectionKey] = this._crs.code;
  10099. TileLayer.prototype.onAdd.call(this, map);
  10100. },
  10101. getTileUrl: function (coords) {
  10102. var tileBounds = this._tileCoordsToNwSe(coords),
  10103. crs = this._crs,
  10104. bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
  10105. min = bounds.min,
  10106. max = bounds.max,
  10107. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  10108. [min.y, min.x, max.y, max.x] :
  10109. [min.x, min.y, max.x, max.y]).join(','),
  10110. url = TileLayer.prototype.getTileUrl.call(this, coords);
  10111. return url +
  10112. getParamString(this.wmsParams, url, this.options.uppercase) +
  10113. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  10114. },
  10115. // @method setParams(params: Object, noRedraw?: Boolean): this
  10116. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  10117. setParams: function (params, noRedraw) {
  10118. extend(this.wmsParams, params);
  10119. if (!noRedraw) {
  10120. this.redraw();
  10121. }
  10122. return this;
  10123. }
  10124. });
  10125. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  10126. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  10127. function tileLayerWMS(url, options) {
  10128. return new TileLayerWMS(url, options);
  10129. }
  10130. TileLayer.WMS = TileLayerWMS;
  10131. tileLayer.wms = tileLayerWMS;
  10132. /*
  10133. * @class Renderer
  10134. * @inherits Layer
  10135. * @aka L.Renderer
  10136. *
  10137. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  10138. * DOM container of the renderer, its bounds, and its zoom animation.
  10139. *
  10140. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  10141. * itself can be added or removed to the map. All paths use a renderer, which can
  10142. * be implicit (the map will decide the type of renderer and use it automatically)
  10143. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  10144. *
  10145. * Do not use this class directly, use `SVG` and `Canvas` instead.
  10146. *
  10147. * @event update: Event
  10148. * Fired when the renderer updates its bounds, center and zoom, for example when
  10149. * its map has moved
  10150. */
  10151. var Renderer = Layer.extend({
  10152. // @section
  10153. // @aka Renderer options
  10154. options: {
  10155. // @option padding: Number = 0.1
  10156. // How much to extend the clip area around the map view (relative to its size)
  10157. // e.g. 0.1 would be 10% of map view in each direction
  10158. padding: 0.1
  10159. },
  10160. initialize: function (options) {
  10161. setOptions(this, options);
  10162. stamp(this);
  10163. this._layers = this._layers || {};
  10164. },
  10165. onAdd: function () {
  10166. if (!this._container) {
  10167. this._initContainer(); // defined by renderer implementations
  10168. if (this._zoomAnimated) {
  10169. addClass(this._container, 'leaflet-zoom-animated');
  10170. }
  10171. }
  10172. this.getPane().appendChild(this._container);
  10173. this._update();
  10174. this.on('update', this._updatePaths, this);
  10175. },
  10176. onRemove: function () {
  10177. this.off('update', this._updatePaths, this);
  10178. this._destroyContainer();
  10179. },
  10180. getEvents: function () {
  10181. var events = {
  10182. viewreset: this._reset,
  10183. zoom: this._onZoom,
  10184. moveend: this._update,
  10185. zoomend: this._onZoomEnd
  10186. };
  10187. if (this._zoomAnimated) {
  10188. events.zoomanim = this._onAnimZoom;
  10189. }
  10190. return events;
  10191. },
  10192. _onAnimZoom: function (ev) {
  10193. this._updateTransform(ev.center, ev.zoom);
  10194. },
  10195. _onZoom: function () {
  10196. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  10197. },
  10198. _updateTransform: function (center, zoom) {
  10199. var scale = this._map.getZoomScale(zoom, this._zoom),
  10200. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  10201. currentCenterPoint = this._map.project(this._center, zoom),
  10202. topLeftOffset = viewHalf.multiplyBy(-scale).add(currentCenterPoint)
  10203. .subtract(this._map._getNewPixelOrigin(center, zoom));
  10204. if (Browser.any3d) {
  10205. setTransform(this._container, topLeftOffset, scale);
  10206. } else {
  10207. setPosition(this._container, topLeftOffset);
  10208. }
  10209. },
  10210. _reset: function () {
  10211. this._update();
  10212. this._updateTransform(this._center, this._zoom);
  10213. for (var id in this._layers) {
  10214. this._layers[id]._reset();
  10215. }
  10216. },
  10217. _onZoomEnd: function () {
  10218. for (var id in this._layers) {
  10219. this._layers[id]._project();
  10220. }
  10221. },
  10222. _updatePaths: function () {
  10223. for (var id in this._layers) {
  10224. this._layers[id]._update();
  10225. }
  10226. },
  10227. _update: function () {
  10228. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  10229. // Subclasses are responsible of firing the 'update' event.
  10230. var p = this.options.padding,
  10231. size = this._map.getSize(),
  10232. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  10233. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  10234. this._center = this._map.getCenter();
  10235. this._zoom = this._map.getZoom();
  10236. }
  10237. });
  10238. /*
  10239. * @class Canvas
  10240. * @inherits Renderer
  10241. * @aka L.Canvas
  10242. *
  10243. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  10244. * Inherits `Renderer`.
  10245. *
  10246. * Due to [technical limitations](https://caniuse.com/canvas), Canvas is not
  10247. * available in all web browsers, notably IE8, and overlapping geometries might
  10248. * not display properly in some edge cases.
  10249. *
  10250. * @example
  10251. *
  10252. * Use Canvas by default for all paths in the map:
  10253. *
  10254. * ```js
  10255. * var map = L.map('map', {
  10256. * renderer: L.canvas()
  10257. * });
  10258. * ```
  10259. *
  10260. * Use a Canvas renderer with extra padding for specific vector geometries:
  10261. *
  10262. * ```js
  10263. * var map = L.map('map');
  10264. * var myRenderer = L.canvas({ padding: 0.5 });
  10265. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10266. * var circle = L.circle( center, { renderer: myRenderer } );
  10267. * ```
  10268. */
  10269. var Canvas = Renderer.extend({
  10270. // @section
  10271. // @aka Canvas options
  10272. options: {
  10273. // @option tolerance: Number = 0
  10274. // How much to extend the click tolerance around a path/object on the map.
  10275. tolerance: 0
  10276. },
  10277. getEvents: function () {
  10278. var events = Renderer.prototype.getEvents.call(this);
  10279. events.viewprereset = this._onViewPreReset;
  10280. return events;
  10281. },
  10282. _onViewPreReset: function () {
  10283. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  10284. this._postponeUpdatePaths = true;
  10285. },
  10286. onAdd: function () {
  10287. Renderer.prototype.onAdd.call(this);
  10288. // Redraw vectors since canvas is cleared upon removal,
  10289. // in case of removing the renderer itself from the map.
  10290. this._draw();
  10291. },
  10292. _initContainer: function () {
  10293. var container = this._container = document.createElement('canvas');
  10294. on(container, 'mousemove', this._onMouseMove, this);
  10295. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  10296. on(container, 'mouseout', this._handleMouseOut, this);
  10297. container['_leaflet_disable_events'] = true;
  10298. this._ctx = container.getContext('2d');
  10299. },
  10300. _destroyContainer: function () {
  10301. cancelAnimFrame(this._redrawRequest);
  10302. delete this._ctx;
  10303. remove(this._container);
  10304. off(this._container);
  10305. delete this._container;
  10306. },
  10307. _updatePaths: function () {
  10308. if (this._postponeUpdatePaths) { return; }
  10309. var layer;
  10310. this._redrawBounds = null;
  10311. for (var id in this._layers) {
  10312. layer = this._layers[id];
  10313. layer._update();
  10314. }
  10315. this._redraw();
  10316. },
  10317. _update: function () {
  10318. if (this._map._animatingZoom && this._bounds) { return; }
  10319. Renderer.prototype._update.call(this);
  10320. var b = this._bounds,
  10321. container = this._container,
  10322. size = b.getSize(),
  10323. m = Browser.retina ? 2 : 1;
  10324. setPosition(container, b.min);
  10325. // set canvas size (also clearing it); use double size on retina
  10326. container.width = m * size.x;
  10327. container.height = m * size.y;
  10328. container.style.width = size.x + 'px';
  10329. container.style.height = size.y + 'px';
  10330. if (Browser.retina) {
  10331. this._ctx.scale(2, 2);
  10332. }
  10333. // translate so we use the same path coordinates after canvas element moves
  10334. this._ctx.translate(-b.min.x, -b.min.y);
  10335. // Tell paths to redraw themselves
  10336. this.fire('update');
  10337. },
  10338. _reset: function () {
  10339. Renderer.prototype._reset.call(this);
  10340. if (this._postponeUpdatePaths) {
  10341. this._postponeUpdatePaths = false;
  10342. this._updatePaths();
  10343. }
  10344. },
  10345. _initPath: function (layer) {
  10346. this._updateDashArray(layer);
  10347. this._layers[stamp(layer)] = layer;
  10348. var order = layer._order = {
  10349. layer: layer,
  10350. prev: this._drawLast,
  10351. next: null
  10352. };
  10353. if (this._drawLast) { this._drawLast.next = order; }
  10354. this._drawLast = order;
  10355. this._drawFirst = this._drawFirst || this._drawLast;
  10356. },
  10357. _addPath: function (layer) {
  10358. this._requestRedraw(layer);
  10359. },
  10360. _removePath: function (layer) {
  10361. var order = layer._order;
  10362. var next = order.next;
  10363. var prev = order.prev;
  10364. if (next) {
  10365. next.prev = prev;
  10366. } else {
  10367. this._drawLast = prev;
  10368. }
  10369. if (prev) {
  10370. prev.next = next;
  10371. } else {
  10372. this._drawFirst = next;
  10373. }
  10374. delete layer._order;
  10375. delete this._layers[stamp(layer)];
  10376. this._requestRedraw(layer);
  10377. },
  10378. _updatePath: function (layer) {
  10379. // Redraw the union of the layer's old pixel
  10380. // bounds and the new pixel bounds.
  10381. this._extendRedrawBounds(layer);
  10382. layer._project();
  10383. layer._update();
  10384. // The redraw will extend the redraw bounds
  10385. // with the new pixel bounds.
  10386. this._requestRedraw(layer);
  10387. },
  10388. _updateStyle: function (layer) {
  10389. this._updateDashArray(layer);
  10390. this._requestRedraw(layer);
  10391. },
  10392. _updateDashArray: function (layer) {
  10393. if (typeof layer.options.dashArray === 'string') {
  10394. var parts = layer.options.dashArray.split(/[, ]+/),
  10395. dashArray = [],
  10396. dashValue,
  10397. i;
  10398. for (i = 0; i < parts.length; i++) {
  10399. dashValue = Number(parts[i]);
  10400. // Ignore dash array containing invalid lengths
  10401. if (isNaN(dashValue)) { return; }
  10402. dashArray.push(dashValue);
  10403. }
  10404. layer.options._dashArray = dashArray;
  10405. } else {
  10406. layer.options._dashArray = layer.options.dashArray;
  10407. }
  10408. },
  10409. _requestRedraw: function (layer) {
  10410. if (!this._map) { return; }
  10411. this._extendRedrawBounds(layer);
  10412. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  10413. },
  10414. _extendRedrawBounds: function (layer) {
  10415. if (layer._pxBounds) {
  10416. var padding = (layer.options.weight || 0) + 1;
  10417. this._redrawBounds = this._redrawBounds || new Bounds();
  10418. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  10419. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  10420. }
  10421. },
  10422. _redraw: function () {
  10423. this._redrawRequest = null;
  10424. if (this._redrawBounds) {
  10425. this._redrawBounds.min._floor();
  10426. this._redrawBounds.max._ceil();
  10427. }
  10428. this._clear(); // clear layers in redraw bounds
  10429. this._draw(); // draw layers
  10430. this._redrawBounds = null;
  10431. },
  10432. _clear: function () {
  10433. var bounds = this._redrawBounds;
  10434. if (bounds) {
  10435. var size = bounds.getSize();
  10436. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  10437. } else {
  10438. this._ctx.save();
  10439. this._ctx.setTransform(1, 0, 0, 1, 0, 0);
  10440. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  10441. this._ctx.restore();
  10442. }
  10443. },
  10444. _draw: function () {
  10445. var layer, bounds = this._redrawBounds;
  10446. this._ctx.save();
  10447. if (bounds) {
  10448. var size = bounds.getSize();
  10449. this._ctx.beginPath();
  10450. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  10451. this._ctx.clip();
  10452. }
  10453. this._drawing = true;
  10454. for (var order = this._drawFirst; order; order = order.next) {
  10455. layer = order.layer;
  10456. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  10457. layer._updatePath();
  10458. }
  10459. }
  10460. this._drawing = false;
  10461. this._ctx.restore(); // Restore state before clipping.
  10462. },
  10463. _updatePoly: function (layer, closed) {
  10464. if (!this._drawing) { return; }
  10465. var i, j, len2, p,
  10466. parts = layer._parts,
  10467. len = parts.length,
  10468. ctx = this._ctx;
  10469. if (!len) { return; }
  10470. ctx.beginPath();
  10471. for (i = 0; i < len; i++) {
  10472. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  10473. p = parts[i][j];
  10474. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  10475. }
  10476. if (closed) {
  10477. ctx.closePath();
  10478. }
  10479. }
  10480. this._fillStroke(ctx, layer);
  10481. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  10482. },
  10483. _updateCircle: function (layer) {
  10484. if (!this._drawing || layer._empty()) { return; }
  10485. var p = layer._point,
  10486. ctx = this._ctx,
  10487. r = Math.max(Math.round(layer._radius), 1),
  10488. s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
  10489. if (s !== 1) {
  10490. ctx.save();
  10491. ctx.scale(1, s);
  10492. }
  10493. ctx.beginPath();
  10494. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  10495. if (s !== 1) {
  10496. ctx.restore();
  10497. }
  10498. this._fillStroke(ctx, layer);
  10499. },
  10500. _fillStroke: function (ctx, layer) {
  10501. var options = layer.options;
  10502. if (options.fill) {
  10503. ctx.globalAlpha = options.fillOpacity;
  10504. ctx.fillStyle = options.fillColor || options.color;
  10505. ctx.fill(options.fillRule || 'evenodd');
  10506. }
  10507. if (options.stroke && options.weight !== 0) {
  10508. if (ctx.setLineDash) {
  10509. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  10510. }
  10511. ctx.globalAlpha = options.opacity;
  10512. ctx.lineWidth = options.weight;
  10513. ctx.strokeStyle = options.color;
  10514. ctx.lineCap = options.lineCap;
  10515. ctx.lineJoin = options.lineJoin;
  10516. ctx.stroke();
  10517. }
  10518. },
  10519. // Canvas obviously doesn't have mouse events for individual drawn objects,
  10520. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  10521. _onClick: function (e) {
  10522. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  10523. for (var order = this._drawFirst; order; order = order.next) {
  10524. layer = order.layer;
  10525. if (layer.options.interactive && layer._containsPoint(point)) {
  10526. if (!(e.type === 'click' || e.type === 'preclick') || !this._map._draggableMoved(layer)) {
  10527. clickedLayer = layer;
  10528. }
  10529. }
  10530. }
  10531. this._fireEvent(clickedLayer ? [clickedLayer] : false, e);
  10532. },
  10533. _onMouseMove: function (e) {
  10534. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  10535. var point = this._map.mouseEventToLayerPoint(e);
  10536. this._handleMouseHover(e, point);
  10537. },
  10538. _handleMouseOut: function (e) {
  10539. var layer = this._hoveredLayer;
  10540. if (layer) {
  10541. // if we're leaving the layer, fire mouseout
  10542. removeClass(this._container, 'leaflet-interactive');
  10543. this._fireEvent([layer], e, 'mouseout');
  10544. this._hoveredLayer = null;
  10545. this._mouseHoverThrottled = false;
  10546. }
  10547. },
  10548. _handleMouseHover: function (e, point) {
  10549. if (this._mouseHoverThrottled) {
  10550. return;
  10551. }
  10552. var layer, candidateHoveredLayer;
  10553. for (var order = this._drawFirst; order; order = order.next) {
  10554. layer = order.layer;
  10555. if (layer.options.interactive && layer._containsPoint(point)) {
  10556. candidateHoveredLayer = layer;
  10557. }
  10558. }
  10559. if (candidateHoveredLayer !== this._hoveredLayer) {
  10560. this._handleMouseOut(e);
  10561. if (candidateHoveredLayer) {
  10562. addClass(this._container, 'leaflet-interactive'); // change cursor
  10563. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  10564. this._hoveredLayer = candidateHoveredLayer;
  10565. }
  10566. }
  10567. this._fireEvent(this._hoveredLayer ? [this._hoveredLayer] : false, e);
  10568. this._mouseHoverThrottled = true;
  10569. setTimeout(bind(function () {
  10570. this._mouseHoverThrottled = false;
  10571. }, this), 32);
  10572. },
  10573. _fireEvent: function (layers, e, type) {
  10574. this._map._fireDOMEvent(e, type || e.type, layers);
  10575. },
  10576. _bringToFront: function (layer) {
  10577. var order = layer._order;
  10578. if (!order) { return; }
  10579. var next = order.next;
  10580. var prev = order.prev;
  10581. if (next) {
  10582. next.prev = prev;
  10583. } else {
  10584. // Already last
  10585. return;
  10586. }
  10587. if (prev) {
  10588. prev.next = next;
  10589. } else if (next) {
  10590. // Update first entry unless this is the
  10591. // single entry
  10592. this._drawFirst = next;
  10593. }
  10594. order.prev = this._drawLast;
  10595. this._drawLast.next = order;
  10596. order.next = null;
  10597. this._drawLast = order;
  10598. this._requestRedraw(layer);
  10599. },
  10600. _bringToBack: function (layer) {
  10601. var order = layer._order;
  10602. if (!order) { return; }
  10603. var next = order.next;
  10604. var prev = order.prev;
  10605. if (prev) {
  10606. prev.next = next;
  10607. } else {
  10608. // Already first
  10609. return;
  10610. }
  10611. if (next) {
  10612. next.prev = prev;
  10613. } else if (prev) {
  10614. // Update last entry unless this is the
  10615. // single entry
  10616. this._drawLast = prev;
  10617. }
  10618. order.prev = null;
  10619. order.next = this._drawFirst;
  10620. this._drawFirst.prev = order;
  10621. this._drawFirst = order;
  10622. this._requestRedraw(layer);
  10623. }
  10624. });
  10625. // @factory L.canvas(options?: Renderer options)
  10626. // Creates a Canvas renderer with the given options.
  10627. function canvas(options) {
  10628. return Browser.canvas ? new Canvas(options) : null;
  10629. }
  10630. /*
  10631. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10632. */
  10633. var vmlCreate = (function () {
  10634. try {
  10635. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10636. return function (name) {
  10637. return document.createElement('<lvml:' + name + ' class="lvml">');
  10638. };
  10639. } catch (e) {
  10640. // Do not return fn from catch block so `e` can be garbage collected
  10641. // See https://github.com/Leaflet/Leaflet/pull/7279
  10642. }
  10643. return function (name) {
  10644. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10645. };
  10646. })();
  10647. /*
  10648. * @class SVG
  10649. *
  10650. *
  10651. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10652. * with old versions of Internet Explorer.
  10653. */
  10654. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10655. var vmlMixin = {
  10656. _initContainer: function () {
  10657. this._container = create$1('div', 'leaflet-vml-container');
  10658. },
  10659. _update: function () {
  10660. if (this._map._animatingZoom) { return; }
  10661. Renderer.prototype._update.call(this);
  10662. this.fire('update');
  10663. },
  10664. _initPath: function (layer) {
  10665. var container = layer._container = vmlCreate('shape');
  10666. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10667. container.coordsize = '1 1';
  10668. layer._path = vmlCreate('path');
  10669. container.appendChild(layer._path);
  10670. this._updateStyle(layer);
  10671. this._layers[stamp(layer)] = layer;
  10672. },
  10673. _addPath: function (layer) {
  10674. var container = layer._container;
  10675. this._container.appendChild(container);
  10676. if (layer.options.interactive) {
  10677. layer.addInteractiveTarget(container);
  10678. }
  10679. },
  10680. _removePath: function (layer) {
  10681. var container = layer._container;
  10682. remove(container);
  10683. layer.removeInteractiveTarget(container);
  10684. delete this._layers[stamp(layer)];
  10685. },
  10686. _updateStyle: function (layer) {
  10687. var stroke = layer._stroke,
  10688. fill = layer._fill,
  10689. options = layer.options,
  10690. container = layer._container;
  10691. container.stroked = !!options.stroke;
  10692. container.filled = !!options.fill;
  10693. if (options.stroke) {
  10694. if (!stroke) {
  10695. stroke = layer._stroke = vmlCreate('stroke');
  10696. }
  10697. container.appendChild(stroke);
  10698. stroke.weight = options.weight + 'px';
  10699. stroke.color = options.color;
  10700. stroke.opacity = options.opacity;
  10701. if (options.dashArray) {
  10702. stroke.dashStyle = isArray(options.dashArray) ?
  10703. options.dashArray.join(' ') :
  10704. options.dashArray.replace(/( *, *)/g, ' ');
  10705. } else {
  10706. stroke.dashStyle = '';
  10707. }
  10708. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10709. stroke.joinstyle = options.lineJoin;
  10710. } else if (stroke) {
  10711. container.removeChild(stroke);
  10712. layer._stroke = null;
  10713. }
  10714. if (options.fill) {
  10715. if (!fill) {
  10716. fill = layer._fill = vmlCreate('fill');
  10717. }
  10718. container.appendChild(fill);
  10719. fill.color = options.fillColor || options.color;
  10720. fill.opacity = options.fillOpacity;
  10721. } else if (fill) {
  10722. container.removeChild(fill);
  10723. layer._fill = null;
  10724. }
  10725. },
  10726. _updateCircle: function (layer) {
  10727. var p = layer._point.round(),
  10728. r = Math.round(layer._radius),
  10729. r2 = Math.round(layer._radiusY || r);
  10730. this._setPath(layer, layer._empty() ? 'M0 0' :
  10731. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10732. },
  10733. _setPath: function (layer, path) {
  10734. layer._path.v = path;
  10735. },
  10736. _bringToFront: function (layer) {
  10737. toFront(layer._container);
  10738. },
  10739. _bringToBack: function (layer) {
  10740. toBack(layer._container);
  10741. }
  10742. };
  10743. var create = Browser.vml ? vmlCreate : svgCreate;
  10744. /*
  10745. * @class SVG
  10746. * @inherits Renderer
  10747. * @aka L.SVG
  10748. *
  10749. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10750. * Inherits `Renderer`.
  10751. *
  10752. * Due to [technical limitations](https://caniuse.com/svg), SVG is not
  10753. * available in all web browsers, notably Android 2.x and 3.x.
  10754. *
  10755. * Although SVG is not available on IE7 and IE8, these browsers support
  10756. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10757. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10758. * this case.
  10759. *
  10760. * @example
  10761. *
  10762. * Use SVG by default for all paths in the map:
  10763. *
  10764. * ```js
  10765. * var map = L.map('map', {
  10766. * renderer: L.svg()
  10767. * });
  10768. * ```
  10769. *
  10770. * Use a SVG renderer with extra padding for specific vector geometries:
  10771. *
  10772. * ```js
  10773. * var map = L.map('map');
  10774. * var myRenderer = L.svg({ padding: 0.5 });
  10775. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10776. * var circle = L.circle( center, { renderer: myRenderer } );
  10777. * ```
  10778. */
  10779. var SVG = Renderer.extend({
  10780. _initContainer: function () {
  10781. this._container = create('svg');
  10782. // makes it possible to click through svg root; we'll reset it back in individual paths
  10783. this._container.setAttribute('pointer-events', 'none');
  10784. this._rootGroup = create('g');
  10785. this._container.appendChild(this._rootGroup);
  10786. },
  10787. _destroyContainer: function () {
  10788. remove(this._container);
  10789. off(this._container);
  10790. delete this._container;
  10791. delete this._rootGroup;
  10792. delete this._svgSize;
  10793. },
  10794. _update: function () {
  10795. if (this._map._animatingZoom && this._bounds) { return; }
  10796. Renderer.prototype._update.call(this);
  10797. var b = this._bounds,
  10798. size = b.getSize(),
  10799. container = this._container;
  10800. // set size of svg-container if changed
  10801. if (!this._svgSize || !this._svgSize.equals(size)) {
  10802. this._svgSize = size;
  10803. container.setAttribute('width', size.x);
  10804. container.setAttribute('height', size.y);
  10805. }
  10806. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10807. setPosition(container, b.min);
  10808. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10809. this.fire('update');
  10810. },
  10811. // methods below are called by vector layers implementations
  10812. _initPath: function (layer) {
  10813. var path = layer._path = create('path');
  10814. // @namespace Path
  10815. // @option className: String = null
  10816. // Custom class name set on an element. Only for SVG renderer.
  10817. if (layer.options.className) {
  10818. addClass(path, layer.options.className);
  10819. }
  10820. if (layer.options.interactive) {
  10821. addClass(path, 'leaflet-interactive');
  10822. }
  10823. this._updateStyle(layer);
  10824. this._layers[stamp(layer)] = layer;
  10825. },
  10826. _addPath: function (layer) {
  10827. if (!this._rootGroup) { this._initContainer(); }
  10828. this._rootGroup.appendChild(layer._path);
  10829. layer.addInteractiveTarget(layer._path);
  10830. },
  10831. _removePath: function (layer) {
  10832. remove(layer._path);
  10833. layer.removeInteractiveTarget(layer._path);
  10834. delete this._layers[stamp(layer)];
  10835. },
  10836. _updatePath: function (layer) {
  10837. layer._project();
  10838. layer._update();
  10839. },
  10840. _updateStyle: function (layer) {
  10841. var path = layer._path,
  10842. options = layer.options;
  10843. if (!path) { return; }
  10844. if (options.stroke) {
  10845. path.setAttribute('stroke', options.color);
  10846. path.setAttribute('stroke-opacity', options.opacity);
  10847. path.setAttribute('stroke-width', options.weight);
  10848. path.setAttribute('stroke-linecap', options.lineCap);
  10849. path.setAttribute('stroke-linejoin', options.lineJoin);
  10850. if (options.dashArray) {
  10851. path.setAttribute('stroke-dasharray', options.dashArray);
  10852. } else {
  10853. path.removeAttribute('stroke-dasharray');
  10854. }
  10855. if (options.dashOffset) {
  10856. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10857. } else {
  10858. path.removeAttribute('stroke-dashoffset');
  10859. }
  10860. } else {
  10861. path.setAttribute('stroke', 'none');
  10862. }
  10863. if (options.fill) {
  10864. path.setAttribute('fill', options.fillColor || options.color);
  10865. path.setAttribute('fill-opacity', options.fillOpacity);
  10866. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10867. } else {
  10868. path.setAttribute('fill', 'none');
  10869. }
  10870. },
  10871. _updatePoly: function (layer, closed) {
  10872. this._setPath(layer, pointsToPath(layer._parts, closed));
  10873. },
  10874. _updateCircle: function (layer) {
  10875. var p = layer._point,
  10876. r = Math.max(Math.round(layer._radius), 1),
  10877. r2 = Math.max(Math.round(layer._radiusY), 1) || r,
  10878. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10879. // drawing a circle with two half-arcs
  10880. var d = layer._empty() ? 'M0 0' :
  10881. 'M' + (p.x - r) + ',' + p.y +
  10882. arc + (r * 2) + ',0 ' +
  10883. arc + (-r * 2) + ',0 ';
  10884. this._setPath(layer, d);
  10885. },
  10886. _setPath: function (layer, path) {
  10887. layer._path.setAttribute('d', path);
  10888. },
  10889. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10890. _bringToFront: function (layer) {
  10891. toFront(layer._path);
  10892. },
  10893. _bringToBack: function (layer) {
  10894. toBack(layer._path);
  10895. }
  10896. });
  10897. if (Browser.vml) {
  10898. SVG.include(vmlMixin);
  10899. }
  10900. // @namespace SVG
  10901. // @factory L.svg(options?: Renderer options)
  10902. // Creates a SVG renderer with the given options.
  10903. function svg(options) {
  10904. return Browser.svg || Browser.vml ? new SVG(options) : null;
  10905. }
  10906. Map.include({
  10907. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10908. // Returns the instance of `Renderer` that should be used to render the given
  10909. // `Path`. It will ensure that the `renderer` options of the map and paths
  10910. // are respected, and that the renderers do exist on the map.
  10911. getRenderer: function (layer) {
  10912. // @namespace Path; @option renderer: Renderer
  10913. // Use this specific instance of `Renderer` for this path. Takes
  10914. // precedence over the map's [default renderer](#map-renderer).
  10915. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10916. if (!renderer) {
  10917. renderer = this._renderer = this._createRenderer();
  10918. }
  10919. if (!this.hasLayer(renderer)) {
  10920. this.addLayer(renderer);
  10921. }
  10922. return renderer;
  10923. },
  10924. _getPaneRenderer: function (name) {
  10925. if (name === 'overlayPane' || name === undefined) {
  10926. return false;
  10927. }
  10928. var renderer = this._paneRenderers[name];
  10929. if (renderer === undefined) {
  10930. renderer = this._createRenderer({pane: name});
  10931. this._paneRenderers[name] = renderer;
  10932. }
  10933. return renderer;
  10934. },
  10935. _createRenderer: function (options) {
  10936. // @namespace Map; @option preferCanvas: Boolean = false
  10937. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10938. // By default, all `Path`s are rendered in a `SVG` renderer.
  10939. return (this.options.preferCanvas && canvas(options)) || svg(options);
  10940. }
  10941. });
  10942. /*
  10943. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10944. */
  10945. /*
  10946. * @class Rectangle
  10947. * @aka L.Rectangle
  10948. * @inherits Polygon
  10949. *
  10950. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10951. *
  10952. * @example
  10953. *
  10954. * ```js
  10955. * // define rectangle geographical bounds
  10956. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10957. *
  10958. * // create an orange rectangle
  10959. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10960. *
  10961. * // zoom the map to the rectangle bounds
  10962. * map.fitBounds(bounds);
  10963. * ```
  10964. *
  10965. */
  10966. var Rectangle = Polygon.extend({
  10967. initialize: function (latLngBounds, options) {
  10968. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10969. },
  10970. // @method setBounds(latLngBounds: LatLngBounds): this
  10971. // Redraws the rectangle with the passed bounds.
  10972. setBounds: function (latLngBounds) {
  10973. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  10974. },
  10975. _boundsToLatLngs: function (latLngBounds) {
  10976. latLngBounds = toLatLngBounds(latLngBounds);
  10977. return [
  10978. latLngBounds.getSouthWest(),
  10979. latLngBounds.getNorthWest(),
  10980. latLngBounds.getNorthEast(),
  10981. latLngBounds.getSouthEast()
  10982. ];
  10983. }
  10984. });
  10985. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  10986. function rectangle(latLngBounds, options) {
  10987. return new Rectangle(latLngBounds, options);
  10988. }
  10989. SVG.create = create;
  10990. SVG.pointsToPath = pointsToPath;
  10991. GeoJSON.geometryToLayer = geometryToLayer;
  10992. GeoJSON.coordsToLatLng = coordsToLatLng;
  10993. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  10994. GeoJSON.latLngToCoords = latLngToCoords;
  10995. GeoJSON.latLngsToCoords = latLngsToCoords;
  10996. GeoJSON.getFeature = getFeature;
  10997. GeoJSON.asFeature = asFeature;
  10998. /*
  10999. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  11000. * (zoom to a selected bounding box), enabled by default.
  11001. */
  11002. // @namespace Map
  11003. // @section Interaction Options
  11004. Map.mergeOptions({
  11005. // @option boxZoom: Boolean = true
  11006. // Whether the map can be zoomed to a rectangular area specified by
  11007. // dragging the mouse while pressing the shift key.
  11008. boxZoom: true
  11009. });
  11010. var BoxZoom = Handler.extend({
  11011. initialize: function (map) {
  11012. this._map = map;
  11013. this._container = map._container;
  11014. this._pane = map._panes.overlayPane;
  11015. this._resetStateTimeout = 0;
  11016. map.on('unload', this._destroy, this);
  11017. },
  11018. addHooks: function () {
  11019. on(this._container, 'mousedown', this._onMouseDown, this);
  11020. },
  11021. removeHooks: function () {
  11022. off(this._container, 'mousedown', this._onMouseDown, this);
  11023. },
  11024. moved: function () {
  11025. return this._moved;
  11026. },
  11027. _destroy: function () {
  11028. remove(this._pane);
  11029. delete this._pane;
  11030. },
  11031. _resetState: function () {
  11032. this._resetStateTimeout = 0;
  11033. this._moved = false;
  11034. },
  11035. _clearDeferredResetState: function () {
  11036. if (this._resetStateTimeout !== 0) {
  11037. clearTimeout(this._resetStateTimeout);
  11038. this._resetStateTimeout = 0;
  11039. }
  11040. },
  11041. _onMouseDown: function (e) {
  11042. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  11043. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  11044. // will interrupt the interaction and orphan a box element in the container.
  11045. this._clearDeferredResetState();
  11046. this._resetState();
  11047. disableTextSelection();
  11048. disableImageDrag();
  11049. this._startPoint = this._map.mouseEventToContainerPoint(e);
  11050. on(document, {
  11051. contextmenu: stop,
  11052. mousemove: this._onMouseMove,
  11053. mouseup: this._onMouseUp,
  11054. keydown: this._onKeyDown
  11055. }, this);
  11056. },
  11057. _onMouseMove: function (e) {
  11058. if (!this._moved) {
  11059. this._moved = true;
  11060. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  11061. addClass(this._container, 'leaflet-crosshair');
  11062. this._map.fire('boxzoomstart');
  11063. }
  11064. this._point = this._map.mouseEventToContainerPoint(e);
  11065. var bounds = new Bounds(this._point, this._startPoint),
  11066. size = bounds.getSize();
  11067. setPosition(this._box, bounds.min);
  11068. this._box.style.width = size.x + 'px';
  11069. this._box.style.height = size.y + 'px';
  11070. },
  11071. _finish: function () {
  11072. if (this._moved) {
  11073. remove(this._box);
  11074. removeClass(this._container, 'leaflet-crosshair');
  11075. }
  11076. enableTextSelection();
  11077. enableImageDrag();
  11078. off(document, {
  11079. contextmenu: stop,
  11080. mousemove: this._onMouseMove,
  11081. mouseup: this._onMouseUp,
  11082. keydown: this._onKeyDown
  11083. }, this);
  11084. },
  11085. _onMouseUp: function (e) {
  11086. if ((e.which !== 1) && (e.button !== 1)) { return; }
  11087. this._finish();
  11088. if (!this._moved) { return; }
  11089. // Postpone to next JS tick so internal click event handling
  11090. // still see it as "moved".
  11091. this._clearDeferredResetState();
  11092. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  11093. var bounds = new LatLngBounds(
  11094. this._map.containerPointToLatLng(this._startPoint),
  11095. this._map.containerPointToLatLng(this._point));
  11096. this._map
  11097. .fitBounds(bounds)
  11098. .fire('boxzoomend', {boxZoomBounds: bounds});
  11099. },
  11100. _onKeyDown: function (e) {
  11101. if (e.keyCode === 27) {
  11102. this._finish();
  11103. this._clearDeferredResetState();
  11104. this._resetState();
  11105. }
  11106. }
  11107. });
  11108. // @section Handlers
  11109. // @property boxZoom: Handler
  11110. // Box (shift-drag with mouse) zoom handler.
  11111. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  11112. /*
  11113. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  11114. */
  11115. // @namespace Map
  11116. // @section Interaction Options
  11117. Map.mergeOptions({
  11118. // @option doubleClickZoom: Boolean|String = true
  11119. // Whether the map can be zoomed in by double clicking on it and
  11120. // zoomed out by double clicking while holding shift. If passed
  11121. // `'center'`, double-click zoom will zoom to the center of the
  11122. // view regardless of where the mouse was.
  11123. doubleClickZoom: true
  11124. });
  11125. var DoubleClickZoom = Handler.extend({
  11126. addHooks: function () {
  11127. this._map.on('dblclick', this._onDoubleClick, this);
  11128. },
  11129. removeHooks: function () {
  11130. this._map.off('dblclick', this._onDoubleClick, this);
  11131. },
  11132. _onDoubleClick: function (e) {
  11133. var map = this._map,
  11134. oldZoom = map.getZoom(),
  11135. delta = map.options.zoomDelta,
  11136. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  11137. if (map.options.doubleClickZoom === 'center') {
  11138. map.setZoom(zoom);
  11139. } else {
  11140. map.setZoomAround(e.containerPoint, zoom);
  11141. }
  11142. }
  11143. });
  11144. // @section Handlers
  11145. //
  11146. // Map properties include interaction handlers that allow you to control
  11147. // interaction behavior in runtime, enabling or disabling certain features such
  11148. // as dragging or touch zoom (see `Handler` methods). For example:
  11149. //
  11150. // ```js
  11151. // map.doubleClickZoom.disable();
  11152. // ```
  11153. //
  11154. // @property doubleClickZoom: Handler
  11155. // Double click zoom handler.
  11156. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  11157. /*
  11158. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  11159. */
  11160. // @namespace Map
  11161. // @section Interaction Options
  11162. Map.mergeOptions({
  11163. // @option dragging: Boolean = true
  11164. // Whether the map is draggable with mouse/touch or not.
  11165. dragging: true,
  11166. // @section Panning Inertia Options
  11167. // @option inertia: Boolean = *
  11168. // If enabled, panning of the map will have an inertia effect where
  11169. // the map builds momentum while dragging and continues moving in
  11170. // the same direction for some time. Feels especially nice on touch
  11171. // devices. Enabled by default.
  11172. inertia: true,
  11173. // @option inertiaDeceleration: Number = 3000
  11174. // The rate with which the inertial movement slows down, in pixels/second².
  11175. inertiaDeceleration: 3400, // px/s^2
  11176. // @option inertiaMaxSpeed: Number = Infinity
  11177. // Max speed of the inertial movement, in pixels/second.
  11178. inertiaMaxSpeed: Infinity, // px/s
  11179. // @option easeLinearity: Number = 0.2
  11180. easeLinearity: 0.2,
  11181. // TODO refactor, move to CRS
  11182. // @option worldCopyJump: Boolean = false
  11183. // With this option enabled, the map tracks when you pan to another "copy"
  11184. // of the world and seamlessly jumps to the original one so that all overlays
  11185. // like markers and vector layers are still visible.
  11186. worldCopyJump: false,
  11187. // @option maxBoundsViscosity: Number = 0.0
  11188. // If `maxBounds` is set, this option will control how solid the bounds
  11189. // are when dragging the map around. The default value of `0.0` allows the
  11190. // user to drag outside the bounds at normal speed, higher values will
  11191. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  11192. // solid, preventing the user from dragging outside the bounds.
  11193. maxBoundsViscosity: 0.0
  11194. });
  11195. var Drag = Handler.extend({
  11196. addHooks: function () {
  11197. if (!this._draggable) {
  11198. var map = this._map;
  11199. this._draggable = new Draggable(map._mapPane, map._container);
  11200. this._draggable.on({
  11201. dragstart: this._onDragStart,
  11202. drag: this._onDrag,
  11203. dragend: this._onDragEnd
  11204. }, this);
  11205. this._draggable.on('predrag', this._onPreDragLimit, this);
  11206. if (map.options.worldCopyJump) {
  11207. this._draggable.on('predrag', this._onPreDragWrap, this);
  11208. map.on('zoomend', this._onZoomEnd, this);
  11209. map.whenReady(this._onZoomEnd, this);
  11210. }
  11211. }
  11212. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  11213. this._draggable.enable();
  11214. this._positions = [];
  11215. this._times = [];
  11216. },
  11217. removeHooks: function () {
  11218. removeClass(this._map._container, 'leaflet-grab');
  11219. removeClass(this._map._container, 'leaflet-touch-drag');
  11220. this._draggable.disable();
  11221. },
  11222. moved: function () {
  11223. return this._draggable && this._draggable._moved;
  11224. },
  11225. moving: function () {
  11226. return this._draggable && this._draggable._moving;
  11227. },
  11228. _onDragStart: function () {
  11229. var map = this._map;
  11230. map._stop();
  11231. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  11232. var bounds = toLatLngBounds(this._map.options.maxBounds);
  11233. this._offsetLimit = toBounds(
  11234. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  11235. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  11236. .add(this._map.getSize()));
  11237. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  11238. } else {
  11239. this._offsetLimit = null;
  11240. }
  11241. map
  11242. .fire('movestart')
  11243. .fire('dragstart');
  11244. if (map.options.inertia) {
  11245. this._positions = [];
  11246. this._times = [];
  11247. }
  11248. },
  11249. _onDrag: function (e) {
  11250. if (this._map.options.inertia) {
  11251. var time = this._lastTime = +new Date(),
  11252. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  11253. this._positions.push(pos);
  11254. this._times.push(time);
  11255. this._prunePositions(time);
  11256. }
  11257. this._map
  11258. .fire('move', e)
  11259. .fire('drag', e);
  11260. },
  11261. _prunePositions: function (time) {
  11262. while (this._positions.length > 1 && time - this._times[0] > 50) {
  11263. this._positions.shift();
  11264. this._times.shift();
  11265. }
  11266. },
  11267. _onZoomEnd: function () {
  11268. var pxCenter = this._map.getSize().divideBy(2),
  11269. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  11270. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  11271. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  11272. },
  11273. _viscousLimit: function (value, threshold) {
  11274. return value - (value - threshold) * this._viscosity;
  11275. },
  11276. _onPreDragLimit: function () {
  11277. if (!this._viscosity || !this._offsetLimit) { return; }
  11278. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  11279. var limit = this._offsetLimit;
  11280. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  11281. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  11282. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  11283. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  11284. this._draggable._newPos = this._draggable._startPos.add(offset);
  11285. },
  11286. _onPreDragWrap: function () {
  11287. // TODO refactor to be able to adjust map pane position after zoom
  11288. var worldWidth = this._worldWidth,
  11289. halfWidth = Math.round(worldWidth / 2),
  11290. dx = this._initialWorldOffset,
  11291. x = this._draggable._newPos.x,
  11292. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  11293. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  11294. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  11295. this._draggable._absPos = this._draggable._newPos.clone();
  11296. this._draggable._newPos.x = newX;
  11297. },
  11298. _onDragEnd: function (e) {
  11299. var map = this._map,
  11300. options = map.options,
  11301. noInertia = !options.inertia || e.noInertia || this._times.length < 2;
  11302. map.fire('dragend', e);
  11303. if (noInertia) {
  11304. map.fire('moveend');
  11305. } else {
  11306. this._prunePositions(+new Date());
  11307. var direction = this._lastPos.subtract(this._positions[0]),
  11308. duration = (this._lastTime - this._times[0]) / 1000,
  11309. ease = options.easeLinearity,
  11310. speedVector = direction.multiplyBy(ease / duration),
  11311. speed = speedVector.distanceTo([0, 0]),
  11312. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  11313. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  11314. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  11315. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  11316. if (!offset.x && !offset.y) {
  11317. map.fire('moveend');
  11318. } else {
  11319. offset = map._limitOffset(offset, map.options.maxBounds);
  11320. requestAnimFrame(function () {
  11321. map.panBy(offset, {
  11322. duration: decelerationDuration,
  11323. easeLinearity: ease,
  11324. noMoveStart: true,
  11325. animate: true
  11326. });
  11327. });
  11328. }
  11329. }
  11330. }
  11331. });
  11332. // @section Handlers
  11333. // @property dragging: Handler
  11334. // Map dragging handler (by both mouse and touch).
  11335. Map.addInitHook('addHandler', 'dragging', Drag);
  11336. /*
  11337. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  11338. */
  11339. // @namespace Map
  11340. // @section Keyboard Navigation Options
  11341. Map.mergeOptions({
  11342. // @option keyboard: Boolean = true
  11343. // Makes the map focusable and allows users to navigate the map with keyboard
  11344. // arrows and `+`/`-` keys.
  11345. keyboard: true,
  11346. // @option keyboardPanDelta: Number = 80
  11347. // Amount of pixels to pan when pressing an arrow key.
  11348. keyboardPanDelta: 80
  11349. });
  11350. var Keyboard = Handler.extend({
  11351. keyCodes: {
  11352. left: [37],
  11353. right: [39],
  11354. down: [40],
  11355. up: [38],
  11356. zoomIn: [187, 107, 61, 171],
  11357. zoomOut: [189, 109, 54, 173]
  11358. },
  11359. initialize: function (map) {
  11360. this._map = map;
  11361. this._setPanDelta(map.options.keyboardPanDelta);
  11362. this._setZoomDelta(map.options.zoomDelta);
  11363. },
  11364. addHooks: function () {
  11365. var container = this._map._container;
  11366. // make the container focusable by tabbing
  11367. if (container.tabIndex <= 0) {
  11368. container.tabIndex = '0';
  11369. }
  11370. on(container, {
  11371. focus: this._onFocus,
  11372. blur: this._onBlur,
  11373. mousedown: this._onMouseDown
  11374. }, this);
  11375. this._map.on({
  11376. focus: this._addHooks,
  11377. blur: this._removeHooks
  11378. }, this);
  11379. },
  11380. removeHooks: function () {
  11381. this._removeHooks();
  11382. off(this._map._container, {
  11383. focus: this._onFocus,
  11384. blur: this._onBlur,
  11385. mousedown: this._onMouseDown
  11386. }, this);
  11387. this._map.off({
  11388. focus: this._addHooks,
  11389. blur: this._removeHooks
  11390. }, this);
  11391. },
  11392. _onMouseDown: function () {
  11393. if (this._focused) { return; }
  11394. var body = document.body,
  11395. docEl = document.documentElement,
  11396. top = body.scrollTop || docEl.scrollTop,
  11397. left = body.scrollLeft || docEl.scrollLeft;
  11398. this._map._container.focus();
  11399. window.scrollTo(left, top);
  11400. },
  11401. _onFocus: function () {
  11402. this._focused = true;
  11403. this._map.fire('focus');
  11404. },
  11405. _onBlur: function () {
  11406. this._focused = false;
  11407. this._map.fire('blur');
  11408. },
  11409. _setPanDelta: function (panDelta) {
  11410. var keys = this._panKeys = {},
  11411. codes = this.keyCodes,
  11412. i, len;
  11413. for (i = 0, len = codes.left.length; i < len; i++) {
  11414. keys[codes.left[i]] = [-1 * panDelta, 0];
  11415. }
  11416. for (i = 0, len = codes.right.length; i < len; i++) {
  11417. keys[codes.right[i]] = [panDelta, 0];
  11418. }
  11419. for (i = 0, len = codes.down.length; i < len; i++) {
  11420. keys[codes.down[i]] = [0, panDelta];
  11421. }
  11422. for (i = 0, len = codes.up.length; i < len; i++) {
  11423. keys[codes.up[i]] = [0, -1 * panDelta];
  11424. }
  11425. },
  11426. _setZoomDelta: function (zoomDelta) {
  11427. var keys = this._zoomKeys = {},
  11428. codes = this.keyCodes,
  11429. i, len;
  11430. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  11431. keys[codes.zoomIn[i]] = zoomDelta;
  11432. }
  11433. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  11434. keys[codes.zoomOut[i]] = -zoomDelta;
  11435. }
  11436. },
  11437. _addHooks: function () {
  11438. on(document, 'keydown', this._onKeyDown, this);
  11439. },
  11440. _removeHooks: function () {
  11441. off(document, 'keydown', this._onKeyDown, this);
  11442. },
  11443. _onKeyDown: function (e) {
  11444. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  11445. var key = e.keyCode,
  11446. map = this._map,
  11447. offset;
  11448. if (key in this._panKeys) {
  11449. if (!map._panAnim || !map._panAnim._inProgress) {
  11450. offset = this._panKeys[key];
  11451. if (e.shiftKey) {
  11452. offset = toPoint(offset).multiplyBy(3);
  11453. }
  11454. map.panBy(offset);
  11455. if (map.options.maxBounds) {
  11456. map.panInsideBounds(map.options.maxBounds);
  11457. }
  11458. }
  11459. } else if (key in this._zoomKeys) {
  11460. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  11461. } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
  11462. map.closePopup();
  11463. } else {
  11464. return;
  11465. }
  11466. stop(e);
  11467. }
  11468. });
  11469. // @section Handlers
  11470. // @section Handlers
  11471. // @property keyboard: Handler
  11472. // Keyboard navigation handler.
  11473. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  11474. /*
  11475. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  11476. */
  11477. // @namespace Map
  11478. // @section Interaction Options
  11479. Map.mergeOptions({
  11480. // @section Mouse wheel options
  11481. // @option scrollWheelZoom: Boolean|String = true
  11482. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  11483. // it will zoom to the center of the view regardless of where the mouse was.
  11484. scrollWheelZoom: true,
  11485. // @option wheelDebounceTime: Number = 40
  11486. // Limits the rate at which a wheel can fire (in milliseconds). By default
  11487. // user can't zoom via wheel more often than once per 40 ms.
  11488. wheelDebounceTime: 40,
  11489. // @option wheelPxPerZoomLevel: Number = 60
  11490. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  11491. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  11492. // faster (and vice versa).
  11493. wheelPxPerZoomLevel: 60
  11494. });
  11495. var ScrollWheelZoom = Handler.extend({
  11496. addHooks: function () {
  11497. on(this._map._container, 'wheel', this._onWheelScroll, this);
  11498. this._delta = 0;
  11499. },
  11500. removeHooks: function () {
  11501. off(this._map._container, 'wheel', this._onWheelScroll, this);
  11502. },
  11503. _onWheelScroll: function (e) {
  11504. var delta = getWheelDelta(e);
  11505. var debounce = this._map.options.wheelDebounceTime;
  11506. this._delta += delta;
  11507. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  11508. if (!this._startTime) {
  11509. this._startTime = +new Date();
  11510. }
  11511. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  11512. clearTimeout(this._timer);
  11513. this._timer = setTimeout(bind(this._performZoom, this), left);
  11514. stop(e);
  11515. },
  11516. _performZoom: function () {
  11517. var map = this._map,
  11518. zoom = map.getZoom(),
  11519. snap = this._map.options.zoomSnap || 0;
  11520. map._stop(); // stop panning and fly animations if any
  11521. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  11522. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  11523. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  11524. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  11525. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  11526. this._delta = 0;
  11527. this._startTime = null;
  11528. if (!delta) { return; }
  11529. if (map.options.scrollWheelZoom === 'center') {
  11530. map.setZoom(zoom + delta);
  11531. } else {
  11532. map.setZoomAround(this._lastMousePos, zoom + delta);
  11533. }
  11534. }
  11535. });
  11536. // @section Handlers
  11537. // @property scrollWheelZoom: Handler
  11538. // Scroll wheel zoom handler.
  11539. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  11540. /*
  11541. * L.Map.TapHold is used to simulate `contextmenu` event on long hold,
  11542. * which otherwise is not fired by mobile Safari.
  11543. */
  11544. var tapHoldDelay = 600;
  11545. // @namespace Map
  11546. // @section Interaction Options
  11547. Map.mergeOptions({
  11548. // @section Touch interaction options
  11549. // @option tapHold: Boolean
  11550. // Enables simulation of `contextmenu` event, default is `true` for mobile Safari.
  11551. tapHold: Browser.touchNative && Browser.safari && Browser.mobile,
  11552. // @option tapTolerance: Number = 15
  11553. // The max number of pixels a user can shift his finger during touch
  11554. // for it to be considered a valid tap.
  11555. tapTolerance: 15
  11556. });
  11557. var TapHold = Handler.extend({
  11558. addHooks: function () {
  11559. on(this._map._container, 'touchstart', this._onDown, this);
  11560. },
  11561. removeHooks: function () {
  11562. off(this._map._container, 'touchstart', this._onDown, this);
  11563. },
  11564. _onDown: function (e) {
  11565. clearTimeout(this._holdTimeout);
  11566. if (e.touches.length !== 1) { return; }
  11567. var first = e.touches[0];
  11568. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  11569. this._holdTimeout = setTimeout(bind(function () {
  11570. this._cancel();
  11571. if (!this._isTapValid()) { return; }
  11572. // prevent simulated mouse events https://w3c.github.io/touch-events/#mouse-events
  11573. on(document, 'touchend', preventDefault);
  11574. on(document, 'touchend touchcancel', this._cancelClickPrevent);
  11575. this._simulateEvent('contextmenu', first);
  11576. }, this), tapHoldDelay);
  11577. on(document, 'touchend touchcancel contextmenu', this._cancel, this);
  11578. on(document, 'touchmove', this._onMove, this);
  11579. },
  11580. _cancelClickPrevent: function cancelClickPrevent() {
  11581. off(document, 'touchend', preventDefault);
  11582. off(document, 'touchend touchcancel', cancelClickPrevent);
  11583. },
  11584. _cancel: function () {
  11585. clearTimeout(this._holdTimeout);
  11586. off(document, 'touchend touchcancel contextmenu', this._cancel, this);
  11587. off(document, 'touchmove', this._onMove, this);
  11588. },
  11589. _onMove: function (e) {
  11590. var first = e.touches[0];
  11591. this._newPos = new Point(first.clientX, first.clientY);
  11592. },
  11593. _isTapValid: function () {
  11594. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11595. },
  11596. _simulateEvent: function (type, e) {
  11597. var simulatedEvent = new MouseEvent(type, {
  11598. bubbles: true,
  11599. cancelable: true,
  11600. view: window,
  11601. // detail: 1,
  11602. screenX: e.screenX,
  11603. screenY: e.screenY,
  11604. clientX: e.clientX,
  11605. clientY: e.clientY,
  11606. // button: 2,
  11607. // buttons: 2
  11608. });
  11609. simulatedEvent._simulated = true;
  11610. e.target.dispatchEvent(simulatedEvent);
  11611. }
  11612. });
  11613. // @section Handlers
  11614. // @property tapHold: Handler
  11615. // Long tap handler to simulate `contextmenu` event (useful in mobile Safari).
  11616. Map.addInitHook('addHandler', 'tapHold', TapHold);
  11617. /*
  11618. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11619. */
  11620. // @namespace Map
  11621. // @section Interaction Options
  11622. Map.mergeOptions({
  11623. // @section Touch interaction options
  11624. // @option touchZoom: Boolean|String = *
  11625. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11626. // passed `'center'`, it will zoom to the center of the view regardless of
  11627. // where the touch events (fingers) were. Enabled for touch-capable web
  11628. // browsers.
  11629. touchZoom: Browser.touch,
  11630. // @option bounceAtZoomLimits: Boolean = true
  11631. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11632. // and then bounce back when pinch-zooming.
  11633. bounceAtZoomLimits: true
  11634. });
  11635. var TouchZoom = Handler.extend({
  11636. addHooks: function () {
  11637. addClass(this._map._container, 'leaflet-touch-zoom');
  11638. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11639. },
  11640. removeHooks: function () {
  11641. removeClass(this._map._container, 'leaflet-touch-zoom');
  11642. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11643. },
  11644. _onTouchStart: function (e) {
  11645. var map = this._map;
  11646. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  11647. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11648. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11649. this._centerPoint = map.getSize()._divideBy(2);
  11650. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11651. if (map.options.touchZoom !== 'center') {
  11652. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11653. }
  11654. this._startDist = p1.distanceTo(p2);
  11655. this._startZoom = map.getZoom();
  11656. this._moved = false;
  11657. this._zooming = true;
  11658. map._stop();
  11659. on(document, 'touchmove', this._onTouchMove, this);
  11660. on(document, 'touchend touchcancel', this._onTouchEnd, this);
  11661. preventDefault(e);
  11662. },
  11663. _onTouchMove: function (e) {
  11664. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  11665. var map = this._map,
  11666. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11667. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11668. scale = p1.distanceTo(p2) / this._startDist;
  11669. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11670. if (!map.options.bounceAtZoomLimits && (
  11671. (this._zoom < map.getMinZoom() && scale < 1) ||
  11672. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11673. this._zoom = map._limitZoom(this._zoom);
  11674. }
  11675. if (map.options.touchZoom === 'center') {
  11676. this._center = this._startLatLng;
  11677. if (scale === 1) { return; }
  11678. } else {
  11679. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11680. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11681. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  11682. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11683. }
  11684. if (!this._moved) {
  11685. map._moveStart(true, false);
  11686. this._moved = true;
  11687. }
  11688. cancelAnimFrame(this._animRequest);
  11689. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false}, undefined);
  11690. this._animRequest = requestAnimFrame(moveFn, this, true);
  11691. preventDefault(e);
  11692. },
  11693. _onTouchEnd: function () {
  11694. if (!this._moved || !this._zooming) {
  11695. this._zooming = false;
  11696. return;
  11697. }
  11698. this._zooming = false;
  11699. cancelAnimFrame(this._animRequest);
  11700. off(document, 'touchmove', this._onTouchMove, this);
  11701. off(document, 'touchend touchcancel', this._onTouchEnd, this);
  11702. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11703. if (this._map.options.zoomAnimation) {
  11704. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11705. } else {
  11706. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11707. }
  11708. }
  11709. });
  11710. // @section Handlers
  11711. // @property touchZoom: Handler
  11712. // Touch zoom handler.
  11713. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11714. Map.BoxZoom = BoxZoom;
  11715. Map.DoubleClickZoom = DoubleClickZoom;
  11716. Map.Drag = Drag;
  11717. Map.Keyboard = Keyboard;
  11718. Map.ScrollWheelZoom = ScrollWheelZoom;
  11719. Map.TapHold = TapHold;
  11720. Map.TouchZoom = TouchZoom;
  11721. exports.Bounds = Bounds;
  11722. exports.Browser = Browser;
  11723. exports.CRS = CRS;
  11724. exports.Canvas = Canvas;
  11725. exports.Circle = Circle;
  11726. exports.CircleMarker = CircleMarker;
  11727. exports.Class = Class;
  11728. exports.Control = Control;
  11729. exports.DivIcon = DivIcon;
  11730. exports.DivOverlay = DivOverlay;
  11731. exports.DomEvent = DomEvent;
  11732. exports.DomUtil = DomUtil;
  11733. exports.Draggable = Draggable;
  11734. exports.Evented = Evented;
  11735. exports.FeatureGroup = FeatureGroup;
  11736. exports.GeoJSON = GeoJSON;
  11737. exports.GridLayer = GridLayer;
  11738. exports.Handler = Handler;
  11739. exports.Icon = Icon;
  11740. exports.ImageOverlay = ImageOverlay;
  11741. exports.LatLng = LatLng;
  11742. exports.LatLngBounds = LatLngBounds;
  11743. exports.Layer = Layer;
  11744. exports.LayerGroup = LayerGroup;
  11745. exports.LineUtil = LineUtil;
  11746. exports.Map = Map;
  11747. exports.Marker = Marker;
  11748. exports.Mixin = Mixin;
  11749. exports.Path = Path;
  11750. exports.Point = Point;
  11751. exports.PolyUtil = PolyUtil;
  11752. exports.Polygon = Polygon;
  11753. exports.Polyline = Polyline;
  11754. exports.Popup = Popup;
  11755. exports.PosAnimation = PosAnimation;
  11756. exports.Projection = index;
  11757. exports.Rectangle = Rectangle;
  11758. exports.Renderer = Renderer;
  11759. exports.SVG = SVG;
  11760. exports.SVGOverlay = SVGOverlay;
  11761. exports.TileLayer = TileLayer;
  11762. exports.Tooltip = Tooltip;
  11763. exports.Transformation = Transformation;
  11764. exports.Util = Util;
  11765. exports.VideoOverlay = VideoOverlay;
  11766. exports.bind = bind;
  11767. exports.bounds = toBounds;
  11768. exports.canvas = canvas;
  11769. exports.circle = circle;
  11770. exports.circleMarker = circleMarker;
  11771. exports.control = control;
  11772. exports.divIcon = divIcon;
  11773. exports.extend = extend;
  11774. exports.featureGroup = featureGroup;
  11775. exports.geoJSON = geoJSON;
  11776. exports.geoJson = geoJson;
  11777. exports.gridLayer = gridLayer;
  11778. exports.icon = icon;
  11779. exports.imageOverlay = imageOverlay;
  11780. exports.latLng = toLatLng;
  11781. exports.latLngBounds = toLatLngBounds;
  11782. exports.layerGroup = layerGroup;
  11783. exports.map = createMap;
  11784. exports.marker = marker;
  11785. exports.point = toPoint;
  11786. exports.polygon = polygon;
  11787. exports.polyline = polyline;
  11788. exports.popup = popup;
  11789. exports.rectangle = rectangle;
  11790. exports.setOptions = setOptions;
  11791. exports.stamp = stamp;
  11792. exports.svg = svg;
  11793. exports.svgOverlay = svgOverlay;
  11794. exports.tileLayer = tileLayer;
  11795. exports.tooltip = tooltip;
  11796. exports.transformation = toTransformation;
  11797. exports.version = version;
  11798. exports.videoOverlay = videoOverlay;
  11799. var oldL = window.L;
  11800. exports.noConflict = function() {
  11801. window.L = oldL;
  11802. return this;
  11803. }
  11804. // Always export us to window global (see #2364)
  11805. window.L = exports;
  11806. }));
  11807. //# sourceMappingURL=leaflet-src.js.map