leaflet-src.esm.js 403 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316
  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. var version = "1.9.2";
  6. /*
  7. * @namespace Util
  8. *
  9. * Various utility functions, used by Leaflet internally.
  10. */
  11. // @function extend(dest: Object, src?: Object): Object
  12. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  13. function extend(dest) {
  14. var i, j, len, src;
  15. for (j = 1, len = arguments.length; j < len; j++) {
  16. src = arguments[j];
  17. for (i in src) {
  18. dest[i] = src[i];
  19. }
  20. }
  21. return dest;
  22. }
  23. // @function create(proto: Object, properties?: Object): Object
  24. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  25. var create$2 = Object.create || (function () {
  26. function F() {}
  27. return function (proto) {
  28. F.prototype = proto;
  29. return new F();
  30. };
  31. })();
  32. // @function bind(fn: Function, …): Function
  33. // 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).
  34. // Has a `L.bind()` shortcut.
  35. function bind(fn, obj) {
  36. var slice = Array.prototype.slice;
  37. if (fn.bind) {
  38. return fn.bind.apply(fn, slice.call(arguments, 1));
  39. }
  40. var args = slice.call(arguments, 2);
  41. return function () {
  42. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  43. };
  44. }
  45. // @property lastId: Number
  46. // Last unique ID used by [`stamp()`](#util-stamp)
  47. var lastId = 0;
  48. // @function stamp(obj: Object): Number
  49. // Returns the unique ID of an object, assigning it one if it doesn't have it.
  50. function stamp(obj) {
  51. if (!('_leaflet_id' in obj)) {
  52. obj['_leaflet_id'] = ++lastId;
  53. }
  54. return obj._leaflet_id;
  55. }
  56. // @function throttle(fn: Function, time: Number, context: Object): Function
  57. // Returns a function which executes function `fn` with the given scope `context`
  58. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  59. // `fn` will be called no more than one time per given amount of `time`. The arguments
  60. // received by the bound function will be any arguments passed when binding the
  61. // function, followed by any arguments passed when invoking the bound function.
  62. // Has an `L.throttle` shortcut.
  63. function throttle(fn, time, context) {
  64. var lock, args, wrapperFn, later;
  65. later = function () {
  66. // reset lock and call if queued
  67. lock = false;
  68. if (args) {
  69. wrapperFn.apply(context, args);
  70. args = false;
  71. }
  72. };
  73. wrapperFn = function () {
  74. if (lock) {
  75. // called too soon, queue to call later
  76. args = arguments;
  77. } else {
  78. // call and lock until later
  79. fn.apply(context, arguments);
  80. setTimeout(later, time);
  81. lock = true;
  82. }
  83. };
  84. return wrapperFn;
  85. }
  86. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  87. // Returns the number `num` modulo `range` in such a way so it lies within
  88. // `range[0]` and `range[1]`. The returned value will be always smaller than
  89. // `range[1]` unless `includeMax` is set to `true`.
  90. function wrapNum(x, range, includeMax) {
  91. var max = range[1],
  92. min = range[0],
  93. d = max - min;
  94. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  95. }
  96. // @function falseFn(): Function
  97. // Returns a function which always returns `false`.
  98. function falseFn() { return false; }
  99. // @function formatNum(num: Number, precision?: Number|false): Number
  100. // Returns the number `num` rounded with specified `precision`.
  101. // The default `precision` value is 6 decimal places.
  102. // `false` can be passed to skip any processing (can be useful to avoid round-off errors).
  103. function formatNum(num, precision) {
  104. if (precision === false) { return num; }
  105. var pow = Math.pow(10, precision === undefined ? 6 : precision);
  106. return Math.round(num * pow) / pow;
  107. }
  108. // @function trim(str: String): String
  109. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  110. function trim(str) {
  111. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  112. }
  113. // @function splitWords(str: String): String[]
  114. // Trims and splits the string on whitespace and returns the array of parts.
  115. function splitWords(str) {
  116. return trim(str).split(/\s+/);
  117. }
  118. // @function setOptions(obj: Object, options: Object): Object
  119. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  120. function setOptions(obj, options) {
  121. if (!Object.prototype.hasOwnProperty.call(obj, 'options')) {
  122. obj.options = obj.options ? create$2(obj.options) : {};
  123. }
  124. for (var i in options) {
  125. obj.options[i] = options[i];
  126. }
  127. return obj.options;
  128. }
  129. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  130. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  131. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  132. // be appended at the end. If `uppercase` is `true`, the parameter names will
  133. // be uppercased (e.g. `'?A=foo&B=bar'`)
  134. function getParamString(obj, existingUrl, uppercase) {
  135. var params = [];
  136. for (var i in obj) {
  137. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  138. }
  139. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  140. }
  141. var templateRe = /\{ *([\w_ -]+) *\}/g;
  142. // @function template(str: String, data: Object): String
  143. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  144. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  145. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  146. // data values — they will be evaluated passing `data` as an argument.
  147. function template(str, data) {
  148. return str.replace(templateRe, function (str, key) {
  149. var value = data[key];
  150. if (value === undefined) {
  151. throw new Error('No value provided for variable ' + str);
  152. } else if (typeof value === 'function') {
  153. value = value(data);
  154. }
  155. return value;
  156. });
  157. }
  158. // @function isArray(obj): Boolean
  159. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  160. var isArray = Array.isArray || function (obj) {
  161. return (Object.prototype.toString.call(obj) === '[object Array]');
  162. };
  163. // @function indexOf(array: Array, el: Object): Number
  164. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  165. function indexOf(array, el) {
  166. for (var i = 0; i < array.length; i++) {
  167. if (array[i] === el) { return i; }
  168. }
  169. return -1;
  170. }
  171. // @property emptyImageUrl: String
  172. // Data URI string containing a base64-encoded empty GIF image.
  173. // Used as a hack to free memory from unused images on WebKit-powered
  174. // mobile devices (by setting image `src` to this string).
  175. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  176. // inspired by https://paulirish.com/2011/requestanimationframe-for-smart-animating/
  177. function getPrefixed(name) {
  178. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  179. }
  180. var lastTime = 0;
  181. // fallback for IE 7-8
  182. function timeoutDefer(fn) {
  183. var time = +new Date(),
  184. timeToCall = Math.max(0, 16 - (time - lastTime));
  185. lastTime = time + timeToCall;
  186. return window.setTimeout(fn, timeToCall);
  187. }
  188. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  189. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  190. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  191. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  192. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  193. // `context` if given. When `immediate` is set, `fn` is called immediately if
  194. // the browser doesn't have native support for
  195. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  196. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  197. function requestAnimFrame(fn, context, immediate) {
  198. if (immediate && requestFn === timeoutDefer) {
  199. fn.call(context);
  200. } else {
  201. return requestFn.call(window, bind(fn, context));
  202. }
  203. }
  204. // @function cancelAnimFrame(id: Number): undefined
  205. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  206. function cancelAnimFrame(id) {
  207. if (id) {
  208. cancelFn.call(window, id);
  209. }
  210. }
  211. var Util = {
  212. __proto__: null,
  213. extend: extend,
  214. create: create$2,
  215. bind: bind,
  216. get lastId () { return lastId; },
  217. stamp: stamp,
  218. throttle: throttle,
  219. wrapNum: wrapNum,
  220. falseFn: falseFn,
  221. formatNum: formatNum,
  222. trim: trim,
  223. splitWords: splitWords,
  224. setOptions: setOptions,
  225. getParamString: getParamString,
  226. template: template,
  227. isArray: isArray,
  228. indexOf: indexOf,
  229. emptyImageUrl: emptyImageUrl,
  230. requestFn: requestFn,
  231. cancelFn: cancelFn,
  232. requestAnimFrame: requestAnimFrame,
  233. cancelAnimFrame: cancelAnimFrame
  234. };
  235. // @class Class
  236. // @aka L.Class
  237. // @section
  238. // @uninheritable
  239. // Thanks to John Resig and Dean Edwards for inspiration!
  240. function Class() {}
  241. Class.extend = function (props) {
  242. // @function extend(props: Object): Function
  243. // [Extends the current class](#class-inheritance) given the properties to be included.
  244. // Returns a Javascript function that is a class constructor (to be called with `new`).
  245. var NewClass = function () {
  246. setOptions(this);
  247. // call the constructor
  248. if (this.initialize) {
  249. this.initialize.apply(this, arguments);
  250. }
  251. // call all constructor hooks
  252. this.callInitHooks();
  253. };
  254. var parentProto = NewClass.__super__ = this.prototype;
  255. var proto = create$2(parentProto);
  256. proto.constructor = NewClass;
  257. NewClass.prototype = proto;
  258. // inherit parent's statics
  259. for (var i in this) {
  260. if (Object.prototype.hasOwnProperty.call(this, i) && i !== 'prototype' && i !== '__super__') {
  261. NewClass[i] = this[i];
  262. }
  263. }
  264. // mix static properties into the class
  265. if (props.statics) {
  266. extend(NewClass, props.statics);
  267. }
  268. // mix includes into the prototype
  269. if (props.includes) {
  270. checkDeprecatedMixinEvents(props.includes);
  271. extend.apply(null, [proto].concat(props.includes));
  272. }
  273. // mix given properties into the prototype
  274. extend(proto, props);
  275. delete proto.statics;
  276. delete proto.includes;
  277. // merge options
  278. if (proto.options) {
  279. proto.options = parentProto.options ? create$2(parentProto.options) : {};
  280. extend(proto.options, props.options);
  281. }
  282. proto._initHooks = [];
  283. // add method for calling all hooks
  284. proto.callInitHooks = function () {
  285. if (this._initHooksCalled) { return; }
  286. if (parentProto.callInitHooks) {
  287. parentProto.callInitHooks.call(this);
  288. }
  289. this._initHooksCalled = true;
  290. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  291. proto._initHooks[i].call(this);
  292. }
  293. };
  294. return NewClass;
  295. };
  296. // @function include(properties: Object): this
  297. // [Includes a mixin](#class-includes) into the current class.
  298. Class.include = function (props) {
  299. var parentOptions = this.prototype.options;
  300. extend(this.prototype, props);
  301. if (props.options) {
  302. this.prototype.options = parentOptions;
  303. this.mergeOptions(props.options);
  304. }
  305. return this;
  306. };
  307. // @function mergeOptions(options: Object): this
  308. // [Merges `options`](#class-options) into the defaults of the class.
  309. Class.mergeOptions = function (options) {
  310. extend(this.prototype.options, options);
  311. return this;
  312. };
  313. // @function addInitHook(fn: Function): this
  314. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  315. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  316. var args = Array.prototype.slice.call(arguments, 1);
  317. var init = typeof fn === 'function' ? fn : function () {
  318. this[fn].apply(this, args);
  319. };
  320. this.prototype._initHooks = this.prototype._initHooks || [];
  321. this.prototype._initHooks.push(init);
  322. return this;
  323. };
  324. function checkDeprecatedMixinEvents(includes) {
  325. if (typeof L === 'undefined' || !L || !L.Mixin) { return; }
  326. includes = isArray(includes) ? includes : [includes];
  327. for (var i = 0; i < includes.length; i++) {
  328. if (includes[i] === L.Mixin.Events) {
  329. console.warn('Deprecated include of L.Mixin.Events: ' +
  330. 'this property will be removed in future releases, ' +
  331. 'please inherit from L.Evented instead.', new Error().stack);
  332. }
  333. }
  334. }
  335. /*
  336. * @class Evented
  337. * @aka L.Evented
  338. * @inherits Class
  339. *
  340. * 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).
  341. *
  342. * @example
  343. *
  344. * ```js
  345. * map.on('click', function(e) {
  346. * alert(e.latlng);
  347. * } );
  348. * ```
  349. *
  350. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  351. *
  352. * ```js
  353. * function onClick(e) { ... }
  354. *
  355. * map.on('click', onClick);
  356. * map.off('click', onClick);
  357. * ```
  358. */
  359. var Events = {
  360. /* @method on(type: String, fn: Function, context?: Object): this
  361. * 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'`).
  362. *
  363. * @alternative
  364. * @method on(eventMap: Object): this
  365. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  366. */
  367. on: function (types, fn, context) {
  368. // types can be a map of types/handlers
  369. if (typeof types === 'object') {
  370. for (var type in types) {
  371. // we don't process space-separated events here for performance;
  372. // it's a hot path since Layer uses the on(obj) syntax
  373. this._on(type, types[type], fn);
  374. }
  375. } else {
  376. // types can be a string of space-separated words
  377. types = splitWords(types);
  378. for (var i = 0, len = types.length; i < len; i++) {
  379. this._on(types[i], fn, context);
  380. }
  381. }
  382. return this;
  383. },
  384. /* @method off(type: String, fn?: Function, context?: Object): this
  385. * 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.
  386. *
  387. * @alternative
  388. * @method off(eventMap: Object): this
  389. * Removes a set of type/listener pairs.
  390. *
  391. * @alternative
  392. * @method off: this
  393. * Removes all listeners to all events on the object. This includes implicitly attached events.
  394. */
  395. off: function (types, fn, context) {
  396. if (!arguments.length) {
  397. // clear all listeners if called without arguments
  398. delete this._events;
  399. } else if (typeof types === 'object') {
  400. for (var type in types) {
  401. this._off(type, types[type], fn);
  402. }
  403. } else {
  404. types = splitWords(types);
  405. var removeAll = arguments.length === 1;
  406. for (var i = 0, len = types.length; i < len; i++) {
  407. if (removeAll) {
  408. this._off(types[i]);
  409. } else {
  410. this._off(types[i], fn, context);
  411. }
  412. }
  413. }
  414. return this;
  415. },
  416. // attach listener (without syntactic sugar now)
  417. _on: function (type, fn, context, _once) {
  418. if (typeof fn !== 'function') {
  419. console.warn('wrong listener type: ' + typeof fn);
  420. return;
  421. }
  422. // check if fn already there
  423. if (this._listens(type, fn, context) !== false) {
  424. return;
  425. }
  426. if (context === this) {
  427. // Less memory footprint.
  428. context = undefined;
  429. }
  430. var newListener = {fn: fn, ctx: context};
  431. if (_once) {
  432. newListener.once = true;
  433. }
  434. this._events = this._events || {};
  435. this._events[type] = this._events[type] || [];
  436. this._events[type].push(newListener);
  437. },
  438. _off: function (type, fn, context) {
  439. var listeners,
  440. i,
  441. len;
  442. if (!this._events) {
  443. return;
  444. }
  445. listeners = this._events[type];
  446. if (!listeners) {
  447. return;
  448. }
  449. if (arguments.length === 1) { // remove all
  450. if (this._firingCount) {
  451. // Set all removed listeners to noop
  452. // so they are not called if remove happens in fire
  453. for (i = 0, len = listeners.length; i < len; i++) {
  454. listeners[i].fn = falseFn;
  455. }
  456. }
  457. // clear all listeners for a type if function isn't specified
  458. delete this._events[type];
  459. return;
  460. }
  461. if (typeof fn !== 'function') {
  462. console.warn('wrong listener type: ' + typeof fn);
  463. return;
  464. }
  465. // find fn and remove it
  466. var index = this._listens(type, fn, context);
  467. if (index !== false) {
  468. var listener = listeners[index];
  469. if (this._firingCount) {
  470. // set the removed listener to noop so that's not called if remove happens in fire
  471. listener.fn = falseFn;
  472. /* copy array in case events are being fired */
  473. this._events[type] = listeners = listeners.slice();
  474. }
  475. listeners.splice(index, 1);
  476. }
  477. },
  478. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  479. // Fires an event of the specified type. You can optionally provide a data
  480. // object — the first argument of the listener function will contain its
  481. // properties. The event can optionally be propagated to event parents.
  482. fire: function (type, data, propagate) {
  483. if (!this.listens(type, propagate)) { return this; }
  484. var event = extend({}, data, {
  485. type: type,
  486. target: this,
  487. sourceTarget: data && data.sourceTarget || this
  488. });
  489. if (this._events) {
  490. var listeners = this._events[type];
  491. if (listeners) {
  492. this._firingCount = (this._firingCount + 1) || 1;
  493. for (var i = 0, len = listeners.length; i < len; i++) {
  494. var l = listeners[i];
  495. // off overwrites l.fn, so we need to copy fn to a var
  496. var fn = l.fn;
  497. if (l.once) {
  498. this.off(type, fn, l.ctx);
  499. }
  500. fn.call(l.ctx || this, event);
  501. }
  502. this._firingCount--;
  503. }
  504. }
  505. if (propagate) {
  506. // propagate the event to parents (set with addEventParent)
  507. this._propagateEvent(event);
  508. }
  509. return this;
  510. },
  511. // @method listens(type: String, propagate?: Boolean): Boolean
  512. // @method listens(type: String, fn: Function, context?: Object, propagate?: Boolean): Boolean
  513. // Returns `true` if a particular event type has any listeners attached to it.
  514. // The verification can optionally be propagated, it will return `true` if parents have the listener attached to it.
  515. listens: function (type, fn, context, propagate) {
  516. if (typeof type !== 'string') {
  517. console.warn('"string" type argument expected');
  518. }
  519. // we don't overwrite the input `fn` value, because we need to use it for propagation
  520. var _fn = fn;
  521. if (typeof fn !== 'function') {
  522. propagate = !!fn;
  523. _fn = undefined;
  524. context = undefined;
  525. }
  526. var listeners = this._events && this._events[type];
  527. if (listeners && listeners.length) {
  528. if (this._listens(type, _fn, context) !== false) {
  529. return true;
  530. }
  531. }
  532. if (propagate) {
  533. // also check parents for listeners if event propagates
  534. for (var id in this._eventParents) {
  535. if (this._eventParents[id].listens(type, fn, context, propagate)) { return true; }
  536. }
  537. }
  538. return false;
  539. },
  540. // returns the index (number) or false
  541. _listens: function (type, fn, context) {
  542. if (!this._events) {
  543. return false;
  544. }
  545. var listeners = this._events[type] || [];
  546. if (!fn) {
  547. return !!listeners.length;
  548. }
  549. if (context === this) {
  550. // Less memory footprint.
  551. context = undefined;
  552. }
  553. for (var i = 0, len = listeners.length; i < len; i++) {
  554. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  555. return i;
  556. }
  557. }
  558. return false;
  559. },
  560. // @method once(…): this
  561. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  562. once: function (types, fn, context) {
  563. // types can be a map of types/handlers
  564. if (typeof types === 'object') {
  565. for (var type in types) {
  566. // we don't process space-separated events here for performance;
  567. // it's a hot path since Layer uses the on(obj) syntax
  568. this._on(type, types[type], fn, true);
  569. }
  570. } else {
  571. // types can be a string of space-separated words
  572. types = splitWords(types);
  573. for (var i = 0, len = types.length; i < len; i++) {
  574. this._on(types[i], fn, context, true);
  575. }
  576. }
  577. return this;
  578. },
  579. // @method addEventParent(obj: Evented): this
  580. // Adds an event parent - an `Evented` that will receive propagated events
  581. addEventParent: function (obj) {
  582. this._eventParents = this._eventParents || {};
  583. this._eventParents[stamp(obj)] = obj;
  584. return this;
  585. },
  586. // @method removeEventParent(obj: Evented): this
  587. // Removes an event parent, so it will stop receiving propagated events
  588. removeEventParent: function (obj) {
  589. if (this._eventParents) {
  590. delete this._eventParents[stamp(obj)];
  591. }
  592. return this;
  593. },
  594. _propagateEvent: function (e) {
  595. for (var id in this._eventParents) {
  596. this._eventParents[id].fire(e.type, extend({
  597. layer: e.target,
  598. propagatedFrom: e.target
  599. }, e), true);
  600. }
  601. }
  602. };
  603. // aliases; we should ditch those eventually
  604. // @method addEventListener(…): this
  605. // Alias to [`on(…)`](#evented-on)
  606. Events.addEventListener = Events.on;
  607. // @method removeEventListener(…): this
  608. // Alias to [`off(…)`](#evented-off)
  609. // @method clearAllEventListeners(…): this
  610. // Alias to [`off()`](#evented-off)
  611. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  612. // @method addOneTimeEventListener(…): this
  613. // Alias to [`once(…)`](#evented-once)
  614. Events.addOneTimeEventListener = Events.once;
  615. // @method fireEvent(…): this
  616. // Alias to [`fire(…)`](#evented-fire)
  617. Events.fireEvent = Events.fire;
  618. // @method hasEventListeners(…): Boolean
  619. // Alias to [`listens(…)`](#evented-listens)
  620. Events.hasEventListeners = Events.listens;
  621. var Evented = Class.extend(Events);
  622. /*
  623. * @class Point
  624. * @aka L.Point
  625. *
  626. * Represents a point with `x` and `y` coordinates in pixels.
  627. *
  628. * @example
  629. *
  630. * ```js
  631. * var point = L.point(200, 300);
  632. * ```
  633. *
  634. * 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:
  635. *
  636. * ```js
  637. * map.panBy([200, 300]);
  638. * map.panBy(L.point(200, 300));
  639. * ```
  640. *
  641. * Note that `Point` does not inherit from Leaflet's `Class` object,
  642. * which means new classes can't inherit from it, and new methods
  643. * can't be added to it with the `include` function.
  644. */
  645. function Point(x, y, round) {
  646. // @property x: Number; The `x` coordinate of the point
  647. this.x = (round ? Math.round(x) : x);
  648. // @property y: Number; The `y` coordinate of the point
  649. this.y = (round ? Math.round(y) : y);
  650. }
  651. var trunc = Math.trunc || function (v) {
  652. return v > 0 ? Math.floor(v) : Math.ceil(v);
  653. };
  654. Point.prototype = {
  655. // @method clone(): Point
  656. // Returns a copy of the current point.
  657. clone: function () {
  658. return new Point(this.x, this.y);
  659. },
  660. // @method add(otherPoint: Point): Point
  661. // Returns the result of addition of the current and the given points.
  662. add: function (point) {
  663. // non-destructive, returns a new point
  664. return this.clone()._add(toPoint(point));
  665. },
  666. _add: function (point) {
  667. // destructive, used directly for performance in situations where it's safe to modify existing point
  668. this.x += point.x;
  669. this.y += point.y;
  670. return this;
  671. },
  672. // @method subtract(otherPoint: Point): Point
  673. // Returns the result of subtraction of the given point from the current.
  674. subtract: function (point) {
  675. return this.clone()._subtract(toPoint(point));
  676. },
  677. _subtract: function (point) {
  678. this.x -= point.x;
  679. this.y -= point.y;
  680. return this;
  681. },
  682. // @method divideBy(num: Number): Point
  683. // Returns the result of division of the current point by the given number.
  684. divideBy: function (num) {
  685. return this.clone()._divideBy(num);
  686. },
  687. _divideBy: function (num) {
  688. this.x /= num;
  689. this.y /= num;
  690. return this;
  691. },
  692. // @method multiplyBy(num: Number): Point
  693. // Returns the result of multiplication of the current point by the given number.
  694. multiplyBy: function (num) {
  695. return this.clone()._multiplyBy(num);
  696. },
  697. _multiplyBy: function (num) {
  698. this.x *= num;
  699. this.y *= num;
  700. return this;
  701. },
  702. // @method scaleBy(scale: Point): Point
  703. // Multiply each coordinate of the current point by each coordinate of
  704. // `scale`. In linear algebra terms, multiply the point by the
  705. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  706. // defined by `scale`.
  707. scaleBy: function (point) {
  708. return new Point(this.x * point.x, this.y * point.y);
  709. },
  710. // @method unscaleBy(scale: Point): Point
  711. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  712. // each coordinate of `scale`.
  713. unscaleBy: function (point) {
  714. return new Point(this.x / point.x, this.y / point.y);
  715. },
  716. // @method round(): Point
  717. // Returns a copy of the current point with rounded coordinates.
  718. round: function () {
  719. return this.clone()._round();
  720. },
  721. _round: function () {
  722. this.x = Math.round(this.x);
  723. this.y = Math.round(this.y);
  724. return this;
  725. },
  726. // @method floor(): Point
  727. // Returns a copy of the current point with floored coordinates (rounded down).
  728. floor: function () {
  729. return this.clone()._floor();
  730. },
  731. _floor: function () {
  732. this.x = Math.floor(this.x);
  733. this.y = Math.floor(this.y);
  734. return this;
  735. },
  736. // @method ceil(): Point
  737. // Returns a copy of the current point with ceiled coordinates (rounded up).
  738. ceil: function () {
  739. return this.clone()._ceil();
  740. },
  741. _ceil: function () {
  742. this.x = Math.ceil(this.x);
  743. this.y = Math.ceil(this.y);
  744. return this;
  745. },
  746. // @method trunc(): Point
  747. // Returns a copy of the current point with truncated coordinates (rounded towards zero).
  748. trunc: function () {
  749. return this.clone()._trunc();
  750. },
  751. _trunc: function () {
  752. this.x = trunc(this.x);
  753. this.y = trunc(this.y);
  754. return this;
  755. },
  756. // @method distanceTo(otherPoint: Point): Number
  757. // Returns the cartesian distance between the current and the given points.
  758. distanceTo: function (point) {
  759. point = toPoint(point);
  760. var x = point.x - this.x,
  761. y = point.y - this.y;
  762. return Math.sqrt(x * x + y * y);
  763. },
  764. // @method equals(otherPoint: Point): Boolean
  765. // Returns `true` if the given point has the same coordinates.
  766. equals: function (point) {
  767. point = toPoint(point);
  768. return point.x === this.x &&
  769. point.y === this.y;
  770. },
  771. // @method contains(otherPoint: Point): Boolean
  772. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  773. contains: function (point) {
  774. point = toPoint(point);
  775. return Math.abs(point.x) <= Math.abs(this.x) &&
  776. Math.abs(point.y) <= Math.abs(this.y);
  777. },
  778. // @method toString(): String
  779. // Returns a string representation of the point for debugging purposes.
  780. toString: function () {
  781. return 'Point(' +
  782. formatNum(this.x) + ', ' +
  783. formatNum(this.y) + ')';
  784. }
  785. };
  786. // @factory L.point(x: Number, y: Number, round?: Boolean)
  787. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  788. // @alternative
  789. // @factory L.point(coords: Number[])
  790. // Expects an array of the form `[x, y]` instead.
  791. // @alternative
  792. // @factory L.point(coords: Object)
  793. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  794. function toPoint(x, y, round) {
  795. if (x instanceof Point) {
  796. return x;
  797. }
  798. if (isArray(x)) {
  799. return new Point(x[0], x[1]);
  800. }
  801. if (x === undefined || x === null) {
  802. return x;
  803. }
  804. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  805. return new Point(x.x, x.y);
  806. }
  807. return new Point(x, y, round);
  808. }
  809. /*
  810. * @class Bounds
  811. * @aka L.Bounds
  812. *
  813. * Represents a rectangular area in pixel coordinates.
  814. *
  815. * @example
  816. *
  817. * ```js
  818. * var p1 = L.point(10, 10),
  819. * p2 = L.point(40, 60),
  820. * bounds = L.bounds(p1, p2);
  821. * ```
  822. *
  823. * 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:
  824. *
  825. * ```js
  826. * otherBounds.intersects([[10, 10], [40, 60]]);
  827. * ```
  828. *
  829. * Note that `Bounds` does not inherit from Leaflet's `Class` object,
  830. * which means new classes can't inherit from it, and new methods
  831. * can't be added to it with the `include` function.
  832. */
  833. function Bounds(a, b) {
  834. if (!a) { return; }
  835. var points = b ? [a, b] : a;
  836. for (var i = 0, len = points.length; i < len; i++) {
  837. this.extend(points[i]);
  838. }
  839. }
  840. Bounds.prototype = {
  841. // @method extend(point: Point): this
  842. // Extends the bounds to contain the given point.
  843. // @alternative
  844. // @method extend(otherBounds: Bounds): this
  845. // Extend the bounds to contain the given bounds
  846. extend: function (obj) {
  847. var min2, max2;
  848. if (!obj) { return this; }
  849. if (obj instanceof Point || typeof obj[0] === 'number' || 'x' in obj) {
  850. min2 = max2 = toPoint(obj);
  851. } else {
  852. obj = toBounds(obj);
  853. min2 = obj.min;
  854. max2 = obj.max;
  855. if (!min2 || !max2) { return this; }
  856. }
  857. // @property min: Point
  858. // The top left corner of the rectangle.
  859. // @property max: Point
  860. // The bottom right corner of the rectangle.
  861. if (!this.min && !this.max) {
  862. this.min = min2.clone();
  863. this.max = max2.clone();
  864. } else {
  865. this.min.x = Math.min(min2.x, this.min.x);
  866. this.max.x = Math.max(max2.x, this.max.x);
  867. this.min.y = Math.min(min2.y, this.min.y);
  868. this.max.y = Math.max(max2.y, this.max.y);
  869. }
  870. return this;
  871. },
  872. // @method getCenter(round?: Boolean): Point
  873. // Returns the center point of the bounds.
  874. getCenter: function (round) {
  875. return toPoint(
  876. (this.min.x + this.max.x) / 2,
  877. (this.min.y + this.max.y) / 2, round);
  878. },
  879. // @method getBottomLeft(): Point
  880. // Returns the bottom-left point of the bounds.
  881. getBottomLeft: function () {
  882. return toPoint(this.min.x, this.max.y);
  883. },
  884. // @method getTopRight(): Point
  885. // Returns the top-right point of the bounds.
  886. getTopRight: function () { // -> Point
  887. return toPoint(this.max.x, this.min.y);
  888. },
  889. // @method getTopLeft(): Point
  890. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  891. getTopLeft: function () {
  892. return this.min; // left, top
  893. },
  894. // @method getBottomRight(): Point
  895. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  896. getBottomRight: function () {
  897. return this.max; // right, bottom
  898. },
  899. // @method getSize(): Point
  900. // Returns the size of the given bounds
  901. getSize: function () {
  902. return this.max.subtract(this.min);
  903. },
  904. // @method contains(otherBounds: Bounds): Boolean
  905. // Returns `true` if the rectangle contains the given one.
  906. // @alternative
  907. // @method contains(point: Point): Boolean
  908. // Returns `true` if the rectangle contains the given point.
  909. contains: function (obj) {
  910. var min, max;
  911. if (typeof obj[0] === 'number' || obj instanceof Point) {
  912. obj = toPoint(obj);
  913. } else {
  914. obj = toBounds(obj);
  915. }
  916. if (obj instanceof Bounds) {
  917. min = obj.min;
  918. max = obj.max;
  919. } else {
  920. min = max = obj;
  921. }
  922. return (min.x >= this.min.x) &&
  923. (max.x <= this.max.x) &&
  924. (min.y >= this.min.y) &&
  925. (max.y <= this.max.y);
  926. },
  927. // @method intersects(otherBounds: Bounds): Boolean
  928. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  929. // intersect if they have at least one point in common.
  930. intersects: function (bounds) { // (Bounds) -> Boolean
  931. bounds = toBounds(bounds);
  932. var min = this.min,
  933. max = this.max,
  934. min2 = bounds.min,
  935. max2 = bounds.max,
  936. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  937. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  938. return xIntersects && yIntersects;
  939. },
  940. // @method overlaps(otherBounds: Bounds): Boolean
  941. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  942. // overlap if their intersection is an area.
  943. overlaps: function (bounds) { // (Bounds) -> Boolean
  944. bounds = toBounds(bounds);
  945. var min = this.min,
  946. max = this.max,
  947. min2 = bounds.min,
  948. max2 = bounds.max,
  949. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  950. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  951. return xOverlaps && yOverlaps;
  952. },
  953. // @method isValid(): Boolean
  954. // Returns `true` if the bounds are properly initialized.
  955. isValid: function () {
  956. return !!(this.min && this.max);
  957. },
  958. // @method pad(bufferRatio: Number): Bounds
  959. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  960. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  961. // Negative values will retract the bounds.
  962. pad: function (bufferRatio) {
  963. var min = this.min,
  964. max = this.max,
  965. heightBuffer = Math.abs(min.x - max.x) * bufferRatio,
  966. widthBuffer = Math.abs(min.y - max.y) * bufferRatio;
  967. return toBounds(
  968. toPoint(min.x - heightBuffer, min.y - widthBuffer),
  969. toPoint(max.x + heightBuffer, max.y + widthBuffer));
  970. },
  971. // @method equals(otherBounds: Bounds): Boolean
  972. // Returns `true` if the rectangle is equivalent to the given bounds.
  973. equals: function (bounds) {
  974. if (!bounds) { return false; }
  975. bounds = toBounds(bounds);
  976. return this.min.equals(bounds.getTopLeft()) &&
  977. this.max.equals(bounds.getBottomRight());
  978. },
  979. };
  980. // @factory L.bounds(corner1: Point, corner2: Point)
  981. // Creates a Bounds object from two corners coordinate pairs.
  982. // @alternative
  983. // @factory L.bounds(points: Point[])
  984. // Creates a Bounds object from the given array of points.
  985. function toBounds(a, b) {
  986. if (!a || a instanceof Bounds) {
  987. return a;
  988. }
  989. return new Bounds(a, b);
  990. }
  991. /*
  992. * @class LatLngBounds
  993. * @aka L.LatLngBounds
  994. *
  995. * Represents a rectangular geographical area on a map.
  996. *
  997. * @example
  998. *
  999. * ```js
  1000. * var corner1 = L.latLng(40.712, -74.227),
  1001. * corner2 = L.latLng(40.774, -74.125),
  1002. * bounds = L.latLngBounds(corner1, corner2);
  1003. * ```
  1004. *
  1005. * 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:
  1006. *
  1007. * ```js
  1008. * map.fitBounds([
  1009. * [40.712, -74.227],
  1010. * [40.774, -74.125]
  1011. * ]);
  1012. * ```
  1013. *
  1014. * 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.
  1015. *
  1016. * Note that `LatLngBounds` does not inherit from Leaflet's `Class` object,
  1017. * which means new classes can't inherit from it, and new methods
  1018. * can't be added to it with the `include` function.
  1019. */
  1020. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  1021. if (!corner1) { return; }
  1022. var latlngs = corner2 ? [corner1, corner2] : corner1;
  1023. for (var i = 0, len = latlngs.length; i < len; i++) {
  1024. this.extend(latlngs[i]);
  1025. }
  1026. }
  1027. LatLngBounds.prototype = {
  1028. // @method extend(latlng: LatLng): this
  1029. // Extend the bounds to contain the given point
  1030. // @alternative
  1031. // @method extend(otherBounds: LatLngBounds): this
  1032. // Extend the bounds to contain the given bounds
  1033. extend: function (obj) {
  1034. var sw = this._southWest,
  1035. ne = this._northEast,
  1036. sw2, ne2;
  1037. if (obj instanceof LatLng) {
  1038. sw2 = obj;
  1039. ne2 = obj;
  1040. } else if (obj instanceof LatLngBounds) {
  1041. sw2 = obj._southWest;
  1042. ne2 = obj._northEast;
  1043. if (!sw2 || !ne2) { return this; }
  1044. } else {
  1045. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  1046. }
  1047. if (!sw && !ne) {
  1048. this._southWest = new LatLng(sw2.lat, sw2.lng);
  1049. this._northEast = new LatLng(ne2.lat, ne2.lng);
  1050. } else {
  1051. sw.lat = Math.min(sw2.lat, sw.lat);
  1052. sw.lng = Math.min(sw2.lng, sw.lng);
  1053. ne.lat = Math.max(ne2.lat, ne.lat);
  1054. ne.lng = Math.max(ne2.lng, ne.lng);
  1055. }
  1056. return this;
  1057. },
  1058. // @method pad(bufferRatio: Number): LatLngBounds
  1059. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  1060. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  1061. // Negative values will retract the bounds.
  1062. pad: function (bufferRatio) {
  1063. var sw = this._southWest,
  1064. ne = this._northEast,
  1065. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  1066. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  1067. return new LatLngBounds(
  1068. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  1069. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  1070. },
  1071. // @method getCenter(): LatLng
  1072. // Returns the center point of the bounds.
  1073. getCenter: function () {
  1074. return new LatLng(
  1075. (this._southWest.lat + this._northEast.lat) / 2,
  1076. (this._southWest.lng + this._northEast.lng) / 2);
  1077. },
  1078. // @method getSouthWest(): LatLng
  1079. // Returns the south-west point of the bounds.
  1080. getSouthWest: function () {
  1081. return this._southWest;
  1082. },
  1083. // @method getNorthEast(): LatLng
  1084. // Returns the north-east point of the bounds.
  1085. getNorthEast: function () {
  1086. return this._northEast;
  1087. },
  1088. // @method getNorthWest(): LatLng
  1089. // Returns the north-west point of the bounds.
  1090. getNorthWest: function () {
  1091. return new LatLng(this.getNorth(), this.getWest());
  1092. },
  1093. // @method getSouthEast(): LatLng
  1094. // Returns the south-east point of the bounds.
  1095. getSouthEast: function () {
  1096. return new LatLng(this.getSouth(), this.getEast());
  1097. },
  1098. // @method getWest(): Number
  1099. // Returns the west longitude of the bounds
  1100. getWest: function () {
  1101. return this._southWest.lng;
  1102. },
  1103. // @method getSouth(): Number
  1104. // Returns the south latitude of the bounds
  1105. getSouth: function () {
  1106. return this._southWest.lat;
  1107. },
  1108. // @method getEast(): Number
  1109. // Returns the east longitude of the bounds
  1110. getEast: function () {
  1111. return this._northEast.lng;
  1112. },
  1113. // @method getNorth(): Number
  1114. // Returns the north latitude of the bounds
  1115. getNorth: function () {
  1116. return this._northEast.lat;
  1117. },
  1118. // @method contains(otherBounds: LatLngBounds): Boolean
  1119. // Returns `true` if the rectangle contains the given one.
  1120. // @alternative
  1121. // @method contains (latlng: LatLng): Boolean
  1122. // Returns `true` if the rectangle contains the given point.
  1123. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1124. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1125. obj = toLatLng(obj);
  1126. } else {
  1127. obj = toLatLngBounds(obj);
  1128. }
  1129. var sw = this._southWest,
  1130. ne = this._northEast,
  1131. sw2, ne2;
  1132. if (obj instanceof LatLngBounds) {
  1133. sw2 = obj.getSouthWest();
  1134. ne2 = obj.getNorthEast();
  1135. } else {
  1136. sw2 = ne2 = obj;
  1137. }
  1138. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1139. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1140. },
  1141. // @method intersects(otherBounds: LatLngBounds): Boolean
  1142. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1143. intersects: function (bounds) {
  1144. bounds = toLatLngBounds(bounds);
  1145. var sw = this._southWest,
  1146. ne = this._northEast,
  1147. sw2 = bounds.getSouthWest(),
  1148. ne2 = bounds.getNorthEast(),
  1149. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1150. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1151. return latIntersects && lngIntersects;
  1152. },
  1153. // @method overlaps(otherBounds: LatLngBounds): Boolean
  1154. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1155. overlaps: function (bounds) {
  1156. bounds = toLatLngBounds(bounds);
  1157. var sw = this._southWest,
  1158. ne = this._northEast,
  1159. sw2 = bounds.getSouthWest(),
  1160. ne2 = bounds.getNorthEast(),
  1161. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1162. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1163. return latOverlaps && lngOverlaps;
  1164. },
  1165. // @method toBBoxString(): String
  1166. // 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.
  1167. toBBoxString: function () {
  1168. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1169. },
  1170. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1171. // 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.
  1172. equals: function (bounds, maxMargin) {
  1173. if (!bounds) { return false; }
  1174. bounds = toLatLngBounds(bounds);
  1175. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1176. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1177. },
  1178. // @method isValid(): Boolean
  1179. // Returns `true` if the bounds are properly initialized.
  1180. isValid: function () {
  1181. return !!(this._southWest && this._northEast);
  1182. }
  1183. };
  1184. // TODO International date line?
  1185. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1186. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1187. // @alternative
  1188. // @factory L.latLngBounds(latlngs: LatLng[])
  1189. // 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).
  1190. function toLatLngBounds(a, b) {
  1191. if (a instanceof LatLngBounds) {
  1192. return a;
  1193. }
  1194. return new LatLngBounds(a, b);
  1195. }
  1196. /* @class LatLng
  1197. * @aka L.LatLng
  1198. *
  1199. * Represents a geographical point with a certain latitude and longitude.
  1200. *
  1201. * @example
  1202. *
  1203. * ```
  1204. * var latlng = L.latLng(50.5, 30.5);
  1205. * ```
  1206. *
  1207. * 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:
  1208. *
  1209. * ```
  1210. * map.panTo([50, 30]);
  1211. * map.panTo({lon: 30, lat: 50});
  1212. * map.panTo({lat: 50, lng: 30});
  1213. * map.panTo(L.latLng(50, 30));
  1214. * ```
  1215. *
  1216. * Note that `LatLng` does not inherit from Leaflet's `Class` object,
  1217. * which means new classes can't inherit from it, and new methods
  1218. * can't be added to it with the `include` function.
  1219. */
  1220. function LatLng(lat, lng, alt) {
  1221. if (isNaN(lat) || isNaN(lng)) {
  1222. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1223. }
  1224. // @property lat: Number
  1225. // Latitude in degrees
  1226. this.lat = +lat;
  1227. // @property lng: Number
  1228. // Longitude in degrees
  1229. this.lng = +lng;
  1230. // @property alt: Number
  1231. // Altitude in meters (optional)
  1232. if (alt !== undefined) {
  1233. this.alt = +alt;
  1234. }
  1235. }
  1236. LatLng.prototype = {
  1237. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1238. // 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.
  1239. equals: function (obj, maxMargin) {
  1240. if (!obj) { return false; }
  1241. obj = toLatLng(obj);
  1242. var margin = Math.max(
  1243. Math.abs(this.lat - obj.lat),
  1244. Math.abs(this.lng - obj.lng));
  1245. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1246. },
  1247. // @method toString(): String
  1248. // Returns a string representation of the point (for debugging purposes).
  1249. toString: function (precision) {
  1250. return 'LatLng(' +
  1251. formatNum(this.lat, precision) + ', ' +
  1252. formatNum(this.lng, precision) + ')';
  1253. },
  1254. // @method distanceTo(otherLatLng: LatLng): Number
  1255. // 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).
  1256. distanceTo: function (other) {
  1257. return Earth.distance(this, toLatLng(other));
  1258. },
  1259. // @method wrap(): LatLng
  1260. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1261. wrap: function () {
  1262. return Earth.wrapLatLng(this);
  1263. },
  1264. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1265. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1266. toBounds: function (sizeInMeters) {
  1267. var latAccuracy = 180 * sizeInMeters / 40075017,
  1268. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1269. return toLatLngBounds(
  1270. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1271. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1272. },
  1273. clone: function () {
  1274. return new LatLng(this.lat, this.lng, this.alt);
  1275. }
  1276. };
  1277. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1278. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1279. // @alternative
  1280. // @factory L.latLng(coords: Array): LatLng
  1281. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1282. // @alternative
  1283. // @factory L.latLng(coords: Object): LatLng
  1284. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1285. function toLatLng(a, b, c) {
  1286. if (a instanceof LatLng) {
  1287. return a;
  1288. }
  1289. if (isArray(a) && typeof a[0] !== 'object') {
  1290. if (a.length === 3) {
  1291. return new LatLng(a[0], a[1], a[2]);
  1292. }
  1293. if (a.length === 2) {
  1294. return new LatLng(a[0], a[1]);
  1295. }
  1296. return null;
  1297. }
  1298. if (a === undefined || a === null) {
  1299. return a;
  1300. }
  1301. if (typeof a === 'object' && 'lat' in a) {
  1302. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1303. }
  1304. if (b === undefined) {
  1305. return null;
  1306. }
  1307. return new LatLng(a, b, c);
  1308. }
  1309. /*
  1310. * @namespace CRS
  1311. * @crs L.CRS.Base
  1312. * Object that defines coordinate reference systems for projecting
  1313. * geographical points into pixel (screen) coordinates and back (and to
  1314. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1315. * [spatial reference system](https://en.wikipedia.org/wiki/Spatial_reference_system).
  1316. *
  1317. * Leaflet defines the most usual CRSs by default. If you want to use a
  1318. * CRS not defined by default, take a look at the
  1319. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1320. *
  1321. * Note that the CRS instances do not inherit from Leaflet's `Class` object,
  1322. * and can't be instantiated. Also, new classes can't inherit from them,
  1323. * and methods can't be added to them with the `include` function.
  1324. */
  1325. var CRS = {
  1326. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1327. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1328. latLngToPoint: function (latlng, zoom) {
  1329. var projectedPoint = this.projection.project(latlng),
  1330. scale = this.scale(zoom);
  1331. return this.transformation._transform(projectedPoint, scale);
  1332. },
  1333. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1334. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1335. // zoom into geographical coordinates.
  1336. pointToLatLng: function (point, zoom) {
  1337. var scale = this.scale(zoom),
  1338. untransformedPoint = this.transformation.untransform(point, scale);
  1339. return this.projection.unproject(untransformedPoint);
  1340. },
  1341. // @method project(latlng: LatLng): Point
  1342. // Projects geographical coordinates into coordinates in units accepted for
  1343. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1344. project: function (latlng) {
  1345. return this.projection.project(latlng);
  1346. },
  1347. // @method unproject(point: Point): LatLng
  1348. // Given a projected coordinate returns the corresponding LatLng.
  1349. // The inverse of `project`.
  1350. unproject: function (point) {
  1351. return this.projection.unproject(point);
  1352. },
  1353. // @method scale(zoom: Number): Number
  1354. // Returns the scale used when transforming projected coordinates into
  1355. // pixel coordinates for a particular zoom. For example, it returns
  1356. // `256 * 2^zoom` for Mercator-based CRS.
  1357. scale: function (zoom) {
  1358. return 256 * Math.pow(2, zoom);
  1359. },
  1360. // @method zoom(scale: Number): Number
  1361. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1362. // factor of `scale`.
  1363. zoom: function (scale) {
  1364. return Math.log(scale / 256) / Math.LN2;
  1365. },
  1366. // @method getProjectedBounds(zoom: Number): Bounds
  1367. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1368. getProjectedBounds: function (zoom) {
  1369. if (this.infinite) { return null; }
  1370. var b = this.projection.bounds,
  1371. s = this.scale(zoom),
  1372. min = this.transformation.transform(b.min, s),
  1373. max = this.transformation.transform(b.max, s);
  1374. return new Bounds(min, max);
  1375. },
  1376. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1377. // Returns the distance between two geographical coordinates.
  1378. // @property code: String
  1379. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1380. //
  1381. // @property wrapLng: Number[]
  1382. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1383. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1384. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1385. //
  1386. // @property wrapLat: Number[]
  1387. // Like `wrapLng`, but for the latitude (vertical) axis.
  1388. // wrapLng: [min, max],
  1389. // wrapLat: [min, max],
  1390. // @property infinite: Boolean
  1391. // If true, the coordinate space will be unbounded (infinite in both axes)
  1392. infinite: false,
  1393. // @method wrapLatLng(latlng: LatLng): LatLng
  1394. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1395. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1396. wrapLatLng: function (latlng) {
  1397. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1398. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1399. alt = latlng.alt;
  1400. return new LatLng(lat, lng, alt);
  1401. },
  1402. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1403. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1404. // that its center is within the CRS's bounds.
  1405. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1406. wrapLatLngBounds: function (bounds) {
  1407. var center = bounds.getCenter(),
  1408. newCenter = this.wrapLatLng(center),
  1409. latShift = center.lat - newCenter.lat,
  1410. lngShift = center.lng - newCenter.lng;
  1411. if (latShift === 0 && lngShift === 0) {
  1412. return bounds;
  1413. }
  1414. var sw = bounds.getSouthWest(),
  1415. ne = bounds.getNorthEast(),
  1416. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1417. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1418. return new LatLngBounds(newSw, newNe);
  1419. }
  1420. };
  1421. /*
  1422. * @namespace CRS
  1423. * @crs L.CRS.Earth
  1424. *
  1425. * Serves as the base for CRS that are global such that they cover the earth.
  1426. * Can only be used as the base for other CRS and cannot be used directly,
  1427. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1428. * meters.
  1429. */
  1430. var Earth = extend({}, CRS, {
  1431. wrapLng: [-180, 180],
  1432. // Mean Earth Radius, as recommended for use by
  1433. // the International Union of Geodesy and Geophysics,
  1434. // see https://rosettacode.org/wiki/Haversine_formula
  1435. R: 6371000,
  1436. // distance between two geographical points using spherical law of cosines approximation
  1437. distance: function (latlng1, latlng2) {
  1438. var rad = Math.PI / 180,
  1439. lat1 = latlng1.lat * rad,
  1440. lat2 = latlng2.lat * rad,
  1441. sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
  1442. sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
  1443. a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
  1444. c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1445. return this.R * c;
  1446. }
  1447. });
  1448. /*
  1449. * @namespace Projection
  1450. * @projection L.Projection.SphericalMercator
  1451. *
  1452. * Spherical Mercator projection — the most common projection for online maps,
  1453. * used by almost all free and commercial tile providers. Assumes that Earth is
  1454. * a sphere. Used by the `EPSG:3857` CRS.
  1455. */
  1456. var earthRadius = 6378137;
  1457. var SphericalMercator = {
  1458. R: earthRadius,
  1459. MAX_LATITUDE: 85.0511287798,
  1460. project: function (latlng) {
  1461. var d = Math.PI / 180,
  1462. max = this.MAX_LATITUDE,
  1463. lat = Math.max(Math.min(max, latlng.lat), -max),
  1464. sin = Math.sin(lat * d);
  1465. return new Point(
  1466. this.R * latlng.lng * d,
  1467. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1468. },
  1469. unproject: function (point) {
  1470. var d = 180 / Math.PI;
  1471. return new LatLng(
  1472. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1473. point.x * d / this.R);
  1474. },
  1475. bounds: (function () {
  1476. var d = earthRadius * Math.PI;
  1477. return new Bounds([-d, -d], [d, d]);
  1478. })()
  1479. };
  1480. /*
  1481. * @class Transformation
  1482. * @aka L.Transformation
  1483. *
  1484. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1485. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1486. * the reverse. Used by Leaflet in its projections code.
  1487. *
  1488. * @example
  1489. *
  1490. * ```js
  1491. * var transformation = L.transformation(2, 5, -1, 10),
  1492. * p = L.point(1, 2),
  1493. * p2 = transformation.transform(p), // L.point(7, 8)
  1494. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1495. * ```
  1496. */
  1497. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1498. // Creates a `Transformation` object with the given coefficients.
  1499. function Transformation(a, b, c, d) {
  1500. if (isArray(a)) {
  1501. // use array properties
  1502. this._a = a[0];
  1503. this._b = a[1];
  1504. this._c = a[2];
  1505. this._d = a[3];
  1506. return;
  1507. }
  1508. this._a = a;
  1509. this._b = b;
  1510. this._c = c;
  1511. this._d = d;
  1512. }
  1513. Transformation.prototype = {
  1514. // @method transform(point: Point, scale?: Number): Point
  1515. // Returns a transformed point, optionally multiplied by the given scale.
  1516. // Only accepts actual `L.Point` instances, not arrays.
  1517. transform: function (point, scale) { // (Point, Number) -> Point
  1518. return this._transform(point.clone(), scale);
  1519. },
  1520. // destructive transform (faster)
  1521. _transform: function (point, scale) {
  1522. scale = scale || 1;
  1523. point.x = scale * (this._a * point.x + this._b);
  1524. point.y = scale * (this._c * point.y + this._d);
  1525. return point;
  1526. },
  1527. // @method untransform(point: Point, scale?: Number): Point
  1528. // Returns the reverse transformation of the given point, optionally divided
  1529. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1530. untransform: function (point, scale) {
  1531. scale = scale || 1;
  1532. return new Point(
  1533. (point.x / scale - this._b) / this._a,
  1534. (point.y / scale - this._d) / this._c);
  1535. }
  1536. };
  1537. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1538. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1539. // Instantiates a Transformation object with the given coefficients.
  1540. // @alternative
  1541. // @factory L.transformation(coefficients: Array): Transformation
  1542. // Expects an coefficients array of the form
  1543. // `[a: Number, b: Number, c: Number, d: Number]`.
  1544. function toTransformation(a, b, c, d) {
  1545. return new Transformation(a, b, c, d);
  1546. }
  1547. /*
  1548. * @namespace CRS
  1549. * @crs L.CRS.EPSG3857
  1550. *
  1551. * The most common CRS for online maps, used by almost all free and commercial
  1552. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1553. * Map's `crs` option.
  1554. */
  1555. var EPSG3857 = extend({}, Earth, {
  1556. code: 'EPSG:3857',
  1557. projection: SphericalMercator,
  1558. transformation: (function () {
  1559. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1560. return toTransformation(scale, 0.5, -scale, 0.5);
  1561. }())
  1562. });
  1563. var EPSG900913 = extend({}, EPSG3857, {
  1564. code: 'EPSG:900913'
  1565. });
  1566. // @namespace SVG; @section
  1567. // There are several static functions which can be called without instantiating L.SVG:
  1568. // @function create(name: String): SVGElement
  1569. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1570. // corresponding to the class name passed. For example, using 'line' will return
  1571. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1572. function svgCreate(name) {
  1573. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1574. }
  1575. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1576. // Generates a SVG path string for multiple rings, with each ring turning
  1577. // into "M..L..L.." instructions
  1578. function pointsToPath(rings, closed) {
  1579. var str = '',
  1580. i, j, len, len2, points, p;
  1581. for (i = 0, len = rings.length; i < len; i++) {
  1582. points = rings[i];
  1583. for (j = 0, len2 = points.length; j < len2; j++) {
  1584. p = points[j];
  1585. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1586. }
  1587. // closes the ring for polygons; "x" is VML syntax
  1588. str += closed ? (Browser.svg ? 'z' : 'x') : '';
  1589. }
  1590. // SVG complains about empty path strings
  1591. return str || 'M0 0';
  1592. }
  1593. /*
  1594. * @namespace Browser
  1595. * @aka L.Browser
  1596. *
  1597. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1598. *
  1599. * @example
  1600. *
  1601. * ```js
  1602. * if (L.Browser.ielt9) {
  1603. * alert('Upgrade your browser, dude!');
  1604. * }
  1605. * ```
  1606. */
  1607. var style = document.documentElement.style;
  1608. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1609. var ie = 'ActiveXObject' in window;
  1610. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1611. var ielt9 = ie && !document.addEventListener;
  1612. // @property edge: Boolean; `true` for the Edge web browser.
  1613. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1614. // @property webkit: Boolean;
  1615. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1616. var webkit = userAgentContains('webkit');
  1617. // @property android: Boolean
  1618. // **Deprecated.** `true` for any browser running on an Android platform.
  1619. var android = userAgentContains('android');
  1620. // @property android23: Boolean; **Deprecated.** `true` for browsers running on Android 2 or Android 3.
  1621. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1622. /* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */
  1623. var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit
  1624. // @property androidStock: Boolean; **Deprecated.** `true` for the Android stock browser (i.e. not Chrome)
  1625. var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);
  1626. // @property opera: Boolean; `true` for the Opera browser
  1627. var opera = !!window.opera;
  1628. // @property chrome: Boolean; `true` for the Chrome browser.
  1629. var chrome = !edge && userAgentContains('chrome');
  1630. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1631. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1632. // @property safari: Boolean; `true` for the Safari browser.
  1633. var safari = !chrome && userAgentContains('safari');
  1634. var phantom = userAgentContains('phantom');
  1635. // @property opera12: Boolean
  1636. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1637. var opera12 = 'OTransition' in style;
  1638. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1639. var win = navigator.platform.indexOf('Win') === 0;
  1640. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1641. var ie3d = ie && ('transition' in style);
  1642. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1643. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1644. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1645. var gecko3d = 'MozPerspective' in style;
  1646. // @property any3d: Boolean
  1647. // `true` for all browsers supporting CSS transforms.
  1648. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1649. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1650. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1651. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1652. var mobileWebkit = mobile && webkit;
  1653. // @property mobileWebkit3d: Boolean
  1654. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1655. var mobileWebkit3d = mobile && webkit3d;
  1656. // @property msPointer: Boolean
  1657. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1658. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1659. // @property pointer: Boolean
  1660. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1661. var pointer = !!(window.PointerEvent || msPointer);
  1662. // @property touchNative: Boolean
  1663. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1664. // **This does not necessarily mean** that the browser is running in a computer with
  1665. // a touchscreen, it only means that the browser is capable of understanding
  1666. // touch events.
  1667. var touchNative = 'ontouchstart' in window || !!window.TouchEvent;
  1668. // @property touch: Boolean
  1669. // `true` for all browsers supporting either [touch](#browser-touch) or [pointer](#browser-pointer) events.
  1670. // Note: pointer events will be preferred (if available), and processed for all `touch*` listeners.
  1671. var touch = !window.L_NO_TOUCH && (touchNative || pointer);
  1672. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1673. var mobileOpera = mobile && opera;
  1674. // @property mobileGecko: Boolean
  1675. // `true` for gecko-based browsers running in a mobile device.
  1676. var mobileGecko = mobile && gecko;
  1677. // @property retina: Boolean
  1678. // `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%.
  1679. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1680. // @property passiveEvents: Boolean
  1681. // `true` for browsers that support passive events.
  1682. var passiveEvents = (function () {
  1683. var supportsPassiveOption = false;
  1684. try {
  1685. var opts = Object.defineProperty({}, 'passive', {
  1686. get: function () { // eslint-disable-line getter-return
  1687. supportsPassiveOption = true;
  1688. }
  1689. });
  1690. window.addEventListener('testPassiveEventSupport', falseFn, opts);
  1691. window.removeEventListener('testPassiveEventSupport', falseFn, opts);
  1692. } catch (e) {
  1693. // Errors can safely be ignored since this is only a browser support test.
  1694. }
  1695. return supportsPassiveOption;
  1696. }());
  1697. // @property canvas: Boolean
  1698. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1699. var canvas$1 = (function () {
  1700. return !!document.createElement('canvas').getContext;
  1701. }());
  1702. // @property svg: Boolean
  1703. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1704. var svg$1 = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1705. var inlineSvg = !!svg$1 && (function () {
  1706. var div = document.createElement('div');
  1707. div.innerHTML = '<svg/>';
  1708. return (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg';
  1709. })();
  1710. // @property vml: Boolean
  1711. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1712. var vml = !svg$1 && (function () {
  1713. try {
  1714. var div = document.createElement('div');
  1715. div.innerHTML = '<v:shape adj="1"/>';
  1716. var shape = div.firstChild;
  1717. shape.style.behavior = 'url(#default#VML)';
  1718. return shape && (typeof shape.adj === 'object');
  1719. } catch (e) {
  1720. return false;
  1721. }
  1722. }());
  1723. // @property mac: Boolean; `true` when the browser is running in a Mac platform
  1724. var mac = navigator.platform.indexOf('Mac') === 0;
  1725. // @property mac: Boolean; `true` when the browser is running in a Linux platform
  1726. var linux = navigator.platform.indexOf('Linux') === 0;
  1727. function userAgentContains(str) {
  1728. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1729. }
  1730. var Browser = {
  1731. ie: ie,
  1732. ielt9: ielt9,
  1733. edge: edge,
  1734. webkit: webkit,
  1735. android: android,
  1736. android23: android23,
  1737. androidStock: androidStock,
  1738. opera: opera,
  1739. chrome: chrome,
  1740. gecko: gecko,
  1741. safari: safari,
  1742. phantom: phantom,
  1743. opera12: opera12,
  1744. win: win,
  1745. ie3d: ie3d,
  1746. webkit3d: webkit3d,
  1747. gecko3d: gecko3d,
  1748. any3d: any3d,
  1749. mobile: mobile,
  1750. mobileWebkit: mobileWebkit,
  1751. mobileWebkit3d: mobileWebkit3d,
  1752. msPointer: msPointer,
  1753. pointer: pointer,
  1754. touch: touch,
  1755. touchNative: touchNative,
  1756. mobileOpera: mobileOpera,
  1757. mobileGecko: mobileGecko,
  1758. retina: retina,
  1759. passiveEvents: passiveEvents,
  1760. canvas: canvas$1,
  1761. svg: svg$1,
  1762. vml: vml,
  1763. inlineSvg: inlineSvg,
  1764. mac: mac,
  1765. linux: linux
  1766. };
  1767. /*
  1768. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1769. */
  1770. var POINTER_DOWN = Browser.msPointer ? 'MSPointerDown' : 'pointerdown';
  1771. var POINTER_MOVE = Browser.msPointer ? 'MSPointerMove' : 'pointermove';
  1772. var POINTER_UP = Browser.msPointer ? 'MSPointerUp' : 'pointerup';
  1773. var POINTER_CANCEL = Browser.msPointer ? 'MSPointerCancel' : 'pointercancel';
  1774. var pEvent = {
  1775. touchstart : POINTER_DOWN,
  1776. touchmove : POINTER_MOVE,
  1777. touchend : POINTER_UP,
  1778. touchcancel : POINTER_CANCEL
  1779. };
  1780. var handle = {
  1781. touchstart : _onPointerStart,
  1782. touchmove : _handlePointer,
  1783. touchend : _handlePointer,
  1784. touchcancel : _handlePointer
  1785. };
  1786. var _pointers = {};
  1787. var _pointerDocListener = false;
  1788. // Provides a touch events wrapper for (ms)pointer events.
  1789. // ref https://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1790. function addPointerListener(obj, type, handler) {
  1791. if (type === 'touchstart') {
  1792. _addPointerDocListener();
  1793. }
  1794. if (!handle[type]) {
  1795. console.warn('wrong event specified:', type);
  1796. return L.Util.falseFn;
  1797. }
  1798. handler = handle[type].bind(this, handler);
  1799. obj.addEventListener(pEvent[type], handler, false);
  1800. return handler;
  1801. }
  1802. function removePointerListener(obj, type, handler) {
  1803. if (!pEvent[type]) {
  1804. console.warn('wrong event specified:', type);
  1805. return;
  1806. }
  1807. obj.removeEventListener(pEvent[type], handler, false);
  1808. }
  1809. function _globalPointerDown(e) {
  1810. _pointers[e.pointerId] = e;
  1811. }
  1812. function _globalPointerMove(e) {
  1813. if (_pointers[e.pointerId]) {
  1814. _pointers[e.pointerId] = e;
  1815. }
  1816. }
  1817. function _globalPointerUp(e) {
  1818. delete _pointers[e.pointerId];
  1819. }
  1820. function _addPointerDocListener() {
  1821. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1822. if (!_pointerDocListener) {
  1823. // we listen document as any drags that end by moving the touch off the screen get fired there
  1824. document.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1825. document.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1826. document.addEventListener(POINTER_UP, _globalPointerUp, true);
  1827. document.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1828. _pointerDocListener = true;
  1829. }
  1830. }
  1831. function _handlePointer(handler, e) {
  1832. if (e.pointerType === (e.MSPOINTER_TYPE_MOUSE || 'mouse')) { return; }
  1833. e.touches = [];
  1834. for (var i in _pointers) {
  1835. e.touches.push(_pointers[i]);
  1836. }
  1837. e.changedTouches = [e];
  1838. handler(e);
  1839. }
  1840. function _onPointerStart(handler, e) {
  1841. // IE10 specific: MsTouch needs preventDefault. See #2000
  1842. if (e.MSPOINTER_TYPE_TOUCH && e.pointerType === e.MSPOINTER_TYPE_TOUCH) {
  1843. preventDefault(e);
  1844. }
  1845. _handlePointer(handler, e);
  1846. }
  1847. /*
  1848. * Extends the event handling code with double tap support for mobile browsers.
  1849. *
  1850. * Note: currently most browsers fire native dblclick, with only a few exceptions
  1851. * (see https://github.com/Leaflet/Leaflet/issues/7012#issuecomment-595087386)
  1852. */
  1853. function makeDblclick(event) {
  1854. // in modern browsers `type` cannot be just overridden:
  1855. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only
  1856. var newEvent = {},
  1857. prop, i;
  1858. for (i in event) {
  1859. prop = event[i];
  1860. newEvent[i] = prop && prop.bind ? prop.bind(event) : prop;
  1861. }
  1862. event = newEvent;
  1863. newEvent.type = 'dblclick';
  1864. newEvent.detail = 2;
  1865. newEvent.isTrusted = false;
  1866. newEvent._simulated = true; // for debug purposes
  1867. return newEvent;
  1868. }
  1869. var delay = 200;
  1870. function addDoubleTapListener(obj, handler) {
  1871. // Most browsers handle double tap natively
  1872. obj.addEventListener('dblclick', handler);
  1873. // On some platforms the browser doesn't fire native dblclicks for touch events.
  1874. // It seems that in all such cases `detail` property of `click` event is always `1`.
  1875. // So here we rely on that fact to avoid excessive 'dblclick' simulation when not needed.
  1876. var last = 0,
  1877. detail;
  1878. function simDblclick(e) {
  1879. if (e.detail !== 1) {
  1880. detail = e.detail; // keep in sync to avoid false dblclick in some cases
  1881. return;
  1882. }
  1883. if (e.pointerType === 'mouse' ||
  1884. (e.sourceCapabilities && !e.sourceCapabilities.firesTouchEvents)) {
  1885. return;
  1886. }
  1887. // When clicking on an <input>, the browser generates a click on its
  1888. // <label> (and vice versa) triggering two clicks in quick succession.
  1889. // This ignores clicks on elements which are a label with a 'for'
  1890. // attribute (or children of such a label), but not children of
  1891. // a <input>.
  1892. var path = getPropagationPath(e);
  1893. if (path.some(function (el) {
  1894. return el instanceof HTMLLabelElement && el.attributes.for;
  1895. }) &&
  1896. !path.some(function (el) {
  1897. return (
  1898. el instanceof HTMLInputElement ||
  1899. el instanceof HTMLSelectElement
  1900. );
  1901. })
  1902. ) {
  1903. return;
  1904. }
  1905. var now = Date.now();
  1906. if (now - last <= delay) {
  1907. detail++;
  1908. if (detail === 2) {
  1909. handler(makeDblclick(e));
  1910. }
  1911. } else {
  1912. detail = 1;
  1913. }
  1914. last = now;
  1915. }
  1916. obj.addEventListener('click', simDblclick);
  1917. return {
  1918. dblclick: handler,
  1919. simDblclick: simDblclick
  1920. };
  1921. }
  1922. function removeDoubleTapListener(obj, handlers) {
  1923. obj.removeEventListener('dblclick', handlers.dblclick);
  1924. obj.removeEventListener('click', handlers.simDblclick);
  1925. }
  1926. /*
  1927. * @namespace DomUtil
  1928. *
  1929. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1930. * tree, used by Leaflet internally.
  1931. *
  1932. * Most functions expecting or returning a `HTMLElement` also work for
  1933. * SVG elements. The only difference is that classes refer to CSS classes
  1934. * in HTML and SVG classes in SVG.
  1935. */
  1936. // @property TRANSFORM: String
  1937. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  1938. var TRANSFORM = testProp(
  1939. ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1940. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1941. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1942. // @property TRANSITION: String
  1943. // Vendor-prefixed transition style name.
  1944. var TRANSITION = testProp(
  1945. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1946. // @property TRANSITION_END: String
  1947. // Vendor-prefixed transitionend event name.
  1948. var TRANSITION_END =
  1949. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  1950. // @function get(id: String|HTMLElement): HTMLElement
  1951. // Returns an element given its DOM id, or returns the element itself
  1952. // if it was passed directly.
  1953. function get(id) {
  1954. return typeof id === 'string' ? document.getElementById(id) : id;
  1955. }
  1956. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1957. // Returns the value for a certain style attribute on an element,
  1958. // including computed values or values set through CSS.
  1959. function getStyle(el, style) {
  1960. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1961. if ((!value || value === 'auto') && document.defaultView) {
  1962. var css = document.defaultView.getComputedStyle(el, null);
  1963. value = css ? css[style] : null;
  1964. }
  1965. return value === 'auto' ? null : value;
  1966. }
  1967. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1968. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1969. function create$1(tagName, className, container) {
  1970. var el = document.createElement(tagName);
  1971. el.className = className || '';
  1972. if (container) {
  1973. container.appendChild(el);
  1974. }
  1975. return el;
  1976. }
  1977. // @function remove(el: HTMLElement)
  1978. // Removes `el` from its parent element
  1979. function remove(el) {
  1980. var parent = el.parentNode;
  1981. if (parent) {
  1982. parent.removeChild(el);
  1983. }
  1984. }
  1985. // @function empty(el: HTMLElement)
  1986. // Removes all of `el`'s children elements from `el`
  1987. function empty(el) {
  1988. while (el.firstChild) {
  1989. el.removeChild(el.firstChild);
  1990. }
  1991. }
  1992. // @function toFront(el: HTMLElement)
  1993. // Makes `el` the last child of its parent, so it renders in front of the other children.
  1994. function toFront(el) {
  1995. var parent = el.parentNode;
  1996. if (parent && parent.lastChild !== el) {
  1997. parent.appendChild(el);
  1998. }
  1999. }
  2000. // @function toBack(el: HTMLElement)
  2001. // Makes `el` the first child of its parent, so it renders behind the other children.
  2002. function toBack(el) {
  2003. var parent = el.parentNode;
  2004. if (parent && parent.firstChild !== el) {
  2005. parent.insertBefore(el, parent.firstChild);
  2006. }
  2007. }
  2008. // @function hasClass(el: HTMLElement, name: String): Boolean
  2009. // Returns `true` if the element's class attribute contains `name`.
  2010. function hasClass(el, name) {
  2011. if (el.classList !== undefined) {
  2012. return el.classList.contains(name);
  2013. }
  2014. var className = getClass(el);
  2015. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  2016. }
  2017. // @function addClass(el: HTMLElement, name: String)
  2018. // Adds `name` to the element's class attribute.
  2019. function addClass(el, name) {
  2020. if (el.classList !== undefined) {
  2021. var classes = splitWords(name);
  2022. for (var i = 0, len = classes.length; i < len; i++) {
  2023. el.classList.add(classes[i]);
  2024. }
  2025. } else if (!hasClass(el, name)) {
  2026. var className = getClass(el);
  2027. setClass(el, (className ? className + ' ' : '') + name);
  2028. }
  2029. }
  2030. // @function removeClass(el: HTMLElement, name: String)
  2031. // Removes `name` from the element's class attribute.
  2032. function removeClass(el, name) {
  2033. if (el.classList !== undefined) {
  2034. el.classList.remove(name);
  2035. } else {
  2036. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  2037. }
  2038. }
  2039. // @function setClass(el: HTMLElement, name: String)
  2040. // Sets the element's class.
  2041. function setClass(el, name) {
  2042. if (el.className.baseVal === undefined) {
  2043. el.className = name;
  2044. } else {
  2045. // in case of SVG element
  2046. el.className.baseVal = name;
  2047. }
  2048. }
  2049. // @function getClass(el: HTMLElement): String
  2050. // Returns the element's class.
  2051. function getClass(el) {
  2052. // Check if the element is an SVGElementInstance and use the correspondingElement instead
  2053. // (Required for linked SVG elements in IE11.)
  2054. if (el.correspondingElement) {
  2055. el = el.correspondingElement;
  2056. }
  2057. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  2058. }
  2059. // @function setOpacity(el: HTMLElement, opacity: Number)
  2060. // Set the opacity of an element (including old IE support).
  2061. // `opacity` must be a number from `0` to `1`.
  2062. function setOpacity(el, value) {
  2063. if ('opacity' in el.style) {
  2064. el.style.opacity = value;
  2065. } else if ('filter' in el.style) {
  2066. _setOpacityIE(el, value);
  2067. }
  2068. }
  2069. function _setOpacityIE(el, value) {
  2070. var filter = false,
  2071. filterName = 'DXImageTransform.Microsoft.Alpha';
  2072. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  2073. try {
  2074. filter = el.filters.item(filterName);
  2075. } catch (e) {
  2076. // don't set opacity to 1 if we haven't already set an opacity,
  2077. // it isn't needed and breaks transparent pngs.
  2078. if (value === 1) { return; }
  2079. }
  2080. value = Math.round(value * 100);
  2081. if (filter) {
  2082. filter.Enabled = (value !== 100);
  2083. filter.Opacity = value;
  2084. } else {
  2085. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  2086. }
  2087. }
  2088. // @function testProp(props: String[]): String|false
  2089. // Goes through the array of style names and returns the first name
  2090. // that is a valid style name for an element. If no such name is found,
  2091. // it returns false. Useful for vendor-prefixed styles like `transform`.
  2092. function testProp(props) {
  2093. var style = document.documentElement.style;
  2094. for (var i = 0; i < props.length; i++) {
  2095. if (props[i] in style) {
  2096. return props[i];
  2097. }
  2098. }
  2099. return false;
  2100. }
  2101. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  2102. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  2103. // and optionally scaled by `scale`. Does not have an effect if the
  2104. // browser doesn't support 3D CSS transforms.
  2105. function setTransform(el, offset, scale) {
  2106. var pos = offset || new Point(0, 0);
  2107. el.style[TRANSFORM] =
  2108. (Browser.ie3d ?
  2109. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2110. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2111. (scale ? ' scale(' + scale + ')' : '');
  2112. }
  2113. // @function setPosition(el: HTMLElement, position: Point)
  2114. // Sets the position of `el` to coordinates specified by `position`,
  2115. // using CSS translate or top/left positioning depending on the browser
  2116. // (used by Leaflet internally to position its layers).
  2117. function setPosition(el, point) {
  2118. /*eslint-disable */
  2119. el._leaflet_pos = point;
  2120. /* eslint-enable */
  2121. if (Browser.any3d) {
  2122. setTransform(el, point);
  2123. } else {
  2124. el.style.left = point.x + 'px';
  2125. el.style.top = point.y + 'px';
  2126. }
  2127. }
  2128. // @function getPosition(el: HTMLElement): Point
  2129. // Returns the coordinates of an element previously positioned with setPosition.
  2130. function getPosition(el) {
  2131. // this method is only used for elements previously positioned using setPosition,
  2132. // so it's safe to cache the position for performance
  2133. return el._leaflet_pos || new Point(0, 0);
  2134. }
  2135. // @function disableTextSelection()
  2136. // Prevents the user from generating `selectstart` DOM events, usually generated
  2137. // when the user drags the mouse through a page with text. Used internally
  2138. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2139. // the map. Affects drag interactions on the whole document.
  2140. // @function enableTextSelection()
  2141. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2142. var disableTextSelection;
  2143. var enableTextSelection;
  2144. var _userSelect;
  2145. if ('onselectstart' in document) {
  2146. disableTextSelection = function () {
  2147. on(window, 'selectstart', preventDefault);
  2148. };
  2149. enableTextSelection = function () {
  2150. off(window, 'selectstart', preventDefault);
  2151. };
  2152. } else {
  2153. var userSelectProperty = testProp(
  2154. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2155. disableTextSelection = function () {
  2156. if (userSelectProperty) {
  2157. var style = document.documentElement.style;
  2158. _userSelect = style[userSelectProperty];
  2159. style[userSelectProperty] = 'none';
  2160. }
  2161. };
  2162. enableTextSelection = function () {
  2163. if (userSelectProperty) {
  2164. document.documentElement.style[userSelectProperty] = _userSelect;
  2165. _userSelect = undefined;
  2166. }
  2167. };
  2168. }
  2169. // @function disableImageDrag()
  2170. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2171. // for `dragstart` DOM events, usually generated when the user drags an image.
  2172. function disableImageDrag() {
  2173. on(window, 'dragstart', preventDefault);
  2174. }
  2175. // @function enableImageDrag()
  2176. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2177. function enableImageDrag() {
  2178. off(window, 'dragstart', preventDefault);
  2179. }
  2180. var _outlineElement, _outlineStyle;
  2181. // @function preventOutline(el: HTMLElement)
  2182. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2183. // of the element `el` invisible. Used internally by Leaflet to prevent
  2184. // focusable elements from displaying an outline when the user performs a
  2185. // drag interaction on them.
  2186. function preventOutline(element) {
  2187. while (element.tabIndex === -1) {
  2188. element = element.parentNode;
  2189. }
  2190. if (!element.style) { return; }
  2191. restoreOutline();
  2192. _outlineElement = element;
  2193. _outlineStyle = element.style.outline;
  2194. element.style.outline = 'none';
  2195. on(window, 'keydown', restoreOutline);
  2196. }
  2197. // @function restoreOutline()
  2198. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2199. function restoreOutline() {
  2200. if (!_outlineElement) { return; }
  2201. _outlineElement.style.outline = _outlineStyle;
  2202. _outlineElement = undefined;
  2203. _outlineStyle = undefined;
  2204. off(window, 'keydown', restoreOutline);
  2205. }
  2206. // @function getSizedParentNode(el: HTMLElement): HTMLElement
  2207. // Finds the closest parent node which size (width and height) is not null.
  2208. function getSizedParentNode(element) {
  2209. do {
  2210. element = element.parentNode;
  2211. } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);
  2212. return element;
  2213. }
  2214. // @function getScale(el: HTMLElement): Object
  2215. // Computes the CSS scale currently applied on the element.
  2216. // Returns an object with `x` and `y` members as horizontal and vertical scales respectively,
  2217. // and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2218. function getScale(element) {
  2219. var rect = element.getBoundingClientRect(); // Read-only in old browsers.
  2220. return {
  2221. x: rect.width / element.offsetWidth || 1,
  2222. y: rect.height / element.offsetHeight || 1,
  2223. boundingClientRect: rect
  2224. };
  2225. }
  2226. var DomUtil = {
  2227. __proto__: null,
  2228. TRANSFORM: TRANSFORM,
  2229. TRANSITION: TRANSITION,
  2230. TRANSITION_END: TRANSITION_END,
  2231. get: get,
  2232. getStyle: getStyle,
  2233. create: create$1,
  2234. remove: remove,
  2235. empty: empty,
  2236. toFront: toFront,
  2237. toBack: toBack,
  2238. hasClass: hasClass,
  2239. addClass: addClass,
  2240. removeClass: removeClass,
  2241. setClass: setClass,
  2242. getClass: getClass,
  2243. setOpacity: setOpacity,
  2244. testProp: testProp,
  2245. setTransform: setTransform,
  2246. setPosition: setPosition,
  2247. getPosition: getPosition,
  2248. get disableTextSelection () { return disableTextSelection; },
  2249. get enableTextSelection () { return enableTextSelection; },
  2250. disableImageDrag: disableImageDrag,
  2251. enableImageDrag: enableImageDrag,
  2252. preventOutline: preventOutline,
  2253. restoreOutline: restoreOutline,
  2254. getSizedParentNode: getSizedParentNode,
  2255. getScale: getScale
  2256. };
  2257. /*
  2258. * @namespace DomEvent
  2259. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  2260. */
  2261. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  2262. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2263. // Adds a listener function (`fn`) to a particular DOM event type of the
  2264. // element `el`. You can optionally specify the context of the listener
  2265. // (object the `this` keyword will point to). You can also pass several
  2266. // space-separated types (e.g. `'click dblclick'`).
  2267. // @alternative
  2268. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  2269. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2270. function on(obj, types, fn, context) {
  2271. if (types && typeof types === 'object') {
  2272. for (var type in types) {
  2273. addOne(obj, type, types[type], fn);
  2274. }
  2275. } else {
  2276. types = splitWords(types);
  2277. for (var i = 0, len = types.length; i < len; i++) {
  2278. addOne(obj, types[i], fn, context);
  2279. }
  2280. }
  2281. return this;
  2282. }
  2283. var eventsKey = '_leaflet_events';
  2284. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2285. // Removes a previously added listener function.
  2286. // Note that if you passed a custom context to on, you must pass the same
  2287. // context to `off` in order to remove the listener.
  2288. // @alternative
  2289. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  2290. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2291. // @alternative
  2292. // @function off(el: HTMLElement, types: String): this
  2293. // Removes all previously added listeners of given types.
  2294. // @alternative
  2295. // @function off(el: HTMLElement): this
  2296. // Removes all previously added listeners from given HTMLElement
  2297. function off(obj, types, fn, context) {
  2298. if (arguments.length === 1) {
  2299. batchRemove(obj);
  2300. delete obj[eventsKey];
  2301. } else if (types && typeof types === 'object') {
  2302. for (var type in types) {
  2303. removeOne(obj, type, types[type], fn);
  2304. }
  2305. } else {
  2306. types = splitWords(types);
  2307. if (arguments.length === 2) {
  2308. batchRemove(obj, function (type) {
  2309. return indexOf(types, type) !== -1;
  2310. });
  2311. } else {
  2312. for (var i = 0, len = types.length; i < len; i++) {
  2313. removeOne(obj, types[i], fn, context);
  2314. }
  2315. }
  2316. }
  2317. return this;
  2318. }
  2319. function batchRemove(obj, filterFn) {
  2320. for (var id in obj[eventsKey]) {
  2321. var type = id.split(/\d/)[0];
  2322. if (!filterFn || filterFn(type)) {
  2323. removeOne(obj, type, null, null, id);
  2324. }
  2325. }
  2326. }
  2327. var mouseSubst = {
  2328. mouseenter: 'mouseover',
  2329. mouseleave: 'mouseout',
  2330. wheel: !('onwheel' in window) && 'mousewheel'
  2331. };
  2332. function addOne(obj, type, fn, context) {
  2333. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2334. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  2335. var handler = function (e) {
  2336. return fn.call(context || obj, e || window.event);
  2337. };
  2338. var originalHandler = handler;
  2339. if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {
  2340. // Needs DomEvent.Pointer.js
  2341. handler = addPointerListener(obj, type, handler);
  2342. } else if (Browser.touch && (type === 'dblclick')) {
  2343. handler = addDoubleTapListener(obj, handler);
  2344. } else if ('addEventListener' in obj) {
  2345. if (type === 'touchstart' || type === 'touchmove' || type === 'wheel' || type === 'mousewheel') {
  2346. obj.addEventListener(mouseSubst[type] || type, handler, Browser.passiveEvents ? {passive: false} : false);
  2347. } else if (type === 'mouseenter' || type === 'mouseleave') {
  2348. handler = function (e) {
  2349. e = e || window.event;
  2350. if (isExternalTarget(obj, e)) {
  2351. originalHandler(e);
  2352. }
  2353. };
  2354. obj.addEventListener(mouseSubst[type], handler, false);
  2355. } else {
  2356. obj.addEventListener(type, originalHandler, false);
  2357. }
  2358. } else {
  2359. obj.attachEvent('on' + type, handler);
  2360. }
  2361. obj[eventsKey] = obj[eventsKey] || {};
  2362. obj[eventsKey][id] = handler;
  2363. }
  2364. function removeOne(obj, type, fn, context, id) {
  2365. id = id || type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2366. var handler = obj[eventsKey] && obj[eventsKey][id];
  2367. if (!handler) { return this; }
  2368. if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {
  2369. removePointerListener(obj, type, handler);
  2370. } else if (Browser.touch && (type === 'dblclick')) {
  2371. removeDoubleTapListener(obj, handler);
  2372. } else if ('removeEventListener' in obj) {
  2373. obj.removeEventListener(mouseSubst[type] || type, handler, false);
  2374. } else {
  2375. obj.detachEvent('on' + type, handler);
  2376. }
  2377. obj[eventsKey][id] = null;
  2378. }
  2379. // @function stopPropagation(ev: DOMEvent): this
  2380. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  2381. // ```js
  2382. // L.DomEvent.on(div, 'click', function (ev) {
  2383. // L.DomEvent.stopPropagation(ev);
  2384. // });
  2385. // ```
  2386. function stopPropagation(e) {
  2387. if (e.stopPropagation) {
  2388. e.stopPropagation();
  2389. } else if (e.originalEvent) { // In case of Leaflet event.
  2390. e.originalEvent._stopped = true;
  2391. } else {
  2392. e.cancelBubble = true;
  2393. }
  2394. return this;
  2395. }
  2396. // @function disableScrollPropagation(el: HTMLElement): this
  2397. // Adds `stopPropagation` to the element's `'wheel'` events (plus browser variants).
  2398. function disableScrollPropagation(el) {
  2399. addOne(el, 'wheel', stopPropagation);
  2400. return this;
  2401. }
  2402. // @function disableClickPropagation(el: HTMLElement): this
  2403. // Adds `stopPropagation` to the element's `'click'`, `'dblclick'`, `'contextmenu'`,
  2404. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  2405. function disableClickPropagation(el) {
  2406. on(el, 'mousedown touchstart dblclick contextmenu', stopPropagation);
  2407. el['_leaflet_disable_click'] = true;
  2408. return this;
  2409. }
  2410. // @function preventDefault(ev: DOMEvent): this
  2411. // Prevents the default action of the DOM Event `ev` from happening (such as
  2412. // following a link in the href of the a element, or doing a POST request
  2413. // with page reload when a `<form>` is submitted).
  2414. // Use it inside listener functions.
  2415. function preventDefault(e) {
  2416. if (e.preventDefault) {
  2417. e.preventDefault();
  2418. } else {
  2419. e.returnValue = false;
  2420. }
  2421. return this;
  2422. }
  2423. // @function stop(ev: DOMEvent): this
  2424. // Does `stopPropagation` and `preventDefault` at the same time.
  2425. function stop(e) {
  2426. preventDefault(e);
  2427. stopPropagation(e);
  2428. return this;
  2429. }
  2430. // @function getPropagationPath(ev: DOMEvent): Array
  2431. // Compatibility polyfill for [`Event.composedPath()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath).
  2432. // Returns an array containing the `HTMLElement`s that the given DOM event
  2433. // should propagate to (if not stopped).
  2434. function getPropagationPath(ev) {
  2435. if (ev.composedPath) {
  2436. return ev.composedPath();
  2437. }
  2438. var path = [];
  2439. var el = ev.target;
  2440. while (el) {
  2441. path.push(el);
  2442. el = el.parentNode;
  2443. }
  2444. return path;
  2445. }
  2446. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  2447. // Gets normalized mouse position from a DOM event relative to the
  2448. // `container` (border excluded) or to the whole page if not specified.
  2449. function getMousePosition(e, container) {
  2450. if (!container) {
  2451. return new Point(e.clientX, e.clientY);
  2452. }
  2453. var scale = getScale(container),
  2454. offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)
  2455. return new Point(
  2456. // offset.left/top values are in page scale (like clientX/Y),
  2457. // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
  2458. (e.clientX - offset.left) / scale.x - container.clientLeft,
  2459. (e.clientY - offset.top) / scale.y - container.clientTop
  2460. );
  2461. }
  2462. // except , Safari and
  2463. // We need double the scroll pixels (see #7403 and #4538) for all Browsers
  2464. // except OSX (Mac) -> 3x, Chrome running on Linux 1x
  2465. var wheelPxFactor =
  2466. (Browser.linux && Browser.chrome) ? window.devicePixelRatio :
  2467. Browser.mac ? window.devicePixelRatio * 3 :
  2468. window.devicePixelRatio > 0 ? 2 * window.devicePixelRatio : 1;
  2469. // @function getWheelDelta(ev: DOMEvent): Number
  2470. // Gets normalized wheel delta from a wheel DOM event, in vertical
  2471. // pixels scrolled (negative if scrolling down).
  2472. // Events from pointing devices without precise scrolling are mapped to
  2473. // a best guess of 60 pixels.
  2474. function getWheelDelta(e) {
  2475. return (Browser.edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2476. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2477. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2478. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2479. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2480. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2481. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2482. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2483. 0;
  2484. }
  2485. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2486. function isExternalTarget(el, e) {
  2487. var related = e.relatedTarget;
  2488. if (!related) { return true; }
  2489. try {
  2490. while (related && (related !== el)) {
  2491. related = related.parentNode;
  2492. }
  2493. } catch (err) {
  2494. return false;
  2495. }
  2496. return (related !== el);
  2497. }
  2498. var DomEvent = {
  2499. __proto__: null,
  2500. on: on,
  2501. off: off,
  2502. stopPropagation: stopPropagation,
  2503. disableScrollPropagation: disableScrollPropagation,
  2504. disableClickPropagation: disableClickPropagation,
  2505. preventDefault: preventDefault,
  2506. stop: stop,
  2507. getPropagationPath: getPropagationPath,
  2508. getMousePosition: getMousePosition,
  2509. getWheelDelta: getWheelDelta,
  2510. isExternalTarget: isExternalTarget,
  2511. addListener: on,
  2512. removeListener: off
  2513. };
  2514. /*
  2515. * @class PosAnimation
  2516. * @aka L.PosAnimation
  2517. * @inherits Evented
  2518. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2519. *
  2520. * @example
  2521. * ```js
  2522. * var myPositionMarker = L.marker([48.864716, 2.294694]).addTo(map);
  2523. *
  2524. * myPositionMarker.on("click", function() {
  2525. * var pos = map.latLngToLayerPoint(myPositionMarker.getLatLng());
  2526. * pos.y -= 25;
  2527. * var fx = new L.PosAnimation();
  2528. *
  2529. * fx.once('end',function() {
  2530. * pos.y += 25;
  2531. * fx.run(myPositionMarker._icon, pos, 0.8);
  2532. * });
  2533. *
  2534. * fx.run(myPositionMarker._icon, pos, 0.3);
  2535. * });
  2536. *
  2537. * ```
  2538. *
  2539. * @constructor L.PosAnimation()
  2540. * Creates a `PosAnimation` object.
  2541. *
  2542. */
  2543. var PosAnimation = Evented.extend({
  2544. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2545. // Run an animation of a given element to a new position, optionally setting
  2546. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2547. // argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1),
  2548. // `0.5` by default).
  2549. run: function (el, newPos, duration, easeLinearity) {
  2550. this.stop();
  2551. this._el = el;
  2552. this._inProgress = true;
  2553. this._duration = duration || 0.25;
  2554. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2555. this._startPos = getPosition(el);
  2556. this._offset = newPos.subtract(this._startPos);
  2557. this._startTime = +new Date();
  2558. // @event start: Event
  2559. // Fired when the animation starts
  2560. this.fire('start');
  2561. this._animate();
  2562. },
  2563. // @method stop()
  2564. // Stops the animation (if currently running).
  2565. stop: function () {
  2566. if (!this._inProgress) { return; }
  2567. this._step(true);
  2568. this._complete();
  2569. },
  2570. _animate: function () {
  2571. // animation loop
  2572. this._animId = requestAnimFrame(this._animate, this);
  2573. this._step();
  2574. },
  2575. _step: function (round) {
  2576. var elapsed = (+new Date()) - this._startTime,
  2577. duration = this._duration * 1000;
  2578. if (elapsed < duration) {
  2579. this._runFrame(this._easeOut(elapsed / duration), round);
  2580. } else {
  2581. this._runFrame(1);
  2582. this._complete();
  2583. }
  2584. },
  2585. _runFrame: function (progress, round) {
  2586. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2587. if (round) {
  2588. pos._round();
  2589. }
  2590. setPosition(this._el, pos);
  2591. // @event step: Event
  2592. // Fired continuously during the animation.
  2593. this.fire('step');
  2594. },
  2595. _complete: function () {
  2596. cancelAnimFrame(this._animId);
  2597. this._inProgress = false;
  2598. // @event end: Event
  2599. // Fired when the animation ends.
  2600. this.fire('end');
  2601. },
  2602. _easeOut: function (t) {
  2603. return 1 - Math.pow(1 - t, this._easeOutPower);
  2604. }
  2605. });
  2606. /*
  2607. * @class Map
  2608. * @aka L.Map
  2609. * @inherits Evented
  2610. *
  2611. * The central class of the API — it is used to create a map on a page and manipulate it.
  2612. *
  2613. * @example
  2614. *
  2615. * ```js
  2616. * // initialize the map on the "map" div with a given center and zoom
  2617. * var map = L.map('map', {
  2618. * center: [51.505, -0.09],
  2619. * zoom: 13
  2620. * });
  2621. * ```
  2622. *
  2623. */
  2624. var Map = Evented.extend({
  2625. options: {
  2626. // @section Map State Options
  2627. // @option crs: CRS = L.CRS.EPSG3857
  2628. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2629. // sure what it means.
  2630. crs: EPSG3857,
  2631. // @option center: LatLng = undefined
  2632. // Initial geographic center of the map
  2633. center: undefined,
  2634. // @option zoom: Number = undefined
  2635. // Initial map zoom level
  2636. zoom: undefined,
  2637. // @option minZoom: Number = *
  2638. // Minimum zoom level of the map.
  2639. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2640. // the lowest of their `minZoom` options will be used instead.
  2641. minZoom: undefined,
  2642. // @option maxZoom: Number = *
  2643. // Maximum zoom level of the map.
  2644. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2645. // the highest of their `maxZoom` options will be used instead.
  2646. maxZoom: undefined,
  2647. // @option layers: Layer[] = []
  2648. // Array of layers that will be added to the map initially
  2649. layers: [],
  2650. // @option maxBounds: LatLngBounds = null
  2651. // When this option is set, the map restricts the view to the given
  2652. // geographical bounds, bouncing the user back if the user tries to pan
  2653. // outside the view. To set the restriction dynamically, use
  2654. // [`setMaxBounds`](#map-setmaxbounds) method.
  2655. maxBounds: undefined,
  2656. // @option renderer: Renderer = *
  2657. // The default method for drawing vector layers on the map. `L.SVG`
  2658. // or `L.Canvas` by default depending on browser support.
  2659. renderer: undefined,
  2660. // @section Animation Options
  2661. // @option zoomAnimation: Boolean = true
  2662. // Whether the map zoom animation is enabled. By default it's enabled
  2663. // in all browsers that support CSS3 Transitions except Android.
  2664. zoomAnimation: true,
  2665. // @option zoomAnimationThreshold: Number = 4
  2666. // Won't animate zoom if the zoom difference exceeds this value.
  2667. zoomAnimationThreshold: 4,
  2668. // @option fadeAnimation: Boolean = true
  2669. // Whether the tile fade animation is enabled. By default it's enabled
  2670. // in all browsers that support CSS3 Transitions except Android.
  2671. fadeAnimation: true,
  2672. // @option markerZoomAnimation: Boolean = true
  2673. // Whether markers animate their zoom with the zoom animation, if disabled
  2674. // they will disappear for the length of the animation. By default it's
  2675. // enabled in all browsers that support CSS3 Transitions except Android.
  2676. markerZoomAnimation: true,
  2677. // @option transform3DLimit: Number = 2^23
  2678. // Defines the maximum size of a CSS translation transform. The default
  2679. // value should not be changed unless a web browser positions layers in
  2680. // the wrong place after doing a large `panBy`.
  2681. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2682. // @section Interaction Options
  2683. // @option zoomSnap: Number = 1
  2684. // Forces the map's zoom level to always be a multiple of this, particularly
  2685. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2686. // By default, the zoom level snaps to the nearest integer; lower values
  2687. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2688. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2689. zoomSnap: 1,
  2690. // @option zoomDelta: Number = 1
  2691. // Controls how much the map's zoom level will change after a
  2692. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2693. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2694. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2695. zoomDelta: 1,
  2696. // @option trackResize: Boolean = true
  2697. // Whether the map automatically handles browser window resize to update itself.
  2698. trackResize: true
  2699. },
  2700. initialize: function (id, options) { // (HTMLElement or String, Object)
  2701. options = setOptions(this, options);
  2702. // Make sure to assign internal flags at the beginning,
  2703. // to avoid inconsistent state in some edge cases.
  2704. this._handlers = [];
  2705. this._layers = {};
  2706. this._zoomBoundLayers = {};
  2707. this._sizeChanged = true;
  2708. this._initContainer(id);
  2709. this._initLayout();
  2710. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2711. this._onResize = bind(this._onResize, this);
  2712. this._initEvents();
  2713. if (options.maxBounds) {
  2714. this.setMaxBounds(options.maxBounds);
  2715. }
  2716. if (options.zoom !== undefined) {
  2717. this._zoom = this._limitZoom(options.zoom);
  2718. }
  2719. if (options.center && options.zoom !== undefined) {
  2720. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2721. }
  2722. this.callInitHooks();
  2723. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2724. this._zoomAnimated = TRANSITION && Browser.any3d && !Browser.mobileOpera &&
  2725. this.options.zoomAnimation;
  2726. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2727. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2728. if (this._zoomAnimated) {
  2729. this._createAnimProxy();
  2730. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2731. }
  2732. this._addLayers(this.options.layers);
  2733. },
  2734. // @section Methods for modifying map state
  2735. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2736. // Sets the view of the map (geographical center and zoom) with the given
  2737. // animation options.
  2738. setView: function (center, zoom, options) {
  2739. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2740. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2741. options = options || {};
  2742. this._stop();
  2743. if (this._loaded && !options.reset && options !== true) {
  2744. if (options.animate !== undefined) {
  2745. options.zoom = extend({animate: options.animate}, options.zoom);
  2746. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2747. }
  2748. // try animating pan or zoom
  2749. var moved = (this._zoom !== zoom) ?
  2750. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2751. this._tryAnimatedPan(center, options.pan);
  2752. if (moved) {
  2753. // prevent resize handler call, the view will refresh after animation anyway
  2754. clearTimeout(this._sizeTimer);
  2755. return this;
  2756. }
  2757. }
  2758. // animation didn't start, just reset the map view
  2759. this._resetView(center, zoom, options.pan && options.pan.noMoveStart);
  2760. return this;
  2761. },
  2762. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2763. // Sets the zoom of the map.
  2764. setZoom: function (zoom, options) {
  2765. if (!this._loaded) {
  2766. this._zoom = zoom;
  2767. return this;
  2768. }
  2769. return this.setView(this.getCenter(), zoom, {zoom: options});
  2770. },
  2771. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2772. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2773. zoomIn: function (delta, options) {
  2774. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  2775. return this.setZoom(this._zoom + delta, options);
  2776. },
  2777. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2778. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2779. zoomOut: function (delta, options) {
  2780. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  2781. return this.setZoom(this._zoom - delta, options);
  2782. },
  2783. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2784. // Zooms the map while keeping a specified geographical point on the map
  2785. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2786. // @alternative
  2787. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2788. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2789. setZoomAround: function (latlng, zoom, options) {
  2790. var scale = this.getZoomScale(zoom),
  2791. viewHalf = this.getSize().divideBy(2),
  2792. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2793. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2794. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2795. return this.setView(newCenter, zoom, {zoom: options});
  2796. },
  2797. _getBoundsCenterZoom: function (bounds, options) {
  2798. options = options || {};
  2799. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2800. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2801. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2802. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2803. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2804. if (zoom === Infinity) {
  2805. return {
  2806. center: bounds.getCenter(),
  2807. zoom: zoom
  2808. };
  2809. }
  2810. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2811. swPoint = this.project(bounds.getSouthWest(), zoom),
  2812. nePoint = this.project(bounds.getNorthEast(), zoom),
  2813. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2814. return {
  2815. center: center,
  2816. zoom: zoom
  2817. };
  2818. },
  2819. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2820. // Sets a map view that contains the given geographical bounds with the
  2821. // maximum zoom level possible.
  2822. fitBounds: function (bounds, options) {
  2823. bounds = toLatLngBounds(bounds);
  2824. if (!bounds.isValid()) {
  2825. throw new Error('Bounds are not valid.');
  2826. }
  2827. var target = this._getBoundsCenterZoom(bounds, options);
  2828. return this.setView(target.center, target.zoom, options);
  2829. },
  2830. // @method fitWorld(options?: fitBounds options): this
  2831. // Sets a map view that mostly contains the whole world with the maximum
  2832. // zoom level possible.
  2833. fitWorld: function (options) {
  2834. return this.fitBounds([[-90, -180], [90, 180]], options);
  2835. },
  2836. // @method panTo(latlng: LatLng, options?: Pan options): this
  2837. // Pans the map to a given center.
  2838. panTo: function (center, options) { // (LatLng)
  2839. return this.setView(center, this._zoom, {pan: options});
  2840. },
  2841. // @method panBy(offset: Point, options?: Pan options): this
  2842. // Pans the map by a given number of pixels (animated).
  2843. panBy: function (offset, options) {
  2844. offset = toPoint(offset).round();
  2845. options = options || {};
  2846. if (!offset.x && !offset.y) {
  2847. return this.fire('moveend');
  2848. }
  2849. // If we pan too far, Chrome gets issues with tiles
  2850. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2851. if (options.animate !== true && !this.getSize().contains(offset)) {
  2852. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2853. return this;
  2854. }
  2855. if (!this._panAnim) {
  2856. this._panAnim = new PosAnimation();
  2857. this._panAnim.on({
  2858. 'step': this._onPanTransitionStep,
  2859. 'end': this._onPanTransitionEnd
  2860. }, this);
  2861. }
  2862. // don't fire movestart if animating inertia
  2863. if (!options.noMoveStart) {
  2864. this.fire('movestart');
  2865. }
  2866. // animate pan unless animate: false specified
  2867. if (options.animate !== false) {
  2868. addClass(this._mapPane, 'leaflet-pan-anim');
  2869. var newPos = this._getMapPanePos().subtract(offset).round();
  2870. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2871. } else {
  2872. this._rawPanBy(offset);
  2873. this.fire('move').fire('moveend');
  2874. }
  2875. return this;
  2876. },
  2877. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2878. // Sets the view of the map (geographical center and zoom) performing a smooth
  2879. // pan-zoom animation.
  2880. flyTo: function (targetCenter, targetZoom, options) {
  2881. options = options || {};
  2882. if (options.animate === false || !Browser.any3d) {
  2883. return this.setView(targetCenter, targetZoom, options);
  2884. }
  2885. this._stop();
  2886. var from = this.project(this.getCenter()),
  2887. to = this.project(targetCenter),
  2888. size = this.getSize(),
  2889. startZoom = this._zoom;
  2890. targetCenter = toLatLng(targetCenter);
  2891. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2892. var w0 = Math.max(size.x, size.y),
  2893. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2894. u1 = (to.distanceTo(from)) || 1,
  2895. rho = 1.42,
  2896. rho2 = rho * rho;
  2897. function r(i) {
  2898. var s1 = i ? -1 : 1,
  2899. s2 = i ? w1 : w0,
  2900. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2901. b1 = 2 * s2 * rho2 * u1,
  2902. b = t1 / b1,
  2903. sq = Math.sqrt(b * b + 1) - b;
  2904. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2905. // thus triggering an infinite loop in flyTo
  2906. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2907. return log;
  2908. }
  2909. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2910. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2911. function tanh(n) { return sinh(n) / cosh(n); }
  2912. var r0 = r(0);
  2913. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2914. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2915. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2916. var start = Date.now(),
  2917. S = (r(1) - r0) / rho,
  2918. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2919. function frame() {
  2920. var t = (Date.now() - start) / duration,
  2921. s = easeOut(t) * S;
  2922. if (t <= 1) {
  2923. this._flyToFrame = requestAnimFrame(frame, this);
  2924. this._move(
  2925. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2926. this.getScaleZoom(w0 / w(s), startZoom),
  2927. {flyTo: true});
  2928. } else {
  2929. this
  2930. ._move(targetCenter, targetZoom)
  2931. ._moveEnd(true);
  2932. }
  2933. }
  2934. this._moveStart(true, options.noMoveStart);
  2935. frame.call(this);
  2936. return this;
  2937. },
  2938. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2939. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2940. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2941. flyToBounds: function (bounds, options) {
  2942. var target = this._getBoundsCenterZoom(bounds, options);
  2943. return this.flyTo(target.center, target.zoom, options);
  2944. },
  2945. // @method setMaxBounds(bounds: LatLngBounds): this
  2946. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2947. setMaxBounds: function (bounds) {
  2948. bounds = toLatLngBounds(bounds);
  2949. if (this.listens('moveend', this._panInsideMaxBounds)) {
  2950. this.off('moveend', this._panInsideMaxBounds);
  2951. }
  2952. if (!bounds.isValid()) {
  2953. this.options.maxBounds = null;
  2954. return this;
  2955. }
  2956. this.options.maxBounds = bounds;
  2957. if (this._loaded) {
  2958. this._panInsideMaxBounds();
  2959. }
  2960. return this.on('moveend', this._panInsideMaxBounds);
  2961. },
  2962. // @method setMinZoom(zoom: Number): this
  2963. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2964. setMinZoom: function (zoom) {
  2965. var oldZoom = this.options.minZoom;
  2966. this.options.minZoom = zoom;
  2967. if (this._loaded && oldZoom !== zoom) {
  2968. this.fire('zoomlevelschange');
  2969. if (this.getZoom() < this.options.minZoom) {
  2970. return this.setZoom(zoom);
  2971. }
  2972. }
  2973. return this;
  2974. },
  2975. // @method setMaxZoom(zoom: Number): this
  2976. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2977. setMaxZoom: function (zoom) {
  2978. var oldZoom = this.options.maxZoom;
  2979. this.options.maxZoom = zoom;
  2980. if (this._loaded && oldZoom !== zoom) {
  2981. this.fire('zoomlevelschange');
  2982. if (this.getZoom() > this.options.maxZoom) {
  2983. return this.setZoom(zoom);
  2984. }
  2985. }
  2986. return this;
  2987. },
  2988. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2989. // 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.
  2990. panInsideBounds: function (bounds, options) {
  2991. this._enforcingBounds = true;
  2992. var center = this.getCenter(),
  2993. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2994. if (!center.equals(newCenter)) {
  2995. this.panTo(newCenter, options);
  2996. }
  2997. this._enforcingBounds = false;
  2998. return this;
  2999. },
  3000. // @method panInside(latlng: LatLng, options?: padding options): this
  3001. // Pans the map the minimum amount to make the `latlng` visible. Use
  3002. // padding options to fit the display to more restricted bounds.
  3003. // If `latlng` is already within the (optionally padded) display bounds,
  3004. // the map will not be panned.
  3005. panInside: function (latlng, options) {
  3006. options = options || {};
  3007. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  3008. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  3009. pixelCenter = this.project(this.getCenter()),
  3010. pixelPoint = this.project(latlng),
  3011. pixelBounds = this.getPixelBounds(),
  3012. paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]),
  3013. paddedSize = paddedBounds.getSize();
  3014. if (!paddedBounds.contains(pixelPoint)) {
  3015. this._enforcingBounds = true;
  3016. var centerOffset = pixelPoint.subtract(paddedBounds.getCenter());
  3017. var offset = paddedBounds.extend(pixelPoint).getSize().subtract(paddedSize);
  3018. pixelCenter.x += centerOffset.x < 0 ? -offset.x : offset.x;
  3019. pixelCenter.y += centerOffset.y < 0 ? -offset.y : offset.y;
  3020. this.panTo(this.unproject(pixelCenter), options);
  3021. this._enforcingBounds = false;
  3022. }
  3023. return this;
  3024. },
  3025. // @method invalidateSize(options: Zoom/pan options): this
  3026. // Checks if the map container size changed and updates the map if so —
  3027. // call it after you've changed the map size dynamically, also animating
  3028. // pan by default. If `options.pan` is `false`, panning will not occur.
  3029. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  3030. // that it doesn't happen often even if the method is called many
  3031. // times in a row.
  3032. // @alternative
  3033. // @method invalidateSize(animate: Boolean): this
  3034. // Checks if the map container size changed and updates the map if so —
  3035. // call it after you've changed the map size dynamically, also animating
  3036. // pan by default.
  3037. invalidateSize: function (options) {
  3038. if (!this._loaded) { return this; }
  3039. options = extend({
  3040. animate: false,
  3041. pan: true
  3042. }, options === true ? {animate: true} : options);
  3043. var oldSize = this.getSize();
  3044. this._sizeChanged = true;
  3045. this._lastCenter = null;
  3046. var newSize = this.getSize(),
  3047. oldCenter = oldSize.divideBy(2).round(),
  3048. newCenter = newSize.divideBy(2).round(),
  3049. offset = oldCenter.subtract(newCenter);
  3050. if (!offset.x && !offset.y) { return this; }
  3051. if (options.animate && options.pan) {
  3052. this.panBy(offset);
  3053. } else {
  3054. if (options.pan) {
  3055. this._rawPanBy(offset);
  3056. }
  3057. this.fire('move');
  3058. if (options.debounceMoveend) {
  3059. clearTimeout(this._sizeTimer);
  3060. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  3061. } else {
  3062. this.fire('moveend');
  3063. }
  3064. }
  3065. // @section Map state change events
  3066. // @event resize: ResizeEvent
  3067. // Fired when the map is resized.
  3068. return this.fire('resize', {
  3069. oldSize: oldSize,
  3070. newSize: newSize
  3071. });
  3072. },
  3073. // @section Methods for modifying map state
  3074. // @method stop(): this
  3075. // Stops the currently running `panTo` or `flyTo` animation, if any.
  3076. stop: function () {
  3077. this.setZoom(this._limitZoom(this._zoom));
  3078. if (!this.options.zoomSnap) {
  3079. this.fire('viewreset');
  3080. }
  3081. return this._stop();
  3082. },
  3083. // @section Geolocation methods
  3084. // @method locate(options?: Locate options): this
  3085. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  3086. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  3087. // and optionally sets the map view to the user's location with respect to
  3088. // detection accuracy (or to the world view if geolocation failed).
  3089. // Note that, if your page doesn't use HTTPS, this method will fail in
  3090. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  3091. // See `Locate options` for more details.
  3092. locate: function (options) {
  3093. options = this._locateOptions = extend({
  3094. timeout: 10000,
  3095. watch: false
  3096. // setView: false
  3097. // maxZoom: <Number>
  3098. // maximumAge: 0
  3099. // enableHighAccuracy: false
  3100. }, options);
  3101. if (!('geolocation' in navigator)) {
  3102. this._handleGeolocationError({
  3103. code: 0,
  3104. message: 'Geolocation not supported.'
  3105. });
  3106. return this;
  3107. }
  3108. var onResponse = bind(this._handleGeolocationResponse, this),
  3109. onError = bind(this._handleGeolocationError, this);
  3110. if (options.watch) {
  3111. this._locationWatchId =
  3112. navigator.geolocation.watchPosition(onResponse, onError, options);
  3113. } else {
  3114. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  3115. }
  3116. return this;
  3117. },
  3118. // @method stopLocate(): this
  3119. // Stops watching location previously initiated by `map.locate({watch: true})`
  3120. // and aborts resetting the map view if map.locate was called with
  3121. // `{setView: true}`.
  3122. stopLocate: function () {
  3123. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  3124. navigator.geolocation.clearWatch(this._locationWatchId);
  3125. }
  3126. if (this._locateOptions) {
  3127. this._locateOptions.setView = false;
  3128. }
  3129. return this;
  3130. },
  3131. _handleGeolocationError: function (error) {
  3132. if (!this._container._leaflet_id) { return; }
  3133. var c = error.code,
  3134. message = error.message ||
  3135. (c === 1 ? 'permission denied' :
  3136. (c === 2 ? 'position unavailable' : 'timeout'));
  3137. if (this._locateOptions.setView && !this._loaded) {
  3138. this.fitWorld();
  3139. }
  3140. // @section Location events
  3141. // @event locationerror: ErrorEvent
  3142. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  3143. this.fire('locationerror', {
  3144. code: c,
  3145. message: 'Geolocation error: ' + message + '.'
  3146. });
  3147. },
  3148. _handleGeolocationResponse: function (pos) {
  3149. if (!this._container._leaflet_id) { return; }
  3150. var lat = pos.coords.latitude,
  3151. lng = pos.coords.longitude,
  3152. latlng = new LatLng(lat, lng),
  3153. bounds = latlng.toBounds(pos.coords.accuracy * 2),
  3154. options = this._locateOptions;
  3155. if (options.setView) {
  3156. var zoom = this.getBoundsZoom(bounds);
  3157. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  3158. }
  3159. var data = {
  3160. latlng: latlng,
  3161. bounds: bounds,
  3162. timestamp: pos.timestamp
  3163. };
  3164. for (var i in pos.coords) {
  3165. if (typeof pos.coords[i] === 'number') {
  3166. data[i] = pos.coords[i];
  3167. }
  3168. }
  3169. // @event locationfound: LocationEvent
  3170. // Fired when geolocation (using the [`locate`](#map-locate) method)
  3171. // went successfully.
  3172. this.fire('locationfound', data);
  3173. },
  3174. // TODO Appropriate docs section?
  3175. // @section Other Methods
  3176. // @method addHandler(name: String, HandlerClass: Function): this
  3177. // Adds a new `Handler` to the map, given its name and constructor function.
  3178. addHandler: function (name, HandlerClass) {
  3179. if (!HandlerClass) { return this; }
  3180. var handler = this[name] = new HandlerClass(this);
  3181. this._handlers.push(handler);
  3182. if (this.options[name]) {
  3183. handler.enable();
  3184. }
  3185. return this;
  3186. },
  3187. // @method remove(): this
  3188. // Destroys the map and clears all related event listeners.
  3189. remove: function () {
  3190. this._initEvents(true);
  3191. if (this.options.maxBounds) { this.off('moveend', this._panInsideMaxBounds); }
  3192. if (this._containerId !== this._container._leaflet_id) {
  3193. throw new Error('Map container is being reused by another instance');
  3194. }
  3195. try {
  3196. // throws error in IE6-8
  3197. delete this._container._leaflet_id;
  3198. delete this._containerId;
  3199. } catch (e) {
  3200. /*eslint-disable */
  3201. this._container._leaflet_id = undefined;
  3202. /* eslint-enable */
  3203. this._containerId = undefined;
  3204. }
  3205. if (this._locationWatchId !== undefined) {
  3206. this.stopLocate();
  3207. }
  3208. this._stop();
  3209. remove(this._mapPane);
  3210. if (this._clearControlPos) {
  3211. this._clearControlPos();
  3212. }
  3213. if (this._resizeRequest) {
  3214. cancelAnimFrame(this._resizeRequest);
  3215. this._resizeRequest = null;
  3216. }
  3217. this._clearHandlers();
  3218. if (this._loaded) {
  3219. // @section Map state change events
  3220. // @event unload: Event
  3221. // Fired when the map is destroyed with [remove](#map-remove) method.
  3222. this.fire('unload');
  3223. }
  3224. var i;
  3225. for (i in this._layers) {
  3226. this._layers[i].remove();
  3227. }
  3228. for (i in this._panes) {
  3229. remove(this._panes[i]);
  3230. }
  3231. this._layers = [];
  3232. this._panes = [];
  3233. delete this._mapPane;
  3234. delete this._renderer;
  3235. return this;
  3236. },
  3237. // @section Other Methods
  3238. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3239. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3240. // then returns it. The pane is created as a child of `container`, or
  3241. // as a child of the main map pane if not set.
  3242. createPane: function (name, container) {
  3243. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3244. pane = create$1('div', className, container || this._mapPane);
  3245. if (name) {
  3246. this._panes[name] = pane;
  3247. }
  3248. return pane;
  3249. },
  3250. // @section Methods for Getting Map State
  3251. // @method getCenter(): LatLng
  3252. // Returns the geographical center of the map view
  3253. getCenter: function () {
  3254. this._checkIfLoaded();
  3255. if (this._lastCenter && !this._moved()) {
  3256. return this._lastCenter.clone();
  3257. }
  3258. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3259. },
  3260. // @method getZoom(): Number
  3261. // Returns the current zoom level of the map view
  3262. getZoom: function () {
  3263. return this._zoom;
  3264. },
  3265. // @method getBounds(): LatLngBounds
  3266. // Returns the geographical bounds visible in the current map view
  3267. getBounds: function () {
  3268. var bounds = this.getPixelBounds(),
  3269. sw = this.unproject(bounds.getBottomLeft()),
  3270. ne = this.unproject(bounds.getTopRight());
  3271. return new LatLngBounds(sw, ne);
  3272. },
  3273. // @method getMinZoom(): Number
  3274. // 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.
  3275. getMinZoom: function () {
  3276. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3277. },
  3278. // @method getMaxZoom(): Number
  3279. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3280. getMaxZoom: function () {
  3281. return this.options.maxZoom === undefined ?
  3282. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3283. this.options.maxZoom;
  3284. },
  3285. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
  3286. // Returns the maximum zoom level on which the given bounds fit to the map
  3287. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3288. // instead returns the minimum zoom level on which the map view fits into
  3289. // the given bounds in its entirety.
  3290. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3291. bounds = toLatLngBounds(bounds);
  3292. padding = toPoint(padding || [0, 0]);
  3293. var zoom = this.getZoom() || 0,
  3294. min = this.getMinZoom(),
  3295. max = this.getMaxZoom(),
  3296. nw = bounds.getNorthWest(),
  3297. se = bounds.getSouthEast(),
  3298. size = this.getSize().subtract(padding),
  3299. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3300. snap = Browser.any3d ? this.options.zoomSnap : 1,
  3301. scalex = size.x / boundsSize.x,
  3302. scaley = size.y / boundsSize.y,
  3303. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3304. zoom = this.getScaleZoom(scale, zoom);
  3305. if (snap) {
  3306. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3307. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3308. }
  3309. return Math.max(min, Math.min(max, zoom));
  3310. },
  3311. // @method getSize(): Point
  3312. // Returns the current size of the map container (in pixels).
  3313. getSize: function () {
  3314. if (!this._size || this._sizeChanged) {
  3315. this._size = new Point(
  3316. this._container.clientWidth || 0,
  3317. this._container.clientHeight || 0);
  3318. this._sizeChanged = false;
  3319. }
  3320. return this._size.clone();
  3321. },
  3322. // @method getPixelBounds(): Bounds
  3323. // Returns the bounds of the current map view in projected pixel
  3324. // coordinates (sometimes useful in layer and overlay implementations).
  3325. getPixelBounds: function (center, zoom) {
  3326. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3327. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3328. },
  3329. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3330. // the map pane? "left point of the map layer" can be confusing, specially
  3331. // since there can be negative offsets.
  3332. // @method getPixelOrigin(): Point
  3333. // Returns the projected pixel coordinates of the top left point of
  3334. // the map layer (useful in custom layer and overlay implementations).
  3335. getPixelOrigin: function () {
  3336. this._checkIfLoaded();
  3337. return this._pixelOrigin;
  3338. },
  3339. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3340. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3341. // If `zoom` is omitted, the map's current zoom level is used.
  3342. getPixelWorldBounds: function (zoom) {
  3343. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3344. },
  3345. // @section Other Methods
  3346. // @method getPane(pane: String|HTMLElement): HTMLElement
  3347. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3348. getPane: function (pane) {
  3349. return typeof pane === 'string' ? this._panes[pane] : pane;
  3350. },
  3351. // @method getPanes(): Object
  3352. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3353. // the panes as values.
  3354. getPanes: function () {
  3355. return this._panes;
  3356. },
  3357. // @method getContainer: HTMLElement
  3358. // Returns the HTML element that contains the map.
  3359. getContainer: function () {
  3360. return this._container;
  3361. },
  3362. // @section Conversion Methods
  3363. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3364. // Returns the scale factor to be applied to a map transition from zoom level
  3365. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3366. getZoomScale: function (toZoom, fromZoom) {
  3367. // TODO replace with universal implementation after refactoring projections
  3368. var crs = this.options.crs;
  3369. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3370. return crs.scale(toZoom) / crs.scale(fromZoom);
  3371. },
  3372. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3373. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3374. // level and everything is scaled by a factor of `scale`. Inverse of
  3375. // [`getZoomScale`](#map-getZoomScale).
  3376. getScaleZoom: function (scale, fromZoom) {
  3377. var crs = this.options.crs;
  3378. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3379. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3380. return isNaN(zoom) ? Infinity : zoom;
  3381. },
  3382. // @method project(latlng: LatLng, zoom: Number): Point
  3383. // Projects a geographical coordinate `LatLng` according to the projection
  3384. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3385. // `Transformation`. The result is pixel coordinate relative to
  3386. // the CRS origin.
  3387. project: function (latlng, zoom) {
  3388. zoom = zoom === undefined ? this._zoom : zoom;
  3389. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3390. },
  3391. // @method unproject(point: Point, zoom: Number): LatLng
  3392. // Inverse of [`project`](#map-project).
  3393. unproject: function (point, zoom) {
  3394. zoom = zoom === undefined ? this._zoom : zoom;
  3395. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3396. },
  3397. // @method layerPointToLatLng(point: Point): LatLng
  3398. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3399. // returns the corresponding geographical coordinate (for the current zoom level).
  3400. layerPointToLatLng: function (point) {
  3401. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3402. return this.unproject(projectedPoint);
  3403. },
  3404. // @method latLngToLayerPoint(latlng: LatLng): Point
  3405. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3406. // relative to the [origin pixel](#map-getpixelorigin).
  3407. latLngToLayerPoint: function (latlng) {
  3408. var projectedPoint = this.project(toLatLng(latlng))._round();
  3409. return projectedPoint._subtract(this.getPixelOrigin());
  3410. },
  3411. // @method wrapLatLng(latlng: LatLng): LatLng
  3412. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3413. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3414. // CRS's bounds.
  3415. // By default this means longitude is wrapped around the dateline so its
  3416. // value is between -180 and +180 degrees.
  3417. wrapLatLng: function (latlng) {
  3418. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3419. },
  3420. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3421. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3422. // its center is within the CRS's bounds.
  3423. // By default this means the center longitude is wrapped around the dateline so its
  3424. // value is between -180 and +180 degrees, and the majority of the bounds
  3425. // overlaps the CRS's bounds.
  3426. wrapLatLngBounds: function (latlng) {
  3427. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3428. },
  3429. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3430. // Returns the distance between two geographical coordinates according to
  3431. // the map's CRS. By default this measures distance in meters.
  3432. distance: function (latlng1, latlng2) {
  3433. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3434. },
  3435. // @method containerPointToLayerPoint(point: Point): Point
  3436. // Given a pixel coordinate relative to the map container, returns the corresponding
  3437. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3438. containerPointToLayerPoint: function (point) { // (Point)
  3439. return toPoint(point).subtract(this._getMapPanePos());
  3440. },
  3441. // @method layerPointToContainerPoint(point: Point): Point
  3442. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3443. // returns the corresponding pixel coordinate relative to the map container.
  3444. layerPointToContainerPoint: function (point) { // (Point)
  3445. return toPoint(point).add(this._getMapPanePos());
  3446. },
  3447. // @method containerPointToLatLng(point: Point): LatLng
  3448. // Given a pixel coordinate relative to the map container, returns
  3449. // the corresponding geographical coordinate (for the current zoom level).
  3450. containerPointToLatLng: function (point) {
  3451. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3452. return this.layerPointToLatLng(layerPoint);
  3453. },
  3454. // @method latLngToContainerPoint(latlng: LatLng): Point
  3455. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3456. // relative to the map container.
  3457. latLngToContainerPoint: function (latlng) {
  3458. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3459. },
  3460. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3461. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3462. // map container where the event took place.
  3463. mouseEventToContainerPoint: function (e) {
  3464. return getMousePosition(e, this._container);
  3465. },
  3466. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3467. // Given a MouseEvent object, returns the pixel coordinate relative to
  3468. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3469. mouseEventToLayerPoint: function (e) {
  3470. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3471. },
  3472. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3473. // Given a MouseEvent object, returns geographical coordinate where the
  3474. // event took place.
  3475. mouseEventToLatLng: function (e) { // (MouseEvent)
  3476. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3477. },
  3478. // map initialization methods
  3479. _initContainer: function (id) {
  3480. var container = this._container = get(id);
  3481. if (!container) {
  3482. throw new Error('Map container not found.');
  3483. } else if (container._leaflet_id) {
  3484. throw new Error('Map container is already initialized.');
  3485. }
  3486. on(container, 'scroll', this._onScroll, this);
  3487. this._containerId = stamp(container);
  3488. },
  3489. _initLayout: function () {
  3490. var container = this._container;
  3491. this._fadeAnimated = this.options.fadeAnimation && Browser.any3d;
  3492. addClass(container, 'leaflet-container' +
  3493. (Browser.touch ? ' leaflet-touch' : '') +
  3494. (Browser.retina ? ' leaflet-retina' : '') +
  3495. (Browser.ielt9 ? ' leaflet-oldie' : '') +
  3496. (Browser.safari ? ' leaflet-safari' : '') +
  3497. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3498. var position = getStyle(container, 'position');
  3499. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  3500. container.style.position = 'relative';
  3501. }
  3502. this._initPanes();
  3503. if (this._initControlPos) {
  3504. this._initControlPos();
  3505. }
  3506. },
  3507. _initPanes: function () {
  3508. var panes = this._panes = {};
  3509. this._paneRenderers = {};
  3510. // @section
  3511. //
  3512. // Panes are DOM elements used to control the ordering of layers on the map. You
  3513. // can access panes with [`map.getPane`](#map-getpane) or
  3514. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3515. // [`map.createPane`](#map-createpane) method.
  3516. //
  3517. // Every map has the following default panes that differ only in zIndex.
  3518. //
  3519. // @pane mapPane: HTMLElement = 'auto'
  3520. // Pane that contains all other map panes
  3521. this._mapPane = this.createPane('mapPane', this._container);
  3522. setPosition(this._mapPane, new Point(0, 0));
  3523. // @pane tilePane: HTMLElement = 200
  3524. // Pane for `GridLayer`s and `TileLayer`s
  3525. this.createPane('tilePane');
  3526. // @pane overlayPane: HTMLElement = 400
  3527. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  3528. this.createPane('overlayPane');
  3529. // @pane shadowPane: HTMLElement = 500
  3530. // Pane for overlay shadows (e.g. `Marker` shadows)
  3531. this.createPane('shadowPane');
  3532. // @pane markerPane: HTMLElement = 600
  3533. // Pane for `Icon`s of `Marker`s
  3534. this.createPane('markerPane');
  3535. // @pane tooltipPane: HTMLElement = 650
  3536. // Pane for `Tooltip`s.
  3537. this.createPane('tooltipPane');
  3538. // @pane popupPane: HTMLElement = 700
  3539. // Pane for `Popup`s.
  3540. this.createPane('popupPane');
  3541. if (!this.options.markerZoomAnimation) {
  3542. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3543. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3544. }
  3545. },
  3546. // private methods that modify map state
  3547. // @section Map state change events
  3548. _resetView: function (center, zoom, noMoveStart) {
  3549. setPosition(this._mapPane, new Point(0, 0));
  3550. var loading = !this._loaded;
  3551. this._loaded = true;
  3552. zoom = this._limitZoom(zoom);
  3553. this.fire('viewprereset');
  3554. var zoomChanged = this._zoom !== zoom;
  3555. this
  3556. ._moveStart(zoomChanged, noMoveStart)
  3557. ._move(center, zoom)
  3558. ._moveEnd(zoomChanged);
  3559. // @event viewreset: Event
  3560. // Fired when the map needs to redraw its content (this usually happens
  3561. // on map zoom or load). Very useful for creating custom overlays.
  3562. this.fire('viewreset');
  3563. // @event load: Event
  3564. // Fired when the map is initialized (when its center and zoom are set
  3565. // for the first time).
  3566. if (loading) {
  3567. this.fire('load');
  3568. }
  3569. },
  3570. _moveStart: function (zoomChanged, noMoveStart) {
  3571. // @event zoomstart: Event
  3572. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3573. // @event movestart: Event
  3574. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3575. if (zoomChanged) {
  3576. this.fire('zoomstart');
  3577. }
  3578. if (!noMoveStart) {
  3579. this.fire('movestart');
  3580. }
  3581. return this;
  3582. },
  3583. _move: function (center, zoom, data, supressEvent) {
  3584. if (zoom === undefined) {
  3585. zoom = this._zoom;
  3586. }
  3587. var zoomChanged = this._zoom !== zoom;
  3588. this._zoom = zoom;
  3589. this._lastCenter = center;
  3590. this._pixelOrigin = this._getNewPixelOrigin(center);
  3591. if (!supressEvent) {
  3592. // @event zoom: Event
  3593. // Fired repeatedly during any change in zoom level,
  3594. // including zoom and fly animations.
  3595. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3596. this.fire('zoom', data);
  3597. }
  3598. // @event move: Event
  3599. // Fired repeatedly during any movement of the map,
  3600. // including pan and fly animations.
  3601. this.fire('move', data);
  3602. } else if (data && data.pinch) { // Always fire 'zoom' if pinching because #3530
  3603. this.fire('zoom', data);
  3604. }
  3605. return this;
  3606. },
  3607. _moveEnd: function (zoomChanged) {
  3608. // @event zoomend: Event
  3609. // Fired when the map zoom changed, after any animations.
  3610. if (zoomChanged) {
  3611. this.fire('zoomend');
  3612. }
  3613. // @event moveend: Event
  3614. // Fired when the center of the map stops changing
  3615. // (e.g. user stopped dragging the map or after non-centered zoom).
  3616. return this.fire('moveend');
  3617. },
  3618. _stop: function () {
  3619. cancelAnimFrame(this._flyToFrame);
  3620. if (this._panAnim) {
  3621. this._panAnim.stop();
  3622. }
  3623. return this;
  3624. },
  3625. _rawPanBy: function (offset) {
  3626. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3627. },
  3628. _getZoomSpan: function () {
  3629. return this.getMaxZoom() - this.getMinZoom();
  3630. },
  3631. _panInsideMaxBounds: function () {
  3632. if (!this._enforcingBounds) {
  3633. this.panInsideBounds(this.options.maxBounds);
  3634. }
  3635. },
  3636. _checkIfLoaded: function () {
  3637. if (!this._loaded) {
  3638. throw new Error('Set map center and zoom first.');
  3639. }
  3640. },
  3641. // DOM event handling
  3642. // @section Interaction events
  3643. _initEvents: function (remove) {
  3644. this._targets = {};
  3645. this._targets[stamp(this._container)] = this;
  3646. var onOff = remove ? off : on;
  3647. // @event click: MouseEvent
  3648. // Fired when the user clicks (or taps) the map.
  3649. // @event dblclick: MouseEvent
  3650. // Fired when the user double-clicks (or double-taps) the map.
  3651. // @event mousedown: MouseEvent
  3652. // Fired when the user pushes the mouse button on the map.
  3653. // @event mouseup: MouseEvent
  3654. // Fired when the user releases the mouse button on the map.
  3655. // @event mouseover: MouseEvent
  3656. // Fired when the mouse enters the map.
  3657. // @event mouseout: MouseEvent
  3658. // Fired when the mouse leaves the map.
  3659. // @event mousemove: MouseEvent
  3660. // Fired while the mouse moves over the map.
  3661. // @event contextmenu: MouseEvent
  3662. // Fired when the user pushes the right mouse button on the map, prevents
  3663. // default browser context menu from showing if there are listeners on
  3664. // this event. Also fired on mobile when the user holds a single touch
  3665. // for a second (also called long press).
  3666. // @event keypress: KeyboardEvent
  3667. // Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
  3668. // @event keydown: KeyboardEvent
  3669. // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
  3670. // the `keydown` event is fired for keys that produce a character value and for keys
  3671. // that do not produce a character value.
  3672. // @event keyup: KeyboardEvent
  3673. // Fired when the user releases a key from the keyboard while the map is focused.
  3674. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3675. 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
  3676. if (this.options.trackResize) {
  3677. onOff(window, 'resize', this._onResize, this);
  3678. }
  3679. if (Browser.any3d && this.options.transform3DLimit) {
  3680. (remove ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3681. }
  3682. },
  3683. _onResize: function () {
  3684. cancelAnimFrame(this._resizeRequest);
  3685. this._resizeRequest = requestAnimFrame(
  3686. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3687. },
  3688. _onScroll: function () {
  3689. this._container.scrollTop = 0;
  3690. this._container.scrollLeft = 0;
  3691. },
  3692. _onMoveEnd: function () {
  3693. var pos = this._getMapPanePos();
  3694. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3695. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3696. // a pixel offset on very high values, see: https://jsfiddle.net/dg6r5hhb/
  3697. this._resetView(this.getCenter(), this.getZoom());
  3698. }
  3699. },
  3700. _findEventTargets: function (e, type) {
  3701. var targets = [],
  3702. target,
  3703. isHover = type === 'mouseout' || type === 'mouseover',
  3704. src = e.target || e.srcElement,
  3705. dragging = false;
  3706. while (src) {
  3707. target = this._targets[stamp(src)];
  3708. if (target && (type === 'click' || type === 'preclick') && this._draggableMoved(target)) {
  3709. // Prevent firing click after you just dragged an object.
  3710. dragging = true;
  3711. break;
  3712. }
  3713. if (target && target.listens(type, true)) {
  3714. if (isHover && !isExternalTarget(src, e)) { break; }
  3715. targets.push(target);
  3716. if (isHover) { break; }
  3717. }
  3718. if (src === this._container) { break; }
  3719. src = src.parentNode;
  3720. }
  3721. if (!targets.length && !dragging && !isHover && this.listens(type, true)) {
  3722. targets = [this];
  3723. }
  3724. return targets;
  3725. },
  3726. _isClickDisabled: function (el) {
  3727. while (el && el !== this._container) {
  3728. if (el['_leaflet_disable_click']) { return true; }
  3729. el = el.parentNode;
  3730. }
  3731. },
  3732. _handleDOMEvent: function (e) {
  3733. var el = (e.target || e.srcElement);
  3734. if (!this._loaded || el['_leaflet_disable_events'] || e.type === 'click' && this._isClickDisabled(el)) {
  3735. return;
  3736. }
  3737. var type = e.type;
  3738. if (type === 'mousedown') {
  3739. // prevents outline when clicking on keyboard-focusable element
  3740. preventOutline(el);
  3741. }
  3742. this._fireDOMEvent(e, type);
  3743. },
  3744. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3745. _fireDOMEvent: function (e, type, canvasTargets) {
  3746. if (e.type === 'click') {
  3747. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3748. // @event preclick: MouseEvent
  3749. // Fired before mouse click on the map (sometimes useful when you
  3750. // want something to happen on click before any existing click
  3751. // handlers start running).
  3752. var synth = extend({}, e);
  3753. synth.type = 'preclick';
  3754. this._fireDOMEvent(synth, synth.type, canvasTargets);
  3755. }
  3756. // Find the layer the event is propagating from and its parents.
  3757. var targets = this._findEventTargets(e, type);
  3758. if (canvasTargets) {
  3759. var filtered = []; // pick only targets with listeners
  3760. for (var i = 0; i < canvasTargets.length; i++) {
  3761. if (canvasTargets[i].listens(type, true)) {
  3762. filtered.push(canvasTargets[i]);
  3763. }
  3764. }
  3765. targets = filtered.concat(targets);
  3766. }
  3767. if (!targets.length) { return; }
  3768. if (type === 'contextmenu') {
  3769. preventDefault(e);
  3770. }
  3771. var target = targets[0];
  3772. var data = {
  3773. originalEvent: e
  3774. };
  3775. if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
  3776. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  3777. data.containerPoint = isMarker ?
  3778. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3779. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3780. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3781. }
  3782. for (i = 0; i < targets.length; i++) {
  3783. targets[i].fire(type, data, true);
  3784. if (data.originalEvent._stopped ||
  3785. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3786. }
  3787. },
  3788. _draggableMoved: function (obj) {
  3789. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3790. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3791. },
  3792. _clearHandlers: function () {
  3793. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3794. this._handlers[i].disable();
  3795. }
  3796. },
  3797. // @section Other Methods
  3798. // @method whenReady(fn: Function, context?: Object): this
  3799. // Runs the given function `fn` when the map gets initialized with
  3800. // a view (center and zoom) and at least one layer, or immediately
  3801. // if it's already initialized, optionally passing a function context.
  3802. whenReady: function (callback, context) {
  3803. if (this._loaded) {
  3804. callback.call(context || this, {target: this});
  3805. } else {
  3806. this.on('load', callback, context);
  3807. }
  3808. return this;
  3809. },
  3810. // private methods for getting map state
  3811. _getMapPanePos: function () {
  3812. return getPosition(this._mapPane) || new Point(0, 0);
  3813. },
  3814. _moved: function () {
  3815. var pos = this._getMapPanePos();
  3816. return pos && !pos.equals([0, 0]);
  3817. },
  3818. _getTopLeftPoint: function (center, zoom) {
  3819. var pixelOrigin = center && zoom !== undefined ?
  3820. this._getNewPixelOrigin(center, zoom) :
  3821. this.getPixelOrigin();
  3822. return pixelOrigin.subtract(this._getMapPanePos());
  3823. },
  3824. _getNewPixelOrigin: function (center, zoom) {
  3825. var viewHalf = this.getSize()._divideBy(2);
  3826. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3827. },
  3828. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3829. var topLeft = this._getNewPixelOrigin(center, zoom);
  3830. return this.project(latlng, zoom)._subtract(topLeft);
  3831. },
  3832. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3833. var topLeft = this._getNewPixelOrigin(center, zoom);
  3834. return toBounds([
  3835. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3836. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3837. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3838. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3839. ]);
  3840. },
  3841. // layer point of the current center
  3842. _getCenterLayerPoint: function () {
  3843. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3844. },
  3845. // offset of the specified place to the current center in pixels
  3846. _getCenterOffset: function (latlng) {
  3847. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3848. },
  3849. // adjust center for view to get inside bounds
  3850. _limitCenter: function (center, zoom, bounds) {
  3851. if (!bounds) { return center; }
  3852. var centerPoint = this.project(center, zoom),
  3853. viewHalf = this.getSize().divideBy(2),
  3854. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3855. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3856. // If offset is less than a pixel, ignore.
  3857. // This prevents unstable projections from getting into
  3858. // an infinite loop of tiny offsets.
  3859. if (offset.round().equals([0, 0])) {
  3860. return center;
  3861. }
  3862. return this.unproject(centerPoint.add(offset), zoom);
  3863. },
  3864. // adjust offset for view to get inside bounds
  3865. _limitOffset: function (offset, bounds) {
  3866. if (!bounds) { return offset; }
  3867. var viewBounds = this.getPixelBounds(),
  3868. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3869. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3870. },
  3871. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3872. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3873. var projectedMaxBounds = toBounds(
  3874. this.project(maxBounds.getNorthEast(), zoom),
  3875. this.project(maxBounds.getSouthWest(), zoom)
  3876. ),
  3877. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3878. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3879. dx = this._rebound(minOffset.x, -maxOffset.x),
  3880. dy = this._rebound(minOffset.y, -maxOffset.y);
  3881. return new Point(dx, dy);
  3882. },
  3883. _rebound: function (left, right) {
  3884. return left + right > 0 ?
  3885. Math.round(left - right) / 2 :
  3886. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3887. },
  3888. _limitZoom: function (zoom) {
  3889. var min = this.getMinZoom(),
  3890. max = this.getMaxZoom(),
  3891. snap = Browser.any3d ? this.options.zoomSnap : 1;
  3892. if (snap) {
  3893. zoom = Math.round(zoom / snap) * snap;
  3894. }
  3895. return Math.max(min, Math.min(max, zoom));
  3896. },
  3897. _onPanTransitionStep: function () {
  3898. this.fire('move');
  3899. },
  3900. _onPanTransitionEnd: function () {
  3901. removeClass(this._mapPane, 'leaflet-pan-anim');
  3902. this.fire('moveend');
  3903. },
  3904. _tryAnimatedPan: function (center, options) {
  3905. // difference between the new and current centers in pixels
  3906. var offset = this._getCenterOffset(center)._trunc();
  3907. // don't animate too far unless animate: true specified in options
  3908. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3909. this.panBy(offset, options);
  3910. return true;
  3911. },
  3912. _createAnimProxy: function () {
  3913. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3914. this._panes.mapPane.appendChild(proxy);
  3915. this.on('zoomanim', function (e) {
  3916. var prop = TRANSFORM,
  3917. transform = this._proxy.style[prop];
  3918. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3919. // workaround for case when transform is the same and so transitionend event is not fired
  3920. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3921. this._onZoomTransitionEnd();
  3922. }
  3923. }, this);
  3924. this.on('load moveend', this._animMoveEnd, this);
  3925. this._on('unload', this._destroyAnimProxy, this);
  3926. },
  3927. _destroyAnimProxy: function () {
  3928. remove(this._proxy);
  3929. this.off('load moveend', this._animMoveEnd, this);
  3930. delete this._proxy;
  3931. },
  3932. _animMoveEnd: function () {
  3933. var c = this.getCenter(),
  3934. z = this.getZoom();
  3935. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3936. },
  3937. _catchTransitionEnd: function (e) {
  3938. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3939. this._onZoomTransitionEnd();
  3940. }
  3941. },
  3942. _nothingToAnimate: function () {
  3943. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3944. },
  3945. _tryAnimatedZoom: function (center, zoom, options) {
  3946. if (this._animatingZoom) { return true; }
  3947. options = options || {};
  3948. // don't animate if disabled, not supported or zoom difference is too large
  3949. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3950. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3951. // offset is the pixel coords of the zoom origin relative to the current center
  3952. var scale = this.getZoomScale(zoom),
  3953. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3954. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3955. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3956. requestAnimFrame(function () {
  3957. this
  3958. ._moveStart(true, false)
  3959. ._animateZoom(center, zoom, true);
  3960. }, this);
  3961. return true;
  3962. },
  3963. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3964. if (!this._mapPane) { return; }
  3965. if (startAnim) {
  3966. this._animatingZoom = true;
  3967. // remember what center/zoom to set after animation
  3968. this._animateToCenter = center;
  3969. this._animateToZoom = zoom;
  3970. addClass(this._mapPane, 'leaflet-zoom-anim');
  3971. }
  3972. // @section Other Events
  3973. // @event zoomanim: ZoomAnimEvent
  3974. // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
  3975. this.fire('zoomanim', {
  3976. center: center,
  3977. zoom: zoom,
  3978. noUpdate: noUpdate
  3979. });
  3980. if (!this._tempFireZoomEvent) {
  3981. this._tempFireZoomEvent = this._zoom !== this._animateToZoom;
  3982. }
  3983. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  3984. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3985. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3986. },
  3987. _onZoomTransitionEnd: function () {
  3988. if (!this._animatingZoom) { return; }
  3989. if (this._mapPane) {
  3990. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3991. }
  3992. this._animatingZoom = false;
  3993. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  3994. if (this._tempFireZoomEvent) {
  3995. this.fire('zoom');
  3996. }
  3997. delete this._tempFireZoomEvent;
  3998. this.fire('move');
  3999. this._moveEnd(true);
  4000. }
  4001. });
  4002. // @section
  4003. // @factory L.map(id: String, options?: Map options)
  4004. // Instantiates a map object given the DOM ID of a `<div>` element
  4005. // and optionally an object literal with `Map options`.
  4006. //
  4007. // @alternative
  4008. // @factory L.map(el: HTMLElement, options?: Map options)
  4009. // Instantiates a map object given an instance of a `<div>` HTML element
  4010. // and optionally an object literal with `Map options`.
  4011. function createMap(id, options) {
  4012. return new Map(id, options);
  4013. }
  4014. /*
  4015. * @class Control
  4016. * @aka L.Control
  4017. * @inherits Class
  4018. *
  4019. * L.Control is a base class for implementing map controls. Handles positioning.
  4020. * All other controls extend from this class.
  4021. */
  4022. var Control = Class.extend({
  4023. // @section
  4024. // @aka Control Options
  4025. options: {
  4026. // @option position: String = 'topright'
  4027. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  4028. // `'topright'`, `'bottomleft'` or `'bottomright'`
  4029. position: 'topright'
  4030. },
  4031. initialize: function (options) {
  4032. setOptions(this, options);
  4033. },
  4034. /* @section
  4035. * Classes extending L.Control will inherit the following methods:
  4036. *
  4037. * @method getPosition: string
  4038. * Returns the position of the control.
  4039. */
  4040. getPosition: function () {
  4041. return this.options.position;
  4042. },
  4043. // @method setPosition(position: string): this
  4044. // Sets the position of the control.
  4045. setPosition: function (position) {
  4046. var map = this._map;
  4047. if (map) {
  4048. map.removeControl(this);
  4049. }
  4050. this.options.position = position;
  4051. if (map) {
  4052. map.addControl(this);
  4053. }
  4054. return this;
  4055. },
  4056. // @method getContainer: HTMLElement
  4057. // Returns the HTMLElement that contains the control.
  4058. getContainer: function () {
  4059. return this._container;
  4060. },
  4061. // @method addTo(map: Map): this
  4062. // Adds the control to the given map.
  4063. addTo: function (map) {
  4064. this.remove();
  4065. this._map = map;
  4066. var container = this._container = this.onAdd(map),
  4067. pos = this.getPosition(),
  4068. corner = map._controlCorners[pos];
  4069. addClass(container, 'leaflet-control');
  4070. if (pos.indexOf('bottom') !== -1) {
  4071. corner.insertBefore(container, corner.firstChild);
  4072. } else {
  4073. corner.appendChild(container);
  4074. }
  4075. this._map.on('unload', this.remove, this);
  4076. return this;
  4077. },
  4078. // @method remove: this
  4079. // Removes the control from the map it is currently active on.
  4080. remove: function () {
  4081. if (!this._map) {
  4082. return this;
  4083. }
  4084. remove(this._container);
  4085. if (this.onRemove) {
  4086. this.onRemove(this._map);
  4087. }
  4088. this._map.off('unload', this.remove, this);
  4089. this._map = null;
  4090. return this;
  4091. },
  4092. _refocusOnMap: function (e) {
  4093. // if map exists and event is not a keyboard event
  4094. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  4095. this._map.getContainer().focus();
  4096. }
  4097. }
  4098. });
  4099. var control = function (options) {
  4100. return new Control(options);
  4101. };
  4102. /* @section Extension methods
  4103. * @uninheritable
  4104. *
  4105. * Every control should extend from `L.Control` and (re-)implement the following methods.
  4106. *
  4107. * @method onAdd(map: Map): HTMLElement
  4108. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  4109. *
  4110. * @method onRemove(map: Map)
  4111. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  4112. */
  4113. /* @namespace Map
  4114. * @section Methods for Layers and Controls
  4115. */
  4116. Map.include({
  4117. // @method addControl(control: Control): this
  4118. // Adds the given control to the map
  4119. addControl: function (control) {
  4120. control.addTo(this);
  4121. return this;
  4122. },
  4123. // @method removeControl(control: Control): this
  4124. // Removes the given control from the map
  4125. removeControl: function (control) {
  4126. control.remove();
  4127. return this;
  4128. },
  4129. _initControlPos: function () {
  4130. var corners = this._controlCorners = {},
  4131. l = 'leaflet-',
  4132. container = this._controlContainer =
  4133. create$1('div', l + 'control-container', this._container);
  4134. function createCorner(vSide, hSide) {
  4135. var className = l + vSide + ' ' + l + hSide;
  4136. corners[vSide + hSide] = create$1('div', className, container);
  4137. }
  4138. createCorner('top', 'left');
  4139. createCorner('top', 'right');
  4140. createCorner('bottom', 'left');
  4141. createCorner('bottom', 'right');
  4142. },
  4143. _clearControlPos: function () {
  4144. for (var i in this._controlCorners) {
  4145. remove(this._controlCorners[i]);
  4146. }
  4147. remove(this._controlContainer);
  4148. delete this._controlCorners;
  4149. delete this._controlContainer;
  4150. }
  4151. });
  4152. /*
  4153. * @class Control.Layers
  4154. * @aka L.Control.Layers
  4155. * @inherits Control
  4156. *
  4157. * 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`.
  4158. *
  4159. * @example
  4160. *
  4161. * ```js
  4162. * var baseLayers = {
  4163. * "Mapbox": mapbox,
  4164. * "OpenStreetMap": osm
  4165. * };
  4166. *
  4167. * var overlays = {
  4168. * "Marker": marker,
  4169. * "Roads": roadsLayer
  4170. * };
  4171. *
  4172. * L.control.layers(baseLayers, overlays).addTo(map);
  4173. * ```
  4174. *
  4175. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  4176. *
  4177. * ```js
  4178. * {
  4179. * "<someName1>": layer1,
  4180. * "<someName2>": layer2
  4181. * }
  4182. * ```
  4183. *
  4184. * The layer names can contain HTML, which allows you to add additional styling to the items:
  4185. *
  4186. * ```js
  4187. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  4188. * ```
  4189. */
  4190. var Layers = Control.extend({
  4191. // @section
  4192. // @aka Control.Layers options
  4193. options: {
  4194. // @option collapsed: Boolean = true
  4195. // If `true`, the control will be collapsed into an icon and expanded on mouse hover, touch, or keyboard activation.
  4196. collapsed: true,
  4197. position: 'topright',
  4198. // @option autoZIndex: Boolean = true
  4199. // 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.
  4200. autoZIndex: true,
  4201. // @option hideSingleBase: Boolean = false
  4202. // If `true`, the base layers in the control will be hidden when there is only one.
  4203. hideSingleBase: false,
  4204. // @option sortLayers: Boolean = false
  4205. // Whether to sort the layers. When `false`, layers will keep the order
  4206. // in which they were added to the control.
  4207. sortLayers: false,
  4208. // @option sortFunction: Function = *
  4209. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  4210. // that will be used for sorting the layers, when `sortLayers` is `true`.
  4211. // The function receives both the `L.Layer` instances and their names, as in
  4212. // `sortFunction(layerA, layerB, nameA, nameB)`.
  4213. // By default, it sorts layers alphabetically by their name.
  4214. sortFunction: function (layerA, layerB, nameA, nameB) {
  4215. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  4216. }
  4217. },
  4218. initialize: function (baseLayers, overlays, options) {
  4219. setOptions(this, options);
  4220. this._layerControlInputs = [];
  4221. this._layers = [];
  4222. this._lastZIndex = 0;
  4223. this._handlingClick = false;
  4224. for (var i in baseLayers) {
  4225. this._addLayer(baseLayers[i], i);
  4226. }
  4227. for (i in overlays) {
  4228. this._addLayer(overlays[i], i, true);
  4229. }
  4230. },
  4231. onAdd: function (map) {
  4232. this._initLayout();
  4233. this._update();
  4234. this._map = map;
  4235. map.on('zoomend', this._checkDisabledLayers, this);
  4236. for (var i = 0; i < this._layers.length; i++) {
  4237. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4238. }
  4239. return this._container;
  4240. },
  4241. addTo: function (map) {
  4242. Control.prototype.addTo.call(this, map);
  4243. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4244. return this._expandIfNotCollapsed();
  4245. },
  4246. onRemove: function () {
  4247. this._map.off('zoomend', this._checkDisabledLayers, this);
  4248. for (var i = 0; i < this._layers.length; i++) {
  4249. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4250. }
  4251. },
  4252. // @method addBaseLayer(layer: Layer, name: String): this
  4253. // Adds a base layer (radio button entry) with the given name to the control.
  4254. addBaseLayer: function (layer, name) {
  4255. this._addLayer(layer, name);
  4256. return (this._map) ? this._update() : this;
  4257. },
  4258. // @method addOverlay(layer: Layer, name: String): this
  4259. // Adds an overlay (checkbox entry) with the given name to the control.
  4260. addOverlay: function (layer, name) {
  4261. this._addLayer(layer, name, true);
  4262. return (this._map) ? this._update() : this;
  4263. },
  4264. // @method removeLayer(layer: Layer): this
  4265. // Remove the given layer from the control.
  4266. removeLayer: function (layer) {
  4267. layer.off('add remove', this._onLayerChange, this);
  4268. var obj = this._getLayer(stamp(layer));
  4269. if (obj) {
  4270. this._layers.splice(this._layers.indexOf(obj), 1);
  4271. }
  4272. return (this._map) ? this._update() : this;
  4273. },
  4274. // @method expand(): this
  4275. // Expand the control container if collapsed.
  4276. expand: function () {
  4277. addClass(this._container, 'leaflet-control-layers-expanded');
  4278. this._section.style.height = null;
  4279. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4280. if (acceptableHeight < this._section.clientHeight) {
  4281. addClass(this._section, 'leaflet-control-layers-scrollbar');
  4282. this._section.style.height = acceptableHeight + 'px';
  4283. } else {
  4284. removeClass(this._section, 'leaflet-control-layers-scrollbar');
  4285. }
  4286. this._checkDisabledLayers();
  4287. return this;
  4288. },
  4289. // @method collapse(): this
  4290. // Collapse the control container if expanded.
  4291. collapse: function () {
  4292. removeClass(this._container, 'leaflet-control-layers-expanded');
  4293. return this;
  4294. },
  4295. _initLayout: function () {
  4296. var className = 'leaflet-control-layers',
  4297. container = this._container = create$1('div', className),
  4298. collapsed = this.options.collapsed;
  4299. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4300. container.setAttribute('aria-haspopup', true);
  4301. disableClickPropagation(container);
  4302. disableScrollPropagation(container);
  4303. var section = this._section = create$1('section', className + '-list');
  4304. if (collapsed) {
  4305. this._map.on('click', this.collapse, this);
  4306. on(container, {
  4307. mouseenter: function () {
  4308. on(section, 'click', preventDefault);
  4309. this.expand();
  4310. setTimeout(function () {
  4311. off(section, 'click', preventDefault);
  4312. });
  4313. },
  4314. mouseleave: this.collapse
  4315. }, this);
  4316. }
  4317. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4318. link.href = '#';
  4319. link.title = 'Layers';
  4320. link.setAttribute('role', 'button');
  4321. on(link, 'click', preventDefault); // prevent link function
  4322. on(link, 'focus', this.expand, this);
  4323. if (!collapsed) {
  4324. this.expand();
  4325. }
  4326. this._baseLayersList = create$1('div', className + '-base', section);
  4327. this._separator = create$1('div', className + '-separator', section);
  4328. this._overlaysList = create$1('div', className + '-overlays', section);
  4329. container.appendChild(section);
  4330. },
  4331. _getLayer: function (id) {
  4332. for (var i = 0; i < this._layers.length; i++) {
  4333. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4334. return this._layers[i];
  4335. }
  4336. }
  4337. },
  4338. _addLayer: function (layer, name, overlay) {
  4339. if (this._map) {
  4340. layer.on('add remove', this._onLayerChange, this);
  4341. }
  4342. this._layers.push({
  4343. layer: layer,
  4344. name: name,
  4345. overlay: overlay
  4346. });
  4347. if (this.options.sortLayers) {
  4348. this._layers.sort(bind(function (a, b) {
  4349. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4350. }, this));
  4351. }
  4352. if (this.options.autoZIndex && layer.setZIndex) {
  4353. this._lastZIndex++;
  4354. layer.setZIndex(this._lastZIndex);
  4355. }
  4356. this._expandIfNotCollapsed();
  4357. },
  4358. _update: function () {
  4359. if (!this._container) { return this; }
  4360. empty(this._baseLayersList);
  4361. empty(this._overlaysList);
  4362. this._layerControlInputs = [];
  4363. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4364. for (i = 0; i < this._layers.length; i++) {
  4365. obj = this._layers[i];
  4366. this._addItem(obj);
  4367. overlaysPresent = overlaysPresent || obj.overlay;
  4368. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4369. baseLayersCount += !obj.overlay ? 1 : 0;
  4370. }
  4371. // Hide base layers section if there's only one layer.
  4372. if (this.options.hideSingleBase) {
  4373. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4374. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4375. }
  4376. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4377. return this;
  4378. },
  4379. _onLayerChange: function (e) {
  4380. if (!this._handlingClick) {
  4381. this._update();
  4382. }
  4383. var obj = this._getLayer(stamp(e.target));
  4384. // @namespace Map
  4385. // @section Layer events
  4386. // @event baselayerchange: LayersControlEvent
  4387. // Fired when the base layer is changed through the [layers control](#control-layers).
  4388. // @event overlayadd: LayersControlEvent
  4389. // Fired when an overlay is selected through the [layers control](#control-layers).
  4390. // @event overlayremove: LayersControlEvent
  4391. // Fired when an overlay is deselected through the [layers control](#control-layers).
  4392. // @namespace Control.Layers
  4393. var type = obj.overlay ?
  4394. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4395. (e.type === 'add' ? 'baselayerchange' : null);
  4396. if (type) {
  4397. this._map.fire(type, obj);
  4398. }
  4399. },
  4400. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see https://stackoverflow.com/a/119079)
  4401. _createRadioElement: function (name, checked) {
  4402. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4403. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4404. var radioFragment = document.createElement('div');
  4405. radioFragment.innerHTML = radioHtml;
  4406. return radioFragment.firstChild;
  4407. },
  4408. _addItem: function (obj) {
  4409. var label = document.createElement('label'),
  4410. checked = this._map.hasLayer(obj.layer),
  4411. input;
  4412. if (obj.overlay) {
  4413. input = document.createElement('input');
  4414. input.type = 'checkbox';
  4415. input.className = 'leaflet-control-layers-selector';
  4416. input.defaultChecked = checked;
  4417. } else {
  4418. input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);
  4419. }
  4420. this._layerControlInputs.push(input);
  4421. input.layerId = stamp(obj.layer);
  4422. on(input, 'click', this._onInputClick, this);
  4423. var name = document.createElement('span');
  4424. name.innerHTML = ' ' + obj.name;
  4425. // Helps from preventing layer control flicker when checkboxes are disabled
  4426. // https://github.com/Leaflet/Leaflet/issues/2771
  4427. var holder = document.createElement('span');
  4428. label.appendChild(holder);
  4429. holder.appendChild(input);
  4430. holder.appendChild(name);
  4431. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4432. container.appendChild(label);
  4433. this._checkDisabledLayers();
  4434. return label;
  4435. },
  4436. _onInputClick: function () {
  4437. var inputs = this._layerControlInputs,
  4438. input, layer;
  4439. var addedLayers = [],
  4440. removedLayers = [];
  4441. this._handlingClick = true;
  4442. for (var i = inputs.length - 1; i >= 0; i--) {
  4443. input = inputs[i];
  4444. layer = this._getLayer(input.layerId).layer;
  4445. if (input.checked) {
  4446. addedLayers.push(layer);
  4447. } else if (!input.checked) {
  4448. removedLayers.push(layer);
  4449. }
  4450. }
  4451. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4452. for (i = 0; i < removedLayers.length; i++) {
  4453. if (this._map.hasLayer(removedLayers[i])) {
  4454. this._map.removeLayer(removedLayers[i]);
  4455. }
  4456. }
  4457. for (i = 0; i < addedLayers.length; i++) {
  4458. if (!this._map.hasLayer(addedLayers[i])) {
  4459. this._map.addLayer(addedLayers[i]);
  4460. }
  4461. }
  4462. this._handlingClick = false;
  4463. this._refocusOnMap();
  4464. },
  4465. _checkDisabledLayers: function () {
  4466. var inputs = this._layerControlInputs,
  4467. input,
  4468. layer,
  4469. zoom = this._map.getZoom();
  4470. for (var i = inputs.length - 1; i >= 0; i--) {
  4471. input = inputs[i];
  4472. layer = this._getLayer(input.layerId).layer;
  4473. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4474. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4475. }
  4476. },
  4477. _expandIfNotCollapsed: function () {
  4478. if (this._map && !this.options.collapsed) {
  4479. this.expand();
  4480. }
  4481. return this;
  4482. }
  4483. });
  4484. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4485. // 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.
  4486. var layers = function (baseLayers, overlays, options) {
  4487. return new Layers(baseLayers, overlays, options);
  4488. };
  4489. /*
  4490. * @class Control.Zoom
  4491. * @aka L.Control.Zoom
  4492. * @inherits Control
  4493. *
  4494. * 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`.
  4495. */
  4496. var Zoom = Control.extend({
  4497. // @section
  4498. // @aka Control.Zoom options
  4499. options: {
  4500. position: 'topleft',
  4501. // @option zoomInText: String = '<span aria-hidden="true">+</span>'
  4502. // The text set on the 'zoom in' button.
  4503. zoomInText: '<span aria-hidden="true">+</span>',
  4504. // @option zoomInTitle: String = 'Zoom in'
  4505. // The title set on the 'zoom in' button.
  4506. zoomInTitle: 'Zoom in',
  4507. // @option zoomOutText: String = '<span aria-hidden="true">&#x2212;</span>'
  4508. // The text set on the 'zoom out' button.
  4509. zoomOutText: '<span aria-hidden="true">&#x2212;</span>',
  4510. // @option zoomOutTitle: String = 'Zoom out'
  4511. // The title set on the 'zoom out' button.
  4512. zoomOutTitle: 'Zoom out'
  4513. },
  4514. onAdd: function (map) {
  4515. var zoomName = 'leaflet-control-zoom',
  4516. container = create$1('div', zoomName + ' leaflet-bar'),
  4517. options = this.options;
  4518. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4519. zoomName + '-in', container, this._zoomIn);
  4520. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4521. zoomName + '-out', container, this._zoomOut);
  4522. this._updateDisabled();
  4523. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4524. return container;
  4525. },
  4526. onRemove: function (map) {
  4527. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4528. },
  4529. disable: function () {
  4530. this._disabled = true;
  4531. this._updateDisabled();
  4532. return this;
  4533. },
  4534. enable: function () {
  4535. this._disabled = false;
  4536. this._updateDisabled();
  4537. return this;
  4538. },
  4539. _zoomIn: function (e) {
  4540. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4541. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4542. }
  4543. },
  4544. _zoomOut: function (e) {
  4545. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4546. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4547. }
  4548. },
  4549. _createButton: function (html, title, className, container, fn) {
  4550. var link = create$1('a', className, container);
  4551. link.innerHTML = html;
  4552. link.href = '#';
  4553. link.title = title;
  4554. /*
  4555. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4556. */
  4557. link.setAttribute('role', 'button');
  4558. link.setAttribute('aria-label', title);
  4559. disableClickPropagation(link);
  4560. on(link, 'click', stop);
  4561. on(link, 'click', fn, this);
  4562. on(link, 'click', this._refocusOnMap, this);
  4563. return link;
  4564. },
  4565. _updateDisabled: function () {
  4566. var map = this._map,
  4567. className = 'leaflet-disabled';
  4568. removeClass(this._zoomInButton, className);
  4569. removeClass(this._zoomOutButton, className);
  4570. this._zoomInButton.setAttribute('aria-disabled', 'false');
  4571. this._zoomOutButton.setAttribute('aria-disabled', 'false');
  4572. if (this._disabled || map._zoom === map.getMinZoom()) {
  4573. addClass(this._zoomOutButton, className);
  4574. this._zoomOutButton.setAttribute('aria-disabled', 'true');
  4575. }
  4576. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4577. addClass(this._zoomInButton, className);
  4578. this._zoomInButton.setAttribute('aria-disabled', 'true');
  4579. }
  4580. }
  4581. });
  4582. // @namespace Map
  4583. // @section Control options
  4584. // @option zoomControl: Boolean = true
  4585. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4586. Map.mergeOptions({
  4587. zoomControl: true
  4588. });
  4589. Map.addInitHook(function () {
  4590. if (this.options.zoomControl) {
  4591. // @section Controls
  4592. // @property zoomControl: Control.Zoom
  4593. // The default zoom control (only available if the
  4594. // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
  4595. this.zoomControl = new Zoom();
  4596. this.addControl(this.zoomControl);
  4597. }
  4598. });
  4599. // @namespace Control.Zoom
  4600. // @factory L.control.zoom(options: Control.Zoom options)
  4601. // Creates a zoom control
  4602. var zoom = function (options) {
  4603. return new Zoom(options);
  4604. };
  4605. /*
  4606. * @class Control.Scale
  4607. * @aka L.Control.Scale
  4608. * @inherits Control
  4609. *
  4610. * 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`.
  4611. *
  4612. * @example
  4613. *
  4614. * ```js
  4615. * L.control.scale().addTo(map);
  4616. * ```
  4617. */
  4618. var Scale = Control.extend({
  4619. // @section
  4620. // @aka Control.Scale options
  4621. options: {
  4622. position: 'bottomleft',
  4623. // @option maxWidth: Number = 100
  4624. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4625. maxWidth: 100,
  4626. // @option metric: Boolean = True
  4627. // Whether to show the metric scale line (m/km).
  4628. metric: true,
  4629. // @option imperial: Boolean = True
  4630. // Whether to show the imperial scale line (mi/ft).
  4631. imperial: true
  4632. // @option updateWhenIdle: Boolean = false
  4633. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4634. },
  4635. onAdd: function (map) {
  4636. var className = 'leaflet-control-scale',
  4637. container = create$1('div', className),
  4638. options = this.options;
  4639. this._addScales(options, className + '-line', container);
  4640. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4641. map.whenReady(this._update, this);
  4642. return container;
  4643. },
  4644. onRemove: function (map) {
  4645. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4646. },
  4647. _addScales: function (options, className, container) {
  4648. if (options.metric) {
  4649. this._mScale = create$1('div', className, container);
  4650. }
  4651. if (options.imperial) {
  4652. this._iScale = create$1('div', className, container);
  4653. }
  4654. },
  4655. _update: function () {
  4656. var map = this._map,
  4657. y = map.getSize().y / 2;
  4658. var maxMeters = map.distance(
  4659. map.containerPointToLatLng([0, y]),
  4660. map.containerPointToLatLng([this.options.maxWidth, y]));
  4661. this._updateScales(maxMeters);
  4662. },
  4663. _updateScales: function (maxMeters) {
  4664. if (this.options.metric && maxMeters) {
  4665. this._updateMetric(maxMeters);
  4666. }
  4667. if (this.options.imperial && maxMeters) {
  4668. this._updateImperial(maxMeters);
  4669. }
  4670. },
  4671. _updateMetric: function (maxMeters) {
  4672. var meters = this._getRoundNum(maxMeters),
  4673. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4674. this._updateScale(this._mScale, label, meters / maxMeters);
  4675. },
  4676. _updateImperial: function (maxMeters) {
  4677. var maxFeet = maxMeters * 3.2808399,
  4678. maxMiles, miles, feet;
  4679. if (maxFeet > 5280) {
  4680. maxMiles = maxFeet / 5280;
  4681. miles = this._getRoundNum(maxMiles);
  4682. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4683. } else {
  4684. feet = this._getRoundNum(maxFeet);
  4685. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4686. }
  4687. },
  4688. _updateScale: function (scale, text, ratio) {
  4689. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4690. scale.innerHTML = text;
  4691. },
  4692. _getRoundNum: function (num) {
  4693. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4694. d = num / pow10;
  4695. d = d >= 10 ? 10 :
  4696. d >= 5 ? 5 :
  4697. d >= 3 ? 3 :
  4698. d >= 2 ? 2 : 1;
  4699. return pow10 * d;
  4700. }
  4701. });
  4702. // @factory L.control.scale(options?: Control.Scale options)
  4703. // Creates an scale control with the given options.
  4704. var scale = function (options) {
  4705. return new Scale(options);
  4706. };
  4707. 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>';
  4708. /*
  4709. * @class Control.Attribution
  4710. * @aka L.Control.Attribution
  4711. * @inherits Control
  4712. *
  4713. * 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.
  4714. */
  4715. var Attribution = Control.extend({
  4716. // @section
  4717. // @aka Control.Attribution options
  4718. options: {
  4719. position: 'bottomright',
  4720. // @option prefix: String|false = 'Leaflet'
  4721. // The HTML text shown before the attributions. Pass `false` to disable.
  4722. prefix: '<a href="https://leafletjs.com" title="A JavaScript library for interactive maps">' + (Browser.inlineSvg ? ukrainianFlag + ' ' : '') + 'Leaflet</a>'
  4723. },
  4724. initialize: function (options) {
  4725. setOptions(this, options);
  4726. this._attributions = {};
  4727. },
  4728. onAdd: function (map) {
  4729. map.attributionControl = this;
  4730. this._container = create$1('div', 'leaflet-control-attribution');
  4731. disableClickPropagation(this._container);
  4732. // TODO ugly, refactor
  4733. for (var i in map._layers) {
  4734. if (map._layers[i].getAttribution) {
  4735. this.addAttribution(map._layers[i].getAttribution());
  4736. }
  4737. }
  4738. this._update();
  4739. map.on('layeradd', this._addAttribution, this);
  4740. return this._container;
  4741. },
  4742. onRemove: function (map) {
  4743. map.off('layeradd', this._addAttribution, this);
  4744. },
  4745. _addAttribution: function (ev) {
  4746. if (ev.layer.getAttribution) {
  4747. this.addAttribution(ev.layer.getAttribution());
  4748. ev.layer.once('remove', function () {
  4749. this.removeAttribution(ev.layer.getAttribution());
  4750. }, this);
  4751. }
  4752. },
  4753. // @method setPrefix(prefix: String|false): this
  4754. // The HTML text shown before the attributions. Pass `false` to disable.
  4755. setPrefix: function (prefix) {
  4756. this.options.prefix = prefix;
  4757. this._update();
  4758. return this;
  4759. },
  4760. // @method addAttribution(text: String): this
  4761. // Adds an attribution text (e.g. `'&copy; OpenStreetMap contributors'`).
  4762. addAttribution: function (text) {
  4763. if (!text) { return this; }
  4764. if (!this._attributions[text]) {
  4765. this._attributions[text] = 0;
  4766. }
  4767. this._attributions[text]++;
  4768. this._update();
  4769. return this;
  4770. },
  4771. // @method removeAttribution(text: String): this
  4772. // Removes an attribution text.
  4773. removeAttribution: function (text) {
  4774. if (!text) { return this; }
  4775. if (this._attributions[text]) {
  4776. this._attributions[text]--;
  4777. this._update();
  4778. }
  4779. return this;
  4780. },
  4781. _update: function () {
  4782. if (!this._map) { return; }
  4783. var attribs = [];
  4784. for (var i in this._attributions) {
  4785. if (this._attributions[i]) {
  4786. attribs.push(i);
  4787. }
  4788. }
  4789. var prefixAndAttribs = [];
  4790. if (this.options.prefix) {
  4791. prefixAndAttribs.push(this.options.prefix);
  4792. }
  4793. if (attribs.length) {
  4794. prefixAndAttribs.push(attribs.join(', '));
  4795. }
  4796. this._container.innerHTML = prefixAndAttribs.join(' <span aria-hidden="true">|</span> ');
  4797. }
  4798. });
  4799. // @namespace Map
  4800. // @section Control options
  4801. // @option attributionControl: Boolean = true
  4802. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4803. Map.mergeOptions({
  4804. attributionControl: true
  4805. });
  4806. Map.addInitHook(function () {
  4807. if (this.options.attributionControl) {
  4808. new Attribution().addTo(this);
  4809. }
  4810. });
  4811. // @namespace Control.Attribution
  4812. // @factory L.control.attribution(options: Control.Attribution options)
  4813. // Creates an attribution control.
  4814. var attribution = function (options) {
  4815. return new Attribution(options);
  4816. };
  4817. Control.Layers = Layers;
  4818. Control.Zoom = Zoom;
  4819. Control.Scale = Scale;
  4820. Control.Attribution = Attribution;
  4821. control.layers = layers;
  4822. control.zoom = zoom;
  4823. control.scale = scale;
  4824. control.attribution = attribution;
  4825. /*
  4826. L.Handler is a base class for handler classes that are used internally to inject
  4827. interaction features like dragging to classes like Map and Marker.
  4828. */
  4829. // @class Handler
  4830. // @aka L.Handler
  4831. // Abstract class for map interaction handlers
  4832. var Handler = Class.extend({
  4833. initialize: function (map) {
  4834. this._map = map;
  4835. },
  4836. // @method enable(): this
  4837. // Enables the handler
  4838. enable: function () {
  4839. if (this._enabled) { return this; }
  4840. this._enabled = true;
  4841. this.addHooks();
  4842. return this;
  4843. },
  4844. // @method disable(): this
  4845. // Disables the handler
  4846. disable: function () {
  4847. if (!this._enabled) { return this; }
  4848. this._enabled = false;
  4849. this.removeHooks();
  4850. return this;
  4851. },
  4852. // @method enabled(): Boolean
  4853. // Returns `true` if the handler is enabled
  4854. enabled: function () {
  4855. return !!this._enabled;
  4856. }
  4857. // @section Extension methods
  4858. // Classes inheriting from `Handler` must implement the two following methods:
  4859. // @method addHooks()
  4860. // Called when the handler is enabled, should add event hooks.
  4861. // @method removeHooks()
  4862. // Called when the handler is disabled, should remove the event hooks added previously.
  4863. });
  4864. // @section There is static function which can be called without instantiating L.Handler:
  4865. // @function addTo(map: Map, name: String): this
  4866. // Adds a new Handler to the given map with the given name.
  4867. Handler.addTo = function (map, name) {
  4868. map.addHandler(name, this);
  4869. return this;
  4870. };
  4871. var Mixin = {Events: Events};
  4872. /*
  4873. * @class Draggable
  4874. * @aka L.Draggable
  4875. * @inherits Evented
  4876. *
  4877. * A class for making DOM elements draggable (including touch support).
  4878. * Used internally for map and marker dragging. Only works for elements
  4879. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4880. *
  4881. * @example
  4882. * ```js
  4883. * var draggable = new L.Draggable(elementToDrag);
  4884. * draggable.enable();
  4885. * ```
  4886. */
  4887. var START = Browser.touch ? 'touchstart mousedown' : 'mousedown';
  4888. var Draggable = Evented.extend({
  4889. options: {
  4890. // @section
  4891. // @aka Draggable options
  4892. // @option clickTolerance: Number = 3
  4893. // The max number of pixels a user can shift the mouse pointer during a click
  4894. // for it to be considered a valid click (as opposed to a mouse drag).
  4895. clickTolerance: 3
  4896. },
  4897. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4898. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4899. initialize: function (element, dragStartTarget, preventOutline, options) {
  4900. setOptions(this, options);
  4901. this._element = element;
  4902. this._dragStartTarget = dragStartTarget || element;
  4903. this._preventOutline = preventOutline;
  4904. },
  4905. // @method enable()
  4906. // Enables the dragging ability
  4907. enable: function () {
  4908. if (this._enabled) { return; }
  4909. on(this._dragStartTarget, START, this._onDown, this);
  4910. this._enabled = true;
  4911. },
  4912. // @method disable()
  4913. // Disables the dragging ability
  4914. disable: function () {
  4915. if (!this._enabled) { return; }
  4916. // If we're currently dragging this draggable,
  4917. // disabling it counts as first ending the drag.
  4918. if (Draggable._dragging === this) {
  4919. this.finishDrag(true);
  4920. }
  4921. off(this._dragStartTarget, START, this._onDown, this);
  4922. this._enabled = false;
  4923. this._moved = false;
  4924. },
  4925. _onDown: function (e) {
  4926. // Ignore the event if disabled; this happens in IE11
  4927. // under some circumstances, see #3666.
  4928. if (!this._enabled) { return; }
  4929. this._moved = false;
  4930. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4931. if (e.touches && e.touches.length !== 1) {
  4932. // Finish dragging to avoid conflict with touchZoom
  4933. if (Draggable._dragging === this) {
  4934. this.finishDrag();
  4935. }
  4936. return;
  4937. }
  4938. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4939. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4940. if (this._preventOutline) {
  4941. preventOutline(this._element);
  4942. }
  4943. disableImageDrag();
  4944. disableTextSelection();
  4945. if (this._moving) { return; }
  4946. // @event down: Event
  4947. // Fired when a drag is about to start.
  4948. this.fire('down');
  4949. var first = e.touches ? e.touches[0] : e,
  4950. sizedParent = getSizedParentNode(this._element);
  4951. this._startPoint = new Point(first.clientX, first.clientY);
  4952. this._startPos = getPosition(this._element);
  4953. // Cache the scale, so that we can continuously compensate for it during drag (_onMove).
  4954. this._parentScale = getScale(sizedParent);
  4955. var mouseevent = e.type === 'mousedown';
  4956. on(document, mouseevent ? 'mousemove' : 'touchmove', this._onMove, this);
  4957. on(document, mouseevent ? 'mouseup' : 'touchend touchcancel', this._onUp, this);
  4958. },
  4959. _onMove: function (e) {
  4960. // Ignore the event if disabled; this happens in IE11
  4961. // under some circumstances, see #3666.
  4962. if (!this._enabled) { return; }
  4963. if (e.touches && e.touches.length > 1) {
  4964. this._moved = true;
  4965. return;
  4966. }
  4967. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4968. offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);
  4969. if (!offset.x && !offset.y) { return; }
  4970. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4971. // We assume that the parent container's position, border and scale do not change for the duration of the drag.
  4972. // Therefore there is no need to account for the position and border (they are eliminated by the subtraction)
  4973. // and we can use the cached value for the scale.
  4974. offset.x /= this._parentScale.x;
  4975. offset.y /= this._parentScale.y;
  4976. preventDefault(e);
  4977. if (!this._moved) {
  4978. // @event dragstart: Event
  4979. // Fired when a drag starts
  4980. this.fire('dragstart');
  4981. this._moved = true;
  4982. addClass(document.body, 'leaflet-dragging');
  4983. this._lastTarget = e.target || e.srcElement;
  4984. // IE and Edge do not give the <use> element, so fetch it
  4985. // if necessary
  4986. if (window.SVGElementInstance && this._lastTarget instanceof window.SVGElementInstance) {
  4987. this._lastTarget = this._lastTarget.correspondingUseElement;
  4988. }
  4989. addClass(this._lastTarget, 'leaflet-drag-target');
  4990. }
  4991. this._newPos = this._startPos.add(offset);
  4992. this._moving = true;
  4993. this._lastEvent = e;
  4994. this._updatePosition();
  4995. },
  4996. _updatePosition: function () {
  4997. var e = {originalEvent: this._lastEvent};
  4998. // @event predrag: Event
  4999. // Fired continuously during dragging *before* each corresponding
  5000. // update of the element's position.
  5001. this.fire('predrag', e);
  5002. setPosition(this._element, this._newPos);
  5003. // @event drag: Event
  5004. // Fired continuously during dragging.
  5005. this.fire('drag', e);
  5006. },
  5007. _onUp: function () {
  5008. // Ignore the event if disabled; this happens in IE11
  5009. // under some circumstances, see #3666.
  5010. if (!this._enabled) { return; }
  5011. this.finishDrag();
  5012. },
  5013. finishDrag: function (noInertia) {
  5014. removeClass(document.body, 'leaflet-dragging');
  5015. if (this._lastTarget) {
  5016. removeClass(this._lastTarget, 'leaflet-drag-target');
  5017. this._lastTarget = null;
  5018. }
  5019. off(document, 'mousemove touchmove', this._onMove, this);
  5020. off(document, 'mouseup touchend touchcancel', this._onUp, this);
  5021. enableImageDrag();
  5022. enableTextSelection();
  5023. if (this._moved && this._moving) {
  5024. // @event dragend: DragEndEvent
  5025. // Fired when the drag ends.
  5026. this.fire('dragend', {
  5027. noInertia: noInertia,
  5028. distance: this._newPos.distanceTo(this._startPos)
  5029. });
  5030. }
  5031. this._moving = false;
  5032. Draggable._dragging = false;
  5033. }
  5034. });
  5035. /*
  5036. * @namespace LineUtil
  5037. *
  5038. * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
  5039. */
  5040. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  5041. // Improves rendering performance dramatically by lessening the number of points to draw.
  5042. // @function simplify(points: Point[], tolerance: Number): Point[]
  5043. // Dramatically reduces the number of points in a polyline while retaining
  5044. // its shape and returns a new array of simplified points, using the
  5045. // [Ramer-Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm).
  5046. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  5047. // each zoom level and also reducing visual noise. tolerance affects the amount of
  5048. // simplification (lesser value means higher quality but slower and with more points).
  5049. // Also released as a separated micro-library [Simplify.js](https://mourner.github.io/simplify-js/).
  5050. function simplify(points, tolerance) {
  5051. if (!tolerance || !points.length) {
  5052. return points.slice();
  5053. }
  5054. var sqTolerance = tolerance * tolerance;
  5055. // stage 1: vertex reduction
  5056. points = _reducePoints(points, sqTolerance);
  5057. // stage 2: Douglas-Peucker simplification
  5058. points = _simplifyDP(points, sqTolerance);
  5059. return points;
  5060. }
  5061. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  5062. // Returns the distance between point `p` and segment `p1` to `p2`.
  5063. function pointToSegmentDistance(p, p1, p2) {
  5064. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  5065. }
  5066. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  5067. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  5068. function closestPointOnSegment(p, p1, p2) {
  5069. return _sqClosestPointOnSegment(p, p1, p2);
  5070. }
  5071. // Ramer-Douglas-Peucker simplification, see https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
  5072. function _simplifyDP(points, sqTolerance) {
  5073. var len = points.length,
  5074. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  5075. markers = new ArrayConstructor(len);
  5076. markers[0] = markers[len - 1] = 1;
  5077. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  5078. var i,
  5079. newPoints = [];
  5080. for (i = 0; i < len; i++) {
  5081. if (markers[i]) {
  5082. newPoints.push(points[i]);
  5083. }
  5084. }
  5085. return newPoints;
  5086. }
  5087. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  5088. var maxSqDist = 0,
  5089. index, i, sqDist;
  5090. for (i = first + 1; i <= last - 1; i++) {
  5091. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  5092. if (sqDist > maxSqDist) {
  5093. index = i;
  5094. maxSqDist = sqDist;
  5095. }
  5096. }
  5097. if (maxSqDist > sqTolerance) {
  5098. markers[index] = 1;
  5099. _simplifyDPStep(points, markers, sqTolerance, first, index);
  5100. _simplifyDPStep(points, markers, sqTolerance, index, last);
  5101. }
  5102. }
  5103. // reduce points that are too close to each other to a single point
  5104. function _reducePoints(points, sqTolerance) {
  5105. var reducedPoints = [points[0]];
  5106. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  5107. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  5108. reducedPoints.push(points[i]);
  5109. prev = i;
  5110. }
  5111. }
  5112. if (prev < len - 1) {
  5113. reducedPoints.push(points[len - 1]);
  5114. }
  5115. return reducedPoints;
  5116. }
  5117. var _lastCode;
  5118. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  5119. // Clips the segment a to b by rectangular bounds with the
  5120. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  5121. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  5122. // points that are on the screen or near, increasing performance.
  5123. function clipSegment(a, b, bounds, useLastCode, round) {
  5124. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  5125. codeB = _getBitCode(b, bounds),
  5126. codeOut, p, newCode;
  5127. // save 2nd code to avoid calculating it on the next segment
  5128. _lastCode = codeB;
  5129. while (true) {
  5130. // if a,b is inside the clip window (trivial accept)
  5131. if (!(codeA | codeB)) {
  5132. return [a, b];
  5133. }
  5134. // if a,b is outside the clip window (trivial reject)
  5135. if (codeA & codeB) {
  5136. return false;
  5137. }
  5138. // other cases
  5139. codeOut = codeA || codeB;
  5140. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  5141. newCode = _getBitCode(p, bounds);
  5142. if (codeOut === codeA) {
  5143. a = p;
  5144. codeA = newCode;
  5145. } else {
  5146. b = p;
  5147. codeB = newCode;
  5148. }
  5149. }
  5150. }
  5151. function _getEdgeIntersection(a, b, code, bounds, round) {
  5152. var dx = b.x - a.x,
  5153. dy = b.y - a.y,
  5154. min = bounds.min,
  5155. max = bounds.max,
  5156. x, y;
  5157. if (code & 8) { // top
  5158. x = a.x + dx * (max.y - a.y) / dy;
  5159. y = max.y;
  5160. } else if (code & 4) { // bottom
  5161. x = a.x + dx * (min.y - a.y) / dy;
  5162. y = min.y;
  5163. } else if (code & 2) { // right
  5164. x = max.x;
  5165. y = a.y + dy * (max.x - a.x) / dx;
  5166. } else if (code & 1) { // left
  5167. x = min.x;
  5168. y = a.y + dy * (min.x - a.x) / dx;
  5169. }
  5170. return new Point(x, y, round);
  5171. }
  5172. function _getBitCode(p, bounds) {
  5173. var code = 0;
  5174. if (p.x < bounds.min.x) { // left
  5175. code |= 1;
  5176. } else if (p.x > bounds.max.x) { // right
  5177. code |= 2;
  5178. }
  5179. if (p.y < bounds.min.y) { // bottom
  5180. code |= 4;
  5181. } else if (p.y > bounds.max.y) { // top
  5182. code |= 8;
  5183. }
  5184. return code;
  5185. }
  5186. // square distance (to avoid unnecessary Math.sqrt calls)
  5187. function _sqDist(p1, p2) {
  5188. var dx = p2.x - p1.x,
  5189. dy = p2.y - p1.y;
  5190. return dx * dx + dy * dy;
  5191. }
  5192. // return closest point on segment or distance to that point
  5193. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  5194. var x = p1.x,
  5195. y = p1.y,
  5196. dx = p2.x - x,
  5197. dy = p2.y - y,
  5198. dot = dx * dx + dy * dy,
  5199. t;
  5200. if (dot > 0) {
  5201. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  5202. if (t > 1) {
  5203. x = p2.x;
  5204. y = p2.y;
  5205. } else if (t > 0) {
  5206. x += dx * t;
  5207. y += dy * t;
  5208. }
  5209. }
  5210. dx = p.x - x;
  5211. dy = p.y - y;
  5212. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  5213. }
  5214. // @function isFlat(latlngs: LatLng[]): Boolean
  5215. // Returns true if `latlngs` is a flat array, false is nested.
  5216. function isFlat(latlngs) {
  5217. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  5218. }
  5219. function _flat(latlngs) {
  5220. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  5221. return isFlat(latlngs);
  5222. }
  5223. /* @function polylineCenter(latlngs: LatLng[], crs: CRS): LatLng
  5224. * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polyline.
  5225. */
  5226. function polylineCenter(latlngs, crs) {
  5227. var i, halfDist, segDist, dist, p1, p2, ratio, center;
  5228. if (!latlngs || latlngs.length === 0) {
  5229. throw new Error('latlngs not passed');
  5230. }
  5231. if (!isFlat(latlngs)) {
  5232. console.warn('latlngs are not flat! Only the first ring will be used');
  5233. latlngs = latlngs[0];
  5234. }
  5235. var points = [];
  5236. for (var j in latlngs) {
  5237. points.push(crs.project(toLatLng(latlngs[j])));
  5238. }
  5239. var len = points.length;
  5240. for (i = 0, halfDist = 0; i < len - 1; i++) {
  5241. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  5242. }
  5243. // The line is so small in the current view that all points are on the same pixel.
  5244. if (halfDist === 0) {
  5245. center = points[0];
  5246. } else {
  5247. for (i = 0, dist = 0; i < len - 1; i++) {
  5248. p1 = points[i];
  5249. p2 = points[i + 1];
  5250. segDist = p1.distanceTo(p2);
  5251. dist += segDist;
  5252. if (dist > halfDist) {
  5253. ratio = (dist - halfDist) / segDist;
  5254. center = [
  5255. p2.x - ratio * (p2.x - p1.x),
  5256. p2.y - ratio * (p2.y - p1.y)
  5257. ];
  5258. break;
  5259. }
  5260. }
  5261. }
  5262. return crs.unproject(toPoint(center));
  5263. }
  5264. var LineUtil = {
  5265. __proto__: null,
  5266. simplify: simplify,
  5267. pointToSegmentDistance: pointToSegmentDistance,
  5268. closestPointOnSegment: closestPointOnSegment,
  5269. clipSegment: clipSegment,
  5270. _getEdgeIntersection: _getEdgeIntersection,
  5271. _getBitCode: _getBitCode,
  5272. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5273. isFlat: isFlat,
  5274. _flat: _flat,
  5275. polylineCenter: polylineCenter
  5276. };
  5277. /*
  5278. * @namespace PolyUtil
  5279. * Various utility functions for polygon geometries.
  5280. */
  5281. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5282. * 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)).
  5283. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5284. * performance. Note that polygon points needs different algorithm for clipping
  5285. * than polyline, so there's a separate method for it.
  5286. */
  5287. function clipPolygon(points, bounds, round) {
  5288. var clippedPoints,
  5289. edges = [1, 4, 2, 8],
  5290. i, j, k,
  5291. a, b,
  5292. len, edge, p;
  5293. for (i = 0, len = points.length; i < len; i++) {
  5294. points[i]._code = _getBitCode(points[i], bounds);
  5295. }
  5296. // for each edge (left, bottom, right, top)
  5297. for (k = 0; k < 4; k++) {
  5298. edge = edges[k];
  5299. clippedPoints = [];
  5300. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5301. a = points[i];
  5302. b = points[j];
  5303. // if a is inside the clip window
  5304. if (!(a._code & edge)) {
  5305. // if b is outside the clip window (a->b goes out of screen)
  5306. if (b._code & edge) {
  5307. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5308. p._code = _getBitCode(p, bounds);
  5309. clippedPoints.push(p);
  5310. }
  5311. clippedPoints.push(a);
  5312. // else if b is inside the clip window (a->b enters the screen)
  5313. } else if (!(b._code & edge)) {
  5314. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5315. p._code = _getBitCode(p, bounds);
  5316. clippedPoints.push(p);
  5317. }
  5318. }
  5319. points = clippedPoints;
  5320. }
  5321. return points;
  5322. }
  5323. /* @function polygonCenter(latlngs: LatLng[] crs: CRS): LatLng
  5324. * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polygon.
  5325. */
  5326. function polygonCenter(latlngs, crs) {
  5327. var i, j, p1, p2, f, area, x, y, center;
  5328. if (!latlngs || latlngs.length === 0) {
  5329. throw new Error('latlngs not passed');
  5330. }
  5331. if (!isFlat(latlngs)) {
  5332. console.warn('latlngs are not flat! Only the first ring will be used');
  5333. latlngs = latlngs[0];
  5334. }
  5335. var points = [];
  5336. for (var k in latlngs) {
  5337. points.push(crs.project(toLatLng(latlngs[k])));
  5338. }
  5339. var len = points.length;
  5340. area = x = y = 0;
  5341. // polygon centroid algorithm;
  5342. for (i = 0, j = len - 1; i < len; j = i++) {
  5343. p1 = points[i];
  5344. p2 = points[j];
  5345. f = p1.y * p2.x - p2.y * p1.x;
  5346. x += (p1.x + p2.x) * f;
  5347. y += (p1.y + p2.y) * f;
  5348. area += f * 3;
  5349. }
  5350. if (area === 0) {
  5351. // Polygon is so small that all points are on same pixel.
  5352. center = points[0];
  5353. } else {
  5354. center = [x / area, y / area];
  5355. }
  5356. return crs.unproject(toPoint(center));
  5357. }
  5358. var PolyUtil = {
  5359. __proto__: null,
  5360. clipPolygon: clipPolygon,
  5361. polygonCenter: polygonCenter
  5362. };
  5363. /*
  5364. * @namespace Projection
  5365. * @section
  5366. * Leaflet comes with a set of already defined Projections out of the box:
  5367. *
  5368. * @projection L.Projection.LonLat
  5369. *
  5370. * Equirectangular, or Plate Carree projection — the most simple projection,
  5371. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5372. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5373. * `EPSG:4326` and `Simple` CRS.
  5374. */
  5375. var LonLat = {
  5376. project: function (latlng) {
  5377. return new Point(latlng.lng, latlng.lat);
  5378. },
  5379. unproject: function (point) {
  5380. return new LatLng(point.y, point.x);
  5381. },
  5382. bounds: new Bounds([-180, -90], [180, 90])
  5383. };
  5384. /*
  5385. * @namespace Projection
  5386. * @projection L.Projection.Mercator
  5387. *
  5388. * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.
  5389. */
  5390. var Mercator = {
  5391. R: 6378137,
  5392. R_MINOR: 6356752.314245179,
  5393. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5394. project: function (latlng) {
  5395. var d = Math.PI / 180,
  5396. r = this.R,
  5397. y = latlng.lat * d,
  5398. tmp = this.R_MINOR / r,
  5399. e = Math.sqrt(1 - tmp * tmp),
  5400. con = e * Math.sin(y);
  5401. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5402. y = -r * Math.log(Math.max(ts, 1E-10));
  5403. return new Point(latlng.lng * d * r, y);
  5404. },
  5405. unproject: function (point) {
  5406. var d = 180 / Math.PI,
  5407. r = this.R,
  5408. tmp = this.R_MINOR / r,
  5409. e = Math.sqrt(1 - tmp * tmp),
  5410. ts = Math.exp(-point.y / r),
  5411. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5412. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5413. con = e * Math.sin(phi);
  5414. con = Math.pow((1 - con) / (1 + con), e / 2);
  5415. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5416. phi += dphi;
  5417. }
  5418. return new LatLng(phi * d, point.x * d / r);
  5419. }
  5420. };
  5421. /*
  5422. * @class Projection
  5423. * An object with methods for projecting geographical coordinates of the world onto
  5424. * a flat surface (and back). See [Map projection](https://en.wikipedia.org/wiki/Map_projection).
  5425. * @property bounds: Bounds
  5426. * The bounds (specified in CRS units) where the projection is valid
  5427. * @method project(latlng: LatLng): Point
  5428. * Projects geographical coordinates into a 2D point.
  5429. * Only accepts actual `L.LatLng` instances, not arrays.
  5430. * @method unproject(point: Point): LatLng
  5431. * The inverse of `project`. Projects a 2D point into a geographical location.
  5432. * Only accepts actual `L.Point` instances, not arrays.
  5433. * Note that the projection instances do not inherit from Leaflet's `Class` object,
  5434. * and can't be instantiated. Also, new classes can't inherit from them,
  5435. * and methods can't be added to them with the `include` function.
  5436. */
  5437. var index = {
  5438. __proto__: null,
  5439. LonLat: LonLat,
  5440. Mercator: Mercator,
  5441. SphericalMercator: SphericalMercator
  5442. };
  5443. /*
  5444. * @namespace CRS
  5445. * @crs L.CRS.EPSG3395
  5446. *
  5447. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5448. */
  5449. var EPSG3395 = extend({}, Earth, {
  5450. code: 'EPSG:3395',
  5451. projection: Mercator,
  5452. transformation: (function () {
  5453. var scale = 0.5 / (Math.PI * Mercator.R);
  5454. return toTransformation(scale, 0.5, -scale, 0.5);
  5455. }())
  5456. });
  5457. /*
  5458. * @namespace CRS
  5459. * @crs L.CRS.EPSG4326
  5460. *
  5461. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5462. *
  5463. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5464. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5465. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5466. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5467. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5468. */
  5469. var EPSG4326 = extend({}, Earth, {
  5470. code: 'EPSG:4326',
  5471. projection: LonLat,
  5472. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5473. });
  5474. /*
  5475. * @namespace CRS
  5476. * @crs L.CRS.Simple
  5477. *
  5478. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5479. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5480. * axis should still be inverted (going from bottom to top). `distance()` returns
  5481. * simple euclidean distance.
  5482. */
  5483. var Simple = extend({}, CRS, {
  5484. projection: LonLat,
  5485. transformation: toTransformation(1, 0, -1, 0),
  5486. scale: function (zoom) {
  5487. return Math.pow(2, zoom);
  5488. },
  5489. zoom: function (scale) {
  5490. return Math.log(scale) / Math.LN2;
  5491. },
  5492. distance: function (latlng1, latlng2) {
  5493. var dx = latlng2.lng - latlng1.lng,
  5494. dy = latlng2.lat - latlng1.lat;
  5495. return Math.sqrt(dx * dx + dy * dy);
  5496. },
  5497. infinite: true
  5498. });
  5499. CRS.Earth = Earth;
  5500. CRS.EPSG3395 = EPSG3395;
  5501. CRS.EPSG3857 = EPSG3857;
  5502. CRS.EPSG900913 = EPSG900913;
  5503. CRS.EPSG4326 = EPSG4326;
  5504. CRS.Simple = Simple;
  5505. /*
  5506. * @class Layer
  5507. * @inherits Evented
  5508. * @aka L.Layer
  5509. * @aka ILayer
  5510. *
  5511. * A set of methods from the Layer base class that all Leaflet layers use.
  5512. * Inherits all methods, options and events from `L.Evented`.
  5513. *
  5514. * @example
  5515. *
  5516. * ```js
  5517. * var layer = L.marker(latlng).addTo(map);
  5518. * layer.addTo(map);
  5519. * layer.remove();
  5520. * ```
  5521. *
  5522. * @event add: Event
  5523. * Fired after the layer is added to a map
  5524. *
  5525. * @event remove: Event
  5526. * Fired after the layer is removed from a map
  5527. */
  5528. var Layer = Evented.extend({
  5529. // Classes extending `L.Layer` will inherit the following options:
  5530. options: {
  5531. // @option pane: String = 'overlayPane'
  5532. // 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.
  5533. pane: 'overlayPane',
  5534. // @option attribution: String = null
  5535. // 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.
  5536. attribution: null,
  5537. bubblingMouseEvents: true
  5538. },
  5539. /* @section
  5540. * Classes extending `L.Layer` will inherit the following methods:
  5541. *
  5542. * @method addTo(map: Map|LayerGroup): this
  5543. * Adds the layer to the given map or layer group.
  5544. */
  5545. addTo: function (map) {
  5546. map.addLayer(this);
  5547. return this;
  5548. },
  5549. // @method remove: this
  5550. // Removes the layer from the map it is currently active on.
  5551. remove: function () {
  5552. return this.removeFrom(this._map || this._mapToAdd);
  5553. },
  5554. // @method removeFrom(map: Map): this
  5555. // Removes the layer from the given map
  5556. //
  5557. // @alternative
  5558. // @method removeFrom(group: LayerGroup): this
  5559. // Removes the layer from the given `LayerGroup`
  5560. removeFrom: function (obj) {
  5561. if (obj) {
  5562. obj.removeLayer(this);
  5563. }
  5564. return this;
  5565. },
  5566. // @method getPane(name? : String): HTMLElement
  5567. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5568. getPane: function (name) {
  5569. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5570. },
  5571. addInteractiveTarget: function (targetEl) {
  5572. this._map._targets[stamp(targetEl)] = this;
  5573. return this;
  5574. },
  5575. removeInteractiveTarget: function (targetEl) {
  5576. delete this._map._targets[stamp(targetEl)];
  5577. return this;
  5578. },
  5579. // @method getAttribution: String
  5580. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5581. getAttribution: function () {
  5582. return this.options.attribution;
  5583. },
  5584. _layerAdd: function (e) {
  5585. var map = e.target;
  5586. // check in case layer gets added and then removed before the map is ready
  5587. if (!map.hasLayer(this)) { return; }
  5588. this._map = map;
  5589. this._zoomAnimated = map._zoomAnimated;
  5590. if (this.getEvents) {
  5591. var events = this.getEvents();
  5592. map.on(events, this);
  5593. this.once('remove', function () {
  5594. map.off(events, this);
  5595. }, this);
  5596. }
  5597. this.onAdd(map);
  5598. this.fire('add');
  5599. map.fire('layeradd', {layer: this});
  5600. }
  5601. });
  5602. /* @section Extension methods
  5603. * @uninheritable
  5604. *
  5605. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5606. *
  5607. * @method onAdd(map: Map): this
  5608. * 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).
  5609. *
  5610. * @method onRemove(map: Map): this
  5611. * 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).
  5612. *
  5613. * @method getEvents(): Object
  5614. * 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.
  5615. *
  5616. * @method getAttribution(): String
  5617. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5618. *
  5619. * @method beforeAdd(map: Map): this
  5620. * 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.
  5621. */
  5622. /* @namespace Map
  5623. * @section Layer events
  5624. *
  5625. * @event layeradd: LayerEvent
  5626. * Fired when a new layer is added to the map.
  5627. *
  5628. * @event layerremove: LayerEvent
  5629. * Fired when some layer is removed from the map
  5630. *
  5631. * @section Methods for Layers and Controls
  5632. */
  5633. Map.include({
  5634. // @method addLayer(layer: Layer): this
  5635. // Adds the given layer to the map
  5636. addLayer: function (layer) {
  5637. if (!layer._layerAdd) {
  5638. throw new Error('The provided object is not a Layer.');
  5639. }
  5640. var id = stamp(layer);
  5641. if (this._layers[id]) { return this; }
  5642. this._layers[id] = layer;
  5643. layer._mapToAdd = this;
  5644. if (layer.beforeAdd) {
  5645. layer.beforeAdd(this);
  5646. }
  5647. this.whenReady(layer._layerAdd, layer);
  5648. return this;
  5649. },
  5650. // @method removeLayer(layer: Layer): this
  5651. // Removes the given layer from the map.
  5652. removeLayer: function (layer) {
  5653. var id = stamp(layer);
  5654. if (!this._layers[id]) { return this; }
  5655. if (this._loaded) {
  5656. layer.onRemove(this);
  5657. }
  5658. delete this._layers[id];
  5659. if (this._loaded) {
  5660. this.fire('layerremove', {layer: layer});
  5661. layer.fire('remove');
  5662. }
  5663. layer._map = layer._mapToAdd = null;
  5664. return this;
  5665. },
  5666. // @method hasLayer(layer: Layer): Boolean
  5667. // Returns `true` if the given layer is currently added to the map
  5668. hasLayer: function (layer) {
  5669. return stamp(layer) in this._layers;
  5670. },
  5671. /* @method eachLayer(fn: Function, context?: Object): this
  5672. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5673. * ```
  5674. * map.eachLayer(function(layer){
  5675. * layer.bindPopup('Hello');
  5676. * });
  5677. * ```
  5678. */
  5679. eachLayer: function (method, context) {
  5680. for (var i in this._layers) {
  5681. method.call(context, this._layers[i]);
  5682. }
  5683. return this;
  5684. },
  5685. _addLayers: function (layers) {
  5686. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5687. for (var i = 0, len = layers.length; i < len; i++) {
  5688. this.addLayer(layers[i]);
  5689. }
  5690. },
  5691. _addZoomLimit: function (layer) {
  5692. if (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5693. this._zoomBoundLayers[stamp(layer)] = layer;
  5694. this._updateZoomLevels();
  5695. }
  5696. },
  5697. _removeZoomLimit: function (layer) {
  5698. var id = stamp(layer);
  5699. if (this._zoomBoundLayers[id]) {
  5700. delete this._zoomBoundLayers[id];
  5701. this._updateZoomLevels();
  5702. }
  5703. },
  5704. _updateZoomLevels: function () {
  5705. var minZoom = Infinity,
  5706. maxZoom = -Infinity,
  5707. oldZoomSpan = this._getZoomSpan();
  5708. for (var i in this._zoomBoundLayers) {
  5709. var options = this._zoomBoundLayers[i].options;
  5710. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5711. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5712. }
  5713. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5714. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5715. // @section Map state change events
  5716. // @event zoomlevelschange: Event
  5717. // Fired when the number of zoomlevels on the map is changed due
  5718. // to adding or removing a layer.
  5719. if (oldZoomSpan !== this._getZoomSpan()) {
  5720. this.fire('zoomlevelschange');
  5721. }
  5722. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5723. this.setZoom(this._layersMaxZoom);
  5724. }
  5725. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5726. this.setZoom(this._layersMinZoom);
  5727. }
  5728. }
  5729. });
  5730. /*
  5731. * @class LayerGroup
  5732. * @aka L.LayerGroup
  5733. * @inherits Interactive layer
  5734. *
  5735. * Used to group several layers and handle them as one. If you add it to the map,
  5736. * any layers added or removed from the group will be added/removed on the map as
  5737. * well. Extends `Layer`.
  5738. *
  5739. * @example
  5740. *
  5741. * ```js
  5742. * L.layerGroup([marker1, marker2])
  5743. * .addLayer(polyline)
  5744. * .addTo(map);
  5745. * ```
  5746. */
  5747. var LayerGroup = Layer.extend({
  5748. initialize: function (layers, options) {
  5749. setOptions(this, options);
  5750. this._layers = {};
  5751. var i, len;
  5752. if (layers) {
  5753. for (i = 0, len = layers.length; i < len; i++) {
  5754. this.addLayer(layers[i]);
  5755. }
  5756. }
  5757. },
  5758. // @method addLayer(layer: Layer): this
  5759. // Adds the given layer to the group.
  5760. addLayer: function (layer) {
  5761. var id = this.getLayerId(layer);
  5762. this._layers[id] = layer;
  5763. if (this._map) {
  5764. this._map.addLayer(layer);
  5765. }
  5766. return this;
  5767. },
  5768. // @method removeLayer(layer: Layer): this
  5769. // Removes the given layer from the group.
  5770. // @alternative
  5771. // @method removeLayer(id: Number): this
  5772. // Removes the layer with the given internal ID from the group.
  5773. removeLayer: function (layer) {
  5774. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5775. if (this._map && this._layers[id]) {
  5776. this._map.removeLayer(this._layers[id]);
  5777. }
  5778. delete this._layers[id];
  5779. return this;
  5780. },
  5781. // @method hasLayer(layer: Layer): Boolean
  5782. // Returns `true` if the given layer is currently added to the group.
  5783. // @alternative
  5784. // @method hasLayer(id: Number): Boolean
  5785. // Returns `true` if the given internal ID is currently added to the group.
  5786. hasLayer: function (layer) {
  5787. var layerId = typeof layer === 'number' ? layer : this.getLayerId(layer);
  5788. return layerId in this._layers;
  5789. },
  5790. // @method clearLayers(): this
  5791. // Removes all the layers from the group.
  5792. clearLayers: function () {
  5793. return this.eachLayer(this.removeLayer, this);
  5794. },
  5795. // @method invoke(methodName: String, …): this
  5796. // Calls `methodName` on every layer contained in this group, passing any
  5797. // additional parameters. Has no effect if the layers contained do not
  5798. // implement `methodName`.
  5799. invoke: function (methodName) {
  5800. var args = Array.prototype.slice.call(arguments, 1),
  5801. i, layer;
  5802. for (i in this._layers) {
  5803. layer = this._layers[i];
  5804. if (layer[methodName]) {
  5805. layer[methodName].apply(layer, args);
  5806. }
  5807. }
  5808. return this;
  5809. },
  5810. onAdd: function (map) {
  5811. this.eachLayer(map.addLayer, map);
  5812. },
  5813. onRemove: function (map) {
  5814. this.eachLayer(map.removeLayer, map);
  5815. },
  5816. // @method eachLayer(fn: Function, context?: Object): this
  5817. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5818. // ```js
  5819. // group.eachLayer(function (layer) {
  5820. // layer.bindPopup('Hello');
  5821. // });
  5822. // ```
  5823. eachLayer: function (method, context) {
  5824. for (var i in this._layers) {
  5825. method.call(context, this._layers[i]);
  5826. }
  5827. return this;
  5828. },
  5829. // @method getLayer(id: Number): Layer
  5830. // Returns the layer with the given internal ID.
  5831. getLayer: function (id) {
  5832. return this._layers[id];
  5833. },
  5834. // @method getLayers(): Layer[]
  5835. // Returns an array of all the layers added to the group.
  5836. getLayers: function () {
  5837. var layers = [];
  5838. this.eachLayer(layers.push, layers);
  5839. return layers;
  5840. },
  5841. // @method setZIndex(zIndex: Number): this
  5842. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5843. setZIndex: function (zIndex) {
  5844. return this.invoke('setZIndex', zIndex);
  5845. },
  5846. // @method getLayerId(layer: Layer): Number
  5847. // Returns the internal ID for a layer
  5848. getLayerId: function (layer) {
  5849. return stamp(layer);
  5850. }
  5851. });
  5852. // @factory L.layerGroup(layers?: Layer[], options?: Object)
  5853. // Create a layer group, optionally given an initial set of layers and an `options` object.
  5854. var layerGroup = function (layers, options) {
  5855. return new LayerGroup(layers, options);
  5856. };
  5857. /*
  5858. * @class FeatureGroup
  5859. * @aka L.FeatureGroup
  5860. * @inherits LayerGroup
  5861. *
  5862. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5863. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5864. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5865. * handler, it will handle events from any of the layers. This includes mouse events
  5866. * and custom events.
  5867. * * Has `layeradd` and `layerremove` events
  5868. *
  5869. * @example
  5870. *
  5871. * ```js
  5872. * L.featureGroup([marker1, marker2, polyline])
  5873. * .bindPopup('Hello world!')
  5874. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5875. * .addTo(map);
  5876. * ```
  5877. */
  5878. var FeatureGroup = LayerGroup.extend({
  5879. addLayer: function (layer) {
  5880. if (this.hasLayer(layer)) {
  5881. return this;
  5882. }
  5883. layer.addEventParent(this);
  5884. LayerGroup.prototype.addLayer.call(this, layer);
  5885. // @event layeradd: LayerEvent
  5886. // Fired when a layer is added to this `FeatureGroup`
  5887. return this.fire('layeradd', {layer: layer});
  5888. },
  5889. removeLayer: function (layer) {
  5890. if (!this.hasLayer(layer)) {
  5891. return this;
  5892. }
  5893. if (layer in this._layers) {
  5894. layer = this._layers[layer];
  5895. }
  5896. layer.removeEventParent(this);
  5897. LayerGroup.prototype.removeLayer.call(this, layer);
  5898. // @event layerremove: LayerEvent
  5899. // Fired when a layer is removed from this `FeatureGroup`
  5900. return this.fire('layerremove', {layer: layer});
  5901. },
  5902. // @method setStyle(style: Path options): this
  5903. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5904. setStyle: function (style) {
  5905. return this.invoke('setStyle', style);
  5906. },
  5907. // @method bringToFront(): this
  5908. // Brings the layer group to the top of all other layers
  5909. bringToFront: function () {
  5910. return this.invoke('bringToFront');
  5911. },
  5912. // @method bringToBack(): this
  5913. // Brings the layer group to the back of all other layers
  5914. bringToBack: function () {
  5915. return this.invoke('bringToBack');
  5916. },
  5917. // @method getBounds(): LatLngBounds
  5918. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5919. getBounds: function () {
  5920. var bounds = new LatLngBounds();
  5921. for (var id in this._layers) {
  5922. var layer = this._layers[id];
  5923. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5924. }
  5925. return bounds;
  5926. }
  5927. });
  5928. // @factory L.featureGroup(layers?: Layer[], options?: Object)
  5929. // Create a feature group, optionally given an initial set of layers and an `options` object.
  5930. var featureGroup = function (layers, options) {
  5931. return new FeatureGroup(layers, options);
  5932. };
  5933. /*
  5934. * @class Icon
  5935. * @aka L.Icon
  5936. *
  5937. * Represents an icon to provide when creating a marker.
  5938. *
  5939. * @example
  5940. *
  5941. * ```js
  5942. * var myIcon = L.icon({
  5943. * iconUrl: 'my-icon.png',
  5944. * iconRetinaUrl: 'my-icon@2x.png',
  5945. * iconSize: [38, 95],
  5946. * iconAnchor: [22, 94],
  5947. * popupAnchor: [-3, -76],
  5948. * shadowUrl: 'my-icon-shadow.png',
  5949. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5950. * shadowSize: [68, 95],
  5951. * shadowAnchor: [22, 94]
  5952. * });
  5953. *
  5954. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5955. * ```
  5956. *
  5957. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5958. *
  5959. */
  5960. var Icon = Class.extend({
  5961. /* @section
  5962. * @aka Icon options
  5963. *
  5964. * @option iconUrl: String = null
  5965. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5966. *
  5967. * @option iconRetinaUrl: String = null
  5968. * The URL to a retina sized version of the icon image (absolute or relative to your
  5969. * script path). Used for Retina screen devices.
  5970. *
  5971. * @option iconSize: Point = null
  5972. * Size of the icon image in pixels.
  5973. *
  5974. * @option iconAnchor: Point = null
  5975. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5976. * will be aligned so that this point is at the marker's geographical location. Centered
  5977. * by default if size is specified, also can be set in CSS with negative margins.
  5978. *
  5979. * @option popupAnchor: Point = [0, 0]
  5980. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5981. *
  5982. * @option tooltipAnchor: Point = [0, 0]
  5983. * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
  5984. *
  5985. * @option shadowUrl: String = null
  5986. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  5987. *
  5988. * @option shadowRetinaUrl: String = null
  5989. *
  5990. * @option shadowSize: Point = null
  5991. * Size of the shadow image in pixels.
  5992. *
  5993. * @option shadowAnchor: Point = null
  5994. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  5995. * as iconAnchor if not specified).
  5996. *
  5997. * @option className: String = ''
  5998. * A custom class name to assign to both icon and shadow images. Empty by default.
  5999. */
  6000. options: {
  6001. popupAnchor: [0, 0],
  6002. tooltipAnchor: [0, 0],
  6003. // @option crossOrigin: Boolean|String = false
  6004. // Whether the crossOrigin attribute will be added to the tiles.
  6005. // 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.
  6006. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  6007. crossOrigin: false
  6008. },
  6009. initialize: function (options) {
  6010. setOptions(this, options);
  6011. },
  6012. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  6013. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  6014. // styled according to the options.
  6015. createIcon: function (oldIcon) {
  6016. return this._createIcon('icon', oldIcon);
  6017. },
  6018. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  6019. // As `createIcon`, but for the shadow beneath it.
  6020. createShadow: function (oldIcon) {
  6021. return this._createIcon('shadow', oldIcon);
  6022. },
  6023. _createIcon: function (name, oldIcon) {
  6024. var src = this._getIconUrl(name);
  6025. if (!src) {
  6026. if (name === 'icon') {
  6027. throw new Error('iconUrl not set in Icon options (see the docs).');
  6028. }
  6029. return null;
  6030. }
  6031. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  6032. this._setIconStyles(img, name);
  6033. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  6034. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  6035. }
  6036. return img;
  6037. },
  6038. _setIconStyles: function (img, name) {
  6039. var options = this.options;
  6040. var sizeOption = options[name + 'Size'];
  6041. if (typeof sizeOption === 'number') {
  6042. sizeOption = [sizeOption, sizeOption];
  6043. }
  6044. var size = toPoint(sizeOption),
  6045. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  6046. size && size.divideBy(2, true));
  6047. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  6048. if (anchor) {
  6049. img.style.marginLeft = (-anchor.x) + 'px';
  6050. img.style.marginTop = (-anchor.y) + 'px';
  6051. }
  6052. if (size) {
  6053. img.style.width = size.x + 'px';
  6054. img.style.height = size.y + 'px';
  6055. }
  6056. },
  6057. _createImg: function (src, el) {
  6058. el = el || document.createElement('img');
  6059. el.src = src;
  6060. return el;
  6061. },
  6062. _getIconUrl: function (name) {
  6063. return Browser.retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  6064. }
  6065. });
  6066. // @factory L.icon(options: Icon options)
  6067. // Creates an icon instance with the given options.
  6068. function icon(options) {
  6069. return new Icon(options);
  6070. }
  6071. /*
  6072. * @miniclass Icon.Default (Icon)
  6073. * @aka L.Icon.Default
  6074. * @section
  6075. *
  6076. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  6077. * no icon is specified. Points to the blue marker image distributed with Leaflet
  6078. * releases.
  6079. *
  6080. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  6081. * (which is a set of `Icon options`).
  6082. *
  6083. * If you want to _completely_ replace the default icon, override the
  6084. * `L.Marker.prototype.options.icon` with your own icon instead.
  6085. */
  6086. var IconDefault = Icon.extend({
  6087. options: {
  6088. iconUrl: 'marker-icon.png',
  6089. iconRetinaUrl: 'marker-icon-2x.png',
  6090. shadowUrl: 'marker-shadow.png',
  6091. iconSize: [25, 41],
  6092. iconAnchor: [12, 41],
  6093. popupAnchor: [1, -34],
  6094. tooltipAnchor: [16, -28],
  6095. shadowSize: [41, 41]
  6096. },
  6097. _getIconUrl: function (name) {
  6098. if (typeof IconDefault.imagePath !== 'string') { // Deprecated, backwards-compatibility only
  6099. IconDefault.imagePath = this._detectIconPath();
  6100. }
  6101. // @option imagePath: String
  6102. // `Icon.Default` will try to auto-detect the location of the
  6103. // blue icon images. If you are placing these images in a non-standard
  6104. // way, set this option to point to the right path.
  6105. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  6106. },
  6107. _stripUrl: function (path) { // separate function to use in tests
  6108. var strip = function (str, re, idx) {
  6109. var match = re.exec(str);
  6110. return match && match[idx];
  6111. };
  6112. path = strip(path, /^url\((['"])?(.+)\1\)$/, 2);
  6113. return path && strip(path, /^(.*)marker-icon\.png$/, 1);
  6114. },
  6115. _detectIconPath: function () {
  6116. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  6117. var path = getStyle(el, 'background-image') ||
  6118. getStyle(el, 'backgroundImage'); // IE8
  6119. document.body.removeChild(el);
  6120. path = this._stripUrl(path);
  6121. if (path) { return path; }
  6122. var link = document.querySelector('link[href$="leaflet.css"]');
  6123. if (!link) { return ''; }
  6124. return link.href.substring(0, link.href.length - 'leaflet.css'.length - 1);
  6125. }
  6126. });
  6127. /*
  6128. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  6129. */
  6130. /* @namespace Marker
  6131. * @section Interaction handlers
  6132. *
  6133. * 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:
  6134. *
  6135. * ```js
  6136. * marker.dragging.disable();
  6137. * ```
  6138. *
  6139. * @property dragging: Handler
  6140. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  6141. */
  6142. var MarkerDrag = Handler.extend({
  6143. initialize: function (marker) {
  6144. this._marker = marker;
  6145. },
  6146. addHooks: function () {
  6147. var icon = this._marker._icon;
  6148. if (!this._draggable) {
  6149. this._draggable = new Draggable(icon, icon, true);
  6150. }
  6151. this._draggable.on({
  6152. dragstart: this._onDragStart,
  6153. predrag: this._onPreDrag,
  6154. drag: this._onDrag,
  6155. dragend: this._onDragEnd
  6156. }, this).enable();
  6157. addClass(icon, 'leaflet-marker-draggable');
  6158. },
  6159. removeHooks: function () {
  6160. this._draggable.off({
  6161. dragstart: this._onDragStart,
  6162. predrag: this._onPreDrag,
  6163. drag: this._onDrag,
  6164. dragend: this._onDragEnd
  6165. }, this).disable();
  6166. if (this._marker._icon) {
  6167. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  6168. }
  6169. },
  6170. moved: function () {
  6171. return this._draggable && this._draggable._moved;
  6172. },
  6173. _adjustPan: function (e) {
  6174. var marker = this._marker,
  6175. map = marker._map,
  6176. speed = this._marker.options.autoPanSpeed,
  6177. padding = this._marker.options.autoPanPadding,
  6178. iconPos = getPosition(marker._icon),
  6179. bounds = map.getPixelBounds(),
  6180. origin = map.getPixelOrigin();
  6181. var panBounds = toBounds(
  6182. bounds.min._subtract(origin).add(padding),
  6183. bounds.max._subtract(origin).subtract(padding)
  6184. );
  6185. if (!panBounds.contains(iconPos)) {
  6186. // Compute incremental movement
  6187. var movement = toPoint(
  6188. (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
  6189. (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
  6190. (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
  6191. (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
  6192. ).multiplyBy(speed);
  6193. map.panBy(movement, {animate: false});
  6194. this._draggable._newPos._add(movement);
  6195. this._draggable._startPos._add(movement);
  6196. setPosition(marker._icon, this._draggable._newPos);
  6197. this._onDrag(e);
  6198. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  6199. }
  6200. },
  6201. _onDragStart: function () {
  6202. // @section Dragging events
  6203. // @event dragstart: Event
  6204. // Fired when the user starts dragging the marker.
  6205. // @event movestart: Event
  6206. // Fired when the marker starts moving (because of dragging).
  6207. this._oldLatLng = this._marker.getLatLng();
  6208. // When using ES6 imports it could not be set when `Popup` was not imported as well
  6209. this._marker.closePopup && this._marker.closePopup();
  6210. this._marker
  6211. .fire('movestart')
  6212. .fire('dragstart');
  6213. },
  6214. _onPreDrag: function (e) {
  6215. if (this._marker.options.autoPan) {
  6216. cancelAnimFrame(this._panRequest);
  6217. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  6218. }
  6219. },
  6220. _onDrag: function (e) {
  6221. var marker = this._marker,
  6222. shadow = marker._shadow,
  6223. iconPos = getPosition(marker._icon),
  6224. latlng = marker._map.layerPointToLatLng(iconPos);
  6225. // update shadow position
  6226. if (shadow) {
  6227. setPosition(shadow, iconPos);
  6228. }
  6229. marker._latlng = latlng;
  6230. e.latlng = latlng;
  6231. e.oldLatLng = this._oldLatLng;
  6232. // @event drag: Event
  6233. // Fired repeatedly while the user drags the marker.
  6234. marker
  6235. .fire('move', e)
  6236. .fire('drag', e);
  6237. },
  6238. _onDragEnd: function (e) {
  6239. // @event dragend: DragEndEvent
  6240. // Fired when the user stops dragging the marker.
  6241. cancelAnimFrame(this._panRequest);
  6242. // @event moveend: Event
  6243. // Fired when the marker stops moving (because of dragging).
  6244. delete this._oldLatLng;
  6245. this._marker
  6246. .fire('moveend')
  6247. .fire('dragend', e);
  6248. }
  6249. });
  6250. /*
  6251. * @class Marker
  6252. * @inherits Interactive layer
  6253. * @aka L.Marker
  6254. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  6255. *
  6256. * @example
  6257. *
  6258. * ```js
  6259. * L.marker([50.5, 30.5]).addTo(map);
  6260. * ```
  6261. */
  6262. var Marker = Layer.extend({
  6263. // @section
  6264. // @aka Marker options
  6265. options: {
  6266. // @option icon: Icon = *
  6267. // Icon instance to use for rendering the marker.
  6268. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  6269. // If not specified, a common instance of `L.Icon.Default` is used.
  6270. icon: new IconDefault(),
  6271. // Option inherited from "Interactive layer" abstract class
  6272. interactive: true,
  6273. // @option keyboard: Boolean = true
  6274. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  6275. keyboard: true,
  6276. // @option title: String = ''
  6277. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  6278. // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
  6279. title: '',
  6280. // @option alt: String = 'Marker'
  6281. // Text for the `alt` attribute of the icon image.
  6282. // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
  6283. alt: 'Marker',
  6284. // @option zIndexOffset: Number = 0
  6285. // 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).
  6286. zIndexOffset: 0,
  6287. // @option opacity: Number = 1.0
  6288. // The opacity of the marker.
  6289. opacity: 1,
  6290. // @option riseOnHover: Boolean = false
  6291. // If `true`, the marker will get on top of others when you hover the mouse over it.
  6292. riseOnHover: false,
  6293. // @option riseOffset: Number = 250
  6294. // The z-index offset used for the `riseOnHover` feature.
  6295. riseOffset: 250,
  6296. // @option pane: String = 'markerPane'
  6297. // `Map pane` where the markers icon will be added.
  6298. pane: 'markerPane',
  6299. // @option shadowPane: String = 'shadowPane'
  6300. // `Map pane` where the markers shadow will be added.
  6301. shadowPane: 'shadowPane',
  6302. // @option bubblingMouseEvents: Boolean = false
  6303. // When `true`, a mouse event on this marker will trigger the same event on the map
  6304. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6305. bubblingMouseEvents: false,
  6306. // @option autoPanOnFocus: Boolean = true
  6307. // When `true`, the map will pan whenever the marker is focused (via
  6308. // e.g. pressing `tab` on the keyboard) to ensure the marker is
  6309. // visible within the map's bounds
  6310. autoPanOnFocus: true,
  6311. // @section Draggable marker options
  6312. // @option draggable: Boolean = false
  6313. // Whether the marker is draggable with mouse/touch or not.
  6314. draggable: false,
  6315. // @option autoPan: Boolean = false
  6316. // Whether to pan the map when dragging this marker near its edge or not.
  6317. autoPan: false,
  6318. // @option autoPanPadding: Point = Point(50, 50)
  6319. // Distance (in pixels to the left/right and to the top/bottom) of the
  6320. // map edge to start panning the map.
  6321. autoPanPadding: [50, 50],
  6322. // @option autoPanSpeed: Number = 10
  6323. // Number of pixels the map should pan by.
  6324. autoPanSpeed: 10
  6325. },
  6326. /* @section
  6327. *
  6328. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  6329. */
  6330. initialize: function (latlng, options) {
  6331. setOptions(this, options);
  6332. this._latlng = toLatLng(latlng);
  6333. },
  6334. onAdd: function (map) {
  6335. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  6336. if (this._zoomAnimated) {
  6337. map.on('zoomanim', this._animateZoom, this);
  6338. }
  6339. this._initIcon();
  6340. this.update();
  6341. },
  6342. onRemove: function (map) {
  6343. if (this.dragging && this.dragging.enabled()) {
  6344. this.options.draggable = true;
  6345. this.dragging.removeHooks();
  6346. }
  6347. delete this.dragging;
  6348. if (this._zoomAnimated) {
  6349. map.off('zoomanim', this._animateZoom, this);
  6350. }
  6351. this._removeIcon();
  6352. this._removeShadow();
  6353. },
  6354. getEvents: function () {
  6355. return {
  6356. zoom: this.update,
  6357. viewreset: this.update
  6358. };
  6359. },
  6360. // @method getLatLng: LatLng
  6361. // Returns the current geographical position of the marker.
  6362. getLatLng: function () {
  6363. return this._latlng;
  6364. },
  6365. // @method setLatLng(latlng: LatLng): this
  6366. // Changes the marker position to the given point.
  6367. setLatLng: function (latlng) {
  6368. var oldLatLng = this._latlng;
  6369. this._latlng = toLatLng(latlng);
  6370. this.update();
  6371. // @event move: Event
  6372. // 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`.
  6373. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6374. },
  6375. // @method setZIndexOffset(offset: Number): this
  6376. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6377. setZIndexOffset: function (offset) {
  6378. this.options.zIndexOffset = offset;
  6379. return this.update();
  6380. },
  6381. // @method getIcon: Icon
  6382. // Returns the current icon used by the marker
  6383. getIcon: function () {
  6384. return this.options.icon;
  6385. },
  6386. // @method setIcon(icon: Icon): this
  6387. // Changes the marker icon.
  6388. setIcon: function (icon) {
  6389. this.options.icon = icon;
  6390. if (this._map) {
  6391. this._initIcon();
  6392. this.update();
  6393. }
  6394. if (this._popup) {
  6395. this.bindPopup(this._popup, this._popup.options);
  6396. }
  6397. return this;
  6398. },
  6399. getElement: function () {
  6400. return this._icon;
  6401. },
  6402. update: function () {
  6403. if (this._icon && this._map) {
  6404. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6405. this._setPos(pos);
  6406. }
  6407. return this;
  6408. },
  6409. _initIcon: function () {
  6410. var options = this.options,
  6411. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6412. var icon = options.icon.createIcon(this._icon),
  6413. addIcon = false;
  6414. // if we're not reusing the icon, remove the old one and init new one
  6415. if (icon !== this._icon) {
  6416. if (this._icon) {
  6417. this._removeIcon();
  6418. }
  6419. addIcon = true;
  6420. if (options.title) {
  6421. icon.title = options.title;
  6422. }
  6423. if (icon.tagName === 'IMG') {
  6424. icon.alt = options.alt || '';
  6425. }
  6426. }
  6427. addClass(icon, classToAdd);
  6428. if (options.keyboard) {
  6429. icon.tabIndex = '0';
  6430. icon.setAttribute('role', 'button');
  6431. }
  6432. this._icon = icon;
  6433. if (options.riseOnHover) {
  6434. this.on({
  6435. mouseover: this._bringToFront,
  6436. mouseout: this._resetZIndex
  6437. });
  6438. }
  6439. if (this.options.autoPanOnFocus) {
  6440. on(icon, 'focus', this._panOnFocus, this);
  6441. }
  6442. var newShadow = options.icon.createShadow(this._shadow),
  6443. addShadow = false;
  6444. if (newShadow !== this._shadow) {
  6445. this._removeShadow();
  6446. addShadow = true;
  6447. }
  6448. if (newShadow) {
  6449. addClass(newShadow, classToAdd);
  6450. newShadow.alt = '';
  6451. }
  6452. this._shadow = newShadow;
  6453. if (options.opacity < 1) {
  6454. this._updateOpacity();
  6455. }
  6456. if (addIcon) {
  6457. this.getPane().appendChild(this._icon);
  6458. }
  6459. this._initInteraction();
  6460. if (newShadow && addShadow) {
  6461. this.getPane(options.shadowPane).appendChild(this._shadow);
  6462. }
  6463. },
  6464. _removeIcon: function () {
  6465. if (this.options.riseOnHover) {
  6466. this.off({
  6467. mouseover: this._bringToFront,
  6468. mouseout: this._resetZIndex
  6469. });
  6470. }
  6471. if (this.options.autoPanOnFocus) {
  6472. off(this._icon, 'focus', this._panOnFocus, this);
  6473. }
  6474. remove(this._icon);
  6475. this.removeInteractiveTarget(this._icon);
  6476. this._icon = null;
  6477. },
  6478. _removeShadow: function () {
  6479. if (this._shadow) {
  6480. remove(this._shadow);
  6481. }
  6482. this._shadow = null;
  6483. },
  6484. _setPos: function (pos) {
  6485. if (this._icon) {
  6486. setPosition(this._icon, pos);
  6487. }
  6488. if (this._shadow) {
  6489. setPosition(this._shadow, pos);
  6490. }
  6491. this._zIndex = pos.y + this.options.zIndexOffset;
  6492. this._resetZIndex();
  6493. },
  6494. _updateZIndex: function (offset) {
  6495. if (this._icon) {
  6496. this._icon.style.zIndex = this._zIndex + offset;
  6497. }
  6498. },
  6499. _animateZoom: function (opt) {
  6500. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6501. this._setPos(pos);
  6502. },
  6503. _initInteraction: function () {
  6504. if (!this.options.interactive) { return; }
  6505. addClass(this._icon, 'leaflet-interactive');
  6506. this.addInteractiveTarget(this._icon);
  6507. if (MarkerDrag) {
  6508. var draggable = this.options.draggable;
  6509. if (this.dragging) {
  6510. draggable = this.dragging.enabled();
  6511. this.dragging.disable();
  6512. }
  6513. this.dragging = new MarkerDrag(this);
  6514. if (draggable) {
  6515. this.dragging.enable();
  6516. }
  6517. }
  6518. },
  6519. // @method setOpacity(opacity: Number): this
  6520. // Changes the opacity of the marker.
  6521. setOpacity: function (opacity) {
  6522. this.options.opacity = opacity;
  6523. if (this._map) {
  6524. this._updateOpacity();
  6525. }
  6526. return this;
  6527. },
  6528. _updateOpacity: function () {
  6529. var opacity = this.options.opacity;
  6530. if (this._icon) {
  6531. setOpacity(this._icon, opacity);
  6532. }
  6533. if (this._shadow) {
  6534. setOpacity(this._shadow, opacity);
  6535. }
  6536. },
  6537. _bringToFront: function () {
  6538. this._updateZIndex(this.options.riseOffset);
  6539. },
  6540. _resetZIndex: function () {
  6541. this._updateZIndex(0);
  6542. },
  6543. _panOnFocus: function () {
  6544. var map = this._map;
  6545. if (!map) { return; }
  6546. var iconOpts = this.options.icon.options;
  6547. var size = iconOpts.iconSize ? toPoint(iconOpts.iconSize) : toPoint(0, 0);
  6548. var anchor = iconOpts.iconAnchor ? toPoint(iconOpts.iconAnchor) : toPoint(0, 0);
  6549. map.panInside(this._latlng, {
  6550. paddingTopLeft: anchor,
  6551. paddingBottomRight: size.subtract(anchor)
  6552. });
  6553. },
  6554. _getPopupAnchor: function () {
  6555. return this.options.icon.options.popupAnchor;
  6556. },
  6557. _getTooltipAnchor: function () {
  6558. return this.options.icon.options.tooltipAnchor;
  6559. }
  6560. });
  6561. // factory L.marker(latlng: LatLng, options? : Marker options)
  6562. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6563. // Instantiates a Marker object given a geographical point and optionally an options object.
  6564. function marker(latlng, options) {
  6565. return new Marker(latlng, options);
  6566. }
  6567. /*
  6568. * @class Path
  6569. * @aka L.Path
  6570. * @inherits Interactive layer
  6571. *
  6572. * An abstract class that contains options and constants shared between vector
  6573. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6574. */
  6575. var Path = Layer.extend({
  6576. // @section
  6577. // @aka Path options
  6578. options: {
  6579. // @option stroke: Boolean = true
  6580. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6581. stroke: true,
  6582. // @option color: String = '#3388ff'
  6583. // Stroke color
  6584. color: '#3388ff',
  6585. // @option weight: Number = 3
  6586. // Stroke width in pixels
  6587. weight: 3,
  6588. // @option opacity: Number = 1.0
  6589. // Stroke opacity
  6590. opacity: 1,
  6591. // @option lineCap: String= 'round'
  6592. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6593. lineCap: 'round',
  6594. // @option lineJoin: String = 'round'
  6595. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6596. lineJoin: 'round',
  6597. // @option dashArray: String = null
  6598. // 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).
  6599. dashArray: null,
  6600. // @option dashOffset: String = null
  6601. // 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).
  6602. dashOffset: null,
  6603. // @option fill: Boolean = depends
  6604. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6605. fill: false,
  6606. // @option fillColor: String = *
  6607. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6608. fillColor: null,
  6609. // @option fillOpacity: Number = 0.2
  6610. // Fill opacity.
  6611. fillOpacity: 0.2,
  6612. // @option fillRule: String = 'evenodd'
  6613. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6614. fillRule: 'evenodd',
  6615. // className: '',
  6616. // Option inherited from "Interactive layer" abstract class
  6617. interactive: true,
  6618. // @option bubblingMouseEvents: Boolean = true
  6619. // When `true`, a mouse event on this path will trigger the same event on the map
  6620. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6621. bubblingMouseEvents: true
  6622. },
  6623. beforeAdd: function (map) {
  6624. // Renderer is set here because we need to call renderer.getEvents
  6625. // before this.getEvents.
  6626. this._renderer = map.getRenderer(this);
  6627. },
  6628. onAdd: function () {
  6629. this._renderer._initPath(this);
  6630. this._reset();
  6631. this._renderer._addPath(this);
  6632. },
  6633. onRemove: function () {
  6634. this._renderer._removePath(this);
  6635. },
  6636. // @method redraw(): this
  6637. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6638. redraw: function () {
  6639. if (this._map) {
  6640. this._renderer._updatePath(this);
  6641. }
  6642. return this;
  6643. },
  6644. // @method setStyle(style: Path options): this
  6645. // Changes the appearance of a Path based on the options in the `Path options` object.
  6646. setStyle: function (style) {
  6647. setOptions(this, style);
  6648. if (this._renderer) {
  6649. this._renderer._updateStyle(this);
  6650. if (this.options.stroke && style && Object.prototype.hasOwnProperty.call(style, 'weight')) {
  6651. this._updateBounds();
  6652. }
  6653. }
  6654. return this;
  6655. },
  6656. // @method bringToFront(): this
  6657. // Brings the layer to the top of all path layers.
  6658. bringToFront: function () {
  6659. if (this._renderer) {
  6660. this._renderer._bringToFront(this);
  6661. }
  6662. return this;
  6663. },
  6664. // @method bringToBack(): this
  6665. // Brings the layer to the bottom of all path layers.
  6666. bringToBack: function () {
  6667. if (this._renderer) {
  6668. this._renderer._bringToBack(this);
  6669. }
  6670. return this;
  6671. },
  6672. getElement: function () {
  6673. return this._path;
  6674. },
  6675. _reset: function () {
  6676. // defined in child classes
  6677. this._project();
  6678. this._update();
  6679. },
  6680. _clickTolerance: function () {
  6681. // used when doing hit detection for Canvas layers
  6682. return (this.options.stroke ? this.options.weight / 2 : 0) +
  6683. (this._renderer.options.tolerance || 0);
  6684. }
  6685. });
  6686. /*
  6687. * @class CircleMarker
  6688. * @aka L.CircleMarker
  6689. * @inherits Path
  6690. *
  6691. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6692. */
  6693. var CircleMarker = Path.extend({
  6694. // @section
  6695. // @aka CircleMarker options
  6696. options: {
  6697. fill: true,
  6698. // @option radius: Number = 10
  6699. // Radius of the circle marker, in pixels
  6700. radius: 10
  6701. },
  6702. initialize: function (latlng, options) {
  6703. setOptions(this, options);
  6704. this._latlng = toLatLng(latlng);
  6705. this._radius = this.options.radius;
  6706. },
  6707. // @method setLatLng(latLng: LatLng): this
  6708. // Sets the position of a circle marker to a new location.
  6709. setLatLng: function (latlng) {
  6710. var oldLatLng = this._latlng;
  6711. this._latlng = toLatLng(latlng);
  6712. this.redraw();
  6713. // @event move: Event
  6714. // Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
  6715. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6716. },
  6717. // @method getLatLng(): LatLng
  6718. // Returns the current geographical position of the circle marker
  6719. getLatLng: function () {
  6720. return this._latlng;
  6721. },
  6722. // @method setRadius(radius: Number): this
  6723. // Sets the radius of a circle marker. Units are in pixels.
  6724. setRadius: function (radius) {
  6725. this.options.radius = this._radius = radius;
  6726. return this.redraw();
  6727. },
  6728. // @method getRadius(): Number
  6729. // Returns the current radius of the circle
  6730. getRadius: function () {
  6731. return this._radius;
  6732. },
  6733. setStyle : function (options) {
  6734. var radius = options && options.radius || this._radius;
  6735. Path.prototype.setStyle.call(this, options);
  6736. this.setRadius(radius);
  6737. return this;
  6738. },
  6739. _project: function () {
  6740. this._point = this._map.latLngToLayerPoint(this._latlng);
  6741. this._updateBounds();
  6742. },
  6743. _updateBounds: function () {
  6744. var r = this._radius,
  6745. r2 = this._radiusY || r,
  6746. w = this._clickTolerance(),
  6747. p = [r + w, r2 + w];
  6748. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6749. },
  6750. _update: function () {
  6751. if (this._map) {
  6752. this._updatePath();
  6753. }
  6754. },
  6755. _updatePath: function () {
  6756. this._renderer._updateCircle(this);
  6757. },
  6758. _empty: function () {
  6759. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6760. },
  6761. // Needed by the `Canvas` renderer for interactivity
  6762. _containsPoint: function (p) {
  6763. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6764. }
  6765. });
  6766. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6767. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6768. function circleMarker(latlng, options) {
  6769. return new CircleMarker(latlng, options);
  6770. }
  6771. /*
  6772. * @class Circle
  6773. * @aka L.Circle
  6774. * @inherits CircleMarker
  6775. *
  6776. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6777. *
  6778. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6779. *
  6780. * @example
  6781. *
  6782. * ```js
  6783. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6784. * ```
  6785. */
  6786. var Circle = CircleMarker.extend({
  6787. initialize: function (latlng, options, legacyOptions) {
  6788. if (typeof options === 'number') {
  6789. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6790. options = extend({}, legacyOptions, {radius: options});
  6791. }
  6792. setOptions(this, options);
  6793. this._latlng = toLatLng(latlng);
  6794. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6795. // @section
  6796. // @aka Circle options
  6797. // @option radius: Number; Radius of the circle, in meters.
  6798. this._mRadius = this.options.radius;
  6799. },
  6800. // @method setRadius(radius: Number): this
  6801. // Sets the radius of a circle. Units are in meters.
  6802. setRadius: function (radius) {
  6803. this._mRadius = radius;
  6804. return this.redraw();
  6805. },
  6806. // @method getRadius(): Number
  6807. // Returns the current radius of a circle. Units are in meters.
  6808. getRadius: function () {
  6809. return this._mRadius;
  6810. },
  6811. // @method getBounds(): LatLngBounds
  6812. // Returns the `LatLngBounds` of the path.
  6813. getBounds: function () {
  6814. var half = [this._radius, this._radiusY || this._radius];
  6815. return new LatLngBounds(
  6816. this._map.layerPointToLatLng(this._point.subtract(half)),
  6817. this._map.layerPointToLatLng(this._point.add(half)));
  6818. },
  6819. setStyle: Path.prototype.setStyle,
  6820. _project: function () {
  6821. var lng = this._latlng.lng,
  6822. lat = this._latlng.lat,
  6823. map = this._map,
  6824. crs = map.options.crs;
  6825. if (crs.distance === Earth.distance) {
  6826. var d = Math.PI / 180,
  6827. latR = (this._mRadius / Earth.R) / d,
  6828. top = map.project([lat + latR, lng]),
  6829. bottom = map.project([lat - latR, lng]),
  6830. p = top.add(bottom).divideBy(2),
  6831. lat2 = map.unproject(p).lat,
  6832. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6833. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6834. if (isNaN(lngR) || lngR === 0) {
  6835. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6836. }
  6837. this._point = p.subtract(map.getPixelOrigin());
  6838. this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
  6839. this._radiusY = p.y - top.y;
  6840. } else {
  6841. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6842. this._point = map.latLngToLayerPoint(this._latlng);
  6843. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6844. }
  6845. this._updateBounds();
  6846. }
  6847. });
  6848. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6849. // Instantiates a circle object given a geographical point, and an options object
  6850. // which contains the circle radius.
  6851. // @alternative
  6852. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6853. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6854. // Do not use in new applications or plugins.
  6855. function circle(latlng, options, legacyOptions) {
  6856. return new Circle(latlng, options, legacyOptions);
  6857. }
  6858. /*
  6859. * @class Polyline
  6860. * @aka L.Polyline
  6861. * @inherits Path
  6862. *
  6863. * A class for drawing polyline overlays on a map. Extends `Path`.
  6864. *
  6865. * @example
  6866. *
  6867. * ```js
  6868. * // create a red polyline from an array of LatLng points
  6869. * var latlngs = [
  6870. * [45.51, -122.68],
  6871. * [37.77, -122.43],
  6872. * [34.04, -118.2]
  6873. * ];
  6874. *
  6875. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6876. *
  6877. * // zoom the map to the polyline
  6878. * map.fitBounds(polyline.getBounds());
  6879. * ```
  6880. *
  6881. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6882. *
  6883. * ```js
  6884. * // create a red polyline from an array of arrays of LatLng points
  6885. * var latlngs = [
  6886. * [[45.51, -122.68],
  6887. * [37.77, -122.43],
  6888. * [34.04, -118.2]],
  6889. * [[40.78, -73.91],
  6890. * [41.83, -87.62],
  6891. * [32.76, -96.72]]
  6892. * ];
  6893. * ```
  6894. */
  6895. var Polyline = Path.extend({
  6896. // @section
  6897. // @aka Polyline options
  6898. options: {
  6899. // @option smoothFactor: Number = 1.0
  6900. // How much to simplify the polyline on each zoom level. More means
  6901. // better performance and smoother look, and less means more accurate representation.
  6902. smoothFactor: 1.0,
  6903. // @option noClip: Boolean = false
  6904. // Disable polyline clipping.
  6905. noClip: false
  6906. },
  6907. initialize: function (latlngs, options) {
  6908. setOptions(this, options);
  6909. this._setLatLngs(latlngs);
  6910. },
  6911. // @method getLatLngs(): LatLng[]
  6912. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6913. getLatLngs: function () {
  6914. return this._latlngs;
  6915. },
  6916. // @method setLatLngs(latlngs: LatLng[]): this
  6917. // Replaces all the points in the polyline with the given array of geographical points.
  6918. setLatLngs: function (latlngs) {
  6919. this._setLatLngs(latlngs);
  6920. return this.redraw();
  6921. },
  6922. // @method isEmpty(): Boolean
  6923. // Returns `true` if the Polyline has no LatLngs.
  6924. isEmpty: function () {
  6925. return !this._latlngs.length;
  6926. },
  6927. // @method closestLayerPoint(p: Point): Point
  6928. // Returns the point closest to `p` on the Polyline.
  6929. closestLayerPoint: function (p) {
  6930. var minDistance = Infinity,
  6931. minPoint = null,
  6932. closest = _sqClosestPointOnSegment,
  6933. p1, p2;
  6934. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6935. var points = this._parts[j];
  6936. for (var i = 1, len = points.length; i < len; i++) {
  6937. p1 = points[i - 1];
  6938. p2 = points[i];
  6939. var sqDist = closest(p, p1, p2, true);
  6940. if (sqDist < minDistance) {
  6941. minDistance = sqDist;
  6942. minPoint = closest(p, p1, p2);
  6943. }
  6944. }
  6945. }
  6946. if (minPoint) {
  6947. minPoint.distance = Math.sqrt(minDistance);
  6948. }
  6949. return minPoint;
  6950. },
  6951. // @method getCenter(): LatLng
  6952. // Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6953. getCenter: function () {
  6954. // throws error when not yet added to map as this center calculation requires projected coordinates
  6955. if (!this._map) {
  6956. throw new Error('Must add layer to map before using getCenter()');
  6957. }
  6958. return polylineCenter(this._defaultShape(), this._map.options.crs);
  6959. },
  6960. // @method getBounds(): LatLngBounds
  6961. // Returns the `LatLngBounds` of the path.
  6962. getBounds: function () {
  6963. return this._bounds;
  6964. },
  6965. // @method addLatLng(latlng: LatLng, latlngs?: LatLng[]): this
  6966. // Adds a given point to the polyline. By default, adds to the first ring of
  6967. // the polyline in case of a multi-polyline, but can be overridden by passing
  6968. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6969. addLatLng: function (latlng, latlngs) {
  6970. latlngs = latlngs || this._defaultShape();
  6971. latlng = toLatLng(latlng);
  6972. latlngs.push(latlng);
  6973. this._bounds.extend(latlng);
  6974. return this.redraw();
  6975. },
  6976. _setLatLngs: function (latlngs) {
  6977. this._bounds = new LatLngBounds();
  6978. this._latlngs = this._convertLatLngs(latlngs);
  6979. },
  6980. _defaultShape: function () {
  6981. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6982. },
  6983. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6984. _convertLatLngs: function (latlngs) {
  6985. var result = [],
  6986. flat = isFlat(latlngs);
  6987. for (var i = 0, len = latlngs.length; i < len; i++) {
  6988. if (flat) {
  6989. result[i] = toLatLng(latlngs[i]);
  6990. this._bounds.extend(result[i]);
  6991. } else {
  6992. result[i] = this._convertLatLngs(latlngs[i]);
  6993. }
  6994. }
  6995. return result;
  6996. },
  6997. _project: function () {
  6998. var pxBounds = new Bounds();
  6999. this._rings = [];
  7000. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  7001. if (this._bounds.isValid() && pxBounds.isValid()) {
  7002. this._rawPxBounds = pxBounds;
  7003. this._updateBounds();
  7004. }
  7005. },
  7006. _updateBounds: function () {
  7007. var w = this._clickTolerance(),
  7008. p = new Point(w, w);
  7009. if (!this._rawPxBounds) {
  7010. return;
  7011. }
  7012. this._pxBounds = new Bounds([
  7013. this._rawPxBounds.min.subtract(p),
  7014. this._rawPxBounds.max.add(p)
  7015. ]);
  7016. },
  7017. // recursively turns latlngs into a set of rings with projected coordinates
  7018. _projectLatlngs: function (latlngs, result, projectedBounds) {
  7019. var flat = latlngs[0] instanceof LatLng,
  7020. len = latlngs.length,
  7021. i, ring;
  7022. if (flat) {
  7023. ring = [];
  7024. for (i = 0; i < len; i++) {
  7025. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  7026. projectedBounds.extend(ring[i]);
  7027. }
  7028. result.push(ring);
  7029. } else {
  7030. for (i = 0; i < len; i++) {
  7031. this._projectLatlngs(latlngs[i], result, projectedBounds);
  7032. }
  7033. }
  7034. },
  7035. // clip polyline by renderer bounds so that we have less to render for performance
  7036. _clipPoints: function () {
  7037. var bounds = this._renderer._bounds;
  7038. this._parts = [];
  7039. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7040. return;
  7041. }
  7042. if (this.options.noClip) {
  7043. this._parts = this._rings;
  7044. return;
  7045. }
  7046. var parts = this._parts,
  7047. i, j, k, len, len2, segment, points;
  7048. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  7049. points = this._rings[i];
  7050. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  7051. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  7052. if (!segment) { continue; }
  7053. parts[k] = parts[k] || [];
  7054. parts[k].push(segment[0]);
  7055. // if segment goes out of screen, or it's the last one, it's the end of the line part
  7056. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  7057. parts[k].push(segment[1]);
  7058. k++;
  7059. }
  7060. }
  7061. }
  7062. },
  7063. // simplify each clipped part of the polyline for performance
  7064. _simplifyPoints: function () {
  7065. var parts = this._parts,
  7066. tolerance = this.options.smoothFactor;
  7067. for (var i = 0, len = parts.length; i < len; i++) {
  7068. parts[i] = simplify(parts[i], tolerance);
  7069. }
  7070. },
  7071. _update: function () {
  7072. if (!this._map) { return; }
  7073. this._clipPoints();
  7074. this._simplifyPoints();
  7075. this._updatePath();
  7076. },
  7077. _updatePath: function () {
  7078. this._renderer._updatePoly(this);
  7079. },
  7080. // Needed by the `Canvas` renderer for interactivity
  7081. _containsPoint: function (p, closed) {
  7082. var i, j, k, len, len2, part,
  7083. w = this._clickTolerance();
  7084. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  7085. // hit detection for polylines
  7086. for (i = 0, len = this._parts.length; i < len; i++) {
  7087. part = this._parts[i];
  7088. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7089. if (!closed && (j === 0)) { continue; }
  7090. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  7091. return true;
  7092. }
  7093. }
  7094. }
  7095. return false;
  7096. }
  7097. });
  7098. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  7099. // Instantiates a polyline object given an array of geographical points and
  7100. // optionally an options object. You can create a `Polyline` object with
  7101. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  7102. // of geographic points.
  7103. function polyline(latlngs, options) {
  7104. return new Polyline(latlngs, options);
  7105. }
  7106. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  7107. Polyline._flat = _flat;
  7108. /*
  7109. * @class Polygon
  7110. * @aka L.Polygon
  7111. * @inherits Polyline
  7112. *
  7113. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  7114. *
  7115. * 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.
  7116. *
  7117. *
  7118. * @example
  7119. *
  7120. * ```js
  7121. * // create a red polygon from an array of LatLng points
  7122. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  7123. *
  7124. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  7125. *
  7126. * // zoom the map to the polygon
  7127. * map.fitBounds(polygon.getBounds());
  7128. * ```
  7129. *
  7130. * 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:
  7131. *
  7132. * ```js
  7133. * var latlngs = [
  7134. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7135. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7136. * ];
  7137. * ```
  7138. *
  7139. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  7140. *
  7141. * ```js
  7142. * var latlngs = [
  7143. * [ // first polygon
  7144. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7145. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7146. * ],
  7147. * [ // second polygon
  7148. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  7149. * ]
  7150. * ];
  7151. * ```
  7152. */
  7153. var Polygon = Polyline.extend({
  7154. options: {
  7155. fill: true
  7156. },
  7157. isEmpty: function () {
  7158. return !this._latlngs.length || !this._latlngs[0].length;
  7159. },
  7160. // @method getCenter(): LatLng
  7161. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the Polygon.
  7162. getCenter: function () {
  7163. // throws error when not yet added to map as this center calculation requires projected coordinates
  7164. if (!this._map) {
  7165. throw new Error('Must add layer to map before using getCenter()');
  7166. }
  7167. return polygonCenter(this._defaultShape(), this._map.options.crs);
  7168. },
  7169. _convertLatLngs: function (latlngs) {
  7170. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  7171. len = result.length;
  7172. // remove last point if it equals first one
  7173. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  7174. result.pop();
  7175. }
  7176. return result;
  7177. },
  7178. _setLatLngs: function (latlngs) {
  7179. Polyline.prototype._setLatLngs.call(this, latlngs);
  7180. if (isFlat(this._latlngs)) {
  7181. this._latlngs = [this._latlngs];
  7182. }
  7183. },
  7184. _defaultShape: function () {
  7185. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  7186. },
  7187. _clipPoints: function () {
  7188. // polygons need a different clipping algorithm so we redefine that
  7189. var bounds = this._renderer._bounds,
  7190. w = this.options.weight,
  7191. p = new Point(w, w);
  7192. // increase clip padding by stroke width to avoid stroke on clip edges
  7193. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  7194. this._parts = [];
  7195. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7196. return;
  7197. }
  7198. if (this.options.noClip) {
  7199. this._parts = this._rings;
  7200. return;
  7201. }
  7202. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  7203. clipped = clipPolygon(this._rings[i], bounds, true);
  7204. if (clipped.length) {
  7205. this._parts.push(clipped);
  7206. }
  7207. }
  7208. },
  7209. _updatePath: function () {
  7210. this._renderer._updatePoly(this, true);
  7211. },
  7212. // Needed by the `Canvas` renderer for interactivity
  7213. _containsPoint: function (p) {
  7214. var inside = false,
  7215. part, p1, p2, i, j, k, len, len2;
  7216. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  7217. // ray casting algorithm for detecting if point is in polygon
  7218. for (i = 0, len = this._parts.length; i < len; i++) {
  7219. part = this._parts[i];
  7220. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7221. p1 = part[j];
  7222. p2 = part[k];
  7223. 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)) {
  7224. inside = !inside;
  7225. }
  7226. }
  7227. }
  7228. // also check if it's on polygon stroke
  7229. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  7230. }
  7231. });
  7232. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  7233. function polygon(latlngs, options) {
  7234. return new Polygon(latlngs, options);
  7235. }
  7236. /*
  7237. * @class GeoJSON
  7238. * @aka L.GeoJSON
  7239. * @inherits FeatureGroup
  7240. *
  7241. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  7242. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  7243. *
  7244. * @example
  7245. *
  7246. * ```js
  7247. * L.geoJSON(data, {
  7248. * style: function (feature) {
  7249. * return {color: feature.properties.color};
  7250. * }
  7251. * }).bindPopup(function (layer) {
  7252. * return layer.feature.properties.description;
  7253. * }).addTo(map);
  7254. * ```
  7255. */
  7256. var GeoJSON = FeatureGroup.extend({
  7257. /* @section
  7258. * @aka GeoJSON options
  7259. *
  7260. * @option pointToLayer: Function = *
  7261. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  7262. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  7263. * The default is to spawn a default `Marker`:
  7264. * ```js
  7265. * function(geoJsonPoint, latlng) {
  7266. * return L.marker(latlng);
  7267. * }
  7268. * ```
  7269. *
  7270. * @option style: Function = *
  7271. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  7272. * called internally when data is added.
  7273. * The default value is to not override any defaults:
  7274. * ```js
  7275. * function (geoJsonFeature) {
  7276. * return {}
  7277. * }
  7278. * ```
  7279. *
  7280. * @option onEachFeature: Function = *
  7281. * A `Function` that will be called once for each created `Feature`, after it has
  7282. * been created and styled. Useful for attaching events and popups to features.
  7283. * The default is to do nothing with the newly created layers:
  7284. * ```js
  7285. * function (feature, layer) {}
  7286. * ```
  7287. *
  7288. * @option filter: Function = *
  7289. * A `Function` that will be used to decide whether to include a feature or not.
  7290. * The default is to include all features:
  7291. * ```js
  7292. * function (geoJsonFeature) {
  7293. * return true;
  7294. * }
  7295. * ```
  7296. * Note: dynamically changing the `filter` option will have effect only on newly
  7297. * added data. It will _not_ re-evaluate already included features.
  7298. *
  7299. * @option coordsToLatLng: Function = *
  7300. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  7301. * The default is the `coordsToLatLng` static method.
  7302. *
  7303. * @option markersInheritOptions: Boolean = false
  7304. * Whether default Markers for "Point" type Features inherit from group options.
  7305. */
  7306. initialize: function (geojson, options) {
  7307. setOptions(this, options);
  7308. this._layers = {};
  7309. if (geojson) {
  7310. this.addData(geojson);
  7311. }
  7312. },
  7313. // @method addData( <GeoJSON> data ): this
  7314. // Adds a GeoJSON object to the layer.
  7315. addData: function (geojson) {
  7316. var features = isArray(geojson) ? geojson : geojson.features,
  7317. i, len, feature;
  7318. if (features) {
  7319. for (i = 0, len = features.length; i < len; i++) {
  7320. // only add this if geometry or geometries are set and not null
  7321. feature = features[i];
  7322. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  7323. this.addData(feature);
  7324. }
  7325. }
  7326. return this;
  7327. }
  7328. var options = this.options;
  7329. if (options.filter && !options.filter(geojson)) { return this; }
  7330. var layer = geometryToLayer(geojson, options);
  7331. if (!layer) {
  7332. return this;
  7333. }
  7334. layer.feature = asFeature(geojson);
  7335. layer.defaultOptions = layer.options;
  7336. this.resetStyle(layer);
  7337. if (options.onEachFeature) {
  7338. options.onEachFeature(geojson, layer);
  7339. }
  7340. return this.addLayer(layer);
  7341. },
  7342. // @method resetStyle( <Path> layer? ): this
  7343. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7344. // If `layer` is omitted, the style of all features in the current layer is reset.
  7345. resetStyle: function (layer) {
  7346. if (layer === undefined) {
  7347. return this.eachLayer(this.resetStyle, this);
  7348. }
  7349. // reset any custom styles
  7350. layer.options = extend({}, layer.defaultOptions);
  7351. this._setLayerStyle(layer, this.options.style);
  7352. return this;
  7353. },
  7354. // @method setStyle( <Function> style ): this
  7355. // Changes styles of GeoJSON vector layers with the given style function.
  7356. setStyle: function (style) {
  7357. return this.eachLayer(function (layer) {
  7358. this._setLayerStyle(layer, style);
  7359. }, this);
  7360. },
  7361. _setLayerStyle: function (layer, style) {
  7362. if (layer.setStyle) {
  7363. if (typeof style === 'function') {
  7364. style = style(layer.feature);
  7365. }
  7366. layer.setStyle(style);
  7367. }
  7368. }
  7369. });
  7370. // @section
  7371. // There are several static functions which can be called without instantiating L.GeoJSON:
  7372. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7373. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7374. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7375. // functions if provided as options.
  7376. function geometryToLayer(geojson, options) {
  7377. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7378. coords = geometry ? geometry.coordinates : null,
  7379. layers = [],
  7380. pointToLayer = options && options.pointToLayer,
  7381. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7382. latlng, latlngs, i, len;
  7383. if (!coords && !geometry) {
  7384. return null;
  7385. }
  7386. switch (geometry.type) {
  7387. case 'Point':
  7388. latlng = _coordsToLatLng(coords);
  7389. return _pointToLayer(pointToLayer, geojson, latlng, options);
  7390. case 'MultiPoint':
  7391. for (i = 0, len = coords.length; i < len; i++) {
  7392. latlng = _coordsToLatLng(coords[i]);
  7393. layers.push(_pointToLayer(pointToLayer, geojson, latlng, options));
  7394. }
  7395. return new FeatureGroup(layers);
  7396. case 'LineString':
  7397. case 'MultiLineString':
  7398. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7399. return new Polyline(latlngs, options);
  7400. case 'Polygon':
  7401. case 'MultiPolygon':
  7402. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7403. return new Polygon(latlngs, options);
  7404. case 'GeometryCollection':
  7405. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7406. var geoLayer = geometryToLayer({
  7407. geometry: geometry.geometries[i],
  7408. type: 'Feature',
  7409. properties: geojson.properties
  7410. }, options);
  7411. if (geoLayer) {
  7412. layers.push(geoLayer);
  7413. }
  7414. }
  7415. return new FeatureGroup(layers);
  7416. case 'FeatureCollection':
  7417. for (i = 0, len = geometry.features.length; i < len; i++) {
  7418. var featureLayer = geometryToLayer(geometry.features[i], options);
  7419. if (featureLayer) {
  7420. layers.push(featureLayer);
  7421. }
  7422. }
  7423. return new FeatureGroup(layers);
  7424. default:
  7425. throw new Error('Invalid GeoJSON object.');
  7426. }
  7427. }
  7428. function _pointToLayer(pointToLayerFn, geojson, latlng, options) {
  7429. return pointToLayerFn ?
  7430. pointToLayerFn(geojson, latlng) :
  7431. new Marker(latlng, options && options.markersInheritOptions && options);
  7432. }
  7433. // @function coordsToLatLng(coords: Array): LatLng
  7434. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7435. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7436. function coordsToLatLng(coords) {
  7437. return new LatLng(coords[1], coords[0], coords[2]);
  7438. }
  7439. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7440. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7441. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7442. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7443. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7444. var latlngs = [];
  7445. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7446. latlng = levelsDeep ?
  7447. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7448. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7449. latlngs.push(latlng);
  7450. }
  7451. return latlngs;
  7452. }
  7453. // @function latLngToCoords(latlng: LatLng, precision?: Number|false): Array
  7454. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7455. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function.
  7456. function latLngToCoords(latlng, precision) {
  7457. latlng = toLatLng(latlng);
  7458. return latlng.alt !== undefined ?
  7459. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7460. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7461. }
  7462. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean, precision?: Number|false): Array
  7463. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7464. // `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.
  7465. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function.
  7466. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7467. var coords = [];
  7468. for (var i = 0, len = latlngs.length; i < len; i++) {
  7469. // Check for flat arrays required to ensure unbalanced arrays are correctly converted in recursion
  7470. coords.push(levelsDeep ?
  7471. latLngsToCoords(latlngs[i], isFlat(latlngs[i]) ? 0 : levelsDeep - 1, closed, precision) :
  7472. latLngToCoords(latlngs[i], precision));
  7473. }
  7474. if (!levelsDeep && closed) {
  7475. coords.push(coords[0]);
  7476. }
  7477. return coords;
  7478. }
  7479. function getFeature(layer, newGeometry) {
  7480. return layer.feature ?
  7481. extend({}, layer.feature, {geometry: newGeometry}) :
  7482. asFeature(newGeometry);
  7483. }
  7484. // @function asFeature(geojson: Object): Object
  7485. // Normalize GeoJSON geometries/features into GeoJSON features.
  7486. function asFeature(geojson) {
  7487. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7488. return geojson;
  7489. }
  7490. return {
  7491. type: 'Feature',
  7492. properties: {},
  7493. geometry: geojson
  7494. };
  7495. }
  7496. var PointToGeoJSON = {
  7497. toGeoJSON: function (precision) {
  7498. return getFeature(this, {
  7499. type: 'Point',
  7500. coordinates: latLngToCoords(this.getLatLng(), precision)
  7501. });
  7502. }
  7503. };
  7504. // @namespace Marker
  7505. // @section Other methods
  7506. // @method toGeoJSON(precision?: Number|false): Object
  7507. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7508. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7509. Marker.include(PointToGeoJSON);
  7510. // @namespace CircleMarker
  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 circle marker (as a GeoJSON `Point` Feature).
  7514. Circle.include(PointToGeoJSON);
  7515. CircleMarker.include(PointToGeoJSON);
  7516. // @namespace Polyline
  7517. // @method toGeoJSON(precision?: Number|false): Object
  7518. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7519. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7520. Polyline.include({
  7521. toGeoJSON: function (precision) {
  7522. var multi = !isFlat(this._latlngs);
  7523. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7524. return getFeature(this, {
  7525. type: (multi ? 'Multi' : '') + 'LineString',
  7526. coordinates: coords
  7527. });
  7528. }
  7529. });
  7530. // @namespace Polygon
  7531. // @method toGeoJSON(precision?: Number|false): Object
  7532. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7533. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7534. Polygon.include({
  7535. toGeoJSON: function (precision) {
  7536. var holes = !isFlat(this._latlngs),
  7537. multi = holes && !isFlat(this._latlngs[0]);
  7538. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7539. if (!holes) {
  7540. coords = [coords];
  7541. }
  7542. return getFeature(this, {
  7543. type: (multi ? 'Multi' : '') + 'Polygon',
  7544. coordinates: coords
  7545. });
  7546. }
  7547. });
  7548. // @namespace LayerGroup
  7549. LayerGroup.include({
  7550. toMultiPoint: function (precision) {
  7551. var coords = [];
  7552. this.eachLayer(function (layer) {
  7553. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7554. });
  7555. return getFeature(this, {
  7556. type: 'MultiPoint',
  7557. coordinates: coords
  7558. });
  7559. },
  7560. // @method toGeoJSON(precision?: Number|false): Object
  7561. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7562. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7563. toGeoJSON: function (precision) {
  7564. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7565. if (type === 'MultiPoint') {
  7566. return this.toMultiPoint(precision);
  7567. }
  7568. var isGeometryCollection = type === 'GeometryCollection',
  7569. jsons = [];
  7570. this.eachLayer(function (layer) {
  7571. if (layer.toGeoJSON) {
  7572. var json = layer.toGeoJSON(precision);
  7573. if (isGeometryCollection) {
  7574. jsons.push(json.geometry);
  7575. } else {
  7576. var feature = asFeature(json);
  7577. // Squash nested feature collections
  7578. if (feature.type === 'FeatureCollection') {
  7579. jsons.push.apply(jsons, feature.features);
  7580. } else {
  7581. jsons.push(feature);
  7582. }
  7583. }
  7584. }
  7585. });
  7586. if (isGeometryCollection) {
  7587. return getFeature(this, {
  7588. geometries: jsons,
  7589. type: 'GeometryCollection'
  7590. });
  7591. }
  7592. return {
  7593. type: 'FeatureCollection',
  7594. features: jsons
  7595. };
  7596. }
  7597. });
  7598. // @namespace GeoJSON
  7599. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7600. // Creates a GeoJSON layer. Optionally accepts an object in
  7601. // [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map
  7602. // (you can alternatively add it later with `addData` method) and an `options` object.
  7603. function geoJSON(geojson, options) {
  7604. return new GeoJSON(geojson, options);
  7605. }
  7606. // Backward compatibility.
  7607. var geoJson = geoJSON;
  7608. /*
  7609. * @class ImageOverlay
  7610. * @aka L.ImageOverlay
  7611. * @inherits Interactive layer
  7612. *
  7613. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7614. *
  7615. * @example
  7616. *
  7617. * ```js
  7618. * var imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7619. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7620. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7621. * ```
  7622. */
  7623. var ImageOverlay = Layer.extend({
  7624. // @section
  7625. // @aka ImageOverlay options
  7626. options: {
  7627. // @option opacity: Number = 1.0
  7628. // The opacity of the image overlay.
  7629. opacity: 1,
  7630. // @option alt: String = ''
  7631. // Text for the `alt` attribute of the image (useful for accessibility).
  7632. alt: '',
  7633. // @option interactive: Boolean = false
  7634. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7635. interactive: false,
  7636. // @option crossOrigin: Boolean|String = false
  7637. // Whether the crossOrigin attribute will be added to the image.
  7638. // 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.
  7639. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  7640. crossOrigin: false,
  7641. // @option errorOverlayUrl: String = ''
  7642. // URL to the overlay image to show in place of the overlay that failed to load.
  7643. errorOverlayUrl: '',
  7644. // @option zIndex: Number = 1
  7645. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
  7646. zIndex: 1,
  7647. // @option className: String = ''
  7648. // A custom class name to assign to the image. Empty by default.
  7649. className: ''
  7650. },
  7651. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7652. this._url = url;
  7653. this._bounds = toLatLngBounds(bounds);
  7654. setOptions(this, options);
  7655. },
  7656. onAdd: function () {
  7657. if (!this._image) {
  7658. this._initImage();
  7659. if (this.options.opacity < 1) {
  7660. this._updateOpacity();
  7661. }
  7662. }
  7663. if (this.options.interactive) {
  7664. addClass(this._image, 'leaflet-interactive');
  7665. this.addInteractiveTarget(this._image);
  7666. }
  7667. this.getPane().appendChild(this._image);
  7668. this._reset();
  7669. },
  7670. onRemove: function () {
  7671. remove(this._image);
  7672. if (this.options.interactive) {
  7673. this.removeInteractiveTarget(this._image);
  7674. }
  7675. },
  7676. // @method setOpacity(opacity: Number): this
  7677. // Sets the opacity of the overlay.
  7678. setOpacity: function (opacity) {
  7679. this.options.opacity = opacity;
  7680. if (this._image) {
  7681. this._updateOpacity();
  7682. }
  7683. return this;
  7684. },
  7685. setStyle: function (styleOpts) {
  7686. if (styleOpts.opacity) {
  7687. this.setOpacity(styleOpts.opacity);
  7688. }
  7689. return this;
  7690. },
  7691. // @method bringToFront(): this
  7692. // Brings the layer to the top of all overlays.
  7693. bringToFront: function () {
  7694. if (this._map) {
  7695. toFront(this._image);
  7696. }
  7697. return this;
  7698. },
  7699. // @method bringToBack(): this
  7700. // Brings the layer to the bottom of all overlays.
  7701. bringToBack: function () {
  7702. if (this._map) {
  7703. toBack(this._image);
  7704. }
  7705. return this;
  7706. },
  7707. // @method setUrl(url: String): this
  7708. // Changes the URL of the image.
  7709. setUrl: function (url) {
  7710. this._url = url;
  7711. if (this._image) {
  7712. this._image.src = url;
  7713. }
  7714. return this;
  7715. },
  7716. // @method setBounds(bounds: LatLngBounds): this
  7717. // Update the bounds that this ImageOverlay covers
  7718. setBounds: function (bounds) {
  7719. this._bounds = toLatLngBounds(bounds);
  7720. if (this._map) {
  7721. this._reset();
  7722. }
  7723. return this;
  7724. },
  7725. getEvents: function () {
  7726. var events = {
  7727. zoom: this._reset,
  7728. viewreset: this._reset
  7729. };
  7730. if (this._zoomAnimated) {
  7731. events.zoomanim = this._animateZoom;
  7732. }
  7733. return events;
  7734. },
  7735. // @method setZIndex(value: Number): this
  7736. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7737. setZIndex: function (value) {
  7738. this.options.zIndex = value;
  7739. this._updateZIndex();
  7740. return this;
  7741. },
  7742. // @method getBounds(): LatLngBounds
  7743. // Get the bounds that this ImageOverlay covers
  7744. getBounds: function () {
  7745. return this._bounds;
  7746. },
  7747. // @method getElement(): HTMLElement
  7748. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7749. // used by this overlay.
  7750. getElement: function () {
  7751. return this._image;
  7752. },
  7753. _initImage: function () {
  7754. var wasElementSupplied = this._url.tagName === 'IMG';
  7755. var img = this._image = wasElementSupplied ? this._url : create$1('img');
  7756. addClass(img, 'leaflet-image-layer');
  7757. if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
  7758. if (this.options.className) { addClass(img, this.options.className); }
  7759. img.onselectstart = falseFn;
  7760. img.onmousemove = falseFn;
  7761. // @event load: Event
  7762. // Fired when the ImageOverlay layer has loaded its image
  7763. img.onload = bind(this.fire, this, 'load');
  7764. img.onerror = bind(this._overlayOnError, this, 'error');
  7765. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  7766. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  7767. }
  7768. if (this.options.zIndex) {
  7769. this._updateZIndex();
  7770. }
  7771. if (wasElementSupplied) {
  7772. this._url = img.src;
  7773. return;
  7774. }
  7775. img.src = this._url;
  7776. img.alt = this.options.alt;
  7777. },
  7778. _animateZoom: function (e) {
  7779. var scale = this._map.getZoomScale(e.zoom),
  7780. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7781. setTransform(this._image, offset, scale);
  7782. },
  7783. _reset: function () {
  7784. var image = this._image,
  7785. bounds = new Bounds(
  7786. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7787. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7788. size = bounds.getSize();
  7789. setPosition(image, bounds.min);
  7790. image.style.width = size.x + 'px';
  7791. image.style.height = size.y + 'px';
  7792. },
  7793. _updateOpacity: function () {
  7794. setOpacity(this._image, this.options.opacity);
  7795. },
  7796. _updateZIndex: function () {
  7797. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7798. this._image.style.zIndex = this.options.zIndex;
  7799. }
  7800. },
  7801. _overlayOnError: function () {
  7802. // @event error: Event
  7803. // Fired when the ImageOverlay layer fails to load its image
  7804. this.fire('error');
  7805. var errorUrl = this.options.errorOverlayUrl;
  7806. if (errorUrl && this._url !== errorUrl) {
  7807. this._url = errorUrl;
  7808. this._image.src = errorUrl;
  7809. }
  7810. },
  7811. // @method getCenter(): LatLng
  7812. // Returns the center of the ImageOverlay.
  7813. getCenter: function () {
  7814. return this._bounds.getCenter();
  7815. }
  7816. });
  7817. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7818. // Instantiates an image overlay object given the URL of the image and the
  7819. // geographical bounds it is tied to.
  7820. var imageOverlay = function (url, bounds, options) {
  7821. return new ImageOverlay(url, bounds, options);
  7822. };
  7823. /*
  7824. * @class VideoOverlay
  7825. * @aka L.VideoOverlay
  7826. * @inherits ImageOverlay
  7827. *
  7828. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7829. *
  7830. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7831. * HTML5 element.
  7832. *
  7833. * @example
  7834. *
  7835. * ```js
  7836. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7837. * videoBounds = [[ 32, -130], [ 13, -100]];
  7838. * L.videoOverlay(videoUrl, videoBounds ).addTo(map);
  7839. * ```
  7840. */
  7841. var VideoOverlay = ImageOverlay.extend({
  7842. // @section
  7843. // @aka VideoOverlay options
  7844. options: {
  7845. // @option autoplay: Boolean = true
  7846. // Whether the video starts playing automatically when loaded.
  7847. // On some browsers autoplay will only work with `muted: true`
  7848. autoplay: true,
  7849. // @option loop: Boolean = true
  7850. // Whether the video will loop back to the beginning when played.
  7851. loop: true,
  7852. // @option keepAspectRatio: Boolean = true
  7853. // Whether the video will save aspect ratio after the projection.
  7854. // Relevant for supported browsers. See [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
  7855. keepAspectRatio: true,
  7856. // @option muted: Boolean = false
  7857. // Whether the video starts on mute when loaded.
  7858. muted: false,
  7859. // @option playsInline: Boolean = true
  7860. // Mobile browsers will play the video right where it is instead of open it up in fullscreen mode.
  7861. playsInline: true
  7862. },
  7863. _initImage: function () {
  7864. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7865. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7866. addClass(vid, 'leaflet-image-layer');
  7867. if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
  7868. if (this.options.className) { addClass(vid, this.options.className); }
  7869. vid.onselectstart = falseFn;
  7870. vid.onmousemove = falseFn;
  7871. // @event load: Event
  7872. // Fired when the video has finished loading the first frame
  7873. vid.onloadeddata = bind(this.fire, this, 'load');
  7874. if (wasElementSupplied) {
  7875. var sourceElements = vid.getElementsByTagName('source');
  7876. var sources = [];
  7877. for (var j = 0; j < sourceElements.length; j++) {
  7878. sources.push(sourceElements[j].src);
  7879. }
  7880. this._url = (sourceElements.length > 0) ? sources : [vid.src];
  7881. return;
  7882. }
  7883. if (!isArray(this._url)) { this._url = [this._url]; }
  7884. if (!this.options.keepAspectRatio && Object.prototype.hasOwnProperty.call(vid.style, 'objectFit')) {
  7885. vid.style['objectFit'] = 'fill';
  7886. }
  7887. vid.autoplay = !!this.options.autoplay;
  7888. vid.loop = !!this.options.loop;
  7889. vid.muted = !!this.options.muted;
  7890. vid.playsInline = !!this.options.playsInline;
  7891. for (var i = 0; i < this._url.length; i++) {
  7892. var source = create$1('source');
  7893. source.src = this._url[i];
  7894. vid.appendChild(source);
  7895. }
  7896. }
  7897. // @method getElement(): HTMLVideoElement
  7898. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7899. // used by this overlay.
  7900. });
  7901. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7902. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7903. // geographical bounds it is tied to.
  7904. function videoOverlay(video, bounds, options) {
  7905. return new VideoOverlay(video, bounds, options);
  7906. }
  7907. /*
  7908. * @class SVGOverlay
  7909. * @aka L.SVGOverlay
  7910. * @inherits ImageOverlay
  7911. *
  7912. * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.
  7913. *
  7914. * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.
  7915. *
  7916. * @example
  7917. *
  7918. * ```js
  7919. * var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  7920. * svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
  7921. * svgElement.setAttribute('viewBox', "0 0 200 200");
  7922. * 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"/>';
  7923. * var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
  7924. * L.svgOverlay(svgElement, svgElementBounds).addTo(map);
  7925. * ```
  7926. */
  7927. var SVGOverlay = ImageOverlay.extend({
  7928. _initImage: function () {
  7929. var el = this._image = this._url;
  7930. addClass(el, 'leaflet-image-layer');
  7931. if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); }
  7932. if (this.options.className) { addClass(el, this.options.className); }
  7933. el.onselectstart = falseFn;
  7934. el.onmousemove = falseFn;
  7935. }
  7936. // @method getElement(): SVGElement
  7937. // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
  7938. // used by this overlay.
  7939. });
  7940. // @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)
  7941. // Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.
  7942. // A viewBox attribute is required on the SVG element to zoom in and out properly.
  7943. function svgOverlay(el, bounds, options) {
  7944. return new SVGOverlay(el, bounds, options);
  7945. }
  7946. /*
  7947. * @class DivOverlay
  7948. * @inherits Interactive layer
  7949. * @aka L.DivOverlay
  7950. * Base model for L.Popup and L.Tooltip. Inherit from it for custom overlays like plugins.
  7951. */
  7952. // @namespace DivOverlay
  7953. var DivOverlay = Layer.extend({
  7954. // @section
  7955. // @aka DivOverlay options
  7956. options: {
  7957. // @option interactive: Boolean = false
  7958. // If true, the popup/tooltip will listen to the mouse events.
  7959. interactive: false,
  7960. // @option offset: Point = Point(0, 0)
  7961. // The offset of the overlay position.
  7962. offset: [0, 0],
  7963. // @option className: String = ''
  7964. // A custom CSS class name to assign to the overlay.
  7965. className: '',
  7966. // @option pane: String = undefined
  7967. // `Map pane` where the overlay will be added.
  7968. pane: undefined,
  7969. // @option content: String|HTMLElement|Function = ''
  7970. // Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be
  7971. // passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay.
  7972. content: ''
  7973. },
  7974. initialize: function (options, source) {
  7975. if (options && (options instanceof L.LatLng || isArray(options))) {
  7976. this._latlng = toLatLng(options);
  7977. setOptions(this, source);
  7978. } else {
  7979. setOptions(this, options);
  7980. this._source = source;
  7981. }
  7982. if (this.options.content) {
  7983. this._content = this.options.content;
  7984. }
  7985. },
  7986. // @method openOn(map: Map): this
  7987. // Adds the overlay to the map.
  7988. // Alternative to `map.openPopup(popup)`/`.openTooltip(tooltip)`.
  7989. openOn: function (map) {
  7990. map = arguments.length ? map : this._source._map; // experimental, not the part of public api
  7991. if (!map.hasLayer(this)) {
  7992. map.addLayer(this);
  7993. }
  7994. return this;
  7995. },
  7996. // @method close(): this
  7997. // Closes the overlay.
  7998. // Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)`
  7999. // and `layer.closePopup()`/`.closeTooltip()`.
  8000. close: function () {
  8001. if (this._map) {
  8002. this._map.removeLayer(this);
  8003. }
  8004. return this;
  8005. },
  8006. // @method toggle(layer?: Layer): this
  8007. // Opens or closes the overlay bound to layer depending on its current state.
  8008. // Argument may be omitted only for overlay bound to layer.
  8009. // Alternative to `layer.togglePopup()`/`.toggleTooltip()`.
  8010. toggle: function (layer) {
  8011. if (this._map) {
  8012. this.close();
  8013. } else {
  8014. if (arguments.length) {
  8015. this._source = layer;
  8016. } else {
  8017. layer = this._source;
  8018. }
  8019. this._prepareOpen();
  8020. // open the overlay on the map
  8021. this.openOn(layer._map);
  8022. }
  8023. return this;
  8024. },
  8025. onAdd: function (map) {
  8026. this._zoomAnimated = map._zoomAnimated;
  8027. if (!this._container) {
  8028. this._initLayout();
  8029. }
  8030. if (map._fadeAnimated) {
  8031. setOpacity(this._container, 0);
  8032. }
  8033. clearTimeout(this._removeTimeout);
  8034. this.getPane().appendChild(this._container);
  8035. this.update();
  8036. if (map._fadeAnimated) {
  8037. setOpacity(this._container, 1);
  8038. }
  8039. this.bringToFront();
  8040. if (this.options.interactive) {
  8041. addClass(this._container, 'leaflet-interactive');
  8042. this.addInteractiveTarget(this._container);
  8043. }
  8044. },
  8045. onRemove: function (map) {
  8046. if (map._fadeAnimated) {
  8047. setOpacity(this._container, 0);
  8048. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  8049. } else {
  8050. remove(this._container);
  8051. }
  8052. if (this.options.interactive) {
  8053. removeClass(this._container, 'leaflet-interactive');
  8054. this.removeInteractiveTarget(this._container);
  8055. }
  8056. },
  8057. // @namespace DivOverlay
  8058. // @method getLatLng: LatLng
  8059. // Returns the geographical point of the overlay.
  8060. getLatLng: function () {
  8061. return this._latlng;
  8062. },
  8063. // @method setLatLng(latlng: LatLng): this
  8064. // Sets the geographical point where the overlay will open.
  8065. setLatLng: function (latlng) {
  8066. this._latlng = toLatLng(latlng);
  8067. if (this._map) {
  8068. this._updatePosition();
  8069. this._adjustPan();
  8070. }
  8071. return this;
  8072. },
  8073. // @method getContent: String|HTMLElement
  8074. // Returns the content of the overlay.
  8075. getContent: function () {
  8076. return this._content;
  8077. },
  8078. // @method setContent(htmlContent: String|HTMLElement|Function): this
  8079. // Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function.
  8080. // The function should return a `String` or `HTMLElement` to be used in the overlay.
  8081. setContent: function (content) {
  8082. this._content = content;
  8083. this.update();
  8084. return this;
  8085. },
  8086. // @method getElement: String|HTMLElement
  8087. // Returns the HTML container of the overlay.
  8088. getElement: function () {
  8089. return this._container;
  8090. },
  8091. // @method update: null
  8092. // Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded.
  8093. update: function () {
  8094. if (!this._map) { return; }
  8095. this._container.style.visibility = 'hidden';
  8096. this._updateContent();
  8097. this._updateLayout();
  8098. this._updatePosition();
  8099. this._container.style.visibility = '';
  8100. this._adjustPan();
  8101. },
  8102. getEvents: function () {
  8103. var events = {
  8104. zoom: this._updatePosition,
  8105. viewreset: this._updatePosition
  8106. };
  8107. if (this._zoomAnimated) {
  8108. events.zoomanim = this._animateZoom;
  8109. }
  8110. return events;
  8111. },
  8112. // @method isOpen: Boolean
  8113. // Returns `true` when the overlay is visible on the map.
  8114. isOpen: function () {
  8115. return !!this._map && this._map.hasLayer(this);
  8116. },
  8117. // @method bringToFront: this
  8118. // Brings this overlay in front of other overlays (in the same map pane).
  8119. bringToFront: function () {
  8120. if (this._map) {
  8121. toFront(this._container);
  8122. }
  8123. return this;
  8124. },
  8125. // @method bringToBack: this
  8126. // Brings this overlay to the back of other overlays (in the same map pane).
  8127. bringToBack: function () {
  8128. if (this._map) {
  8129. toBack(this._container);
  8130. }
  8131. return this;
  8132. },
  8133. // prepare bound overlay to open: update latlng pos / content source (for FeatureGroup)
  8134. _prepareOpen: function (latlng) {
  8135. var source = this._source;
  8136. if (!source._map) { return false; }
  8137. if (source instanceof FeatureGroup) {
  8138. source = null;
  8139. var layers = this._source._layers;
  8140. for (var id in layers) {
  8141. if (layers[id]._map) {
  8142. source = layers[id];
  8143. break;
  8144. }
  8145. }
  8146. if (!source) { return false; } // Unable to get source layer.
  8147. // set overlay source to this layer
  8148. this._source = source;
  8149. }
  8150. if (!latlng) {
  8151. if (source.getCenter) {
  8152. latlng = source.getCenter();
  8153. } else if (source.getLatLng) {
  8154. latlng = source.getLatLng();
  8155. } else if (source.getBounds) {
  8156. latlng = source.getBounds().getCenter();
  8157. } else {
  8158. throw new Error('Unable to get source layer LatLng.');
  8159. }
  8160. }
  8161. this.setLatLng(latlng);
  8162. if (this._map) {
  8163. // update the overlay (content, layout, etc...)
  8164. this.update();
  8165. }
  8166. return true;
  8167. },
  8168. _updateContent: function () {
  8169. if (!this._content) { return; }
  8170. var node = this._contentNode;
  8171. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  8172. if (typeof content === 'string') {
  8173. node.innerHTML = content;
  8174. } else {
  8175. while (node.hasChildNodes()) {
  8176. node.removeChild(node.firstChild);
  8177. }
  8178. node.appendChild(content);
  8179. }
  8180. // @namespace DivOverlay
  8181. // @section DivOverlay events
  8182. // @event contentupdate: Event
  8183. // Fired when the content of the overlay is updated
  8184. this.fire('contentupdate');
  8185. },
  8186. _updatePosition: function () {
  8187. if (!this._map) { return; }
  8188. var pos = this._map.latLngToLayerPoint(this._latlng),
  8189. offset = toPoint(this.options.offset),
  8190. anchor = this._getAnchor();
  8191. if (this._zoomAnimated) {
  8192. setPosition(this._container, pos.add(anchor));
  8193. } else {
  8194. offset = offset.add(pos).add(anchor);
  8195. }
  8196. var bottom = this._containerBottom = -offset.y,
  8197. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  8198. // bottom position the overlay in case the height of the overlay changes (images loading etc)
  8199. this._container.style.bottom = bottom + 'px';
  8200. this._container.style.left = left + 'px';
  8201. },
  8202. _getAnchor: function () {
  8203. return [0, 0];
  8204. }
  8205. });
  8206. Map.include({
  8207. _initOverlay: function (OverlayClass, content, latlng, options) {
  8208. var overlay = content;
  8209. if (!(overlay instanceof OverlayClass)) {
  8210. overlay = new OverlayClass(options).setContent(content);
  8211. }
  8212. if (latlng) {
  8213. overlay.setLatLng(latlng);
  8214. }
  8215. return overlay;
  8216. }
  8217. });
  8218. Layer.include({
  8219. _initOverlay: function (OverlayClass, old, content, options) {
  8220. var overlay = content;
  8221. if (overlay instanceof OverlayClass) {
  8222. setOptions(overlay, options);
  8223. overlay._source = this;
  8224. } else {
  8225. overlay = (old && !options) ? old : new OverlayClass(options, this);
  8226. overlay.setContent(content);
  8227. }
  8228. return overlay;
  8229. }
  8230. });
  8231. /*
  8232. * @class Popup
  8233. * @inherits DivOverlay
  8234. * @aka L.Popup
  8235. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  8236. * open popups while making sure that only one popup is open at one time
  8237. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  8238. *
  8239. * @example
  8240. *
  8241. * If you want to just bind a popup to marker click and then open it, it's really easy:
  8242. *
  8243. * ```js
  8244. * marker.bindPopup(popupContent).openPopup();
  8245. * ```
  8246. * Path overlays like polylines also have a `bindPopup` method.
  8247. *
  8248. * A popup can be also standalone:
  8249. *
  8250. * ```js
  8251. * var popup = L.popup()
  8252. * .setLatLng(latlng)
  8253. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  8254. * .openOn(map);
  8255. * ```
  8256. * or
  8257. * ```js
  8258. * var popup = L.popup(latlng, {content: '<p>Hello world!<br />This is a nice popup.</p>')
  8259. * .openOn(map);
  8260. * ```
  8261. */
  8262. // @namespace Popup
  8263. var Popup = DivOverlay.extend({
  8264. // @section
  8265. // @aka Popup options
  8266. options: {
  8267. // @option pane: String = 'popupPane'
  8268. // `Map pane` where the popup will be added.
  8269. pane: 'popupPane',
  8270. // @option offset: Point = Point(0, 7)
  8271. // The offset of the popup position.
  8272. offset: [0, 7],
  8273. // @option maxWidth: Number = 300
  8274. // Max width of the popup, in pixels.
  8275. maxWidth: 300,
  8276. // @option minWidth: Number = 50
  8277. // Min width of the popup, in pixels.
  8278. minWidth: 50,
  8279. // @option maxHeight: Number = null
  8280. // If set, creates a scrollable container of the given height
  8281. // inside a popup if its content exceeds it.
  8282. // The scrollable container can be styled using the
  8283. // `leaflet-popup-scrolled` CSS class selector.
  8284. maxHeight: null,
  8285. // @option autoPan: Boolean = true
  8286. // Set it to `false` if you don't want the map to do panning animation
  8287. // to fit the opened popup.
  8288. autoPan: true,
  8289. // @option autoPanPaddingTopLeft: Point = null
  8290. // The margin between the popup and the top left corner of the map
  8291. // view after autopanning was performed.
  8292. autoPanPaddingTopLeft: null,
  8293. // @option autoPanPaddingBottomRight: Point = null
  8294. // The margin between the popup and the bottom right corner of the map
  8295. // view after autopanning was performed.
  8296. autoPanPaddingBottomRight: null,
  8297. // @option autoPanPadding: Point = Point(5, 5)
  8298. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  8299. autoPanPadding: [5, 5],
  8300. // @option keepInView: Boolean = false
  8301. // Set it to `true` if you want to prevent users from panning the popup
  8302. // off of the screen while it is open.
  8303. keepInView: false,
  8304. // @option closeButton: Boolean = true
  8305. // Controls the presence of a close button in the popup.
  8306. closeButton: true,
  8307. // @option autoClose: Boolean = true
  8308. // Set it to `false` if you want to override the default behavior of
  8309. // the popup closing when another popup is opened.
  8310. autoClose: true,
  8311. // @option closeOnEscapeKey: Boolean = true
  8312. // Set it to `false` if you want to override the default behavior of
  8313. // the ESC key for closing of the popup.
  8314. closeOnEscapeKey: true,
  8315. // @option closeOnClick: Boolean = *
  8316. // Set it if you want to override the default behavior of the popup closing when user clicks
  8317. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  8318. // @option className: String = ''
  8319. // A custom CSS class name to assign to the popup.
  8320. className: ''
  8321. },
  8322. // @namespace Popup
  8323. // @method openOn(map: Map): this
  8324. // Alternative to `map.openPopup(popup)`.
  8325. // Adds the popup to the map and closes the previous one.
  8326. openOn: function (map) {
  8327. map = arguments.length ? map : this._source._map; // experimental, not the part of public api
  8328. if (!map.hasLayer(this) && map._popup && map._popup.options.autoClose) {
  8329. map.removeLayer(map._popup);
  8330. }
  8331. map._popup = this;
  8332. return DivOverlay.prototype.openOn.call(this, map);
  8333. },
  8334. onAdd: function (map) {
  8335. DivOverlay.prototype.onAdd.call(this, map);
  8336. // @namespace Map
  8337. // @section Popup events
  8338. // @event popupopen: PopupEvent
  8339. // Fired when a popup is opened in the map
  8340. map.fire('popupopen', {popup: this});
  8341. if (this._source) {
  8342. // @namespace Layer
  8343. // @section Popup events
  8344. // @event popupopen: PopupEvent
  8345. // Fired when a popup bound to this layer is opened
  8346. this._source.fire('popupopen', {popup: this}, true);
  8347. // For non-path layers, we toggle the popup when clicking
  8348. // again the layer, so prevent the map to reopen it.
  8349. if (!(this._source instanceof Path)) {
  8350. this._source.on('preclick', stopPropagation);
  8351. }
  8352. }
  8353. },
  8354. onRemove: function (map) {
  8355. DivOverlay.prototype.onRemove.call(this, map);
  8356. // @namespace Map
  8357. // @section Popup events
  8358. // @event popupclose: PopupEvent
  8359. // Fired when a popup in the map is closed
  8360. map.fire('popupclose', {popup: this});
  8361. if (this._source) {
  8362. // @namespace Layer
  8363. // @section Popup events
  8364. // @event popupclose: PopupEvent
  8365. // Fired when a popup bound to this layer is closed
  8366. this._source.fire('popupclose', {popup: this}, true);
  8367. if (!(this._source instanceof Path)) {
  8368. this._source.off('preclick', stopPropagation);
  8369. }
  8370. }
  8371. },
  8372. getEvents: function () {
  8373. var events = DivOverlay.prototype.getEvents.call(this);
  8374. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  8375. events.preclick = this.close;
  8376. }
  8377. if (this.options.keepInView) {
  8378. events.moveend = this._adjustPan;
  8379. }
  8380. return events;
  8381. },
  8382. _initLayout: function () {
  8383. var prefix = 'leaflet-popup',
  8384. container = this._container = create$1('div',
  8385. prefix + ' ' + (this.options.className || '') +
  8386. ' leaflet-zoom-animated');
  8387. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  8388. this._contentNode = create$1('div', prefix + '-content', wrapper);
  8389. disableClickPropagation(container);
  8390. disableScrollPropagation(this._contentNode);
  8391. on(container, 'contextmenu', stopPropagation);
  8392. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  8393. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  8394. if (this.options.closeButton) {
  8395. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  8396. closeButton.setAttribute('role', 'button'); // overrides the implicit role=link of <a> elements #7399
  8397. closeButton.setAttribute('aria-label', 'Close popup');
  8398. closeButton.href = '#close';
  8399. closeButton.innerHTML = '<span aria-hidden="true">&#215;</span>';
  8400. on(closeButton, 'click', function (ev) {
  8401. preventDefault(ev);
  8402. this.close();
  8403. }, this);
  8404. }
  8405. },
  8406. _updateLayout: function () {
  8407. var container = this._contentNode,
  8408. style = container.style;
  8409. style.width = '';
  8410. style.whiteSpace = 'nowrap';
  8411. var width = container.offsetWidth;
  8412. width = Math.min(width, this.options.maxWidth);
  8413. width = Math.max(width, this.options.minWidth);
  8414. style.width = (width + 1) + 'px';
  8415. style.whiteSpace = '';
  8416. style.height = '';
  8417. var height = container.offsetHeight,
  8418. maxHeight = this.options.maxHeight,
  8419. scrolledClass = 'leaflet-popup-scrolled';
  8420. if (maxHeight && height > maxHeight) {
  8421. style.height = maxHeight + 'px';
  8422. addClass(container, scrolledClass);
  8423. } else {
  8424. removeClass(container, scrolledClass);
  8425. }
  8426. this._containerWidth = this._container.offsetWidth;
  8427. },
  8428. _animateZoom: function (e) {
  8429. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  8430. anchor = this._getAnchor();
  8431. setPosition(this._container, pos.add(anchor));
  8432. },
  8433. _adjustPan: function (e) {
  8434. if (!this.options.autoPan) { return; }
  8435. if (this._map._panAnim) { this._map._panAnim.stop(); }
  8436. var map = this._map,
  8437. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  8438. containerHeight = this._container.offsetHeight + marginBottom,
  8439. containerWidth = this._containerWidth,
  8440. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  8441. layerPos._add(getPosition(this._container));
  8442. var containerPos = map.layerPointToContainerPoint(layerPos),
  8443. padding = toPoint(this.options.autoPanPadding),
  8444. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  8445. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  8446. size = map.getSize(),
  8447. dx = 0,
  8448. dy = 0;
  8449. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  8450. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  8451. }
  8452. if (containerPos.x - dx - paddingTL.x < 0) { // left
  8453. dx = containerPos.x - paddingTL.x;
  8454. }
  8455. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  8456. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  8457. }
  8458. if (containerPos.y - dy - paddingTL.y < 0) { // top
  8459. dy = containerPos.y - paddingTL.y;
  8460. }
  8461. // @namespace Map
  8462. // @section Popup events
  8463. // @event autopanstart: Event
  8464. // Fired when the map starts autopanning when opening a popup.
  8465. if (dx || dy) {
  8466. map
  8467. .fire('autopanstart')
  8468. .panBy([dx, dy], {animate: e && e.type === 'moveend'});
  8469. }
  8470. },
  8471. _getAnchor: function () {
  8472. // Where should we anchor the popup on the source layer?
  8473. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  8474. }
  8475. });
  8476. // @namespace Popup
  8477. // @factory L.popup(options?: Popup options, source?: Layer)
  8478. // 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.
  8479. // @alternative
  8480. // @factory L.popup(latlng: LatLng, options?: Popup options)
  8481. // Instantiates a `Popup` object given `latlng` where the popup will open and an optional `options` object that describes its appearance and location.
  8482. var popup = function (options, source) {
  8483. return new Popup(options, source);
  8484. };
  8485. /* @namespace Map
  8486. * @section Interaction Options
  8487. * @option closePopupOnClick: Boolean = true
  8488. * Set it to `false` if you don't want popups to close when user clicks the map.
  8489. */
  8490. Map.mergeOptions({
  8491. closePopupOnClick: true
  8492. });
  8493. // @namespace Map
  8494. // @section Methods for Layers and Controls
  8495. Map.include({
  8496. // @method openPopup(popup: Popup): this
  8497. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  8498. // @alternative
  8499. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  8500. // Creates a popup with the specified content and options and opens it in the given point on a map.
  8501. openPopup: function (popup, latlng, options) {
  8502. this._initOverlay(Popup, popup, latlng, options)
  8503. .openOn(this);
  8504. return this;
  8505. },
  8506. // @method closePopup(popup?: Popup): this
  8507. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  8508. closePopup: function (popup) {
  8509. popup = arguments.length ? popup : this._popup;
  8510. if (popup) {
  8511. popup.close();
  8512. }
  8513. return this;
  8514. }
  8515. });
  8516. /*
  8517. * @namespace Layer
  8518. * @section Popup methods example
  8519. *
  8520. * All layers share a set of methods convenient for binding popups to it.
  8521. *
  8522. * ```js
  8523. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  8524. * layer.openPopup();
  8525. * layer.closePopup();
  8526. * ```
  8527. *
  8528. * 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.
  8529. */
  8530. // @section Popup methods
  8531. Layer.include({
  8532. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  8533. // Binds a popup to the layer with the passed `content` and sets up the
  8534. // necessary event listeners. If a `Function` is passed it will receive
  8535. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8536. bindPopup: function (content, options) {
  8537. this._popup = this._initOverlay(Popup, this._popup, content, options);
  8538. if (!this._popupHandlersAdded) {
  8539. this.on({
  8540. click: this._openPopup,
  8541. keypress: this._onKeyPress,
  8542. remove: this.closePopup,
  8543. move: this._movePopup
  8544. });
  8545. this._popupHandlersAdded = true;
  8546. }
  8547. return this;
  8548. },
  8549. // @method unbindPopup(): this
  8550. // Removes the popup previously bound with `bindPopup`.
  8551. unbindPopup: function () {
  8552. if (this._popup) {
  8553. this.off({
  8554. click: this._openPopup,
  8555. keypress: this._onKeyPress,
  8556. remove: this.closePopup,
  8557. move: this._movePopup
  8558. });
  8559. this._popupHandlersAdded = false;
  8560. this._popup = null;
  8561. }
  8562. return this;
  8563. },
  8564. // @method openPopup(latlng?: LatLng): this
  8565. // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
  8566. openPopup: function (latlng) {
  8567. if (this._popup && this._popup._prepareOpen(latlng || this._latlng)) {
  8568. // open the popup on the map
  8569. this._popup.openOn(this._map);
  8570. }
  8571. return this;
  8572. },
  8573. // @method closePopup(): this
  8574. // Closes the popup bound to this layer if it is open.
  8575. closePopup: function () {
  8576. if (this._popup) {
  8577. this._popup.close();
  8578. }
  8579. return this;
  8580. },
  8581. // @method togglePopup(): this
  8582. // Opens or closes the popup bound to this layer depending on its current state.
  8583. togglePopup: function () {
  8584. if (this._popup) {
  8585. this._popup.toggle(this);
  8586. }
  8587. return this;
  8588. },
  8589. // @method isPopupOpen(): boolean
  8590. // Returns `true` if the popup bound to this layer is currently open.
  8591. isPopupOpen: function () {
  8592. return (this._popup ? this._popup.isOpen() : false);
  8593. },
  8594. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8595. // Sets the content of the popup bound to this layer.
  8596. setPopupContent: function (content) {
  8597. if (this._popup) {
  8598. this._popup.setContent(content);
  8599. }
  8600. return this;
  8601. },
  8602. // @method getPopup(): Popup
  8603. // Returns the popup bound to this layer.
  8604. getPopup: function () {
  8605. return this._popup;
  8606. },
  8607. _openPopup: function (e) {
  8608. if (!this._popup || !this._map) {
  8609. return;
  8610. }
  8611. // prevent map click
  8612. stop(e);
  8613. var target = e.layer || e.target;
  8614. if (this._popup._source === target && !(target instanceof Path)) {
  8615. // treat it like a marker and figure out
  8616. // if we should toggle it open/closed
  8617. if (this._map.hasLayer(this._popup)) {
  8618. this.closePopup();
  8619. } else {
  8620. this.openPopup(e.latlng);
  8621. }
  8622. return;
  8623. }
  8624. this._popup._source = target;
  8625. this.openPopup(e.latlng);
  8626. },
  8627. _movePopup: function (e) {
  8628. this._popup.setLatLng(e.latlng);
  8629. },
  8630. _onKeyPress: function (e) {
  8631. if (e.originalEvent.keyCode === 13) {
  8632. this._openPopup(e);
  8633. }
  8634. }
  8635. });
  8636. /*
  8637. * @class Tooltip
  8638. * @inherits DivOverlay
  8639. * @aka L.Tooltip
  8640. * Used to display small texts on top of map layers.
  8641. *
  8642. * @example
  8643. * If you want to just bind a tooltip to marker:
  8644. *
  8645. * ```js
  8646. * marker.bindTooltip("my tooltip text").openTooltip();
  8647. * ```
  8648. * Path overlays like polylines also have a `bindTooltip` method.
  8649. *
  8650. * A tooltip can be also standalone:
  8651. *
  8652. * ```js
  8653. * var tooltip = L.tooltip()
  8654. * .setLatLng(latlng)
  8655. * .setContent('Hello world!<br />This is a nice tooltip.')
  8656. * .addTo(map);
  8657. * ```
  8658. * or
  8659. * ```js
  8660. * var tooltip = L.tooltip(latlng, {content: 'Hello world!<br />This is a nice tooltip.'})
  8661. * .addTo(map);
  8662. * ```
  8663. *
  8664. *
  8665. * Note about tooltip offset. Leaflet takes two options in consideration
  8666. * for computing tooltip offsetting:
  8667. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8668. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8669. * move it to the bottom. Negatives will move to the left and top.
  8670. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8671. * should adapt this value if you use a custom icon.
  8672. */
  8673. // @namespace Tooltip
  8674. var Tooltip = DivOverlay.extend({
  8675. // @section
  8676. // @aka Tooltip options
  8677. options: {
  8678. // @option pane: String = 'tooltipPane'
  8679. // `Map pane` where the tooltip will be added.
  8680. pane: 'tooltipPane',
  8681. // @option offset: Point = Point(0, 0)
  8682. // Optional offset of the tooltip position.
  8683. offset: [0, 0],
  8684. // @option direction: String = 'auto'
  8685. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8686. // `top`, `bottom`, `center`, `auto`.
  8687. // `auto` will dynamically switch between `right` and `left` according to the tooltip
  8688. // position on the map.
  8689. direction: 'auto',
  8690. // @option permanent: Boolean = false
  8691. // Whether to open the tooltip permanently or only on mouseover.
  8692. permanent: false,
  8693. // @option sticky: Boolean = false
  8694. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8695. sticky: false,
  8696. // @option opacity: Number = 0.9
  8697. // Tooltip container opacity.
  8698. opacity: 0.9
  8699. },
  8700. onAdd: function (map) {
  8701. DivOverlay.prototype.onAdd.call(this, map);
  8702. this.setOpacity(this.options.opacity);
  8703. // @namespace Map
  8704. // @section Tooltip events
  8705. // @event tooltipopen: TooltipEvent
  8706. // Fired when a tooltip is opened in the map.
  8707. map.fire('tooltipopen', {tooltip: this});
  8708. if (this._source) {
  8709. this.addEventParent(this._source);
  8710. // @namespace Layer
  8711. // @section Tooltip events
  8712. // @event tooltipopen: TooltipEvent
  8713. // Fired when a tooltip bound to this layer is opened.
  8714. this._source.fire('tooltipopen', {tooltip: this}, true);
  8715. }
  8716. },
  8717. onRemove: function (map) {
  8718. DivOverlay.prototype.onRemove.call(this, map);
  8719. // @namespace Map
  8720. // @section Tooltip events
  8721. // @event tooltipclose: TooltipEvent
  8722. // Fired when a tooltip in the map is closed.
  8723. map.fire('tooltipclose', {tooltip: this});
  8724. if (this._source) {
  8725. this.removeEventParent(this._source);
  8726. // @namespace Layer
  8727. // @section Tooltip events
  8728. // @event tooltipclose: TooltipEvent
  8729. // Fired when a tooltip bound to this layer is closed.
  8730. this._source.fire('tooltipclose', {tooltip: this}, true);
  8731. }
  8732. },
  8733. getEvents: function () {
  8734. var events = DivOverlay.prototype.getEvents.call(this);
  8735. if (!this.options.permanent) {
  8736. events.preclick = this.close;
  8737. }
  8738. return events;
  8739. },
  8740. _initLayout: function () {
  8741. var prefix = 'leaflet-tooltip',
  8742. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8743. this._contentNode = this._container = create$1('div', className);
  8744. this._container.setAttribute('role', 'tooltip');
  8745. this._container.setAttribute('id', 'leaflet-tooltip-' + stamp(this));
  8746. },
  8747. _updateLayout: function () {},
  8748. _adjustPan: function () {},
  8749. _setPosition: function (pos) {
  8750. var subX, subY,
  8751. map = this._map,
  8752. container = this._container,
  8753. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8754. tooltipPoint = map.layerPointToContainerPoint(pos),
  8755. direction = this.options.direction,
  8756. tooltipWidth = container.offsetWidth,
  8757. tooltipHeight = container.offsetHeight,
  8758. offset = toPoint(this.options.offset),
  8759. anchor = this._getAnchor();
  8760. if (direction === 'top') {
  8761. subX = tooltipWidth / 2;
  8762. subY = tooltipHeight;
  8763. } else if (direction === 'bottom') {
  8764. subX = tooltipWidth / 2;
  8765. subY = 0;
  8766. } else if (direction === 'center') {
  8767. subX = tooltipWidth / 2;
  8768. subY = tooltipHeight / 2;
  8769. } else if (direction === 'right') {
  8770. subX = 0;
  8771. subY = tooltipHeight / 2;
  8772. } else if (direction === 'left') {
  8773. subX = tooltipWidth;
  8774. subY = tooltipHeight / 2;
  8775. } else if (tooltipPoint.x < centerPoint.x) {
  8776. direction = 'right';
  8777. subX = 0;
  8778. subY = tooltipHeight / 2;
  8779. } else {
  8780. direction = 'left';
  8781. subX = tooltipWidth + (offset.x + anchor.x) * 2;
  8782. subY = tooltipHeight / 2;
  8783. }
  8784. pos = pos.subtract(toPoint(subX, subY, true)).add(offset).add(anchor);
  8785. removeClass(container, 'leaflet-tooltip-right');
  8786. removeClass(container, 'leaflet-tooltip-left');
  8787. removeClass(container, 'leaflet-tooltip-top');
  8788. removeClass(container, 'leaflet-tooltip-bottom');
  8789. addClass(container, 'leaflet-tooltip-' + direction);
  8790. setPosition(container, pos);
  8791. },
  8792. _updatePosition: function () {
  8793. var pos = this._map.latLngToLayerPoint(this._latlng);
  8794. this._setPosition(pos);
  8795. },
  8796. setOpacity: function (opacity) {
  8797. this.options.opacity = opacity;
  8798. if (this._container) {
  8799. setOpacity(this._container, opacity);
  8800. }
  8801. },
  8802. _animateZoom: function (e) {
  8803. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8804. this._setPosition(pos);
  8805. },
  8806. _getAnchor: function () {
  8807. // Where should we anchor the tooltip on the source layer?
  8808. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8809. }
  8810. });
  8811. // @namespace Tooltip
  8812. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8813. // 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.
  8814. // @alternative
  8815. // @factory L.tooltip(latlng: LatLng, options?: Tooltip options)
  8816. // Instantiates a `Tooltip` object given `latlng` where the tooltip will open and an optional `options` object that describes its appearance and location.
  8817. var tooltip = function (options, source) {
  8818. return new Tooltip(options, source);
  8819. };
  8820. // @namespace Map
  8821. // @section Methods for Layers and Controls
  8822. Map.include({
  8823. // @method openTooltip(tooltip: Tooltip): this
  8824. // Opens the specified tooltip.
  8825. // @alternative
  8826. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8827. // Creates a tooltip with the specified content and options and open it.
  8828. openTooltip: function (tooltip, latlng, options) {
  8829. this._initOverlay(Tooltip, tooltip, latlng, options)
  8830. .openOn(this);
  8831. return this;
  8832. },
  8833. // @method closeTooltip(tooltip: Tooltip): this
  8834. // Closes the tooltip given as parameter.
  8835. closeTooltip: function (tooltip) {
  8836. tooltip.close();
  8837. return this;
  8838. }
  8839. });
  8840. /*
  8841. * @namespace Layer
  8842. * @section Tooltip methods example
  8843. *
  8844. * All layers share a set of methods convenient for binding tooltips to it.
  8845. *
  8846. * ```js
  8847. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8848. * layer.openTooltip();
  8849. * layer.closeTooltip();
  8850. * ```
  8851. */
  8852. // @section Tooltip methods
  8853. Layer.include({
  8854. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8855. // Binds a tooltip to the layer with the passed `content` and sets up the
  8856. // necessary event listeners. If a `Function` is passed it will receive
  8857. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8858. bindTooltip: function (content, options) {
  8859. if (this._tooltip && this.isTooltipOpen()) {
  8860. this.unbindTooltip();
  8861. }
  8862. this._tooltip = this._initOverlay(Tooltip, this._tooltip, content, options);
  8863. this._initTooltipInteractions();
  8864. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8865. this.openTooltip();
  8866. }
  8867. return this;
  8868. },
  8869. // @method unbindTooltip(): this
  8870. // Removes the tooltip previously bound with `bindTooltip`.
  8871. unbindTooltip: function () {
  8872. if (this._tooltip) {
  8873. this._initTooltipInteractions(true);
  8874. this.closeTooltip();
  8875. this._tooltip = null;
  8876. }
  8877. return this;
  8878. },
  8879. _initTooltipInteractions: function (remove) {
  8880. if (!remove && this._tooltipHandlersAdded) { return; }
  8881. var onOff = remove ? 'off' : 'on',
  8882. events = {
  8883. remove: this.closeTooltip,
  8884. move: this._moveTooltip
  8885. };
  8886. if (!this._tooltip.options.permanent) {
  8887. events.mouseover = this._openTooltip;
  8888. events.mouseout = this.closeTooltip;
  8889. events.click = this._openTooltip;
  8890. if (this._map) {
  8891. this._addFocusListeners();
  8892. } else {
  8893. events.add = this._addFocusListeners;
  8894. }
  8895. } else {
  8896. events.add = this._openTooltip;
  8897. }
  8898. if (this._tooltip.options.sticky) {
  8899. events.mousemove = this._moveTooltip;
  8900. }
  8901. this[onOff](events);
  8902. this._tooltipHandlersAdded = !remove;
  8903. },
  8904. // @method openTooltip(latlng?: LatLng): this
  8905. // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8906. openTooltip: function (latlng) {
  8907. if (this._tooltip && this._tooltip._prepareOpen(latlng)) {
  8908. // open the tooltip on the map
  8909. this._tooltip.openOn(this._map);
  8910. if (this.getElement) {
  8911. this._setAriaDescribedByOnLayer(this);
  8912. } else if (this.eachLayer) {
  8913. this.eachLayer(this._setAriaDescribedByOnLayer, this);
  8914. }
  8915. }
  8916. return this;
  8917. },
  8918. // @method closeTooltip(): this
  8919. // Closes the tooltip bound to this layer if it is open.
  8920. closeTooltip: function () {
  8921. if (this._tooltip) {
  8922. return this._tooltip.close();
  8923. }
  8924. },
  8925. // @method toggleTooltip(): this
  8926. // Opens or closes the tooltip bound to this layer depending on its current state.
  8927. toggleTooltip: function () {
  8928. if (this._tooltip) {
  8929. this._tooltip.toggle(this);
  8930. }
  8931. return this;
  8932. },
  8933. // @method isTooltipOpen(): boolean
  8934. // Returns `true` if the tooltip bound to this layer is currently open.
  8935. isTooltipOpen: function () {
  8936. return this._tooltip.isOpen();
  8937. },
  8938. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8939. // Sets the content of the tooltip bound to this layer.
  8940. setTooltipContent: function (content) {
  8941. if (this._tooltip) {
  8942. this._tooltip.setContent(content);
  8943. }
  8944. return this;
  8945. },
  8946. // @method getTooltip(): Tooltip
  8947. // Returns the tooltip bound to this layer.
  8948. getTooltip: function () {
  8949. return this._tooltip;
  8950. },
  8951. _addFocusListeners: function () {
  8952. if (this.getElement) {
  8953. this._addFocusListenersOnLayer(this);
  8954. } else if (this.eachLayer) {
  8955. this.eachLayer(this._addFocusListenersOnLayer, this);
  8956. }
  8957. },
  8958. _addFocusListenersOnLayer: function (layer) {
  8959. var el = layer.getElement();
  8960. if (el) {
  8961. on(el, 'focus', function () {
  8962. this._tooltip._source = layer;
  8963. this.openTooltip();
  8964. }, this);
  8965. on(el, 'blur', this.closeTooltip, this);
  8966. }
  8967. },
  8968. _setAriaDescribedByOnLayer: function (layer) {
  8969. var el = layer.getElement();
  8970. if (el) {
  8971. el.setAttribute('aria-describedby', this._tooltip._container.id);
  8972. }
  8973. },
  8974. _openTooltip: function (e) {
  8975. if (!this._tooltip || !this._map || (this._map.dragging && this._map.dragging.moving())) {
  8976. return;
  8977. }
  8978. this._tooltip._source = e.layer || e.target;
  8979. this.openTooltip(this._tooltip.options.sticky ? e.latlng : undefined);
  8980. },
  8981. _moveTooltip: function (e) {
  8982. var latlng = e.latlng, containerPoint, layerPoint;
  8983. if (this._tooltip.options.sticky && e.originalEvent) {
  8984. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  8985. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  8986. latlng = this._map.layerPointToLatLng(layerPoint);
  8987. }
  8988. this._tooltip.setLatLng(latlng);
  8989. }
  8990. });
  8991. /*
  8992. * @class DivIcon
  8993. * @aka L.DivIcon
  8994. * @inherits Icon
  8995. *
  8996. * Represents a lightweight icon for markers that uses a simple `<div>`
  8997. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  8998. *
  8999. * @example
  9000. * ```js
  9001. * var myIcon = L.divIcon({className: 'my-div-icon'});
  9002. * // you can set .my-div-icon styles in CSS
  9003. *
  9004. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  9005. * ```
  9006. *
  9007. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  9008. */
  9009. var DivIcon = Icon.extend({
  9010. options: {
  9011. // @section
  9012. // @aka DivIcon options
  9013. iconSize: [12, 12], // also can be set through CSS
  9014. // iconAnchor: (Point),
  9015. // popupAnchor: (Point),
  9016. // @option html: String|HTMLElement = ''
  9017. // Custom HTML code to put inside the div element, empty by default. Alternatively,
  9018. // an instance of `HTMLElement`.
  9019. html: false,
  9020. // @option bgPos: Point = [0, 0]
  9021. // Optional relative position of the background, in pixels
  9022. bgPos: null,
  9023. className: 'leaflet-div-icon'
  9024. },
  9025. createIcon: function (oldIcon) {
  9026. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  9027. options = this.options;
  9028. if (options.html instanceof Element) {
  9029. empty(div);
  9030. div.appendChild(options.html);
  9031. } else {
  9032. div.innerHTML = options.html !== false ? options.html : '';
  9033. }
  9034. if (options.bgPos) {
  9035. var bgPos = toPoint(options.bgPos);
  9036. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  9037. }
  9038. this._setIconStyles(div, 'icon');
  9039. return div;
  9040. },
  9041. createShadow: function () {
  9042. return null;
  9043. }
  9044. });
  9045. // @factory L.divIcon(options: DivIcon options)
  9046. // Creates a `DivIcon` instance with the given options.
  9047. function divIcon(options) {
  9048. return new DivIcon(options);
  9049. }
  9050. Icon.Default = IconDefault;
  9051. /*
  9052. * @class GridLayer
  9053. * @inherits Layer
  9054. * @aka L.GridLayer
  9055. *
  9056. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  9057. * 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.
  9058. *
  9059. *
  9060. * @section Synchronous usage
  9061. * @example
  9062. *
  9063. * 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.
  9064. *
  9065. * ```js
  9066. * var CanvasLayer = L.GridLayer.extend({
  9067. * createTile: function(coords){
  9068. * // create a <canvas> element for drawing
  9069. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  9070. *
  9071. * // setup tile width and height according to the options
  9072. * var size = this.getTileSize();
  9073. * tile.width = size.x;
  9074. * tile.height = size.y;
  9075. *
  9076. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  9077. * var ctx = tile.getContext('2d');
  9078. *
  9079. * // return the tile so it can be rendered on screen
  9080. * return tile;
  9081. * }
  9082. * });
  9083. * ```
  9084. *
  9085. * @section Asynchronous usage
  9086. * @example
  9087. *
  9088. * 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.
  9089. *
  9090. * ```js
  9091. * var CanvasLayer = L.GridLayer.extend({
  9092. * createTile: function(coords, done){
  9093. * var error;
  9094. *
  9095. * // create a <canvas> element for drawing
  9096. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  9097. *
  9098. * // setup tile width and height according to the options
  9099. * var size = this.getTileSize();
  9100. * tile.width = size.x;
  9101. * tile.height = size.y;
  9102. *
  9103. * // draw something asynchronously and pass the tile to the done() callback
  9104. * setTimeout(function() {
  9105. * done(error, tile);
  9106. * }, 1000);
  9107. *
  9108. * return tile;
  9109. * }
  9110. * });
  9111. * ```
  9112. *
  9113. * @section
  9114. */
  9115. var GridLayer = Layer.extend({
  9116. // @section
  9117. // @aka GridLayer options
  9118. options: {
  9119. // @option tileSize: Number|Point = 256
  9120. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  9121. tileSize: 256,
  9122. // @option opacity: Number = 1.0
  9123. // Opacity of the tiles. Can be used in the `createTile()` function.
  9124. opacity: 1,
  9125. // @option updateWhenIdle: Boolean = (depends)
  9126. // Load new tiles only when panning ends.
  9127. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  9128. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  9129. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  9130. updateWhenIdle: Browser.mobile,
  9131. // @option updateWhenZooming: Boolean = true
  9132. // 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.
  9133. updateWhenZooming: true,
  9134. // @option updateInterval: Number = 200
  9135. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  9136. updateInterval: 200,
  9137. // @option zIndex: Number = 1
  9138. // The explicit zIndex of the tile layer.
  9139. zIndex: 1,
  9140. // @option bounds: LatLngBounds = undefined
  9141. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  9142. bounds: null,
  9143. // @option minZoom: Number = 0
  9144. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9145. minZoom: 0,
  9146. // @option maxZoom: Number = undefined
  9147. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9148. maxZoom: undefined,
  9149. // @option maxNativeZoom: Number = undefined
  9150. // Maximum zoom number the tile source has available. If it is specified,
  9151. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  9152. // from `maxNativeZoom` level and auto-scaled.
  9153. maxNativeZoom: undefined,
  9154. // @option minNativeZoom: Number = undefined
  9155. // Minimum zoom number the tile source has available. If it is specified,
  9156. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  9157. // from `minNativeZoom` level and auto-scaled.
  9158. minNativeZoom: undefined,
  9159. // @option noWrap: Boolean = false
  9160. // Whether the layer is wrapped around the antimeridian. If `true`, the
  9161. // GridLayer will only be displayed once at low zoom levels. Has no
  9162. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  9163. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  9164. // tiles outside the CRS limits.
  9165. noWrap: false,
  9166. // @option pane: String = 'tilePane'
  9167. // `Map pane` where the grid layer will be added.
  9168. pane: 'tilePane',
  9169. // @option className: String = ''
  9170. // A custom class name to assign to the tile layer. Empty by default.
  9171. className: '',
  9172. // @option keepBuffer: Number = 2
  9173. // When panning the map, keep this many rows and columns of tiles before unloading them.
  9174. keepBuffer: 2
  9175. },
  9176. initialize: function (options) {
  9177. setOptions(this, options);
  9178. },
  9179. onAdd: function () {
  9180. this._initContainer();
  9181. this._levels = {};
  9182. this._tiles = {};
  9183. this._resetView(); // implicit _update() call
  9184. },
  9185. beforeAdd: function (map) {
  9186. map._addZoomLimit(this);
  9187. },
  9188. onRemove: function (map) {
  9189. this._removeAllTiles();
  9190. remove(this._container);
  9191. map._removeZoomLimit(this);
  9192. this._container = null;
  9193. this._tileZoom = undefined;
  9194. },
  9195. // @method bringToFront: this
  9196. // Brings the tile layer to the top of all tile layers.
  9197. bringToFront: function () {
  9198. if (this._map) {
  9199. toFront(this._container);
  9200. this._setAutoZIndex(Math.max);
  9201. }
  9202. return this;
  9203. },
  9204. // @method bringToBack: this
  9205. // Brings the tile layer to the bottom of all tile layers.
  9206. bringToBack: function () {
  9207. if (this._map) {
  9208. toBack(this._container);
  9209. this._setAutoZIndex(Math.min);
  9210. }
  9211. return this;
  9212. },
  9213. // @method getContainer: HTMLElement
  9214. // Returns the HTML element that contains the tiles for this layer.
  9215. getContainer: function () {
  9216. return this._container;
  9217. },
  9218. // @method setOpacity(opacity: Number): this
  9219. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  9220. setOpacity: function (opacity) {
  9221. this.options.opacity = opacity;
  9222. this._updateOpacity();
  9223. return this;
  9224. },
  9225. // @method setZIndex(zIndex: Number): this
  9226. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  9227. setZIndex: function (zIndex) {
  9228. this.options.zIndex = zIndex;
  9229. this._updateZIndex();
  9230. return this;
  9231. },
  9232. // @method isLoading: Boolean
  9233. // Returns `true` if any tile in the grid layer has not finished loading.
  9234. isLoading: function () {
  9235. return this._loading;
  9236. },
  9237. // @method redraw: this
  9238. // Causes the layer to clear all the tiles and request them again.
  9239. redraw: function () {
  9240. if (this._map) {
  9241. this._removeAllTiles();
  9242. var tileZoom = this._clampZoom(this._map.getZoom());
  9243. if (tileZoom !== this._tileZoom) {
  9244. this._tileZoom = tileZoom;
  9245. this._updateLevels();
  9246. }
  9247. this._update();
  9248. }
  9249. return this;
  9250. },
  9251. getEvents: function () {
  9252. var events = {
  9253. viewprereset: this._invalidateAll,
  9254. viewreset: this._resetView,
  9255. zoom: this._resetView,
  9256. moveend: this._onMoveEnd
  9257. };
  9258. if (!this.options.updateWhenIdle) {
  9259. // update tiles on move, but not more often than once per given interval
  9260. if (!this._onMove) {
  9261. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  9262. }
  9263. events.move = this._onMove;
  9264. }
  9265. if (this._zoomAnimated) {
  9266. events.zoomanim = this._animateZoom;
  9267. }
  9268. return events;
  9269. },
  9270. // @section Extension methods
  9271. // Layers extending `GridLayer` shall reimplement the following method.
  9272. // @method createTile(coords: Object, done?: Function): HTMLElement
  9273. // Called only internally, must be overridden by classes extending `GridLayer`.
  9274. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  9275. // is specified, it must be called when the tile has finished loading and drawing.
  9276. createTile: function () {
  9277. return document.createElement('div');
  9278. },
  9279. // @section
  9280. // @method getTileSize: Point
  9281. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  9282. getTileSize: function () {
  9283. var s = this.options.tileSize;
  9284. return s instanceof Point ? s : new Point(s, s);
  9285. },
  9286. _updateZIndex: function () {
  9287. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  9288. this._container.style.zIndex = this.options.zIndex;
  9289. }
  9290. },
  9291. _setAutoZIndex: function (compare) {
  9292. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  9293. var layers = this.getPane().children,
  9294. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  9295. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  9296. zIndex = layers[i].style.zIndex;
  9297. if (layers[i] !== this._container && zIndex) {
  9298. edgeZIndex = compare(edgeZIndex, +zIndex);
  9299. }
  9300. }
  9301. if (isFinite(edgeZIndex)) {
  9302. this.options.zIndex = edgeZIndex + compare(-1, 1);
  9303. this._updateZIndex();
  9304. }
  9305. },
  9306. _updateOpacity: function () {
  9307. if (!this._map) { return; }
  9308. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  9309. if (Browser.ielt9) { return; }
  9310. setOpacity(this._container, this.options.opacity);
  9311. var now = +new Date(),
  9312. nextFrame = false,
  9313. willPrune = false;
  9314. for (var key in this._tiles) {
  9315. var tile = this._tiles[key];
  9316. if (!tile.current || !tile.loaded) { continue; }
  9317. var fade = Math.min(1, (now - tile.loaded) / 200);
  9318. setOpacity(tile.el, fade);
  9319. if (fade < 1) {
  9320. nextFrame = true;
  9321. } else {
  9322. if (tile.active) {
  9323. willPrune = true;
  9324. } else {
  9325. this._onOpaqueTile(tile);
  9326. }
  9327. tile.active = true;
  9328. }
  9329. }
  9330. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  9331. if (nextFrame) {
  9332. cancelAnimFrame(this._fadeFrame);
  9333. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9334. }
  9335. },
  9336. _onOpaqueTile: falseFn,
  9337. _initContainer: function () {
  9338. if (this._container) { return; }
  9339. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  9340. this._updateZIndex();
  9341. if (this.options.opacity < 1) {
  9342. this._updateOpacity();
  9343. }
  9344. this.getPane().appendChild(this._container);
  9345. },
  9346. _updateLevels: function () {
  9347. var zoom = this._tileZoom,
  9348. maxZoom = this.options.maxZoom;
  9349. if (zoom === undefined) { return undefined; }
  9350. for (var z in this._levels) {
  9351. z = Number(z);
  9352. if (this._levels[z].el.children.length || z === zoom) {
  9353. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  9354. this._onUpdateLevel(z);
  9355. } else {
  9356. remove(this._levels[z].el);
  9357. this._removeTilesAtZoom(z);
  9358. this._onRemoveLevel(z);
  9359. delete this._levels[z];
  9360. }
  9361. }
  9362. var level = this._levels[zoom],
  9363. map = this._map;
  9364. if (!level) {
  9365. level = this._levels[zoom] = {};
  9366. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  9367. level.el.style.zIndex = maxZoom;
  9368. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  9369. level.zoom = zoom;
  9370. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  9371. // force the browser to consider the newly added element for transition
  9372. falseFn(level.el.offsetWidth);
  9373. this._onCreateLevel(level);
  9374. }
  9375. this._level = level;
  9376. return level;
  9377. },
  9378. _onUpdateLevel: falseFn,
  9379. _onRemoveLevel: falseFn,
  9380. _onCreateLevel: falseFn,
  9381. _pruneTiles: function () {
  9382. if (!this._map) {
  9383. return;
  9384. }
  9385. var key, tile;
  9386. var zoom = this._map.getZoom();
  9387. if (zoom > this.options.maxZoom ||
  9388. zoom < this.options.minZoom) {
  9389. this._removeAllTiles();
  9390. return;
  9391. }
  9392. for (key in this._tiles) {
  9393. tile = this._tiles[key];
  9394. tile.retain = tile.current;
  9395. }
  9396. for (key in this._tiles) {
  9397. tile = this._tiles[key];
  9398. if (tile.current && !tile.active) {
  9399. var coords = tile.coords;
  9400. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  9401. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  9402. }
  9403. }
  9404. }
  9405. for (key in this._tiles) {
  9406. if (!this._tiles[key].retain) {
  9407. this._removeTile(key);
  9408. }
  9409. }
  9410. },
  9411. _removeTilesAtZoom: function (zoom) {
  9412. for (var key in this._tiles) {
  9413. if (this._tiles[key].coords.z !== zoom) {
  9414. continue;
  9415. }
  9416. this._removeTile(key);
  9417. }
  9418. },
  9419. _removeAllTiles: function () {
  9420. for (var key in this._tiles) {
  9421. this._removeTile(key);
  9422. }
  9423. },
  9424. _invalidateAll: function () {
  9425. for (var z in this._levels) {
  9426. remove(this._levels[z].el);
  9427. this._onRemoveLevel(Number(z));
  9428. delete this._levels[z];
  9429. }
  9430. this._removeAllTiles();
  9431. this._tileZoom = undefined;
  9432. },
  9433. _retainParent: function (x, y, z, minZoom) {
  9434. var x2 = Math.floor(x / 2),
  9435. y2 = Math.floor(y / 2),
  9436. z2 = z - 1,
  9437. coords2 = new Point(+x2, +y2);
  9438. coords2.z = +z2;
  9439. var key = this._tileCoordsToKey(coords2),
  9440. tile = this._tiles[key];
  9441. if (tile && tile.active) {
  9442. tile.retain = true;
  9443. return true;
  9444. } else if (tile && tile.loaded) {
  9445. tile.retain = true;
  9446. }
  9447. if (z2 > minZoom) {
  9448. return this._retainParent(x2, y2, z2, minZoom);
  9449. }
  9450. return false;
  9451. },
  9452. _retainChildren: function (x, y, z, maxZoom) {
  9453. for (var i = 2 * x; i < 2 * x + 2; i++) {
  9454. for (var j = 2 * y; j < 2 * y + 2; j++) {
  9455. var coords = new Point(i, j);
  9456. coords.z = z + 1;
  9457. var key = this._tileCoordsToKey(coords),
  9458. tile = this._tiles[key];
  9459. if (tile && tile.active) {
  9460. tile.retain = true;
  9461. continue;
  9462. } else if (tile && tile.loaded) {
  9463. tile.retain = true;
  9464. }
  9465. if (z + 1 < maxZoom) {
  9466. this._retainChildren(i, j, z + 1, maxZoom);
  9467. }
  9468. }
  9469. }
  9470. },
  9471. _resetView: function (e) {
  9472. var animating = e && (e.pinch || e.flyTo);
  9473. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  9474. },
  9475. _animateZoom: function (e) {
  9476. this._setView(e.center, e.zoom, true, e.noUpdate);
  9477. },
  9478. _clampZoom: function (zoom) {
  9479. var options = this.options;
  9480. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  9481. return options.minNativeZoom;
  9482. }
  9483. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  9484. return options.maxNativeZoom;
  9485. }
  9486. return zoom;
  9487. },
  9488. _setView: function (center, zoom, noPrune, noUpdate) {
  9489. var tileZoom = Math.round(zoom);
  9490. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  9491. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  9492. tileZoom = undefined;
  9493. } else {
  9494. tileZoom = this._clampZoom(tileZoom);
  9495. }
  9496. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  9497. if (!noUpdate || tileZoomChanged) {
  9498. this._tileZoom = tileZoom;
  9499. if (this._abortLoading) {
  9500. this._abortLoading();
  9501. }
  9502. this._updateLevels();
  9503. this._resetGrid();
  9504. if (tileZoom !== undefined) {
  9505. this._update(center);
  9506. }
  9507. if (!noPrune) {
  9508. this._pruneTiles();
  9509. }
  9510. // Flag to prevent _updateOpacity from pruning tiles during
  9511. // a zoom anim or a pinch gesture
  9512. this._noPrune = !!noPrune;
  9513. }
  9514. this._setZoomTransforms(center, zoom);
  9515. },
  9516. _setZoomTransforms: function (center, zoom) {
  9517. for (var i in this._levels) {
  9518. this._setZoomTransform(this._levels[i], center, zoom);
  9519. }
  9520. },
  9521. _setZoomTransform: function (level, center, zoom) {
  9522. var scale = this._map.getZoomScale(zoom, level.zoom),
  9523. translate = level.origin.multiplyBy(scale)
  9524. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  9525. if (Browser.any3d) {
  9526. setTransform(level.el, translate, scale);
  9527. } else {
  9528. setPosition(level.el, translate);
  9529. }
  9530. },
  9531. _resetGrid: function () {
  9532. var map = this._map,
  9533. crs = map.options.crs,
  9534. tileSize = this._tileSize = this.getTileSize(),
  9535. tileZoom = this._tileZoom;
  9536. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  9537. if (bounds) {
  9538. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  9539. }
  9540. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  9541. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  9542. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  9543. ];
  9544. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  9545. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  9546. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  9547. ];
  9548. },
  9549. _onMoveEnd: function () {
  9550. if (!this._map || this._map._animatingZoom) { return; }
  9551. this._update();
  9552. },
  9553. _getTiledPixelBounds: function (center) {
  9554. var map = this._map,
  9555. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9556. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9557. pixelCenter = map.project(center, this._tileZoom).floor(),
  9558. halfSize = map.getSize().divideBy(scale * 2);
  9559. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9560. },
  9561. // Private method to load tiles in the grid's active zoom level according to map bounds
  9562. _update: function (center) {
  9563. var map = this._map;
  9564. if (!map) { return; }
  9565. var zoom = this._clampZoom(map.getZoom());
  9566. if (center === undefined) { center = map.getCenter(); }
  9567. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  9568. var pixelBounds = this._getTiledPixelBounds(center),
  9569. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9570. tileCenter = tileRange.getCenter(),
  9571. queue = [],
  9572. margin = this.options.keepBuffer,
  9573. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9574. tileRange.getTopRight().add([margin, -margin]));
  9575. // Sanity check: panic if the tile range contains Infinity somewhere.
  9576. if (!(isFinite(tileRange.min.x) &&
  9577. isFinite(tileRange.min.y) &&
  9578. isFinite(tileRange.max.x) &&
  9579. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  9580. for (var key in this._tiles) {
  9581. var c = this._tiles[key].coords;
  9582. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9583. this._tiles[key].current = false;
  9584. }
  9585. }
  9586. // _update just loads more tiles. If the tile zoom level differs too much
  9587. // from the map's, let _setView reset levels and prune old tiles.
  9588. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  9589. // create a queue of coordinates to load tiles from
  9590. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9591. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9592. var coords = new Point(i, j);
  9593. coords.z = this._tileZoom;
  9594. if (!this._isValidTile(coords)) { continue; }
  9595. var tile = this._tiles[this._tileCoordsToKey(coords)];
  9596. if (tile) {
  9597. tile.current = true;
  9598. } else {
  9599. queue.push(coords);
  9600. }
  9601. }
  9602. }
  9603. // sort tile queue to load tiles in order of their distance to center
  9604. queue.sort(function (a, b) {
  9605. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9606. });
  9607. if (queue.length !== 0) {
  9608. // if it's the first batch of tiles to load
  9609. if (!this._loading) {
  9610. this._loading = true;
  9611. // @event loading: Event
  9612. // Fired when the grid layer starts loading tiles.
  9613. this.fire('loading');
  9614. }
  9615. // create DOM fragment to append tiles in one batch
  9616. var fragment = document.createDocumentFragment();
  9617. for (i = 0; i < queue.length; i++) {
  9618. this._addTile(queue[i], fragment);
  9619. }
  9620. this._level.el.appendChild(fragment);
  9621. }
  9622. },
  9623. _isValidTile: function (coords) {
  9624. var crs = this._map.options.crs;
  9625. if (!crs.infinite) {
  9626. // don't load tile if it's out of bounds and not wrapped
  9627. var bounds = this._globalTileRange;
  9628. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9629. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  9630. }
  9631. if (!this.options.bounds) { return true; }
  9632. // don't load tile if it doesn't intersect the bounds in options
  9633. var tileBounds = this._tileCoordsToBounds(coords);
  9634. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9635. },
  9636. _keyToBounds: function (key) {
  9637. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9638. },
  9639. _tileCoordsToNwSe: function (coords) {
  9640. var map = this._map,
  9641. tileSize = this.getTileSize(),
  9642. nwPoint = coords.scaleBy(tileSize),
  9643. sePoint = nwPoint.add(tileSize),
  9644. nw = map.unproject(nwPoint, coords.z),
  9645. se = map.unproject(sePoint, coords.z);
  9646. return [nw, se];
  9647. },
  9648. // converts tile coordinates to its geographical bounds
  9649. _tileCoordsToBounds: function (coords) {
  9650. var bp = this._tileCoordsToNwSe(coords),
  9651. bounds = new LatLngBounds(bp[0], bp[1]);
  9652. if (!this.options.noWrap) {
  9653. bounds = this._map.wrapLatLngBounds(bounds);
  9654. }
  9655. return bounds;
  9656. },
  9657. // converts tile coordinates to key for the tile cache
  9658. _tileCoordsToKey: function (coords) {
  9659. return coords.x + ':' + coords.y + ':' + coords.z;
  9660. },
  9661. // converts tile cache key to coordinates
  9662. _keyToTileCoords: function (key) {
  9663. var k = key.split(':'),
  9664. coords = new Point(+k[0], +k[1]);
  9665. coords.z = +k[2];
  9666. return coords;
  9667. },
  9668. _removeTile: function (key) {
  9669. var tile = this._tiles[key];
  9670. if (!tile) { return; }
  9671. remove(tile.el);
  9672. delete this._tiles[key];
  9673. // @event tileunload: TileEvent
  9674. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9675. this.fire('tileunload', {
  9676. tile: tile.el,
  9677. coords: this._keyToTileCoords(key)
  9678. });
  9679. },
  9680. _initTile: function (tile) {
  9681. addClass(tile, 'leaflet-tile');
  9682. var tileSize = this.getTileSize();
  9683. tile.style.width = tileSize.x + 'px';
  9684. tile.style.height = tileSize.y + 'px';
  9685. tile.onselectstart = falseFn;
  9686. tile.onmousemove = falseFn;
  9687. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9688. if (Browser.ielt9 && this.options.opacity < 1) {
  9689. setOpacity(tile, this.options.opacity);
  9690. }
  9691. },
  9692. _addTile: function (coords, container) {
  9693. var tilePos = this._getTilePos(coords),
  9694. key = this._tileCoordsToKey(coords);
  9695. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9696. this._initTile(tile);
  9697. // if createTile is defined with a second argument ("done" callback),
  9698. // we know that tile is async and will be ready later; otherwise
  9699. if (this.createTile.length < 2) {
  9700. // mark tile as ready, but delay one frame for opacity animation to happen
  9701. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9702. }
  9703. setPosition(tile, tilePos);
  9704. // save tile in cache
  9705. this._tiles[key] = {
  9706. el: tile,
  9707. coords: coords,
  9708. current: true
  9709. };
  9710. container.appendChild(tile);
  9711. // @event tileloadstart: TileEvent
  9712. // Fired when a tile is requested and starts loading.
  9713. this.fire('tileloadstart', {
  9714. tile: tile,
  9715. coords: coords
  9716. });
  9717. },
  9718. _tileReady: function (coords, err, tile) {
  9719. if (err) {
  9720. // @event tileerror: TileErrorEvent
  9721. // Fired when there is an error loading a tile.
  9722. this.fire('tileerror', {
  9723. error: err,
  9724. tile: tile,
  9725. coords: coords
  9726. });
  9727. }
  9728. var key = this._tileCoordsToKey(coords);
  9729. tile = this._tiles[key];
  9730. if (!tile) { return; }
  9731. tile.loaded = +new Date();
  9732. if (this._map._fadeAnimated) {
  9733. setOpacity(tile.el, 0);
  9734. cancelAnimFrame(this._fadeFrame);
  9735. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9736. } else {
  9737. tile.active = true;
  9738. this._pruneTiles();
  9739. }
  9740. if (!err) {
  9741. addClass(tile.el, 'leaflet-tile-loaded');
  9742. // @event tileload: TileEvent
  9743. // Fired when a tile loads.
  9744. this.fire('tileload', {
  9745. tile: tile.el,
  9746. coords: coords
  9747. });
  9748. }
  9749. if (this._noTilesToLoad()) {
  9750. this._loading = false;
  9751. // @event load: Event
  9752. // Fired when the grid layer loaded all visible tiles.
  9753. this.fire('load');
  9754. if (Browser.ielt9 || !this._map._fadeAnimated) {
  9755. requestAnimFrame(this._pruneTiles, this);
  9756. } else {
  9757. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9758. // to trigger a pruning.
  9759. setTimeout(bind(this._pruneTiles, this), 250);
  9760. }
  9761. }
  9762. },
  9763. _getTilePos: function (coords) {
  9764. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9765. },
  9766. _wrapCoords: function (coords) {
  9767. var newCoords = new Point(
  9768. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9769. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9770. newCoords.z = coords.z;
  9771. return newCoords;
  9772. },
  9773. _pxBoundsToTileRange: function (bounds) {
  9774. var tileSize = this.getTileSize();
  9775. return new Bounds(
  9776. bounds.min.unscaleBy(tileSize).floor(),
  9777. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9778. },
  9779. _noTilesToLoad: function () {
  9780. for (var key in this._tiles) {
  9781. if (!this._tiles[key].loaded) { return false; }
  9782. }
  9783. return true;
  9784. }
  9785. });
  9786. // @factory L.gridLayer(options?: GridLayer options)
  9787. // Creates a new instance of GridLayer with the supplied options.
  9788. function gridLayer(options) {
  9789. return new GridLayer(options);
  9790. }
  9791. /*
  9792. * @class TileLayer
  9793. * @inherits GridLayer
  9794. * @aka L.TileLayer
  9795. * 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`.
  9796. *
  9797. * @example
  9798. *
  9799. * ```js
  9800. * 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);
  9801. * ```
  9802. *
  9803. * @section URL template
  9804. * @example
  9805. *
  9806. * A string of the following form:
  9807. *
  9808. * ```
  9809. * 'https://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9810. * ```
  9811. *
  9812. * `{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.
  9813. *
  9814. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9815. *
  9816. * ```
  9817. * L.tileLayer('https://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9818. * ```
  9819. */
  9820. var TileLayer = GridLayer.extend({
  9821. // @section
  9822. // @aka TileLayer options
  9823. options: {
  9824. // @option minZoom: Number = 0
  9825. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9826. minZoom: 0,
  9827. // @option maxZoom: Number = 18
  9828. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9829. maxZoom: 18,
  9830. // @option subdomains: String|String[] = 'abc'
  9831. // 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.
  9832. subdomains: 'abc',
  9833. // @option errorTileUrl: String = ''
  9834. // URL to the tile image to show in place of the tile that failed to load.
  9835. errorTileUrl: '',
  9836. // @option zoomOffset: Number = 0
  9837. // The zoom number used in tile URLs will be offset with this value.
  9838. zoomOffset: 0,
  9839. // @option tms: Boolean = false
  9840. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9841. tms: false,
  9842. // @option zoomReverse: Boolean = false
  9843. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9844. zoomReverse: false,
  9845. // @option detectRetina: Boolean = false
  9846. // 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.
  9847. detectRetina: false,
  9848. // @option crossOrigin: Boolean|String = false
  9849. // Whether the crossOrigin attribute will be added to the tiles.
  9850. // 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.
  9851. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  9852. crossOrigin: false,
  9853. // @option referrerPolicy: Boolean|String = false
  9854. // Whether the referrerPolicy attribute will be added to the tiles.
  9855. // If a String is provided, all tiles will have their referrerPolicy attribute set to the String provided.
  9856. // This may be needed if your map's rendering context has a strict default but your tile provider expects a valid referrer
  9857. // (e.g. to validate an API token).
  9858. // Refer to [HTMLImageElement.referrerPolicy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/referrerPolicy) for valid String values.
  9859. referrerPolicy: false
  9860. },
  9861. initialize: function (url, options) {
  9862. this._url = url;
  9863. options = setOptions(this, options);
  9864. // detecting retina displays, adjusting tileSize and zoom levels
  9865. if (options.detectRetina && Browser.retina && options.maxZoom > 0) {
  9866. options.tileSize = Math.floor(options.tileSize / 2);
  9867. if (!options.zoomReverse) {
  9868. options.zoomOffset++;
  9869. options.maxZoom = Math.max(options.minZoom, options.maxZoom - 1);
  9870. } else {
  9871. options.zoomOffset--;
  9872. options.minZoom = Math.min(options.maxZoom, options.minZoom + 1);
  9873. }
  9874. options.minZoom = Math.max(0, options.minZoom);
  9875. } else if (!options.zoomReverse) {
  9876. // make sure maxZoom is gte minZoom
  9877. options.maxZoom = Math.max(options.minZoom, options.maxZoom);
  9878. } else {
  9879. // make sure minZoom is lte maxZoom
  9880. options.minZoom = Math.min(options.maxZoom, options.minZoom);
  9881. }
  9882. if (typeof options.subdomains === 'string') {
  9883. options.subdomains = options.subdomains.split('');
  9884. }
  9885. this.on('tileunload', this._onTileRemove);
  9886. },
  9887. // @method setUrl(url: String, noRedraw?: Boolean): this
  9888. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9889. // If the URL does not change, the layer will not be redrawn unless
  9890. // the noRedraw parameter is set to false.
  9891. setUrl: function (url, noRedraw) {
  9892. if (this._url === url && noRedraw === undefined) {
  9893. noRedraw = true;
  9894. }
  9895. this._url = url;
  9896. if (!noRedraw) {
  9897. this.redraw();
  9898. }
  9899. return this;
  9900. },
  9901. // @method createTile(coords: Object, done?: Function): HTMLElement
  9902. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9903. // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
  9904. // callback is called when the tile has been loaded.
  9905. createTile: function (coords, done) {
  9906. var tile = document.createElement('img');
  9907. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9908. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9909. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  9910. tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  9911. }
  9912. // for this new option we follow the documented behavior
  9913. // more closely by only setting the property when string
  9914. if (typeof this.options.referrerPolicy === 'string') {
  9915. tile.referrerPolicy = this.options.referrerPolicy;
  9916. }
  9917. // The alt attribute is set to the empty string,
  9918. // allowing screen readers to ignore the decorative image tiles.
  9919. // https://www.w3.org/WAI/tutorials/images/decorative/
  9920. // https://www.w3.org/TR/html-aria/#el-img-empty-alt
  9921. tile.alt = '';
  9922. tile.src = this.getTileUrl(coords);
  9923. return tile;
  9924. },
  9925. // @section Extension methods
  9926. // @uninheritable
  9927. // Layers extending `TileLayer` might reimplement the following method.
  9928. // @method getTileUrl(coords: Object): String
  9929. // Called only internally, returns the URL for a tile given its coordinates.
  9930. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9931. getTileUrl: function (coords) {
  9932. var data = {
  9933. r: Browser.retina ? '@2x' : '',
  9934. s: this._getSubdomain(coords),
  9935. x: coords.x,
  9936. y: coords.y,
  9937. z: this._getZoomForUrl()
  9938. };
  9939. if (this._map && !this._map.options.crs.infinite) {
  9940. var invertedY = this._globalTileRange.max.y - coords.y;
  9941. if (this.options.tms) {
  9942. data['y'] = invertedY;
  9943. }
  9944. data['-y'] = invertedY;
  9945. }
  9946. return template(this._url, extend(data, this.options));
  9947. },
  9948. _tileOnLoad: function (done, tile) {
  9949. // For https://github.com/Leaflet/Leaflet/issues/3332
  9950. if (Browser.ielt9) {
  9951. setTimeout(bind(done, this, null, tile), 0);
  9952. } else {
  9953. done(null, tile);
  9954. }
  9955. },
  9956. _tileOnError: function (done, tile, e) {
  9957. var errorUrl = this.options.errorTileUrl;
  9958. if (errorUrl && tile.getAttribute('src') !== errorUrl) {
  9959. tile.src = errorUrl;
  9960. }
  9961. done(e, tile);
  9962. },
  9963. _onTileRemove: function (e) {
  9964. e.tile.onload = null;
  9965. },
  9966. _getZoomForUrl: function () {
  9967. var zoom = this._tileZoom,
  9968. maxZoom = this.options.maxZoom,
  9969. zoomReverse = this.options.zoomReverse,
  9970. zoomOffset = this.options.zoomOffset;
  9971. if (zoomReverse) {
  9972. zoom = maxZoom - zoom;
  9973. }
  9974. return zoom + zoomOffset;
  9975. },
  9976. _getSubdomain: function (tilePoint) {
  9977. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  9978. return this.options.subdomains[index];
  9979. },
  9980. // stops loading all tiles in the background layer
  9981. _abortLoading: function () {
  9982. var i, tile;
  9983. for (i in this._tiles) {
  9984. if (this._tiles[i].coords.z !== this._tileZoom) {
  9985. tile = this._tiles[i].el;
  9986. tile.onload = falseFn;
  9987. tile.onerror = falseFn;
  9988. if (!tile.complete) {
  9989. tile.src = emptyImageUrl;
  9990. var coords = this._tiles[i].coords;
  9991. remove(tile);
  9992. delete this._tiles[i];
  9993. // @event tileabort: TileEvent
  9994. // Fired when a tile was loading but is now not wanted.
  9995. this.fire('tileabort', {
  9996. tile: tile,
  9997. coords: coords
  9998. });
  9999. }
  10000. }
  10001. }
  10002. },
  10003. _removeTile: function (key) {
  10004. var tile = this._tiles[key];
  10005. if (!tile) { return; }
  10006. // Cancels any pending http requests associated with the tile
  10007. tile.el.setAttribute('src', emptyImageUrl);
  10008. return GridLayer.prototype._removeTile.call(this, key);
  10009. },
  10010. _tileReady: function (coords, err, tile) {
  10011. if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) {
  10012. return;
  10013. }
  10014. return GridLayer.prototype._tileReady.call(this, coords, err, tile);
  10015. }
  10016. });
  10017. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  10018. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  10019. function tileLayer(url, options) {
  10020. return new TileLayer(url, options);
  10021. }
  10022. /*
  10023. * @class TileLayer.WMS
  10024. * @inherits TileLayer
  10025. * @aka L.TileLayer.WMS
  10026. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  10027. *
  10028. * @example
  10029. *
  10030. * ```js
  10031. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  10032. * layers: 'nexrad-n0r-900913',
  10033. * format: 'image/png',
  10034. * transparent: true,
  10035. * attribution: "Weather data © 2012 IEM Nexrad"
  10036. * });
  10037. * ```
  10038. */
  10039. var TileLayerWMS = TileLayer.extend({
  10040. // @section
  10041. // @aka TileLayer.WMS options
  10042. // If any custom options not documented here are used, they will be sent to the
  10043. // WMS server as extra parameters in each request URL. This can be useful for
  10044. // [non-standard vendor WMS parameters](https://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  10045. defaultWmsParams: {
  10046. service: 'WMS',
  10047. request: 'GetMap',
  10048. // @option layers: String = ''
  10049. // **(required)** Comma-separated list of WMS layers to show.
  10050. layers: '',
  10051. // @option styles: String = ''
  10052. // Comma-separated list of WMS styles.
  10053. styles: '',
  10054. // @option format: String = 'image/jpeg'
  10055. // WMS image format (use `'image/png'` for layers with transparency).
  10056. format: 'image/jpeg',
  10057. // @option transparent: Boolean = false
  10058. // If `true`, the WMS service will return images with transparency.
  10059. transparent: false,
  10060. // @option version: String = '1.1.1'
  10061. // Version of the WMS service to use
  10062. version: '1.1.1'
  10063. },
  10064. options: {
  10065. // @option crs: CRS = null
  10066. // Coordinate Reference System to use for the WMS requests, defaults to
  10067. // map CRS. Don't change this if you're not sure what it means.
  10068. crs: null,
  10069. // @option uppercase: Boolean = false
  10070. // If `true`, WMS request parameter keys will be uppercase.
  10071. uppercase: false
  10072. },
  10073. initialize: function (url, options) {
  10074. this._url = url;
  10075. var wmsParams = extend({}, this.defaultWmsParams);
  10076. // all keys that are not TileLayer options go to WMS params
  10077. for (var i in options) {
  10078. if (!(i in this.options)) {
  10079. wmsParams[i] = options[i];
  10080. }
  10081. }
  10082. options = setOptions(this, options);
  10083. var realRetina = options.detectRetina && Browser.retina ? 2 : 1;
  10084. var tileSize = this.getTileSize();
  10085. wmsParams.width = tileSize.x * realRetina;
  10086. wmsParams.height = tileSize.y * realRetina;
  10087. this.wmsParams = wmsParams;
  10088. },
  10089. onAdd: function (map) {
  10090. this._crs = this.options.crs || map.options.crs;
  10091. this._wmsVersion = parseFloat(this.wmsParams.version);
  10092. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  10093. this.wmsParams[projectionKey] = this._crs.code;
  10094. TileLayer.prototype.onAdd.call(this, map);
  10095. },
  10096. getTileUrl: function (coords) {
  10097. var tileBounds = this._tileCoordsToNwSe(coords),
  10098. crs = this._crs,
  10099. bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
  10100. min = bounds.min,
  10101. max = bounds.max,
  10102. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  10103. [min.y, min.x, max.y, max.x] :
  10104. [min.x, min.y, max.x, max.y]).join(','),
  10105. url = TileLayer.prototype.getTileUrl.call(this, coords);
  10106. return url +
  10107. getParamString(this.wmsParams, url, this.options.uppercase) +
  10108. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  10109. },
  10110. // @method setParams(params: Object, noRedraw?: Boolean): this
  10111. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  10112. setParams: function (params, noRedraw) {
  10113. extend(this.wmsParams, params);
  10114. if (!noRedraw) {
  10115. this.redraw();
  10116. }
  10117. return this;
  10118. }
  10119. });
  10120. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  10121. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  10122. function tileLayerWMS(url, options) {
  10123. return new TileLayerWMS(url, options);
  10124. }
  10125. TileLayer.WMS = TileLayerWMS;
  10126. tileLayer.wms = tileLayerWMS;
  10127. /*
  10128. * @class Renderer
  10129. * @inherits Layer
  10130. * @aka L.Renderer
  10131. *
  10132. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  10133. * DOM container of the renderer, its bounds, and its zoom animation.
  10134. *
  10135. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  10136. * itself can be added or removed to the map. All paths use a renderer, which can
  10137. * be implicit (the map will decide the type of renderer and use it automatically)
  10138. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  10139. *
  10140. * Do not use this class directly, use `SVG` and `Canvas` instead.
  10141. *
  10142. * @event update: Event
  10143. * Fired when the renderer updates its bounds, center and zoom, for example when
  10144. * its map has moved
  10145. */
  10146. var Renderer = Layer.extend({
  10147. // @section
  10148. // @aka Renderer options
  10149. options: {
  10150. // @option padding: Number = 0.1
  10151. // How much to extend the clip area around the map view (relative to its size)
  10152. // e.g. 0.1 would be 10% of map view in each direction
  10153. padding: 0.1
  10154. },
  10155. initialize: function (options) {
  10156. setOptions(this, options);
  10157. stamp(this);
  10158. this._layers = this._layers || {};
  10159. },
  10160. onAdd: function () {
  10161. if (!this._container) {
  10162. this._initContainer(); // defined by renderer implementations
  10163. if (this._zoomAnimated) {
  10164. addClass(this._container, 'leaflet-zoom-animated');
  10165. }
  10166. }
  10167. this.getPane().appendChild(this._container);
  10168. this._update();
  10169. this.on('update', this._updatePaths, this);
  10170. },
  10171. onRemove: function () {
  10172. this.off('update', this._updatePaths, this);
  10173. this._destroyContainer();
  10174. },
  10175. getEvents: function () {
  10176. var events = {
  10177. viewreset: this._reset,
  10178. zoom: this._onZoom,
  10179. moveend: this._update,
  10180. zoomend: this._onZoomEnd
  10181. };
  10182. if (this._zoomAnimated) {
  10183. events.zoomanim = this._onAnimZoom;
  10184. }
  10185. return events;
  10186. },
  10187. _onAnimZoom: function (ev) {
  10188. this._updateTransform(ev.center, ev.zoom);
  10189. },
  10190. _onZoom: function () {
  10191. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  10192. },
  10193. _updateTransform: function (center, zoom) {
  10194. var scale = this._map.getZoomScale(zoom, this._zoom),
  10195. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  10196. currentCenterPoint = this._map.project(this._center, zoom),
  10197. topLeftOffset = viewHalf.multiplyBy(-scale).add(currentCenterPoint)
  10198. .subtract(this._map._getNewPixelOrigin(center, zoom));
  10199. if (Browser.any3d) {
  10200. setTransform(this._container, topLeftOffset, scale);
  10201. } else {
  10202. setPosition(this._container, topLeftOffset);
  10203. }
  10204. },
  10205. _reset: function () {
  10206. this._update();
  10207. this._updateTransform(this._center, this._zoom);
  10208. for (var id in this._layers) {
  10209. this._layers[id]._reset();
  10210. }
  10211. },
  10212. _onZoomEnd: function () {
  10213. for (var id in this._layers) {
  10214. this._layers[id]._project();
  10215. }
  10216. },
  10217. _updatePaths: function () {
  10218. for (var id in this._layers) {
  10219. this._layers[id]._update();
  10220. }
  10221. },
  10222. _update: function () {
  10223. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  10224. // Subclasses are responsible of firing the 'update' event.
  10225. var p = this.options.padding,
  10226. size = this._map.getSize(),
  10227. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  10228. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  10229. this._center = this._map.getCenter();
  10230. this._zoom = this._map.getZoom();
  10231. }
  10232. });
  10233. /*
  10234. * @class Canvas
  10235. * @inherits Renderer
  10236. * @aka L.Canvas
  10237. *
  10238. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  10239. * Inherits `Renderer`.
  10240. *
  10241. * Due to [technical limitations](https://caniuse.com/canvas), Canvas is not
  10242. * available in all web browsers, notably IE8, and overlapping geometries might
  10243. * not display properly in some edge cases.
  10244. *
  10245. * @example
  10246. *
  10247. * Use Canvas by default for all paths in the map:
  10248. *
  10249. * ```js
  10250. * var map = L.map('map', {
  10251. * renderer: L.canvas()
  10252. * });
  10253. * ```
  10254. *
  10255. * Use a Canvas renderer with extra padding for specific vector geometries:
  10256. *
  10257. * ```js
  10258. * var map = L.map('map');
  10259. * var myRenderer = L.canvas({ padding: 0.5 });
  10260. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10261. * var circle = L.circle( center, { renderer: myRenderer } );
  10262. * ```
  10263. */
  10264. var Canvas = Renderer.extend({
  10265. // @section
  10266. // @aka Canvas options
  10267. options: {
  10268. // @option tolerance: Number = 0
  10269. // How much to extend the click tolerance around a path/object on the map.
  10270. tolerance: 0
  10271. },
  10272. getEvents: function () {
  10273. var events = Renderer.prototype.getEvents.call(this);
  10274. events.viewprereset = this._onViewPreReset;
  10275. return events;
  10276. },
  10277. _onViewPreReset: function () {
  10278. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  10279. this._postponeUpdatePaths = true;
  10280. },
  10281. onAdd: function () {
  10282. Renderer.prototype.onAdd.call(this);
  10283. // Redraw vectors since canvas is cleared upon removal,
  10284. // in case of removing the renderer itself from the map.
  10285. this._draw();
  10286. },
  10287. _initContainer: function () {
  10288. var container = this._container = document.createElement('canvas');
  10289. on(container, 'mousemove', this._onMouseMove, this);
  10290. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  10291. on(container, 'mouseout', this._handleMouseOut, this);
  10292. container['_leaflet_disable_events'] = true;
  10293. this._ctx = container.getContext('2d');
  10294. },
  10295. _destroyContainer: function () {
  10296. cancelAnimFrame(this._redrawRequest);
  10297. delete this._ctx;
  10298. remove(this._container);
  10299. off(this._container);
  10300. delete this._container;
  10301. },
  10302. _updatePaths: function () {
  10303. if (this._postponeUpdatePaths) { return; }
  10304. var layer;
  10305. this._redrawBounds = null;
  10306. for (var id in this._layers) {
  10307. layer = this._layers[id];
  10308. layer._update();
  10309. }
  10310. this._redraw();
  10311. },
  10312. _update: function () {
  10313. if (this._map._animatingZoom && this._bounds) { return; }
  10314. Renderer.prototype._update.call(this);
  10315. var b = this._bounds,
  10316. container = this._container,
  10317. size = b.getSize(),
  10318. m = Browser.retina ? 2 : 1;
  10319. setPosition(container, b.min);
  10320. // set canvas size (also clearing it); use double size on retina
  10321. container.width = m * size.x;
  10322. container.height = m * size.y;
  10323. container.style.width = size.x + 'px';
  10324. container.style.height = size.y + 'px';
  10325. if (Browser.retina) {
  10326. this._ctx.scale(2, 2);
  10327. }
  10328. // translate so we use the same path coordinates after canvas element moves
  10329. this._ctx.translate(-b.min.x, -b.min.y);
  10330. // Tell paths to redraw themselves
  10331. this.fire('update');
  10332. },
  10333. _reset: function () {
  10334. Renderer.prototype._reset.call(this);
  10335. if (this._postponeUpdatePaths) {
  10336. this._postponeUpdatePaths = false;
  10337. this._updatePaths();
  10338. }
  10339. },
  10340. _initPath: function (layer) {
  10341. this._updateDashArray(layer);
  10342. this._layers[stamp(layer)] = layer;
  10343. var order = layer._order = {
  10344. layer: layer,
  10345. prev: this._drawLast,
  10346. next: null
  10347. };
  10348. if (this._drawLast) { this._drawLast.next = order; }
  10349. this._drawLast = order;
  10350. this._drawFirst = this._drawFirst || this._drawLast;
  10351. },
  10352. _addPath: function (layer) {
  10353. this._requestRedraw(layer);
  10354. },
  10355. _removePath: function (layer) {
  10356. var order = layer._order;
  10357. var next = order.next;
  10358. var prev = order.prev;
  10359. if (next) {
  10360. next.prev = prev;
  10361. } else {
  10362. this._drawLast = prev;
  10363. }
  10364. if (prev) {
  10365. prev.next = next;
  10366. } else {
  10367. this._drawFirst = next;
  10368. }
  10369. delete layer._order;
  10370. delete this._layers[stamp(layer)];
  10371. this._requestRedraw(layer);
  10372. },
  10373. _updatePath: function (layer) {
  10374. // Redraw the union of the layer's old pixel
  10375. // bounds and the new pixel bounds.
  10376. this._extendRedrawBounds(layer);
  10377. layer._project();
  10378. layer._update();
  10379. // The redraw will extend the redraw bounds
  10380. // with the new pixel bounds.
  10381. this._requestRedraw(layer);
  10382. },
  10383. _updateStyle: function (layer) {
  10384. this._updateDashArray(layer);
  10385. this._requestRedraw(layer);
  10386. },
  10387. _updateDashArray: function (layer) {
  10388. if (typeof layer.options.dashArray === 'string') {
  10389. var parts = layer.options.dashArray.split(/[, ]+/),
  10390. dashArray = [],
  10391. dashValue,
  10392. i;
  10393. for (i = 0; i < parts.length; i++) {
  10394. dashValue = Number(parts[i]);
  10395. // Ignore dash array containing invalid lengths
  10396. if (isNaN(dashValue)) { return; }
  10397. dashArray.push(dashValue);
  10398. }
  10399. layer.options._dashArray = dashArray;
  10400. } else {
  10401. layer.options._dashArray = layer.options.dashArray;
  10402. }
  10403. },
  10404. _requestRedraw: function (layer) {
  10405. if (!this._map) { return; }
  10406. this._extendRedrawBounds(layer);
  10407. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  10408. },
  10409. _extendRedrawBounds: function (layer) {
  10410. if (layer._pxBounds) {
  10411. var padding = (layer.options.weight || 0) + 1;
  10412. this._redrawBounds = this._redrawBounds || new Bounds();
  10413. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  10414. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  10415. }
  10416. },
  10417. _redraw: function () {
  10418. this._redrawRequest = null;
  10419. if (this._redrawBounds) {
  10420. this._redrawBounds.min._floor();
  10421. this._redrawBounds.max._ceil();
  10422. }
  10423. this._clear(); // clear layers in redraw bounds
  10424. this._draw(); // draw layers
  10425. this._redrawBounds = null;
  10426. },
  10427. _clear: function () {
  10428. var bounds = this._redrawBounds;
  10429. if (bounds) {
  10430. var size = bounds.getSize();
  10431. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  10432. } else {
  10433. this._ctx.save();
  10434. this._ctx.setTransform(1, 0, 0, 1, 0, 0);
  10435. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  10436. this._ctx.restore();
  10437. }
  10438. },
  10439. _draw: function () {
  10440. var layer, bounds = this._redrawBounds;
  10441. this._ctx.save();
  10442. if (bounds) {
  10443. var size = bounds.getSize();
  10444. this._ctx.beginPath();
  10445. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  10446. this._ctx.clip();
  10447. }
  10448. this._drawing = true;
  10449. for (var order = this._drawFirst; order; order = order.next) {
  10450. layer = order.layer;
  10451. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  10452. layer._updatePath();
  10453. }
  10454. }
  10455. this._drawing = false;
  10456. this._ctx.restore(); // Restore state before clipping.
  10457. },
  10458. _updatePoly: function (layer, closed) {
  10459. if (!this._drawing) { return; }
  10460. var i, j, len2, p,
  10461. parts = layer._parts,
  10462. len = parts.length,
  10463. ctx = this._ctx;
  10464. if (!len) { return; }
  10465. ctx.beginPath();
  10466. for (i = 0; i < len; i++) {
  10467. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  10468. p = parts[i][j];
  10469. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  10470. }
  10471. if (closed) {
  10472. ctx.closePath();
  10473. }
  10474. }
  10475. this._fillStroke(ctx, layer);
  10476. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  10477. },
  10478. _updateCircle: function (layer) {
  10479. if (!this._drawing || layer._empty()) { return; }
  10480. var p = layer._point,
  10481. ctx = this._ctx,
  10482. r = Math.max(Math.round(layer._radius), 1),
  10483. s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
  10484. if (s !== 1) {
  10485. ctx.save();
  10486. ctx.scale(1, s);
  10487. }
  10488. ctx.beginPath();
  10489. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  10490. if (s !== 1) {
  10491. ctx.restore();
  10492. }
  10493. this._fillStroke(ctx, layer);
  10494. },
  10495. _fillStroke: function (ctx, layer) {
  10496. var options = layer.options;
  10497. if (options.fill) {
  10498. ctx.globalAlpha = options.fillOpacity;
  10499. ctx.fillStyle = options.fillColor || options.color;
  10500. ctx.fill(options.fillRule || 'evenodd');
  10501. }
  10502. if (options.stroke && options.weight !== 0) {
  10503. if (ctx.setLineDash) {
  10504. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  10505. }
  10506. ctx.globalAlpha = options.opacity;
  10507. ctx.lineWidth = options.weight;
  10508. ctx.strokeStyle = options.color;
  10509. ctx.lineCap = options.lineCap;
  10510. ctx.lineJoin = options.lineJoin;
  10511. ctx.stroke();
  10512. }
  10513. },
  10514. // Canvas obviously doesn't have mouse events for individual drawn objects,
  10515. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  10516. _onClick: function (e) {
  10517. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  10518. for (var order = this._drawFirst; order; order = order.next) {
  10519. layer = order.layer;
  10520. if (layer.options.interactive && layer._containsPoint(point)) {
  10521. if (!(e.type === 'click' || e.type === 'preclick') || !this._map._draggableMoved(layer)) {
  10522. clickedLayer = layer;
  10523. }
  10524. }
  10525. }
  10526. this._fireEvent(clickedLayer ? [clickedLayer] : false, e);
  10527. },
  10528. _onMouseMove: function (e) {
  10529. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  10530. var point = this._map.mouseEventToLayerPoint(e);
  10531. this._handleMouseHover(e, point);
  10532. },
  10533. _handleMouseOut: function (e) {
  10534. var layer = this._hoveredLayer;
  10535. if (layer) {
  10536. // if we're leaving the layer, fire mouseout
  10537. removeClass(this._container, 'leaflet-interactive');
  10538. this._fireEvent([layer], e, 'mouseout');
  10539. this._hoveredLayer = null;
  10540. this._mouseHoverThrottled = false;
  10541. }
  10542. },
  10543. _handleMouseHover: function (e, point) {
  10544. if (this._mouseHoverThrottled) {
  10545. return;
  10546. }
  10547. var layer, candidateHoveredLayer;
  10548. for (var order = this._drawFirst; order; order = order.next) {
  10549. layer = order.layer;
  10550. if (layer.options.interactive && layer._containsPoint(point)) {
  10551. candidateHoveredLayer = layer;
  10552. }
  10553. }
  10554. if (candidateHoveredLayer !== this._hoveredLayer) {
  10555. this._handleMouseOut(e);
  10556. if (candidateHoveredLayer) {
  10557. addClass(this._container, 'leaflet-interactive'); // change cursor
  10558. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  10559. this._hoveredLayer = candidateHoveredLayer;
  10560. }
  10561. }
  10562. this._fireEvent(this._hoveredLayer ? [this._hoveredLayer] : false, e);
  10563. this._mouseHoverThrottled = true;
  10564. setTimeout(bind(function () {
  10565. this._mouseHoverThrottled = false;
  10566. }, this), 32);
  10567. },
  10568. _fireEvent: function (layers, e, type) {
  10569. this._map._fireDOMEvent(e, type || e.type, layers);
  10570. },
  10571. _bringToFront: function (layer) {
  10572. var order = layer._order;
  10573. if (!order) { return; }
  10574. var next = order.next;
  10575. var prev = order.prev;
  10576. if (next) {
  10577. next.prev = prev;
  10578. } else {
  10579. // Already last
  10580. return;
  10581. }
  10582. if (prev) {
  10583. prev.next = next;
  10584. } else if (next) {
  10585. // Update first entry unless this is the
  10586. // single entry
  10587. this._drawFirst = next;
  10588. }
  10589. order.prev = this._drawLast;
  10590. this._drawLast.next = order;
  10591. order.next = null;
  10592. this._drawLast = order;
  10593. this._requestRedraw(layer);
  10594. },
  10595. _bringToBack: function (layer) {
  10596. var order = layer._order;
  10597. if (!order) { return; }
  10598. var next = order.next;
  10599. var prev = order.prev;
  10600. if (prev) {
  10601. prev.next = next;
  10602. } else {
  10603. // Already first
  10604. return;
  10605. }
  10606. if (next) {
  10607. next.prev = prev;
  10608. } else if (prev) {
  10609. // Update last entry unless this is the
  10610. // single entry
  10611. this._drawLast = prev;
  10612. }
  10613. order.prev = null;
  10614. order.next = this._drawFirst;
  10615. this._drawFirst.prev = order;
  10616. this._drawFirst = order;
  10617. this._requestRedraw(layer);
  10618. }
  10619. });
  10620. // @factory L.canvas(options?: Renderer options)
  10621. // Creates a Canvas renderer with the given options.
  10622. function canvas(options) {
  10623. return Browser.canvas ? new Canvas(options) : null;
  10624. }
  10625. /*
  10626. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10627. */
  10628. var vmlCreate = (function () {
  10629. try {
  10630. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10631. return function (name) {
  10632. return document.createElement('<lvml:' + name + ' class="lvml">');
  10633. };
  10634. } catch (e) {
  10635. // Do not return fn from catch block so `e` can be garbage collected
  10636. // See https://github.com/Leaflet/Leaflet/pull/7279
  10637. }
  10638. return function (name) {
  10639. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10640. };
  10641. })();
  10642. /*
  10643. * @class SVG
  10644. *
  10645. *
  10646. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10647. * with old versions of Internet Explorer.
  10648. */
  10649. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10650. var vmlMixin = {
  10651. _initContainer: function () {
  10652. this._container = create$1('div', 'leaflet-vml-container');
  10653. },
  10654. _update: function () {
  10655. if (this._map._animatingZoom) { return; }
  10656. Renderer.prototype._update.call(this);
  10657. this.fire('update');
  10658. },
  10659. _initPath: function (layer) {
  10660. var container = layer._container = vmlCreate('shape');
  10661. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10662. container.coordsize = '1 1';
  10663. layer._path = vmlCreate('path');
  10664. container.appendChild(layer._path);
  10665. this._updateStyle(layer);
  10666. this._layers[stamp(layer)] = layer;
  10667. },
  10668. _addPath: function (layer) {
  10669. var container = layer._container;
  10670. this._container.appendChild(container);
  10671. if (layer.options.interactive) {
  10672. layer.addInteractiveTarget(container);
  10673. }
  10674. },
  10675. _removePath: function (layer) {
  10676. var container = layer._container;
  10677. remove(container);
  10678. layer.removeInteractiveTarget(container);
  10679. delete this._layers[stamp(layer)];
  10680. },
  10681. _updateStyle: function (layer) {
  10682. var stroke = layer._stroke,
  10683. fill = layer._fill,
  10684. options = layer.options,
  10685. container = layer._container;
  10686. container.stroked = !!options.stroke;
  10687. container.filled = !!options.fill;
  10688. if (options.stroke) {
  10689. if (!stroke) {
  10690. stroke = layer._stroke = vmlCreate('stroke');
  10691. }
  10692. container.appendChild(stroke);
  10693. stroke.weight = options.weight + 'px';
  10694. stroke.color = options.color;
  10695. stroke.opacity = options.opacity;
  10696. if (options.dashArray) {
  10697. stroke.dashStyle = isArray(options.dashArray) ?
  10698. options.dashArray.join(' ') :
  10699. options.dashArray.replace(/( *, *)/g, ' ');
  10700. } else {
  10701. stroke.dashStyle = '';
  10702. }
  10703. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10704. stroke.joinstyle = options.lineJoin;
  10705. } else if (stroke) {
  10706. container.removeChild(stroke);
  10707. layer._stroke = null;
  10708. }
  10709. if (options.fill) {
  10710. if (!fill) {
  10711. fill = layer._fill = vmlCreate('fill');
  10712. }
  10713. container.appendChild(fill);
  10714. fill.color = options.fillColor || options.color;
  10715. fill.opacity = options.fillOpacity;
  10716. } else if (fill) {
  10717. container.removeChild(fill);
  10718. layer._fill = null;
  10719. }
  10720. },
  10721. _updateCircle: function (layer) {
  10722. var p = layer._point.round(),
  10723. r = Math.round(layer._radius),
  10724. r2 = Math.round(layer._radiusY || r);
  10725. this._setPath(layer, layer._empty() ? 'M0 0' :
  10726. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10727. },
  10728. _setPath: function (layer, path) {
  10729. layer._path.v = path;
  10730. },
  10731. _bringToFront: function (layer) {
  10732. toFront(layer._container);
  10733. },
  10734. _bringToBack: function (layer) {
  10735. toBack(layer._container);
  10736. }
  10737. };
  10738. var create = Browser.vml ? vmlCreate : svgCreate;
  10739. /*
  10740. * @class SVG
  10741. * @inherits Renderer
  10742. * @aka L.SVG
  10743. *
  10744. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10745. * Inherits `Renderer`.
  10746. *
  10747. * Due to [technical limitations](https://caniuse.com/svg), SVG is not
  10748. * available in all web browsers, notably Android 2.x and 3.x.
  10749. *
  10750. * Although SVG is not available on IE7 and IE8, these browsers support
  10751. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10752. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10753. * this case.
  10754. *
  10755. * @example
  10756. *
  10757. * Use SVG by default for all paths in the map:
  10758. *
  10759. * ```js
  10760. * var map = L.map('map', {
  10761. * renderer: L.svg()
  10762. * });
  10763. * ```
  10764. *
  10765. * Use a SVG renderer with extra padding for specific vector geometries:
  10766. *
  10767. * ```js
  10768. * var map = L.map('map');
  10769. * var myRenderer = L.svg({ padding: 0.5 });
  10770. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10771. * var circle = L.circle( center, { renderer: myRenderer } );
  10772. * ```
  10773. */
  10774. var SVG = Renderer.extend({
  10775. _initContainer: function () {
  10776. this._container = create('svg');
  10777. // makes it possible to click through svg root; we'll reset it back in individual paths
  10778. this._container.setAttribute('pointer-events', 'none');
  10779. this._rootGroup = create('g');
  10780. this._container.appendChild(this._rootGroup);
  10781. },
  10782. _destroyContainer: function () {
  10783. remove(this._container);
  10784. off(this._container);
  10785. delete this._container;
  10786. delete this._rootGroup;
  10787. delete this._svgSize;
  10788. },
  10789. _update: function () {
  10790. if (this._map._animatingZoom && this._bounds) { return; }
  10791. Renderer.prototype._update.call(this);
  10792. var b = this._bounds,
  10793. size = b.getSize(),
  10794. container = this._container;
  10795. // set size of svg-container if changed
  10796. if (!this._svgSize || !this._svgSize.equals(size)) {
  10797. this._svgSize = size;
  10798. container.setAttribute('width', size.x);
  10799. container.setAttribute('height', size.y);
  10800. }
  10801. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10802. setPosition(container, b.min);
  10803. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10804. this.fire('update');
  10805. },
  10806. // methods below are called by vector layers implementations
  10807. _initPath: function (layer) {
  10808. var path = layer._path = create('path');
  10809. // @namespace Path
  10810. // @option className: String = null
  10811. // Custom class name set on an element. Only for SVG renderer.
  10812. if (layer.options.className) {
  10813. addClass(path, layer.options.className);
  10814. }
  10815. if (layer.options.interactive) {
  10816. addClass(path, 'leaflet-interactive');
  10817. }
  10818. this._updateStyle(layer);
  10819. this._layers[stamp(layer)] = layer;
  10820. },
  10821. _addPath: function (layer) {
  10822. if (!this._rootGroup) { this._initContainer(); }
  10823. this._rootGroup.appendChild(layer._path);
  10824. layer.addInteractiveTarget(layer._path);
  10825. },
  10826. _removePath: function (layer) {
  10827. remove(layer._path);
  10828. layer.removeInteractiveTarget(layer._path);
  10829. delete this._layers[stamp(layer)];
  10830. },
  10831. _updatePath: function (layer) {
  10832. layer._project();
  10833. layer._update();
  10834. },
  10835. _updateStyle: function (layer) {
  10836. var path = layer._path,
  10837. options = layer.options;
  10838. if (!path) { return; }
  10839. if (options.stroke) {
  10840. path.setAttribute('stroke', options.color);
  10841. path.setAttribute('stroke-opacity', options.opacity);
  10842. path.setAttribute('stroke-width', options.weight);
  10843. path.setAttribute('stroke-linecap', options.lineCap);
  10844. path.setAttribute('stroke-linejoin', options.lineJoin);
  10845. if (options.dashArray) {
  10846. path.setAttribute('stroke-dasharray', options.dashArray);
  10847. } else {
  10848. path.removeAttribute('stroke-dasharray');
  10849. }
  10850. if (options.dashOffset) {
  10851. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10852. } else {
  10853. path.removeAttribute('stroke-dashoffset');
  10854. }
  10855. } else {
  10856. path.setAttribute('stroke', 'none');
  10857. }
  10858. if (options.fill) {
  10859. path.setAttribute('fill', options.fillColor || options.color);
  10860. path.setAttribute('fill-opacity', options.fillOpacity);
  10861. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10862. } else {
  10863. path.setAttribute('fill', 'none');
  10864. }
  10865. },
  10866. _updatePoly: function (layer, closed) {
  10867. this._setPath(layer, pointsToPath(layer._parts, closed));
  10868. },
  10869. _updateCircle: function (layer) {
  10870. var p = layer._point,
  10871. r = Math.max(Math.round(layer._radius), 1),
  10872. r2 = Math.max(Math.round(layer._radiusY), 1) || r,
  10873. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10874. // drawing a circle with two half-arcs
  10875. var d = layer._empty() ? 'M0 0' :
  10876. 'M' + (p.x - r) + ',' + p.y +
  10877. arc + (r * 2) + ',0 ' +
  10878. arc + (-r * 2) + ',0 ';
  10879. this._setPath(layer, d);
  10880. },
  10881. _setPath: function (layer, path) {
  10882. layer._path.setAttribute('d', path);
  10883. },
  10884. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10885. _bringToFront: function (layer) {
  10886. toFront(layer._path);
  10887. },
  10888. _bringToBack: function (layer) {
  10889. toBack(layer._path);
  10890. }
  10891. });
  10892. if (Browser.vml) {
  10893. SVG.include(vmlMixin);
  10894. }
  10895. // @namespace SVG
  10896. // @factory L.svg(options?: Renderer options)
  10897. // Creates a SVG renderer with the given options.
  10898. function svg(options) {
  10899. return Browser.svg || Browser.vml ? new SVG(options) : null;
  10900. }
  10901. Map.include({
  10902. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10903. // Returns the instance of `Renderer` that should be used to render the given
  10904. // `Path`. It will ensure that the `renderer` options of the map and paths
  10905. // are respected, and that the renderers do exist on the map.
  10906. getRenderer: function (layer) {
  10907. // @namespace Path; @option renderer: Renderer
  10908. // Use this specific instance of `Renderer` for this path. Takes
  10909. // precedence over the map's [default renderer](#map-renderer).
  10910. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10911. if (!renderer) {
  10912. renderer = this._renderer = this._createRenderer();
  10913. }
  10914. if (!this.hasLayer(renderer)) {
  10915. this.addLayer(renderer);
  10916. }
  10917. return renderer;
  10918. },
  10919. _getPaneRenderer: function (name) {
  10920. if (name === 'overlayPane' || name === undefined) {
  10921. return false;
  10922. }
  10923. var renderer = this._paneRenderers[name];
  10924. if (renderer === undefined) {
  10925. renderer = this._createRenderer({pane: name});
  10926. this._paneRenderers[name] = renderer;
  10927. }
  10928. return renderer;
  10929. },
  10930. _createRenderer: function (options) {
  10931. // @namespace Map; @option preferCanvas: Boolean = false
  10932. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10933. // By default, all `Path`s are rendered in a `SVG` renderer.
  10934. return (this.options.preferCanvas && canvas(options)) || svg(options);
  10935. }
  10936. });
  10937. /*
  10938. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10939. */
  10940. /*
  10941. * @class Rectangle
  10942. * @aka L.Rectangle
  10943. * @inherits Polygon
  10944. *
  10945. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10946. *
  10947. * @example
  10948. *
  10949. * ```js
  10950. * // define rectangle geographical bounds
  10951. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10952. *
  10953. * // create an orange rectangle
  10954. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10955. *
  10956. * // zoom the map to the rectangle bounds
  10957. * map.fitBounds(bounds);
  10958. * ```
  10959. *
  10960. */
  10961. var Rectangle = Polygon.extend({
  10962. initialize: function (latLngBounds, options) {
  10963. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10964. },
  10965. // @method setBounds(latLngBounds: LatLngBounds): this
  10966. // Redraws the rectangle with the passed bounds.
  10967. setBounds: function (latLngBounds) {
  10968. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  10969. },
  10970. _boundsToLatLngs: function (latLngBounds) {
  10971. latLngBounds = toLatLngBounds(latLngBounds);
  10972. return [
  10973. latLngBounds.getSouthWest(),
  10974. latLngBounds.getNorthWest(),
  10975. latLngBounds.getNorthEast(),
  10976. latLngBounds.getSouthEast()
  10977. ];
  10978. }
  10979. });
  10980. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  10981. function rectangle(latLngBounds, options) {
  10982. return new Rectangle(latLngBounds, options);
  10983. }
  10984. SVG.create = create;
  10985. SVG.pointsToPath = pointsToPath;
  10986. GeoJSON.geometryToLayer = geometryToLayer;
  10987. GeoJSON.coordsToLatLng = coordsToLatLng;
  10988. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  10989. GeoJSON.latLngToCoords = latLngToCoords;
  10990. GeoJSON.latLngsToCoords = latLngsToCoords;
  10991. GeoJSON.getFeature = getFeature;
  10992. GeoJSON.asFeature = asFeature;
  10993. /*
  10994. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  10995. * (zoom to a selected bounding box), enabled by default.
  10996. */
  10997. // @namespace Map
  10998. // @section Interaction Options
  10999. Map.mergeOptions({
  11000. // @option boxZoom: Boolean = true
  11001. // Whether the map can be zoomed to a rectangular area specified by
  11002. // dragging the mouse while pressing the shift key.
  11003. boxZoom: true
  11004. });
  11005. var BoxZoom = Handler.extend({
  11006. initialize: function (map) {
  11007. this._map = map;
  11008. this._container = map._container;
  11009. this._pane = map._panes.overlayPane;
  11010. this._resetStateTimeout = 0;
  11011. map.on('unload', this._destroy, this);
  11012. },
  11013. addHooks: function () {
  11014. on(this._container, 'mousedown', this._onMouseDown, this);
  11015. },
  11016. removeHooks: function () {
  11017. off(this._container, 'mousedown', this._onMouseDown, this);
  11018. },
  11019. moved: function () {
  11020. return this._moved;
  11021. },
  11022. _destroy: function () {
  11023. remove(this._pane);
  11024. delete this._pane;
  11025. },
  11026. _resetState: function () {
  11027. this._resetStateTimeout = 0;
  11028. this._moved = false;
  11029. },
  11030. _clearDeferredResetState: function () {
  11031. if (this._resetStateTimeout !== 0) {
  11032. clearTimeout(this._resetStateTimeout);
  11033. this._resetStateTimeout = 0;
  11034. }
  11035. },
  11036. _onMouseDown: function (e) {
  11037. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  11038. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  11039. // will interrupt the interaction and orphan a box element in the container.
  11040. this._clearDeferredResetState();
  11041. this._resetState();
  11042. disableTextSelection();
  11043. disableImageDrag();
  11044. this._startPoint = this._map.mouseEventToContainerPoint(e);
  11045. on(document, {
  11046. contextmenu: stop,
  11047. mousemove: this._onMouseMove,
  11048. mouseup: this._onMouseUp,
  11049. keydown: this._onKeyDown
  11050. }, this);
  11051. },
  11052. _onMouseMove: function (e) {
  11053. if (!this._moved) {
  11054. this._moved = true;
  11055. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  11056. addClass(this._container, 'leaflet-crosshair');
  11057. this._map.fire('boxzoomstart');
  11058. }
  11059. this._point = this._map.mouseEventToContainerPoint(e);
  11060. var bounds = new Bounds(this._point, this._startPoint),
  11061. size = bounds.getSize();
  11062. setPosition(this._box, bounds.min);
  11063. this._box.style.width = size.x + 'px';
  11064. this._box.style.height = size.y + 'px';
  11065. },
  11066. _finish: function () {
  11067. if (this._moved) {
  11068. remove(this._box);
  11069. removeClass(this._container, 'leaflet-crosshair');
  11070. }
  11071. enableTextSelection();
  11072. enableImageDrag();
  11073. off(document, {
  11074. contextmenu: stop,
  11075. mousemove: this._onMouseMove,
  11076. mouseup: this._onMouseUp,
  11077. keydown: this._onKeyDown
  11078. }, this);
  11079. },
  11080. _onMouseUp: function (e) {
  11081. if ((e.which !== 1) && (e.button !== 1)) { return; }
  11082. this._finish();
  11083. if (!this._moved) { return; }
  11084. // Postpone to next JS tick so internal click event handling
  11085. // still see it as "moved".
  11086. this._clearDeferredResetState();
  11087. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  11088. var bounds = new LatLngBounds(
  11089. this._map.containerPointToLatLng(this._startPoint),
  11090. this._map.containerPointToLatLng(this._point));
  11091. this._map
  11092. .fitBounds(bounds)
  11093. .fire('boxzoomend', {boxZoomBounds: bounds});
  11094. },
  11095. _onKeyDown: function (e) {
  11096. if (e.keyCode === 27) {
  11097. this._finish();
  11098. this._clearDeferredResetState();
  11099. this._resetState();
  11100. }
  11101. }
  11102. });
  11103. // @section Handlers
  11104. // @property boxZoom: Handler
  11105. // Box (shift-drag with mouse) zoom handler.
  11106. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  11107. /*
  11108. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  11109. */
  11110. // @namespace Map
  11111. // @section Interaction Options
  11112. Map.mergeOptions({
  11113. // @option doubleClickZoom: Boolean|String = true
  11114. // Whether the map can be zoomed in by double clicking on it and
  11115. // zoomed out by double clicking while holding shift. If passed
  11116. // `'center'`, double-click zoom will zoom to the center of the
  11117. // view regardless of where the mouse was.
  11118. doubleClickZoom: true
  11119. });
  11120. var DoubleClickZoom = Handler.extend({
  11121. addHooks: function () {
  11122. this._map.on('dblclick', this._onDoubleClick, this);
  11123. },
  11124. removeHooks: function () {
  11125. this._map.off('dblclick', this._onDoubleClick, this);
  11126. },
  11127. _onDoubleClick: function (e) {
  11128. var map = this._map,
  11129. oldZoom = map.getZoom(),
  11130. delta = map.options.zoomDelta,
  11131. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  11132. if (map.options.doubleClickZoom === 'center') {
  11133. map.setZoom(zoom);
  11134. } else {
  11135. map.setZoomAround(e.containerPoint, zoom);
  11136. }
  11137. }
  11138. });
  11139. // @section Handlers
  11140. //
  11141. // Map properties include interaction handlers that allow you to control
  11142. // interaction behavior in runtime, enabling or disabling certain features such
  11143. // as dragging or touch zoom (see `Handler` methods). For example:
  11144. //
  11145. // ```js
  11146. // map.doubleClickZoom.disable();
  11147. // ```
  11148. //
  11149. // @property doubleClickZoom: Handler
  11150. // Double click zoom handler.
  11151. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  11152. /*
  11153. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  11154. */
  11155. // @namespace Map
  11156. // @section Interaction Options
  11157. Map.mergeOptions({
  11158. // @option dragging: Boolean = true
  11159. // Whether the map is draggable with mouse/touch or not.
  11160. dragging: true,
  11161. // @section Panning Inertia Options
  11162. // @option inertia: Boolean = *
  11163. // If enabled, panning of the map will have an inertia effect where
  11164. // the map builds momentum while dragging and continues moving in
  11165. // the same direction for some time. Feels especially nice on touch
  11166. // devices. Enabled by default.
  11167. inertia: true,
  11168. // @option inertiaDeceleration: Number = 3000
  11169. // The rate with which the inertial movement slows down, in pixels/second².
  11170. inertiaDeceleration: 3400, // px/s^2
  11171. // @option inertiaMaxSpeed: Number = Infinity
  11172. // Max speed of the inertial movement, in pixels/second.
  11173. inertiaMaxSpeed: Infinity, // px/s
  11174. // @option easeLinearity: Number = 0.2
  11175. easeLinearity: 0.2,
  11176. // TODO refactor, move to CRS
  11177. // @option worldCopyJump: Boolean = false
  11178. // With this option enabled, the map tracks when you pan to another "copy"
  11179. // of the world and seamlessly jumps to the original one so that all overlays
  11180. // like markers and vector layers are still visible.
  11181. worldCopyJump: false,
  11182. // @option maxBoundsViscosity: Number = 0.0
  11183. // If `maxBounds` is set, this option will control how solid the bounds
  11184. // are when dragging the map around. The default value of `0.0` allows the
  11185. // user to drag outside the bounds at normal speed, higher values will
  11186. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  11187. // solid, preventing the user from dragging outside the bounds.
  11188. maxBoundsViscosity: 0.0
  11189. });
  11190. var Drag = Handler.extend({
  11191. addHooks: function () {
  11192. if (!this._draggable) {
  11193. var map = this._map;
  11194. this._draggable = new Draggable(map._mapPane, map._container);
  11195. this._draggable.on({
  11196. dragstart: this._onDragStart,
  11197. drag: this._onDrag,
  11198. dragend: this._onDragEnd
  11199. }, this);
  11200. this._draggable.on('predrag', this._onPreDragLimit, this);
  11201. if (map.options.worldCopyJump) {
  11202. this._draggable.on('predrag', this._onPreDragWrap, this);
  11203. map.on('zoomend', this._onZoomEnd, this);
  11204. map.whenReady(this._onZoomEnd, this);
  11205. }
  11206. }
  11207. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  11208. this._draggable.enable();
  11209. this._positions = [];
  11210. this._times = [];
  11211. },
  11212. removeHooks: function () {
  11213. removeClass(this._map._container, 'leaflet-grab');
  11214. removeClass(this._map._container, 'leaflet-touch-drag');
  11215. this._draggable.disable();
  11216. },
  11217. moved: function () {
  11218. return this._draggable && this._draggable._moved;
  11219. },
  11220. moving: function () {
  11221. return this._draggable && this._draggable._moving;
  11222. },
  11223. _onDragStart: function () {
  11224. var map = this._map;
  11225. map._stop();
  11226. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  11227. var bounds = toLatLngBounds(this._map.options.maxBounds);
  11228. this._offsetLimit = toBounds(
  11229. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  11230. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  11231. .add(this._map.getSize()));
  11232. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  11233. } else {
  11234. this._offsetLimit = null;
  11235. }
  11236. map
  11237. .fire('movestart')
  11238. .fire('dragstart');
  11239. if (map.options.inertia) {
  11240. this._positions = [];
  11241. this._times = [];
  11242. }
  11243. },
  11244. _onDrag: function (e) {
  11245. if (this._map.options.inertia) {
  11246. var time = this._lastTime = +new Date(),
  11247. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  11248. this._positions.push(pos);
  11249. this._times.push(time);
  11250. this._prunePositions(time);
  11251. }
  11252. this._map
  11253. .fire('move', e)
  11254. .fire('drag', e);
  11255. },
  11256. _prunePositions: function (time) {
  11257. while (this._positions.length > 1 && time - this._times[0] > 50) {
  11258. this._positions.shift();
  11259. this._times.shift();
  11260. }
  11261. },
  11262. _onZoomEnd: function () {
  11263. var pxCenter = this._map.getSize().divideBy(2),
  11264. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  11265. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  11266. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  11267. },
  11268. _viscousLimit: function (value, threshold) {
  11269. return value - (value - threshold) * this._viscosity;
  11270. },
  11271. _onPreDragLimit: function () {
  11272. if (!this._viscosity || !this._offsetLimit) { return; }
  11273. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  11274. var limit = this._offsetLimit;
  11275. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  11276. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  11277. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  11278. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  11279. this._draggable._newPos = this._draggable._startPos.add(offset);
  11280. },
  11281. _onPreDragWrap: function () {
  11282. // TODO refactor to be able to adjust map pane position after zoom
  11283. var worldWidth = this._worldWidth,
  11284. halfWidth = Math.round(worldWidth / 2),
  11285. dx = this._initialWorldOffset,
  11286. x = this._draggable._newPos.x,
  11287. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  11288. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  11289. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  11290. this._draggable._absPos = this._draggable._newPos.clone();
  11291. this._draggable._newPos.x = newX;
  11292. },
  11293. _onDragEnd: function (e) {
  11294. var map = this._map,
  11295. options = map.options,
  11296. noInertia = !options.inertia || e.noInertia || this._times.length < 2;
  11297. map.fire('dragend', e);
  11298. if (noInertia) {
  11299. map.fire('moveend');
  11300. } else {
  11301. this._prunePositions(+new Date());
  11302. var direction = this._lastPos.subtract(this._positions[0]),
  11303. duration = (this._lastTime - this._times[0]) / 1000,
  11304. ease = options.easeLinearity,
  11305. speedVector = direction.multiplyBy(ease / duration),
  11306. speed = speedVector.distanceTo([0, 0]),
  11307. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  11308. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  11309. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  11310. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  11311. if (!offset.x && !offset.y) {
  11312. map.fire('moveend');
  11313. } else {
  11314. offset = map._limitOffset(offset, map.options.maxBounds);
  11315. requestAnimFrame(function () {
  11316. map.panBy(offset, {
  11317. duration: decelerationDuration,
  11318. easeLinearity: ease,
  11319. noMoveStart: true,
  11320. animate: true
  11321. });
  11322. });
  11323. }
  11324. }
  11325. }
  11326. });
  11327. // @section Handlers
  11328. // @property dragging: Handler
  11329. // Map dragging handler (by both mouse and touch).
  11330. Map.addInitHook('addHandler', 'dragging', Drag);
  11331. /*
  11332. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  11333. */
  11334. // @namespace Map
  11335. // @section Keyboard Navigation Options
  11336. Map.mergeOptions({
  11337. // @option keyboard: Boolean = true
  11338. // Makes the map focusable and allows users to navigate the map with keyboard
  11339. // arrows and `+`/`-` keys.
  11340. keyboard: true,
  11341. // @option keyboardPanDelta: Number = 80
  11342. // Amount of pixels to pan when pressing an arrow key.
  11343. keyboardPanDelta: 80
  11344. });
  11345. var Keyboard = Handler.extend({
  11346. keyCodes: {
  11347. left: [37],
  11348. right: [39],
  11349. down: [40],
  11350. up: [38],
  11351. zoomIn: [187, 107, 61, 171],
  11352. zoomOut: [189, 109, 54, 173]
  11353. },
  11354. initialize: function (map) {
  11355. this._map = map;
  11356. this._setPanDelta(map.options.keyboardPanDelta);
  11357. this._setZoomDelta(map.options.zoomDelta);
  11358. },
  11359. addHooks: function () {
  11360. var container = this._map._container;
  11361. // make the container focusable by tabbing
  11362. if (container.tabIndex <= 0) {
  11363. container.tabIndex = '0';
  11364. }
  11365. on(container, {
  11366. focus: this._onFocus,
  11367. blur: this._onBlur,
  11368. mousedown: this._onMouseDown
  11369. }, this);
  11370. this._map.on({
  11371. focus: this._addHooks,
  11372. blur: this._removeHooks
  11373. }, this);
  11374. },
  11375. removeHooks: function () {
  11376. this._removeHooks();
  11377. off(this._map._container, {
  11378. focus: this._onFocus,
  11379. blur: this._onBlur,
  11380. mousedown: this._onMouseDown
  11381. }, this);
  11382. this._map.off({
  11383. focus: this._addHooks,
  11384. blur: this._removeHooks
  11385. }, this);
  11386. },
  11387. _onMouseDown: function () {
  11388. if (this._focused) { return; }
  11389. var body = document.body,
  11390. docEl = document.documentElement,
  11391. top = body.scrollTop || docEl.scrollTop,
  11392. left = body.scrollLeft || docEl.scrollLeft;
  11393. this._map._container.focus();
  11394. window.scrollTo(left, top);
  11395. },
  11396. _onFocus: function () {
  11397. this._focused = true;
  11398. this._map.fire('focus');
  11399. },
  11400. _onBlur: function () {
  11401. this._focused = false;
  11402. this._map.fire('blur');
  11403. },
  11404. _setPanDelta: function (panDelta) {
  11405. var keys = this._panKeys = {},
  11406. codes = this.keyCodes,
  11407. i, len;
  11408. for (i = 0, len = codes.left.length; i < len; i++) {
  11409. keys[codes.left[i]] = [-1 * panDelta, 0];
  11410. }
  11411. for (i = 0, len = codes.right.length; i < len; i++) {
  11412. keys[codes.right[i]] = [panDelta, 0];
  11413. }
  11414. for (i = 0, len = codes.down.length; i < len; i++) {
  11415. keys[codes.down[i]] = [0, panDelta];
  11416. }
  11417. for (i = 0, len = codes.up.length; i < len; i++) {
  11418. keys[codes.up[i]] = [0, -1 * panDelta];
  11419. }
  11420. },
  11421. _setZoomDelta: function (zoomDelta) {
  11422. var keys = this._zoomKeys = {},
  11423. codes = this.keyCodes,
  11424. i, len;
  11425. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  11426. keys[codes.zoomIn[i]] = zoomDelta;
  11427. }
  11428. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  11429. keys[codes.zoomOut[i]] = -zoomDelta;
  11430. }
  11431. },
  11432. _addHooks: function () {
  11433. on(document, 'keydown', this._onKeyDown, this);
  11434. },
  11435. _removeHooks: function () {
  11436. off(document, 'keydown', this._onKeyDown, this);
  11437. },
  11438. _onKeyDown: function (e) {
  11439. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  11440. var key = e.keyCode,
  11441. map = this._map,
  11442. offset;
  11443. if (key in this._panKeys) {
  11444. if (!map._panAnim || !map._panAnim._inProgress) {
  11445. offset = this._panKeys[key];
  11446. if (e.shiftKey) {
  11447. offset = toPoint(offset).multiplyBy(3);
  11448. }
  11449. map.panBy(offset);
  11450. if (map.options.maxBounds) {
  11451. map.panInsideBounds(map.options.maxBounds);
  11452. }
  11453. }
  11454. } else if (key in this._zoomKeys) {
  11455. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  11456. } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
  11457. map.closePopup();
  11458. } else {
  11459. return;
  11460. }
  11461. stop(e);
  11462. }
  11463. });
  11464. // @section Handlers
  11465. // @section Handlers
  11466. // @property keyboard: Handler
  11467. // Keyboard navigation handler.
  11468. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  11469. /*
  11470. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  11471. */
  11472. // @namespace Map
  11473. // @section Interaction Options
  11474. Map.mergeOptions({
  11475. // @section Mouse wheel options
  11476. // @option scrollWheelZoom: Boolean|String = true
  11477. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  11478. // it will zoom to the center of the view regardless of where the mouse was.
  11479. scrollWheelZoom: true,
  11480. // @option wheelDebounceTime: Number = 40
  11481. // Limits the rate at which a wheel can fire (in milliseconds). By default
  11482. // user can't zoom via wheel more often than once per 40 ms.
  11483. wheelDebounceTime: 40,
  11484. // @option wheelPxPerZoomLevel: Number = 60
  11485. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  11486. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  11487. // faster (and vice versa).
  11488. wheelPxPerZoomLevel: 60
  11489. });
  11490. var ScrollWheelZoom = Handler.extend({
  11491. addHooks: function () {
  11492. on(this._map._container, 'wheel', this._onWheelScroll, this);
  11493. this._delta = 0;
  11494. },
  11495. removeHooks: function () {
  11496. off(this._map._container, 'wheel', this._onWheelScroll, this);
  11497. },
  11498. _onWheelScroll: function (e) {
  11499. var delta = getWheelDelta(e);
  11500. var debounce = this._map.options.wheelDebounceTime;
  11501. this._delta += delta;
  11502. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  11503. if (!this._startTime) {
  11504. this._startTime = +new Date();
  11505. }
  11506. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  11507. clearTimeout(this._timer);
  11508. this._timer = setTimeout(bind(this._performZoom, this), left);
  11509. stop(e);
  11510. },
  11511. _performZoom: function () {
  11512. var map = this._map,
  11513. zoom = map.getZoom(),
  11514. snap = this._map.options.zoomSnap || 0;
  11515. map._stop(); // stop panning and fly animations if any
  11516. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  11517. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  11518. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  11519. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  11520. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  11521. this._delta = 0;
  11522. this._startTime = null;
  11523. if (!delta) { return; }
  11524. if (map.options.scrollWheelZoom === 'center') {
  11525. map.setZoom(zoom + delta);
  11526. } else {
  11527. map.setZoomAround(this._lastMousePos, zoom + delta);
  11528. }
  11529. }
  11530. });
  11531. // @section Handlers
  11532. // @property scrollWheelZoom: Handler
  11533. // Scroll wheel zoom handler.
  11534. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  11535. /*
  11536. * L.Map.TapHold is used to simulate `contextmenu` event on long hold,
  11537. * which otherwise is not fired by mobile Safari.
  11538. */
  11539. var tapHoldDelay = 600;
  11540. // @namespace Map
  11541. // @section Interaction Options
  11542. Map.mergeOptions({
  11543. // @section Touch interaction options
  11544. // @option tapHold: Boolean
  11545. // Enables simulation of `contextmenu` event, default is `true` for mobile Safari.
  11546. tapHold: Browser.touchNative && Browser.safari && Browser.mobile,
  11547. // @option tapTolerance: Number = 15
  11548. // The max number of pixels a user can shift his finger during touch
  11549. // for it to be considered a valid tap.
  11550. tapTolerance: 15
  11551. });
  11552. var TapHold = Handler.extend({
  11553. addHooks: function () {
  11554. on(this._map._container, 'touchstart', this._onDown, this);
  11555. },
  11556. removeHooks: function () {
  11557. off(this._map._container, 'touchstart', this._onDown, this);
  11558. },
  11559. _onDown: function (e) {
  11560. clearTimeout(this._holdTimeout);
  11561. if (e.touches.length !== 1) { return; }
  11562. var first = e.touches[0];
  11563. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  11564. this._holdTimeout = setTimeout(bind(function () {
  11565. this._cancel();
  11566. if (!this._isTapValid()) { return; }
  11567. // prevent simulated mouse events https://w3c.github.io/touch-events/#mouse-events
  11568. on(document, 'touchend', preventDefault);
  11569. on(document, 'touchend touchcancel', this._cancelClickPrevent);
  11570. this._simulateEvent('contextmenu', first);
  11571. }, this), tapHoldDelay);
  11572. on(document, 'touchend touchcancel contextmenu', this._cancel, this);
  11573. on(document, 'touchmove', this._onMove, this);
  11574. },
  11575. _cancelClickPrevent: function cancelClickPrevent() {
  11576. off(document, 'touchend', preventDefault);
  11577. off(document, 'touchend touchcancel', cancelClickPrevent);
  11578. },
  11579. _cancel: function () {
  11580. clearTimeout(this._holdTimeout);
  11581. off(document, 'touchend touchcancel contextmenu', this._cancel, this);
  11582. off(document, 'touchmove', this._onMove, this);
  11583. },
  11584. _onMove: function (e) {
  11585. var first = e.touches[0];
  11586. this._newPos = new Point(first.clientX, first.clientY);
  11587. },
  11588. _isTapValid: function () {
  11589. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11590. },
  11591. _simulateEvent: function (type, e) {
  11592. var simulatedEvent = new MouseEvent(type, {
  11593. bubbles: true,
  11594. cancelable: true,
  11595. view: window,
  11596. // detail: 1,
  11597. screenX: e.screenX,
  11598. screenY: e.screenY,
  11599. clientX: e.clientX,
  11600. clientY: e.clientY,
  11601. // button: 2,
  11602. // buttons: 2
  11603. });
  11604. simulatedEvent._simulated = true;
  11605. e.target.dispatchEvent(simulatedEvent);
  11606. }
  11607. });
  11608. // @section Handlers
  11609. // @property tapHold: Handler
  11610. // Long tap handler to simulate `contextmenu` event (useful in mobile Safari).
  11611. Map.addInitHook('addHandler', 'tapHold', TapHold);
  11612. /*
  11613. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11614. */
  11615. // @namespace Map
  11616. // @section Interaction Options
  11617. Map.mergeOptions({
  11618. // @section Touch interaction options
  11619. // @option touchZoom: Boolean|String = *
  11620. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11621. // passed `'center'`, it will zoom to the center of the view regardless of
  11622. // where the touch events (fingers) were. Enabled for touch-capable web
  11623. // browsers.
  11624. touchZoom: Browser.touch,
  11625. // @option bounceAtZoomLimits: Boolean = true
  11626. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11627. // and then bounce back when pinch-zooming.
  11628. bounceAtZoomLimits: true
  11629. });
  11630. var TouchZoom = Handler.extend({
  11631. addHooks: function () {
  11632. addClass(this._map._container, 'leaflet-touch-zoom');
  11633. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11634. },
  11635. removeHooks: function () {
  11636. removeClass(this._map._container, 'leaflet-touch-zoom');
  11637. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11638. },
  11639. _onTouchStart: function (e) {
  11640. var map = this._map;
  11641. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  11642. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11643. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11644. this._centerPoint = map.getSize()._divideBy(2);
  11645. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11646. if (map.options.touchZoom !== 'center') {
  11647. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11648. }
  11649. this._startDist = p1.distanceTo(p2);
  11650. this._startZoom = map.getZoom();
  11651. this._moved = false;
  11652. this._zooming = true;
  11653. map._stop();
  11654. on(document, 'touchmove', this._onTouchMove, this);
  11655. on(document, 'touchend touchcancel', this._onTouchEnd, this);
  11656. preventDefault(e);
  11657. },
  11658. _onTouchMove: function (e) {
  11659. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  11660. var map = this._map,
  11661. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11662. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11663. scale = p1.distanceTo(p2) / this._startDist;
  11664. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11665. if (!map.options.bounceAtZoomLimits && (
  11666. (this._zoom < map.getMinZoom() && scale < 1) ||
  11667. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11668. this._zoom = map._limitZoom(this._zoom);
  11669. }
  11670. if (map.options.touchZoom === 'center') {
  11671. this._center = this._startLatLng;
  11672. if (scale === 1) { return; }
  11673. } else {
  11674. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11675. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11676. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  11677. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11678. }
  11679. if (!this._moved) {
  11680. map._moveStart(true, false);
  11681. this._moved = true;
  11682. }
  11683. cancelAnimFrame(this._animRequest);
  11684. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false}, undefined);
  11685. this._animRequest = requestAnimFrame(moveFn, this, true);
  11686. preventDefault(e);
  11687. },
  11688. _onTouchEnd: function () {
  11689. if (!this._moved || !this._zooming) {
  11690. this._zooming = false;
  11691. return;
  11692. }
  11693. this._zooming = false;
  11694. cancelAnimFrame(this._animRequest);
  11695. off(document, 'touchmove', this._onTouchMove, this);
  11696. off(document, 'touchend touchcancel', this._onTouchEnd, this);
  11697. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11698. if (this._map.options.zoomAnimation) {
  11699. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11700. } else {
  11701. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11702. }
  11703. }
  11704. });
  11705. // @section Handlers
  11706. // @property touchZoom: Handler
  11707. // Touch zoom handler.
  11708. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11709. Map.BoxZoom = BoxZoom;
  11710. Map.DoubleClickZoom = DoubleClickZoom;
  11711. Map.Drag = Drag;
  11712. Map.Keyboard = Keyboard;
  11713. Map.ScrollWheelZoom = ScrollWheelZoom;
  11714. Map.TapHold = TapHold;
  11715. Map.TouchZoom = TouchZoom;
  11716. export { Bounds, Browser, CRS, Canvas, Circle, CircleMarker, Class, Control, DivIcon, DivOverlay, DomEvent, DomUtil, Draggable, Evented, FeatureGroup, GeoJSON, GridLayer, Handler, Icon, ImageOverlay, LatLng, LatLngBounds, Layer, LayerGroup, LineUtil, Map, Marker, Mixin, Path, Point, PolyUtil, Polygon, Polyline, Popup, PosAnimation, index as Projection, Rectangle, Renderer, SVG, SVGOverlay, TileLayer, Tooltip, Transformation, Util, VideoOverlay, bind, toBounds as bounds, canvas, circle, circleMarker, control, divIcon, extend, featureGroup, geoJSON, geoJson, gridLayer, icon, imageOverlay, toLatLng as latLng, toLatLngBounds as latLngBounds, layerGroup, createMap as map, marker, toPoint as point, polygon, polyline, popup, rectangle, setOptions, stamp, svg, svgOverlay, tileLayer, tooltip, toTransformation as transformation, version, videoOverlay };
  11717. //# sourceMappingURL=leaflet-src.esm.js.map