leaflet-src.js 462 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887
  1. /* @preserve
  2. * Leaflet 1.2.0+Detached: 1ac320ba232cb85b73ac81f3d82780c9d07f0d4e.1ac320b, a JS library for interactive maps. http://leafletjs.com
  3. * (c) 2010-2017 Vladimir Agafonkin, (c) 2010-2011 CloudMade
  4. */
  5. (function (global, factory) {
  6. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  7. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  8. (factory((global.L = {})));
  9. }(this, (function (exports) {
  10. 'use strict';
  11. var version = "1.2.0+HEAD.1ac320b";
  12. /*
  13. * @namespace Util
  14. *
  15. * Various utility functions, used by Leaflet internally.
  16. */
  17. var freeze = Object.freeze;
  18. Object.freeze = function (obj) {
  19. return obj;
  20. };
  21. // @function extend(dest: Object, src?: Object): Object
  22. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  23. function extend(dest) {
  24. var i, j, len, src;
  25. for (j = 1, len = arguments.length; j < len; j++) {
  26. src = arguments[j];
  27. for (i in src) {
  28. dest[i] = src[i];
  29. }
  30. }
  31. return dest;
  32. }
  33. // @function create(proto: Object, properties?: Object): Object
  34. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  35. var create = Object.create || (function () {
  36. function F() {
  37. }
  38. return function (proto) {
  39. F.prototype = proto;
  40. return new F();
  41. };
  42. })();
  43. // @function bind(fn: Function, …): Function
  44. // 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).
  45. // Has a `L.bind()` shortcut.
  46. function bind(fn, obj) {
  47. var slice = Array.prototype.slice;
  48. if (fn.bind) {
  49. return fn.bind.apply(fn, slice.call(arguments, 1));
  50. }
  51. var args = slice.call(arguments, 2);
  52. return function () {
  53. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  54. };
  55. }
  56. // @property lastId: Number
  57. // Last unique ID used by [`stamp()`](#util-stamp)
  58. var lastId = 0;
  59. // @function stamp(obj: Object): Number
  60. // Returns the unique ID of an object, assiging it one if it doesn't have it.
  61. function stamp(obj) {
  62. /*eslint-disable */
  63. obj._leaflet_id = obj._leaflet_id || ++lastId;
  64. return obj._leaflet_id;
  65. /*eslint-enable */
  66. }
  67. // @function throttle(fn: Function, time: Number, context: Object): Function
  68. // Returns a function which executes function `fn` with the given scope `context`
  69. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  70. // `fn` will be called no more than one time per given amount of `time`. The arguments
  71. // received by the bound function will be any arguments passed when binding the
  72. // function, followed by any arguments passed when invoking the bound function.
  73. // Has an `L.throttle` shortcut.
  74. function throttle(fn, time, context) {
  75. var lock, args, wrapperFn, later;
  76. later = function () {
  77. // reset lock and call if queued
  78. lock = false;
  79. if (args) {
  80. wrapperFn.apply(context, args);
  81. args = false;
  82. }
  83. };
  84. wrapperFn = function () {
  85. if (lock) {
  86. // called too soon, queue to call later
  87. args = arguments;
  88. } else {
  89. // call and lock until later
  90. fn.apply(context, arguments);
  91. setTimeout(later, time);
  92. lock = true;
  93. }
  94. };
  95. return wrapperFn;
  96. }
  97. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  98. // Returns the number `num` modulo `range` in such a way so it lies within
  99. // `range[0]` and `range[1]`. The returned value will be always smaller than
  100. // `range[1]` unless `includeMax` is set to `true`.
  101. function wrapNum(x, range, includeMax) {
  102. var max = range[1],
  103. min = range[0],
  104. d = max - min;
  105. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  106. }
  107. // @function falseFn(): Function
  108. // Returns a function which always returns `false`.
  109. function falseFn() {
  110. return false;
  111. }
  112. // @function formatNum(num: Number, digits?: Number): Number
  113. // Returns the number `num` rounded to `digits` decimals, or to 5 decimals by default.
  114. function formatNum(num, digits) {
  115. var pow = Math.pow(10, digits || 5);
  116. return Math.round(num * pow) / pow;
  117. }
  118. // @function trim(str: String): String
  119. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  120. function trim(str) {
  121. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  122. }
  123. // @function splitWords(str: String): String[]
  124. // Trims and splits the string on whitespace and returns the array of parts.
  125. function splitWords(str) {
  126. return trim(str).split(/\s+/);
  127. }
  128. // @function setOptions(obj: Object, options: Object): Object
  129. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  130. function setOptions(obj, options) {
  131. if (!obj.hasOwnProperty('options')) {
  132. obj.options = obj.options ? create(obj.options) : {};
  133. }
  134. for (var i in options) {
  135. obj.options[i] = options[i];
  136. }
  137. return obj.options;
  138. }
  139. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  140. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  141. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  142. // be appended at the end. If `uppercase` is `true`, the parameter names will
  143. // be uppercased (e.g. `'?A=foo&B=bar'`)
  144. function getParamString(obj, existingUrl, uppercase) {
  145. var params = [];
  146. for (var i in obj) {
  147. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  148. }
  149. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  150. }
  151. var templateRe = /\{ *([\w_\-]+) *\}/g;
  152. // @function template(str: String, data: Object): String
  153. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  154. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  155. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  156. // data values — they will be evaluated passing `data` as an argument.
  157. function template(str, data) {
  158. return str.replace(templateRe, function (str, key) {
  159. var value = data[key];
  160. if (value === undefined) {
  161. throw new Error('No value provided for variable ' + str);
  162. } else if (typeof value === 'function') {
  163. value = value(data);
  164. }
  165. return value;
  166. });
  167. }
  168. // @function isArray(obj): Boolean
  169. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  170. var isArray = Array.isArray || function (obj) {
  171. return (Object.prototype.toString.call(obj) === '[object Array]');
  172. };
  173. // @function indexOf(array: Array, el: Object): Number
  174. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  175. function indexOf(array, el) {
  176. for (var i = 0; i < array.length; i++) {
  177. if (array[i] === el) {
  178. return i;
  179. }
  180. }
  181. return -1;
  182. }
  183. // @property emptyImageUrl: String
  184. // Data URI string containing a base64-encoded empty GIF image.
  185. // Used as a hack to free memory from unused images on WebKit-powered
  186. // mobile devices (by setting image `src` to this string).
  187. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  188. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  189. function getPrefixed(name) {
  190. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  191. }
  192. var lastTime = 0;
  193. // fallback for IE 7-8
  194. function timeoutDefer(fn) {
  195. var time = +new Date(),
  196. timeToCall = Math.max(0, 16 - (time - lastTime));
  197. lastTime = time + timeToCall;
  198. return window.setTimeout(fn, timeToCall);
  199. }
  200. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  201. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  202. getPrefixed('CancelRequestAnimationFrame') || function (id) {
  203. window.clearTimeout(id);
  204. };
  205. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  206. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  207. // `context` if given. When `immediate` is set, `fn` is called immediately if
  208. // the browser doesn't have native support for
  209. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  210. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  211. function requestAnimFrame(fn, context, immediate) {
  212. if (immediate && requestFn === timeoutDefer) {
  213. fn.call(context);
  214. } else {
  215. return requestFn.call(window, bind(fn, context));
  216. }
  217. }
  218. // @function cancelAnimFrame(id: Number): undefined
  219. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  220. function cancelAnimFrame(id) {
  221. if (id) {
  222. cancelFn.call(window, id);
  223. }
  224. }
  225. var Util = (Object.freeze || Object)({
  226. freeze: freeze,
  227. extend: extend,
  228. create: create,
  229. bind: bind,
  230. lastId: lastId,
  231. stamp: stamp,
  232. throttle: throttle,
  233. wrapNum: wrapNum,
  234. falseFn: falseFn,
  235. formatNum: formatNum,
  236. trim: trim,
  237. splitWords: splitWords,
  238. setOptions: setOptions,
  239. getParamString: getParamString,
  240. template: template,
  241. isArray: isArray,
  242. indexOf: indexOf,
  243. emptyImageUrl: emptyImageUrl,
  244. requestFn: requestFn,
  245. cancelFn: cancelFn,
  246. requestAnimFrame: requestAnimFrame,
  247. cancelAnimFrame: cancelAnimFrame
  248. });
  249. // @class Class
  250. // @aka L.Class
  251. // @section
  252. // @uninheritable
  253. // Thanks to John Resig and Dean Edwards for inspiration!
  254. function Class() {
  255. }
  256. Class.extend = function (props) {
  257. // @function extend(props: Object): Function
  258. // [Extends the current class](#class-inheritance) given the properties to be included.
  259. // Returns a Javascript function that is a class constructor (to be called with `new`).
  260. var NewClass = function () {
  261. // call the constructor
  262. if (this.initialize) {
  263. this.initialize.apply(this, arguments);
  264. }
  265. // call all constructor hooks
  266. this.callInitHooks();
  267. };
  268. var parentProto = NewClass.__super__ = this.prototype;
  269. var proto = create(parentProto);
  270. proto.constructor = NewClass;
  271. NewClass.prototype = proto;
  272. // inherit parent's statics
  273. for (var i in this) {
  274. if (this.hasOwnProperty(i) && i !== 'prototype' && i !== '__super__') {
  275. NewClass[i] = this[i];
  276. }
  277. }
  278. // mix static properties into the class
  279. if (props.statics) {
  280. extend(NewClass, props.statics);
  281. delete props.statics;
  282. }
  283. // mix includes into the prototype
  284. if (props.includes) {
  285. checkDeprecatedMixinEvents(props.includes);
  286. extend.apply(null, [proto].concat(props.includes));
  287. delete props.includes;
  288. }
  289. // merge options
  290. if (proto.options) {
  291. props.options = extend(create(proto.options), props.options);
  292. }
  293. // mix given properties into the prototype
  294. extend(proto, props);
  295. proto._initHooks = [];
  296. // add method for calling all hooks
  297. proto.callInitHooks = function () {
  298. if (this._initHooksCalled) {
  299. return;
  300. }
  301. if (parentProto.callInitHooks) {
  302. parentProto.callInitHooks.call(this);
  303. }
  304. this._initHooksCalled = true;
  305. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  306. proto._initHooks[i].call(this);
  307. }
  308. };
  309. return NewClass;
  310. };
  311. // @function include(properties: Object): this
  312. // [Includes a mixin](#class-includes) into the current class.
  313. Class.include = function (props) {
  314. extend(this.prototype, props);
  315. return this;
  316. };
  317. // @function mergeOptions(options: Object): this
  318. // [Merges `options`](#class-options) into the defaults of the class.
  319. Class.mergeOptions = function (options) {
  320. extend(this.prototype.options, options);
  321. return this;
  322. };
  323. // @function addInitHook(fn: Function): this
  324. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  325. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  326. var args = Array.prototype.slice.call(arguments, 1);
  327. var init = typeof fn === 'function' ? fn : function () {
  328. this[fn].apply(this, args);
  329. };
  330. this.prototype._initHooks = this.prototype._initHooks || [];
  331. this.prototype._initHooks.push(init);
  332. return this;
  333. };
  334. function checkDeprecatedMixinEvents(includes) {
  335. if (!L || !L.Mixin) {
  336. return;
  337. }
  338. includes = isArray(includes) ? includes : [includes];
  339. for (var i = 0; i < includes.length; i++) {
  340. if (includes[i] === L.Mixin.Events) {
  341. console.warn('Deprecated include of L.Mixin.Events: ' +
  342. 'this property will be removed in future releases, ' +
  343. 'please inherit from L.Evented instead.', new Error().stack);
  344. }
  345. }
  346. }
  347. /*
  348. * @class Evented
  349. * @aka L.Evented
  350. * @inherits Class
  351. *
  352. * 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).
  353. *
  354. * @example
  355. *
  356. * ```js
  357. * map.on('click', function(e) {
  358. * alert(e.latlng);
  359. * } );
  360. * ```
  361. *
  362. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  363. *
  364. * ```js
  365. * function onClick(e) { ... }
  366. *
  367. * map.on('click', onClick);
  368. * map.off('click', onClick);
  369. * ```
  370. */
  371. var Events = {
  372. /* @method on(type: String, fn: Function, context?: Object): this
  373. * 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'`).
  374. *
  375. * @alternative
  376. * @method on(eventMap: Object): this
  377. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  378. */
  379. on: function (types, fn, context) {
  380. // types can be a map of types/handlers
  381. if (typeof types === 'object') {
  382. for (var type in types) {
  383. // we don't process space-separated events here for performance;
  384. // it's a hot path since Layer uses the on(obj) syntax
  385. this._on(type, types[type], fn);
  386. }
  387. } else {
  388. // types can be a string of space-separated words
  389. types = splitWords(types);
  390. for (var i = 0, len = types.length; i < len; i++) {
  391. this._on(types[i], fn, context);
  392. }
  393. }
  394. return this;
  395. },
  396. /* @method off(type: String, fn?: Function, context?: Object): this
  397. * 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.
  398. *
  399. * @alternative
  400. * @method off(eventMap: Object): this
  401. * Removes a set of type/listener pairs.
  402. *
  403. * @alternative
  404. * @method off: this
  405. * Removes all listeners to all events on the object.
  406. */
  407. off: function (types, fn, context) {
  408. if (!types) {
  409. // clear all listeners if called without arguments
  410. delete this._events;
  411. } else if (typeof types === 'object') {
  412. for (var type in types) {
  413. this._off(type, types[type], fn);
  414. }
  415. } else {
  416. types = splitWords(types);
  417. for (var i = 0, len = types.length; i < len; i++) {
  418. this._off(types[i], fn, context);
  419. }
  420. }
  421. return this;
  422. },
  423. // attach listener (without syntactic sugar now)
  424. _on: function (type, fn, context) {
  425. this._events = this._events || {};
  426. /* get/init listeners for type */
  427. var typeListeners = this._events[type];
  428. if (!typeListeners) {
  429. typeListeners = [];
  430. this._events[type] = typeListeners;
  431. }
  432. if (context === this) {
  433. // Less memory footprint.
  434. context = undefined;
  435. }
  436. var newListener = {fn: fn, ctx: context},
  437. listeners = typeListeners;
  438. // check if fn already there
  439. for (var i = 0, len = listeners.length; i < len; i++) {
  440. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  441. return;
  442. }
  443. }
  444. listeners.push(newListener);
  445. },
  446. _off: function (type, fn, context) {
  447. var listeners,
  448. i,
  449. len;
  450. if (!this._events) {
  451. return;
  452. }
  453. listeners = this._events[type];
  454. if (!listeners) {
  455. return;
  456. }
  457. if (!fn) {
  458. // Set all removed listeners to noop so they are not called if remove happens in fire
  459. for (i = 0, len = listeners.length; i < len; i++) {
  460. listeners[i].fn = falseFn;
  461. }
  462. // clear all listeners for a type if function isn't specified
  463. delete this._events[type];
  464. return;
  465. }
  466. if (context === this) {
  467. context = undefined;
  468. }
  469. if (listeners) {
  470. // find fn and remove it
  471. for (i = 0, len = listeners.length; i < len; i++) {
  472. var l = listeners[i];
  473. if (l.ctx !== context) {
  474. continue;
  475. }
  476. if (l.fn === fn) {
  477. // set the removed listener to noop so that's not called if remove happens in fire
  478. l.fn = falseFn;
  479. if (this._firingCount) {
  480. /* copy array in case events are being fired */
  481. this._events[type] = listeners = listeners.slice();
  482. }
  483. listeners.splice(i, 1);
  484. return;
  485. }
  486. }
  487. }
  488. },
  489. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  490. // Fires an event of the specified type. You can optionally provide an data
  491. // object — the first argument of the listener function will contain its
  492. // properties. The event can optionally be propagated to event parents.
  493. fire: function (type, data, propagate) {
  494. if (!this.listens(type, propagate)) {
  495. return this;
  496. }
  497. var event = extend({}, data, {type: type, target: this});
  498. if (this._events) {
  499. var listeners = this._events[type];
  500. if (listeners) {
  501. this._firingCount = (this._firingCount + 1) || 1;
  502. for (var i = 0, len = listeners.length; i < len; i++) {
  503. var l = listeners[i];
  504. l.fn.call(l.ctx || this, event);
  505. }
  506. this._firingCount--;
  507. }
  508. }
  509. if (propagate) {
  510. // propagate the event to parents (set with addEventParent)
  511. this._propagateEvent(event);
  512. }
  513. return this;
  514. },
  515. // @method listens(type: String): Boolean
  516. // Returns `true` if a particular event type has any listeners attached to it.
  517. listens: function (type, propagate) {
  518. var listeners = this._events && this._events[type];
  519. if (listeners && listeners.length) {
  520. return true;
  521. }
  522. if (propagate) {
  523. // also check parents for listeners if event propagates
  524. for (var id in this._eventParents) {
  525. if (this._eventParents[id].listens(type, propagate)) {
  526. return true;
  527. }
  528. }
  529. }
  530. return false;
  531. },
  532. // @method once(…): this
  533. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  534. once: function (types, fn, context) {
  535. if (typeof types === 'object') {
  536. for (var type in types) {
  537. this.once(type, types[type], fn);
  538. }
  539. return this;
  540. }
  541. var handler = bind(function () {
  542. this
  543. .off(types, fn, context)
  544. .off(types, handler, context);
  545. }, this);
  546. // add a listener that's executed once and removed after that
  547. return this
  548. .on(types, fn, context)
  549. .on(types, handler, context);
  550. },
  551. // @method addEventParent(obj: Evented): this
  552. // Adds an event parent - an `Evented` that will receive propagated events
  553. addEventParent: function (obj) {
  554. this._eventParents = this._eventParents || {};
  555. this._eventParents[stamp(obj)] = obj;
  556. return this;
  557. },
  558. // @method removeEventParent(obj: Evented): this
  559. // Removes an event parent, so it will stop receiving propagated events
  560. removeEventParent: function (obj) {
  561. if (this._eventParents) {
  562. delete this._eventParents[stamp(obj)];
  563. }
  564. return this;
  565. },
  566. _propagateEvent: function (e) {
  567. for (var id in this._eventParents) {
  568. this._eventParents[id].fire(e.type, extend({layer: e.target}, e), true);
  569. }
  570. }
  571. };
  572. // aliases; we should ditch those eventually
  573. // @method addEventListener(…): this
  574. // Alias to [`on(…)`](#evented-on)
  575. Events.addEventListener = Events.on;
  576. // @method removeEventListener(…): this
  577. // Alias to [`off(…)`](#evented-off)
  578. // @method clearAllEventListeners(…): this
  579. // Alias to [`off()`](#evented-off)
  580. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  581. // @method addOneTimeEventListener(…): this
  582. // Alias to [`once(…)`](#evented-once)
  583. Events.addOneTimeEventListener = Events.once;
  584. // @method fireEvent(…): this
  585. // Alias to [`fire(…)`](#evented-fire)
  586. Events.fireEvent = Events.fire;
  587. // @method hasEventListeners(…): Boolean
  588. // Alias to [`listens(…)`](#evented-listens)
  589. Events.hasEventListeners = Events.listens;
  590. var Evented = Class.extend(Events);
  591. /*
  592. * @class Point
  593. * @aka L.Point
  594. *
  595. * Represents a point with `x` and `y` coordinates in pixels.
  596. *
  597. * @example
  598. *
  599. * ```js
  600. * var point = L.point(200, 300);
  601. * ```
  602. *
  603. * 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:
  604. *
  605. * ```js
  606. * map.panBy([200, 300]);
  607. * map.panBy(L.point(200, 300));
  608. * ```
  609. */
  610. function Point(x, y, round) {
  611. // @property x: Number; The `x` coordinate of the point
  612. this.x = (round ? Math.round(x) : x);
  613. // @property y: Number; The `y` coordinate of the point
  614. this.y = (round ? Math.round(y) : y);
  615. }
  616. Point.prototype = {
  617. // @method clone(): Point
  618. // Returns a copy of the current point.
  619. clone: function () {
  620. return new Point(this.x, this.y);
  621. },
  622. // @method add(otherPoint: Point): Point
  623. // Returns the result of addition of the current and the given points.
  624. add: function (point) {
  625. // non-destructive, returns a new point
  626. return this.clone()._add(toPoint(point));
  627. },
  628. _add: function (point) {
  629. // destructive, used directly for performance in situations where it's safe to modify existing point
  630. this.x += point.x;
  631. this.y += point.y;
  632. return this;
  633. },
  634. // @method subtract(otherPoint: Point): Point
  635. // Returns the result of subtraction of the given point from the current.
  636. subtract: function (point) {
  637. return this.clone()._subtract(toPoint(point));
  638. },
  639. _subtract: function (point) {
  640. this.x -= point.x;
  641. this.y -= point.y;
  642. return this;
  643. },
  644. // @method divideBy(num: Number): Point
  645. // Returns the result of division of the current point by the given number.
  646. divideBy: function (num) {
  647. return this.clone()._divideBy(num);
  648. },
  649. _divideBy: function (num) {
  650. this.x /= num;
  651. this.y /= num;
  652. return this;
  653. },
  654. // @method multiplyBy(num: Number): Point
  655. // Returns the result of multiplication of the current point by the given number.
  656. multiplyBy: function (num) {
  657. return this.clone()._multiplyBy(num);
  658. },
  659. _multiplyBy: function (num) {
  660. this.x *= num;
  661. this.y *= num;
  662. return this;
  663. },
  664. // @method scaleBy(scale: Point): Point
  665. // Multiply each coordinate of the current point by each coordinate of
  666. // `scale`. In linear algebra terms, multiply the point by the
  667. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  668. // defined by `scale`.
  669. scaleBy: function (point) {
  670. return new Point(this.x * point.x, this.y * point.y);
  671. },
  672. // @method unscaleBy(scale: Point): Point
  673. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  674. // each coordinate of `scale`.
  675. unscaleBy: function (point) {
  676. return new Point(this.x / point.x, this.y / point.y);
  677. },
  678. // @method round(): Point
  679. // Returns a copy of the current point with rounded coordinates.
  680. round: function () {
  681. return this.clone()._round();
  682. },
  683. _round: function () {
  684. this.x = Math.round(this.x);
  685. this.y = Math.round(this.y);
  686. return this;
  687. },
  688. // @method floor(): Point
  689. // Returns a copy of the current point with floored coordinates (rounded down).
  690. floor: function () {
  691. return this.clone()._floor();
  692. },
  693. _floor: function () {
  694. this.x = Math.floor(this.x);
  695. this.y = Math.floor(this.y);
  696. return this;
  697. },
  698. // @method ceil(): Point
  699. // Returns a copy of the current point with ceiled coordinates (rounded up).
  700. ceil: function () {
  701. return this.clone()._ceil();
  702. },
  703. _ceil: function () {
  704. this.x = Math.ceil(this.x);
  705. this.y = Math.ceil(this.y);
  706. return this;
  707. },
  708. // @method distanceTo(otherPoint: Point): Number
  709. // Returns the cartesian distance between the current and the given points.
  710. distanceTo: function (point) {
  711. point = toPoint(point);
  712. var x = point.x - this.x,
  713. y = point.y - this.y;
  714. return Math.sqrt(x * x + y * y);
  715. },
  716. // @method equals(otherPoint: Point): Boolean
  717. // Returns `true` if the given point has the same coordinates.
  718. equals: function (point) {
  719. point = toPoint(point);
  720. return point.x === this.x &&
  721. point.y === this.y;
  722. },
  723. // @method contains(otherPoint: Point): Boolean
  724. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  725. contains: function (point) {
  726. point = toPoint(point);
  727. return Math.abs(point.x) <= Math.abs(this.x) &&
  728. Math.abs(point.y) <= Math.abs(this.y);
  729. },
  730. // @method toString(): String
  731. // Returns a string representation of the point for debugging purposes.
  732. toString: function () {
  733. return 'Point(' +
  734. formatNum(this.x) + ', ' +
  735. formatNum(this.y) + ')';
  736. }
  737. };
  738. // @factory L.point(x: Number, y: Number, round?: Boolean)
  739. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  740. // @alternative
  741. // @factory L.point(coords: Number[])
  742. // Expects an array of the form `[x, y]` instead.
  743. // @alternative
  744. // @factory L.point(coords: Object)
  745. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  746. function toPoint(x, y, round) {
  747. if (x instanceof Point) {
  748. return x;
  749. }
  750. if (isArray(x)) {
  751. return new Point(x[0], x[1]);
  752. }
  753. if (x === undefined || x === null) {
  754. return x;
  755. }
  756. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  757. return new Point(x.x, x.y);
  758. }
  759. return new Point(x, y, round);
  760. }
  761. /*
  762. * @class Bounds
  763. * @aka L.Bounds
  764. *
  765. * Represents a rectangular area in pixel coordinates.
  766. *
  767. * @example
  768. *
  769. * ```js
  770. * var p1 = L.point(10, 10),
  771. * p2 = L.point(40, 60),
  772. * bounds = L.bounds(p1, p2);
  773. * ```
  774. *
  775. * 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:
  776. *
  777. * ```js
  778. * otherBounds.intersects([[10, 10], [40, 60]]);
  779. * ```
  780. */
  781. function Bounds(a, b) {
  782. if (!a) {
  783. return;
  784. }
  785. var points = b ? [a, b] : a;
  786. for (var i = 0, len = points.length; i < len; i++) {
  787. this.extend(points[i]);
  788. }
  789. }
  790. Bounds.prototype = {
  791. // @method extend(point: Point): this
  792. // Extends the bounds to contain the given point.
  793. extend: function (point) { // (Point)
  794. point = toPoint(point);
  795. // @property min: Point
  796. // The top left corner of the rectangle.
  797. // @property max: Point
  798. // The bottom right corner of the rectangle.
  799. if (!this.min && !this.max) {
  800. this.min = point.clone();
  801. this.max = point.clone();
  802. } else {
  803. this.min.x = Math.min(point.x, this.min.x);
  804. this.max.x = Math.max(point.x, this.max.x);
  805. this.min.y = Math.min(point.y, this.min.y);
  806. this.max.y = Math.max(point.y, this.max.y);
  807. }
  808. return this;
  809. },
  810. // @method getCenter(round?: Boolean): Point
  811. // Returns the center point of the bounds.
  812. getCenter: function (round) {
  813. return new Point(
  814. (this.min.x + this.max.x) / 2,
  815. (this.min.y + this.max.y) / 2, round);
  816. },
  817. // @method getBottomLeft(): Point
  818. // Returns the bottom-left point of the bounds.
  819. getBottomLeft: function () {
  820. return new Point(this.min.x, this.max.y);
  821. },
  822. // @method getTopRight(): Point
  823. // Returns the top-right point of the bounds.
  824. getTopRight: function () { // -> Point
  825. return new Point(this.max.x, this.min.y);
  826. },
  827. // @method getTopLeft(): Point
  828. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  829. getTopLeft: function () {
  830. return this.min; // left, top
  831. },
  832. // @method getBottomRight(): Point
  833. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  834. getBottomRight: function () {
  835. return this.max; // right, bottom
  836. },
  837. // @method getSize(): Point
  838. // Returns the size of the given bounds
  839. getSize: function () {
  840. return this.max.subtract(this.min);
  841. },
  842. // @method contains(otherBounds: Bounds): Boolean
  843. // Returns `true` if the rectangle contains the given one.
  844. // @alternative
  845. // @method contains(point: Point): Boolean
  846. // Returns `true` if the rectangle contains the given point.
  847. contains: function (obj) {
  848. var min, max;
  849. if (typeof obj[0] === 'number' || obj instanceof Point) {
  850. obj = toPoint(obj);
  851. } else {
  852. obj = toBounds(obj);
  853. }
  854. if (obj instanceof Bounds) {
  855. min = obj.min;
  856. max = obj.max;
  857. } else {
  858. min = max = obj;
  859. }
  860. return (min.x >= this.min.x) &&
  861. (max.x <= this.max.x) &&
  862. (min.y >= this.min.y) &&
  863. (max.y <= this.max.y);
  864. },
  865. // @method intersects(otherBounds: Bounds): Boolean
  866. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  867. // intersect if they have at least one point in common.
  868. intersects: function (bounds) { // (Bounds) -> Boolean
  869. bounds = toBounds(bounds);
  870. var min = this.min,
  871. max = this.max,
  872. min2 = bounds.min,
  873. max2 = bounds.max,
  874. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  875. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  876. return xIntersects && yIntersects;
  877. },
  878. // @method overlaps(otherBounds: Bounds): Boolean
  879. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  880. // overlap if their intersection is an area.
  881. overlaps: function (bounds) { // (Bounds) -> Boolean
  882. bounds = toBounds(bounds);
  883. var min = this.min,
  884. max = this.max,
  885. min2 = bounds.min,
  886. max2 = bounds.max,
  887. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  888. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  889. return xOverlaps && yOverlaps;
  890. },
  891. isValid: function () {
  892. return !!(this.min && this.max);
  893. }
  894. };
  895. // @factory L.bounds(corner1: Point, corner2: Point)
  896. // Creates a Bounds object from two corners coordinate pairs.
  897. // @alternative
  898. // @factory L.bounds(points: Point[])
  899. // Creates a Bounds object from the given array of points.
  900. function toBounds(a, b) {
  901. if (!a || a instanceof Bounds) {
  902. return a;
  903. }
  904. return new Bounds(a, b);
  905. }
  906. /*
  907. * @class LatLngBounds
  908. * @aka L.LatLngBounds
  909. *
  910. * Represents a rectangular geographical area on a map.
  911. *
  912. * @example
  913. *
  914. * ```js
  915. * var corner1 = L.latLng(40.712, -74.227),
  916. * corner2 = L.latLng(40.774, -74.125),
  917. * bounds = L.latLngBounds(corner1, corner2);
  918. * ```
  919. *
  920. * 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:
  921. *
  922. * ```js
  923. * map.fitBounds([
  924. * [40.712, -74.227],
  925. * [40.774, -74.125]
  926. * ]);
  927. * ```
  928. *
  929. * 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.
  930. */
  931. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  932. if (!corner1) {
  933. return;
  934. }
  935. var latlngs = corner2 ? [corner1, corner2] : corner1;
  936. for (var i = 0, len = latlngs.length; i < len; i++) {
  937. this.extend(latlngs[i]);
  938. }
  939. }
  940. LatLngBounds.prototype = {
  941. // @method extend(latlng: LatLng): this
  942. // Extend the bounds to contain the given point
  943. // @alternative
  944. // @method extend(otherBounds: LatLngBounds): this
  945. // Extend the bounds to contain the given bounds
  946. extend: function (obj) {
  947. var sw = this._southWest,
  948. ne = this._northEast,
  949. sw2, ne2;
  950. if (obj instanceof LatLng) {
  951. sw2 = obj;
  952. ne2 = obj;
  953. } else if (obj instanceof LatLngBounds) {
  954. sw2 = obj._southWest;
  955. ne2 = obj._northEast;
  956. if (!sw2 || !ne2) {
  957. return this;
  958. }
  959. } else {
  960. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  961. }
  962. if (!sw && !ne) {
  963. this._southWest = new LatLng(sw2.lat, sw2.lng);
  964. this._northEast = new LatLng(ne2.lat, ne2.lng);
  965. } else {
  966. sw.lat = Math.min(sw2.lat, sw.lat);
  967. sw.lng = Math.min(sw2.lng, sw.lng);
  968. ne.lat = Math.max(ne2.lat, ne.lat);
  969. ne.lng = Math.max(ne2.lng, ne.lng);
  970. }
  971. return this;
  972. },
  973. // @method pad(bufferRatio: Number): LatLngBounds
  974. // Returns bigger bounds created by extending the current bounds by a given percentage in each direction.
  975. pad: function (bufferRatio) {
  976. var sw = this._southWest,
  977. ne = this._northEast,
  978. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  979. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  980. return new LatLngBounds(
  981. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  982. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  983. },
  984. // @method getCenter(): LatLng
  985. // Returns the center point of the bounds.
  986. getCenter: function () {
  987. return new LatLng(
  988. (this._southWest.lat + this._northEast.lat) / 2,
  989. (this._southWest.lng + this._northEast.lng) / 2);
  990. },
  991. // @method getSouthWest(): LatLng
  992. // Returns the south-west point of the bounds.
  993. getSouthWest: function () {
  994. return this._southWest;
  995. },
  996. // @method getNorthEast(): LatLng
  997. // Returns the north-east point of the bounds.
  998. getNorthEast: function () {
  999. return this._northEast;
  1000. },
  1001. // @method getNorthWest(): LatLng
  1002. // Returns the north-west point of the bounds.
  1003. getNorthWest: function () {
  1004. return new LatLng(this.getNorth(), this.getWest());
  1005. },
  1006. // @method getSouthEast(): LatLng
  1007. // Returns the south-east point of the bounds.
  1008. getSouthEast: function () {
  1009. return new LatLng(this.getSouth(), this.getEast());
  1010. },
  1011. // @method getWest(): Number
  1012. // Returns the west longitude of the bounds
  1013. getWest: function () {
  1014. return this._southWest.lng;
  1015. },
  1016. // @method getSouth(): Number
  1017. // Returns the south latitude of the bounds
  1018. getSouth: function () {
  1019. return this._southWest.lat;
  1020. },
  1021. // @method getEast(): Number
  1022. // Returns the east longitude of the bounds
  1023. getEast: function () {
  1024. return this._northEast.lng;
  1025. },
  1026. // @method getNorth(): Number
  1027. // Returns the north latitude of the bounds
  1028. getNorth: function () {
  1029. return this._northEast.lat;
  1030. },
  1031. // @method contains(otherBounds: LatLngBounds): Boolean
  1032. // Returns `true` if the rectangle contains the given one.
  1033. // @alternative
  1034. // @method contains (latlng: LatLng): Boolean
  1035. // Returns `true` if the rectangle contains the given point.
  1036. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1037. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1038. obj = toLatLng(obj);
  1039. } else {
  1040. obj = toLatLngBounds(obj);
  1041. }
  1042. var sw = this._southWest,
  1043. ne = this._northEast,
  1044. sw2, ne2;
  1045. if (obj instanceof LatLngBounds) {
  1046. sw2 = obj.getSouthWest();
  1047. ne2 = obj.getNorthEast();
  1048. } else {
  1049. sw2 = ne2 = obj;
  1050. }
  1051. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1052. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1053. },
  1054. // @method intersects(otherBounds: LatLngBounds): Boolean
  1055. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1056. intersects: function (bounds) {
  1057. bounds = toLatLngBounds(bounds);
  1058. var sw = this._southWest,
  1059. ne = this._northEast,
  1060. sw2 = bounds.getSouthWest(),
  1061. ne2 = bounds.getNorthEast(),
  1062. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1063. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1064. return latIntersects && lngIntersects;
  1065. },
  1066. // @method overlaps(otherBounds: Bounds): Boolean
  1067. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1068. overlaps: function (bounds) {
  1069. bounds = toLatLngBounds(bounds);
  1070. var sw = this._southWest,
  1071. ne = this._northEast,
  1072. sw2 = bounds.getSouthWest(),
  1073. ne2 = bounds.getNorthEast(),
  1074. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1075. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1076. return latOverlaps && lngOverlaps;
  1077. },
  1078. // @method toBBoxString(): String
  1079. // 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.
  1080. toBBoxString: function () {
  1081. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1082. },
  1083. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1084. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overriden by setting `maxMargin` to a small number.
  1085. equals: function (bounds, maxMargin) {
  1086. if (!bounds) {
  1087. return false;
  1088. }
  1089. bounds = toLatLngBounds(bounds);
  1090. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1091. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1092. },
  1093. // @method isValid(): Boolean
  1094. // Returns `true` if the bounds are properly initialized.
  1095. isValid: function () {
  1096. return !!(this._southWest && this._northEast);
  1097. }
  1098. };
  1099. // TODO International date line?
  1100. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1101. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1102. // @alternative
  1103. // @factory L.latLngBounds(latlngs: LatLng[])
  1104. // 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).
  1105. function toLatLngBounds(a, b) {
  1106. if (a instanceof LatLngBounds) {
  1107. return a;
  1108. }
  1109. return new LatLngBounds(a, b);
  1110. }
  1111. /* @class LatLng
  1112. * @aka L.LatLng
  1113. *
  1114. * Represents a geographical point with a certain latitude and longitude.
  1115. *
  1116. * @example
  1117. *
  1118. * ```
  1119. * var latlng = L.latLng(50.5, 30.5);
  1120. * ```
  1121. *
  1122. * 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:
  1123. *
  1124. * ```
  1125. * map.panTo([50, 30]);
  1126. * map.panTo({lon: 30, lat: 50});
  1127. * map.panTo({lat: 50, lng: 30});
  1128. * map.panTo(L.latLng(50, 30));
  1129. * ```
  1130. */
  1131. function LatLng(lat, lng, alt) {
  1132. if (isNaN(lat) || isNaN(lng)) {
  1133. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1134. }
  1135. // @property lat: Number
  1136. // Latitude in degrees
  1137. this.lat = +lat;
  1138. // @property lng: Number
  1139. // Longitude in degrees
  1140. this.lng = +lng;
  1141. // @property alt: Number
  1142. // Altitude in meters (optional)
  1143. if (alt !== undefined) {
  1144. this.alt = +alt;
  1145. }
  1146. }
  1147. LatLng.prototype = {
  1148. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1149. // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overriden by setting `maxMargin` to a small number.
  1150. equals: function (obj, maxMargin) {
  1151. if (!obj) {
  1152. return false;
  1153. }
  1154. obj = toLatLng(obj);
  1155. var margin = Math.max(
  1156. Math.abs(this.lat - obj.lat),
  1157. Math.abs(this.lng - obj.lng));
  1158. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1159. },
  1160. // @method toString(): String
  1161. // Returns a string representation of the point (for debugging purposes).
  1162. toString: function (precision) {
  1163. return 'LatLng(' +
  1164. formatNum(this.lat, precision) + ', ' +
  1165. formatNum(this.lng, precision) + ')';
  1166. },
  1167. // @method distanceTo(otherLatLng: LatLng): Number
  1168. // Returns the distance (in meters) to the given `LatLng` calculated using the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula).
  1169. distanceTo: function (other) {
  1170. return Earth.distance(this, toLatLng(other));
  1171. },
  1172. // @method wrap(): LatLng
  1173. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1174. wrap: function () {
  1175. return Earth.wrapLatLng(this);
  1176. },
  1177. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1178. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1179. toBounds: function (sizeInMeters) {
  1180. var latAccuracy = 180 * sizeInMeters / 40075017,
  1181. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1182. return toLatLngBounds(
  1183. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1184. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1185. },
  1186. clone: function () {
  1187. return new LatLng(this.lat, this.lng, this.alt);
  1188. }
  1189. };
  1190. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1191. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1192. // @alternative
  1193. // @factory L.latLng(coords: Array): LatLng
  1194. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1195. // @alternative
  1196. // @factory L.latLng(coords: Object): LatLng
  1197. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1198. function toLatLng(a, b, c) {
  1199. if (a instanceof LatLng) {
  1200. return a;
  1201. }
  1202. if (isArray(a) && typeof a[0] !== 'object') {
  1203. if (a.length === 3) {
  1204. return new LatLng(a[0], a[1], a[2]);
  1205. }
  1206. if (a.length === 2) {
  1207. return new LatLng(a[0], a[1]);
  1208. }
  1209. return null;
  1210. }
  1211. if (a === undefined || a === null) {
  1212. return a;
  1213. }
  1214. if (typeof a === 'object' && 'lat' in a) {
  1215. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1216. }
  1217. if (b === undefined) {
  1218. return null;
  1219. }
  1220. return new LatLng(a, b, c);
  1221. }
  1222. /*
  1223. * @namespace CRS
  1224. * @crs L.CRS.Base
  1225. * Object that defines coordinate reference systems for projecting
  1226. * geographical points into pixel (screen) coordinates and back (and to
  1227. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1228. * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
  1229. *
  1230. * Leaflet defines the most usual CRSs by default. If you want to use a
  1231. * CRS not defined by default, take a look at the
  1232. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1233. */
  1234. var CRS = {
  1235. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1236. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1237. latLngToPoint: function (latlng, zoom) {
  1238. var projectedPoint = this.projection.project(latlng),
  1239. scale = this.scale(zoom);
  1240. return this.transformation._transform(projectedPoint, scale);
  1241. },
  1242. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1243. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1244. // zoom into geographical coordinates.
  1245. pointToLatLng: function (point, zoom) {
  1246. var scale = this.scale(zoom),
  1247. untransformedPoint = this.transformation.untransform(point, scale);
  1248. return this.projection.unproject(untransformedPoint);
  1249. },
  1250. // @method project(latlng: LatLng): Point
  1251. // Projects geographical coordinates into coordinates in units accepted for
  1252. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1253. project: function (latlng) {
  1254. return this.projection.project(latlng);
  1255. },
  1256. // @method unproject(point: Point): LatLng
  1257. // Given a projected coordinate returns the corresponding LatLng.
  1258. // The inverse of `project`.
  1259. unproject: function (point) {
  1260. return this.projection.unproject(point);
  1261. },
  1262. // @method scale(zoom: Number): Number
  1263. // Returns the scale used when transforming projected coordinates into
  1264. // pixel coordinates for a particular zoom. For example, it returns
  1265. // `256 * 2^zoom` for Mercator-based CRS.
  1266. scale: function (zoom) {
  1267. return 256 * Math.pow(2, zoom);
  1268. },
  1269. // @method zoom(scale: Number): Number
  1270. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1271. // factor of `scale`.
  1272. zoom: function (scale) {
  1273. return Math.log(scale / 256) / Math.LN2;
  1274. },
  1275. // @method getProjectedBounds(zoom: Number): Bounds
  1276. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1277. getProjectedBounds: function (zoom) {
  1278. if (this.infinite) {
  1279. return null;
  1280. }
  1281. var b = this.projection.bounds,
  1282. s = this.scale(zoom),
  1283. min = this.transformation.transform(b.min, s),
  1284. max = this.transformation.transform(b.max, s);
  1285. return new Bounds(min, max);
  1286. },
  1287. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1288. // Returns the distance between two geographical coordinates.
  1289. // @property code: String
  1290. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1291. //
  1292. // @property wrapLng: Number[]
  1293. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1294. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1295. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1296. //
  1297. // @property wrapLat: Number[]
  1298. // Like `wrapLng`, but for the latitude (vertical) axis.
  1299. // wrapLng: [min, max],
  1300. // wrapLat: [min, max],
  1301. // @property infinite: Boolean
  1302. // If true, the coordinate space will be unbounded (infinite in both axes)
  1303. infinite: false,
  1304. // @method wrapLatLng(latlng: LatLng): LatLng
  1305. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1306. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1307. wrapLatLng: function (latlng) {
  1308. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1309. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1310. alt = latlng.alt;
  1311. return new LatLng(lat, lng, alt);
  1312. },
  1313. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1314. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1315. // that its center is within the CRS's bounds.
  1316. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1317. wrapLatLngBounds: function (bounds) {
  1318. var center = bounds.getCenter(),
  1319. newCenter = this.wrapLatLng(center),
  1320. latShift = center.lat - newCenter.lat,
  1321. lngShift = center.lng - newCenter.lng;
  1322. if (latShift === 0 && lngShift === 0) {
  1323. return bounds;
  1324. }
  1325. var sw = bounds.getSouthWest(),
  1326. ne = bounds.getNorthEast(),
  1327. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1328. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1329. return new LatLngBounds(newSw, newNe);
  1330. }
  1331. };
  1332. /*
  1333. * @namespace CRS
  1334. * @crs L.CRS.Earth
  1335. *
  1336. * Serves as the base for CRS that are global such that they cover the earth.
  1337. * Can only be used as the base for other CRS and cannot be used directly,
  1338. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1339. * meters.
  1340. */
  1341. var Earth = extend({}, CRS, {
  1342. wrapLng: [-180, 180],
  1343. // Mean Earth Radius, as recommended for use by
  1344. // the International Union of Geodesy and Geophysics,
  1345. // see http://rosettacode.org/wiki/Haversine_formula
  1346. R: 6371000,
  1347. // distance between two geographical points using spherical law of cosines approximation
  1348. distance: function (latlng1, latlng2) {
  1349. var rad = Math.PI / 180,
  1350. lat1 = latlng1.lat * rad,
  1351. lat2 = latlng2.lat * rad,
  1352. a = Math.sin(lat1) * Math.sin(lat2) +
  1353. Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad);
  1354. return this.R * Math.acos(Math.min(a, 1));
  1355. }
  1356. });
  1357. /*
  1358. * @namespace Projection
  1359. * @projection L.Projection.SphericalMercator
  1360. *
  1361. * Spherical Mercator projection — the most common projection for online maps,
  1362. * used by almost all free and commercial tile providers. Assumes that Earth is
  1363. * a sphere. Used by the `EPSG:3857` CRS.
  1364. */
  1365. var SphericalMercator = {
  1366. R: 6378137,
  1367. MAX_LATITUDE: 85.0511287798,
  1368. project: function (latlng) {
  1369. var d = Math.PI / 180,
  1370. max = this.MAX_LATITUDE,
  1371. lat = Math.max(Math.min(max, latlng.lat), -max),
  1372. sin = Math.sin(lat * d);
  1373. return new Point(
  1374. this.R * latlng.lng * d,
  1375. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1376. },
  1377. unproject: function (point) {
  1378. var d = 180 / Math.PI;
  1379. return new LatLng(
  1380. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1381. point.x * d / this.R);
  1382. },
  1383. bounds: (function () {
  1384. var d = 6378137 * Math.PI;
  1385. return new Bounds([-d, -d], [d, d]);
  1386. })()
  1387. };
  1388. /*
  1389. * @class Transformation
  1390. * @aka L.Transformation
  1391. *
  1392. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1393. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1394. * the reverse. Used by Leaflet in its projections code.
  1395. *
  1396. * @example
  1397. *
  1398. * ```js
  1399. * var transformation = L.transformation(2, 5, -1, 10),
  1400. * p = L.point(1, 2),
  1401. * p2 = transformation.transform(p), // L.point(7, 8)
  1402. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1403. * ```
  1404. */
  1405. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1406. // Creates a `Transformation` object with the given coefficients.
  1407. function Transformation(a, b, c, d) {
  1408. if (isArray(a)) {
  1409. // use array properties
  1410. this._a = a[0];
  1411. this._b = a[1];
  1412. this._c = a[2];
  1413. this._d = a[3];
  1414. return;
  1415. }
  1416. this._a = a;
  1417. this._b = b;
  1418. this._c = c;
  1419. this._d = d;
  1420. }
  1421. Transformation.prototype = {
  1422. // @method transform(point: Point, scale?: Number): Point
  1423. // Returns a transformed point, optionally multiplied by the given scale.
  1424. // Only accepts actual `L.Point` instances, not arrays.
  1425. transform: function (point, scale) { // (Point, Number) -> Point
  1426. return this._transform(point.clone(), scale);
  1427. },
  1428. // destructive transform (faster)
  1429. _transform: function (point, scale) {
  1430. scale = scale || 1;
  1431. point.x = scale * (this._a * point.x + this._b);
  1432. point.y = scale * (this._c * point.y + this._d);
  1433. return point;
  1434. },
  1435. // @method untransform(point: Point, scale?: Number): Point
  1436. // Returns the reverse transformation of the given point, optionally divided
  1437. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1438. untransform: function (point, scale) {
  1439. scale = scale || 1;
  1440. return new Point(
  1441. (point.x / scale - this._b) / this._a,
  1442. (point.y / scale - this._d) / this._c);
  1443. }
  1444. };
  1445. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1446. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1447. // Instantiates a Transformation object with the given coefficients.
  1448. // @alternative
  1449. // @factory L.transformation(coefficients: Array): Transformation
  1450. // Expects an coeficients array of the form
  1451. // `[a: Number, b: Number, c: Number, d: Number]`.
  1452. function toTransformation(a, b, c, d) {
  1453. return new Transformation(a, b, c, d);
  1454. }
  1455. /*
  1456. * @namespace CRS
  1457. * @crs L.CRS.EPSG3857
  1458. *
  1459. * The most common CRS for online maps, used by almost all free and commercial
  1460. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1461. * Map's `crs` option.
  1462. */
  1463. var EPSG3857 = extend({}, Earth, {
  1464. code: 'EPSG:3857',
  1465. projection: SphericalMercator,
  1466. transformation: (function () {
  1467. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1468. return toTransformation(scale, 0.5, -scale, 0.5);
  1469. }())
  1470. });
  1471. var EPSG900913 = extend({}, EPSG3857, {
  1472. code: 'EPSG:900913'
  1473. });
  1474. // @namespace SVG; @section
  1475. // There are several static functions which can be called without instantiating L.SVG:
  1476. // @function create(name: String): SVGElement
  1477. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1478. // corresponding to the class name passed. For example, using 'line' will return
  1479. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1480. function svgCreate(name) {
  1481. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1482. }
  1483. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1484. // Generates a SVG path string for multiple rings, with each ring turning
  1485. // into "M..L..L.." instructions
  1486. function pointsToPath(rings, closed) {
  1487. var str = '',
  1488. i, j, len, len2, points, p;
  1489. for (i = 0, len = rings.length; i < len; i++) {
  1490. points = rings[i];
  1491. for (j = 0, len2 = points.length; j < len2; j++) {
  1492. p = points[j];
  1493. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1494. }
  1495. // closes the ring for polygons; "x" is VML syntax
  1496. str += closed ? (svg ? 'z' : 'x') : '';
  1497. }
  1498. // SVG complains about empty path strings
  1499. return str || 'M0 0';
  1500. }
  1501. /*
  1502. * @namespace Browser
  1503. * @aka L.Browser
  1504. *
  1505. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1506. *
  1507. * @example
  1508. *
  1509. * ```js
  1510. * if (L.Browser.ielt9) {
  1511. * alert('Upgrade your browser, dude!');
  1512. * }
  1513. * ```
  1514. */
  1515. var style$1 = document.documentElement.style;
  1516. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1517. var ie = 'ActiveXObject' in window;
  1518. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1519. var ielt9 = ie && !document.addEventListener;
  1520. // @property edge: Boolean; `true` for the Edge web browser.
  1521. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1522. // @property webkit: Boolean;
  1523. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1524. var webkit = userAgentContains('webkit');
  1525. // @property android: Boolean
  1526. // `true` for any browser running on an Android platform.
  1527. var android = userAgentContains('android');
  1528. // @property android23: Boolean; `true` for browsers running on Android 2 or Android 3.
  1529. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1530. // @property opera: Boolean; `true` for the Opera browser
  1531. var opera = !!window.opera;
  1532. // @property chrome: Boolean; `true` for the Chrome browser.
  1533. var chrome = userAgentContains('chrome');
  1534. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1535. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1536. // @property safari: Boolean; `true` for the Safari browser.
  1537. var safari = !chrome && userAgentContains('safari');
  1538. var phantom = userAgentContains('phantom');
  1539. // @property opera12: Boolean
  1540. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1541. var opera12 = 'OTransition' in style$1;
  1542. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1543. var win = navigator.platform.indexOf('Win') === 0;
  1544. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1545. var ie3d = ie && ('transition' in style$1);
  1546. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1547. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1548. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1549. var gecko3d = 'MozPerspective' in style$1;
  1550. // @property any3d: Boolean
  1551. // `true` for all browsers supporting CSS transforms.
  1552. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1553. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1554. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1555. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1556. var mobileWebkit = mobile && webkit;
  1557. // @property mobileWebkit3d: Boolean
  1558. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1559. var mobileWebkit3d = mobile && webkit3d;
  1560. // @property msPointer: Boolean
  1561. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1562. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1563. // @property pointer: Boolean
  1564. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1565. var pointer = !!(window.PointerEvent || msPointer);
  1566. // @property touch: Boolean
  1567. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1568. // This does not necessarily mean that the browser is running in a computer with
  1569. // a touchscreen, it only means that the browser is capable of understanding
  1570. // touch events.
  1571. var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
  1572. (window.DocumentTouch && document instanceof window.DocumentTouch));
  1573. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1574. var mobileOpera = mobile && opera;
  1575. // @property mobileGecko: Boolean
  1576. // `true` for gecko-based browsers running in a mobile device.
  1577. var mobileGecko = mobile && gecko;
  1578. // @property retina: Boolean
  1579. // `true` for browsers on a high-resolution "retina" screen.
  1580. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1581. // @property canvas: Boolean
  1582. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1583. var canvas = (function () {
  1584. return !!document.createElement('canvas').getContext;
  1585. }());
  1586. // @property svg: Boolean
  1587. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1588. var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1589. // @property vml: Boolean
  1590. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1591. var vml = !svg && (function () {
  1592. try {
  1593. var div = document.createElement('div');
  1594. div.innerHTML = '<v:shape adj="1"/>';
  1595. var shape = div.firstChild;
  1596. shape.style.behavior = 'url(#default#VML)';
  1597. return shape && (typeof shape.adj === 'object');
  1598. } catch (e) {
  1599. return false;
  1600. }
  1601. }());
  1602. function userAgentContains(str) {
  1603. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1604. }
  1605. var Browser = (Object.freeze || Object)({
  1606. ie: ie,
  1607. ielt9: ielt9,
  1608. edge: edge,
  1609. webkit: webkit,
  1610. android: android,
  1611. android23: android23,
  1612. opera: opera,
  1613. chrome: chrome,
  1614. gecko: gecko,
  1615. safari: safari,
  1616. phantom: phantom,
  1617. opera12: opera12,
  1618. win: win,
  1619. ie3d: ie3d,
  1620. webkit3d: webkit3d,
  1621. gecko3d: gecko3d,
  1622. any3d: any3d,
  1623. mobile: mobile,
  1624. mobileWebkit: mobileWebkit,
  1625. mobileWebkit3d: mobileWebkit3d,
  1626. msPointer: msPointer,
  1627. pointer: pointer,
  1628. touch: touch,
  1629. mobileOpera: mobileOpera,
  1630. mobileGecko: mobileGecko,
  1631. retina: retina,
  1632. canvas: canvas,
  1633. svg: svg,
  1634. vml: vml
  1635. });
  1636. /*
  1637. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1638. */
  1639. var POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';
  1640. var POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';
  1641. var POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';
  1642. var POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';
  1643. var TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION'];
  1644. var _pointers = {};
  1645. var _pointerDocListener = false;
  1646. // DomEvent.DoubleTap needs to know about this
  1647. var _pointersCount = 0;
  1648. // Provides a touch events wrapper for (ms)pointer events.
  1649. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1650. function addPointerListener(obj, type, handler, id) {
  1651. if (type === 'touchstart') {
  1652. _addPointerStart(obj, handler, id);
  1653. } else if (type === 'touchmove') {
  1654. _addPointerMove(obj, handler, id);
  1655. } else if (type === 'touchend') {
  1656. _addPointerEnd(obj, handler, id);
  1657. }
  1658. return this;
  1659. }
  1660. function removePointerListener(obj, type, id) {
  1661. var handler = obj['_leaflet_' + type + id];
  1662. if (type === 'touchstart') {
  1663. obj.removeEventListener(POINTER_DOWN, handler, false);
  1664. } else if (type === 'touchmove') {
  1665. obj.removeEventListener(POINTER_MOVE, handler, false);
  1666. } else if (type === 'touchend') {
  1667. obj.removeEventListener(POINTER_UP, handler, false);
  1668. obj.removeEventListener(POINTER_CANCEL, handler, false);
  1669. }
  1670. return this;
  1671. }
  1672. function _addPointerStart(obj, handler, id) {
  1673. var onDown = bind(function (e) {
  1674. if (e.pointerType !== 'mouse' && e.pointerType !== e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
  1675. // In IE11, some touch events needs to fire for form controls, or
  1676. // the controls will stop working. We keep a whitelist of tag names that
  1677. // need these events. For other target tags, we prevent default on the event.
  1678. if (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
  1679. preventDefault(e);
  1680. } else {
  1681. return;
  1682. }
  1683. }
  1684. _handlePointer(e, handler);
  1685. });
  1686. obj['_leaflet_touchstart' + id] = onDown;
  1687. obj.addEventListener(POINTER_DOWN, onDown, false);
  1688. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1689. if (!_pointerDocListener) {
  1690. // we listen documentElement as any drags that end by moving the touch off the screen get fired there
  1691. document.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1692. document.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1693. document.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true);
  1694. document.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1695. _pointerDocListener = true;
  1696. }
  1697. }
  1698. function _globalPointerDown(e) {
  1699. _pointers[e.pointerId] = e;
  1700. _pointersCount++;
  1701. }
  1702. function _globalPointerMove(e) {
  1703. if (_pointers[e.pointerId]) {
  1704. _pointers[e.pointerId] = e;
  1705. }
  1706. }
  1707. function _globalPointerUp(e) {
  1708. delete _pointers[e.pointerId];
  1709. _pointersCount--;
  1710. }
  1711. function _handlePointer(e, handler) {
  1712. e.touches = [];
  1713. for (var i in _pointers) {
  1714. e.touches.push(_pointers[i]);
  1715. }
  1716. e.changedTouches = [e];
  1717. handler(e);
  1718. }
  1719. function _addPointerMove(obj, handler, id) {
  1720. var onMove = function (e) {
  1721. // don't fire touch moves when mouse isn't down
  1722. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) {
  1723. return;
  1724. }
  1725. _handlePointer(e, handler);
  1726. };
  1727. obj['_leaflet_touchmove' + id] = onMove;
  1728. obj.addEventListener(POINTER_MOVE, onMove, false);
  1729. }
  1730. function _addPointerEnd(obj, handler, id) {
  1731. var onUp = function (e) {
  1732. _handlePointer(e, handler);
  1733. };
  1734. obj['_leaflet_touchend' + id] = onUp;
  1735. obj.addEventListener(POINTER_UP, onUp, false);
  1736. obj.addEventListener(POINTER_CANCEL, onUp, false);
  1737. }
  1738. /*
  1739. * Extends the event handling code with double tap support for mobile browsers.
  1740. */
  1741. var _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';
  1742. var _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';
  1743. var _pre = '_leaflet_';
  1744. // inspired by Zepto touch code by Thomas Fuchs
  1745. function addDoubleTapListener(obj, handler, id) {
  1746. var last, touch$$1,
  1747. doubleTap = false,
  1748. delay = 250;
  1749. function onTouchStart(e) {
  1750. var count;
  1751. if (pointer) {
  1752. if ((!edge) || e.pointerType === 'mouse') {
  1753. return;
  1754. }
  1755. count = _pointersCount;
  1756. } else {
  1757. count = e.touches.length;
  1758. }
  1759. if (count > 1) {
  1760. return;
  1761. }
  1762. var now = Date.now(),
  1763. delta = now - (last || now);
  1764. touch$$1 = e.touches ? e.touches[0] : e;
  1765. doubleTap = (delta > 0 && delta <= delay);
  1766. last = now;
  1767. }
  1768. function onTouchEnd(e) {
  1769. if (doubleTap && !touch$$1.cancelBubble) {
  1770. if (pointer) {
  1771. if ((!edge) || e.pointerType === 'mouse') {
  1772. return;
  1773. }
  1774. // work around .type being readonly with MSPointer* events
  1775. var newTouch = {},
  1776. prop, i;
  1777. for (i in touch$$1) {
  1778. prop = touch$$1[i];
  1779. newTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;
  1780. }
  1781. touch$$1 = newTouch;
  1782. }
  1783. touch$$1.type = 'dblclick';
  1784. handler(touch$$1);
  1785. last = null;
  1786. }
  1787. }
  1788. obj[_pre + _touchstart + id] = onTouchStart;
  1789. obj[_pre + _touchend + id] = onTouchEnd;
  1790. obj[_pre + 'dblclick' + id] = handler;
  1791. obj.addEventListener(_touchstart, onTouchStart, false);
  1792. obj.addEventListener(_touchend, onTouchEnd, false);
  1793. // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
  1794. // the browser doesn't fire touchend/pointerup events but does fire
  1795. // native dblclicks. See #4127.
  1796. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
  1797. obj.addEventListener('dblclick', handler, false);
  1798. return this;
  1799. }
  1800. function removeDoubleTapListener(obj, id) {
  1801. var touchstart = obj[_pre + _touchstart + id],
  1802. touchend = obj[_pre + _touchend + id],
  1803. dblclick = obj[_pre + 'dblclick' + id];
  1804. obj.removeEventListener(_touchstart, touchstart, false);
  1805. obj.removeEventListener(_touchend, touchend, false);
  1806. if (!edge) {
  1807. obj.removeEventListener('dblclick', dblclick, false);
  1808. }
  1809. return this;
  1810. }
  1811. /*
  1812. * @namespace DomEvent
  1813. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  1814. */
  1815. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  1816. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  1817. // Adds a listener function (`fn`) to a particular DOM event type of the
  1818. // element `el`. You can optionally specify the context of the listener
  1819. // (object the `this` keyword will point to). You can also pass several
  1820. // space-separated types (e.g. `'click dblclick'`).
  1821. // @alternative
  1822. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  1823. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  1824. function on(obj, types, fn, context) {
  1825. if (typeof types === 'object') {
  1826. for (var type in types) {
  1827. addOne(obj, type, types[type], fn);
  1828. }
  1829. } else {
  1830. types = splitWords(types);
  1831. for (var i = 0, len = types.length; i < len; i++) {
  1832. addOne(obj, types[i], fn, context);
  1833. }
  1834. }
  1835. return this;
  1836. }
  1837. var eventsKey = '_leaflet_events';
  1838. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  1839. // Removes a previously added listener function. If no function is specified,
  1840. // it will remove all the listeners of that particular DOM event from the element.
  1841. // Note that if you passed a custom context to on, you must pass the same
  1842. // context to `off` in order to remove the listener.
  1843. // @alternative
  1844. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  1845. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  1846. // @alternative
  1847. // @function off(el: HTMLElement): this
  1848. // Removes all known event listeners
  1849. function off(obj, types, fn, context) {
  1850. if (typeof types === 'object') {
  1851. for (var type in types) {
  1852. removeOne(obj, type, types[type], fn);
  1853. }
  1854. } else if (types) {
  1855. types = splitWords(types);
  1856. for (var i = 0, len = types.length; i < len; i++) {
  1857. removeOne(obj, types[i], fn, context);
  1858. }
  1859. } else {
  1860. for (var j in obj[eventsKey]) {
  1861. removeOne(obj, j, obj[eventsKey][j]);
  1862. }
  1863. delete obj[eventsKey];
  1864. }
  1865. return this;
  1866. }
  1867. function addOne(obj, type, fn, context) {
  1868. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  1869. if (obj[eventsKey] && obj[eventsKey][id]) {
  1870. return this;
  1871. }
  1872. var handler = function (e) {
  1873. return fn.call(context || obj, e || window.event);
  1874. };
  1875. var originalHandler = handler;
  1876. if (pointer && type.indexOf('touch') === 0) {
  1877. // Needs DomEvent.Pointer.js
  1878. addPointerListener(obj, type, handler, id);
  1879. } else if (touch && (type === 'dblclick') && addDoubleTapListener &&
  1880. !(pointer && chrome)) {
  1881. // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener
  1882. // See #5180
  1883. addDoubleTapListener(obj, handler, id);
  1884. } else if ('addEventListener' in obj) {
  1885. if (type === 'mousewheel') {
  1886. obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  1887. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  1888. handler = function (e) {
  1889. e = e || window.event;
  1890. if (isExternalTarget(obj, e)) {
  1891. originalHandler(e);
  1892. }
  1893. };
  1894. obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
  1895. } else {
  1896. if (type === 'click' && android) {
  1897. handler = function (e) {
  1898. filterClick(e, originalHandler);
  1899. };
  1900. }
  1901. obj.addEventListener(type, handler, false);
  1902. }
  1903. } else if ('attachEvent' in obj) {
  1904. obj.attachEvent('on' + type, handler);
  1905. }
  1906. obj[eventsKey] = obj[eventsKey] || {};
  1907. obj[eventsKey][id] = handler;
  1908. }
  1909. function removeOne(obj, type, fn, context) {
  1910. var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),
  1911. handler = obj[eventsKey] && obj[eventsKey][id];
  1912. if (!handler) {
  1913. return this;
  1914. }
  1915. if (pointer && type.indexOf('touch') === 0) {
  1916. removePointerListener(obj, type, id);
  1917. } else if (touch && (type === 'dblclick') && removeDoubleTapListener) {
  1918. removeDoubleTapListener(obj, id);
  1919. } else if ('removeEventListener' in obj) {
  1920. if (type === 'mousewheel') {
  1921. obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  1922. } else {
  1923. obj.removeEventListener(
  1924. type === 'mouseenter' ? 'mouseover' :
  1925. type === 'mouseleave' ? 'mouseout' : type, handler, false);
  1926. }
  1927. } else if ('detachEvent' in obj) {
  1928. obj.detachEvent('on' + type, handler);
  1929. }
  1930. obj[eventsKey][id] = null;
  1931. }
  1932. // @function stopPropagation(ev: DOMEvent): this
  1933. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  1934. // ```js
  1935. // L.DomEvent.on(div, 'click', function (ev) {
  1936. // L.DomEvent.stopPropagation(ev);
  1937. // });
  1938. // ```
  1939. function stopPropagation(e) {
  1940. if (e.stopPropagation) {
  1941. e.stopPropagation();
  1942. } else if (e.originalEvent) { // In case of Leaflet event.
  1943. e.originalEvent._stopped = true;
  1944. } else {
  1945. e.cancelBubble = true;
  1946. }
  1947. skipped(e);
  1948. return this;
  1949. }
  1950. // @function disableScrollPropagation(el: HTMLElement): this
  1951. // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
  1952. function disableScrollPropagation(el) {
  1953. addOne(el, 'mousewheel', stopPropagation);
  1954. return this;
  1955. }
  1956. // @function disableClickPropagation(el: HTMLElement): this
  1957. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  1958. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  1959. function disableClickPropagation(el) {
  1960. on(el, 'mousedown touchstart dblclick', stopPropagation);
  1961. addOne(el, 'click', fakeStop);
  1962. return this;
  1963. }
  1964. // @function preventDefault(ev: DOMEvent): this
  1965. // Prevents the default action of the DOM Event `ev` from happening (such as
  1966. // following a link in the href of the a element, or doing a POST request
  1967. // with page reload when a `<form>` is submitted).
  1968. // Use it inside listener functions.
  1969. function preventDefault(e) {
  1970. if (e.preventDefault) {
  1971. e.preventDefault();
  1972. } else {
  1973. e.returnValue = false;
  1974. }
  1975. return this;
  1976. }
  1977. // @function stop(ev): this
  1978. // Does `stopPropagation` and `preventDefault` at the same time.
  1979. function stop(e) {
  1980. preventDefault(e);
  1981. stopPropagation(e);
  1982. return this;
  1983. }
  1984. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  1985. // Gets normalized mouse position from a DOM event relative to the
  1986. // `container` or to the whole page if not specified.
  1987. function getMousePosition(e, container) {
  1988. if (!container) {
  1989. return new Point(e.clientX, e.clientY);
  1990. }
  1991. var rect = container.getBoundingClientRect();
  1992. return new Point(
  1993. e.clientX - rect.left - container.clientLeft,
  1994. e.clientY - rect.top - container.clientTop);
  1995. }
  1996. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  1997. // and Firefox scrolls device pixels, not CSS pixels
  1998. var wheelPxFactor =
  1999. (win && chrome) ? 2 * window.devicePixelRatio :
  2000. gecko ? window.devicePixelRatio : 1;
  2001. // @function getWheelDelta(ev: DOMEvent): Number
  2002. // Gets normalized wheel delta from a mousewheel DOM event, in vertical
  2003. // pixels scrolled (negative if scrolling down).
  2004. // Events from pointing devices without precise scrolling are mapped to
  2005. // a best guess of 60 pixels.
  2006. function getWheelDelta(e) {
  2007. return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2008. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2009. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2010. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2011. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2012. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2013. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2014. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2015. 0;
  2016. }
  2017. var skipEvents = {};
  2018. function fakeStop(e) {
  2019. // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)
  2020. skipEvents[e.type] = true;
  2021. }
  2022. function skipped(e) {
  2023. var events = skipEvents[e.type];
  2024. // reset when checking, as it's only used in map container and propagates outside of the map
  2025. skipEvents[e.type] = false;
  2026. return events;
  2027. }
  2028. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2029. function isExternalTarget(el, e) {
  2030. var related = e.relatedTarget;
  2031. if (!related) {
  2032. return true;
  2033. }
  2034. try {
  2035. while (related && (related !== el)) {
  2036. related = related.parentNode;
  2037. }
  2038. } catch (err) {
  2039. return false;
  2040. }
  2041. return (related !== el);
  2042. }
  2043. var lastClick;
  2044. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  2045. function filterClick(e, handler) {
  2046. var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
  2047. elapsed = lastClick && (timeStamp - lastClick);
  2048. // are they closer together than 500ms yet more than 100ms?
  2049. // Android typically triggers them ~300ms apart while multiple listeners
  2050. // on the same event should be triggered far faster;
  2051. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  2052. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  2053. stop(e);
  2054. return;
  2055. }
  2056. lastClick = timeStamp;
  2057. handler(e);
  2058. }
  2059. var DomEvent = (Object.freeze || Object)({
  2060. on: on,
  2061. off: off,
  2062. stopPropagation: stopPropagation,
  2063. disableScrollPropagation: disableScrollPropagation,
  2064. disableClickPropagation: disableClickPropagation,
  2065. preventDefault: preventDefault,
  2066. stop: stop,
  2067. getMousePosition: getMousePosition,
  2068. getWheelDelta: getWheelDelta,
  2069. fakeStop: fakeStop,
  2070. skipped: skipped,
  2071. isExternalTarget: isExternalTarget,
  2072. addListener: on,
  2073. removeListener: off
  2074. });
  2075. /*
  2076. * @namespace DomUtil
  2077. *
  2078. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  2079. * tree, used by Leaflet internally.
  2080. *
  2081. * Most functions expecting or returning a `HTMLElement` also work for
  2082. * SVG elements. The only difference is that classes refer to CSS classes
  2083. * in HTML and SVG classes in SVG.
  2084. */
  2085. // @property TRANSFORM: String
  2086. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  2087. var TRANSFORM = testProp(
  2088. ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  2089. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  2090. // the same for the transitionend event, in particular the Android 4.1 stock browser
  2091. // @property TRANSITION: String
  2092. // Vendor-prefixed transition style name.
  2093. var TRANSITION = testProp(
  2094. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  2095. // @property TRANSITION_END: String
  2096. // Vendor-prefixed transitionend event name.
  2097. var TRANSITION_END =
  2098. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  2099. // @function get(id: String|HTMLElement): HTMLElement
  2100. // Returns an element given its DOM id, or returns the element itself
  2101. // if it was passed directly.
  2102. function get(id) {
  2103. return typeof id === 'string' ? document.getElementById(id) : id;
  2104. }
  2105. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  2106. // Returns the value for a certain style attribute on an element,
  2107. // including computed values or values set through CSS.
  2108. function getStyle(el, style) {
  2109. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  2110. if ((!value || value === 'auto') && document.defaultView) {
  2111. var css = document.defaultView.getComputedStyle(el, null);
  2112. value = css ? css[style] : null;
  2113. }
  2114. return value === 'auto' ? null : value;
  2115. }
  2116. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  2117. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  2118. function create$1(tagName, className, container) {
  2119. var el = document.createElement(tagName);
  2120. el.className = className || '';
  2121. if (container) {
  2122. container.appendChild(el);
  2123. }
  2124. return el;
  2125. }
  2126. // @function remove(el: HTMLElement)
  2127. // Removes `el` from its parent element
  2128. function remove(el) {
  2129. var parent = el.parentNode;
  2130. if (parent) {
  2131. parent.removeChild(el);
  2132. }
  2133. }
  2134. // @function empty(el: HTMLElement)
  2135. // Removes all of `el`'s children elements from `el`
  2136. function empty(el) {
  2137. while (el.firstChild) {
  2138. el.removeChild(el.firstChild);
  2139. }
  2140. }
  2141. // @function toFront(el: HTMLElement)
  2142. // Makes `el` the last child of its parent, so it renders in front of the other children.
  2143. function toFront(el) {
  2144. var parent = el.parentNode;
  2145. if (parent.lastChild !== el) {
  2146. parent.appendChild(el);
  2147. }
  2148. }
  2149. // @function toBack(el: HTMLElement)
  2150. // Makes `el` the first child of its parent, so it renders behind the other children.
  2151. function toBack(el) {
  2152. var parent = el.parentNode;
  2153. if (parent.firstChild !== el) {
  2154. parent.insertBefore(el, parent.firstChild);
  2155. }
  2156. }
  2157. // @function hasClass(el: HTMLElement, name: String): Boolean
  2158. // Returns `true` if the element's class attribute contains `name`.
  2159. function hasClass(el, name) {
  2160. if (el.classList !== undefined) {
  2161. return el.classList.contains(name);
  2162. }
  2163. var className = getClass(el);
  2164. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  2165. }
  2166. // @function addClass(el: HTMLElement, name: String)
  2167. // Adds `name` to the element's class attribute.
  2168. function addClass(el, name) {
  2169. if (el.classList !== undefined) {
  2170. var classes = splitWords(name);
  2171. for (var i = 0, len = classes.length; i < len; i++) {
  2172. el.classList.add(classes[i]);
  2173. }
  2174. } else if (!hasClass(el, name)) {
  2175. var className = getClass(el);
  2176. setClass(el, (className ? className + ' ' : '') + name);
  2177. }
  2178. }
  2179. // @function removeClass(el: HTMLElement, name: String)
  2180. // Removes `name` from the element's class attribute.
  2181. function removeClass(el, name) {
  2182. if (el.classList !== undefined) {
  2183. el.classList.remove(name);
  2184. } else {
  2185. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  2186. }
  2187. }
  2188. // @function setClass(el: HTMLElement, name: String)
  2189. // Sets the element's class.
  2190. function setClass(el, name) {
  2191. if (el.className.baseVal === undefined) {
  2192. el.className = name;
  2193. } else {
  2194. // in case of SVG element
  2195. el.className.baseVal = name;
  2196. }
  2197. }
  2198. // @function getClass(el: HTMLElement): String
  2199. // Returns the element's class.
  2200. function getClass(el) {
  2201. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  2202. }
  2203. // @function setOpacity(el: HTMLElement, opacity: Number)
  2204. // Set the opacity of an element (including old IE support).
  2205. // `opacity` must be a number from `0` to `1`.
  2206. function setOpacity(el, value) {
  2207. if ('opacity' in el.style) {
  2208. el.style.opacity = value;
  2209. } else if ('filter' in el.style) {
  2210. _setOpacityIE(el, value);
  2211. }
  2212. }
  2213. function _setOpacityIE(el, value) {
  2214. var filter = false,
  2215. filterName = 'DXImageTransform.Microsoft.Alpha';
  2216. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  2217. try {
  2218. filter = el.filters.item(filterName);
  2219. } catch (e) {
  2220. // don't set opacity to 1 if we haven't already set an opacity,
  2221. // it isn't needed and breaks transparent pngs.
  2222. if (value === 1) {
  2223. return;
  2224. }
  2225. }
  2226. value = Math.round(value * 100);
  2227. if (filter) {
  2228. filter.Enabled = (value !== 100);
  2229. filter.Opacity = value;
  2230. } else {
  2231. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  2232. }
  2233. }
  2234. // @function testProp(props: String[]): String|false
  2235. // Goes through the array of style names and returns the first name
  2236. // that is a valid style name for an element. If no such name is found,
  2237. // it returns false. Useful for vendor-prefixed styles like `transform`.
  2238. function testProp(props) {
  2239. var style = document.documentElement.style;
  2240. for (var i = 0; i < props.length; i++) {
  2241. if (props[i] in style) {
  2242. return props[i];
  2243. }
  2244. }
  2245. return false;
  2246. }
  2247. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  2248. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  2249. // and optionally scaled by `scale`. Does not have an effect if the
  2250. // browser doesn't support 3D CSS transforms.
  2251. function setTransform(el, offset, scale) {
  2252. var pos = offset || new Point(0, 0);
  2253. el.style[TRANSFORM] =
  2254. (ie3d ?
  2255. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2256. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2257. (scale ? ' scale(' + scale + ')' : '');
  2258. }
  2259. // @function setPosition(el: HTMLElement, position: Point)
  2260. // Sets the position of `el` to coordinates specified by `position`,
  2261. // using CSS translate or top/left positioning depending on the browser
  2262. // (used by Leaflet internally to position its layers).
  2263. function setPosition(el, point) {
  2264. /*eslint-disable */
  2265. el._leaflet_pos = point;
  2266. /*eslint-enable */
  2267. if (any3d) {
  2268. setTransform(el, point);
  2269. } else {
  2270. el.style.left = point.x + 'px';
  2271. el.style.top = point.y + 'px';
  2272. }
  2273. }
  2274. // @function getPosition(el: HTMLElement): Point
  2275. // Returns the coordinates of an element previously positioned with setPosition.
  2276. function getPosition(el) {
  2277. // this method is only used for elements previously positioned using setPosition,
  2278. // so it's safe to cache the position for performance
  2279. return el._leaflet_pos || new Point(0, 0);
  2280. }
  2281. // @function disableTextSelection()
  2282. // Prevents the user from generating `selectstart` DOM events, usually generated
  2283. // when the user drags the mouse through a page with text. Used internally
  2284. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2285. // the map. Affects drag interactions on the whole document.
  2286. // @function enableTextSelection()
  2287. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2288. var disableTextSelection;
  2289. var enableTextSelection;
  2290. var _userSelect;
  2291. if ('onselectstart' in document) {
  2292. disableTextSelection = function () {
  2293. on(window, 'selectstart', preventDefault);
  2294. };
  2295. enableTextSelection = function () {
  2296. off(window, 'selectstart', preventDefault);
  2297. };
  2298. } else {
  2299. var userSelectProperty = testProp(
  2300. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2301. disableTextSelection = function () {
  2302. if (userSelectProperty) {
  2303. var style = document.documentElement.style;
  2304. _userSelect = style[userSelectProperty];
  2305. style[userSelectProperty] = 'none';
  2306. }
  2307. };
  2308. enableTextSelection = function () {
  2309. if (userSelectProperty) {
  2310. document.documentElement.style[userSelectProperty] = _userSelect;
  2311. _userSelect = undefined;
  2312. }
  2313. };
  2314. }
  2315. // @function disableImageDrag()
  2316. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2317. // for `dragstart` DOM events, usually generated when the user drags an image.
  2318. function disableImageDrag() {
  2319. on(window, 'dragstart', preventDefault);
  2320. }
  2321. // @function enableImageDrag()
  2322. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2323. function enableImageDrag() {
  2324. off(window, 'dragstart', preventDefault);
  2325. }
  2326. var _outlineElement;
  2327. var _outlineStyle;
  2328. // @function preventOutline(el: HTMLElement)
  2329. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2330. // of the element `el` invisible. Used internally by Leaflet to prevent
  2331. // focusable elements from displaying an outline when the user performs a
  2332. // drag interaction on them.
  2333. function preventOutline(element) {
  2334. while (element.tabIndex === -1) {
  2335. element = element.parentNode;
  2336. }
  2337. if (!element.style) {
  2338. return;
  2339. }
  2340. restoreOutline();
  2341. _outlineElement = element;
  2342. _outlineStyle = element.style.outline;
  2343. element.style.outline = 'none';
  2344. on(window, 'keydown', restoreOutline);
  2345. }
  2346. // @function restoreOutline()
  2347. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2348. function restoreOutline() {
  2349. if (!_outlineElement) {
  2350. return;
  2351. }
  2352. _outlineElement.style.outline = _outlineStyle;
  2353. _outlineElement = undefined;
  2354. _outlineStyle = undefined;
  2355. off(window, 'keydown', restoreOutline);
  2356. }
  2357. var DomUtil = (Object.freeze || Object)({
  2358. TRANSFORM: TRANSFORM,
  2359. TRANSITION: TRANSITION,
  2360. TRANSITION_END: TRANSITION_END,
  2361. get: get,
  2362. getStyle: getStyle,
  2363. create: create$1,
  2364. remove: remove,
  2365. empty: empty,
  2366. toFront: toFront,
  2367. toBack: toBack,
  2368. hasClass: hasClass,
  2369. addClass: addClass,
  2370. removeClass: removeClass,
  2371. setClass: setClass,
  2372. getClass: getClass,
  2373. setOpacity: setOpacity,
  2374. testProp: testProp,
  2375. setTransform: setTransform,
  2376. setPosition: setPosition,
  2377. getPosition: getPosition,
  2378. disableTextSelection: disableTextSelection,
  2379. enableTextSelection: enableTextSelection,
  2380. disableImageDrag: disableImageDrag,
  2381. enableImageDrag: enableImageDrag,
  2382. preventOutline: preventOutline,
  2383. restoreOutline: restoreOutline
  2384. });
  2385. /*
  2386. * @class PosAnimation
  2387. * @aka L.PosAnimation
  2388. * @inherits Evented
  2389. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2390. *
  2391. * @example
  2392. * ```js
  2393. * var fx = new L.PosAnimation();
  2394. * fx.run(el, [300, 500], 0.5);
  2395. * ```
  2396. *
  2397. * @constructor L.PosAnimation()
  2398. * Creates a `PosAnimation` object.
  2399. *
  2400. */
  2401. var PosAnimation = Evented.extend({
  2402. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2403. // Run an animation of a given element to a new position, optionally setting
  2404. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2405. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  2406. // `0.5` by default).
  2407. run: function (el, newPos, duration, easeLinearity) {
  2408. this.stop();
  2409. this._el = el;
  2410. this._inProgress = true;
  2411. this._duration = duration || 0.25;
  2412. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2413. this._startPos = getPosition(el);
  2414. this._offset = newPos.subtract(this._startPos);
  2415. this._startTime = +new Date();
  2416. // @event start: Event
  2417. // Fired when the animation starts
  2418. this.fire('start');
  2419. this._animate();
  2420. },
  2421. // @method stop()
  2422. // Stops the animation (if currently running).
  2423. stop: function () {
  2424. if (!this._inProgress) {
  2425. return;
  2426. }
  2427. this._step(true);
  2428. this._complete();
  2429. },
  2430. _animate: function () {
  2431. // animation loop
  2432. this._animId = requestAnimFrame(this._animate, this);
  2433. this._step();
  2434. },
  2435. _step: function (round) {
  2436. var elapsed = (+new Date()) - this._startTime,
  2437. duration = this._duration * 1000;
  2438. if (elapsed < duration) {
  2439. this._runFrame(this._easeOut(elapsed / duration), round);
  2440. } else {
  2441. this._runFrame(1);
  2442. this._complete();
  2443. }
  2444. },
  2445. _runFrame: function (progress, round) {
  2446. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2447. if (round) {
  2448. pos._round();
  2449. }
  2450. setPosition(this._el, pos);
  2451. // @event step: Event
  2452. // Fired continuously during the animation.
  2453. this.fire('step');
  2454. },
  2455. _complete: function () {
  2456. cancelAnimFrame(this._animId);
  2457. this._inProgress = false;
  2458. // @event end: Event
  2459. // Fired when the animation ends.
  2460. this.fire('end');
  2461. },
  2462. _easeOut: function (t) {
  2463. return 1 - Math.pow(1 - t, this._easeOutPower);
  2464. }
  2465. });
  2466. /*
  2467. * @class Map
  2468. * @aka L.Map
  2469. * @inherits Evented
  2470. *
  2471. * The central class of the API — it is used to create a map on a page and manipulate it.
  2472. *
  2473. * @example
  2474. *
  2475. * ```js
  2476. * // initialize the map on the "map" div with a given center and zoom
  2477. * var map = L.map('map', {
  2478. * center: [51.505, -0.09],
  2479. * zoom: 13
  2480. * });
  2481. * ```
  2482. *
  2483. */
  2484. var Map = Evented.extend({
  2485. options: {
  2486. // @section Map State Options
  2487. // @option crs: CRS = L.CRS.EPSG3857
  2488. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2489. // sure what it means.
  2490. crs: EPSG3857,
  2491. // @option center: LatLng = undefined
  2492. // Initial geographic center of the map
  2493. center: undefined,
  2494. // @option zoom: Number = undefined
  2495. // Initial map zoom level
  2496. zoom: undefined,
  2497. // @option minZoom: Number = *
  2498. // Minimum zoom level of the map.
  2499. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2500. // the lowest of their `minZoom` options will be used instead.
  2501. minZoom: undefined,
  2502. // @option maxZoom: Number = *
  2503. // Maximum zoom level of the map.
  2504. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2505. // the highest of their `maxZoom` options will be used instead.
  2506. maxZoom: undefined,
  2507. // @option layers: Layer[] = []
  2508. // Array of layers that will be added to the map initially
  2509. layers: [],
  2510. // @option maxBounds: LatLngBounds = null
  2511. // When this option is set, the map restricts the view to the given
  2512. // geographical bounds, bouncing the user back if the user tries to pan
  2513. // outside the view. To set the restriction dynamically, use
  2514. // [`setMaxBounds`](#map-setmaxbounds) method.
  2515. maxBounds: undefined,
  2516. // @option renderer: Renderer = *
  2517. // The default method for drawing vector layers on the map. `L.SVG`
  2518. // or `L.Canvas` by default depending on browser support.
  2519. renderer: undefined,
  2520. // @section Animation Options
  2521. // @option zoomAnimation: Boolean = true
  2522. // Whether the map zoom animation is enabled. By default it's enabled
  2523. // in all browsers that support CSS3 Transitions except Android.
  2524. zoomAnimation: true,
  2525. // @option zoomAnimationThreshold: Number = 4
  2526. // Won't animate zoom if the zoom difference exceeds this value.
  2527. zoomAnimationThreshold: 4,
  2528. // @option fadeAnimation: Boolean = true
  2529. // Whether the tile fade animation is enabled. By default it's enabled
  2530. // in all browsers that support CSS3 Transitions except Android.
  2531. fadeAnimation: true,
  2532. // @option markerZoomAnimation: Boolean = true
  2533. // Whether markers animate their zoom with the zoom animation, if disabled
  2534. // they will disappear for the length of the animation. By default it's
  2535. // enabled in all browsers that support CSS3 Transitions except Android.
  2536. markerZoomAnimation: true,
  2537. // @option transform3DLimit: Number = 2^23
  2538. // Defines the maximum size of a CSS translation transform. The default
  2539. // value should not be changed unless a web browser positions layers in
  2540. // the wrong place after doing a large `panBy`.
  2541. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2542. // @section Interaction Options
  2543. // @option zoomSnap: Number = 1
  2544. // Forces the map's zoom level to always be a multiple of this, particularly
  2545. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2546. // By default, the zoom level snaps to the nearest integer; lower values
  2547. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2548. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2549. zoomSnap: 1,
  2550. // @option zoomDelta: Number = 1
  2551. // Controls how much the map's zoom level will change after a
  2552. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2553. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2554. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2555. zoomDelta: 1,
  2556. // @option trackResize: Boolean = true
  2557. // Whether the map automatically handles browser window resize to update itself.
  2558. trackResize: true
  2559. },
  2560. initialize: function (id, options) { // (HTMLElement or String, Object)
  2561. options = setOptions(this, options);
  2562. this._initContainer(id);
  2563. this._initLayout();
  2564. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2565. this._onResize = bind(this._onResize, this);
  2566. this._initEvents();
  2567. if (options.maxBounds) {
  2568. this.setMaxBounds(options.maxBounds);
  2569. }
  2570. if (options.zoom !== undefined) {
  2571. this._zoom = this._limitZoom(options.zoom);
  2572. }
  2573. if (options.center && options.zoom !== undefined) {
  2574. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2575. }
  2576. this._handlers = [];
  2577. this._layers = {};
  2578. this._zoomBoundLayers = {};
  2579. this._sizeChanged = true;
  2580. this.callInitHooks();
  2581. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2582. this._zoomAnimated = TRANSITION && any3d && !mobileOpera &&
  2583. this.options.zoomAnimation;
  2584. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2585. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2586. if (this._zoomAnimated) {
  2587. this._createAnimProxy();
  2588. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2589. }
  2590. this._addLayers(this.options.layers);
  2591. },
  2592. // @section Methods for modifying map state
  2593. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2594. // Sets the view of the map (geographical center and zoom) with the given
  2595. // animation options.
  2596. setView: function (center, zoom, options) {
  2597. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2598. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2599. options = options || {};
  2600. this._stop();
  2601. if (this._loaded && !options.reset && options !== true) {
  2602. if (options.animate !== undefined) {
  2603. options.zoom = extend({animate: options.animate}, options.zoom);
  2604. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2605. }
  2606. // try animating pan or zoom
  2607. var moved = (this._zoom !== zoom) ?
  2608. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2609. this._tryAnimatedPan(center, options.pan);
  2610. if (moved) {
  2611. // prevent resize handler call, the view will refresh after animation anyway
  2612. clearTimeout(this._sizeTimer);
  2613. return this;
  2614. }
  2615. }
  2616. // animation didn't start, just reset the map view
  2617. this._resetView(center, zoom);
  2618. return this;
  2619. },
  2620. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2621. // Sets the zoom of the map.
  2622. setZoom: function (zoom, options) {
  2623. if (!this._loaded) {
  2624. this._zoom = zoom;
  2625. return this;
  2626. }
  2627. return this.setView(this.getCenter(), zoom, {zoom: options});
  2628. },
  2629. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2630. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2631. zoomIn: function (delta, options) {
  2632. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2633. return this.setZoom(this._zoom + delta, options);
  2634. },
  2635. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2636. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2637. zoomOut: function (delta, options) {
  2638. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2639. return this.setZoom(this._zoom - delta, options);
  2640. },
  2641. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2642. // Zooms the map while keeping a specified geographical point on the map
  2643. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2644. // @alternative
  2645. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2646. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2647. setZoomAround: function (latlng, zoom, options) {
  2648. var scale = this.getZoomScale(zoom),
  2649. viewHalf = this.getSize().divideBy(2),
  2650. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2651. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2652. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2653. return this.setView(newCenter, zoom, {zoom: options});
  2654. },
  2655. _getBoundsCenterZoom: function (bounds, options) {
  2656. options = options || {};
  2657. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2658. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2659. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2660. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2661. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2662. if (zoom === Infinity) {
  2663. return {
  2664. center: bounds.getCenter(),
  2665. zoom: zoom
  2666. };
  2667. }
  2668. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2669. swPoint = this.project(bounds.getSouthWest(), zoom),
  2670. nePoint = this.project(bounds.getNorthEast(), zoom),
  2671. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2672. return {
  2673. center: center,
  2674. zoom: zoom
  2675. };
  2676. },
  2677. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2678. // Sets a map view that contains the given geographical bounds with the
  2679. // maximum zoom level possible.
  2680. fitBounds: function (bounds, options) {
  2681. bounds = toLatLngBounds(bounds);
  2682. if (!bounds.isValid()) {
  2683. throw new Error('Bounds are not valid.');
  2684. }
  2685. var target = this._getBoundsCenterZoom(bounds, options);
  2686. return this.setView(target.center, target.zoom, options);
  2687. },
  2688. // @method fitWorld(options?: fitBounds options): this
  2689. // Sets a map view that mostly contains the whole world with the maximum
  2690. // zoom level possible.
  2691. fitWorld: function (options) {
  2692. return this.fitBounds([[-90, -180], [90, 180]], options);
  2693. },
  2694. // @method panTo(latlng: LatLng, options?: Pan options): this
  2695. // Pans the map to a given center.
  2696. panTo: function (center, options) { // (LatLng)
  2697. return this.setView(center, this._zoom, {pan: options});
  2698. },
  2699. // @method panBy(offset: Point, options?: Pan options): this
  2700. // Pans the map by a given number of pixels (animated).
  2701. panBy: function (offset, options) {
  2702. offset = toPoint(offset).round();
  2703. options = options || {};
  2704. if (!offset.x && !offset.y) {
  2705. return this.fire('moveend');
  2706. }
  2707. // If we pan too far, Chrome gets issues with tiles
  2708. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2709. if (options.animate !== true && !this.getSize().contains(offset)) {
  2710. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2711. return this;
  2712. }
  2713. if (!this._panAnim) {
  2714. this._panAnim = new PosAnimation();
  2715. this._panAnim.on({
  2716. 'step': this._onPanTransitionStep,
  2717. 'end': this._onPanTransitionEnd
  2718. }, this);
  2719. }
  2720. // don't fire movestart if animating inertia
  2721. if (!options.noMoveStart) {
  2722. this.fire('movestart');
  2723. }
  2724. // animate pan unless animate: false specified
  2725. if (options.animate !== false) {
  2726. addClass(this._mapPane, 'leaflet-pan-anim');
  2727. var newPos = this._getMapPanePos().subtract(offset).round();
  2728. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2729. } else {
  2730. this._rawPanBy(offset);
  2731. this.fire('move').fire('moveend');
  2732. }
  2733. return this;
  2734. },
  2735. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2736. // Sets the view of the map (geographical center and zoom) performing a smooth
  2737. // pan-zoom animation.
  2738. flyTo: function (targetCenter, targetZoom, options) {
  2739. options = options || {};
  2740. if (options.animate === false || !any3d) {
  2741. return this.setView(targetCenter, targetZoom, options);
  2742. }
  2743. this._stop();
  2744. var from = this.project(this.getCenter()),
  2745. to = this.project(targetCenter),
  2746. size = this.getSize(),
  2747. startZoom = this._zoom;
  2748. targetCenter = toLatLng(targetCenter);
  2749. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2750. var w0 = Math.max(size.x, size.y),
  2751. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2752. u1 = (to.distanceTo(from)) || 1,
  2753. rho = 1.42,
  2754. rho2 = rho * rho;
  2755. function r(i) {
  2756. var s1 = i ? -1 : 1,
  2757. s2 = i ? w1 : w0,
  2758. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2759. b1 = 2 * s2 * rho2 * u1,
  2760. b = t1 / b1,
  2761. sq = Math.sqrt(b * b + 1) - b;
  2762. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2763. // thus triggering an infinite loop in flyTo
  2764. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2765. return log;
  2766. }
  2767. function sinh(n) {
  2768. return (Math.exp(n) - Math.exp(-n)) / 2;
  2769. }
  2770. function cosh(n) {
  2771. return (Math.exp(n) + Math.exp(-n)) / 2;
  2772. }
  2773. function tanh(n) {
  2774. return sinh(n) / cosh(n);
  2775. }
  2776. var r0 = r(0);
  2777. function w(s) {
  2778. return w0 * (cosh(r0) / cosh(r0 + rho * s));
  2779. }
  2780. function u(s) {
  2781. return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2;
  2782. }
  2783. function easeOut(t) {
  2784. return 1 - Math.pow(1 - t, 1.5);
  2785. }
  2786. var start = Date.now(),
  2787. S = (r(1) - r0) / rho,
  2788. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2789. function frame() {
  2790. var t = (Date.now() - start) / duration,
  2791. s = easeOut(t) * S;
  2792. if (t <= 1) {
  2793. this._flyToFrame = requestAnimFrame(frame, this);
  2794. this._move(
  2795. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2796. this.getScaleZoom(w0 / w(s), startZoom),
  2797. {flyTo: true});
  2798. } else {
  2799. this
  2800. ._move(targetCenter, targetZoom)
  2801. ._moveEnd(true);
  2802. }
  2803. }
  2804. this._moveStart(true);
  2805. frame.call(this);
  2806. return this;
  2807. },
  2808. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2809. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2810. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2811. flyToBounds: function (bounds, options) {
  2812. var target = this._getBoundsCenterZoom(bounds, options);
  2813. return this.flyTo(target.center, target.zoom, options);
  2814. },
  2815. // @method setMaxBounds(bounds: Bounds): this
  2816. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2817. setMaxBounds: function (bounds) {
  2818. bounds = toLatLngBounds(bounds);
  2819. if (!bounds.isValid()) {
  2820. this.options.maxBounds = null;
  2821. return this.off('moveend', this._panInsideMaxBounds);
  2822. } else if (this.options.maxBounds) {
  2823. this.off('moveend', this._panInsideMaxBounds);
  2824. }
  2825. this.options.maxBounds = bounds;
  2826. if (this._loaded) {
  2827. this._panInsideMaxBounds();
  2828. }
  2829. return this.on('moveend', this._panInsideMaxBounds);
  2830. },
  2831. // @method setMinZoom(zoom: Number): this
  2832. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2833. setMinZoom: function (zoom) {
  2834. this.options.minZoom = zoom;
  2835. if (this._loaded && this.getZoom() < this.options.minZoom) {
  2836. return this.setZoom(zoom);
  2837. }
  2838. return this;
  2839. },
  2840. // @method setMaxZoom(zoom: Number): this
  2841. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2842. setMaxZoom: function (zoom) {
  2843. this.options.maxZoom = zoom;
  2844. if (this._loaded && (this.getZoom() > this.options.maxZoom)) {
  2845. return this.setZoom(zoom);
  2846. }
  2847. return this;
  2848. },
  2849. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2850. // 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.
  2851. panInsideBounds: function (bounds, options) {
  2852. this._enforcingBounds = true;
  2853. var center = this.getCenter(),
  2854. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2855. if (!center.equals(newCenter)) {
  2856. this.panTo(newCenter, options);
  2857. }
  2858. this._enforcingBounds = false;
  2859. return this;
  2860. },
  2861. // @method invalidateSize(options: Zoom/Pan options): this
  2862. // Checks if the map container size changed and updates the map if so —
  2863. // call it after you've changed the map size dynamically, also animating
  2864. // pan by default. If `options.pan` is `false`, panning will not occur.
  2865. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2866. // that it doesn't happen often even if the method is called many
  2867. // times in a row.
  2868. // @alternative
  2869. // @method invalidateSize(animate: Boolean): this
  2870. // Checks if the map container size changed and updates the map if so —
  2871. // call it after you've changed the map size dynamically, also animating
  2872. // pan by default.
  2873. invalidateSize: function (options) {
  2874. if (!this._loaded) {
  2875. return this;
  2876. }
  2877. options = extend({
  2878. animate: false,
  2879. pan: true
  2880. }, options === true ? {animate: true} : options);
  2881. var oldSize = this.getSize();
  2882. this._sizeChanged = true;
  2883. this._lastCenter = null;
  2884. var newSize = this.getSize(),
  2885. oldCenter = oldSize.divideBy(2).round(),
  2886. newCenter = newSize.divideBy(2).round(),
  2887. offset = oldCenter.subtract(newCenter);
  2888. if (!offset.x && !offset.y) {
  2889. return this;
  2890. }
  2891. if (options.animate && options.pan) {
  2892. this.panBy(offset);
  2893. } else {
  2894. if (options.pan) {
  2895. this._rawPanBy(offset);
  2896. }
  2897. this.fire('move');
  2898. if (options.debounceMoveend) {
  2899. clearTimeout(this._sizeTimer);
  2900. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  2901. } else {
  2902. this.fire('moveend');
  2903. }
  2904. }
  2905. // @section Map state change events
  2906. // @event resize: ResizeEvent
  2907. // Fired when the map is resized.
  2908. return this.fire('resize', {
  2909. oldSize: oldSize,
  2910. newSize: newSize
  2911. });
  2912. },
  2913. // @section Methods for modifying map state
  2914. // @method stop(): this
  2915. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2916. stop: function () {
  2917. this.setZoom(this._limitZoom(this._zoom));
  2918. if (!this.options.zoomSnap) {
  2919. this.fire('viewreset');
  2920. }
  2921. return this._stop();
  2922. },
  2923. // @section Geolocation methods
  2924. // @method locate(options?: Locate options): this
  2925. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  2926. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  2927. // and optionally sets the map view to the user's location with respect to
  2928. // detection accuracy (or to the world view if geolocation failed).
  2929. // Note that, if your page doesn't use HTTPS, this method will fail in
  2930. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  2931. // See `Locate options` for more details.
  2932. locate: function (options) {
  2933. options = this._locateOptions = extend({
  2934. timeout: 10000,
  2935. watch: false
  2936. // setView: false
  2937. // maxZoom: <Number>
  2938. // maximumAge: 0
  2939. // enableHighAccuracy: false
  2940. }, options);
  2941. if (!('geolocation' in navigator)) {
  2942. this._handleGeolocationError({
  2943. code: 0,
  2944. message: 'Geolocation not supported.'
  2945. });
  2946. return this;
  2947. }
  2948. var onResponse = bind(this._handleGeolocationResponse, this),
  2949. onError = bind(this._handleGeolocationError, this);
  2950. if (options.watch) {
  2951. this._locationWatchId =
  2952. navigator.geolocation.watchPosition(onResponse, onError, options);
  2953. } else {
  2954. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  2955. }
  2956. return this;
  2957. },
  2958. // @method stopLocate(): this
  2959. // Stops watching location previously initiated by `map.locate({watch: true})`
  2960. // and aborts resetting the map view if map.locate was called with
  2961. // `{setView: true}`.
  2962. stopLocate: function () {
  2963. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  2964. navigator.geolocation.clearWatch(this._locationWatchId);
  2965. }
  2966. if (this._locateOptions) {
  2967. this._locateOptions.setView = false;
  2968. }
  2969. return this;
  2970. },
  2971. _handleGeolocationError: function (error) {
  2972. var c = error.code,
  2973. message = error.message ||
  2974. (c === 1 ? 'permission denied' :
  2975. (c === 2 ? 'position unavailable' : 'timeout'));
  2976. if (this._locateOptions.setView && !this._loaded) {
  2977. this.fitWorld();
  2978. }
  2979. // @section Location events
  2980. // @event locationerror: ErrorEvent
  2981. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  2982. this.fire('locationerror', {
  2983. code: c,
  2984. message: 'Geolocation error: ' + message + '.'
  2985. });
  2986. },
  2987. _handleGeolocationResponse: function (pos) {
  2988. var lat = pos.coords.latitude,
  2989. lng = pos.coords.longitude,
  2990. latlng = new LatLng(lat, lng),
  2991. bounds = latlng.toBounds(pos.coords.accuracy),
  2992. options = this._locateOptions;
  2993. if (options.setView) {
  2994. var zoom = this.getBoundsZoom(bounds);
  2995. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  2996. }
  2997. var data = {
  2998. latlng: latlng,
  2999. bounds: bounds,
  3000. timestamp: pos.timestamp
  3001. };
  3002. for (var i in pos.coords) {
  3003. if (typeof pos.coords[i] === 'number') {
  3004. data[i] = pos.coords[i];
  3005. }
  3006. }
  3007. // @event locationfound: LocationEvent
  3008. // Fired when geolocation (using the [`locate`](#map-locate) method)
  3009. // went successfully.
  3010. this.fire('locationfound', data);
  3011. },
  3012. // TODO handler.addTo
  3013. // TODO Appropiate docs section?
  3014. // @section Other Methods
  3015. // @method addHandler(name: String, HandlerClass: Function): this
  3016. // Adds a new `Handler` to the map, given its name and constructor function.
  3017. addHandler: function (name, HandlerClass) {
  3018. if (!HandlerClass) {
  3019. return this;
  3020. }
  3021. var handler = this[name] = new HandlerClass(this);
  3022. this._handlers.push(handler);
  3023. if (this.options[name]) {
  3024. handler.enable();
  3025. }
  3026. return this;
  3027. },
  3028. // @method remove(): this
  3029. // Destroys the map and clears all related event listeners.
  3030. remove: function () {
  3031. this._initEvents(true);
  3032. if (this._containerId !== this._container._leaflet_id) {
  3033. throw new Error('Map container is being reused by another instance');
  3034. }
  3035. try {
  3036. // throws error in IE6-8
  3037. delete this._container._leaflet_id;
  3038. delete this._containerId;
  3039. } catch (e) {
  3040. /*eslint-disable */
  3041. this._container._leaflet_id = undefined;
  3042. /*eslint-enable */
  3043. this._containerId = undefined;
  3044. }
  3045. remove(this._mapPane);
  3046. if (this._clearControlPos) {
  3047. this._clearControlPos();
  3048. }
  3049. this._clearHandlers();
  3050. if (this._loaded) {
  3051. // @section Map state change events
  3052. // @event unload: Event
  3053. // Fired when the map is destroyed with [remove](#map-remove) method.
  3054. this.fire('unload');
  3055. }
  3056. var i;
  3057. for (i in this._layers) {
  3058. this._layers[i].remove();
  3059. }
  3060. for (i in this._panes) {
  3061. remove(this._panes[i]);
  3062. }
  3063. this._layers = [];
  3064. this._panes = [];
  3065. delete this._mapPane;
  3066. delete this._renderer;
  3067. return this;
  3068. },
  3069. // @section Other Methods
  3070. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3071. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3072. // then returns it. The pane is created as a child of `container`, or
  3073. // as a child of the main map pane if not set.
  3074. createPane: function (name, container) {
  3075. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3076. pane = create$1('div', className, container || this._mapPane);
  3077. if (name) {
  3078. this._panes[name] = pane;
  3079. }
  3080. return pane;
  3081. },
  3082. // @section Methods for Getting Map State
  3083. // @method getCenter(): LatLng
  3084. // Returns the geographical center of the map view
  3085. getCenter: function () {
  3086. this._checkIfLoaded();
  3087. if (this._lastCenter && !this._moved()) {
  3088. return this._lastCenter;
  3089. }
  3090. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3091. },
  3092. // @method getZoom(): Number
  3093. // Returns the current zoom level of the map view
  3094. getZoom: function () {
  3095. return this._zoom;
  3096. },
  3097. // @method getBounds(): LatLngBounds
  3098. // Returns the geographical bounds visible in the current map view
  3099. getBounds: function () {
  3100. var bounds = this.getPixelBounds(),
  3101. sw = this.unproject(bounds.getBottomLeft()),
  3102. ne = this.unproject(bounds.getTopRight());
  3103. return new LatLngBounds(sw, ne);
  3104. },
  3105. // @method getMinZoom(): Number
  3106. // 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.
  3107. getMinZoom: function () {
  3108. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3109. },
  3110. // @method getMaxZoom(): Number
  3111. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3112. getMaxZoom: function () {
  3113. return this.options.maxZoom === undefined ?
  3114. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3115. this.options.maxZoom;
  3116. },
  3117. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean): Number
  3118. // Returns the maximum zoom level on which the given bounds fit to the map
  3119. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3120. // instead returns the minimum zoom level on which the map view fits into
  3121. // the given bounds in its entirety.
  3122. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3123. bounds = toLatLngBounds(bounds);
  3124. padding = toPoint(padding || [0, 0]);
  3125. var zoom = this.getZoom() || 0,
  3126. min = this.getMinZoom(),
  3127. max = this.getMaxZoom(),
  3128. nw = bounds.getNorthWest(),
  3129. se = bounds.getSouthEast(),
  3130. size = this.getSize().subtract(padding),
  3131. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3132. snap = any3d ? this.options.zoomSnap : 1,
  3133. scalex = size.x / boundsSize.x,
  3134. scaley = size.y / boundsSize.y,
  3135. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3136. zoom = this.getScaleZoom(scale, zoom);
  3137. if (snap) {
  3138. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3139. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3140. }
  3141. return Math.max(min, Math.min(max, zoom));
  3142. },
  3143. // @method getSize(): Point
  3144. // Returns the current size of the map container (in pixels).
  3145. getSize: function () {
  3146. if (!this._size || this._sizeChanged) {
  3147. this._size = new Point(
  3148. this._container.clientWidth || 0,
  3149. this._container.clientHeight || 0);
  3150. this._sizeChanged = false;
  3151. }
  3152. return this._size.clone();
  3153. },
  3154. // @method getPixelBounds(): Bounds
  3155. // Returns the bounds of the current map view in projected pixel
  3156. // coordinates (sometimes useful in layer and overlay implementations).
  3157. getPixelBounds: function (center, zoom) {
  3158. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3159. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3160. },
  3161. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3162. // the map pane? "left point of the map layer" can be confusing, specially
  3163. // since there can be negative offsets.
  3164. // @method getPixelOrigin(): Point
  3165. // Returns the projected pixel coordinates of the top left point of
  3166. // the map layer (useful in custom layer and overlay implementations).
  3167. getPixelOrigin: function () {
  3168. this._checkIfLoaded();
  3169. return this._pixelOrigin;
  3170. },
  3171. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3172. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3173. // If `zoom` is omitted, the map's current zoom level is used.
  3174. getPixelWorldBounds: function (zoom) {
  3175. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3176. },
  3177. // @section Other Methods
  3178. // @method getPane(pane: String|HTMLElement): HTMLElement
  3179. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3180. getPane: function (pane) {
  3181. return typeof pane === 'string' ? this._panes[pane] : pane;
  3182. },
  3183. // @method getPanes(): Object
  3184. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3185. // the panes as values.
  3186. getPanes: function () {
  3187. return this._panes;
  3188. },
  3189. // @method getContainer: HTMLElement
  3190. // Returns the HTML element that contains the map.
  3191. getContainer: function () {
  3192. return this._container;
  3193. },
  3194. // @section Conversion Methods
  3195. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3196. // Returns the scale factor to be applied to a map transition from zoom level
  3197. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3198. getZoomScale: function (toZoom, fromZoom) {
  3199. // TODO replace with universal implementation after refactoring projections
  3200. var crs = this.options.crs;
  3201. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3202. return crs.scale(toZoom) / crs.scale(fromZoom);
  3203. },
  3204. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3205. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3206. // level and everything is scaled by a factor of `scale`. Inverse of
  3207. // [`getZoomScale`](#map-getZoomScale).
  3208. getScaleZoom: function (scale, fromZoom) {
  3209. var crs = this.options.crs;
  3210. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3211. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3212. return isNaN(zoom) ? Infinity : zoom;
  3213. },
  3214. // @method project(latlng: LatLng, zoom: Number): Point
  3215. // Projects a geographical coordinate `LatLng` according to the projection
  3216. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3217. // `Transformation`. The result is pixel coordinate relative to
  3218. // the CRS origin.
  3219. project: function (latlng, zoom) {
  3220. zoom = zoom === undefined ? this._zoom : zoom;
  3221. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3222. },
  3223. // @method unproject(point: Point, zoom: Number): LatLng
  3224. // Inverse of [`project`](#map-project).
  3225. unproject: function (point, zoom) {
  3226. zoom = zoom === undefined ? this._zoom : zoom;
  3227. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3228. },
  3229. // @method layerPointToLatLng(point: Point): LatLng
  3230. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3231. // returns the corresponding geographical coordinate (for the current zoom level).
  3232. layerPointToLatLng: function (point) {
  3233. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3234. return this.unproject(projectedPoint);
  3235. },
  3236. // @method latLngToLayerPoint(latlng: LatLng): Point
  3237. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3238. // relative to the [origin pixel](#map-getpixelorigin).
  3239. latLngToLayerPoint: function (latlng) {
  3240. var projectedPoint = this.project(toLatLng(latlng))._round();
  3241. return projectedPoint._subtract(this.getPixelOrigin());
  3242. },
  3243. // @method wrapLatLng(latlng: LatLng): LatLng
  3244. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3245. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3246. // CRS's bounds.
  3247. // By default this means longitude is wrapped around the dateline so its
  3248. // value is between -180 and +180 degrees.
  3249. wrapLatLng: function (latlng) {
  3250. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3251. },
  3252. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3253. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3254. // its center is within the CRS's bounds.
  3255. // By default this means the center longitude is wrapped around the dateline so its
  3256. // value is between -180 and +180 degrees, and the majority of the bounds
  3257. // overlaps the CRS's bounds.
  3258. wrapLatLngBounds: function (latlng) {
  3259. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3260. },
  3261. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3262. // Returns the distance between two geographical coordinates according to
  3263. // the map's CRS. By default this measures distance in meters.
  3264. distance: function (latlng1, latlng2) {
  3265. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3266. },
  3267. // @method containerPointToLayerPoint(point: Point): Point
  3268. // Given a pixel coordinate relative to the map container, returns the corresponding
  3269. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3270. containerPointToLayerPoint: function (point) { // (Point)
  3271. return toPoint(point).subtract(this._getMapPanePos());
  3272. },
  3273. // @method layerPointToContainerPoint(point: Point): Point
  3274. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3275. // returns the corresponding pixel coordinate relative to the map container.
  3276. layerPointToContainerPoint: function (point) { // (Point)
  3277. return toPoint(point).add(this._getMapPanePos());
  3278. },
  3279. // @method containerPointToLatLng(point: Point): LatLng
  3280. // Given a pixel coordinate relative to the map container, returns
  3281. // the corresponding geographical coordinate (for the current zoom level).
  3282. containerPointToLatLng: function (point) {
  3283. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3284. return this.layerPointToLatLng(layerPoint);
  3285. },
  3286. // @method latLngToContainerPoint(latlng: LatLng): Point
  3287. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3288. // relative to the map container.
  3289. latLngToContainerPoint: function (latlng) {
  3290. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3291. },
  3292. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3293. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3294. // map container where the event took place.
  3295. mouseEventToContainerPoint: function (e) {
  3296. return getMousePosition(e, this._container);
  3297. },
  3298. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3299. // Given a MouseEvent object, returns the pixel coordinate relative to
  3300. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3301. mouseEventToLayerPoint: function (e) {
  3302. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3303. },
  3304. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3305. // Given a MouseEvent object, returns geographical coordinate where the
  3306. // event took place.
  3307. mouseEventToLatLng: function (e) { // (MouseEvent)
  3308. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3309. },
  3310. // map initialization methods
  3311. _initContainer: function (id) {
  3312. var container = this._container = get(id);
  3313. if (!container) {
  3314. throw new Error('Map container not found.');
  3315. } else if (container._leaflet_id) {
  3316. throw new Error('Map container is already initialized.');
  3317. }
  3318. on(container, 'scroll', this._onScroll, this);
  3319. this._containerId = stamp(container);
  3320. },
  3321. _initLayout: function () {
  3322. var container = this._container;
  3323. this._fadeAnimated = this.options.fadeAnimation && any3d;
  3324. addClass(container, 'leaflet-container' +
  3325. (touch ? ' leaflet-touch' : '') +
  3326. (retina ? ' leaflet-retina' : '') +
  3327. (ielt9 ? ' leaflet-oldie' : '') +
  3328. (safari ? ' leaflet-safari' : '') +
  3329. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3330. var position = getStyle(container, 'position');
  3331. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  3332. container.style.position = 'relative';
  3333. }
  3334. this._initPanes();
  3335. if (this._initControlPos) {
  3336. this._initControlPos();
  3337. }
  3338. },
  3339. _initPanes: function () {
  3340. var panes = this._panes = {};
  3341. this._paneRenderers = {};
  3342. // @section
  3343. //
  3344. // Panes are DOM elements used to control the ordering of layers on the map. You
  3345. // can access panes with [`map.getPane`](#map-getpane) or
  3346. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3347. // [`map.createPane`](#map-createpane) method.
  3348. //
  3349. // Every map has the following default panes that differ only in zIndex.
  3350. //
  3351. // @pane mapPane: HTMLElement = 'auto'
  3352. // Pane that contains all other map panes
  3353. this._mapPane = this.createPane('mapPane', this._container);
  3354. setPosition(this._mapPane, new Point(0, 0));
  3355. // @pane tilePane: HTMLElement = 200
  3356. // Pane for `GridLayer`s and `TileLayer`s
  3357. this.createPane('tilePane');
  3358. // @pane overlayPane: HTMLElement = 400
  3359. // Pane for vector overlays (`Path`s), like `Polyline`s and `Polygon`s
  3360. this.createPane('shadowPane');
  3361. // @pane shadowPane: HTMLElement = 500
  3362. // Pane for overlay shadows (e.g. `Marker` shadows)
  3363. this.createPane('overlayPane');
  3364. // @pane markerPane: HTMLElement = 600
  3365. // Pane for `Icon`s of `Marker`s
  3366. this.createPane('markerPane');
  3367. // @pane tooltipPane: HTMLElement = 650
  3368. // Pane for tooltip.
  3369. this.createPane('tooltipPane');
  3370. // @pane popupPane: HTMLElement = 700
  3371. // Pane for `Popup`s.
  3372. this.createPane('popupPane');
  3373. if (!this.options.markerZoomAnimation) {
  3374. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3375. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3376. }
  3377. },
  3378. // private methods that modify map state
  3379. // @section Map state change events
  3380. _resetView: function (center, zoom) {
  3381. setPosition(this._mapPane, new Point(0, 0));
  3382. var loading = !this._loaded;
  3383. this._loaded = true;
  3384. zoom = this._limitZoom(zoom);
  3385. this.fire('viewprereset');
  3386. var zoomChanged = this._zoom !== zoom;
  3387. this
  3388. ._moveStart(zoomChanged)
  3389. ._move(center, zoom)
  3390. ._moveEnd(zoomChanged);
  3391. // @event viewreset: Event
  3392. // Fired when the map needs to redraw its content (this usually happens
  3393. // on map zoom or load). Very useful for creating custom overlays.
  3394. this.fire('viewreset');
  3395. // @event load: Event
  3396. // Fired when the map is initialized (when its center and zoom are set
  3397. // for the first time).
  3398. if (loading) {
  3399. this.fire('load');
  3400. }
  3401. },
  3402. _moveStart: function (zoomChanged) {
  3403. // @event zoomstart: Event
  3404. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3405. // @event movestart: Event
  3406. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3407. if (zoomChanged) {
  3408. this.fire('zoomstart');
  3409. }
  3410. return this.fire('movestart');
  3411. },
  3412. _move: function (center, zoom, data) {
  3413. if (zoom === undefined) {
  3414. zoom = this._zoom;
  3415. }
  3416. var zoomChanged = this._zoom !== zoom;
  3417. this._zoom = zoom;
  3418. this._lastCenter = center;
  3419. this._pixelOrigin = this._getNewPixelOrigin(center);
  3420. // @event zoom: Event
  3421. // Fired repeatedly during any change in zoom level, including zoom
  3422. // and fly animations.
  3423. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3424. this.fire('zoom', data);
  3425. }
  3426. // @event move: Event
  3427. // Fired repeatedly during any movement of the map, including pan and
  3428. // fly animations.
  3429. return this.fire('move', data);
  3430. },
  3431. _moveEnd: function (zoomChanged) {
  3432. // @event zoomend: Event
  3433. // Fired when the map has changed, after any animations.
  3434. if (zoomChanged) {
  3435. this.fire('zoomend');
  3436. }
  3437. // @event moveend: Event
  3438. // Fired when the center of the map stops changing (e.g. user stopped
  3439. // dragging the map).
  3440. return this.fire('moveend');
  3441. },
  3442. _stop: function () {
  3443. cancelAnimFrame(this._flyToFrame);
  3444. if (this._panAnim) {
  3445. this._panAnim.stop();
  3446. }
  3447. return this;
  3448. },
  3449. _rawPanBy: function (offset) {
  3450. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3451. },
  3452. _getZoomSpan: function () {
  3453. return this.getMaxZoom() - this.getMinZoom();
  3454. },
  3455. _panInsideMaxBounds: function () {
  3456. if (!this._enforcingBounds) {
  3457. this.panInsideBounds(this.options.maxBounds);
  3458. }
  3459. },
  3460. _checkIfLoaded: function () {
  3461. if (!this._loaded) {
  3462. throw new Error('Set map center and zoom first.');
  3463. }
  3464. },
  3465. // DOM event handling
  3466. // @section Interaction events
  3467. _initEvents: function (remove$$1) {
  3468. this._targets = {};
  3469. this._targets[stamp(this._container)] = this;
  3470. var onOff = remove$$1 ? off : on;
  3471. // @event click: MouseEvent
  3472. // Fired when the user clicks (or taps) the map.
  3473. // @event dblclick: MouseEvent
  3474. // Fired when the user double-clicks (or double-taps) the map.
  3475. // @event mousedown: MouseEvent
  3476. // Fired when the user pushes the mouse button on the map.
  3477. // @event mouseup: MouseEvent
  3478. // Fired when the user releases the mouse button on the map.
  3479. // @event mouseover: MouseEvent
  3480. // Fired when the mouse enters the map.
  3481. // @event mouseout: MouseEvent
  3482. // Fired when the mouse leaves the map.
  3483. // @event mousemove: MouseEvent
  3484. // Fired while the mouse moves over the map.
  3485. // @event contextmenu: MouseEvent
  3486. // Fired when the user pushes the right mouse button on the map, prevents
  3487. // default browser context menu from showing if there are listeners on
  3488. // this event. Also fired on mobile when the user holds a single touch
  3489. // for a second (also called long press).
  3490. // @event keypress: KeyboardEvent
  3491. // Fired when the user presses a key from the keyboard while the map is focused.
  3492. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3493. 'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this);
  3494. if (this.options.trackResize) {
  3495. onOff(window, 'resize', this._onResize, this);
  3496. }
  3497. if (any3d && this.options.transform3DLimit) {
  3498. (remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3499. }
  3500. },
  3501. _onResize: function () {
  3502. cancelAnimFrame(this._resizeRequest);
  3503. this._resizeRequest = requestAnimFrame(
  3504. function () {
  3505. this.invalidateSize({debounceMoveend: true});
  3506. }, this);
  3507. },
  3508. _onScroll: function () {
  3509. this._container.scrollTop = 0;
  3510. this._container.scrollLeft = 0;
  3511. },
  3512. _onMoveEnd: function () {
  3513. var pos = this._getMapPanePos();
  3514. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3515. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3516. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  3517. this._resetView(this.getCenter(), this.getZoom());
  3518. }
  3519. },
  3520. _findEventTargets: function (e, type) {
  3521. var targets = [],
  3522. target,
  3523. isHover = type === 'mouseout' || type === 'mouseover',
  3524. src = e.target || e.srcElement,
  3525. dragging = false;
  3526. while (src) {
  3527. target = this._targets[stamp(src)];
  3528. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  3529. // Prevent firing click after you just dragged an object.
  3530. dragging = true;
  3531. break;
  3532. }
  3533. if (target && target.listens(type, true)) {
  3534. if (isHover && !isExternalTarget(src, e)) {
  3535. break;
  3536. }
  3537. targets.push(target);
  3538. if (isHover) {
  3539. break;
  3540. }
  3541. }
  3542. if (src === this._container) {
  3543. break;
  3544. }
  3545. src = src.parentNode;
  3546. }
  3547. if (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {
  3548. targets = [this];
  3549. }
  3550. return targets;
  3551. },
  3552. _handleDOMEvent: function (e) {
  3553. if (!this._loaded || skipped(e)) {
  3554. return;
  3555. }
  3556. var type = e.type;
  3557. if (type === 'mousedown' || type === 'keypress') {
  3558. // prevents outline when clicking on keyboard-focusable element
  3559. preventOutline(e.target || e.srcElement);
  3560. }
  3561. this._fireDOMEvent(e, type);
  3562. },
  3563. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3564. _fireDOMEvent: function (e, type, targets) {
  3565. if (e.type === 'click') {
  3566. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3567. // @event preclick: MouseEvent
  3568. // Fired before mouse click on the map (sometimes useful when you
  3569. // want something to happen on click before any existing click
  3570. // handlers start running).
  3571. var synth = extend({}, e);
  3572. synth.type = 'preclick';
  3573. this._fireDOMEvent(synth, synth.type, targets);
  3574. }
  3575. if (e._stopped) {
  3576. return;
  3577. }
  3578. // Find the layer the event is propagating from and its parents.
  3579. targets = (targets || []).concat(this._findEventTargets(e, type));
  3580. if (!targets.length) {
  3581. return;
  3582. }
  3583. var target = targets[0];
  3584. if (type === 'contextmenu' && target.listens(type, true)) {
  3585. preventDefault(e);
  3586. }
  3587. var data = {
  3588. originalEvent: e
  3589. };
  3590. if (e.type !== 'keypress') {
  3591. var isMarker = (target.options && 'icon' in target.options);
  3592. data.containerPoint = isMarker ?
  3593. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3594. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3595. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3596. }
  3597. for (var i = 0; i < targets.length; i++) {
  3598. targets[i].fire(type, data, true);
  3599. if (data.originalEvent._stopped ||
  3600. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) {
  3601. return;
  3602. }
  3603. }
  3604. },
  3605. _draggableMoved: function (obj) {
  3606. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3607. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3608. },
  3609. _clearHandlers: function () {
  3610. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3611. this._handlers[i].disable();
  3612. }
  3613. },
  3614. // @section Other Methods
  3615. // @method whenReady(fn: Function, context?: Object): this
  3616. // Runs the given function `fn` when the map gets initialized with
  3617. // a view (center and zoom) and at least one layer, or immediately
  3618. // if it's already initialized, optionally passing a function context.
  3619. whenReady: function (callback, context) {
  3620. if (this._loaded) {
  3621. callback.call(context || this, {target: this});
  3622. } else {
  3623. this.on('load', callback, context);
  3624. }
  3625. return this;
  3626. },
  3627. // private methods for getting map state
  3628. _getMapPanePos: function () {
  3629. return getPosition(this._mapPane) || new Point(0, 0);
  3630. },
  3631. _moved: function () {
  3632. var pos = this._getMapPanePos();
  3633. return pos && !pos.equals([0, 0]);
  3634. },
  3635. _getTopLeftPoint: function (center, zoom) {
  3636. var pixelOrigin = center && zoom !== undefined ?
  3637. this._getNewPixelOrigin(center, zoom) :
  3638. this.getPixelOrigin();
  3639. return pixelOrigin.subtract(this._getMapPanePos());
  3640. },
  3641. _getNewPixelOrigin: function (center, zoom) {
  3642. var viewHalf = this.getSize()._divideBy(2);
  3643. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3644. },
  3645. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3646. var topLeft = this._getNewPixelOrigin(center, zoom);
  3647. return this.project(latlng, zoom)._subtract(topLeft);
  3648. },
  3649. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3650. var topLeft = this._getNewPixelOrigin(center, zoom);
  3651. return toBounds([
  3652. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3653. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3654. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3655. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3656. ]);
  3657. },
  3658. // layer point of the current center
  3659. _getCenterLayerPoint: function () {
  3660. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3661. },
  3662. // offset of the specified place to the current center in pixels
  3663. _getCenterOffset: function (latlng) {
  3664. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3665. },
  3666. // adjust center for view to get inside bounds
  3667. _limitCenter: function (center, zoom, bounds) {
  3668. if (!bounds) {
  3669. return center;
  3670. }
  3671. var centerPoint = this.project(center, zoom),
  3672. viewHalf = this.getSize().divideBy(2),
  3673. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3674. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3675. // If offset is less than a pixel, ignore.
  3676. // This prevents unstable projections from getting into
  3677. // an infinite loop of tiny offsets.
  3678. if (offset.round().equals([0, 0])) {
  3679. return center;
  3680. }
  3681. return this.unproject(centerPoint.add(offset), zoom);
  3682. },
  3683. // adjust offset for view to get inside bounds
  3684. _limitOffset: function (offset, bounds) {
  3685. if (!bounds) {
  3686. return offset;
  3687. }
  3688. var viewBounds = this.getPixelBounds(),
  3689. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3690. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3691. },
  3692. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3693. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3694. var projectedMaxBounds = toBounds(
  3695. this.project(maxBounds.getNorthEast(), zoom),
  3696. this.project(maxBounds.getSouthWest(), zoom)
  3697. ),
  3698. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3699. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3700. dx = this._rebound(minOffset.x, -maxOffset.x),
  3701. dy = this._rebound(minOffset.y, -maxOffset.y);
  3702. return new Point(dx, dy);
  3703. },
  3704. _rebound: function (left, right) {
  3705. return left + right > 0 ?
  3706. Math.round(left - right) / 2 :
  3707. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3708. },
  3709. _limitZoom: function (zoom) {
  3710. var min = this.getMinZoom(),
  3711. max = this.getMaxZoom(),
  3712. snap = any3d ? this.options.zoomSnap : 1;
  3713. if (snap) {
  3714. zoom = Math.round(zoom / snap) * snap;
  3715. }
  3716. return Math.max(min, Math.min(max, zoom));
  3717. },
  3718. _onPanTransitionStep: function () {
  3719. this.fire('move');
  3720. },
  3721. _onPanTransitionEnd: function () {
  3722. removeClass(this._mapPane, 'leaflet-pan-anim');
  3723. this.fire('moveend');
  3724. },
  3725. _tryAnimatedPan: function (center, options) {
  3726. // difference between the new and current centers in pixels
  3727. var offset = this._getCenterOffset(center)._floor();
  3728. // don't animate too far unless animate: true specified in options
  3729. if ((options && options.animate) !== true && !this.getSize().contains(offset)) {
  3730. return false;
  3731. }
  3732. this.panBy(offset, options);
  3733. return true;
  3734. },
  3735. _createAnimProxy: function () {
  3736. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3737. this._panes.mapPane.appendChild(proxy);
  3738. this.on('zoomanim', function (e) {
  3739. var prop = TRANSFORM,
  3740. transform = this._proxy.style[prop];
  3741. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3742. // workaround for case when transform is the same and so transitionend event is not fired
  3743. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3744. this._onZoomTransitionEnd();
  3745. }
  3746. }, this);
  3747. this.on('load moveend', function () {
  3748. var c = this.getCenter(),
  3749. z = this.getZoom();
  3750. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3751. }, this);
  3752. this._on('unload', this._destroyAnimProxy, this);
  3753. },
  3754. _destroyAnimProxy: function () {
  3755. remove(this._proxy);
  3756. delete this._proxy;
  3757. },
  3758. _catchTransitionEnd: function (e) {
  3759. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3760. this._onZoomTransitionEnd();
  3761. }
  3762. },
  3763. _nothingToAnimate: function () {
  3764. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3765. },
  3766. _tryAnimatedZoom: function (center, zoom, options) {
  3767. if (this._animatingZoom) {
  3768. return true;
  3769. }
  3770. options = options || {};
  3771. // don't animate if disabled, not supported or zoom difference is too large
  3772. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3773. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) {
  3774. return false;
  3775. }
  3776. // offset is the pixel coords of the zoom origin relative to the current center
  3777. var scale = this.getZoomScale(zoom),
  3778. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3779. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3780. if (options.animate !== true && !this.getSize().contains(offset)) {
  3781. return false;
  3782. }
  3783. requestAnimFrame(function () {
  3784. this
  3785. ._moveStart(true)
  3786. ._animateZoom(center, zoom, true);
  3787. }, this);
  3788. return true;
  3789. },
  3790. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3791. if (startAnim) {
  3792. this._animatingZoom = true;
  3793. // remember what center/zoom to set after animation
  3794. this._animateToCenter = center;
  3795. this._animateToZoom = zoom;
  3796. addClass(this._mapPane, 'leaflet-zoom-anim');
  3797. }
  3798. // @event zoomanim: ZoomAnimEvent
  3799. // Fired on every frame of a zoom animation
  3800. this.fire('zoomanim', {
  3801. center: center,
  3802. zoom: zoom,
  3803. noUpdate: noUpdate
  3804. });
  3805. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3806. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3807. },
  3808. _onZoomTransitionEnd: function () {
  3809. if (!this._animatingZoom) {
  3810. return;
  3811. }
  3812. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3813. this._animatingZoom = false;
  3814. this._move(this._animateToCenter, this._animateToZoom);
  3815. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  3816. requestAnimFrame(function () {
  3817. this._moveEnd(true);
  3818. }, this);
  3819. }
  3820. });
  3821. // @section
  3822. // @factory L.map(id: String, options?: Map options)
  3823. // Instantiates a map object given the DOM ID of a `<div>` element
  3824. // and optionally an object literal with `Map options`.
  3825. //
  3826. // @alternative
  3827. // @factory L.map(el: HTMLElement, options?: Map options)
  3828. // Instantiates a map object given an instance of a `<div>` HTML element
  3829. // and optionally an object literal with `Map options`.
  3830. function createMap(id, options) {
  3831. return new Map(id, options);
  3832. }
  3833. /*
  3834. * @class Control
  3835. * @aka L.Control
  3836. * @inherits Class
  3837. *
  3838. * L.Control is a base class for implementing map controls. Handles positioning.
  3839. * All other controls extend from this class.
  3840. */
  3841. var Control = Class.extend({
  3842. // @section
  3843. // @aka Control options
  3844. options: {
  3845. // @option position: String = 'topright'
  3846. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  3847. // `'topright'`, `'bottomleft'` or `'bottomright'`
  3848. position: 'topright'
  3849. },
  3850. initialize: function (options) {
  3851. setOptions(this, options);
  3852. },
  3853. /* @section
  3854. * Classes extending L.Control will inherit the following methods:
  3855. *
  3856. * @method getPosition: string
  3857. * Returns the position of the control.
  3858. */
  3859. getPosition: function () {
  3860. return this.options.position;
  3861. },
  3862. // @method setPosition(position: string): this
  3863. // Sets the position of the control.
  3864. setPosition: function (position) {
  3865. var map = this._map;
  3866. if (map) {
  3867. map.removeControl(this);
  3868. }
  3869. this.options.position = position;
  3870. if (map) {
  3871. map.addControl(this);
  3872. }
  3873. return this;
  3874. },
  3875. // @method getContainer: HTMLElement
  3876. // Returns the HTMLElement that contains the control.
  3877. getContainer: function () {
  3878. return this._container;
  3879. },
  3880. // @method addTo(map: Map): this
  3881. // Adds the control to the given map.
  3882. addTo: function (map) {
  3883. this.remove();
  3884. this._map = map;
  3885. var container = this._container = this.onAdd(map),
  3886. pos = this.getPosition(),
  3887. corner = map._controlCorners[pos];
  3888. addClass(container, 'leaflet-control');
  3889. if (pos.indexOf('bottom') !== -1) {
  3890. corner.insertBefore(container, corner.firstChild);
  3891. } else {
  3892. corner.appendChild(container);
  3893. }
  3894. return this;
  3895. },
  3896. // @method remove: this
  3897. // Removes the control from the map it is currently active on.
  3898. remove: function () {
  3899. if (!this._map) {
  3900. return this;
  3901. }
  3902. remove(this._container);
  3903. if (this.onRemove) {
  3904. this.onRemove(this._map);
  3905. }
  3906. this._map = null;
  3907. return this;
  3908. },
  3909. _refocusOnMap: function (e) {
  3910. // if map exists and event is not a keyboard event
  3911. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  3912. this._map.getContainer().focus();
  3913. }
  3914. }
  3915. });
  3916. var control = function (options) {
  3917. return new Control(options);
  3918. };
  3919. /* @section Extension methods
  3920. * @uninheritable
  3921. *
  3922. * Every control should extend from `L.Control` and (re-)implement the following methods.
  3923. *
  3924. * @method onAdd(map: Map): HTMLElement
  3925. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  3926. *
  3927. * @method onRemove(map: Map)
  3928. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  3929. */
  3930. /* @namespace Map
  3931. * @section Methods for Layers and Controls
  3932. */
  3933. Map.include({
  3934. // @method addControl(control: Control): this
  3935. // Adds the given control to the map
  3936. addControl: function (control) {
  3937. control.addTo(this);
  3938. return this;
  3939. },
  3940. // @method removeControl(control: Control): this
  3941. // Removes the given control from the map
  3942. removeControl: function (control) {
  3943. control.remove();
  3944. return this;
  3945. },
  3946. _initControlPos: function () {
  3947. var corners = this._controlCorners = {},
  3948. l = 'leaflet-',
  3949. container = this._controlContainer =
  3950. create$1('div', l + 'control-container', this._container);
  3951. function createCorner(vSide, hSide) {
  3952. var className = l + vSide + ' ' + l + hSide;
  3953. corners[vSide + hSide] = create$1('div', className, container);
  3954. }
  3955. createCorner('top', 'left');
  3956. createCorner('top', 'right');
  3957. createCorner('bottom', 'left');
  3958. createCorner('bottom', 'right');
  3959. },
  3960. _clearControlPos: function () {
  3961. for (var i in this._controlCorners) {
  3962. remove(this._controlCorners[i]);
  3963. }
  3964. remove(this._controlContainer);
  3965. delete this._controlCorners;
  3966. delete this._controlContainer;
  3967. }
  3968. });
  3969. /*
  3970. * @class Control.Layers
  3971. * @aka L.Control.Layers
  3972. * @inherits Control
  3973. *
  3974. * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control/)). Extends `Control`.
  3975. *
  3976. * @example
  3977. *
  3978. * ```js
  3979. * var baseLayers = {
  3980. * "Mapbox": mapbox,
  3981. * "OpenStreetMap": osm
  3982. * };
  3983. *
  3984. * var overlays = {
  3985. * "Marker": marker,
  3986. * "Roads": roadsLayer
  3987. * };
  3988. *
  3989. * L.control.layers(baseLayers, overlays).addTo(map);
  3990. * ```
  3991. *
  3992. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  3993. *
  3994. * ```js
  3995. * {
  3996. * "<someName1>": layer1,
  3997. * "<someName2>": layer2
  3998. * }
  3999. * ```
  4000. *
  4001. * The layer names can contain HTML, which allows you to add additional styling to the items:
  4002. *
  4003. * ```js
  4004. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  4005. * ```
  4006. */
  4007. var Layers = Control.extend({
  4008. // @section
  4009. // @aka Control.Layers options
  4010. options: {
  4011. // @option collapsed: Boolean = true
  4012. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  4013. collapsed: true,
  4014. position: 'topright',
  4015. // @option autoZIndex: Boolean = true
  4016. // 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.
  4017. autoZIndex: true,
  4018. // @option hideSingleBase: Boolean = false
  4019. // If `true`, the base layers in the control will be hidden when there is only one.
  4020. hideSingleBase: false,
  4021. // @option sortLayers: Boolean = false
  4022. // Whether to sort the layers. When `false`, layers will keep the order
  4023. // in which they were added to the control.
  4024. sortLayers: false,
  4025. // @option sortFunction: Function = *
  4026. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  4027. // that will be used for sorting the layers, when `sortLayers` is `true`.
  4028. // The function receives both the `L.Layer` instances and their names, as in
  4029. // `sortFunction(layerA, layerB, nameA, nameB)`.
  4030. // By default, it sorts layers alphabetically by their name.
  4031. sortFunction: function (layerA, layerB, nameA, nameB) {
  4032. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  4033. }
  4034. },
  4035. initialize: function (baseLayers, overlays, options) {
  4036. setOptions(this, options);
  4037. this._layerControlInputs = [];
  4038. this._layers = [];
  4039. this._lastZIndex = 0;
  4040. this._handlingClick = false;
  4041. for (var i in baseLayers) {
  4042. this._addLayer(baseLayers[i], i);
  4043. }
  4044. for (i in overlays) {
  4045. this._addLayer(overlays[i], i, true);
  4046. }
  4047. },
  4048. onAdd: function (map) {
  4049. this._initLayout();
  4050. this._update();
  4051. this._map = map;
  4052. map.on('zoomend', this._checkDisabledLayers, this);
  4053. for (var i = 0; i < this._layers.length; i++) {
  4054. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4055. }
  4056. return this._container;
  4057. },
  4058. addTo: function (map) {
  4059. Control.prototype.addTo.call(this, map);
  4060. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4061. return this._expandIfNotCollapsed();
  4062. },
  4063. onRemove: function () {
  4064. this._map.off('zoomend', this._checkDisabledLayers, this);
  4065. for (var i = 0; i < this._layers.length; i++) {
  4066. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4067. }
  4068. },
  4069. // @method addBaseLayer(layer: Layer, name: String): this
  4070. // Adds a base layer (radio button entry) with the given name to the control.
  4071. addBaseLayer: function (layer, name) {
  4072. this._addLayer(layer, name);
  4073. return (this._map) ? this._update() : this;
  4074. },
  4075. // @method addOverlay(layer: Layer, name: String): this
  4076. // Adds an overlay (checkbox entry) with the given name to the control.
  4077. addOverlay: function (layer, name) {
  4078. this._addLayer(layer, name, true);
  4079. return (this._map) ? this._update() : this;
  4080. },
  4081. // @method removeLayer(layer: Layer): this
  4082. // Remove the given layer from the control.
  4083. removeLayer: function (layer) {
  4084. layer.off('add remove', this._onLayerChange, this);
  4085. var obj = this._getLayer(stamp(layer));
  4086. if (obj) {
  4087. this._layers.splice(this._layers.indexOf(obj), 1);
  4088. }
  4089. return (this._map) ? this._update() : this;
  4090. },
  4091. // @method expand(): this
  4092. // Expand the control container if collapsed.
  4093. expand: function () {
  4094. addClass(this._container, 'leaflet-control-layers-expanded');
  4095. this._form.style.height = null;
  4096. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4097. if (acceptableHeight < this._form.clientHeight) {
  4098. addClass(this._form, 'leaflet-control-layers-scrollbar');
  4099. this._form.style.height = acceptableHeight + 'px';
  4100. } else {
  4101. removeClass(this._form, 'leaflet-control-layers-scrollbar');
  4102. }
  4103. this._checkDisabledLayers();
  4104. return this;
  4105. },
  4106. // @method collapse(): this
  4107. // Collapse the control container if expanded.
  4108. collapse: function () {
  4109. removeClass(this._container, 'leaflet-control-layers-expanded');
  4110. return this;
  4111. },
  4112. _initLayout: function () {
  4113. var className = 'leaflet-control-layers',
  4114. container = this._container = create$1('div', className),
  4115. collapsed = this.options.collapsed;
  4116. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4117. container.setAttribute('aria-haspopup', true);
  4118. disableClickPropagation(container);
  4119. disableScrollPropagation(container);
  4120. var form = this._form = create$1('form', className + '-list');
  4121. if (collapsed) {
  4122. this._map.on('click', this.collapse, this);
  4123. if (!android) {
  4124. on(container, {
  4125. mouseenter: this.expand,
  4126. mouseleave: this.collapse
  4127. }, this);
  4128. }
  4129. }
  4130. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4131. link.href = '#';
  4132. link.title = 'Layers';
  4133. if (touch) {
  4134. on(link, 'click', stop);
  4135. on(link, 'click', this.expand, this);
  4136. } else {
  4137. on(link, 'focus', this.expand, this);
  4138. }
  4139. if (!collapsed) {
  4140. this.expand();
  4141. }
  4142. this._baseLayersList = create$1('div', className + '-base', form);
  4143. this._separator = create$1('div', className + '-separator', form);
  4144. this._overlaysList = create$1('div', className + '-overlays', form);
  4145. container.appendChild(form);
  4146. },
  4147. _getLayer: function (id) {
  4148. for (var i = 0; i < this._layers.length; i++) {
  4149. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4150. return this._layers[i];
  4151. }
  4152. }
  4153. },
  4154. _addLayer: function (layer, name, overlay) {
  4155. if (this._map) {
  4156. layer.on('add remove', this._onLayerChange, this);
  4157. }
  4158. this._layers.push({
  4159. layer: layer,
  4160. name: name,
  4161. overlay: overlay
  4162. });
  4163. if (this.options.sortLayers) {
  4164. this._layers.sort(bind(function (a, b) {
  4165. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4166. }, this));
  4167. }
  4168. if (this.options.autoZIndex && layer.setZIndex) {
  4169. this._lastZIndex++;
  4170. layer.setZIndex(this._lastZIndex);
  4171. }
  4172. this._expandIfNotCollapsed();
  4173. },
  4174. _update: function () {
  4175. if (!this._container) {
  4176. return this;
  4177. }
  4178. empty(this._baseLayersList);
  4179. empty(this._overlaysList);
  4180. this._layerControlInputs = [];
  4181. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4182. for (i = 0; i < this._layers.length; i++) {
  4183. obj = this._layers[i];
  4184. this._addItem(obj);
  4185. overlaysPresent = overlaysPresent || obj.overlay;
  4186. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4187. baseLayersCount += !obj.overlay ? 1 : 0;
  4188. }
  4189. // Hide base layers section if there's only one layer.
  4190. if (this.options.hideSingleBase) {
  4191. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4192. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4193. }
  4194. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4195. return this;
  4196. },
  4197. _onLayerChange: function (e) {
  4198. if (!this._handlingClick) {
  4199. this._update();
  4200. }
  4201. var obj = this._getLayer(stamp(e.target));
  4202. // @namespace Map
  4203. // @section Layer events
  4204. // @event baselayerchange: LayersControlEvent
  4205. // Fired when the base layer is changed through the [layer control](#control-layers).
  4206. // @event overlayadd: LayersControlEvent
  4207. // Fired when an overlay is selected through the [layer control](#control-layers).
  4208. // @event overlayremove: LayersControlEvent
  4209. // Fired when an overlay is deselected through the [layer control](#control-layers).
  4210. // @namespace Control.Layers
  4211. var type = obj.overlay ?
  4212. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4213. (e.type === 'add' ? 'baselayerchange' : null);
  4214. if (type) {
  4215. this._map.fire(type, obj);
  4216. }
  4217. },
  4218. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  4219. _createRadioElement: function (name, checked) {
  4220. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4221. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4222. var radioFragment = document.createElement('div');
  4223. radioFragment.innerHTML = radioHtml;
  4224. return radioFragment.firstChild;
  4225. },
  4226. _addItem: function (obj) {
  4227. var label = document.createElement('label'),
  4228. checked = this._map.hasLayer(obj.layer),
  4229. input;
  4230. if (obj.overlay) {
  4231. input = document.createElement('input');
  4232. input.type = 'checkbox';
  4233. input.className = 'leaflet-control-layers-selector';
  4234. input.defaultChecked = checked;
  4235. } else {
  4236. input = this._createRadioElement('leaflet-base-layers', checked);
  4237. }
  4238. this._layerControlInputs.push(input);
  4239. input.layerId = stamp(obj.layer);
  4240. on(input, 'click', this._onInputClick, this);
  4241. var name = document.createElement('span');
  4242. name.innerHTML = ' ' + obj.name;
  4243. // Helps from preventing layer control flicker when checkboxes are disabled
  4244. // https://github.com/Leaflet/Leaflet/issues/2771
  4245. var holder = document.createElement('div');
  4246. label.appendChild(holder);
  4247. holder.appendChild(input);
  4248. holder.appendChild(name);
  4249. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4250. container.appendChild(label);
  4251. this._checkDisabledLayers();
  4252. return label;
  4253. },
  4254. _onInputClick: function () {
  4255. var inputs = this._layerControlInputs,
  4256. input, layer;
  4257. var addedLayers = [],
  4258. removedLayers = [];
  4259. this._handlingClick = true;
  4260. for (var i = inputs.length - 1; i >= 0; i--) {
  4261. input = inputs[i];
  4262. layer = this._getLayer(input.layerId).layer;
  4263. if (input.checked) {
  4264. addedLayers.push(layer);
  4265. } else if (!input.checked) {
  4266. removedLayers.push(layer);
  4267. }
  4268. }
  4269. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4270. for (i = 0; i < removedLayers.length; i++) {
  4271. if (this._map.hasLayer(removedLayers[i])) {
  4272. this._map.removeLayer(removedLayers[i]);
  4273. }
  4274. }
  4275. for (i = 0; i < addedLayers.length; i++) {
  4276. if (!this._map.hasLayer(addedLayers[i])) {
  4277. this._map.addLayer(addedLayers[i]);
  4278. }
  4279. }
  4280. this._handlingClick = false;
  4281. this._refocusOnMap();
  4282. },
  4283. _checkDisabledLayers: function () {
  4284. var inputs = this._layerControlInputs,
  4285. input,
  4286. layer,
  4287. zoom = this._map.getZoom();
  4288. for (var i = inputs.length - 1; i >= 0; i--) {
  4289. input = inputs[i];
  4290. layer = this._getLayer(input.layerId).layer;
  4291. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4292. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4293. }
  4294. },
  4295. _expandIfNotCollapsed: function () {
  4296. if (this._map && !this.options.collapsed) {
  4297. this.expand();
  4298. }
  4299. return this;
  4300. },
  4301. _expand: function () {
  4302. // Backward compatibility, remove me in 1.1.
  4303. return this.expand();
  4304. },
  4305. _collapse: function () {
  4306. // Backward compatibility, remove me in 1.1.
  4307. return this.collapse();
  4308. }
  4309. });
  4310. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4311. // Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
  4312. var layers = function (baseLayers, overlays, options) {
  4313. return new Layers(baseLayers, overlays, options);
  4314. };
  4315. /*
  4316. * @class Control.Zoom
  4317. * @aka L.Control.Zoom
  4318. * @inherits Control
  4319. *
  4320. * 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`.
  4321. */
  4322. var Zoom = Control.extend({
  4323. // @section
  4324. // @aka Control.Zoom options
  4325. options: {
  4326. position: 'topleft',
  4327. // @option zoomInText: String = '+'
  4328. // The text set on the 'zoom in' button.
  4329. zoomInText: '+',
  4330. // @option zoomInTitle: String = 'Zoom in'
  4331. // The title set on the 'zoom in' button.
  4332. zoomInTitle: 'Zoom in',
  4333. // @option zoomOutText: String = '&#x2212;'
  4334. // The text set on the 'zoom out' button.
  4335. zoomOutText: '&#x2212;',
  4336. // @option zoomOutTitle: String = 'Zoom out'
  4337. // The title set on the 'zoom out' button.
  4338. zoomOutTitle: 'Zoom out'
  4339. },
  4340. onAdd: function (map) {
  4341. var zoomName = 'leaflet-control-zoom',
  4342. container = create$1('div', zoomName + ' leaflet-bar'),
  4343. options = this.options;
  4344. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4345. zoomName + '-in', container, this._zoomIn);
  4346. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4347. zoomName + '-out', container, this._zoomOut);
  4348. this._updateDisabled();
  4349. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4350. return container;
  4351. },
  4352. onRemove: function (map) {
  4353. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4354. },
  4355. disable: function () {
  4356. this._disabled = true;
  4357. this._updateDisabled();
  4358. return this;
  4359. },
  4360. enable: function () {
  4361. this._disabled = false;
  4362. this._updateDisabled();
  4363. return this;
  4364. },
  4365. _zoomIn: function (e) {
  4366. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4367. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4368. }
  4369. },
  4370. _zoomOut: function (e) {
  4371. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4372. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4373. }
  4374. },
  4375. _createButton: function (html, title, className, container, fn) {
  4376. var link = create$1('a', className, container);
  4377. link.innerHTML = html;
  4378. link.href = '#';
  4379. link.title = title;
  4380. /*
  4381. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4382. */
  4383. link.setAttribute('role', 'button');
  4384. link.setAttribute('aria-label', title);
  4385. disableClickPropagation(link);
  4386. on(link, 'click', stop);
  4387. on(link, 'click', fn, this);
  4388. on(link, 'click', this._refocusOnMap, this);
  4389. return link;
  4390. },
  4391. _updateDisabled: function () {
  4392. var map = this._map,
  4393. className = 'leaflet-disabled';
  4394. removeClass(this._zoomInButton, className);
  4395. removeClass(this._zoomOutButton, className);
  4396. if (this._disabled || map._zoom === map.getMinZoom()) {
  4397. addClass(this._zoomOutButton, className);
  4398. }
  4399. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4400. addClass(this._zoomInButton, className);
  4401. }
  4402. }
  4403. });
  4404. // @namespace Map
  4405. // @section Control options
  4406. // @option zoomControl: Boolean = true
  4407. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4408. Map.mergeOptions({
  4409. zoomControl: true
  4410. });
  4411. Map.addInitHook(function () {
  4412. if (this.options.zoomControl) {
  4413. this.zoomControl = new Zoom();
  4414. this.addControl(this.zoomControl);
  4415. }
  4416. });
  4417. // @namespace Control.Zoom
  4418. // @factory L.control.zoom(options: Control.Zoom options)
  4419. // Creates a zoom control
  4420. var zoom = function (options) {
  4421. return new Zoom(options);
  4422. };
  4423. /*
  4424. * @class Control.Scale
  4425. * @aka L.Control.Scale
  4426. * @inherits Control
  4427. *
  4428. * 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`.
  4429. *
  4430. * @example
  4431. *
  4432. * ```js
  4433. * L.control.scale().addTo(map);
  4434. * ```
  4435. */
  4436. var Scale = Control.extend({
  4437. // @section
  4438. // @aka Control.Scale options
  4439. options: {
  4440. position: 'bottomleft',
  4441. // @option maxWidth: Number = 100
  4442. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4443. maxWidth: 100,
  4444. // @option metric: Boolean = True
  4445. // Whether to show the metric scale line (m/km).
  4446. metric: true,
  4447. // @option imperial: Boolean = True
  4448. // Whether to show the imperial scale line (mi/ft).
  4449. imperial: true
  4450. // @option updateWhenIdle: Boolean = false
  4451. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4452. },
  4453. onAdd: function (map) {
  4454. var className = 'leaflet-control-scale',
  4455. container = create$1('div', className),
  4456. options = this.options;
  4457. this._addScales(options, className + '-line', container);
  4458. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4459. map.whenReady(this._update, this);
  4460. return container;
  4461. },
  4462. onRemove: function (map) {
  4463. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4464. },
  4465. _addScales: function (options, className, container) {
  4466. if (options.metric) {
  4467. this._mScale = create$1('div', className, container);
  4468. }
  4469. if (options.imperial) {
  4470. this._iScale = create$1('div', className, container);
  4471. }
  4472. },
  4473. _update: function () {
  4474. var map = this._map,
  4475. y = map.getSize().y / 2;
  4476. var maxMeters = map.distance(
  4477. map.containerPointToLatLng([0, y]),
  4478. map.containerPointToLatLng([this.options.maxWidth, y]));
  4479. this._updateScales(maxMeters);
  4480. },
  4481. _updateScales: function (maxMeters) {
  4482. if (this.options.metric && maxMeters) {
  4483. this._updateMetric(maxMeters);
  4484. }
  4485. if (this.options.imperial && maxMeters) {
  4486. this._updateImperial(maxMeters);
  4487. }
  4488. },
  4489. _updateMetric: function (maxMeters) {
  4490. var meters = this._getRoundNum(maxMeters),
  4491. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4492. this._updateScale(this._mScale, label, meters / maxMeters);
  4493. },
  4494. _updateImperial: function (maxMeters) {
  4495. var maxFeet = maxMeters * 3.2808399,
  4496. maxMiles, miles, feet;
  4497. if (maxFeet > 5280) {
  4498. maxMiles = maxFeet / 5280;
  4499. miles = this._getRoundNum(maxMiles);
  4500. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4501. } else {
  4502. feet = this._getRoundNum(maxFeet);
  4503. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4504. }
  4505. },
  4506. _updateScale: function (scale, text, ratio) {
  4507. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4508. scale.innerHTML = text;
  4509. },
  4510. _getRoundNum: function (num) {
  4511. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4512. d = num / pow10;
  4513. d = d >= 10 ? 10 :
  4514. d >= 5 ? 5 :
  4515. d >= 3 ? 3 :
  4516. d >= 2 ? 2 : 1;
  4517. return pow10 * d;
  4518. }
  4519. });
  4520. // @factory L.control.scale(options?: Control.Scale options)
  4521. // Creates an scale control with the given options.
  4522. var scale = function (options) {
  4523. return new Scale(options);
  4524. };
  4525. /*
  4526. * @class Control.Attribution
  4527. * @aka L.Control.Attribution
  4528. * @inherits Control
  4529. *
  4530. * 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.
  4531. */
  4532. var Attribution = Control.extend({
  4533. // @section
  4534. // @aka Control.Attribution options
  4535. options: {
  4536. position: 'bottomright',
  4537. // @option prefix: String = 'Leaflet'
  4538. // The HTML text shown before the attributions. Pass `false` to disable.
  4539. prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  4540. },
  4541. initialize: function (options) {
  4542. setOptions(this, options);
  4543. this._attributions = {};
  4544. },
  4545. onAdd: function (map) {
  4546. map.attributionControl = this;
  4547. this._container = create$1('div', 'leaflet-control-attribution');
  4548. disableClickPropagation(this._container);
  4549. // TODO ugly, refactor
  4550. for (var i in map._layers) {
  4551. if (map._layers[i].getAttribution) {
  4552. this.addAttribution(map._layers[i].getAttribution());
  4553. }
  4554. }
  4555. this._update();
  4556. return this._container;
  4557. },
  4558. // @method setPrefix(prefix: String): this
  4559. // Sets the text before the attributions.
  4560. setPrefix: function (prefix) {
  4561. this.options.prefix = prefix;
  4562. this._update();
  4563. return this;
  4564. },
  4565. // @method addAttribution(text: String): this
  4566. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  4567. addAttribution: function (text) {
  4568. if (!text) {
  4569. return this;
  4570. }
  4571. if (!this._attributions[text]) {
  4572. this._attributions[text] = 0;
  4573. }
  4574. this._attributions[text]++;
  4575. this._update();
  4576. return this;
  4577. },
  4578. // @method removeAttribution(text: String): this
  4579. // Removes an attribution text.
  4580. removeAttribution: function (text) {
  4581. if (!text) {
  4582. return this;
  4583. }
  4584. if (this._attributions[text]) {
  4585. this._attributions[text]--;
  4586. this._update();
  4587. }
  4588. return this;
  4589. },
  4590. _update: function () {
  4591. if (!this._map) {
  4592. return;
  4593. }
  4594. var attribs = [];
  4595. for (var i in this._attributions) {
  4596. if (this._attributions[i]) {
  4597. attribs.push(i);
  4598. }
  4599. }
  4600. var prefixAndAttribs = [];
  4601. if (this.options.prefix) {
  4602. prefixAndAttribs.push(this.options.prefix);
  4603. }
  4604. if (attribs.length) {
  4605. prefixAndAttribs.push(attribs.join(', '));
  4606. }
  4607. this._container.innerHTML = prefixAndAttribs.join(' | ');
  4608. }
  4609. });
  4610. // @namespace Map
  4611. // @section Control options
  4612. // @option attributionControl: Boolean = true
  4613. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4614. Map.mergeOptions({
  4615. attributionControl: true
  4616. });
  4617. Map.addInitHook(function () {
  4618. if (this.options.attributionControl) {
  4619. new Attribution().addTo(this);
  4620. }
  4621. });
  4622. // @namespace Control.Attribution
  4623. // @factory L.control.attribution(options: Control.Attribution options)
  4624. // Creates an attribution control.
  4625. var attribution = function (options) {
  4626. return new Attribution(options);
  4627. };
  4628. Control.Layers = Layers;
  4629. Control.Zoom = Zoom;
  4630. Control.Scale = Scale;
  4631. Control.Attribution = Attribution;
  4632. control.layers = layers;
  4633. control.zoom = zoom;
  4634. control.scale = scale;
  4635. control.attribution = attribution;
  4636. /*
  4637. L.Handler is a base class for handler classes that are used internally to inject
  4638. interaction features like dragging to classes like Map and Marker.
  4639. */
  4640. // @class Handler
  4641. // @aka L.Handler
  4642. // Abstract class for map interaction handlers
  4643. var Handler = Class.extend({
  4644. initialize: function (map) {
  4645. this._map = map;
  4646. },
  4647. // @method enable(): this
  4648. // Enables the handler
  4649. enable: function () {
  4650. if (this._enabled) {
  4651. return this;
  4652. }
  4653. this._enabled = true;
  4654. this.addHooks();
  4655. return this;
  4656. },
  4657. // @method disable(): this
  4658. // Disables the handler
  4659. disable: function () {
  4660. if (!this._enabled) {
  4661. return this;
  4662. }
  4663. this._enabled = false;
  4664. this.removeHooks();
  4665. return this;
  4666. },
  4667. // @method enabled(): Boolean
  4668. // Returns `true` if the handler is enabled
  4669. enabled: function () {
  4670. return !!this._enabled;
  4671. }
  4672. // @section Extension methods
  4673. // Classes inheriting from `Handler` must implement the two following methods:
  4674. // @method addHooks()
  4675. // Called when the handler is enabled, should add event hooks.
  4676. // @method removeHooks()
  4677. // Called when the handler is disabled, should remove the event hooks added previously.
  4678. });
  4679. var Mixin = {Events: Events};
  4680. /*
  4681. * @class Draggable
  4682. * @aka L.Draggable
  4683. * @inherits Evented
  4684. *
  4685. * A class for making DOM elements draggable (including touch support).
  4686. * Used internally for map and marker dragging. Only works for elements
  4687. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4688. *
  4689. * @example
  4690. * ```js
  4691. * var draggable = new L.Draggable(elementToDrag);
  4692. * draggable.enable();
  4693. * ```
  4694. */
  4695. var START = touch ? 'touchstart mousedown' : 'mousedown';
  4696. var END = {
  4697. mousedown: 'mouseup',
  4698. touchstart: 'touchend',
  4699. pointerdown: 'touchend',
  4700. MSPointerDown: 'touchend'
  4701. };
  4702. var MOVE = {
  4703. mousedown: 'mousemove',
  4704. touchstart: 'touchmove',
  4705. pointerdown: 'touchmove',
  4706. MSPointerDown: 'touchmove'
  4707. };
  4708. var Draggable = Evented.extend({
  4709. options: {
  4710. // @section
  4711. // @aka Draggable options
  4712. // @option clickTolerance: Number = 3
  4713. // The max number of pixels a user can shift the mouse pointer during a click
  4714. // for it to be considered a valid click (as opposed to a mouse drag).
  4715. clickTolerance: 3
  4716. },
  4717. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4718. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4719. initialize: function (element, dragStartTarget, preventOutline$$1, options) {
  4720. setOptions(this, options);
  4721. this._element = element;
  4722. this._dragStartTarget = dragStartTarget || element;
  4723. this._preventOutline = preventOutline$$1;
  4724. },
  4725. // @method enable()
  4726. // Enables the dragging ability
  4727. enable: function () {
  4728. if (this._enabled) {
  4729. return;
  4730. }
  4731. on(this._dragStartTarget, START, this._onDown, this);
  4732. this._enabled = true;
  4733. },
  4734. // @method disable()
  4735. // Disables the dragging ability
  4736. disable: function () {
  4737. if (!this._enabled) {
  4738. return;
  4739. }
  4740. // If we're currently dragging this draggable,
  4741. // disabling it counts as first ending the drag.
  4742. if (Draggable._dragging === this) {
  4743. this.finishDrag();
  4744. }
  4745. off(this._dragStartTarget, START, this._onDown, this);
  4746. this._enabled = false;
  4747. this._moved = false;
  4748. },
  4749. _onDown: function (e) {
  4750. // Ignore simulated events, since we handle both touch and
  4751. // mouse explicitly; otherwise we risk getting duplicates of
  4752. // touch events, see #4315.
  4753. // Also ignore the event if disabled; this happens in IE11
  4754. // under some circumstances, see #3666.
  4755. if (e._simulated || !this._enabled) {
  4756. return;
  4757. }
  4758. this._moved = false;
  4759. if (hasClass(this._element, 'leaflet-zoom-anim')) {
  4760. return;
  4761. }
  4762. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) {
  4763. return;
  4764. }
  4765. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4766. if (this._preventOutline) {
  4767. preventOutline(this._element);
  4768. }
  4769. disableImageDrag();
  4770. disableTextSelection();
  4771. if (this._moving) {
  4772. return;
  4773. }
  4774. // @event down: Event
  4775. // Fired when a drag is about to start.
  4776. this.fire('down');
  4777. var first = e.touches ? e.touches[0] : e;
  4778. this._startPoint = new Point(first.clientX, first.clientY);
  4779. on(document, MOVE[e.type], this._onMove, this);
  4780. on(document, END[e.type], this._onUp, this);
  4781. },
  4782. _onMove: function (e) {
  4783. // Ignore simulated events, since we handle both touch and
  4784. // mouse explicitly; otherwise we risk getting duplicates of
  4785. // touch events, see #4315.
  4786. // Also ignore the event if disabled; this happens in IE11
  4787. // under some circumstances, see #3666.
  4788. if (e._simulated || !this._enabled) {
  4789. return;
  4790. }
  4791. if (e.touches && e.touches.length > 1) {
  4792. this._moved = true;
  4793. return;
  4794. }
  4795. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4796. newPoint = new Point(first.clientX, first.clientY),
  4797. offset = newPoint.subtract(this._startPoint);
  4798. if (!offset.x && !offset.y) {
  4799. return;
  4800. }
  4801. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) {
  4802. return;
  4803. }
  4804. preventDefault(e);
  4805. if (!this._moved) {
  4806. // @event dragstart: Event
  4807. // Fired when a drag starts
  4808. this.fire('dragstart');
  4809. this._moved = true;
  4810. this._startPos = getPosition(this._element).subtract(offset);
  4811. addClass(document.body, 'leaflet-dragging');
  4812. this._lastTarget = e.target || e.srcElement;
  4813. // IE and Edge do not give the <use> element, so fetch it
  4814. // if necessary
  4815. if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
  4816. this._lastTarget = this._lastTarget.correspondingUseElement;
  4817. }
  4818. addClass(this._lastTarget, 'leaflet-drag-target');
  4819. }
  4820. this._newPos = this._startPos.add(offset);
  4821. this._moving = true;
  4822. cancelAnimFrame(this._animRequest);
  4823. this._lastEvent = e;
  4824. this._animRequest = requestAnimFrame(this._updatePosition, this, true);
  4825. },
  4826. _updatePosition: function () {
  4827. var e = {originalEvent: this._lastEvent};
  4828. // @event predrag: Event
  4829. // Fired continuously during dragging *before* each corresponding
  4830. // update of the element's position.
  4831. this.fire('predrag', e);
  4832. setPosition(this._element, this._newPos);
  4833. // @event drag: Event
  4834. // Fired continuously during dragging.
  4835. this.fire('drag', e);
  4836. },
  4837. _onUp: function (e) {
  4838. // Ignore simulated events, since we handle both touch and
  4839. // mouse explicitly; otherwise we risk getting duplicates of
  4840. // touch events, see #4315.
  4841. // Also ignore the event if disabled; this happens in IE11
  4842. // under some circumstances, see #3666.
  4843. if (e._simulated || !this._enabled) {
  4844. return;
  4845. }
  4846. this.finishDrag();
  4847. },
  4848. finishDrag: function () {
  4849. removeClass(document.body, 'leaflet-dragging');
  4850. if (this._lastTarget) {
  4851. removeClass(this._lastTarget, 'leaflet-drag-target');
  4852. this._lastTarget = null;
  4853. }
  4854. for (var i in MOVE) {
  4855. off(document, MOVE[i], this._onMove, this);
  4856. off(document, END[i], this._onUp, this);
  4857. }
  4858. enableImageDrag();
  4859. enableTextSelection();
  4860. if (this._moved && this._moving) {
  4861. // ensure drag is not fired after dragend
  4862. cancelAnimFrame(this._animRequest);
  4863. // @event dragend: DragEndEvent
  4864. // Fired when the drag ends.
  4865. this.fire('dragend', {
  4866. distance: this._newPos.distanceTo(this._startPos)
  4867. });
  4868. }
  4869. this._moving = false;
  4870. Draggable._dragging = false;
  4871. }
  4872. });
  4873. /*
  4874. * @namespace LineUtil
  4875. *
  4876. * Various utility functions for polyine points processing, used by Leaflet internally to make polylines lightning-fast.
  4877. */
  4878. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  4879. // Improves rendering performance dramatically by lessening the number of points to draw.
  4880. // @function simplify(points: Point[], tolerance: Number): Point[]
  4881. // Dramatically reduces the number of points in a polyline while retaining
  4882. // its shape and returns a new array of simplified points, using the
  4883. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  4884. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  4885. // each zoom level and also reducing visual noise. tolerance affects the amount of
  4886. // simplification (lesser value means higher quality but slower and with more points).
  4887. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  4888. function simplify(points, tolerance) {
  4889. if (!tolerance || !points.length) {
  4890. return points.slice();
  4891. }
  4892. var sqTolerance = tolerance * tolerance;
  4893. // stage 1: vertex reduction
  4894. points = _reducePoints(points, sqTolerance);
  4895. // stage 2: Douglas-Peucker simplification
  4896. points = _simplifyDP(points, sqTolerance);
  4897. return points;
  4898. }
  4899. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  4900. // Returns the distance between point `p` and segment `p1` to `p2`.
  4901. function pointToSegmentDistance(p, p1, p2) {
  4902. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  4903. }
  4904. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  4905. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  4906. function closestPointOnSegment(p, p1, p2) {
  4907. return _sqClosestPointOnSegment(p, p1, p2);
  4908. }
  4909. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  4910. function _simplifyDP(points, sqTolerance) {
  4911. var len = points.length,
  4912. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  4913. markers = new ArrayConstructor(len);
  4914. markers[0] = markers[len - 1] = 1;
  4915. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  4916. var i,
  4917. newPoints = [];
  4918. for (i = 0; i < len; i++) {
  4919. if (markers[i]) {
  4920. newPoints.push(points[i]);
  4921. }
  4922. }
  4923. return newPoints;
  4924. }
  4925. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  4926. var maxSqDist = 0,
  4927. index, i, sqDist;
  4928. for (i = first + 1; i <= last - 1; i++) {
  4929. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  4930. if (sqDist > maxSqDist) {
  4931. index = i;
  4932. maxSqDist = sqDist;
  4933. }
  4934. }
  4935. if (maxSqDist > sqTolerance) {
  4936. markers[index] = 1;
  4937. _simplifyDPStep(points, markers, sqTolerance, first, index);
  4938. _simplifyDPStep(points, markers, sqTolerance, index, last);
  4939. }
  4940. }
  4941. // reduce points that are too close to each other to a single point
  4942. function _reducePoints(points, sqTolerance) {
  4943. var reducedPoints = [points[0]];
  4944. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  4945. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  4946. reducedPoints.push(points[i]);
  4947. prev = i;
  4948. }
  4949. }
  4950. if (prev < len - 1) {
  4951. reducedPoints.push(points[len - 1]);
  4952. }
  4953. return reducedPoints;
  4954. }
  4955. var _lastCode;
  4956. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  4957. // Clips the segment a to b by rectangular bounds with the
  4958. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  4959. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  4960. // points that are on the screen or near, increasing performance.
  4961. function clipSegment(a, b, bounds, useLastCode, round) {
  4962. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  4963. codeB = _getBitCode(b, bounds),
  4964. codeOut, p, newCode;
  4965. // save 2nd code to avoid calculating it on the next segment
  4966. _lastCode = codeB;
  4967. while (true) {
  4968. // if a,b is inside the clip window (trivial accept)
  4969. if (!(codeA | codeB)) {
  4970. return [a, b];
  4971. }
  4972. // if a,b is outside the clip window (trivial reject)
  4973. if (codeA & codeB) {
  4974. return false;
  4975. }
  4976. // other cases
  4977. codeOut = codeA || codeB;
  4978. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  4979. newCode = _getBitCode(p, bounds);
  4980. if (codeOut === codeA) {
  4981. a = p;
  4982. codeA = newCode;
  4983. } else {
  4984. b = p;
  4985. codeB = newCode;
  4986. }
  4987. }
  4988. }
  4989. function _getEdgeIntersection(a, b, code, bounds, round) {
  4990. var dx = b.x - a.x,
  4991. dy = b.y - a.y,
  4992. min = bounds.min,
  4993. max = bounds.max,
  4994. x, y;
  4995. if (code & 8) { // top
  4996. x = a.x + dx * (max.y - a.y) / dy;
  4997. y = max.y;
  4998. } else if (code & 4) { // bottom
  4999. x = a.x + dx * (min.y - a.y) / dy;
  5000. y = min.y;
  5001. } else if (code & 2) { // right
  5002. x = max.x;
  5003. y = a.y + dy * (max.x - a.x) / dx;
  5004. } else if (code & 1) { // left
  5005. x = min.x;
  5006. y = a.y + dy * (min.x - a.x) / dx;
  5007. }
  5008. return new Point(x, y, round);
  5009. }
  5010. function _getBitCode(p, bounds) {
  5011. var code = 0;
  5012. if (p.x < bounds.min.x) { // left
  5013. code |= 1;
  5014. } else if (p.x > bounds.max.x) { // right
  5015. code |= 2;
  5016. }
  5017. if (p.y < bounds.min.y) { // bottom
  5018. code |= 4;
  5019. } else if (p.y > bounds.max.y) { // top
  5020. code |= 8;
  5021. }
  5022. return code;
  5023. }
  5024. // square distance (to avoid unnecessary Math.sqrt calls)
  5025. function _sqDist(p1, p2) {
  5026. var dx = p2.x - p1.x,
  5027. dy = p2.y - p1.y;
  5028. return dx * dx + dy * dy;
  5029. }
  5030. // return closest point on segment or distance to that point
  5031. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  5032. var x = p1.x,
  5033. y = p1.y,
  5034. dx = p2.x - x,
  5035. dy = p2.y - y,
  5036. dot = dx * dx + dy * dy,
  5037. t;
  5038. if (dot > 0) {
  5039. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  5040. if (t > 1) {
  5041. x = p2.x;
  5042. y = p2.y;
  5043. } else if (t > 0) {
  5044. x += dx * t;
  5045. y += dy * t;
  5046. }
  5047. }
  5048. dx = p.x - x;
  5049. dy = p.y - y;
  5050. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  5051. }
  5052. // @function isFlat(latlngs: LatLng[]): Boolean
  5053. // Returns true if `latlngs` is a flat array, false is nested.
  5054. function isFlat(latlngs) {
  5055. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  5056. }
  5057. function _flat(latlngs) {
  5058. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  5059. return isFlat(latlngs);
  5060. }
  5061. var LineUtil = (Object.freeze || Object)({
  5062. simplify: simplify,
  5063. pointToSegmentDistance: pointToSegmentDistance,
  5064. closestPointOnSegment: closestPointOnSegment,
  5065. clipSegment: clipSegment,
  5066. _getEdgeIntersection: _getEdgeIntersection,
  5067. _getBitCode: _getBitCode,
  5068. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5069. isFlat: isFlat,
  5070. _flat: _flat
  5071. });
  5072. /*
  5073. * @namespace PolyUtil
  5074. * Various utility functions for polygon geometries.
  5075. */
  5076. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5077. * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgeman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).
  5078. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5079. * performance. Note that polygon points needs different algorithm for clipping
  5080. * than polyline, so there's a seperate method for it.
  5081. */
  5082. function clipPolygon(points, bounds, round) {
  5083. var clippedPoints,
  5084. edges = [1, 4, 2, 8],
  5085. i, j, k,
  5086. a, b,
  5087. len, edge, p;
  5088. for (i = 0, len = points.length; i < len; i++) {
  5089. points[i]._code = _getBitCode(points[i], bounds);
  5090. }
  5091. // for each edge (left, bottom, right, top)
  5092. for (k = 0; k < 4; k++) {
  5093. edge = edges[k];
  5094. clippedPoints = [];
  5095. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5096. a = points[i];
  5097. b = points[j];
  5098. // if a is inside the clip window
  5099. if (!(a._code & edge)) {
  5100. // if b is outside the clip window (a->b goes out of screen)
  5101. if (b._code & edge) {
  5102. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5103. p._code = _getBitCode(p, bounds);
  5104. clippedPoints.push(p);
  5105. }
  5106. clippedPoints.push(a);
  5107. // else if b is inside the clip window (a->b enters the screen)
  5108. } else if (!(b._code & edge)) {
  5109. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5110. p._code = _getBitCode(p, bounds);
  5111. clippedPoints.push(p);
  5112. }
  5113. }
  5114. points = clippedPoints;
  5115. }
  5116. return points;
  5117. }
  5118. var PolyUtil = (Object.freeze || Object)({
  5119. clipPolygon: clipPolygon
  5120. });
  5121. /*
  5122. * @namespace Projection
  5123. * @section
  5124. * Leaflet comes with a set of already defined Projections out of the box:
  5125. *
  5126. * @projection L.Projection.LonLat
  5127. *
  5128. * Equirectangular, or Plate Carree projection — the most simple projection,
  5129. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5130. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5131. * `EPSG:4326` and `Simple` CRS.
  5132. */
  5133. var LonLat = {
  5134. project: function (latlng) {
  5135. return new Point(latlng.lng, latlng.lat);
  5136. },
  5137. unproject: function (point) {
  5138. return new LatLng(point.y, point.x);
  5139. },
  5140. bounds: new Bounds([-180, -90], [180, 90])
  5141. };
  5142. /*
  5143. * @namespace Projection
  5144. * @projection L.Projection.Mercator
  5145. *
  5146. * Elliptical Mercator projection — more complex than Spherical Mercator. Takes into account that Earth is a geoid, not a perfect sphere. Used by the EPSG:3395 CRS.
  5147. */
  5148. var Mercator = {
  5149. R: 6378137,
  5150. R_MINOR: 6356752.314245179,
  5151. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5152. project: function (latlng) {
  5153. var d = Math.PI / 180,
  5154. r = this.R,
  5155. y = latlng.lat * d,
  5156. tmp = this.R_MINOR / r,
  5157. e = Math.sqrt(1 - tmp * tmp),
  5158. con = e * Math.sin(y);
  5159. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5160. y = -r * Math.log(Math.max(ts, 1E-10));
  5161. return new Point(latlng.lng * d * r, y);
  5162. },
  5163. unproject: function (point) {
  5164. var d = 180 / Math.PI,
  5165. r = this.R,
  5166. tmp = this.R_MINOR / r,
  5167. e = Math.sqrt(1 - tmp * tmp),
  5168. ts = Math.exp(-point.y / r),
  5169. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5170. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5171. con = e * Math.sin(phi);
  5172. con = Math.pow((1 - con) / (1 + con), e / 2);
  5173. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5174. phi += dphi;
  5175. }
  5176. return new LatLng(phi * d, point.x * d / r);
  5177. }
  5178. };
  5179. /*
  5180. * @class Projection
  5181. * An object with methods for projecting geographical coordinates of the world onto
  5182. * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).
  5183. * @property bounds: Bounds
  5184. * The bounds (specified in CRS units) where the projection is valid
  5185. * @method project(latlng: LatLng): Point
  5186. * Projects geographical coordinates into a 2D point.
  5187. * Only accepts actual `L.LatLng` instances, not arrays.
  5188. * @method unproject(point: Point): LatLng
  5189. * The inverse of `project`. Projects a 2D point into a geographical location.
  5190. * Only accepts actual `L.Point` instances, not arrays.
  5191. */
  5192. var index = (Object.freeze || Object)({
  5193. LonLat: LonLat,
  5194. Mercator: Mercator,
  5195. SphericalMercator: SphericalMercator
  5196. });
  5197. /*
  5198. * @namespace CRS
  5199. * @crs L.CRS.EPSG3395
  5200. *
  5201. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5202. */
  5203. var EPSG3395 = extend({}, Earth, {
  5204. code: 'EPSG:3395',
  5205. projection: Mercator,
  5206. transformation: (function () {
  5207. var scale = 0.5 / (Math.PI * Mercator.R);
  5208. return toTransformation(scale, 0.5, -scale, 0.5);
  5209. }())
  5210. });
  5211. /*
  5212. * @namespace CRS
  5213. * @crs L.CRS.EPSG4326
  5214. *
  5215. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5216. *
  5217. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5218. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5219. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5220. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5221. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5222. */
  5223. var EPSG4326 = extend({}, Earth, {
  5224. code: 'EPSG:4326',
  5225. projection: LonLat,
  5226. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5227. });
  5228. /*
  5229. * @namespace CRS
  5230. * @crs L.CRS.Simple
  5231. *
  5232. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5233. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5234. * axis should still be inverted (going from bottom to top). `distance()` returns
  5235. * simple euclidean distance.
  5236. */
  5237. var Simple = extend({}, CRS, {
  5238. projection: LonLat,
  5239. transformation: toTransformation(1, 0, -1, 0),
  5240. scale: function (zoom) {
  5241. return Math.pow(2, zoom);
  5242. },
  5243. zoom: function (scale) {
  5244. return Math.log(scale) / Math.LN2;
  5245. },
  5246. distance: function (latlng1, latlng2) {
  5247. var dx = latlng2.lng - latlng1.lng,
  5248. dy = latlng2.lat - latlng1.lat;
  5249. return Math.sqrt(dx * dx + dy * dy);
  5250. },
  5251. infinite: true
  5252. });
  5253. CRS.Earth = Earth;
  5254. CRS.EPSG3395 = EPSG3395;
  5255. CRS.EPSG3857 = EPSG3857;
  5256. CRS.EPSG900913 = EPSG900913;
  5257. CRS.EPSG4326 = EPSG4326;
  5258. CRS.Simple = Simple;
  5259. /*
  5260. * @class Layer
  5261. * @inherits Evented
  5262. * @aka L.Layer
  5263. * @aka ILayer
  5264. *
  5265. * A set of methods from the Layer base class that all Leaflet layers use.
  5266. * Inherits all methods, options and events from `L.Evented`.
  5267. *
  5268. * @example
  5269. *
  5270. * ```js
  5271. * var layer = L.Marker(latlng).addTo(map);
  5272. * layer.addTo(map);
  5273. * layer.remove();
  5274. * ```
  5275. *
  5276. * @event add: Event
  5277. * Fired after the layer is added to a map
  5278. *
  5279. * @event remove: Event
  5280. * Fired after the layer is removed from a map
  5281. */
  5282. var Layer = Evented.extend({
  5283. // Classes extending `L.Layer` will inherit the following options:
  5284. options: {
  5285. // @option pane: String = 'overlayPane'
  5286. // 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.
  5287. pane: 'overlayPane',
  5288. // @option attribution: String = null
  5289. // String to be shown in the attribution control, describes the layer data, e.g. "© Mapbox".
  5290. attribution: null,
  5291. bubblingMouseEvents: true
  5292. },
  5293. /* @section
  5294. * Classes extending `L.Layer` will inherit the following methods:
  5295. *
  5296. * @method addTo(map: Map|LayerGroup): this
  5297. * Adds the layer to the given map or layer group.
  5298. */
  5299. addTo: function (map) {
  5300. map.addLayer(this);
  5301. return this;
  5302. },
  5303. // @method remove: this
  5304. // Removes the layer from the map it is currently active on.
  5305. remove: function () {
  5306. return this.removeFrom(this._map || this._mapToAdd);
  5307. },
  5308. // @method removeFrom(map: Map): this
  5309. // Removes the layer from the given map
  5310. removeFrom: function (obj) {
  5311. if (obj) {
  5312. obj.removeLayer(this);
  5313. }
  5314. return this;
  5315. },
  5316. // @method getPane(name? : String): HTMLElement
  5317. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5318. getPane: function (name) {
  5319. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5320. },
  5321. addInteractiveTarget: function (targetEl) {
  5322. this._map._targets[stamp(targetEl)] = this;
  5323. return this;
  5324. },
  5325. removeInteractiveTarget: function (targetEl) {
  5326. delete this._map._targets[stamp(targetEl)];
  5327. return this;
  5328. },
  5329. // @method getAttribution: String
  5330. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5331. getAttribution: function () {
  5332. return this.options.attribution;
  5333. },
  5334. _layerAdd: function (e) {
  5335. var map = e.target;
  5336. // check in case layer gets added and then removed before the map is ready
  5337. if (!map.hasLayer(this)) {
  5338. return;
  5339. }
  5340. this._map = map;
  5341. this._zoomAnimated = map._zoomAnimated;
  5342. if (this.getEvents) {
  5343. var events = this.getEvents();
  5344. map.on(events, this);
  5345. this.once('remove', function () {
  5346. map.off(events, this);
  5347. }, this);
  5348. }
  5349. this.onAdd(map);
  5350. if (this.getAttribution && map.attributionControl) {
  5351. map.attributionControl.addAttribution(this.getAttribution());
  5352. }
  5353. this.fire('add');
  5354. map.fire('layeradd', {layer: this});
  5355. }
  5356. });
  5357. /* @section Extension methods
  5358. * @uninheritable
  5359. *
  5360. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5361. *
  5362. * @method onAdd(map: Map): this
  5363. * 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).
  5364. *
  5365. * @method onRemove(map: Map): this
  5366. * 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).
  5367. *
  5368. * @method getEvents(): Object
  5369. * 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.
  5370. *
  5371. * @method getAttribution(): String
  5372. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5373. *
  5374. * @method beforeAdd(map: Map): this
  5375. * 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.
  5376. */
  5377. /* @namespace Map
  5378. * @section Layer events
  5379. *
  5380. * @event layeradd: LayerEvent
  5381. * Fired when a new layer is added to the map.
  5382. *
  5383. * @event layerremove: LayerEvent
  5384. * Fired when some layer is removed from the map
  5385. *
  5386. * @section Methods for Layers and Controls
  5387. */
  5388. Map.include({
  5389. // @method addLayer(layer: Layer): this
  5390. // Adds the given layer to the map
  5391. addLayer: function (layer) {
  5392. if (!layer._layerAdd) {
  5393. throw new Error('The provided object is not a Layer.');
  5394. }
  5395. var id = stamp(layer);
  5396. if (this._layers[id]) {
  5397. return this;
  5398. }
  5399. this._layers[id] = layer;
  5400. layer._mapToAdd = this;
  5401. if (layer.beforeAdd) {
  5402. layer.beforeAdd(this);
  5403. }
  5404. this.whenReady(layer._layerAdd, layer);
  5405. return this;
  5406. },
  5407. // @method removeLayer(layer: Layer): this
  5408. // Removes the given layer from the map.
  5409. removeLayer: function (layer) {
  5410. var id = stamp(layer);
  5411. if (!this._layers[id]) {
  5412. return this;
  5413. }
  5414. if (this._loaded) {
  5415. layer.onRemove(this);
  5416. }
  5417. if (layer.getAttribution && this.attributionControl) {
  5418. this.attributionControl.removeAttribution(layer.getAttribution());
  5419. }
  5420. delete this._layers[id];
  5421. if (this._loaded) {
  5422. this.fire('layerremove', {layer: layer});
  5423. layer.fire('remove');
  5424. }
  5425. layer._map = layer._mapToAdd = null;
  5426. return this;
  5427. },
  5428. // @method hasLayer(layer: Layer): Boolean
  5429. // Returns `true` if the given layer is currently added to the map
  5430. hasLayer: function (layer) {
  5431. return !!layer && (stamp(layer) in this._layers);
  5432. },
  5433. /* @method eachLayer(fn: Function, context?: Object): this
  5434. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5435. * ```
  5436. * map.eachLayer(function(layer){
  5437. * layer.bindPopup('Hello');
  5438. * });
  5439. * ```
  5440. */
  5441. eachLayer: function (method, context) {
  5442. for (var i in this._layers) {
  5443. method.call(context, this._layers[i]);
  5444. }
  5445. return this;
  5446. },
  5447. _addLayers: function (layers) {
  5448. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5449. for (var i = 0, len = layers.length; i < len; i++) {
  5450. this.addLayer(layers[i]);
  5451. }
  5452. },
  5453. _addZoomLimit: function (layer) {
  5454. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5455. this._zoomBoundLayers[stamp(layer)] = layer;
  5456. this._updateZoomLevels();
  5457. }
  5458. },
  5459. _removeZoomLimit: function (layer) {
  5460. var id = stamp(layer);
  5461. if (this._zoomBoundLayers[id]) {
  5462. delete this._zoomBoundLayers[id];
  5463. this._updateZoomLevels();
  5464. }
  5465. },
  5466. _updateZoomLevels: function () {
  5467. var minZoom = Infinity,
  5468. maxZoom = -Infinity,
  5469. oldZoomSpan = this._getZoomSpan();
  5470. for (var i in this._zoomBoundLayers) {
  5471. var options = this._zoomBoundLayers[i].options;
  5472. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5473. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5474. }
  5475. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5476. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5477. // @section Map state change events
  5478. // @event zoomlevelschange: Event
  5479. // Fired when the number of zoomlevels on the map is changed due
  5480. // to adding or removing a layer.
  5481. if (oldZoomSpan !== this._getZoomSpan()) {
  5482. this.fire('zoomlevelschange');
  5483. }
  5484. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5485. this.setZoom(this._layersMaxZoom);
  5486. }
  5487. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5488. this.setZoom(this._layersMinZoom);
  5489. }
  5490. }
  5491. });
  5492. /*
  5493. * @class LayerGroup
  5494. * @aka L.LayerGroup
  5495. * @inherits Layer
  5496. *
  5497. * Used to group several layers and handle them as one. If you add it to the map,
  5498. * any layers added or removed from the group will be added/removed on the map as
  5499. * well. Extends `Layer`.
  5500. *
  5501. * @example
  5502. *
  5503. * ```js
  5504. * L.layerGroup([marker1, marker2])
  5505. * .addLayer(polyline)
  5506. * .addTo(map);
  5507. * ```
  5508. */
  5509. var LayerGroup = Layer.extend({
  5510. initialize: function (layers) {
  5511. this._layers = {};
  5512. var i, len;
  5513. if (layers) {
  5514. for (i = 0, len = layers.length; i < len; i++) {
  5515. this.addLayer(layers[i]);
  5516. }
  5517. }
  5518. },
  5519. // @method addLayer(layer: Layer): this
  5520. // Adds the given layer to the group.
  5521. addLayer: function (layer) {
  5522. var id = this.getLayerId(layer);
  5523. this._layers[id] = layer;
  5524. if (this._map) {
  5525. this._map.addLayer(layer);
  5526. }
  5527. return this;
  5528. },
  5529. // @method removeLayer(layer: Layer): this
  5530. // Removes the given layer from the group.
  5531. // @alternative
  5532. // @method removeLayer(id: Number): this
  5533. // Removes the layer with the given internal ID from the group.
  5534. removeLayer: function (layer) {
  5535. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5536. if (this._map && this._layers[id]) {
  5537. this._map.removeLayer(this._layers[id]);
  5538. }
  5539. delete this._layers[id];
  5540. return this;
  5541. },
  5542. // @method hasLayer(layer: Layer): Boolean
  5543. // Returns `true` if the given layer is currently added to the group.
  5544. // @alternative
  5545. // @method hasLayer(id: Number): Boolean
  5546. // Returns `true` if the given internal ID is currently added to the group.
  5547. hasLayer: function (layer) {
  5548. return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
  5549. },
  5550. // @method clearLayers(): this
  5551. // Removes all the layers from the group.
  5552. clearLayers: function () {
  5553. for (var i in this._layers) {
  5554. this.removeLayer(this._layers[i]);
  5555. }
  5556. return this;
  5557. },
  5558. // @method invoke(methodName: String, …): this
  5559. // Calls `methodName` on every layer contained in this group, passing any
  5560. // additional parameters. Has no effect if the layers contained do not
  5561. // implement `methodName`.
  5562. invoke: function (methodName) {
  5563. var args = Array.prototype.slice.call(arguments, 1),
  5564. i, layer;
  5565. for (i in this._layers) {
  5566. layer = this._layers[i];
  5567. if (layer[methodName]) {
  5568. layer[methodName].apply(layer, args);
  5569. }
  5570. }
  5571. return this;
  5572. },
  5573. onAdd: function (map) {
  5574. for (var i in this._layers) {
  5575. map.addLayer(this._layers[i]);
  5576. }
  5577. },
  5578. onRemove: function (map) {
  5579. for (var i in this._layers) {
  5580. map.removeLayer(this._layers[i]);
  5581. }
  5582. },
  5583. // @method eachLayer(fn: Function, context?: Object): this
  5584. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5585. // ```js
  5586. // group.eachLayer(function (layer) {
  5587. // layer.bindPopup('Hello');
  5588. // });
  5589. // ```
  5590. eachLayer: function (method, context) {
  5591. for (var i in this._layers) {
  5592. method.call(context, this._layers[i]);
  5593. }
  5594. return this;
  5595. },
  5596. // @method getLayer(id: Number): Layer
  5597. // Returns the layer with the given internal ID.
  5598. getLayer: function (id) {
  5599. return this._layers[id];
  5600. },
  5601. // @method getLayers(): Layer[]
  5602. // Returns an array of all the layers added to the group.
  5603. getLayers: function () {
  5604. var layers = [];
  5605. for (var i in this._layers) {
  5606. layers.push(this._layers[i]);
  5607. }
  5608. return layers;
  5609. },
  5610. // @method setZIndex(zIndex: Number): this
  5611. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5612. setZIndex: function (zIndex) {
  5613. return this.invoke('setZIndex', zIndex);
  5614. },
  5615. // @method getLayerId(layer: Layer): Number
  5616. // Returns the internal ID for a layer
  5617. getLayerId: function (layer) {
  5618. return stamp(layer);
  5619. }
  5620. });
  5621. // @factory L.layerGroup(layers?: Layer[])
  5622. // Create a layer group, optionally given an initial set of layers.
  5623. var layerGroup = function (layers) {
  5624. return new LayerGroup(layers);
  5625. };
  5626. /*
  5627. * @class FeatureGroup
  5628. * @aka L.FeatureGroup
  5629. * @inherits LayerGroup
  5630. *
  5631. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5632. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5633. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5634. * handler, it will handle events from any of the layers. This includes mouse events
  5635. * and custom events.
  5636. * * Has `layeradd` and `layerremove` events
  5637. *
  5638. * @example
  5639. *
  5640. * ```js
  5641. * L.featureGroup([marker1, marker2, polyline])
  5642. * .bindPopup('Hello world!')
  5643. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5644. * .addTo(map);
  5645. * ```
  5646. */
  5647. var FeatureGroup = LayerGroup.extend({
  5648. addLayer: function (layer) {
  5649. if (this.hasLayer(layer)) {
  5650. return this;
  5651. }
  5652. layer.addEventParent(this);
  5653. LayerGroup.prototype.addLayer.call(this, layer);
  5654. // @event layeradd: LayerEvent
  5655. // Fired when a layer is added to this `FeatureGroup`
  5656. return this.fire('layeradd', {layer: layer});
  5657. },
  5658. removeLayer: function (layer) {
  5659. if (!this.hasLayer(layer)) {
  5660. return this;
  5661. }
  5662. if (layer in this._layers) {
  5663. layer = this._layers[layer];
  5664. }
  5665. layer.removeEventParent(this);
  5666. LayerGroup.prototype.removeLayer.call(this, layer);
  5667. // @event layerremove: LayerEvent
  5668. // Fired when a layer is removed from this `FeatureGroup`
  5669. return this.fire('layerremove', {layer: layer});
  5670. },
  5671. // @method setStyle(style: Path options): this
  5672. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5673. setStyle: function (style) {
  5674. return this.invoke('setStyle', style);
  5675. },
  5676. // @method bringToFront(): this
  5677. // Brings the layer group to the top of all other layers
  5678. bringToFront: function () {
  5679. return this.invoke('bringToFront');
  5680. },
  5681. // @method bringToBack(): this
  5682. // Brings the layer group to the top of all other layers
  5683. bringToBack: function () {
  5684. return this.invoke('bringToBack');
  5685. },
  5686. // @method getBounds(): LatLngBounds
  5687. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5688. getBounds: function () {
  5689. var bounds = new LatLngBounds();
  5690. for (var id in this._layers) {
  5691. var layer = this._layers[id];
  5692. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5693. }
  5694. return bounds;
  5695. }
  5696. });
  5697. // @factory L.featureGroup(layers: Layer[])
  5698. // Create a feature group, optionally given an initial set of layers.
  5699. var featureGroup = function (layers) {
  5700. return new FeatureGroup(layers);
  5701. };
  5702. /*
  5703. * @class Icon
  5704. * @aka L.Icon
  5705. *
  5706. * Represents an icon to provide when creating a marker.
  5707. *
  5708. * @example
  5709. *
  5710. * ```js
  5711. * var myIcon = L.icon({
  5712. * iconUrl: 'my-icon.png',
  5713. * iconRetinaUrl: 'my-icon@2x.png',
  5714. * iconSize: [38, 95],
  5715. * iconAnchor: [22, 94],
  5716. * popupAnchor: [-3, -76],
  5717. * shadowUrl: 'my-icon-shadow.png',
  5718. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5719. * shadowSize: [68, 95],
  5720. * shadowAnchor: [22, 94]
  5721. * });
  5722. *
  5723. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5724. * ```
  5725. *
  5726. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5727. *
  5728. */
  5729. var Icon = Class.extend({
  5730. /* @section
  5731. * @aka Icon options
  5732. *
  5733. * @option iconUrl: String = null
  5734. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5735. *
  5736. * @option iconRetinaUrl: String = null
  5737. * The URL to a retina sized version of the icon image (absolute or relative to your
  5738. * script path). Used for Retina screen devices.
  5739. *
  5740. * @option iconSize: Point = null
  5741. * Size of the icon image in pixels.
  5742. *
  5743. * @option iconAnchor: Point = null
  5744. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5745. * will be aligned so that this point is at the marker's geographical location. Centered
  5746. * by default if size is specified, also can be set in CSS with negative margins.
  5747. *
  5748. * @option popupAnchor: Point = null
  5749. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5750. *
  5751. * @option shadowUrl: String = null
  5752. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  5753. *
  5754. * @option shadowRetinaUrl: String = null
  5755. *
  5756. * @option shadowSize: Point = null
  5757. * Size of the shadow image in pixels.
  5758. *
  5759. * @option shadowAnchor: Point = null
  5760. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  5761. * as iconAnchor if not specified).
  5762. *
  5763. * @option className: String = ''
  5764. * A custom class name to assign to both icon and shadow images. Empty by default.
  5765. */
  5766. initialize: function (options) {
  5767. setOptions(this, options);
  5768. },
  5769. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  5770. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  5771. // styled according to the options.
  5772. createIcon: function (oldIcon) {
  5773. return this._createIcon('icon', oldIcon);
  5774. },
  5775. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  5776. // As `createIcon`, but for the shadow beneath it.
  5777. createShadow: function (oldIcon) {
  5778. return this._createIcon('shadow', oldIcon);
  5779. },
  5780. _createIcon: function (name, oldIcon) {
  5781. var src = this._getIconUrl(name);
  5782. if (!src) {
  5783. if (name === 'icon') {
  5784. throw new Error('iconUrl not set in Icon options (see the docs).');
  5785. }
  5786. return null;
  5787. }
  5788. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  5789. this._setIconStyles(img, name);
  5790. return img;
  5791. },
  5792. _setIconStyles: function (img, name) {
  5793. var options = this.options;
  5794. var sizeOption = options[name + 'Size'];
  5795. if (typeof sizeOption === 'number') {
  5796. sizeOption = [sizeOption, sizeOption];
  5797. }
  5798. var size = toPoint(sizeOption),
  5799. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  5800. size && size.divideBy(2, true));
  5801. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  5802. if (anchor) {
  5803. img.style.marginLeft = (-anchor.x) + 'px';
  5804. img.style.marginTop = (-anchor.y) + 'px';
  5805. }
  5806. if (size) {
  5807. img.style.width = size.x + 'px';
  5808. img.style.height = size.y + 'px';
  5809. }
  5810. },
  5811. _createImg: function (src, el) {
  5812. el = el || document.createElement('img');
  5813. el.src = src;
  5814. return el;
  5815. },
  5816. _getIconUrl: function (name) {
  5817. return retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  5818. }
  5819. });
  5820. // @factory L.icon(options: Icon options)
  5821. // Creates an icon instance with the given options.
  5822. function icon(options) {
  5823. return new Icon(options);
  5824. }
  5825. /*
  5826. * @miniclass Icon.Default (Icon)
  5827. * @aka L.Icon.Default
  5828. * @section
  5829. *
  5830. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  5831. * no icon is specified. Points to the blue marker image distributed with Leaflet
  5832. * releases.
  5833. *
  5834. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  5835. * (which is a set of `Icon options`).
  5836. *
  5837. * If you want to _completely_ replace the default icon, override the
  5838. * `L.Marker.prototype.options.icon` with your own icon instead.
  5839. */
  5840. var IconDefault = Icon.extend({
  5841. options: {
  5842. iconUrl: 'marker-icon.png',
  5843. iconRetinaUrl: 'marker-icon-2x.png',
  5844. shadowUrl: 'marker-shadow.png',
  5845. iconSize: [25, 41],
  5846. iconAnchor: [12, 41],
  5847. popupAnchor: [1, -34],
  5848. tooltipAnchor: [16, -28],
  5849. shadowSize: [41, 41]
  5850. },
  5851. _getIconUrl: function (name) {
  5852. if (!IconDefault.imagePath) { // Deprecated, backwards-compatibility only
  5853. IconDefault.imagePath = this._detectIconPath();
  5854. }
  5855. // @option imagePath: String
  5856. // `Icon.Default` will try to auto-detect the absolute location of the
  5857. // blue icon images. If you are placing these images in a non-standard
  5858. // way, set this option to point to the right absolute path.
  5859. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  5860. },
  5861. _detectIconPath: function () {
  5862. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  5863. var path = getStyle(el, 'background-image') ||
  5864. getStyle(el, 'backgroundImage'); // IE8
  5865. document.body.removeChild(el);
  5866. if (path === null || path.indexOf('url') !== 0) {
  5867. path = '';
  5868. } else {
  5869. path = path.replace(/^url\([\"\']?/, '').replace(/marker-icon\.png[\"\']?\)$/, '');
  5870. }
  5871. return path;
  5872. }
  5873. });
  5874. /*
  5875. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  5876. */
  5877. /* @namespace Marker
  5878. * @section Interaction handlers
  5879. *
  5880. * 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:
  5881. *
  5882. * ```js
  5883. * marker.dragging.disable();
  5884. * ```
  5885. *
  5886. * @property dragging: Handler
  5887. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  5888. */
  5889. var MarkerDrag = Handler.extend({
  5890. initialize: function (marker) {
  5891. this._marker = marker;
  5892. },
  5893. addHooks: function () {
  5894. var icon = this._marker._icon;
  5895. if (!this._draggable) {
  5896. this._draggable = new Draggable(icon, icon, true);
  5897. }
  5898. this._draggable.on({
  5899. dragstart: this._onDragStart,
  5900. drag: this._onDrag,
  5901. dragend: this._onDragEnd
  5902. }, this).enable();
  5903. addClass(icon, 'leaflet-marker-draggable');
  5904. },
  5905. removeHooks: function () {
  5906. this._draggable.off({
  5907. dragstart: this._onDragStart,
  5908. drag: this._onDrag,
  5909. dragend: this._onDragEnd
  5910. }, this).disable();
  5911. if (this._marker._icon) {
  5912. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  5913. }
  5914. },
  5915. moved: function () {
  5916. return this._draggable && this._draggable._moved;
  5917. },
  5918. _onDragStart: function () {
  5919. // @section Dragging events
  5920. // @event dragstart: Event
  5921. // Fired when the user starts dragging the marker.
  5922. // @event movestart: Event
  5923. // Fired when the marker starts moving (because of dragging).
  5924. this._oldLatLng = this._marker.getLatLng();
  5925. this._marker
  5926. .closePopup()
  5927. .fire('movestart')
  5928. .fire('dragstart');
  5929. },
  5930. _onDrag: function (e) {
  5931. var marker = this._marker,
  5932. shadow = marker._shadow,
  5933. iconPos = getPosition(marker._icon),
  5934. latlng = marker._map.layerPointToLatLng(iconPos);
  5935. // update shadow position
  5936. if (shadow) {
  5937. setPosition(shadow, iconPos);
  5938. }
  5939. marker._latlng = latlng;
  5940. e.latlng = latlng;
  5941. e.oldLatLng = this._oldLatLng;
  5942. // @event drag: Event
  5943. // Fired repeatedly while the user drags the marker.
  5944. marker
  5945. .fire('move', e)
  5946. .fire('drag', e);
  5947. },
  5948. _onDragEnd: function (e) {
  5949. // @event dragend: DragEndEvent
  5950. // Fired when the user stops dragging the marker.
  5951. // @event moveend: Event
  5952. // Fired when the marker stops moving (because of dragging).
  5953. delete this._oldLatLng;
  5954. this._marker
  5955. .fire('moveend')
  5956. .fire('dragend', e);
  5957. }
  5958. });
  5959. /*
  5960. * @class Marker
  5961. * @inherits Interactive layer
  5962. * @aka L.Marker
  5963. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  5964. *
  5965. * @example
  5966. *
  5967. * ```js
  5968. * L.marker([50.5, 30.5]).addTo(map);
  5969. * ```
  5970. */
  5971. var Marker = Layer.extend({
  5972. // @section
  5973. // @aka Marker options
  5974. options: {
  5975. // @option icon: Icon = *
  5976. // Icon instance to use for rendering the marker.
  5977. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  5978. // If not specified, a common instance of `L.Icon.Default` is used.
  5979. icon: new IconDefault(),
  5980. // Option inherited from "Interactive layer" abstract class
  5981. interactive: true,
  5982. // @option draggable: Boolean = false
  5983. // Whether the marker is draggable with mouse/touch or not.
  5984. draggable: false,
  5985. // @option keyboard: Boolean = true
  5986. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  5987. keyboard: true,
  5988. // @option title: String = ''
  5989. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  5990. title: '',
  5991. // @option alt: String = ''
  5992. // Text for the `alt` attribute of the icon image (useful for accessibility).
  5993. alt: '',
  5994. // @option zIndexOffset: Number = 0
  5995. // 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).
  5996. zIndexOffset: 0,
  5997. // @option opacity: Number = 1.0
  5998. // The opacity of the marker.
  5999. opacity: 1,
  6000. // @option riseOnHover: Boolean = false
  6001. // If `true`, the marker will get on top of others when you hover the mouse over it.
  6002. riseOnHover: false,
  6003. // @option riseOffset: Number = 250
  6004. // The z-index offset used for the `riseOnHover` feature.
  6005. riseOffset: 250,
  6006. // @option pane: String = 'markerPane'
  6007. // `Map pane` where the markers icon will be added.
  6008. pane: 'markerPane',
  6009. // @option bubblingMouseEvents: Boolean = false
  6010. // When `true`, a mouse event on this marker will trigger the same event on the map
  6011. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6012. bubblingMouseEvents: false
  6013. },
  6014. /* @section
  6015. *
  6016. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  6017. */
  6018. initialize: function (latlng, options) {
  6019. setOptions(this, options);
  6020. this._latlng = toLatLng(latlng);
  6021. },
  6022. onAdd: function (map) {
  6023. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  6024. if (this._zoomAnimated) {
  6025. map.on('zoomanim', this._animateZoom, this);
  6026. }
  6027. this._initIcon();
  6028. this.update();
  6029. },
  6030. onRemove: function (map) {
  6031. if (this.dragging && this.dragging.enabled()) {
  6032. this.options.draggable = true;
  6033. this.dragging.removeHooks();
  6034. }
  6035. delete this.dragging;
  6036. if (this._zoomAnimated) {
  6037. map.off('zoomanim', this._animateZoom, this);
  6038. }
  6039. this._removeIcon();
  6040. this._removeShadow();
  6041. },
  6042. getEvents: function () {
  6043. return {
  6044. zoom: this.update,
  6045. viewreset: this.update
  6046. };
  6047. },
  6048. // @method getLatLng: LatLng
  6049. // Returns the current geographical position of the marker.
  6050. getLatLng: function () {
  6051. return this._latlng;
  6052. },
  6053. // @method setLatLng(latlng: LatLng): this
  6054. // Changes the marker position to the given point.
  6055. setLatLng: function (latlng) {
  6056. var oldLatLng = this._latlng;
  6057. this._latlng = toLatLng(latlng);
  6058. this.update();
  6059. // @event move: Event
  6060. // 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`.
  6061. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6062. },
  6063. // @method setZIndexOffset(offset: Number): this
  6064. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6065. setZIndexOffset: function (offset) {
  6066. this.options.zIndexOffset = offset;
  6067. return this.update();
  6068. },
  6069. // @method setIcon(icon: Icon): this
  6070. // Changes the marker icon.
  6071. setIcon: function (icon) {
  6072. this.options.icon = icon;
  6073. if (this._map) {
  6074. this._initIcon();
  6075. this.update();
  6076. }
  6077. if (this._popup) {
  6078. this.bindPopup(this._popup, this._popup.options);
  6079. }
  6080. return this;
  6081. },
  6082. getElement: function () {
  6083. return this._icon;
  6084. },
  6085. update: function () {
  6086. if (this._icon) {
  6087. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6088. this._setPos(pos);
  6089. }
  6090. return this;
  6091. },
  6092. _initIcon: function () {
  6093. var options = this.options,
  6094. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6095. var icon = options.icon.createIcon(this._icon),
  6096. addIcon = false;
  6097. // if we're not reusing the icon, remove the old one and init new one
  6098. if (icon !== this._icon) {
  6099. if (this._icon) {
  6100. this._removeIcon();
  6101. }
  6102. addIcon = true;
  6103. if (options.title) {
  6104. icon.title = options.title;
  6105. }
  6106. if (options.alt) {
  6107. icon.alt = options.alt;
  6108. }
  6109. }
  6110. addClass(icon, classToAdd);
  6111. if (options.keyboard) {
  6112. icon.tabIndex = '0';
  6113. }
  6114. this._icon = icon;
  6115. if (options.riseOnHover) {
  6116. this.on({
  6117. mouseover: this._bringToFront,
  6118. mouseout: this._resetZIndex
  6119. });
  6120. }
  6121. var newShadow = options.icon.createShadow(this._shadow),
  6122. addShadow = false;
  6123. if (newShadow !== this._shadow) {
  6124. this._removeShadow();
  6125. addShadow = true;
  6126. }
  6127. if (newShadow) {
  6128. addClass(newShadow, classToAdd);
  6129. newShadow.alt = '';
  6130. }
  6131. this._shadow = newShadow;
  6132. if (options.opacity < 1) {
  6133. this._updateOpacity();
  6134. }
  6135. if (addIcon) {
  6136. this.getPane().appendChild(this._icon);
  6137. }
  6138. this._initInteraction();
  6139. if (newShadow && addShadow) {
  6140. this.getPane('shadowPane').appendChild(this._shadow);
  6141. }
  6142. },
  6143. _removeIcon: function () {
  6144. if (this.options.riseOnHover) {
  6145. this.off({
  6146. mouseover: this._bringToFront,
  6147. mouseout: this._resetZIndex
  6148. });
  6149. }
  6150. remove(this._icon);
  6151. this.removeInteractiveTarget(this._icon);
  6152. this._icon = null;
  6153. },
  6154. _removeShadow: function () {
  6155. if (this._shadow) {
  6156. remove(this._shadow);
  6157. }
  6158. this._shadow = null;
  6159. },
  6160. _setPos: function (pos) {
  6161. setPosition(this._icon, pos);
  6162. if (this._shadow) {
  6163. setPosition(this._shadow, pos);
  6164. }
  6165. this._zIndex = pos.y + this.options.zIndexOffset;
  6166. this._resetZIndex();
  6167. },
  6168. _updateZIndex: function (offset) {
  6169. this._icon.style.zIndex = this._zIndex + offset;
  6170. },
  6171. _animateZoom: function (opt) {
  6172. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6173. this._setPos(pos);
  6174. },
  6175. _initInteraction: function () {
  6176. if (!this.options.interactive) {
  6177. return;
  6178. }
  6179. addClass(this._icon, 'leaflet-interactive');
  6180. this.addInteractiveTarget(this._icon);
  6181. if (MarkerDrag) {
  6182. var draggable = this.options.draggable;
  6183. if (this.dragging) {
  6184. draggable = this.dragging.enabled();
  6185. this.dragging.disable();
  6186. }
  6187. this.dragging = new MarkerDrag(this);
  6188. if (draggable) {
  6189. this.dragging.enable();
  6190. }
  6191. }
  6192. },
  6193. // @method setOpacity(opacity: Number): this
  6194. // Changes the opacity of the marker.
  6195. setOpacity: function (opacity) {
  6196. this.options.opacity = opacity;
  6197. if (this._map) {
  6198. this._updateOpacity();
  6199. }
  6200. return this;
  6201. },
  6202. _updateOpacity: function () {
  6203. var opacity = this.options.opacity;
  6204. setOpacity(this._icon, opacity);
  6205. if (this._shadow) {
  6206. setOpacity(this._shadow, opacity);
  6207. }
  6208. },
  6209. _bringToFront: function () {
  6210. this._updateZIndex(this.options.riseOffset);
  6211. },
  6212. _resetZIndex: function () {
  6213. this._updateZIndex(0);
  6214. },
  6215. _getPopupAnchor: function () {
  6216. return this.options.icon.options.popupAnchor || [0, 0];
  6217. },
  6218. _getTooltipAnchor: function () {
  6219. return this.options.icon.options.tooltipAnchor || [0, 0];
  6220. }
  6221. });
  6222. // factory L.marker(latlng: LatLng, options? : Marker options)
  6223. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6224. // Instantiates a Marker object given a geographical point and optionally an options object.
  6225. function marker(latlng, options) {
  6226. return new Marker(latlng, options);
  6227. }
  6228. /*
  6229. * @class Path
  6230. * @aka L.Path
  6231. * @inherits Interactive layer
  6232. *
  6233. * An abstract class that contains options and constants shared between vector
  6234. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6235. */
  6236. var Path = Layer.extend({
  6237. // @section
  6238. // @aka Path options
  6239. options: {
  6240. // @option stroke: Boolean = true
  6241. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6242. stroke: true,
  6243. // @option color: String = '#3388ff'
  6244. // Stroke color
  6245. color: '#3388ff',
  6246. // @option weight: Number = 3
  6247. // Stroke width in pixels
  6248. weight: 3,
  6249. // @option opacity: Number = 1.0
  6250. // Stroke opacity
  6251. opacity: 1,
  6252. // @option lineCap: String= 'round'
  6253. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6254. lineCap: 'round',
  6255. // @option lineJoin: String = 'round'
  6256. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6257. lineJoin: 'round',
  6258. // @option dashArray: String = null
  6259. // 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).
  6260. dashArray: null,
  6261. // @option dashOffset: String = null
  6262. // 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).
  6263. dashOffset: null,
  6264. // @option fill: Boolean = depends
  6265. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6266. fill: false,
  6267. // @option fillColor: String = *
  6268. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6269. fillColor: null,
  6270. // @option fillOpacity: Number = 0.2
  6271. // Fill opacity.
  6272. fillOpacity: 0.2,
  6273. // @option fillRule: String = 'evenodd'
  6274. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6275. fillRule: 'evenodd',
  6276. // className: '',
  6277. // Option inherited from "Interactive layer" abstract class
  6278. interactive: true,
  6279. // @option bubblingMouseEvents: Boolean = true
  6280. // When `true`, a mouse event on this path will trigger the same event on the map
  6281. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6282. bubblingMouseEvents: true
  6283. },
  6284. beforeAdd: function (map) {
  6285. // Renderer is set here because we need to call renderer.getEvents
  6286. // before this.getEvents.
  6287. this._renderer = map.getRenderer(this);
  6288. },
  6289. onAdd: function () {
  6290. this._renderer._initPath(this);
  6291. this._reset();
  6292. this._renderer._addPath(this);
  6293. },
  6294. onRemove: function () {
  6295. this._renderer._removePath(this);
  6296. },
  6297. // @method redraw(): this
  6298. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6299. redraw: function () {
  6300. if (this._map) {
  6301. this._renderer._updatePath(this);
  6302. }
  6303. return this;
  6304. },
  6305. // @method setStyle(style: Path options): this
  6306. // Changes the appearance of a Path based on the options in the `Path options` object.
  6307. setStyle: function (style) {
  6308. setOptions(this, style);
  6309. if (this._renderer) {
  6310. this._renderer._updateStyle(this);
  6311. }
  6312. return this;
  6313. },
  6314. // @method bringToFront(): this
  6315. // Brings the layer to the top of all path layers.
  6316. bringToFront: function () {
  6317. if (this._renderer) {
  6318. this._renderer._bringToFront(this);
  6319. }
  6320. return this;
  6321. },
  6322. // @method bringToBack(): this
  6323. // Brings the layer to the bottom of all path layers.
  6324. bringToBack: function () {
  6325. if (this._renderer) {
  6326. this._renderer._bringToBack(this);
  6327. }
  6328. return this;
  6329. },
  6330. getElement: function () {
  6331. return this._path;
  6332. },
  6333. _reset: function () {
  6334. // defined in child classes
  6335. this._project();
  6336. this._update();
  6337. },
  6338. _clickTolerance: function () {
  6339. // used when doing hit detection for Canvas layers
  6340. return (this.options.stroke ? this.options.weight / 2 : 0) + (touch ? 10 : 0);
  6341. }
  6342. });
  6343. /*
  6344. * @class CircleMarker
  6345. * @aka L.CircleMarker
  6346. * @inherits Path
  6347. *
  6348. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6349. */
  6350. var CircleMarker = Path.extend({
  6351. // @section
  6352. // @aka CircleMarker options
  6353. options: {
  6354. fill: true,
  6355. // @option radius: Number = 10
  6356. // Radius of the circle marker, in pixels
  6357. radius: 10
  6358. },
  6359. initialize: function (latlng, options) {
  6360. setOptions(this, options);
  6361. this._latlng = toLatLng(latlng);
  6362. this._radius = this.options.radius;
  6363. },
  6364. // @method setLatLng(latLng: LatLng): this
  6365. // Sets the position of a circle marker to a new location.
  6366. setLatLng: function (latlng) {
  6367. this._latlng = toLatLng(latlng);
  6368. this.redraw();
  6369. return this.fire('move', {latlng: this._latlng});
  6370. },
  6371. // @method getLatLng(): LatLng
  6372. // Returns the current geographical position of the circle marker
  6373. getLatLng: function () {
  6374. return this._latlng;
  6375. },
  6376. // @method setRadius(radius: Number): this
  6377. // Sets the radius of a circle marker. Units are in pixels.
  6378. setRadius: function (radius) {
  6379. this.options.radius = this._radius = radius;
  6380. return this.redraw();
  6381. },
  6382. // @method getRadius(): Number
  6383. // Returns the current radius of the circle
  6384. getRadius: function () {
  6385. return this._radius;
  6386. },
  6387. setStyle: function (options) {
  6388. var radius = options && options.radius || this._radius;
  6389. Path.prototype.setStyle.call(this, options);
  6390. this.setRadius(radius);
  6391. return this;
  6392. },
  6393. _project: function () {
  6394. this._point = this._map.latLngToLayerPoint(this._latlng);
  6395. this._updateBounds();
  6396. },
  6397. _updateBounds: function () {
  6398. var r = this._radius,
  6399. r2 = this._radiusY || r,
  6400. w = this._clickTolerance(),
  6401. p = [r + w, r2 + w];
  6402. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6403. },
  6404. _update: function () {
  6405. if (this._map) {
  6406. this._updatePath();
  6407. }
  6408. },
  6409. _updatePath: function () {
  6410. this._renderer._updateCircle(this);
  6411. },
  6412. _empty: function () {
  6413. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6414. },
  6415. // Needed by the `Canvas` renderer for interactivity
  6416. _containsPoint: function (p) {
  6417. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6418. }
  6419. });
  6420. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6421. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6422. function circleMarker(latlng, options) {
  6423. return new CircleMarker(latlng, options);
  6424. }
  6425. /*
  6426. * @class Circle
  6427. * @aka L.Circle
  6428. * @inherits CircleMarker
  6429. *
  6430. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6431. *
  6432. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6433. *
  6434. * @example
  6435. *
  6436. * ```js
  6437. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6438. * ```
  6439. */
  6440. var Circle = CircleMarker.extend({
  6441. initialize: function (latlng, options, legacyOptions) {
  6442. if (typeof options === 'number') {
  6443. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6444. options = extend({}, legacyOptions, {radius: options});
  6445. }
  6446. setOptions(this, options);
  6447. this._latlng = toLatLng(latlng);
  6448. if (isNaN(this.options.radius)) {
  6449. throw new Error('Circle radius cannot be NaN');
  6450. }
  6451. // @section
  6452. // @aka Circle options
  6453. // @option radius: Number; Radius of the circle, in meters.
  6454. this._mRadius = this.options.radius;
  6455. },
  6456. // @method setRadius(radius: Number): this
  6457. // Sets the radius of a circle. Units are in meters.
  6458. setRadius: function (radius) {
  6459. this._mRadius = radius;
  6460. return this.redraw();
  6461. },
  6462. // @method getRadius(): Number
  6463. // Returns the current radius of a circle. Units are in meters.
  6464. getRadius: function () {
  6465. return this._mRadius;
  6466. },
  6467. // @method getBounds(): LatLngBounds
  6468. // Returns the `LatLngBounds` of the path.
  6469. getBounds: function () {
  6470. var half = [this._radius, this._radiusY || this._radius];
  6471. return new LatLngBounds(
  6472. this._map.layerPointToLatLng(this._point.subtract(half)),
  6473. this._map.layerPointToLatLng(this._point.add(half)));
  6474. },
  6475. setStyle: Path.prototype.setStyle,
  6476. _project: function () {
  6477. var lng = this._latlng.lng,
  6478. lat = this._latlng.lat,
  6479. map = this._map,
  6480. crs = map.options.crs;
  6481. if (crs.distance === Earth.distance) {
  6482. var d = Math.PI / 180,
  6483. latR = (this._mRadius / Earth.R) / d,
  6484. top = map.project([lat + latR, lng]),
  6485. bottom = map.project([lat - latR, lng]),
  6486. p = top.add(bottom).divideBy(2),
  6487. lat2 = map.unproject(p).lat,
  6488. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6489. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6490. if (isNaN(lngR) || lngR === 0) {
  6491. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6492. }
  6493. this._point = p.subtract(map.getPixelOrigin());
  6494. this._radius = isNaN(lngR) ? 0 : Math.max(Math.round(p.x - map.project([lat2, lng - lngR]).x), 1);
  6495. this._radiusY = Math.max(Math.round(p.y - top.y), 1);
  6496. } else {
  6497. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6498. this._point = map.latLngToLayerPoint(this._latlng);
  6499. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6500. }
  6501. this._updateBounds();
  6502. }
  6503. });
  6504. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6505. // Instantiates a circle object given a geographical point, and an options object
  6506. // which contains the circle radius.
  6507. // @alternative
  6508. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6509. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6510. // Do not use in new applications or plugins.
  6511. function circle(latlng, options, legacyOptions) {
  6512. return new Circle(latlng, options, legacyOptions);
  6513. }
  6514. /*
  6515. * @class Polyline
  6516. * @aka L.Polyline
  6517. * @inherits Path
  6518. *
  6519. * A class for drawing polyline overlays on a map. Extends `Path`.
  6520. *
  6521. * @example
  6522. *
  6523. * ```js
  6524. * // create a red polyline from an array of LatLng points
  6525. * var latlngs = [
  6526. * [45.51, -122.68],
  6527. * [37.77, -122.43],
  6528. * [34.04, -118.2]
  6529. * ];
  6530. *
  6531. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6532. *
  6533. * // zoom the map to the polyline
  6534. * map.fitBounds(polyline.getBounds());
  6535. * ```
  6536. *
  6537. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6538. *
  6539. * ```js
  6540. * // create a red polyline from an array of arrays of LatLng points
  6541. * var latlngs = [
  6542. * [[45.51, -122.68],
  6543. * [37.77, -122.43],
  6544. * [34.04, -118.2]],
  6545. * [[40.78, -73.91],
  6546. * [41.83, -87.62],
  6547. * [32.76, -96.72]]
  6548. * ];
  6549. * ```
  6550. */
  6551. var Polyline = Path.extend({
  6552. // @section
  6553. // @aka Polyline options
  6554. options: {
  6555. // @option smoothFactor: Number = 1.0
  6556. // How much to simplify the polyline on each zoom level. More means
  6557. // better performance and smoother look, and less means more accurate representation.
  6558. smoothFactor: 1.0,
  6559. // @option noClip: Boolean = false
  6560. // Disable polyline clipping.
  6561. noClip: false
  6562. },
  6563. initialize: function (latlngs, options) {
  6564. setOptions(this, options);
  6565. this._setLatLngs(latlngs);
  6566. },
  6567. // @method getLatLngs(): LatLng[]
  6568. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6569. getLatLngs: function () {
  6570. return this._latlngs;
  6571. },
  6572. // @method setLatLngs(latlngs: LatLng[]): this
  6573. // Replaces all the points in the polyline with the given array of geographical points.
  6574. setLatLngs: function (latlngs) {
  6575. this._setLatLngs(latlngs);
  6576. return this.redraw();
  6577. },
  6578. // @method isEmpty(): Boolean
  6579. // Returns `true` if the Polyline has no LatLngs.
  6580. isEmpty: function () {
  6581. return !this._latlngs.length;
  6582. },
  6583. closestLayerPoint: function (p) {
  6584. var minDistance = Infinity,
  6585. minPoint = null,
  6586. closest = _sqClosestPointOnSegment,
  6587. p1, p2;
  6588. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6589. var points = this._parts[j];
  6590. for (var i = 1, len = points.length; i < len; i++) {
  6591. p1 = points[i - 1];
  6592. p2 = points[i];
  6593. var sqDist = closest(p, p1, p2, true);
  6594. if (sqDist < minDistance) {
  6595. minDistance = sqDist;
  6596. minPoint = closest(p, p1, p2);
  6597. }
  6598. }
  6599. }
  6600. if (minPoint) {
  6601. minPoint.distance = Math.sqrt(minDistance);
  6602. }
  6603. return minPoint;
  6604. },
  6605. // @method getCenter(): LatLng
  6606. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6607. getCenter: function () {
  6608. // throws error when not yet added to map as this center calculation requires projected coordinates
  6609. if (!this._map) {
  6610. throw new Error('Must add layer to map before using getCenter()');
  6611. }
  6612. var i, halfDist, segDist, dist, p1, p2, ratio,
  6613. points = this._rings[0],
  6614. len = points.length;
  6615. if (!len) {
  6616. return null;
  6617. }
  6618. // polyline centroid algorithm; only uses the first ring if there are multiple
  6619. for (i = 0, halfDist = 0; i < len - 1; i++) {
  6620. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  6621. }
  6622. // The line is so small in the current view that all points are on the same pixel.
  6623. if (halfDist === 0) {
  6624. return this._map.layerPointToLatLng(points[0]);
  6625. }
  6626. for (i = 0, dist = 0; i < len - 1; i++) {
  6627. p1 = points[i];
  6628. p2 = points[i + 1];
  6629. segDist = p1.distanceTo(p2);
  6630. dist += segDist;
  6631. if (dist > halfDist) {
  6632. ratio = (dist - halfDist) / segDist;
  6633. return this._map.layerPointToLatLng([
  6634. p2.x - ratio * (p2.x - p1.x),
  6635. p2.y - ratio * (p2.y - p1.y)
  6636. ]);
  6637. }
  6638. }
  6639. },
  6640. // @method getBounds(): LatLngBounds
  6641. // Returns the `LatLngBounds` of the path.
  6642. getBounds: function () {
  6643. return this._bounds;
  6644. },
  6645. // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
  6646. // Adds a given point to the polyline. By default, adds to the first ring of
  6647. // the polyline in case of a multi-polyline, but can be overridden by passing
  6648. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6649. addLatLng: function (latlng, latlngs) {
  6650. latlngs = latlngs || this._defaultShape();
  6651. latlng = toLatLng(latlng);
  6652. latlngs.push(latlng);
  6653. this._bounds.extend(latlng);
  6654. return this.redraw();
  6655. },
  6656. _setLatLngs: function (latlngs) {
  6657. this._bounds = new LatLngBounds();
  6658. this._latlngs = this._convertLatLngs(latlngs);
  6659. },
  6660. _defaultShape: function () {
  6661. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6662. },
  6663. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6664. _convertLatLngs: function (latlngs) {
  6665. var result = [],
  6666. flat = isFlat(latlngs);
  6667. for (var i = 0, len = latlngs.length; i < len; i++) {
  6668. if (flat) {
  6669. result[i] = toLatLng(latlngs[i]);
  6670. this._bounds.extend(result[i]);
  6671. } else {
  6672. result[i] = this._convertLatLngs(latlngs[i]);
  6673. }
  6674. }
  6675. return result;
  6676. },
  6677. _project: function () {
  6678. var pxBounds = new Bounds();
  6679. this._rings = [];
  6680. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  6681. var w = this._clickTolerance(),
  6682. p = new Point(w, w);
  6683. if (this._bounds.isValid() && pxBounds.isValid()) {
  6684. pxBounds.min._subtract(p);
  6685. pxBounds.max._add(p);
  6686. this._pxBounds = pxBounds;
  6687. }
  6688. },
  6689. // recursively turns latlngs into a set of rings with projected coordinates
  6690. _projectLatlngs: function (latlngs, result, projectedBounds) {
  6691. var flat = latlngs[0] instanceof LatLng,
  6692. len = latlngs.length,
  6693. i, ring;
  6694. if (flat) {
  6695. ring = [];
  6696. for (i = 0; i < len; i++) {
  6697. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  6698. projectedBounds.extend(ring[i]);
  6699. }
  6700. result.push(ring);
  6701. } else {
  6702. for (i = 0; i < len; i++) {
  6703. this._projectLatlngs(latlngs[i], result, projectedBounds);
  6704. }
  6705. }
  6706. },
  6707. // clip polyline by renderer bounds so that we have less to render for performance
  6708. _clipPoints: function () {
  6709. var bounds = this._renderer._bounds;
  6710. this._parts = [];
  6711. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6712. return;
  6713. }
  6714. if (this.options.noClip) {
  6715. this._parts = this._rings;
  6716. return;
  6717. }
  6718. var parts = this._parts,
  6719. i, j, k, len, len2, segment, points;
  6720. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  6721. points = this._rings[i];
  6722. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  6723. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  6724. if (!segment) {
  6725. continue;
  6726. }
  6727. parts[k] = parts[k] || [];
  6728. parts[k].push(segment[0]);
  6729. // if segment goes out of screen, or it's the last one, it's the end of the line part
  6730. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  6731. parts[k].push(segment[1]);
  6732. k++;
  6733. }
  6734. }
  6735. }
  6736. },
  6737. // simplify each clipped part of the polyline for performance
  6738. _simplifyPoints: function () {
  6739. var parts = this._parts,
  6740. tolerance = this.options.smoothFactor;
  6741. for (var i = 0, len = parts.length; i < len; i++) {
  6742. parts[i] = simplify(parts[i], tolerance);
  6743. }
  6744. },
  6745. _update: function () {
  6746. if (!this._map) {
  6747. return;
  6748. }
  6749. this._clipPoints();
  6750. this._simplifyPoints();
  6751. this._updatePath();
  6752. },
  6753. _updatePath: function () {
  6754. this._renderer._updatePoly(this);
  6755. },
  6756. // Needed by the `Canvas` renderer for interactivity
  6757. _containsPoint: function (p, closed) {
  6758. var i, j, k, len, len2, part,
  6759. w = this._clickTolerance();
  6760. if (!this._pxBounds || !this._pxBounds.contains(p)) {
  6761. return false;
  6762. }
  6763. // hit detection for polylines
  6764. for (i = 0, len = this._parts.length; i < len; i++) {
  6765. part = this._parts[i];
  6766. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6767. if (!closed && (j === 0)) {
  6768. continue;
  6769. }
  6770. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  6771. return true;
  6772. }
  6773. }
  6774. }
  6775. return false;
  6776. }
  6777. });
  6778. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  6779. // Instantiates a polyline object given an array of geographical points and
  6780. // optionally an options object. You can create a `Polyline` object with
  6781. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  6782. // of geographic points.
  6783. function polyline(latlngs, options) {
  6784. return new Polyline(latlngs, options);
  6785. }
  6786. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  6787. Polyline._flat = _flat;
  6788. /*
  6789. * @class Polygon
  6790. * @aka L.Polygon
  6791. * @inherits Polyline
  6792. *
  6793. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  6794. *
  6795. * 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.
  6796. *
  6797. *
  6798. * @example
  6799. *
  6800. * ```js
  6801. * // create a red polygon from an array of LatLng points
  6802. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  6803. *
  6804. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  6805. *
  6806. * // zoom the map to the polygon
  6807. * map.fitBounds(polygon.getBounds());
  6808. * ```
  6809. *
  6810. * 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:
  6811. *
  6812. * ```js
  6813. * var latlngs = [
  6814. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6815. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6816. * ];
  6817. * ```
  6818. *
  6819. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  6820. *
  6821. * ```js
  6822. * var latlngs = [
  6823. * [ // first polygon
  6824. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6825. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6826. * ],
  6827. * [ // second polygon
  6828. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  6829. * ]
  6830. * ];
  6831. * ```
  6832. */
  6833. var Polygon = Polyline.extend({
  6834. options: {
  6835. fill: true
  6836. },
  6837. isEmpty: function () {
  6838. return !this._latlngs.length || !this._latlngs[0].length;
  6839. },
  6840. getCenter: function () {
  6841. // throws error when not yet added to map as this center calculation requires projected coordinates
  6842. if (!this._map) {
  6843. throw new Error('Must add layer to map before using getCenter()');
  6844. }
  6845. var i, j, p1, p2, f, area, x, y, center,
  6846. points = this._rings[0],
  6847. len = points.length;
  6848. if (!len) {
  6849. return null;
  6850. }
  6851. // polygon centroid algorithm; only uses the first ring if there are multiple
  6852. area = x = y = 0;
  6853. for (i = 0, j = len - 1; i < len; j = i++) {
  6854. p1 = points[i];
  6855. p2 = points[j];
  6856. f = p1.y * p2.x - p2.y * p1.x;
  6857. x += (p1.x + p2.x) * f;
  6858. y += (p1.y + p2.y) * f;
  6859. area += f * 3;
  6860. }
  6861. if (area === 0) {
  6862. // Polygon is so small that all points are on same pixel.
  6863. center = points[0];
  6864. } else {
  6865. center = [x / area, y / area];
  6866. }
  6867. return this._map.layerPointToLatLng(center);
  6868. },
  6869. _convertLatLngs: function (latlngs) {
  6870. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  6871. len = result.length;
  6872. // remove last point if it equals first one
  6873. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  6874. result.pop();
  6875. }
  6876. return result;
  6877. },
  6878. _setLatLngs: function (latlngs) {
  6879. Polyline.prototype._setLatLngs.call(this, latlngs);
  6880. if (isFlat(this._latlngs)) {
  6881. this._latlngs = [this._latlngs];
  6882. }
  6883. },
  6884. _defaultShape: function () {
  6885. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  6886. },
  6887. _clipPoints: function () {
  6888. // polygons need a different clipping algorithm so we redefine that
  6889. var bounds = this._renderer._bounds,
  6890. w = this.options.weight,
  6891. p = new Point(w, w);
  6892. // increase clip padding by stroke width to avoid stroke on clip edges
  6893. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  6894. this._parts = [];
  6895. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6896. return;
  6897. }
  6898. if (this.options.noClip) {
  6899. this._parts = this._rings;
  6900. return;
  6901. }
  6902. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  6903. clipped = clipPolygon(this._rings[i], bounds, true);
  6904. if (clipped.length) {
  6905. this._parts.push(clipped);
  6906. }
  6907. }
  6908. },
  6909. _updatePath: function () {
  6910. this._renderer._updatePoly(this, true);
  6911. },
  6912. // Needed by the `Canvas` renderer for interactivity
  6913. _containsPoint: function (p) {
  6914. var inside = false,
  6915. part, p1, p2, i, j, k, len, len2;
  6916. if (!this._pxBounds.contains(p)) {
  6917. return false;
  6918. }
  6919. // ray casting algorithm for detecting if point is in polygon
  6920. for (i = 0, len = this._parts.length; i < len; i++) {
  6921. part = this._parts[i];
  6922. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6923. p1 = part[j];
  6924. p2 = part[k];
  6925. 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)) {
  6926. inside = !inside;
  6927. }
  6928. }
  6929. }
  6930. // also check if it's on polygon stroke
  6931. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  6932. }
  6933. });
  6934. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  6935. function polygon(latlngs, options) {
  6936. return new Polygon(latlngs, options);
  6937. }
  6938. /*
  6939. * @class GeoJSON
  6940. * @aka L.GeoJSON
  6941. * @inherits FeatureGroup
  6942. *
  6943. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  6944. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  6945. *
  6946. * @example
  6947. *
  6948. * ```js
  6949. * L.geoJSON(data, {
  6950. * style: function (feature) {
  6951. * return {color: feature.properties.color};
  6952. * }
  6953. * }).bindPopup(function (layer) {
  6954. * return layer.feature.properties.description;
  6955. * }).addTo(map);
  6956. * ```
  6957. */
  6958. var GeoJSON = FeatureGroup.extend({
  6959. /* @section
  6960. * @aka GeoJSON options
  6961. *
  6962. * @option pointToLayer: Function = *
  6963. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  6964. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  6965. * The default is to spawn a default `Marker`:
  6966. * ```js
  6967. * function(geoJsonPoint, latlng) {
  6968. * return L.marker(latlng);
  6969. * }
  6970. * ```
  6971. *
  6972. * @option style: Function = *
  6973. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  6974. * called internally when data is added.
  6975. * The default value is to not override any defaults:
  6976. * ```js
  6977. * function (geoJsonFeature) {
  6978. * return {}
  6979. * }
  6980. * ```
  6981. *
  6982. * @option onEachFeature: Function = *
  6983. * A `Function` that will be called once for each created `Feature`, after it has
  6984. * been created and styled. Useful for attaching events and popups to features.
  6985. * The default is to do nothing with the newly created layers:
  6986. * ```js
  6987. * function (feature, layer) {}
  6988. * ```
  6989. *
  6990. * @option filter: Function = *
  6991. * A `Function` that will be used to decide whether to include a feature or not.
  6992. * The default is to include all features:
  6993. * ```js
  6994. * function (geoJsonFeature) {
  6995. * return true;
  6996. * }
  6997. * ```
  6998. * Note: dynamically changing the `filter` option will have effect only on newly
  6999. * added data. It will _not_ re-evaluate already included features.
  7000. *
  7001. * @option coordsToLatLng: Function = *
  7002. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  7003. * The default is the `coordsToLatLng` static method.
  7004. */
  7005. initialize: function (geojson, options) {
  7006. setOptions(this, options);
  7007. this._layers = {};
  7008. if (geojson) {
  7009. this.addData(geojson);
  7010. }
  7011. },
  7012. // @method addData( <GeoJSON> data ): this
  7013. // Adds a GeoJSON object to the layer.
  7014. addData: function (geojson) {
  7015. var features = isArray(geojson) ? geojson : geojson.features,
  7016. i, len, feature;
  7017. if (features) {
  7018. for (i = 0, len = features.length; i < len; i++) {
  7019. // only add this if geometry or geometries are set and not null
  7020. feature = features[i];
  7021. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  7022. this.addData(feature);
  7023. }
  7024. }
  7025. return this;
  7026. }
  7027. var options = this.options;
  7028. if (options.filter && !options.filter(geojson)) {
  7029. return this;
  7030. }
  7031. var layer = geometryToLayer(geojson, options);
  7032. if (!layer) {
  7033. return this;
  7034. }
  7035. layer.feature = asFeature(geojson);
  7036. layer.defaultOptions = layer.options;
  7037. this.resetStyle(layer);
  7038. if (options.onEachFeature) {
  7039. options.onEachFeature(geojson, layer);
  7040. }
  7041. return this.addLayer(layer);
  7042. },
  7043. // @method resetStyle( <Path> layer ): this
  7044. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7045. resetStyle: function (layer) {
  7046. // reset any custom styles
  7047. layer.options = extend({}, layer.defaultOptions);
  7048. this._setLayerStyle(layer, this.options.style);
  7049. return this;
  7050. },
  7051. // @method setStyle( <Function> style ): this
  7052. // Changes styles of GeoJSON vector layers with the given style function.
  7053. setStyle: function (style) {
  7054. return this.eachLayer(function (layer) {
  7055. this._setLayerStyle(layer, style);
  7056. }, this);
  7057. },
  7058. _setLayerStyle: function (layer, style) {
  7059. if (typeof style === 'function') {
  7060. style = style(layer.feature);
  7061. }
  7062. if (layer.setStyle) {
  7063. layer.setStyle(style);
  7064. }
  7065. }
  7066. });
  7067. // @section
  7068. // There are several static functions which can be called without instantiating L.GeoJSON:
  7069. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7070. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7071. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7072. // functions if provided as options.
  7073. function geometryToLayer(geojson, options) {
  7074. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7075. coords = geometry ? geometry.coordinates : null,
  7076. layers = [],
  7077. pointToLayer = options && options.pointToLayer,
  7078. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7079. latlng, latlngs, i, len;
  7080. if (!coords && !geometry) {
  7081. return null;
  7082. }
  7083. switch (geometry.type) {
  7084. case 'Point':
  7085. latlng = _coordsToLatLng(coords);
  7086. return pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng);
  7087. case 'MultiPoint':
  7088. for (i = 0, len = coords.length; i < len; i++) {
  7089. latlng = _coordsToLatLng(coords[i]);
  7090. layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng));
  7091. }
  7092. return new FeatureGroup(layers);
  7093. case 'LineString':
  7094. case 'MultiLineString':
  7095. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7096. return new Polyline(latlngs, options);
  7097. case 'Polygon':
  7098. case 'MultiPolygon':
  7099. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7100. return new Polygon(latlngs, options);
  7101. case 'GeometryCollection':
  7102. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7103. var layer = geometryToLayer({
  7104. geometry: geometry.geometries[i],
  7105. type: 'Feature',
  7106. properties: geojson.properties
  7107. }, options);
  7108. if (layer) {
  7109. layers.push(layer);
  7110. }
  7111. }
  7112. return new FeatureGroup(layers);
  7113. default:
  7114. throw new Error('Invalid GeoJSON object.');
  7115. }
  7116. }
  7117. // @function coordsToLatLng(coords: Array): LatLng
  7118. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7119. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7120. function coordsToLatLng(coords) {
  7121. return new LatLng(coords[1], coords[0], coords[2]);
  7122. }
  7123. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7124. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7125. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7126. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7127. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7128. var latlngs = [];
  7129. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7130. latlng = levelsDeep ?
  7131. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7132. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7133. latlngs.push(latlng);
  7134. }
  7135. return latlngs;
  7136. }
  7137. // @function latLngToCoords(latlng: LatLng, precision?: Number): Array
  7138. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7139. function latLngToCoords(latlng, precision) {
  7140. precision = typeof precision === 'number' ? precision : 6;
  7141. return latlng.alt !== undefined ?
  7142. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7143. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7144. }
  7145. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  7146. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7147. // `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.
  7148. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7149. var coords = [];
  7150. for (var i = 0, len = latlngs.length; i < len; i++) {
  7151. coords.push(levelsDeep ?
  7152. latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :
  7153. latLngToCoords(latlngs[i], precision));
  7154. }
  7155. if (!levelsDeep && closed) {
  7156. coords.push(coords[0]);
  7157. }
  7158. return coords;
  7159. }
  7160. function getFeature(layer, newGeometry) {
  7161. return layer.feature ?
  7162. extend({}, layer.feature, {geometry: newGeometry}) :
  7163. asFeature(newGeometry);
  7164. }
  7165. // @function asFeature(geojson: Object): Object
  7166. // Normalize GeoJSON geometries/features into GeoJSON features.
  7167. function asFeature(geojson) {
  7168. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7169. return geojson;
  7170. }
  7171. return {
  7172. type: 'Feature',
  7173. properties: {},
  7174. geometry: geojson
  7175. };
  7176. }
  7177. var PointToGeoJSON = {
  7178. toGeoJSON: function (precision) {
  7179. return getFeature(this, {
  7180. type: 'Point',
  7181. coordinates: latLngToCoords(this.getLatLng(), precision)
  7182. });
  7183. }
  7184. };
  7185. // @namespace Marker
  7186. // @method toGeoJSON(): Object
  7187. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7188. Marker.include(PointToGeoJSON);
  7189. // @namespace CircleMarker
  7190. // @method toGeoJSON(): Object
  7191. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7192. Circle.include(PointToGeoJSON);
  7193. CircleMarker.include(PointToGeoJSON);
  7194. // @namespace Polyline
  7195. // @method toGeoJSON(): Object
  7196. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7197. Polyline.include({
  7198. toGeoJSON: function (precision) {
  7199. var multi = !isFlat(this._latlngs);
  7200. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7201. return getFeature(this, {
  7202. type: (multi ? 'Multi' : '') + 'LineString',
  7203. coordinates: coords
  7204. });
  7205. }
  7206. });
  7207. // @namespace Polygon
  7208. // @method toGeoJSON(): Object
  7209. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7210. Polygon.include({
  7211. toGeoJSON: function (precision) {
  7212. var holes = !isFlat(this._latlngs),
  7213. multi = holes && !isFlat(this._latlngs[0]);
  7214. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7215. if (!holes) {
  7216. coords = [coords];
  7217. }
  7218. return getFeature(this, {
  7219. type: (multi ? 'Multi' : '') + 'Polygon',
  7220. coordinates: coords
  7221. });
  7222. }
  7223. });
  7224. // @namespace LayerGroup
  7225. LayerGroup.include({
  7226. toMultiPoint: function (precision) {
  7227. var coords = [];
  7228. this.eachLayer(function (layer) {
  7229. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7230. });
  7231. return getFeature(this, {
  7232. type: 'MultiPoint',
  7233. coordinates: coords
  7234. });
  7235. },
  7236. // @method toGeoJSON(): Object
  7237. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7238. toGeoJSON: function (precision) {
  7239. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7240. if (type === 'MultiPoint') {
  7241. return this.toMultiPoint(precision);
  7242. }
  7243. var isGeometryCollection = type === 'GeometryCollection',
  7244. jsons = [];
  7245. this.eachLayer(function (layer) {
  7246. if (layer.toGeoJSON) {
  7247. var json = layer.toGeoJSON(precision);
  7248. if (isGeometryCollection) {
  7249. jsons.push(json.geometry);
  7250. } else {
  7251. var feature = asFeature(json);
  7252. // Squash nested feature collections
  7253. if (feature.type === 'FeatureCollection') {
  7254. jsons.push.apply(jsons, feature.features);
  7255. } else {
  7256. jsons.push(feature);
  7257. }
  7258. }
  7259. }
  7260. });
  7261. if (isGeometryCollection) {
  7262. return getFeature(this, {
  7263. geometries: jsons,
  7264. type: 'GeometryCollection'
  7265. });
  7266. }
  7267. return {
  7268. type: 'FeatureCollection',
  7269. features: jsons
  7270. };
  7271. }
  7272. });
  7273. // @namespace GeoJSON
  7274. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7275. // Creates a GeoJSON layer. Optionally accepts an object in
  7276. // [GeoJSON format](http://geojson.org/geojson-spec.html) to display on the map
  7277. // (you can alternatively add it later with `addData` method) and an `options` object.
  7278. function geoJSON(geojson, options) {
  7279. return new GeoJSON(geojson, options);
  7280. }
  7281. // Backward compatibility.
  7282. var geoJson = geoJSON;
  7283. /*
  7284. * @class ImageOverlay
  7285. * @aka L.ImageOverlay
  7286. * @inherits Interactive layer
  7287. *
  7288. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7289. *
  7290. * @example
  7291. *
  7292. * ```js
  7293. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7294. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7295. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7296. * ```
  7297. */
  7298. var ImageOverlay = Layer.extend({
  7299. // @section
  7300. // @aka ImageOverlay options
  7301. options: {
  7302. // @option opacity: Number = 1.0
  7303. // The opacity of the image overlay.
  7304. opacity: 1,
  7305. // @option alt: String = ''
  7306. // Text for the `alt` attribute of the image (useful for accessibility).
  7307. alt: '',
  7308. // @option interactive: Boolean = false
  7309. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7310. interactive: false,
  7311. // @option crossOrigin: Boolean = false
  7312. // If true, the image will have its crossOrigin attribute set to ''. This is needed if you want to access image pixel data.
  7313. crossOrigin: false,
  7314. // @option errorOverlayUrl: String = ''
  7315. // URL to the overlay image to show in place of the overlay that failed to load.
  7316. errorOverlayUrl: '',
  7317. // @option zIndex: Number = 1
  7318. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the tile layer.
  7319. zIndex: 1,
  7320. // @option className: String = ''
  7321. // A custom class name to assign to the image. Empty by default.
  7322. className: '',
  7323. },
  7324. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7325. this._url = url;
  7326. this._bounds = toLatLngBounds(bounds);
  7327. setOptions(this, options);
  7328. },
  7329. onAdd: function () {
  7330. if (!this._image) {
  7331. this._initImage();
  7332. if (this.options.opacity < 1) {
  7333. this._updateOpacity();
  7334. }
  7335. }
  7336. if (this.options.interactive) {
  7337. addClass(this._image, 'leaflet-interactive');
  7338. this.addInteractiveTarget(this._image);
  7339. }
  7340. this.getPane().appendChild(this._image);
  7341. this._reset();
  7342. },
  7343. onRemove: function () {
  7344. remove(this._image);
  7345. if (this.options.interactive) {
  7346. this.removeInteractiveTarget(this._image);
  7347. }
  7348. },
  7349. // @method setOpacity(opacity: Number): this
  7350. // Sets the opacity of the overlay.
  7351. setOpacity: function (opacity) {
  7352. this.options.opacity = opacity;
  7353. if (this._image) {
  7354. this._updateOpacity();
  7355. }
  7356. return this;
  7357. },
  7358. setStyle: function (styleOpts) {
  7359. if (styleOpts.opacity) {
  7360. this.setOpacity(styleOpts.opacity);
  7361. }
  7362. return this;
  7363. },
  7364. // @method bringToFront(): this
  7365. // Brings the layer to the top of all overlays.
  7366. bringToFront: function () {
  7367. if (this._map) {
  7368. toFront(this._image);
  7369. }
  7370. return this;
  7371. },
  7372. // @method bringToBack(): this
  7373. // Brings the layer to the bottom of all overlays.
  7374. bringToBack: function () {
  7375. if (this._map) {
  7376. toBack(this._image);
  7377. }
  7378. return this;
  7379. },
  7380. // @method setUrl(url: String): this
  7381. // Changes the URL of the image.
  7382. setUrl: function (url) {
  7383. this._url = url;
  7384. if (this._image) {
  7385. this._image.src = url;
  7386. }
  7387. return this;
  7388. },
  7389. // @method setBounds(bounds: LatLngBounds): this
  7390. // Update the bounds that this ImageOverlay covers
  7391. setBounds: function (bounds) {
  7392. this._bounds = toLatLngBounds(bounds);
  7393. if (this._map) {
  7394. this._reset();
  7395. }
  7396. return this;
  7397. },
  7398. getEvents: function () {
  7399. var events = {
  7400. zoom: this._reset,
  7401. viewreset: this._reset
  7402. };
  7403. if (this._zoomAnimated) {
  7404. events.zoomanim = this._animateZoom;
  7405. }
  7406. return events;
  7407. },
  7408. // @method: setZIndex(value: Number) : this
  7409. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7410. setZIndex: function (value) {
  7411. this.options.zIndex = value;
  7412. this._updateZIndex();
  7413. return this;
  7414. },
  7415. // @method getBounds(): LatLngBounds
  7416. // Get the bounds that this ImageOverlay covers
  7417. getBounds: function () {
  7418. return this._bounds;
  7419. },
  7420. // @method getElement(): HTMLElement
  7421. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7422. // used by this overlay.
  7423. getElement: function () {
  7424. return this._image;
  7425. },
  7426. _initImage: function () {
  7427. var img = this._image = create$1('img',
  7428. 'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated' : '') +
  7429. (this.options.className || ''));
  7430. img.onselectstart = falseFn;
  7431. img.onmousemove = falseFn;
  7432. // @event load: Event
  7433. // Fired when the ImageOverlay layer has loaded its image
  7434. img.onload = bind(this.fire, this, 'load');
  7435. img.onerror = bind(this._overlayOnError, this, 'error');
  7436. if (this.options.crossOrigin) {
  7437. img.crossOrigin = '';
  7438. }
  7439. if (this.options.zIndex) {
  7440. this._updateZIndex();
  7441. }
  7442. img.src = this._url;
  7443. img.alt = this.options.alt;
  7444. },
  7445. _animateZoom: function (e) {
  7446. var scale = this._map.getZoomScale(e.zoom),
  7447. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7448. setTransform(this._image, offset, scale);
  7449. },
  7450. _reset: function () {
  7451. var image = this._image,
  7452. bounds = new Bounds(
  7453. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7454. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7455. size = bounds.getSize();
  7456. setPosition(image, bounds.min);
  7457. image.style.width = size.x + 'px';
  7458. image.style.height = size.y + 'px';
  7459. },
  7460. _updateOpacity: function () {
  7461. setOpacity(this._image, this.options.opacity);
  7462. },
  7463. _updateZIndex: function () {
  7464. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7465. this._image.style.zIndex = this.options.zIndex;
  7466. }
  7467. },
  7468. _overlayOnError: function () {
  7469. // @event error: Event
  7470. // Fired when the ImageOverlay layer has loaded its image
  7471. this.fire('error');
  7472. var errorUrl = this.options.errorOverlayUrl;
  7473. if (errorUrl && this._url !== errorUrl) {
  7474. this._url = errorUrl;
  7475. this._image.src = errorUrl;
  7476. }
  7477. }
  7478. });
  7479. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7480. // Instantiates an image overlay object given the URL of the image and the
  7481. // geographical bounds it is tied to.
  7482. var imageOverlay = function (url, bounds, options) {
  7483. return new ImageOverlay(url, bounds, options);
  7484. };
  7485. /*
  7486. * @class VideoOverlay
  7487. * @aka L.VideoOverlay
  7488. * @inherits ImageOverlay
  7489. *
  7490. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7491. *
  7492. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7493. * HTML5 element.
  7494. *
  7495. * @example
  7496. *
  7497. * ```js
  7498. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7499. * videoBounds = [[ 32, -130], [ 13, -100]];
  7500. * L.VideoOverlay(videoUrl, videoBounds ).addTo(map);
  7501. * ```
  7502. */
  7503. var VideoOverlay = ImageOverlay.extend({
  7504. // @section
  7505. // @aka VideoOverlay options
  7506. options: {
  7507. // @option autoplay: Boolean = true
  7508. // Whether the video starts playing automatically when loaded.
  7509. autoplay: true,
  7510. // @option loop: Boolean = true
  7511. // Whether the video will loop back to the beginning when played.
  7512. loop: true
  7513. },
  7514. _initImage: function () {
  7515. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7516. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7517. vid.class = vid.class || '';
  7518. vid.class += 'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated' : '');
  7519. vid.onselectstart = falseFn;
  7520. vid.onmousemove = falseFn;
  7521. // @event load: Event
  7522. // Fired when the video has finished loading the first frame
  7523. vid.onloadeddata = bind(this.fire, this, 'load');
  7524. if (wasElementSupplied) {
  7525. return;
  7526. }
  7527. if (!isArray(this._url)) {
  7528. this._url = [this._url];
  7529. }
  7530. vid.autoplay = !!this.options.autoplay;
  7531. vid.loop = !!this.options.loop;
  7532. for (var i = 0; i < this._url.length; i++) {
  7533. var source = create$1('source');
  7534. source.src = this._url[i];
  7535. vid.appendChild(source);
  7536. }
  7537. }
  7538. // @method getElement(): HTMLVideoElement
  7539. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7540. // used by this overlay.
  7541. });
  7542. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7543. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7544. // geographical bounds it is tied to.
  7545. function videoOverlay(video, bounds, options) {
  7546. return new VideoOverlay(video, bounds, options);
  7547. }
  7548. /*
  7549. * @class DivOverlay
  7550. * @inherits Layer
  7551. * @aka L.DivOverlay
  7552. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  7553. */
  7554. // @namespace DivOverlay
  7555. var DivOverlay = Layer.extend({
  7556. // @section
  7557. // @aka DivOverlay options
  7558. options: {
  7559. // @option offset: Point = Point(0, 7)
  7560. // The offset of the popup position. Useful to control the anchor
  7561. // of the popup when opening it on some overlays.
  7562. offset: [0, 7],
  7563. // @option className: String = ''
  7564. // A custom CSS class name to assign to the popup.
  7565. className: '',
  7566. // @option pane: String = 'popupPane'
  7567. // `Map pane` where the popup will be added.
  7568. pane: 'popupPane'
  7569. },
  7570. initialize: function (options, source) {
  7571. setOptions(this, options);
  7572. this._source = source;
  7573. },
  7574. onAdd: function (map) {
  7575. this._zoomAnimated = map._zoomAnimated;
  7576. if (!this._container) {
  7577. this._initLayout();
  7578. }
  7579. if (map._fadeAnimated) {
  7580. setOpacity(this._container, 0);
  7581. }
  7582. clearTimeout(this._removeTimeout);
  7583. this.getPane().appendChild(this._container);
  7584. this.update();
  7585. if (map._fadeAnimated) {
  7586. setOpacity(this._container, 1);
  7587. }
  7588. this.bringToFront();
  7589. },
  7590. onRemove: function (map) {
  7591. if (map._fadeAnimated) {
  7592. setOpacity(this._container, 0);
  7593. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  7594. } else {
  7595. remove(this._container);
  7596. }
  7597. },
  7598. // @namespace Popup
  7599. // @method getLatLng: LatLng
  7600. // Returns the geographical point of popup.
  7601. getLatLng: function () {
  7602. return this._latlng;
  7603. },
  7604. // @method setLatLng(latlng: LatLng): this
  7605. // Sets the geographical point where the popup will open.
  7606. setLatLng: function (latlng) {
  7607. this._latlng = toLatLng(latlng);
  7608. if (this._map) {
  7609. this._updatePosition();
  7610. this._adjustPan();
  7611. }
  7612. return this;
  7613. },
  7614. // @method getContent: String|HTMLElement
  7615. // Returns the content of the popup.
  7616. getContent: function () {
  7617. return this._content;
  7618. },
  7619. // @method setContent(htmlContent: String|HTMLElement|Function): this
  7620. // Sets the HTML content of the popup. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the popup.
  7621. setContent: function (content) {
  7622. this._content = content;
  7623. this.update();
  7624. return this;
  7625. },
  7626. // @method getElement: String|HTMLElement
  7627. // Alias for [getContent()](#popup-getcontent)
  7628. getElement: function () {
  7629. return this._container;
  7630. },
  7631. // @method update: null
  7632. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  7633. update: function () {
  7634. if (!this._map) {
  7635. return;
  7636. }
  7637. this._container.style.visibility = 'hidden';
  7638. this._updateContent();
  7639. this._updateLayout();
  7640. this._updatePosition();
  7641. this._container.style.visibility = '';
  7642. this._adjustPan();
  7643. },
  7644. getEvents: function () {
  7645. var events = {
  7646. zoom: this._updatePosition,
  7647. viewreset: this._updatePosition
  7648. };
  7649. if (this._zoomAnimated) {
  7650. events.zoomanim = this._animateZoom;
  7651. }
  7652. return events;
  7653. },
  7654. // @method isOpen: Boolean
  7655. // Returns `true` when the popup is visible on the map.
  7656. isOpen: function () {
  7657. return !!this._map && this._map.hasLayer(this);
  7658. },
  7659. // @method bringToFront: this
  7660. // Brings this popup in front of other popups (in the same map pane).
  7661. bringToFront: function () {
  7662. if (this._map) {
  7663. toFront(this._container);
  7664. }
  7665. return this;
  7666. },
  7667. // @method bringToBack: this
  7668. // Brings this popup to the back of other popups (in the same map pane).
  7669. bringToBack: function () {
  7670. if (this._map) {
  7671. toBack(this._container);
  7672. }
  7673. return this;
  7674. },
  7675. _updateContent: function () {
  7676. if (!this._content) {
  7677. return;
  7678. }
  7679. var node = this._contentNode;
  7680. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  7681. if (typeof content === 'string') {
  7682. node.innerHTML = content;
  7683. } else {
  7684. while (node.hasChildNodes()) {
  7685. node.removeChild(node.firstChild);
  7686. }
  7687. node.appendChild(content);
  7688. }
  7689. this.fire('contentupdate');
  7690. },
  7691. _updatePosition: function () {
  7692. if (!this._map) {
  7693. return;
  7694. }
  7695. var pos = this._map.latLngToLayerPoint(this._latlng),
  7696. offset = toPoint(this.options.offset),
  7697. anchor = this._getAnchor();
  7698. if (this._zoomAnimated) {
  7699. setPosition(this._container, pos.add(anchor));
  7700. } else {
  7701. offset = offset.add(pos).add(anchor);
  7702. }
  7703. var bottom = this._containerBottom = -offset.y,
  7704. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  7705. // bottom position the popup in case the height of the popup changes (images loading etc)
  7706. this._container.style.bottom = bottom + 'px';
  7707. this._container.style.left = left + 'px';
  7708. },
  7709. _getAnchor: function () {
  7710. return [0, 0];
  7711. }
  7712. });
  7713. /*
  7714. * @class Popup
  7715. * @inherits DivOverlay
  7716. * @aka L.Popup
  7717. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  7718. * open popups while making sure that only one popup is open at one time
  7719. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  7720. *
  7721. * @example
  7722. *
  7723. * If you want to just bind a popup to marker click and then open it, it's really easy:
  7724. *
  7725. * ```js
  7726. * marker.bindPopup(popupContent).openPopup();
  7727. * ```
  7728. * Path overlays like polylines also have a `bindPopup` method.
  7729. * Here's a more complicated way to open a popup on a map:
  7730. *
  7731. * ```js
  7732. * var popup = L.popup()
  7733. * .setLatLng(latlng)
  7734. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  7735. * .openOn(map);
  7736. * ```
  7737. */
  7738. // @namespace Popup
  7739. var Popup = DivOverlay.extend({
  7740. // @section
  7741. // @aka Popup options
  7742. options: {
  7743. // @option maxWidth: Number = 300
  7744. // Max width of the popup, in pixels.
  7745. maxWidth: 300,
  7746. // @option minWidth: Number = 50
  7747. // Min width of the popup, in pixels.
  7748. minWidth: 50,
  7749. // @option maxHeight: Number = null
  7750. // If set, creates a scrollable container of the given height
  7751. // inside a popup if its content exceeds it.
  7752. maxHeight: null,
  7753. // @option autoPan: Boolean = true
  7754. // Set it to `false` if you don't want the map to do panning animation
  7755. // to fit the opened popup.
  7756. autoPan: true,
  7757. // @option autoPanPaddingTopLeft: Point = null
  7758. // The margin between the popup and the top left corner of the map
  7759. // view after autopanning was performed.
  7760. autoPanPaddingTopLeft: null,
  7761. // @option autoPanPaddingBottomRight: Point = null
  7762. // The margin between the popup and the bottom right corner of the map
  7763. // view after autopanning was performed.
  7764. autoPanPaddingBottomRight: null,
  7765. // @option autoPanPadding: Point = Point(5, 5)
  7766. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  7767. autoPanPadding: [5, 5],
  7768. // @option keepInView: Boolean = false
  7769. // Set it to `true` if you want to prevent users from panning the popup
  7770. // off of the screen while it is open.
  7771. keepInView: false,
  7772. // @option closeButton: Boolean = true
  7773. // Controls the presence of a close button in the popup.
  7774. closeButton: true,
  7775. // @option autoClose: Boolean = true
  7776. // Set it to `false` if you want to override the default behavior of
  7777. // the popup closing when another popup is opened.
  7778. autoClose: true,
  7779. // @option closeOnClick: Boolean = *
  7780. // Set it if you want to override the default behavior of the popup closing when user clicks
  7781. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  7782. // @option className: String = ''
  7783. // A custom CSS class name to assign to the popup.
  7784. className: ''
  7785. },
  7786. // @namespace Popup
  7787. // @method openOn(map: Map): this
  7788. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  7789. openOn: function (map) {
  7790. map.openPopup(this);
  7791. return this;
  7792. },
  7793. onAdd: function (map) {
  7794. DivOverlay.prototype.onAdd.call(this, map);
  7795. // @namespace Map
  7796. // @section Popup events
  7797. // @event popupopen: PopupEvent
  7798. // Fired when a popup is opened in the map
  7799. map.fire('popupopen', {popup: this});
  7800. if (this._source) {
  7801. // @namespace Layer
  7802. // @section Popup events
  7803. // @event popupopen: PopupEvent
  7804. // Fired when a popup bound to this layer is opened
  7805. this._source.fire('popupopen', {popup: this}, true);
  7806. // For non-path layers, we toggle the popup when clicking
  7807. // again the layer, so prevent the map to reopen it.
  7808. if (!(this._source instanceof Path)) {
  7809. this._source.on('preclick', stopPropagation);
  7810. }
  7811. }
  7812. },
  7813. onRemove: function (map) {
  7814. DivOverlay.prototype.onRemove.call(this, map);
  7815. // @namespace Map
  7816. // @section Popup events
  7817. // @event popupclose: PopupEvent
  7818. // Fired when a popup in the map is closed
  7819. map.fire('popupclose', {popup: this});
  7820. if (this._source) {
  7821. // @namespace Layer
  7822. // @section Popup events
  7823. // @event popupclose: PopupEvent
  7824. // Fired when a popup bound to this layer is closed
  7825. this._source.fire('popupclose', {popup: this}, true);
  7826. if (!(this._source instanceof Path)) {
  7827. this._source.off('preclick', stopPropagation);
  7828. }
  7829. }
  7830. },
  7831. getEvents: function () {
  7832. var events = DivOverlay.prototype.getEvents.call(this);
  7833. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  7834. events.preclick = this._close;
  7835. }
  7836. if (this.options.keepInView) {
  7837. events.moveend = this._adjustPan;
  7838. }
  7839. return events;
  7840. },
  7841. _close: function () {
  7842. if (this._map) {
  7843. this._map.closePopup(this);
  7844. }
  7845. },
  7846. _initLayout: function () {
  7847. var prefix = 'leaflet-popup',
  7848. container = this._container = create$1('div',
  7849. prefix + ' ' + (this.options.className || '') +
  7850. ' leaflet-zoom-animated');
  7851. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  7852. this._contentNode = create$1('div', prefix + '-content', wrapper);
  7853. disableClickPropagation(wrapper);
  7854. disableScrollPropagation(this._contentNode);
  7855. on(wrapper, 'contextmenu', stopPropagation);
  7856. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  7857. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  7858. if (this.options.closeButton) {
  7859. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  7860. closeButton.href = '#close';
  7861. closeButton.innerHTML = '&#215;';
  7862. on(closeButton, 'click', this._onCloseButtonClick, this);
  7863. }
  7864. },
  7865. _updateLayout: function () {
  7866. var container = this._contentNode,
  7867. style = container.style;
  7868. style.width = '';
  7869. style.whiteSpace = 'nowrap';
  7870. var width = container.offsetWidth;
  7871. width = Math.min(width, this.options.maxWidth);
  7872. width = Math.max(width, this.options.minWidth);
  7873. style.width = (width + 1) + 'px';
  7874. style.whiteSpace = '';
  7875. style.height = '';
  7876. var height = container.offsetHeight,
  7877. maxHeight = this.options.maxHeight,
  7878. scrolledClass = 'leaflet-popup-scrolled';
  7879. if (maxHeight && height > maxHeight) {
  7880. style.height = maxHeight + 'px';
  7881. addClass(container, scrolledClass);
  7882. } else {
  7883. removeClass(container, scrolledClass);
  7884. }
  7885. this._containerWidth = this._container.offsetWidth;
  7886. },
  7887. _animateZoom: function (e) {
  7888. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  7889. anchor = this._getAnchor();
  7890. setPosition(this._container, pos.add(anchor));
  7891. },
  7892. _adjustPan: function () {
  7893. if (!this.options.autoPan || (this._map._panAnim && this._map._panAnim._inProgress)) {
  7894. return;
  7895. }
  7896. var map = this._map,
  7897. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  7898. containerHeight = this._container.offsetHeight + marginBottom,
  7899. containerWidth = this._containerWidth,
  7900. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  7901. layerPos._add(getPosition(this._container));
  7902. var containerPos = map.layerPointToContainerPoint(layerPos),
  7903. padding = toPoint(this.options.autoPanPadding),
  7904. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  7905. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  7906. size = map.getSize(),
  7907. dx = 0,
  7908. dy = 0;
  7909. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  7910. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  7911. }
  7912. if (containerPos.x - dx - paddingTL.x < 0) { // left
  7913. dx = containerPos.x - paddingTL.x;
  7914. }
  7915. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  7916. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  7917. }
  7918. if (containerPos.y - dy - paddingTL.y < 0) { // top
  7919. dy = containerPos.y - paddingTL.y;
  7920. }
  7921. // @namespace Map
  7922. // @section Popup events
  7923. // @event autopanstart: Event
  7924. // Fired when the map starts autopanning when opening a popup.
  7925. if (dx || dy) {
  7926. map
  7927. .fire('autopanstart')
  7928. .panBy([dx, dy]);
  7929. }
  7930. },
  7931. _onCloseButtonClick: function (e) {
  7932. this._close();
  7933. stop(e);
  7934. },
  7935. _getAnchor: function () {
  7936. // Where should we anchor the popup on the source layer?
  7937. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  7938. }
  7939. });
  7940. // @namespace Popup
  7941. // @factory L.popup(options?: Popup options, source?: Layer)
  7942. // 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.
  7943. var popup = function (options, source) {
  7944. return new Popup(options, source);
  7945. };
  7946. /* @namespace Map
  7947. * @section Interaction Options
  7948. * @option closePopupOnClick: Boolean = true
  7949. * Set it to `false` if you don't want popups to close when user clicks the map.
  7950. */
  7951. Map.mergeOptions({
  7952. closePopupOnClick: true
  7953. });
  7954. // @namespace Map
  7955. // @section Methods for Layers and Controls
  7956. Map.include({
  7957. // @method openPopup(popup: Popup): this
  7958. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  7959. // @alternative
  7960. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  7961. // Creates a popup with the specified content and options and opens it in the given point on a map.
  7962. openPopup: function (popup, latlng, options) {
  7963. if (!(popup instanceof Popup)) {
  7964. popup = new Popup(options).setContent(popup);
  7965. }
  7966. if (latlng) {
  7967. popup.setLatLng(latlng);
  7968. }
  7969. if (this.hasLayer(popup)) {
  7970. return this;
  7971. }
  7972. if (this._popup && this._popup.options.autoClose) {
  7973. this.closePopup();
  7974. }
  7975. this._popup = popup;
  7976. return this.addLayer(popup);
  7977. },
  7978. // @method closePopup(popup?: Popup): this
  7979. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  7980. closePopup: function (popup) {
  7981. if (!popup || popup === this._popup) {
  7982. popup = this._popup;
  7983. this._popup = null;
  7984. }
  7985. if (popup) {
  7986. this.removeLayer(popup);
  7987. }
  7988. return this;
  7989. }
  7990. });
  7991. /*
  7992. * @namespace Layer
  7993. * @section Popup methods example
  7994. *
  7995. * All layers share a set of methods convenient for binding popups to it.
  7996. *
  7997. * ```js
  7998. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  7999. * layer.openPopup();
  8000. * layer.closePopup();
  8001. * ```
  8002. *
  8003. * 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.
  8004. */
  8005. // @section Popup methods
  8006. Layer.include({
  8007. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  8008. // Binds a popup to the layer with the passed `content` and sets up the
  8009. // necessary event listeners. If a `Function` is passed it will receive
  8010. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8011. bindPopup: function (content, options) {
  8012. if (content instanceof Popup) {
  8013. setOptions(content, options);
  8014. this._popup = content;
  8015. content._source = this;
  8016. } else {
  8017. if (!this._popup || options) {
  8018. this._popup = new Popup(options, this);
  8019. }
  8020. this._popup.setContent(content);
  8021. }
  8022. if (!this._popupHandlersAdded) {
  8023. this.on({
  8024. click: this._openPopup,
  8025. keypress: this._onKeyPress,
  8026. remove: this.closePopup,
  8027. move: this._movePopup
  8028. });
  8029. this._popupHandlersAdded = true;
  8030. }
  8031. return this;
  8032. },
  8033. // @method unbindPopup(): this
  8034. // Removes the popup previously bound with `bindPopup`.
  8035. unbindPopup: function () {
  8036. if (this._popup) {
  8037. this.off({
  8038. click: this._openPopup,
  8039. keypress: this._onKeyPress,
  8040. remove: this.closePopup,
  8041. move: this._movePopup
  8042. });
  8043. this._popupHandlersAdded = false;
  8044. this._popup = null;
  8045. }
  8046. return this;
  8047. },
  8048. // @method openPopup(latlng?: LatLng): this
  8049. // Opens the bound popup at the specificed `latlng` or at the default popup anchor if no `latlng` is passed.
  8050. openPopup: function (layer, latlng) {
  8051. if (!(layer instanceof Layer)) {
  8052. latlng = layer;
  8053. layer = this;
  8054. }
  8055. if (layer instanceof FeatureGroup) {
  8056. for (var id in this._layers) {
  8057. layer = this._layers[id];
  8058. break;
  8059. }
  8060. }
  8061. if (!latlng) {
  8062. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  8063. }
  8064. if (this._popup && this._map) {
  8065. // set popup source to this layer
  8066. this._popup._source = layer;
  8067. // update the popup (content, layout, ect...)
  8068. this._popup.update();
  8069. // open the popup on the map
  8070. this._map.openPopup(this._popup, latlng);
  8071. }
  8072. return this;
  8073. },
  8074. // @method closePopup(): this
  8075. // Closes the popup bound to this layer if it is open.
  8076. closePopup: function () {
  8077. if (this._popup) {
  8078. this._popup._close();
  8079. }
  8080. return this;
  8081. },
  8082. // @method togglePopup(): this
  8083. // Opens or closes the popup bound to this layer depending on its current state.
  8084. togglePopup: function (target) {
  8085. if (this._popup) {
  8086. if (this._popup._map) {
  8087. this.closePopup();
  8088. } else {
  8089. this.openPopup(target);
  8090. }
  8091. }
  8092. return this;
  8093. },
  8094. // @method isPopupOpen(): boolean
  8095. // Returns `true` if the popup bound to this layer is currently open.
  8096. isPopupOpen: function () {
  8097. return (this._popup ? this._popup.isOpen() : false);
  8098. },
  8099. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8100. // Sets the content of the popup bound to this layer.
  8101. setPopupContent: function (content) {
  8102. if (this._popup) {
  8103. this._popup.setContent(content);
  8104. }
  8105. return this;
  8106. },
  8107. // @method getPopup(): Popup
  8108. // Returns the popup bound to this layer.
  8109. getPopup: function () {
  8110. return this._popup;
  8111. },
  8112. _openPopup: function (e) {
  8113. var layer = e.layer || e.target;
  8114. if (!this._popup) {
  8115. return;
  8116. }
  8117. if (!this._map) {
  8118. return;
  8119. }
  8120. // prevent map click
  8121. stop(e);
  8122. // if this inherits from Path its a vector and we can just
  8123. // open the popup at the new location
  8124. if (layer instanceof Path) {
  8125. this.openPopup(e.layer || e.target, e.latlng);
  8126. return;
  8127. }
  8128. // otherwise treat it like a marker and figure out
  8129. // if we should toggle it open/closed
  8130. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  8131. this.closePopup();
  8132. } else {
  8133. this.openPopup(layer, e.latlng);
  8134. }
  8135. },
  8136. _movePopup: function (e) {
  8137. this._popup.setLatLng(e.latlng);
  8138. },
  8139. _onKeyPress: function (e) {
  8140. if (e.originalEvent.keyCode === 13) {
  8141. this._openPopup(e);
  8142. }
  8143. }
  8144. });
  8145. /*
  8146. * @class Tooltip
  8147. * @inherits DivOverlay
  8148. * @aka L.Tooltip
  8149. * Used to display small texts on top of map layers.
  8150. *
  8151. * @example
  8152. *
  8153. * ```js
  8154. * marker.bindTooltip("my tooltip text").openTooltip();
  8155. * ```
  8156. * Note about tooltip offset. Leaflet takes two options in consideration
  8157. * for computing tooltip offseting:
  8158. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8159. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8160. * move it to the bottom. Negatives will move to the left and top.
  8161. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8162. * should adapt this value if you use a custom icon.
  8163. */
  8164. // @namespace Tooltip
  8165. var Tooltip = DivOverlay.extend({
  8166. // @section
  8167. // @aka Tooltip options
  8168. options: {
  8169. // @option pane: String = 'tooltipPane'
  8170. // `Map pane` where the tooltip will be added.
  8171. pane: 'tooltipPane',
  8172. // @option offset: Point = Point(0, 0)
  8173. // Optional offset of the tooltip position.
  8174. offset: [0, 0],
  8175. // @option direction: String = 'auto'
  8176. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8177. // `top`, `bottom`, `center`, `auto`.
  8178. // `auto` will dynamicaly switch between `right` and `left` according to the tooltip
  8179. // position on the map.
  8180. direction: 'auto',
  8181. // @option permanent: Boolean = false
  8182. // Whether to open the tooltip permanently or only on mouseover.
  8183. permanent: false,
  8184. // @option sticky: Boolean = false
  8185. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8186. sticky: false,
  8187. // @option interactive: Boolean = false
  8188. // If true, the tooltip will listen to the feature events.
  8189. interactive: false,
  8190. // @option opacity: Number = 0.9
  8191. // Tooltip container opacity.
  8192. opacity: 0.9
  8193. },
  8194. onAdd: function (map) {
  8195. DivOverlay.prototype.onAdd.call(this, map);
  8196. this.setOpacity(this.options.opacity);
  8197. // @namespace Map
  8198. // @section Tooltip events
  8199. // @event tooltipopen: TooltipEvent
  8200. // Fired when a tooltip is opened in the map.
  8201. map.fire('tooltipopen', {tooltip: this});
  8202. if (this._source) {
  8203. // @namespace Layer
  8204. // @section Tooltip events
  8205. // @event tooltipopen: TooltipEvent
  8206. // Fired when a tooltip bound to this layer is opened.
  8207. this._source.fire('tooltipopen', {tooltip: this}, true);
  8208. }
  8209. },
  8210. onRemove: function (map) {
  8211. DivOverlay.prototype.onRemove.call(this, map);
  8212. // @namespace Map
  8213. // @section Tooltip events
  8214. // @event tooltipclose: TooltipEvent
  8215. // Fired when a tooltip in the map is closed.
  8216. map.fire('tooltipclose', {tooltip: this});
  8217. if (this._source) {
  8218. // @namespace Layer
  8219. // @section Tooltip events
  8220. // @event tooltipclose: TooltipEvent
  8221. // Fired when a tooltip bound to this layer is closed.
  8222. this._source.fire('tooltipclose', {tooltip: this}, true);
  8223. }
  8224. },
  8225. getEvents: function () {
  8226. var events = DivOverlay.prototype.getEvents.call(this);
  8227. if (touch && !this.options.permanent) {
  8228. events.preclick = this._close;
  8229. }
  8230. return events;
  8231. },
  8232. _close: function () {
  8233. if (this._map) {
  8234. this._map.closeTooltip(this);
  8235. }
  8236. },
  8237. _initLayout: function () {
  8238. var prefix = 'leaflet-tooltip',
  8239. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8240. this._contentNode = this._container = create$1('div', className);
  8241. },
  8242. _updateLayout: function () {
  8243. },
  8244. _adjustPan: function () {
  8245. },
  8246. _setPosition: function (pos) {
  8247. var map = this._map,
  8248. container = this._container,
  8249. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8250. tooltipPoint = map.layerPointToContainerPoint(pos),
  8251. direction = this.options.direction,
  8252. tooltipWidth = container.offsetWidth,
  8253. tooltipHeight = container.offsetHeight,
  8254. offset = toPoint(this.options.offset),
  8255. anchor = this._getAnchor();
  8256. if (direction === 'top') {
  8257. pos = pos.add(toPoint(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true));
  8258. } else if (direction === 'bottom') {
  8259. pos = pos.subtract(toPoint(tooltipWidth / 2 - offset.x, -offset.y, true));
  8260. } else if (direction === 'center') {
  8261. pos = pos.subtract(toPoint(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true));
  8262. } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
  8263. direction = 'right';
  8264. pos = pos.add(toPoint(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true));
  8265. } else {
  8266. direction = 'left';
  8267. pos = pos.subtract(toPoint(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true));
  8268. }
  8269. removeClass(container, 'leaflet-tooltip-right');
  8270. removeClass(container, 'leaflet-tooltip-left');
  8271. removeClass(container, 'leaflet-tooltip-top');
  8272. removeClass(container, 'leaflet-tooltip-bottom');
  8273. addClass(container, 'leaflet-tooltip-' + direction);
  8274. setPosition(container, pos);
  8275. },
  8276. _updatePosition: function () {
  8277. var pos = this._map.latLngToLayerPoint(this._latlng);
  8278. this._setPosition(pos);
  8279. },
  8280. setOpacity: function (opacity) {
  8281. this.options.opacity = opacity;
  8282. if (this._container) {
  8283. setOpacity(this._container, opacity);
  8284. }
  8285. },
  8286. _animateZoom: function (e) {
  8287. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8288. this._setPosition(pos);
  8289. },
  8290. _getAnchor: function () {
  8291. // Where should we anchor the tooltip on the source layer?
  8292. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8293. }
  8294. });
  8295. // @namespace Tooltip
  8296. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8297. // 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.
  8298. var tooltip = function (options, source) {
  8299. return new Tooltip(options, source);
  8300. };
  8301. // @namespace Map
  8302. // @section Methods for Layers and Controls
  8303. Map.include({
  8304. // @method openTooltip(tooltip: Tooltip): this
  8305. // Opens the specified tooltip.
  8306. // @alternative
  8307. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8308. // Creates a tooltip with the specified content and options and open it.
  8309. openTooltip: function (tooltip, latlng, options) {
  8310. if (!(tooltip instanceof Tooltip)) {
  8311. tooltip = new Tooltip(options).setContent(tooltip);
  8312. }
  8313. if (latlng) {
  8314. tooltip.setLatLng(latlng);
  8315. }
  8316. if (this.hasLayer(tooltip)) {
  8317. return this;
  8318. }
  8319. return this.addLayer(tooltip);
  8320. },
  8321. // @method closeTooltip(tooltip?: Tooltip): this
  8322. // Closes the tooltip given as parameter.
  8323. closeTooltip: function (tooltip) {
  8324. if (tooltip) {
  8325. this.removeLayer(tooltip);
  8326. }
  8327. return this;
  8328. }
  8329. });
  8330. /*
  8331. * @namespace Layer
  8332. * @section Tooltip methods example
  8333. *
  8334. * All layers share a set of methods convenient for binding tooltips to it.
  8335. *
  8336. * ```js
  8337. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8338. * layer.openTooltip();
  8339. * layer.closeTooltip();
  8340. * ```
  8341. */
  8342. // @section Tooltip methods
  8343. Layer.include({
  8344. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8345. // Binds a tooltip to the layer with the passed `content` and sets up the
  8346. // necessary event listeners. If a `Function` is passed it will receive
  8347. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8348. bindTooltip: function (content, options) {
  8349. if (content instanceof Tooltip) {
  8350. setOptions(content, options);
  8351. this._tooltip = content;
  8352. content._source = this;
  8353. } else {
  8354. if (!this._tooltip || options) {
  8355. this._tooltip = new Tooltip(options, this);
  8356. }
  8357. this._tooltip.setContent(content);
  8358. }
  8359. this._initTooltipInteractions();
  8360. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8361. this.openTooltip();
  8362. }
  8363. return this;
  8364. },
  8365. // @method unbindTooltip(): this
  8366. // Removes the tooltip previously bound with `bindTooltip`.
  8367. unbindTooltip: function () {
  8368. if (this._tooltip) {
  8369. this._initTooltipInteractions(true);
  8370. this.closeTooltip();
  8371. this._tooltip = null;
  8372. }
  8373. return this;
  8374. },
  8375. _initTooltipInteractions: function (remove$$1) {
  8376. if (!remove$$1 && this._tooltipHandlersAdded) {
  8377. return;
  8378. }
  8379. var onOff = remove$$1 ? 'off' : 'on',
  8380. events = {
  8381. remove: this.closeTooltip,
  8382. move: this._moveTooltip
  8383. };
  8384. if (!this._tooltip.options.permanent) {
  8385. events.mouseover = this._openTooltip;
  8386. events.mouseout = this.closeTooltip;
  8387. if (this._tooltip.options.sticky) {
  8388. events.mousemove = this._moveTooltip;
  8389. }
  8390. if (touch) {
  8391. events.click = this._openTooltip;
  8392. }
  8393. } else {
  8394. events.add = this._openTooltip;
  8395. }
  8396. this[onOff](events);
  8397. this._tooltipHandlersAdded = !remove$$1;
  8398. },
  8399. // @method openTooltip(latlng?: LatLng): this
  8400. // Opens the bound tooltip at the specificed `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8401. openTooltip: function (layer, latlng) {
  8402. if (!(layer instanceof Layer)) {
  8403. latlng = layer;
  8404. layer = this;
  8405. }
  8406. if (layer instanceof FeatureGroup) {
  8407. for (var id in this._layers) {
  8408. layer = this._layers[id];
  8409. break;
  8410. }
  8411. }
  8412. if (!latlng) {
  8413. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  8414. }
  8415. if (this._tooltip && this._map) {
  8416. // set tooltip source to this layer
  8417. this._tooltip._source = layer;
  8418. // update the tooltip (content, layout, ect...)
  8419. this._tooltip.update();
  8420. // open the tooltip on the map
  8421. this._map.openTooltip(this._tooltip, latlng);
  8422. // Tooltip container may not be defined if not permanent and never
  8423. // opened.
  8424. if (this._tooltip.options.interactive && this._tooltip._container) {
  8425. addClass(this._tooltip._container, 'leaflet-clickable');
  8426. this.addInteractiveTarget(this._tooltip._container);
  8427. }
  8428. }
  8429. return this;
  8430. },
  8431. // @method closeTooltip(): this
  8432. // Closes the tooltip bound to this layer if it is open.
  8433. closeTooltip: function () {
  8434. if (this._tooltip) {
  8435. this._tooltip._close();
  8436. if (this._tooltip.options.interactive && this._tooltip._container) {
  8437. removeClass(this._tooltip._container, 'leaflet-clickable');
  8438. this.removeInteractiveTarget(this._tooltip._container);
  8439. }
  8440. }
  8441. return this;
  8442. },
  8443. // @method toggleTooltip(): this
  8444. // Opens or closes the tooltip bound to this layer depending on its current state.
  8445. toggleTooltip: function (target) {
  8446. if (this._tooltip) {
  8447. if (this._tooltip._map) {
  8448. this.closeTooltip();
  8449. } else {
  8450. this.openTooltip(target);
  8451. }
  8452. }
  8453. return this;
  8454. },
  8455. // @method isTooltipOpen(): boolean
  8456. // Returns `true` if the tooltip bound to this layer is currently open.
  8457. isTooltipOpen: function () {
  8458. return this._tooltip.isOpen();
  8459. },
  8460. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8461. // Sets the content of the tooltip bound to this layer.
  8462. setTooltipContent: function (content) {
  8463. if (this._tooltip) {
  8464. this._tooltip.setContent(content);
  8465. }
  8466. return this;
  8467. },
  8468. // @method getTooltip(): Tooltip
  8469. // Returns the tooltip bound to this layer.
  8470. getTooltip: function () {
  8471. return this._tooltip;
  8472. },
  8473. _openTooltip: function (e) {
  8474. var layer = e.layer || e.target;
  8475. if (!this._tooltip || !this._map) {
  8476. return;
  8477. }
  8478. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  8479. },
  8480. _moveTooltip: function (e) {
  8481. var latlng = e.latlng, containerPoint, layerPoint;
  8482. if (this._tooltip.options.sticky && e.originalEvent) {
  8483. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  8484. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  8485. latlng = this._map.layerPointToLatLng(layerPoint);
  8486. }
  8487. this._tooltip.setLatLng(latlng);
  8488. }
  8489. });
  8490. /*
  8491. * @class DivIcon
  8492. * @aka L.DivIcon
  8493. * @inherits Icon
  8494. *
  8495. * Represents a lightweight icon for markers that uses a simple `<div>`
  8496. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  8497. *
  8498. * @example
  8499. * ```js
  8500. * var myIcon = L.divIcon({className: 'my-div-icon'});
  8501. * // you can set .my-div-icon styles in CSS
  8502. *
  8503. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  8504. * ```
  8505. *
  8506. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  8507. */
  8508. var DivIcon = Icon.extend({
  8509. options: {
  8510. // @section
  8511. // @aka DivIcon options
  8512. iconSize: [12, 12], // also can be set through CSS
  8513. // iconAnchor: (Point),
  8514. // popupAnchor: (Point),
  8515. // @option html: String = ''
  8516. // Custom HTML code to put inside the div element, empty by default.
  8517. html: false,
  8518. // @option bgPos: Point = [0, 0]
  8519. // Optional relative position of the background, in pixels
  8520. bgPos: null,
  8521. className: 'leaflet-div-icon'
  8522. },
  8523. createIcon: function (oldIcon) {
  8524. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  8525. options = this.options;
  8526. div.innerHTML = options.html !== false ? options.html : '';
  8527. if (options.bgPos) {
  8528. var bgPos = toPoint(options.bgPos);
  8529. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  8530. }
  8531. this._setIconStyles(div, 'icon');
  8532. return div;
  8533. },
  8534. createShadow: function () {
  8535. return null;
  8536. }
  8537. });
  8538. // @factory L.divIcon(options: DivIcon options)
  8539. // Creates a `DivIcon` instance with the given options.
  8540. function divIcon(options) {
  8541. return new DivIcon(options);
  8542. }
  8543. Icon.Default = IconDefault;
  8544. /*
  8545. * @class GridLayer
  8546. * @inherits Layer
  8547. * @aka L.GridLayer
  8548. *
  8549. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  8550. * 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.
  8551. *
  8552. *
  8553. * @section Synchronous usage
  8554. * @example
  8555. *
  8556. * 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.
  8557. *
  8558. * ```js
  8559. * var CanvasLayer = L.GridLayer.extend({
  8560. * createTile: function(coords){
  8561. * // create a <canvas> element for drawing
  8562. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8563. *
  8564. * // setup tile width and height according to the options
  8565. * var size = this.getTileSize();
  8566. * tile.width = size.x;
  8567. * tile.height = size.y;
  8568. *
  8569. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  8570. * var ctx = tile.getContext('2d');
  8571. *
  8572. * // return the tile so it can be rendered on screen
  8573. * return tile;
  8574. * }
  8575. * });
  8576. * ```
  8577. *
  8578. * @section Asynchronous usage
  8579. * @example
  8580. *
  8581. * 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.
  8582. *
  8583. * ```js
  8584. * var CanvasLayer = L.GridLayer.extend({
  8585. * createTile: function(coords, done){
  8586. * var error;
  8587. *
  8588. * // create a <canvas> element for drawing
  8589. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8590. *
  8591. * // setup tile width and height according to the options
  8592. * var size = this.getTileSize();
  8593. * tile.width = size.x;
  8594. * tile.height = size.y;
  8595. *
  8596. * // draw something asynchronously and pass the tile to the done() callback
  8597. * setTimeout(function() {
  8598. * done(error, tile);
  8599. * }, 1000);
  8600. *
  8601. * return tile;
  8602. * }
  8603. * });
  8604. * ```
  8605. *
  8606. * @section
  8607. */
  8608. var GridLayer = Layer.extend({
  8609. // @section
  8610. // @aka GridLayer options
  8611. options: {
  8612. // @option tileSize: Number|Point = 256
  8613. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  8614. tileSize: 256,
  8615. // @option opacity: Number = 1.0
  8616. // Opacity of the tiles. Can be used in the `createTile()` function.
  8617. opacity: 1,
  8618. // @option updateWhenIdle: Boolean = (depends)
  8619. // Load new tiles only when panning ends.
  8620. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  8621. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  8622. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  8623. updateWhenIdle: mobile,
  8624. // @option updateWhenZooming: Boolean = true
  8625. // 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.
  8626. updateWhenZooming: true,
  8627. // @option updateInterval: Number = 200
  8628. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  8629. updateInterval: 200,
  8630. // @option zIndex: Number = 1
  8631. // The explicit zIndex of the tile layer.
  8632. zIndex: 1,
  8633. // @option bounds: LatLngBounds = undefined
  8634. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  8635. bounds: null,
  8636. // @option minZoom: Number = 0
  8637. // The minimum zoom level down to which this layer will be displayed (inclusive).
  8638. minZoom: 0,
  8639. // @option maxZoom: Number = undefined
  8640. // The maximum zoom level up to which this layer will be displayed (inclusive).
  8641. maxZoom: undefined,
  8642. // @option maxNativeZoom: Number = undefined
  8643. // Maximum zoom number the tile source has available. If it is specified,
  8644. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  8645. // from `maxNativeZoom` level and auto-scaled.
  8646. maxNativeZoom: undefined,
  8647. // @option minNativeZoom: Number = undefined
  8648. // Minimum zoom number the tile source has available. If it is specified,
  8649. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  8650. // from `minNativeZoom` level and auto-scaled.
  8651. minNativeZoom: undefined,
  8652. // @option noWrap: Boolean = false
  8653. // Whether the layer is wrapped around the antimeridian. If `true`, the
  8654. // GridLayer will only be displayed once at low zoom levels. Has no
  8655. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  8656. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  8657. // tiles outside the CRS limits.
  8658. noWrap: false,
  8659. // @option pane: String = 'tilePane'
  8660. // `Map pane` where the grid layer will be added.
  8661. pane: 'tilePane',
  8662. // @option className: String = ''
  8663. // A custom class name to assign to the tile layer. Empty by default.
  8664. className: '',
  8665. // @option keepBuffer: Number = 2
  8666. // When panning the map, keep this many rows and columns of tiles before unloading them.
  8667. keepBuffer: 2
  8668. },
  8669. initialize: function (options) {
  8670. setOptions(this, options);
  8671. },
  8672. onAdd: function () {
  8673. this._initContainer();
  8674. this._levels = {};
  8675. this._tiles = {};
  8676. this._resetView();
  8677. this._update();
  8678. },
  8679. beforeAdd: function (map) {
  8680. map._addZoomLimit(this);
  8681. },
  8682. onRemove: function (map) {
  8683. this._removeAllTiles();
  8684. remove(this._container);
  8685. map._removeZoomLimit(this);
  8686. this._container = null;
  8687. this._tileZoom = null;
  8688. },
  8689. // @method bringToFront: this
  8690. // Brings the tile layer to the top of all tile layers.
  8691. bringToFront: function () {
  8692. if (this._map) {
  8693. toFront(this._container);
  8694. this._setAutoZIndex(Math.max);
  8695. }
  8696. return this;
  8697. },
  8698. // @method bringToBack: this
  8699. // Brings the tile layer to the bottom of all tile layers.
  8700. bringToBack: function () {
  8701. if (this._map) {
  8702. toBack(this._container);
  8703. this._setAutoZIndex(Math.min);
  8704. }
  8705. return this;
  8706. },
  8707. // @method getContainer: HTMLElement
  8708. // Returns the HTML element that contains the tiles for this layer.
  8709. getContainer: function () {
  8710. return this._container;
  8711. },
  8712. // @method setOpacity(opacity: Number): this
  8713. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  8714. setOpacity: function (opacity) {
  8715. this.options.opacity = opacity;
  8716. this._updateOpacity();
  8717. return this;
  8718. },
  8719. // @method setZIndex(zIndex: Number): this
  8720. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  8721. setZIndex: function (zIndex) {
  8722. this.options.zIndex = zIndex;
  8723. this._updateZIndex();
  8724. return this;
  8725. },
  8726. // @method isLoading: Boolean
  8727. // Returns `true` if any tile in the grid layer has not finished loading.
  8728. isLoading: function () {
  8729. return this._loading;
  8730. },
  8731. // @method redraw: this
  8732. // Causes the layer to clear all the tiles and request them again.
  8733. redraw: function () {
  8734. if (this._map) {
  8735. this._removeAllTiles();
  8736. this._update();
  8737. }
  8738. return this;
  8739. },
  8740. getEvents: function () {
  8741. var events = {
  8742. viewprereset: this._invalidateAll,
  8743. viewreset: this._resetView,
  8744. zoom: this._resetView,
  8745. moveend: this._onMoveEnd
  8746. };
  8747. if (!this.options.updateWhenIdle) {
  8748. // update tiles on move, but not more often than once per given interval
  8749. if (!this._onMove) {
  8750. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  8751. }
  8752. events.move = this._onMove;
  8753. }
  8754. if (this._zoomAnimated) {
  8755. events.zoomanim = this._animateZoom;
  8756. }
  8757. return events;
  8758. },
  8759. // @section Extension methods
  8760. // Layers extending `GridLayer` shall reimplement the following method.
  8761. // @method createTile(coords: Object, done?: Function): HTMLElement
  8762. // Called only internally, must be overriden by classes extending `GridLayer`.
  8763. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  8764. // is specified, it must be called when the tile has finished loading and drawing.
  8765. createTile: function () {
  8766. return document.createElement('div');
  8767. },
  8768. // @section
  8769. // @method getTileSize: Point
  8770. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  8771. getTileSize: function () {
  8772. var s = this.options.tileSize;
  8773. return s instanceof Point ? s : new Point(s, s);
  8774. },
  8775. _updateZIndex: function () {
  8776. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  8777. this._container.style.zIndex = this.options.zIndex;
  8778. }
  8779. },
  8780. _setAutoZIndex: function (compare) {
  8781. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  8782. var layers = this.getPane().children,
  8783. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  8784. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  8785. zIndex = layers[i].style.zIndex;
  8786. if (layers[i] !== this._container && zIndex) {
  8787. edgeZIndex = compare(edgeZIndex, +zIndex);
  8788. }
  8789. }
  8790. if (isFinite(edgeZIndex)) {
  8791. this.options.zIndex = edgeZIndex + compare(-1, 1);
  8792. this._updateZIndex();
  8793. }
  8794. },
  8795. _updateOpacity: function () {
  8796. if (!this._map) {
  8797. return;
  8798. }
  8799. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  8800. if (ielt9) {
  8801. return;
  8802. }
  8803. setOpacity(this._container, this.options.opacity);
  8804. var now = +new Date(),
  8805. nextFrame = false,
  8806. willPrune = false;
  8807. for (var key in this._tiles) {
  8808. var tile = this._tiles[key];
  8809. if (!tile.current || !tile.loaded) {
  8810. continue;
  8811. }
  8812. var fade = Math.min(1, (now - tile.loaded) / 200);
  8813. setOpacity(tile.el, fade);
  8814. if (fade < 1) {
  8815. nextFrame = true;
  8816. } else {
  8817. if (tile.active) {
  8818. willPrune = true;
  8819. } else {
  8820. this._onOpaqueTile(tile);
  8821. }
  8822. tile.active = true;
  8823. }
  8824. }
  8825. if (willPrune && !this._noPrune) {
  8826. this._pruneTiles();
  8827. }
  8828. if (nextFrame) {
  8829. cancelAnimFrame(this._fadeFrame);
  8830. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  8831. }
  8832. },
  8833. _onOpaqueTile: falseFn,
  8834. _initContainer: function () {
  8835. if (this._container) {
  8836. return;
  8837. }
  8838. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  8839. this._updateZIndex();
  8840. if (this.options.opacity < 1) {
  8841. this._updateOpacity();
  8842. }
  8843. this.getPane().appendChild(this._container);
  8844. },
  8845. _updateLevels: function () {
  8846. var zoom = this._tileZoom,
  8847. maxZoom = this.options.maxZoom;
  8848. if (zoom === undefined) {
  8849. return undefined;
  8850. }
  8851. for (var z in this._levels) {
  8852. if (this._levels[z].el.children.length || z === zoom) {
  8853. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  8854. this._onUpdateLevel(z);
  8855. } else {
  8856. remove(this._levels[z].el);
  8857. this._removeTilesAtZoom(z);
  8858. this._onRemoveLevel(z);
  8859. delete this._levels[z];
  8860. }
  8861. }
  8862. var level = this._levels[zoom],
  8863. map = this._map;
  8864. if (!level) {
  8865. level = this._levels[zoom] = {};
  8866. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  8867. level.el.style.zIndex = maxZoom;
  8868. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  8869. level.zoom = zoom;
  8870. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  8871. // force the browser to consider the newly added element for transition
  8872. falseFn(level.el.offsetWidth);
  8873. this._onCreateLevel(level);
  8874. }
  8875. this._level = level;
  8876. return level;
  8877. },
  8878. _onUpdateLevel: falseFn,
  8879. _onRemoveLevel: falseFn,
  8880. _onCreateLevel: falseFn,
  8881. _pruneTiles: function () {
  8882. if (!this._map) {
  8883. return;
  8884. }
  8885. var key, tile;
  8886. var zoom = this._map.getZoom();
  8887. if (zoom > this.options.maxZoom ||
  8888. zoom < this.options.minZoom) {
  8889. this._removeAllTiles();
  8890. return;
  8891. }
  8892. for (key in this._tiles) {
  8893. tile = this._tiles[key];
  8894. tile.retain = tile.current;
  8895. }
  8896. for (key in this._tiles) {
  8897. tile = this._tiles[key];
  8898. if (tile.current && !tile.active) {
  8899. var coords = tile.coords;
  8900. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  8901. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  8902. }
  8903. }
  8904. }
  8905. for (key in this._tiles) {
  8906. if (!this._tiles[key].retain) {
  8907. this._removeTile(key);
  8908. }
  8909. }
  8910. },
  8911. _removeTilesAtZoom: function (zoom) {
  8912. for (var key in this._tiles) {
  8913. if (this._tiles[key].coords.z !== zoom) {
  8914. continue;
  8915. }
  8916. this._removeTile(key);
  8917. }
  8918. },
  8919. _removeAllTiles: function () {
  8920. for (var key in this._tiles) {
  8921. this._removeTile(key);
  8922. }
  8923. },
  8924. _invalidateAll: function () {
  8925. for (var z in this._levels) {
  8926. remove(this._levels[z].el);
  8927. this._onRemoveLevel(z);
  8928. delete this._levels[z];
  8929. }
  8930. this._removeAllTiles();
  8931. this._tileZoom = null;
  8932. },
  8933. _retainParent: function (x, y, z, minZoom) {
  8934. var x2 = Math.floor(x / 2),
  8935. y2 = Math.floor(y / 2),
  8936. z2 = z - 1,
  8937. coords2 = new Point(+x2, +y2);
  8938. coords2.z = +z2;
  8939. var key = this._tileCoordsToKey(coords2),
  8940. tile = this._tiles[key];
  8941. if (tile && tile.active) {
  8942. tile.retain = true;
  8943. return true;
  8944. } else if (tile && tile.loaded) {
  8945. tile.retain = true;
  8946. }
  8947. if (z2 > minZoom) {
  8948. return this._retainParent(x2, y2, z2, minZoom);
  8949. }
  8950. return false;
  8951. },
  8952. _retainChildren: function (x, y, z, maxZoom) {
  8953. for (var i = 2 * x; i < 2 * x + 2; i++) {
  8954. for (var j = 2 * y; j < 2 * y + 2; j++) {
  8955. var coords = new Point(i, j);
  8956. coords.z = z + 1;
  8957. var key = this._tileCoordsToKey(coords),
  8958. tile = this._tiles[key];
  8959. if (tile && tile.active) {
  8960. tile.retain = true;
  8961. continue;
  8962. } else if (tile && tile.loaded) {
  8963. tile.retain = true;
  8964. }
  8965. if (z + 1 < maxZoom) {
  8966. this._retainChildren(i, j, z + 1, maxZoom);
  8967. }
  8968. }
  8969. }
  8970. },
  8971. _resetView: function (e) {
  8972. var animating = e && (e.pinch || e.flyTo);
  8973. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  8974. },
  8975. _animateZoom: function (e) {
  8976. this._setView(e.center, e.zoom, true, e.noUpdate);
  8977. },
  8978. _clampZoom: function (zoom) {
  8979. var options = this.options;
  8980. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  8981. return options.minNativeZoom;
  8982. }
  8983. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  8984. return options.maxNativeZoom;
  8985. }
  8986. return zoom;
  8987. },
  8988. _setView: function (center, zoom, noPrune, noUpdate) {
  8989. var tileZoom = this._clampZoom(Math.round(zoom));
  8990. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  8991. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  8992. tileZoom = undefined;
  8993. }
  8994. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  8995. if (!noUpdate || tileZoomChanged) {
  8996. this._tileZoom = tileZoom;
  8997. if (this._abortLoading) {
  8998. this._abortLoading();
  8999. }
  9000. this._updateLevels();
  9001. this._resetGrid();
  9002. if (tileZoom !== undefined) {
  9003. this._update(center);
  9004. }
  9005. if (!noPrune) {
  9006. this._pruneTiles();
  9007. }
  9008. // Flag to prevent _updateOpacity from pruning tiles during
  9009. // a zoom anim or a pinch gesture
  9010. this._noPrune = !!noPrune;
  9011. }
  9012. this._setZoomTransforms(center, zoom);
  9013. },
  9014. _setZoomTransforms: function (center, zoom) {
  9015. for (var i in this._levels) {
  9016. this._setZoomTransform(this._levels[i], center, zoom);
  9017. }
  9018. },
  9019. _setZoomTransform: function (level, center, zoom) {
  9020. var scale = this._map.getZoomScale(zoom, level.zoom),
  9021. translate = level.origin.multiplyBy(scale)
  9022. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  9023. if (any3d) {
  9024. setTransform(level.el, translate, scale);
  9025. } else {
  9026. setPosition(level.el, translate);
  9027. }
  9028. },
  9029. _resetGrid: function () {
  9030. var map = this._map,
  9031. crs = map.options.crs,
  9032. tileSize = this._tileSize = this.getTileSize(),
  9033. tileZoom = this._tileZoom;
  9034. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  9035. if (bounds) {
  9036. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  9037. }
  9038. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  9039. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  9040. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  9041. ];
  9042. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  9043. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  9044. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  9045. ];
  9046. },
  9047. _onMoveEnd: function () {
  9048. if (!this._map || this._map._animatingZoom) {
  9049. return;
  9050. }
  9051. this._update();
  9052. },
  9053. _getTiledPixelBounds: function (center) {
  9054. var map = this._map,
  9055. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9056. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9057. pixelCenter = map.project(center, this._tileZoom).floor(),
  9058. halfSize = map.getSize().divideBy(scale * 2);
  9059. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9060. },
  9061. // Private method to load tiles in the grid's active zoom level according to map bounds
  9062. _update: function (center) {
  9063. var map = this._map;
  9064. if (!map) {
  9065. return;
  9066. }
  9067. var zoom = this._clampZoom(map.getZoom());
  9068. if (center === undefined) {
  9069. center = map.getCenter();
  9070. }
  9071. if (this._tileZoom === undefined) {
  9072. return;
  9073. } // if out of minzoom/maxzoom
  9074. var pixelBounds = this._getTiledPixelBounds(center),
  9075. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9076. tileCenter = tileRange.getCenter(),
  9077. queue = [],
  9078. margin = this.options.keepBuffer,
  9079. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9080. tileRange.getTopRight().add([margin, -margin]));
  9081. // Sanity check: panic if the tile range contains Infinity somewhere.
  9082. if (!(isFinite(tileRange.min.x) &&
  9083. isFinite(tileRange.min.y) &&
  9084. isFinite(tileRange.max.x) &&
  9085. isFinite(tileRange.max.y))) {
  9086. throw new Error('Attempted to load an infinite number of tiles');
  9087. }
  9088. for (var key in this._tiles) {
  9089. var c = this._tiles[key].coords;
  9090. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9091. this._tiles[key].current = false;
  9092. }
  9093. }
  9094. // _update just loads more tiles. If the tile zoom level differs too much
  9095. // from the map's, let _setView reset levels and prune old tiles.
  9096. if (Math.abs(zoom - this._tileZoom) > 1) {
  9097. this._setView(center, zoom);
  9098. return;
  9099. }
  9100. // create a queue of coordinates to load tiles from
  9101. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9102. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9103. var coords = new Point(i, j);
  9104. coords.z = this._tileZoom;
  9105. if (!this._isValidTile(coords)) {
  9106. continue;
  9107. }
  9108. if (!this._tiles[this._tileCoordsToKey(coords)]) {
  9109. queue.push(coords);
  9110. }
  9111. }
  9112. }
  9113. // sort tile queue to load tiles in order of their distance to center
  9114. queue.sort(function (a, b) {
  9115. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9116. });
  9117. if (queue.length !== 0) {
  9118. // if it's the first batch of tiles to load
  9119. if (!this._loading) {
  9120. this._loading = true;
  9121. // @event loading: Event
  9122. // Fired when the grid layer starts loading tiles.
  9123. this.fire('loading');
  9124. }
  9125. // create DOM fragment to append tiles in one batch
  9126. var fragment = document.createDocumentFragment();
  9127. for (i = 0; i < queue.length; i++) {
  9128. this._addTile(queue[i], fragment);
  9129. }
  9130. this._level.el.appendChild(fragment);
  9131. }
  9132. },
  9133. _isValidTile: function (coords) {
  9134. var crs = this._map.options.crs;
  9135. if (!crs.infinite) {
  9136. // don't load tile if it's out of bounds and not wrapped
  9137. var bounds = this._globalTileRange;
  9138. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9139. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) {
  9140. return false;
  9141. }
  9142. }
  9143. if (!this.options.bounds) {
  9144. return true;
  9145. }
  9146. // don't load tile if it doesn't intersect the bounds in options
  9147. var tileBounds = this._tileCoordsToBounds(coords);
  9148. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9149. },
  9150. _keyToBounds: function (key) {
  9151. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9152. },
  9153. // converts tile coordinates to its geographical bounds
  9154. _tileCoordsToBounds: function (coords) {
  9155. var map = this._map,
  9156. tileSize = this.getTileSize(),
  9157. nwPoint = coords.scaleBy(tileSize),
  9158. sePoint = nwPoint.add(tileSize),
  9159. nw = map.unproject(nwPoint, coords.z),
  9160. se = map.unproject(sePoint, coords.z),
  9161. bounds = new LatLngBounds(nw, se);
  9162. if (!this.options.noWrap) {
  9163. map.wrapLatLngBounds(bounds);
  9164. }
  9165. return bounds;
  9166. },
  9167. // converts tile coordinates to key for the tile cache
  9168. _tileCoordsToKey: function (coords) {
  9169. return coords.x + ':' + coords.y + ':' + coords.z;
  9170. },
  9171. // converts tile cache key to coordinates
  9172. _keyToTileCoords: function (key) {
  9173. var k = key.split(':'),
  9174. coords = new Point(+k[0], +k[1]);
  9175. coords.z = +k[2];
  9176. return coords;
  9177. },
  9178. _removeTile: function (key) {
  9179. var tile = this._tiles[key];
  9180. if (!tile) {
  9181. return;
  9182. }
  9183. remove(tile.el);
  9184. delete this._tiles[key];
  9185. // @event tileunload: TileEvent
  9186. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9187. this.fire('tileunload', {
  9188. tile: tile.el,
  9189. coords: this._keyToTileCoords(key)
  9190. });
  9191. },
  9192. _initTile: function (tile) {
  9193. addClass(tile, 'leaflet-tile');
  9194. var tileSize = this.getTileSize();
  9195. tile.style.width = tileSize.x + 'px';
  9196. tile.style.height = tileSize.y + 'px';
  9197. tile.onselectstart = falseFn;
  9198. tile.onmousemove = falseFn;
  9199. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9200. if (ielt9 && this.options.opacity < 1) {
  9201. setOpacity(tile, this.options.opacity);
  9202. }
  9203. // without this hack, tiles disappear after zoom on Chrome for Android
  9204. // https://github.com/Leaflet/Leaflet/issues/2078
  9205. if (android && !android23) {
  9206. tile.style.WebkitBackfaceVisibility = 'hidden';
  9207. }
  9208. },
  9209. _addTile: function (coords, container) {
  9210. var tilePos = this._getTilePos(coords),
  9211. key = this._tileCoordsToKey(coords);
  9212. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9213. this._initTile(tile);
  9214. // if createTile is defined with a second argument ("done" callback),
  9215. // we know that tile is async and will be ready later; otherwise
  9216. if (this.createTile.length < 2) {
  9217. // mark tile as ready, but delay one frame for opacity animation to happen
  9218. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9219. }
  9220. setPosition(tile, tilePos);
  9221. // save tile in cache
  9222. this._tiles[key] = {
  9223. el: tile,
  9224. coords: coords,
  9225. current: true
  9226. };
  9227. container.appendChild(tile);
  9228. // @event tileloadstart: TileEvent
  9229. // Fired when a tile is requested and starts loading.
  9230. this.fire('tileloadstart', {
  9231. tile: tile,
  9232. coords: coords
  9233. });
  9234. },
  9235. _tileReady: function (coords, err, tile) {
  9236. if (!this._map) {
  9237. return;
  9238. }
  9239. if (err) {
  9240. // @event tileerror: TileErrorEvent
  9241. // Fired when there is an error loading a tile.
  9242. this.fire('tileerror', {
  9243. error: err,
  9244. tile: tile,
  9245. coords: coords
  9246. });
  9247. }
  9248. var key = this._tileCoordsToKey(coords);
  9249. tile = this._tiles[key];
  9250. if (!tile) {
  9251. return;
  9252. }
  9253. tile.loaded = +new Date();
  9254. if (this._map._fadeAnimated) {
  9255. setOpacity(tile.el, 0);
  9256. cancelAnimFrame(this._fadeFrame);
  9257. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9258. } else {
  9259. tile.active = true;
  9260. this._pruneTiles();
  9261. }
  9262. if (!err) {
  9263. addClass(tile.el, 'leaflet-tile-loaded');
  9264. // @event tileload: TileEvent
  9265. // Fired when a tile loads.
  9266. this.fire('tileload', {
  9267. tile: tile.el,
  9268. coords: coords
  9269. });
  9270. }
  9271. if (this._noTilesToLoad()) {
  9272. this._loading = false;
  9273. // @event load: Event
  9274. // Fired when the grid layer loaded all visible tiles.
  9275. this.fire('load');
  9276. if (ielt9 || !this._map._fadeAnimated) {
  9277. requestAnimFrame(this._pruneTiles, this);
  9278. } else {
  9279. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9280. // to trigger a pruning.
  9281. setTimeout(bind(this._pruneTiles, this), 250);
  9282. }
  9283. }
  9284. },
  9285. _getTilePos: function (coords) {
  9286. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9287. },
  9288. _wrapCoords: function (coords) {
  9289. var newCoords = new Point(
  9290. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9291. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9292. newCoords.z = coords.z;
  9293. return newCoords;
  9294. },
  9295. _pxBoundsToTileRange: function (bounds) {
  9296. var tileSize = this.getTileSize();
  9297. return new Bounds(
  9298. bounds.min.unscaleBy(tileSize).floor(),
  9299. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9300. },
  9301. _noTilesToLoad: function () {
  9302. for (var key in this._tiles) {
  9303. if (!this._tiles[key].loaded) {
  9304. return false;
  9305. }
  9306. }
  9307. return true;
  9308. }
  9309. });
  9310. // @factory L.gridLayer(options?: GridLayer options)
  9311. // Creates a new instance of GridLayer with the supplied options.
  9312. function gridLayer(options) {
  9313. return new GridLayer(options);
  9314. }
  9315. /*
  9316. * @class TileLayer
  9317. * @inherits GridLayer
  9318. * @aka L.TileLayer
  9319. * Used to load and display tile layers on the map. Extends `GridLayer`.
  9320. *
  9321. * @example
  9322. *
  9323. * ```js
  9324. * L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map);
  9325. * ```
  9326. *
  9327. * @section URL template
  9328. * @example
  9329. *
  9330. * A string of the following form:
  9331. *
  9332. * ```
  9333. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9334. * ```
  9335. *
  9336. * `{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.
  9337. *
  9338. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9339. *
  9340. * ```
  9341. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9342. * ```
  9343. */
  9344. var TileLayer = GridLayer.extend({
  9345. // @section
  9346. // @aka TileLayer options
  9347. options: {
  9348. // @option minZoom: Number = 0
  9349. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9350. minZoom: 0,
  9351. // @option maxZoom: Number = 18
  9352. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9353. maxZoom: 18,
  9354. // @option subdomains: String|String[] = 'abc'
  9355. // 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.
  9356. subdomains: 'abc',
  9357. // @option errorTileUrl: String = ''
  9358. // URL to the tile image to show in place of the tile that failed to load.
  9359. errorTileUrl: '',
  9360. // @option zoomOffset: Number = 0
  9361. // The zoom number used in tile URLs will be offset with this value.
  9362. zoomOffset: 0,
  9363. // @option tms: Boolean = false
  9364. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9365. tms: false,
  9366. // @option zoomReverse: Boolean = false
  9367. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9368. zoomReverse: false,
  9369. // @option detectRetina: Boolean = false
  9370. // 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.
  9371. detectRetina: false,
  9372. // @option crossOrigin: Boolean = false
  9373. // If true, all tiles will have their crossOrigin attribute set to ''. This is needed if you want to access tile pixel data.
  9374. crossOrigin: false
  9375. },
  9376. initialize: function (url, options) {
  9377. this._url = url;
  9378. options = setOptions(this, options);
  9379. // detecting retina displays, adjusting tileSize and zoom levels
  9380. if (options.detectRetina && retina && options.maxZoom > 0) {
  9381. options.tileSize = Math.floor(options.tileSize / 2);
  9382. if (!options.zoomReverse) {
  9383. options.zoomOffset++;
  9384. options.maxZoom--;
  9385. } else {
  9386. options.zoomOffset--;
  9387. options.minZoom++;
  9388. }
  9389. options.minZoom = Math.max(0, options.minZoom);
  9390. }
  9391. if (typeof options.subdomains === 'string') {
  9392. options.subdomains = options.subdomains.split('');
  9393. }
  9394. // for https://github.com/Leaflet/Leaflet/issues/137
  9395. if (!android) {
  9396. this.on('tileunload', this._onTileRemove);
  9397. }
  9398. },
  9399. // @method setUrl(url: String, noRedraw?: Boolean): this
  9400. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9401. setUrl: function (url, noRedraw) {
  9402. this._url = url;
  9403. if (!noRedraw) {
  9404. this.redraw();
  9405. }
  9406. return this;
  9407. },
  9408. // @method createTile(coords: Object, done?: Function): HTMLElement
  9409. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9410. // to return an `<img>` HTML element with the appropiate image URL given `coords`. The `done`
  9411. // callback is called when the tile has been loaded.
  9412. createTile: function (coords, done) {
  9413. var tile = document.createElement('img');
  9414. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9415. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9416. if (this.options.crossOrigin) {
  9417. tile.crossOrigin = '';
  9418. }
  9419. /*
  9420. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  9421. http://www.w3.org/TR/WCAG20-TECHS/H67
  9422. */
  9423. tile.alt = '';
  9424. /*
  9425. Set role="presentation" to force screen readers to ignore this
  9426. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  9427. */
  9428. tile.setAttribute('role', 'presentation');
  9429. tile.src = this.getTileUrl(coords);
  9430. return tile;
  9431. },
  9432. // @section Extension methods
  9433. // @uninheritable
  9434. // Layers extending `TileLayer` might reimplement the following method.
  9435. // @method getTileUrl(coords: Object): String
  9436. // Called only internally, returns the URL for a tile given its coordinates.
  9437. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9438. getTileUrl: function (coords) {
  9439. var data = {
  9440. r: retina ? '@2x' : '',
  9441. s: this._getSubdomain(coords),
  9442. x: coords.x,
  9443. y: coords.y,
  9444. z: this._getZoomForUrl()
  9445. };
  9446. if (this._map && !this._map.options.crs.infinite) {
  9447. var invertedY = this._globalTileRange.max.y - coords.y;
  9448. if (this.options.tms) {
  9449. data['y'] = invertedY;
  9450. }
  9451. data['-y'] = invertedY;
  9452. }
  9453. return template(this._url, extend(data, this.options));
  9454. },
  9455. _tileOnLoad: function (done, tile) {
  9456. // For https://github.com/Leaflet/Leaflet/issues/3332
  9457. if (ielt9) {
  9458. setTimeout(bind(done, this, null, tile), 0);
  9459. } else {
  9460. done(null, tile);
  9461. }
  9462. },
  9463. _tileOnError: function (done, tile, e) {
  9464. var errorUrl = this.options.errorTileUrl;
  9465. if (errorUrl && tile.src !== errorUrl) {
  9466. tile.src = errorUrl;
  9467. }
  9468. done(e, tile);
  9469. },
  9470. _onTileRemove: function (e) {
  9471. e.tile.onload = null;
  9472. },
  9473. _getZoomForUrl: function () {
  9474. var zoom = this._tileZoom,
  9475. maxZoom = this.options.maxZoom,
  9476. zoomReverse = this.options.zoomReverse,
  9477. zoomOffset = this.options.zoomOffset;
  9478. if (zoomReverse) {
  9479. zoom = maxZoom - zoom;
  9480. }
  9481. return zoom + zoomOffset;
  9482. },
  9483. _getSubdomain: function (tilePoint) {
  9484. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  9485. return this.options.subdomains[index];
  9486. },
  9487. // stops loading all tiles in the background layer
  9488. _abortLoading: function () {
  9489. var i, tile;
  9490. for (i in this._tiles) {
  9491. if (this._tiles[i].coords.z !== this._tileZoom) {
  9492. tile = this._tiles[i].el;
  9493. tile.onload = falseFn;
  9494. tile.onerror = falseFn;
  9495. if (!tile.complete) {
  9496. tile.src = emptyImageUrl;
  9497. remove(tile);
  9498. }
  9499. }
  9500. }
  9501. }
  9502. });
  9503. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  9504. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  9505. function tileLayer(url, options) {
  9506. return new TileLayer(url, options);
  9507. }
  9508. /*
  9509. * @class TileLayer.WMS
  9510. * @inherits TileLayer
  9511. * @aka L.TileLayer.WMS
  9512. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  9513. *
  9514. * @example
  9515. *
  9516. * ```js
  9517. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  9518. * layers: 'nexrad-n0r-900913',
  9519. * format: 'image/png',
  9520. * transparent: true,
  9521. * attribution: "Weather data © 2012 IEM Nexrad"
  9522. * });
  9523. * ```
  9524. */
  9525. var TileLayerWMS = TileLayer.extend({
  9526. // @section
  9527. // @aka TileLayer.WMS options
  9528. // If any custom options not documented here are used, they will be sent to the
  9529. // WMS server as extra parameters in each request URL. This can be useful for
  9530. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  9531. defaultWmsParams: {
  9532. service: 'WMS',
  9533. request: 'GetMap',
  9534. // @option layers: String = ''
  9535. // **(required)** Comma-separated list of WMS layers to show.
  9536. layers: '',
  9537. // @option styles: String = ''
  9538. // Comma-separated list of WMS styles.
  9539. styles: '',
  9540. // @option format: String = 'image/jpeg'
  9541. // WMS image format (use `'image/png'` for layers with transparency).
  9542. format: 'image/jpeg',
  9543. // @option transparent: Boolean = false
  9544. // If `true`, the WMS service will return images with transparency.
  9545. transparent: false,
  9546. // @option version: String = '1.1.1'
  9547. // Version of the WMS service to use
  9548. version: '1.1.1'
  9549. },
  9550. options: {
  9551. // @option crs: CRS = null
  9552. // Coordinate Reference System to use for the WMS requests, defaults to
  9553. // map CRS. Don't change this if you're not sure what it means.
  9554. crs: null,
  9555. // @option uppercase: Boolean = false
  9556. // If `true`, WMS request parameter keys will be uppercase.
  9557. uppercase: false
  9558. },
  9559. initialize: function (url, options) {
  9560. this._url = url;
  9561. var wmsParams = extend({}, this.defaultWmsParams);
  9562. // all keys that are not TileLayer options go to WMS params
  9563. for (var i in options) {
  9564. if (!(i in this.options)) {
  9565. wmsParams[i] = options[i];
  9566. }
  9567. }
  9568. options = setOptions(this, options);
  9569. wmsParams.width = wmsParams.height = options.tileSize * (options.detectRetina && retina ? 2 : 1);
  9570. this.wmsParams = wmsParams;
  9571. },
  9572. onAdd: function (map) {
  9573. this._crs = this.options.crs || map.options.crs;
  9574. this._wmsVersion = parseFloat(this.wmsParams.version);
  9575. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  9576. this.wmsParams[projectionKey] = this._crs.code;
  9577. TileLayer.prototype.onAdd.call(this, map);
  9578. },
  9579. getTileUrl: function (coords) {
  9580. var tileBounds = this._tileCoordsToBounds(coords),
  9581. nw = this._crs.project(tileBounds.getNorthWest()),
  9582. se = this._crs.project(tileBounds.getSouthEast()),
  9583. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  9584. [se.y, nw.x, nw.y, se.x] :
  9585. [nw.x, se.y, se.x, nw.y]).join(','),
  9586. url = TileLayer.prototype.getTileUrl.call(this, coords);
  9587. return url +
  9588. getParamString(this.wmsParams, url, this.options.uppercase) +
  9589. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  9590. },
  9591. // @method setParams(params: Object, noRedraw?: Boolean): this
  9592. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  9593. setParams: function (params, noRedraw) {
  9594. extend(this.wmsParams, params);
  9595. if (!noRedraw) {
  9596. this.redraw();
  9597. }
  9598. return this;
  9599. }
  9600. });
  9601. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  9602. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  9603. function tileLayerWMS(url, options) {
  9604. return new TileLayerWMS(url, options);
  9605. }
  9606. TileLayer.WMS = TileLayerWMS;
  9607. tileLayer.wms = tileLayerWMS;
  9608. /*
  9609. * @class Renderer
  9610. * @inherits Layer
  9611. * @aka L.Renderer
  9612. *
  9613. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  9614. * DOM container of the renderer, its bounds, and its zoom animation.
  9615. *
  9616. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  9617. * itself can be added or removed to the map. All paths use a renderer, which can
  9618. * be implicit (the map will decide the type of renderer and use it automatically)
  9619. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  9620. *
  9621. * Do not use this class directly, use `SVG` and `Canvas` instead.
  9622. *
  9623. * @event update: Event
  9624. * Fired when the renderer updates its bounds, center and zoom, for example when
  9625. * its map has moved
  9626. */
  9627. var Renderer = Layer.extend({
  9628. // @section
  9629. // @aka Renderer options
  9630. options: {
  9631. // @option padding: Number = 0.1
  9632. // How much to extend the clip area around the map view (relative to its size)
  9633. // e.g. 0.1 would be 10% of map view in each direction
  9634. padding: 0.1
  9635. },
  9636. initialize: function (options) {
  9637. setOptions(this, options);
  9638. stamp(this);
  9639. this._layers = this._layers || {};
  9640. },
  9641. onAdd: function () {
  9642. if (!this._container) {
  9643. this._initContainer(); // defined by renderer implementations
  9644. if (this._zoomAnimated) {
  9645. addClass(this._container, 'leaflet-zoom-animated');
  9646. }
  9647. }
  9648. this.getPane().appendChild(this._container);
  9649. this._update();
  9650. this.on('update', this._updatePaths, this);
  9651. },
  9652. onRemove: function () {
  9653. this.off('update', this._updatePaths, this);
  9654. this._destroyContainer();
  9655. },
  9656. getEvents: function () {
  9657. var events = {
  9658. viewreset: this._reset,
  9659. zoom: this._onZoom,
  9660. moveend: this._update,
  9661. zoomend: this._onZoomEnd
  9662. };
  9663. if (this._zoomAnimated) {
  9664. events.zoomanim = this._onAnimZoom;
  9665. }
  9666. return events;
  9667. },
  9668. _onAnimZoom: function (ev) {
  9669. this._updateTransform(ev.center, ev.zoom);
  9670. },
  9671. _onZoom: function () {
  9672. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  9673. },
  9674. _updateTransform: function (center, zoom) {
  9675. var scale = this._map.getZoomScale(zoom, this._zoom),
  9676. position = getPosition(this._container),
  9677. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  9678. currentCenterPoint = this._map.project(this._center, zoom),
  9679. destCenterPoint = this._map.project(center, zoom),
  9680. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  9681. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  9682. if (any3d) {
  9683. setTransform(this._container, topLeftOffset, scale);
  9684. } else {
  9685. setPosition(this._container, topLeftOffset);
  9686. }
  9687. },
  9688. _reset: function () {
  9689. this._update();
  9690. this._updateTransform(this._center, this._zoom);
  9691. for (var id in this._layers) {
  9692. this._layers[id]._reset();
  9693. }
  9694. },
  9695. _onZoomEnd: function () {
  9696. for (var id in this._layers) {
  9697. this._layers[id]._project();
  9698. }
  9699. },
  9700. _updatePaths: function () {
  9701. for (var id in this._layers) {
  9702. this._layers[id]._update();
  9703. }
  9704. },
  9705. _update: function () {
  9706. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  9707. // Subclasses are responsible of firing the 'update' event.
  9708. var p = this.options.padding,
  9709. size = this._map.getSize(),
  9710. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  9711. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  9712. this._center = this._map.getCenter();
  9713. this._zoom = this._map.getZoom();
  9714. }
  9715. });
  9716. /*
  9717. * @class Canvas
  9718. * @inherits Renderer
  9719. * @aka L.Canvas
  9720. *
  9721. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  9722. * Inherits `Renderer`.
  9723. *
  9724. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  9725. * available in all web browsers, notably IE8, and overlapping geometries might
  9726. * not display properly in some edge cases.
  9727. *
  9728. * @example
  9729. *
  9730. * Use Canvas by default for all paths in the map:
  9731. *
  9732. * ```js
  9733. * var map = L.map('map', {
  9734. * renderer: L.canvas()
  9735. * });
  9736. * ```
  9737. *
  9738. * Use a Canvas renderer with extra padding for specific vector geometries:
  9739. *
  9740. * ```js
  9741. * var map = L.map('map');
  9742. * var myRenderer = L.canvas({ padding: 0.5 });
  9743. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  9744. * var circle = L.circle( center, { renderer: myRenderer } );
  9745. * ```
  9746. */
  9747. var Canvas = Renderer.extend({
  9748. getEvents: function () {
  9749. var events = Renderer.prototype.getEvents.call(this);
  9750. events.viewprereset = this._onViewPreReset;
  9751. return events;
  9752. },
  9753. _onViewPreReset: function () {
  9754. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  9755. this._postponeUpdatePaths = true;
  9756. },
  9757. onAdd: function () {
  9758. Renderer.prototype.onAdd.call(this);
  9759. // Redraw vectors since canvas is cleared upon removal,
  9760. // in case of removing the renderer itself from the map.
  9761. this._draw();
  9762. },
  9763. _initContainer: function () {
  9764. var container = this._container = document.createElement('canvas');
  9765. on(container, 'mousemove', throttle(this._onMouseMove, 32, this), this);
  9766. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  9767. on(container, 'mouseout', this._handleMouseOut, this);
  9768. this._ctx = container.getContext('2d');
  9769. },
  9770. _destroyContainer: function () {
  9771. delete this._ctx;
  9772. remove(this._container);
  9773. off(this._container);
  9774. delete this._container;
  9775. },
  9776. _updatePaths: function () {
  9777. if (this._postponeUpdatePaths) {
  9778. return;
  9779. }
  9780. var layer;
  9781. this._redrawBounds = null;
  9782. for (var id in this._layers) {
  9783. layer = this._layers[id];
  9784. layer._update();
  9785. }
  9786. this._redraw();
  9787. },
  9788. _update: function () {
  9789. if (this._map._animatingZoom && this._bounds) {
  9790. return;
  9791. }
  9792. this._drawnLayers = {};
  9793. Renderer.prototype._update.call(this);
  9794. var b = this._bounds,
  9795. container = this._container,
  9796. size = b.getSize(),
  9797. m = retina ? 2 : 1;
  9798. setPosition(container, b.min);
  9799. // set canvas size (also clearing it); use double size on retina
  9800. container.width = m * size.x;
  9801. container.height = m * size.y;
  9802. container.style.width = size.x + 'px';
  9803. container.style.height = size.y + 'px';
  9804. if (retina) {
  9805. this._ctx.scale(2, 2);
  9806. }
  9807. // translate so we use the same path coordinates after canvas element moves
  9808. this._ctx.translate(-b.min.x, -b.min.y);
  9809. // Tell paths to redraw themselves
  9810. this.fire('update');
  9811. },
  9812. _reset: function () {
  9813. Renderer.prototype._reset.call(this);
  9814. if (this._postponeUpdatePaths) {
  9815. this._postponeUpdatePaths = false;
  9816. this._updatePaths();
  9817. }
  9818. },
  9819. _initPath: function (layer) {
  9820. this._updateDashArray(layer);
  9821. this._layers[stamp(layer)] = layer;
  9822. var order = layer._order = {
  9823. layer: layer,
  9824. prev: this._drawLast,
  9825. next: null
  9826. };
  9827. if (this._drawLast) {
  9828. this._drawLast.next = order;
  9829. }
  9830. this._drawLast = order;
  9831. this._drawFirst = this._drawFirst || this._drawLast;
  9832. },
  9833. _addPath: function (layer) {
  9834. this._requestRedraw(layer);
  9835. },
  9836. _removePath: function (layer) {
  9837. var order = layer._order;
  9838. var next = order.next;
  9839. var prev = order.prev;
  9840. if (next) {
  9841. next.prev = prev;
  9842. } else {
  9843. this._drawLast = prev;
  9844. }
  9845. if (prev) {
  9846. prev.next = next;
  9847. } else {
  9848. this._drawFirst = next;
  9849. }
  9850. delete layer._order;
  9851. delete this._layers[L.stamp(layer)];
  9852. this._requestRedraw(layer);
  9853. },
  9854. _updatePath: function (layer) {
  9855. // Redraw the union of the layer's old pixel
  9856. // bounds and the new pixel bounds.
  9857. this._extendRedrawBounds(layer);
  9858. layer._project();
  9859. layer._update();
  9860. // The redraw will extend the redraw bounds
  9861. // with the new pixel bounds.
  9862. this._requestRedraw(layer);
  9863. },
  9864. _updateStyle: function (layer) {
  9865. this._updateDashArray(layer);
  9866. this._requestRedraw(layer);
  9867. },
  9868. _updateDashArray: function (layer) {
  9869. if (layer.options.dashArray) {
  9870. var parts = layer.options.dashArray.split(','),
  9871. dashArray = [],
  9872. i;
  9873. for (i = 0; i < parts.length; i++) {
  9874. dashArray.push(Number(parts[i]));
  9875. }
  9876. layer.options._dashArray = dashArray;
  9877. }
  9878. },
  9879. _requestRedraw: function (layer) {
  9880. if (!this._map) {
  9881. return;
  9882. }
  9883. this._extendRedrawBounds(layer);
  9884. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  9885. },
  9886. _extendRedrawBounds: function (layer) {
  9887. if (layer._pxBounds) {
  9888. var padding = (layer.options.weight || 0) + 1;
  9889. this._redrawBounds = this._redrawBounds || new Bounds();
  9890. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  9891. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  9892. }
  9893. },
  9894. _redraw: function () {
  9895. this._redrawRequest = null;
  9896. if (this._redrawBounds) {
  9897. this._redrawBounds.min._floor();
  9898. this._redrawBounds.max._ceil();
  9899. }
  9900. this._clear(); // clear layers in redraw bounds
  9901. this._draw(); // draw layers
  9902. this._redrawBounds = null;
  9903. },
  9904. _clear: function () {
  9905. var bounds = this._redrawBounds;
  9906. if (bounds) {
  9907. var size = bounds.getSize();
  9908. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  9909. } else {
  9910. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  9911. }
  9912. },
  9913. _draw: function () {
  9914. var layer, bounds = this._redrawBounds;
  9915. this._ctx.save();
  9916. if (bounds) {
  9917. var size = bounds.getSize();
  9918. this._ctx.beginPath();
  9919. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  9920. this._ctx.clip();
  9921. }
  9922. this._drawing = true;
  9923. for (var order = this._drawFirst; order; order = order.next) {
  9924. layer = order.layer;
  9925. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  9926. layer._updatePath();
  9927. }
  9928. }
  9929. this._drawing = false;
  9930. this._ctx.restore(); // Restore state before clipping.
  9931. },
  9932. _updatePoly: function (layer, closed) {
  9933. if (!this._drawing) {
  9934. return;
  9935. }
  9936. var i, j, len2, p,
  9937. parts = layer._parts,
  9938. len = parts.length,
  9939. ctx = this._ctx;
  9940. if (!len) {
  9941. return;
  9942. }
  9943. this._drawnLayers[layer._leaflet_id] = layer;
  9944. ctx.beginPath();
  9945. for (i = 0; i < len; i++) {
  9946. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  9947. p = parts[i][j];
  9948. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  9949. }
  9950. if (closed) {
  9951. ctx.closePath();
  9952. }
  9953. }
  9954. this._fillStroke(ctx, layer);
  9955. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  9956. },
  9957. _updateCircle: function (layer) {
  9958. if (!this._drawing || layer._empty()) {
  9959. return;
  9960. }
  9961. var p = layer._point,
  9962. ctx = this._ctx,
  9963. r = layer._radius,
  9964. s = (layer._radiusY || r) / r;
  9965. this._drawnLayers[layer._leaflet_id] = layer;
  9966. if (s !== 1) {
  9967. ctx.save();
  9968. ctx.scale(1, s);
  9969. }
  9970. ctx.beginPath();
  9971. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  9972. if (s !== 1) {
  9973. ctx.restore();
  9974. }
  9975. this._fillStroke(ctx, layer);
  9976. },
  9977. _fillStroke: function (ctx, layer) {
  9978. var options = layer.options;
  9979. if (options.fill) {
  9980. ctx.globalAlpha = options.fillOpacity;
  9981. ctx.fillStyle = options.fillColor || options.color;
  9982. ctx.fill(options.fillRule || 'evenodd');
  9983. }
  9984. if (options.stroke && options.weight !== 0) {
  9985. if (ctx.setLineDash) {
  9986. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  9987. }
  9988. ctx.globalAlpha = options.opacity;
  9989. ctx.lineWidth = options.weight;
  9990. ctx.strokeStyle = options.color;
  9991. ctx.lineCap = options.lineCap;
  9992. ctx.lineJoin = options.lineJoin;
  9993. ctx.stroke();
  9994. }
  9995. },
  9996. // Canvas obviously doesn't have mouse events for individual drawn objects,
  9997. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  9998. _onClick: function (e) {
  9999. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  10000. for (var order = this._drawFirst; order; order = order.next) {
  10001. layer = order.layer;
  10002. if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
  10003. clickedLayer = layer;
  10004. }
  10005. }
  10006. if (clickedLayer) {
  10007. fakeStop(e);
  10008. this._fireEvent([clickedLayer], e);
  10009. }
  10010. },
  10011. _onMouseMove: function (e) {
  10012. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) {
  10013. return;
  10014. }
  10015. var point = this._map.mouseEventToLayerPoint(e);
  10016. this._handleMouseHover(e, point);
  10017. },
  10018. _handleMouseOut: function (e) {
  10019. var layer = this._hoveredLayer;
  10020. if (layer) {
  10021. // if we're leaving the layer, fire mouseout
  10022. removeClass(this._container, 'leaflet-interactive');
  10023. this._fireEvent([layer], e, 'mouseout');
  10024. this._hoveredLayer = null;
  10025. }
  10026. },
  10027. _handleMouseHover: function (e, point) {
  10028. var layer, candidateHoveredLayer;
  10029. for (var order = this._drawFirst; order; order = order.next) {
  10030. layer = order.layer;
  10031. if (layer.options.interactive && layer._containsPoint(point)) {
  10032. candidateHoveredLayer = layer;
  10033. }
  10034. }
  10035. if (candidateHoveredLayer !== this._hoveredLayer) {
  10036. this._handleMouseOut(e);
  10037. if (candidateHoveredLayer) {
  10038. addClass(this._container, 'leaflet-interactive'); // change cursor
  10039. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  10040. this._hoveredLayer = candidateHoveredLayer;
  10041. }
  10042. }
  10043. if (this._hoveredLayer) {
  10044. this._fireEvent([this._hoveredLayer], e);
  10045. }
  10046. },
  10047. _fireEvent: function (layers, e, type) {
  10048. this._map._fireDOMEvent(e, type || e.type, layers);
  10049. },
  10050. _bringToFront: function (layer) {
  10051. var order = layer._order;
  10052. var next = order.next;
  10053. var prev = order.prev;
  10054. if (next) {
  10055. next.prev = prev;
  10056. } else {
  10057. // Already last
  10058. return;
  10059. }
  10060. if (prev) {
  10061. prev.next = next;
  10062. } else if (next) {
  10063. // Update first entry unless this is the
  10064. // signle entry
  10065. this._drawFirst = next;
  10066. }
  10067. order.prev = this._drawLast;
  10068. this._drawLast.next = order;
  10069. order.next = null;
  10070. this._drawLast = order;
  10071. this._requestRedraw(layer);
  10072. },
  10073. _bringToBack: function (layer) {
  10074. var order = layer._order;
  10075. var next = order.next;
  10076. var prev = order.prev;
  10077. if (prev) {
  10078. prev.next = next;
  10079. } else {
  10080. // Already first
  10081. return;
  10082. }
  10083. if (next) {
  10084. next.prev = prev;
  10085. } else if (prev) {
  10086. // Update last entry unless this is the
  10087. // signle entry
  10088. this._drawLast = prev;
  10089. }
  10090. order.prev = null;
  10091. order.next = this._drawFirst;
  10092. this._drawFirst.prev = order;
  10093. this._drawFirst = order;
  10094. this._requestRedraw(layer);
  10095. }
  10096. });
  10097. // @factory L.canvas(options?: Renderer options)
  10098. // Creates a Canvas renderer with the given options.
  10099. function canvas$1(options) {
  10100. return canvas ? new Canvas(options) : null;
  10101. }
  10102. /*
  10103. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10104. */
  10105. var vmlCreate = (function () {
  10106. try {
  10107. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10108. return function (name) {
  10109. return document.createElement('<lvml:' + name + ' class="lvml">');
  10110. };
  10111. } catch (e) {
  10112. return function (name) {
  10113. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10114. };
  10115. }
  10116. })();
  10117. /*
  10118. * @class SVG
  10119. *
  10120. * Although SVG is not available on IE7 and IE8, these browsers support [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language), and the SVG renderer will fall back to VML in this case.
  10121. *
  10122. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10123. * with old versions of Internet Explorer.
  10124. */
  10125. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10126. var vmlMixin = {
  10127. _initContainer: function () {
  10128. this._container = create$1('div', 'leaflet-vml-container');
  10129. },
  10130. _update: function () {
  10131. if (this._map._animatingZoom) {
  10132. return;
  10133. }
  10134. Renderer.prototype._update.call(this);
  10135. this.fire('update');
  10136. },
  10137. _initPath: function (layer) {
  10138. var container = layer._container = vmlCreate('shape');
  10139. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10140. container.coordsize = '1 1';
  10141. layer._path = vmlCreate('path');
  10142. container.appendChild(layer._path);
  10143. this._updateStyle(layer);
  10144. this._layers[stamp(layer)] = layer;
  10145. },
  10146. _addPath: function (layer) {
  10147. var container = layer._container;
  10148. this._container.appendChild(container);
  10149. if (layer.options.interactive) {
  10150. layer.addInteractiveTarget(container);
  10151. }
  10152. },
  10153. _removePath: function (layer) {
  10154. var container = layer._container;
  10155. remove(container);
  10156. layer.removeInteractiveTarget(container);
  10157. delete this._layers[stamp(layer)];
  10158. },
  10159. _updateStyle: function (layer) {
  10160. var stroke = layer._stroke,
  10161. fill = layer._fill,
  10162. options = layer.options,
  10163. container = layer._container;
  10164. container.stroked = !!options.stroke;
  10165. container.filled = !!options.fill;
  10166. if (options.stroke) {
  10167. if (!stroke) {
  10168. stroke = layer._stroke = vmlCreate('stroke');
  10169. }
  10170. container.appendChild(stroke);
  10171. stroke.weight = options.weight + 'px';
  10172. stroke.color = options.color;
  10173. stroke.opacity = options.opacity;
  10174. if (options.dashArray) {
  10175. stroke.dashStyle = isArray(options.dashArray) ?
  10176. options.dashArray.join(' ') :
  10177. options.dashArray.replace(/( *, *)/g, ' ');
  10178. } else {
  10179. stroke.dashStyle = '';
  10180. }
  10181. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10182. stroke.joinstyle = options.lineJoin;
  10183. } else if (stroke) {
  10184. container.removeChild(stroke);
  10185. layer._stroke = null;
  10186. }
  10187. if (options.fill) {
  10188. if (!fill) {
  10189. fill = layer._fill = vmlCreate('fill');
  10190. }
  10191. container.appendChild(fill);
  10192. fill.color = options.fillColor || options.color;
  10193. fill.opacity = options.fillOpacity;
  10194. } else if (fill) {
  10195. container.removeChild(fill);
  10196. layer._fill = null;
  10197. }
  10198. },
  10199. _updateCircle: function (layer) {
  10200. var p = layer._point.round(),
  10201. r = Math.round(layer._radius),
  10202. r2 = Math.round(layer._radiusY || r);
  10203. this._setPath(layer, layer._empty() ? 'M0 0' :
  10204. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10205. },
  10206. _setPath: function (layer, path) {
  10207. layer._path.v = path;
  10208. },
  10209. _bringToFront: function (layer) {
  10210. toFront(layer._container);
  10211. },
  10212. _bringToBack: function (layer) {
  10213. toBack(layer._container);
  10214. }
  10215. };
  10216. var create$2 = vml ? vmlCreate : svgCreate;
  10217. /*
  10218. * @class SVG
  10219. * @inherits Renderer
  10220. * @aka L.SVG
  10221. *
  10222. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10223. * Inherits `Renderer`.
  10224. *
  10225. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  10226. * available in all web browsers, notably Android 2.x and 3.x.
  10227. *
  10228. * Although SVG is not available on IE7 and IE8, these browsers support
  10229. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10230. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10231. * this case.
  10232. *
  10233. * @example
  10234. *
  10235. * Use SVG by default for all paths in the map:
  10236. *
  10237. * ```js
  10238. * var map = L.map('map', {
  10239. * renderer: L.svg()
  10240. * });
  10241. * ```
  10242. *
  10243. * Use a SVG renderer with extra padding for specific vector geometries:
  10244. *
  10245. * ```js
  10246. * var map = L.map('map');
  10247. * var myRenderer = L.svg({ padding: 0.5 });
  10248. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10249. * var circle = L.circle( center, { renderer: myRenderer } );
  10250. * ```
  10251. */
  10252. var SVG = Renderer.extend({
  10253. getEvents: function () {
  10254. var events = Renderer.prototype.getEvents.call(this);
  10255. events.zoomstart = this._onZoomStart;
  10256. return events;
  10257. },
  10258. _initContainer: function () {
  10259. this._container = create$2('svg');
  10260. // makes it possible to click through svg root; we'll reset it back in individual paths
  10261. this._container.setAttribute('pointer-events', 'none');
  10262. this._rootGroup = create$2('g');
  10263. this._container.appendChild(this._rootGroup);
  10264. },
  10265. _destroyContainer: function () {
  10266. remove(this._container);
  10267. off(this._container);
  10268. delete this._container;
  10269. delete this._rootGroup;
  10270. },
  10271. _onZoomStart: function () {
  10272. // Drag-then-pinch interactions might mess up the center and zoom.
  10273. // In this case, the easiest way to prevent this is re-do the renderer
  10274. // bounds and padding when the zooming starts.
  10275. this._update();
  10276. },
  10277. _update: function () {
  10278. if (this._map._animatingZoom && this._bounds) {
  10279. return;
  10280. }
  10281. Renderer.prototype._update.call(this);
  10282. var b = this._bounds,
  10283. size = b.getSize(),
  10284. container = this._container;
  10285. // set size of svg-container if changed
  10286. if (!this._svgSize || !this._svgSize.equals(size)) {
  10287. this._svgSize = size;
  10288. container.setAttribute('width', size.x);
  10289. container.setAttribute('height', size.y);
  10290. }
  10291. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10292. setPosition(container, b.min);
  10293. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10294. this.fire('update');
  10295. },
  10296. // methods below are called by vector layers implementations
  10297. _initPath: function (layer) {
  10298. var path = layer._path = create$2('path');
  10299. // @namespace Path
  10300. // @option className: String = null
  10301. // Custom class name set on an element. Only for SVG renderer.
  10302. if (layer.options.className) {
  10303. addClass(path, layer.options.className);
  10304. }
  10305. if (layer.options.interactive) {
  10306. addClass(path, 'leaflet-interactive');
  10307. }
  10308. this._updateStyle(layer);
  10309. this._layers[stamp(layer)] = layer;
  10310. },
  10311. _addPath: function (layer) {
  10312. if (!this._rootGroup) {
  10313. this._initContainer();
  10314. }
  10315. this._rootGroup.appendChild(layer._path);
  10316. layer.addInteractiveTarget(layer._path);
  10317. },
  10318. _removePath: function (layer) {
  10319. remove(layer._path);
  10320. layer.removeInteractiveTarget(layer._path);
  10321. delete this._layers[stamp(layer)];
  10322. },
  10323. _updatePath: function (layer) {
  10324. layer._project();
  10325. layer._update();
  10326. },
  10327. _updateStyle: function (layer) {
  10328. var path = layer._path,
  10329. options = layer.options;
  10330. if (!path) {
  10331. return;
  10332. }
  10333. if (options.stroke) {
  10334. path.setAttribute('stroke', options.color);
  10335. path.setAttribute('stroke-opacity', options.opacity);
  10336. path.setAttribute('stroke-width', options.weight);
  10337. path.setAttribute('stroke-linecap', options.lineCap);
  10338. path.setAttribute('stroke-linejoin', options.lineJoin);
  10339. if (options.dashArray) {
  10340. path.setAttribute('stroke-dasharray', options.dashArray);
  10341. } else {
  10342. path.removeAttribute('stroke-dasharray');
  10343. }
  10344. if (options.dashOffset) {
  10345. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10346. } else {
  10347. path.removeAttribute('stroke-dashoffset');
  10348. }
  10349. } else {
  10350. path.setAttribute('stroke', 'none');
  10351. }
  10352. if (options.fill) {
  10353. path.setAttribute('fill', options.fillColor || options.color);
  10354. path.setAttribute('fill-opacity', options.fillOpacity);
  10355. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10356. } else {
  10357. path.setAttribute('fill', 'none');
  10358. }
  10359. },
  10360. _updatePoly: function (layer, closed) {
  10361. this._setPath(layer, pointsToPath(layer._parts, closed));
  10362. },
  10363. _updateCircle: function (layer) {
  10364. var p = layer._point,
  10365. r = layer._radius,
  10366. r2 = layer._radiusY || r,
  10367. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10368. // drawing a circle with two half-arcs
  10369. var d = layer._empty() ? 'M0 0' :
  10370. 'M' + (p.x - r) + ',' + p.y +
  10371. arc + (r * 2) + ',0 ' +
  10372. arc + (-r * 2) + ',0 ';
  10373. this._setPath(layer, d);
  10374. },
  10375. _setPath: function (layer, path) {
  10376. layer._path.setAttribute('d', path);
  10377. },
  10378. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10379. _bringToFront: function (layer) {
  10380. toFront(layer._path);
  10381. },
  10382. _bringToBack: function (layer) {
  10383. toBack(layer._path);
  10384. }
  10385. });
  10386. if (vml) {
  10387. SVG.include(vmlMixin);
  10388. }
  10389. // @factory L.svg(options?: Renderer options)
  10390. // Creates a SVG renderer with the given options.
  10391. function svg$1(options) {
  10392. return svg || vml ? new SVG(options) : null;
  10393. }
  10394. Map.include({
  10395. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10396. // Returns the instance of `Renderer` that should be used to render the given
  10397. // `Path`. It will ensure that the `renderer` options of the map and paths
  10398. // are respected, and that the renderers do exist on the map.
  10399. getRenderer: function (layer) {
  10400. // @namespace Path; @option renderer: Renderer
  10401. // Use this specific instance of `Renderer` for this path. Takes
  10402. // precedence over the map's [default renderer](#map-renderer).
  10403. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10404. if (!renderer) {
  10405. // @namespace Map; @option preferCanvas: Boolean = false
  10406. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10407. // By default, all `Path`s are rendered in a `SVG` renderer.
  10408. renderer = this._renderer = (this.options.preferCanvas && canvas$1()) || svg$1();
  10409. }
  10410. if (!this.hasLayer(renderer)) {
  10411. this.addLayer(renderer);
  10412. }
  10413. return renderer;
  10414. },
  10415. _getPaneRenderer: function (name) {
  10416. if (name === 'overlayPane' || name === undefined) {
  10417. return false;
  10418. }
  10419. var renderer = this._paneRenderers[name];
  10420. if (renderer === undefined) {
  10421. renderer = (SVG && svg$1({pane: name})) || (Canvas && canvas$1({pane: name}));
  10422. this._paneRenderers[name] = renderer;
  10423. }
  10424. return renderer;
  10425. }
  10426. });
  10427. /*
  10428. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10429. */
  10430. /*
  10431. * @class Rectangle
  10432. * @aka L.Retangle
  10433. * @inherits Polygon
  10434. *
  10435. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10436. *
  10437. * @example
  10438. *
  10439. * ```js
  10440. * // define rectangle geographical bounds
  10441. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10442. *
  10443. * // create an orange rectangle
  10444. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10445. *
  10446. * // zoom the map to the rectangle bounds
  10447. * map.fitBounds(bounds);
  10448. * ```
  10449. *
  10450. */
  10451. var Rectangle = Polygon.extend({
  10452. initialize: function (latLngBounds, options) {
  10453. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10454. },
  10455. // @method setBounds(latLngBounds: LatLngBounds): this
  10456. // Redraws the rectangle with the passed bounds.
  10457. setBounds: function (latLngBounds) {
  10458. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  10459. },
  10460. _boundsToLatLngs: function (latLngBounds) {
  10461. latLngBounds = toLatLngBounds(latLngBounds);
  10462. return [
  10463. latLngBounds.getSouthWest(),
  10464. latLngBounds.getNorthWest(),
  10465. latLngBounds.getNorthEast(),
  10466. latLngBounds.getSouthEast()
  10467. ];
  10468. }
  10469. });
  10470. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  10471. function rectangle(latLngBounds, options) {
  10472. return new Rectangle(latLngBounds, options);
  10473. }
  10474. SVG.create = create$2;
  10475. SVG.pointsToPath = pointsToPath;
  10476. GeoJSON.geometryToLayer = geometryToLayer;
  10477. GeoJSON.coordsToLatLng = coordsToLatLng;
  10478. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  10479. GeoJSON.latLngToCoords = latLngToCoords;
  10480. GeoJSON.latLngsToCoords = latLngsToCoords;
  10481. GeoJSON.getFeature = getFeature;
  10482. GeoJSON.asFeature = asFeature;
  10483. /*
  10484. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  10485. * (zoom to a selected bounding box), enabled by default.
  10486. */
  10487. // @namespace Map
  10488. // @section Interaction Options
  10489. Map.mergeOptions({
  10490. // @option boxZoom: Boolean = true
  10491. // Whether the map can be zoomed to a rectangular area specified by
  10492. // dragging the mouse while pressing the shift key.
  10493. boxZoom: true
  10494. });
  10495. var BoxZoom = Handler.extend({
  10496. initialize: function (map) {
  10497. this._map = map;
  10498. this._container = map._container;
  10499. this._pane = map._panes.overlayPane;
  10500. this._resetStateTimeout = 0;
  10501. map.on('unload', this._destroy, this);
  10502. },
  10503. addHooks: function () {
  10504. on(this._container, 'mousedown', this._onMouseDown, this);
  10505. },
  10506. removeHooks: function () {
  10507. off(this._container, 'mousedown', this._onMouseDown, this);
  10508. },
  10509. moved: function () {
  10510. return this._moved;
  10511. },
  10512. _destroy: function () {
  10513. remove(this._pane);
  10514. delete this._pane;
  10515. },
  10516. _resetState: function () {
  10517. this._resetStateTimeout = 0;
  10518. this._moved = false;
  10519. },
  10520. _clearDeferredResetState: function () {
  10521. if (this._resetStateTimeout !== 0) {
  10522. clearTimeout(this._resetStateTimeout);
  10523. this._resetStateTimeout = 0;
  10524. }
  10525. },
  10526. _onMouseDown: function (e) {
  10527. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) {
  10528. return false;
  10529. }
  10530. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  10531. // will interrupt the interaction and orphan a box element in the container.
  10532. this._clearDeferredResetState();
  10533. this._resetState();
  10534. disableTextSelection();
  10535. disableImageDrag();
  10536. this._startPoint = this._map.mouseEventToContainerPoint(e);
  10537. on(document, {
  10538. contextmenu: stop,
  10539. mousemove: this._onMouseMove,
  10540. mouseup: this._onMouseUp,
  10541. keydown: this._onKeyDown
  10542. }, this);
  10543. },
  10544. _onMouseMove: function (e) {
  10545. if (!this._moved) {
  10546. this._moved = true;
  10547. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  10548. addClass(this._container, 'leaflet-crosshair');
  10549. this._map.fire('boxzoomstart');
  10550. }
  10551. this._point = this._map.mouseEventToContainerPoint(e);
  10552. var bounds = new Bounds(this._point, this._startPoint),
  10553. size = bounds.getSize();
  10554. setPosition(this._box, bounds.min);
  10555. this._box.style.width = size.x + 'px';
  10556. this._box.style.height = size.y + 'px';
  10557. },
  10558. _finish: function () {
  10559. if (this._moved) {
  10560. remove(this._box);
  10561. removeClass(this._container, 'leaflet-crosshair');
  10562. }
  10563. enableTextSelection();
  10564. enableImageDrag();
  10565. off(document, {
  10566. contextmenu: stop,
  10567. mousemove: this._onMouseMove,
  10568. mouseup: this._onMouseUp,
  10569. keydown: this._onKeyDown
  10570. }, this);
  10571. },
  10572. _onMouseUp: function (e) {
  10573. if ((e.which !== 1) && (e.button !== 1)) {
  10574. return;
  10575. }
  10576. this._finish();
  10577. if (!this._moved) {
  10578. return;
  10579. }
  10580. // Postpone to next JS tick so internal click event handling
  10581. // still see it as "moved".
  10582. this._clearDeferredResetState();
  10583. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  10584. var bounds = new LatLngBounds(
  10585. this._map.containerPointToLatLng(this._startPoint),
  10586. this._map.containerPointToLatLng(this._point));
  10587. this._map
  10588. .fitBounds(bounds)
  10589. .fire('boxzoomend', {boxZoomBounds: bounds});
  10590. },
  10591. _onKeyDown: function (e) {
  10592. if (e.keyCode === 27) {
  10593. this._finish();
  10594. }
  10595. }
  10596. });
  10597. // @section Handlers
  10598. // @property boxZoom: Handler
  10599. // Box (shift-drag with mouse) zoom handler.
  10600. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  10601. /*
  10602. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  10603. */
  10604. // @namespace Map
  10605. // @section Interaction Options
  10606. Map.mergeOptions({
  10607. // @option doubleClickZoom: Boolean|String = true
  10608. // Whether the map can be zoomed in by double clicking on it and
  10609. // zoomed out by double clicking while holding shift. If passed
  10610. // `'center'`, double-click zoom will zoom to the center of the
  10611. // view regardless of where the mouse was.
  10612. doubleClickZoom: true
  10613. });
  10614. var DoubleClickZoom = Handler.extend({
  10615. addHooks: function () {
  10616. this._map.on('dblclick', this._onDoubleClick, this);
  10617. },
  10618. removeHooks: function () {
  10619. this._map.off('dblclick', this._onDoubleClick, this);
  10620. },
  10621. _onDoubleClick: function (e) {
  10622. var map = this._map,
  10623. oldZoom = map.getZoom(),
  10624. delta = map.options.zoomDelta,
  10625. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  10626. if (map.options.doubleClickZoom === 'center') {
  10627. map.setZoom(zoom);
  10628. } else {
  10629. map.setZoomAround(e.containerPoint, zoom);
  10630. }
  10631. }
  10632. });
  10633. // @section Handlers
  10634. //
  10635. // Map properties include interaction handlers that allow you to control
  10636. // interaction behavior in runtime, enabling or disabling certain features such
  10637. // as dragging or touch zoom (see `Handler` methods). For example:
  10638. //
  10639. // ```js
  10640. // map.doubleClickZoom.disable();
  10641. // ```
  10642. //
  10643. // @property doubleClickZoom: Handler
  10644. // Double click zoom handler.
  10645. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  10646. /*
  10647. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  10648. */
  10649. // @namespace Map
  10650. // @section Interaction Options
  10651. Map.mergeOptions({
  10652. // @option dragging: Boolean = true
  10653. // Whether the map be draggable with mouse/touch or not.
  10654. dragging: true,
  10655. // @section Panning Inertia Options
  10656. // @option inertia: Boolean = *
  10657. // If enabled, panning of the map will have an inertia effect where
  10658. // the map builds momentum while dragging and continues moving in
  10659. // the same direction for some time. Feels especially nice on touch
  10660. // devices. Enabled by default unless running on old Android devices.
  10661. inertia: !android23,
  10662. // @option inertiaDeceleration: Number = 3000
  10663. // The rate with which the inertial movement slows down, in pixels/second².
  10664. inertiaDeceleration: 3400, // px/s^2
  10665. // @option inertiaMaxSpeed: Number = Infinity
  10666. // Max speed of the inertial movement, in pixels/second.
  10667. inertiaMaxSpeed: Infinity, // px/s
  10668. // @option easeLinearity: Number = 0.2
  10669. easeLinearity: 0.2,
  10670. // TODO refactor, move to CRS
  10671. // @option worldCopyJump: Boolean = false
  10672. // With this option enabled, the map tracks when you pan to another "copy"
  10673. // of the world and seamlessly jumps to the original one so that all overlays
  10674. // like markers and vector layers are still visible.
  10675. worldCopyJump: false,
  10676. // @option maxBoundsViscosity: Number = 0.0
  10677. // If `maxBounds` is set, this option will control how solid the bounds
  10678. // are when dragging the map around. The default value of `0.0` allows the
  10679. // user to drag outside the bounds at normal speed, higher values will
  10680. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  10681. // solid, preventing the user from dragging outside the bounds.
  10682. maxBoundsViscosity: 0.0
  10683. });
  10684. var Drag = Handler.extend({
  10685. addHooks: function () {
  10686. if (!this._draggable) {
  10687. var map = this._map;
  10688. this._draggable = new Draggable(map._mapPane, map._container);
  10689. this._draggable.on({
  10690. dragstart: this._onDragStart,
  10691. drag: this._onDrag,
  10692. dragend: this._onDragEnd
  10693. }, this);
  10694. this._draggable.on('predrag', this._onPreDragLimit, this);
  10695. if (map.options.worldCopyJump) {
  10696. this._draggable.on('predrag', this._onPreDragWrap, this);
  10697. map.on('zoomend', this._onZoomEnd, this);
  10698. map.whenReady(this._onZoomEnd, this);
  10699. }
  10700. }
  10701. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  10702. this._draggable.enable();
  10703. this._positions = [];
  10704. this._times = [];
  10705. },
  10706. removeHooks: function () {
  10707. removeClass(this._map._container, 'leaflet-grab');
  10708. removeClass(this._map._container, 'leaflet-touch-drag');
  10709. this._draggable.disable();
  10710. },
  10711. moved: function () {
  10712. return this._draggable && this._draggable._moved;
  10713. },
  10714. moving: function () {
  10715. return this._draggable && this._draggable._moving;
  10716. },
  10717. _onDragStart: function () {
  10718. var map = this._map;
  10719. map._stop();
  10720. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  10721. var bounds = toLatLngBounds(this._map.options.maxBounds);
  10722. this._offsetLimit = toBounds(
  10723. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  10724. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  10725. .add(this._map.getSize()));
  10726. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  10727. } else {
  10728. this._offsetLimit = null;
  10729. }
  10730. map
  10731. .fire('movestart')
  10732. .fire('dragstart');
  10733. if (map.options.inertia) {
  10734. this._positions = [];
  10735. this._times = [];
  10736. }
  10737. },
  10738. _onDrag: function (e) {
  10739. if (this._map.options.inertia) {
  10740. var time = this._lastTime = +new Date(),
  10741. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  10742. this._positions.push(pos);
  10743. this._times.push(time);
  10744. if (time - this._times[0] > 50) {
  10745. this._positions.shift();
  10746. this._times.shift();
  10747. }
  10748. }
  10749. this._map
  10750. .fire('move', e)
  10751. .fire('drag', e);
  10752. },
  10753. _onZoomEnd: function () {
  10754. var pxCenter = this._map.getSize().divideBy(2),
  10755. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  10756. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  10757. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  10758. },
  10759. _viscousLimit: function (value, threshold) {
  10760. return value - (value - threshold) * this._viscosity;
  10761. },
  10762. _onPreDragLimit: function () {
  10763. if (!this._viscosity || !this._offsetLimit) {
  10764. return;
  10765. }
  10766. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  10767. var limit = this._offsetLimit;
  10768. if (offset.x < limit.min.x) {
  10769. offset.x = this._viscousLimit(offset.x, limit.min.x);
  10770. }
  10771. if (offset.y < limit.min.y) {
  10772. offset.y = this._viscousLimit(offset.y, limit.min.y);
  10773. }
  10774. if (offset.x > limit.max.x) {
  10775. offset.x = this._viscousLimit(offset.x, limit.max.x);
  10776. }
  10777. if (offset.y > limit.max.y) {
  10778. offset.y = this._viscousLimit(offset.y, limit.max.y);
  10779. }
  10780. this._draggable._newPos = this._draggable._startPos.add(offset);
  10781. },
  10782. _onPreDragWrap: function () {
  10783. // TODO refactor to be able to adjust map pane position after zoom
  10784. var worldWidth = this._worldWidth,
  10785. halfWidth = Math.round(worldWidth / 2),
  10786. dx = this._initialWorldOffset,
  10787. x = this._draggable._newPos.x,
  10788. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  10789. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  10790. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  10791. this._draggable._absPos = this._draggable._newPos.clone();
  10792. this._draggable._newPos.x = newX;
  10793. },
  10794. _onDragEnd: function (e) {
  10795. var map = this._map,
  10796. options = map.options,
  10797. noInertia = !options.inertia || this._times.length < 2;
  10798. map.fire('dragend', e);
  10799. if (noInertia) {
  10800. map.fire('moveend');
  10801. } else {
  10802. var direction = this._lastPos.subtract(this._positions[0]),
  10803. duration = (this._lastTime - this._times[0]) / 1000,
  10804. ease = options.easeLinearity,
  10805. speedVector = direction.multiplyBy(ease / duration),
  10806. speed = speedVector.distanceTo([0, 0]),
  10807. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  10808. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  10809. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  10810. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  10811. if (!offset.x && !offset.y) {
  10812. map.fire('moveend');
  10813. } else {
  10814. offset = map._limitOffset(offset, map.options.maxBounds);
  10815. requestAnimFrame(function () {
  10816. map.panBy(offset, {
  10817. duration: decelerationDuration,
  10818. easeLinearity: ease,
  10819. noMoveStart: true,
  10820. animate: true
  10821. });
  10822. });
  10823. }
  10824. }
  10825. }
  10826. });
  10827. // @section Handlers
  10828. // @property dragging: Handler
  10829. // Map dragging handler (by both mouse and touch).
  10830. Map.addInitHook('addHandler', 'dragging', Drag);
  10831. /*
  10832. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  10833. */
  10834. // @namespace Map
  10835. // @section Keyboard Navigation Options
  10836. Map.mergeOptions({
  10837. // @option keyboard: Boolean = true
  10838. // Makes the map focusable and allows users to navigate the map with keyboard
  10839. // arrows and `+`/`-` keys.
  10840. keyboard: true,
  10841. // @option keyboardPanDelta: Number = 80
  10842. // Amount of pixels to pan when pressing an arrow key.
  10843. keyboardPanDelta: 80
  10844. });
  10845. var Keyboard = Handler.extend({
  10846. keyCodes: {
  10847. left: [37],
  10848. right: [39],
  10849. down: [40],
  10850. up: [38],
  10851. zoomIn: [187, 107, 61, 171],
  10852. zoomOut: [189, 109, 54, 173]
  10853. },
  10854. initialize: function (map) {
  10855. this._map = map;
  10856. this._setPanDelta(map.options.keyboardPanDelta);
  10857. this._setZoomDelta(map.options.zoomDelta);
  10858. },
  10859. addHooks: function () {
  10860. var container = this._map._container;
  10861. // make the container focusable by tabbing
  10862. if (container.tabIndex <= 0) {
  10863. container.tabIndex = '0';
  10864. }
  10865. on(container, {
  10866. focus: this._onFocus,
  10867. blur: this._onBlur,
  10868. mousedown: this._onMouseDown
  10869. }, this);
  10870. this._map.on({
  10871. focus: this._addHooks,
  10872. blur: this._removeHooks
  10873. }, this);
  10874. },
  10875. removeHooks: function () {
  10876. this._removeHooks();
  10877. off(this._map._container, {
  10878. focus: this._onFocus,
  10879. blur: this._onBlur,
  10880. mousedown: this._onMouseDown
  10881. }, this);
  10882. this._map.off({
  10883. focus: this._addHooks,
  10884. blur: this._removeHooks
  10885. }, this);
  10886. },
  10887. _onMouseDown: function () {
  10888. if (this._focused) {
  10889. return;
  10890. }
  10891. var body = document.body,
  10892. docEl = document.documentElement,
  10893. top = body.scrollTop || docEl.scrollTop,
  10894. left = body.scrollLeft || docEl.scrollLeft;
  10895. this._map._container.focus();
  10896. window.scrollTo(left, top);
  10897. },
  10898. _onFocus: function () {
  10899. this._focused = true;
  10900. this._map.fire('focus');
  10901. },
  10902. _onBlur: function () {
  10903. this._focused = false;
  10904. this._map.fire('blur');
  10905. },
  10906. _setPanDelta: function (panDelta) {
  10907. var keys = this._panKeys = {},
  10908. codes = this.keyCodes,
  10909. i, len;
  10910. for (i = 0, len = codes.left.length; i < len; i++) {
  10911. keys[codes.left[i]] = [-1 * panDelta, 0];
  10912. }
  10913. for (i = 0, len = codes.right.length; i < len; i++) {
  10914. keys[codes.right[i]] = [panDelta, 0];
  10915. }
  10916. for (i = 0, len = codes.down.length; i < len; i++) {
  10917. keys[codes.down[i]] = [0, panDelta];
  10918. }
  10919. for (i = 0, len = codes.up.length; i < len; i++) {
  10920. keys[codes.up[i]] = [0, -1 * panDelta];
  10921. }
  10922. },
  10923. _setZoomDelta: function (zoomDelta) {
  10924. var keys = this._zoomKeys = {},
  10925. codes = this.keyCodes,
  10926. i, len;
  10927. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  10928. keys[codes.zoomIn[i]] = zoomDelta;
  10929. }
  10930. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  10931. keys[codes.zoomOut[i]] = -zoomDelta;
  10932. }
  10933. },
  10934. _addHooks: function () {
  10935. on(document, 'keydown', this._onKeyDown, this);
  10936. },
  10937. _removeHooks: function () {
  10938. off(document, 'keydown', this._onKeyDown, this);
  10939. },
  10940. _onKeyDown: function (e) {
  10941. if (e.altKey || e.ctrlKey || e.metaKey) {
  10942. return;
  10943. }
  10944. var key = e.keyCode,
  10945. map = this._map,
  10946. offset;
  10947. if (key in this._panKeys) {
  10948. if (map._panAnim && map._panAnim._inProgress) {
  10949. return;
  10950. }
  10951. offset = this._panKeys[key];
  10952. if (e.shiftKey) {
  10953. offset = toPoint(offset).multiplyBy(3);
  10954. }
  10955. map.panBy(offset);
  10956. if (map.options.maxBounds) {
  10957. map.panInsideBounds(map.options.maxBounds);
  10958. }
  10959. } else if (key in this._zoomKeys) {
  10960. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  10961. } else if (key === 27 && map._popup) {
  10962. map.closePopup();
  10963. } else {
  10964. return;
  10965. }
  10966. stop(e);
  10967. }
  10968. });
  10969. // @section Handlers
  10970. // @section Handlers
  10971. // @property keyboard: Handler
  10972. // Keyboard navigation handler.
  10973. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  10974. /*
  10975. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  10976. */
  10977. // @namespace Map
  10978. // @section Interaction Options
  10979. Map.mergeOptions({
  10980. // @section Mousewheel options
  10981. // @option scrollWheelZoom: Boolean|String = true
  10982. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  10983. // it will zoom to the center of the view regardless of where the mouse was.
  10984. scrollWheelZoom: true,
  10985. // @option wheelDebounceTime: Number = 40
  10986. // Limits the rate at which a wheel can fire (in milliseconds). By default
  10987. // user can't zoom via wheel more often than once per 40 ms.
  10988. wheelDebounceTime: 40,
  10989. // @option wheelPxPerZoomLevel: Number = 60
  10990. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  10991. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  10992. // faster (and vice versa).
  10993. wheelPxPerZoomLevel: 60
  10994. });
  10995. var ScrollWheelZoom = Handler.extend({
  10996. addHooks: function () {
  10997. on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  10998. this._delta = 0;
  10999. },
  11000. removeHooks: function () {
  11001. off(this._map._container, 'mousewheel', this._onWheelScroll, this);
  11002. },
  11003. _onWheelScroll: function (e) {
  11004. var delta = getWheelDelta(e);
  11005. var debounce = this._map.options.wheelDebounceTime;
  11006. this._delta += delta;
  11007. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  11008. if (!this._startTime) {
  11009. this._startTime = +new Date();
  11010. }
  11011. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  11012. clearTimeout(this._timer);
  11013. this._timer = setTimeout(bind(this._performZoom, this), left);
  11014. stop(e);
  11015. },
  11016. _performZoom: function () {
  11017. var map = this._map,
  11018. zoom = map.getZoom(),
  11019. snap = this._map.options.zoomSnap || 0;
  11020. map._stop(); // stop panning and fly animations if any
  11021. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  11022. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  11023. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  11024. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  11025. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  11026. this._delta = 0;
  11027. this._startTime = null;
  11028. if (!delta) {
  11029. return;
  11030. }
  11031. if (map.options.scrollWheelZoom === 'center') {
  11032. map.setZoom(zoom + delta);
  11033. } else {
  11034. map.setZoomAround(this._lastMousePos, zoom + delta);
  11035. }
  11036. }
  11037. });
  11038. // @section Handlers
  11039. // @property scrollWheelZoom: Handler
  11040. // Scroll wheel zoom handler.
  11041. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  11042. /*
  11043. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  11044. */
  11045. // @namespace Map
  11046. // @section Interaction Options
  11047. Map.mergeOptions({
  11048. // @section Touch interaction options
  11049. // @option tap: Boolean = true
  11050. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  11051. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  11052. tap: true,
  11053. // @option tapTolerance: Number = 15
  11054. // The max number of pixels a user can shift his finger during touch
  11055. // for it to be considered a valid tap.
  11056. tapTolerance: 15
  11057. });
  11058. var Tap = Handler.extend({
  11059. addHooks: function () {
  11060. on(this._map._container, 'touchstart', this._onDown, this);
  11061. },
  11062. removeHooks: function () {
  11063. off(this._map._container, 'touchstart', this._onDown, this);
  11064. },
  11065. _onDown: function (e) {
  11066. if (!e.touches) {
  11067. return;
  11068. }
  11069. preventDefault(e);
  11070. this._fireClick = true;
  11071. // don't simulate click or track longpress if more than 1 touch
  11072. if (e.touches.length > 1) {
  11073. this._fireClick = false;
  11074. clearTimeout(this._holdTimeout);
  11075. return;
  11076. }
  11077. var first = e.touches[0],
  11078. el = first.target;
  11079. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  11080. // if touching a link, highlight it
  11081. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  11082. addClass(el, 'leaflet-active');
  11083. }
  11084. // simulate long hold but setting a timeout
  11085. this._holdTimeout = setTimeout(bind(function () {
  11086. if (this._isTapValid()) {
  11087. this._fireClick = false;
  11088. this._onUp();
  11089. this._simulateEvent('contextmenu', first);
  11090. }
  11091. }, this), 1000);
  11092. this._simulateEvent('mousedown', first);
  11093. on(document, {
  11094. touchmove: this._onMove,
  11095. touchend: this._onUp
  11096. }, this);
  11097. },
  11098. _onUp: function (e) {
  11099. clearTimeout(this._holdTimeout);
  11100. off(document, {
  11101. touchmove: this._onMove,
  11102. touchend: this._onUp
  11103. }, this);
  11104. if (this._fireClick && e && e.changedTouches) {
  11105. var first = e.changedTouches[0],
  11106. el = first.target;
  11107. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  11108. removeClass(el, 'leaflet-active');
  11109. }
  11110. this._simulateEvent('mouseup', first);
  11111. // simulate click if the touch didn't move too much
  11112. if (this._isTapValid()) {
  11113. this._simulateEvent('click', first);
  11114. }
  11115. }
  11116. },
  11117. _isTapValid: function () {
  11118. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11119. },
  11120. _onMove: function (e) {
  11121. var first = e.touches[0];
  11122. this._newPos = new Point(first.clientX, first.clientY);
  11123. this._simulateEvent('mousemove', first);
  11124. },
  11125. _simulateEvent: function (type, e) {
  11126. var simulatedEvent = document.createEvent('MouseEvents');
  11127. simulatedEvent._simulated = true;
  11128. e.target._simulatedClick = true;
  11129. simulatedEvent.initMouseEvent(
  11130. type, true, true, window, 1,
  11131. e.screenX, e.screenY,
  11132. e.clientX, e.clientY,
  11133. false, false, false, false, 0, null);
  11134. e.target.dispatchEvent(simulatedEvent);
  11135. }
  11136. });
  11137. // @section Handlers
  11138. // @property tap: Handler
  11139. // Mobile touch hacks (quick tap and touch hold) handler.
  11140. if (touch && !pointer) {
  11141. Map.addInitHook('addHandler', 'tap', Tap);
  11142. }
  11143. /*
  11144. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11145. */
  11146. // @namespace Map
  11147. // @section Interaction Options
  11148. Map.mergeOptions({
  11149. // @section Touch interaction options
  11150. // @option touchZoom: Boolean|String = *
  11151. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11152. // passed `'center'`, it will zoom to the center of the view regardless of
  11153. // where the touch events (fingers) were. Enabled for touch-capable web
  11154. // browsers except for old Androids.
  11155. touchZoom: touch && !android23,
  11156. // @option bounceAtZoomLimits: Boolean = true
  11157. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11158. // and then bounce back when pinch-zooming.
  11159. bounceAtZoomLimits: true
  11160. });
  11161. var TouchZoom = Handler.extend({
  11162. addHooks: function () {
  11163. addClass(this._map._container, 'leaflet-touch-zoom');
  11164. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11165. },
  11166. removeHooks: function () {
  11167. removeClass(this._map._container, 'leaflet-touch-zoom');
  11168. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11169. },
  11170. _onTouchStart: function (e) {
  11171. var map = this._map;
  11172. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) {
  11173. return;
  11174. }
  11175. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11176. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11177. this._centerPoint = map.getSize()._divideBy(2);
  11178. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11179. if (map.options.touchZoom !== 'center') {
  11180. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11181. }
  11182. this._startDist = p1.distanceTo(p2);
  11183. this._startZoom = map.getZoom();
  11184. this._moved = false;
  11185. this._zooming = true;
  11186. map._stop();
  11187. on(document, 'touchmove', this._onTouchMove, this);
  11188. on(document, 'touchend', this._onTouchEnd, this);
  11189. preventDefault(e);
  11190. },
  11191. _onTouchMove: function (e) {
  11192. if (!e.touches || e.touches.length !== 2 || !this._zooming) {
  11193. return;
  11194. }
  11195. var map = this._map,
  11196. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11197. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11198. scale = p1.distanceTo(p2) / this._startDist;
  11199. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11200. if (!map.options.bounceAtZoomLimits && (
  11201. (this._zoom < map.getMinZoom() && scale < 1) ||
  11202. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11203. this._zoom = map._limitZoom(this._zoom);
  11204. }
  11205. if (map.options.touchZoom === 'center') {
  11206. this._center = this._startLatLng;
  11207. if (scale === 1) {
  11208. return;
  11209. }
  11210. } else {
  11211. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11212. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11213. if (scale === 1 && delta.x === 0 && delta.y === 0) {
  11214. return;
  11215. }
  11216. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11217. }
  11218. if (!this._moved) {
  11219. map._moveStart(true);
  11220. this._moved = true;
  11221. }
  11222. cancelAnimFrame(this._animRequest);
  11223. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  11224. this._animRequest = requestAnimFrame(moveFn, this, true);
  11225. preventDefault(e);
  11226. },
  11227. _onTouchEnd: function () {
  11228. if (!this._moved || !this._zooming) {
  11229. this._zooming = false;
  11230. return;
  11231. }
  11232. this._zooming = false;
  11233. cancelAnimFrame(this._animRequest);
  11234. off(document, 'touchmove', this._onTouchMove);
  11235. off(document, 'touchend', this._onTouchEnd);
  11236. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11237. if (this._map.options.zoomAnimation) {
  11238. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11239. } else {
  11240. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11241. }
  11242. }
  11243. });
  11244. // @section Handlers
  11245. // @property touchZoom: Handler
  11246. // Touch zoom handler.
  11247. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11248. Map.BoxZoom = BoxZoom;
  11249. Map.DoubleClickZoom = DoubleClickZoom;
  11250. Map.Drag = Drag;
  11251. Map.Keyboard = Keyboard;
  11252. Map.ScrollWheelZoom = ScrollWheelZoom;
  11253. Map.Tap = Tap;
  11254. Map.TouchZoom = TouchZoom;
  11255. // misc
  11256. var oldL = window.L;
  11257. function noConflict() {
  11258. window.L = oldL;
  11259. return this;
  11260. }
  11261. // Always export us to window global (see #2364)
  11262. window.L = exports;
  11263. Object.freeze = freeze;
  11264. exports.version = version;
  11265. exports.noConflict = noConflict;
  11266. exports.Control = Control;
  11267. exports.control = control;
  11268. exports.Browser = Browser;
  11269. exports.Evented = Evented;
  11270. exports.Mixin = Mixin;
  11271. exports.Util = Util;
  11272. exports.Class = Class;
  11273. exports.Handler = Handler;
  11274. exports.extend = extend;
  11275. exports.bind = bind;
  11276. exports.stamp = stamp;
  11277. exports.setOptions = setOptions;
  11278. exports.DomEvent = DomEvent;
  11279. exports.DomUtil = DomUtil;
  11280. exports.PosAnimation = PosAnimation;
  11281. exports.Draggable = Draggable;
  11282. exports.LineUtil = LineUtil;
  11283. exports.PolyUtil = PolyUtil;
  11284. exports.Point = Point;
  11285. exports.point = toPoint;
  11286. exports.Bounds = Bounds;
  11287. exports.bounds = toBounds;
  11288. exports.Transformation = Transformation;
  11289. exports.transformation = toTransformation;
  11290. exports.Projection = index;
  11291. exports.LatLng = LatLng;
  11292. exports.latLng = toLatLng;
  11293. exports.LatLngBounds = LatLngBounds;
  11294. exports.latLngBounds = toLatLngBounds;
  11295. exports.CRS = CRS;
  11296. exports.GeoJSON = GeoJSON;
  11297. exports.geoJSON = geoJSON;
  11298. exports.geoJson = geoJson;
  11299. exports.Layer = Layer;
  11300. exports.LayerGroup = LayerGroup;
  11301. exports.layerGroup = layerGroup;
  11302. exports.FeatureGroup = FeatureGroup;
  11303. exports.featureGroup = featureGroup;
  11304. exports.ImageOverlay = ImageOverlay;
  11305. exports.imageOverlay = imageOverlay;
  11306. exports.VideoOverlay = VideoOverlay;
  11307. exports.videoOverlay = videoOverlay;
  11308. exports.DivOverlay = DivOverlay;
  11309. exports.Popup = Popup;
  11310. exports.popup = popup;
  11311. exports.Tooltip = Tooltip;
  11312. exports.tooltip = tooltip;
  11313. exports.Icon = Icon;
  11314. exports.icon = icon;
  11315. exports.DivIcon = DivIcon;
  11316. exports.divIcon = divIcon;
  11317. exports.Marker = Marker;
  11318. exports.marker = marker;
  11319. exports.TileLayer = TileLayer;
  11320. exports.tileLayer = tileLayer;
  11321. exports.GridLayer = GridLayer;
  11322. exports.gridLayer = gridLayer;
  11323. exports.SVG = SVG;
  11324. exports.svg = svg$1;
  11325. exports.Renderer = Renderer;
  11326. exports.Canvas = Canvas;
  11327. exports.canvas = canvas$1;
  11328. exports.Path = Path;
  11329. exports.CircleMarker = CircleMarker;
  11330. exports.circleMarker = circleMarker;
  11331. exports.Circle = Circle;
  11332. exports.circle = circle;
  11333. exports.Polyline = Polyline;
  11334. exports.polyline = polyline;
  11335. exports.Polygon = Polygon;
  11336. exports.polygon = polygon;
  11337. exports.Rectangle = Rectangle;
  11338. exports.rectangle = rectangle;
  11339. exports.Map = Map;
  11340. exports.map = createMap;
  11341. })));
  11342. //# sourceMappingURL=leaflet-src.js.map