leaflet-src.js 364 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044
  1. /*
  2. Leaflet 1.0.1+ffcfcc1, a JS library for interactive maps. http://leafletjs.com
  3. (c) 2010-2016 Vladimir Agafonkin, (c) 2010-2011 CloudMade
  4. */
  5. (function (window, document, undefined) {
  6. var L = {
  7. version: "1.0.1+ffcfcc1"
  8. };
  9. function expose() {
  10. var oldL = window.L;
  11. L.noConflict = function () {
  12. window.L = oldL;
  13. return this;
  14. };
  15. window.L = L;
  16. }
  17. // define Leaflet for Node module pattern loaders, including Browserify
  18. if (typeof module === 'object' && typeof module.exports === 'object') {
  19. module.exports = L;
  20. // define Leaflet as an AMD module
  21. } else if (typeof define === 'function' && define.amd) {
  22. define(L);
  23. }
  24. // define Leaflet as a global L variable, saving the original L to restore later if needed
  25. if (typeof window !== 'undefined') {
  26. expose();
  27. }
  28. /*
  29. * @namespace Util
  30. *
  31. * Various utility functions, used by Leaflet internally.
  32. */
  33. L.Util = {
  34. // @function extend(dest: Object, src?: Object): Object
  35. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  36. extend: function (dest) {
  37. var i, j, len, src;
  38. for (j = 1, len = arguments.length; j < len; j++) {
  39. src = arguments[j];
  40. for (i in src) {
  41. dest[i] = src[i];
  42. }
  43. }
  44. return dest;
  45. },
  46. // @function create(proto: Object, properties?: Object): Object
  47. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  48. create: Object.create || (function () {
  49. function F() {}
  50. return function (proto) {
  51. F.prototype = proto;
  52. return new F();
  53. };
  54. })(),
  55. // @function bind(fn: Function, …): Function
  56. // 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).
  57. // Has a `L.bind()` shortcut.
  58. bind: function (fn, obj) {
  59. var slice = Array.prototype.slice;
  60. if (fn.bind) {
  61. return fn.bind.apply(fn, slice.call(arguments, 1));
  62. }
  63. var args = slice.call(arguments, 2);
  64. return function () {
  65. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  66. };
  67. },
  68. // @function stamp(obj: Object): Number
  69. // Returns the unique ID of an object, assiging it one if it doesn't have it.
  70. stamp: function (obj) {
  71. /*eslint-disable */
  72. obj._leaflet_id = obj._leaflet_id || ++L.Util.lastId;
  73. return obj._leaflet_id;
  74. /*eslint-enable */
  75. },
  76. // @property lastId: Number
  77. // Last unique ID used by [`stamp()`](#util-stamp)
  78. lastId: 0,
  79. // @function throttle(fn: Function, time: Number, context: Object): Function
  80. // Returns a function which executes function `fn` with the given scope `context`
  81. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  82. // `fn` will be called no more than one time per given amount of `time`. The arguments
  83. // received by the bound function will be any arguments passed when binding the
  84. // function, followed by any arguments passed when invoking the bound function.
  85. // Has an `L.bind` shortcut.
  86. throttle: function (fn, time, context) {
  87. var lock, args, wrapperFn, later;
  88. later = function () {
  89. // reset lock and call if queued
  90. lock = false;
  91. if (args) {
  92. wrapperFn.apply(context, args);
  93. args = false;
  94. }
  95. };
  96. wrapperFn = function () {
  97. if (lock) {
  98. // called too soon, queue to call later
  99. args = arguments;
  100. } else {
  101. // call and lock until later
  102. fn.apply(context, arguments);
  103. setTimeout(later, time);
  104. lock = true;
  105. }
  106. };
  107. return wrapperFn;
  108. },
  109. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  110. // Returns the number `num` modulo `range` in such a way so it lies within
  111. // `range[0]` and `range[1]`. The returned value will be always smaller than
  112. // `range[1]` unless `includeMax` is set to `true`.
  113. wrapNum: function (x, range, includeMax) {
  114. var max = range[1],
  115. min = range[0],
  116. d = max - min;
  117. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  118. },
  119. // @function falseFn(): Function
  120. // Returns a function which always returns `false`.
  121. falseFn: function () { return false; },
  122. // @function formatNum(num: Number, digits?: Number): Number
  123. // Returns the number `num` rounded to `digits` decimals, or to 5 decimals by default.
  124. formatNum: function (num, digits) {
  125. var pow = Math.pow(10, digits || 5);
  126. return Math.round(num * pow) / pow;
  127. },
  128. // @function trim(str: String): String
  129. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  130. trim: function (str) {
  131. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  132. },
  133. // @function splitWords(str: String): String[]
  134. // Trims and splits the string on whitespace and returns the array of parts.
  135. splitWords: function (str) {
  136. return L.Util.trim(str).split(/\s+/);
  137. },
  138. // @function setOptions(obj: Object, options: Object): Object
  139. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  140. setOptions: function (obj, options) {
  141. if (!obj.hasOwnProperty('options')) {
  142. obj.options = obj.options ? L.Util.create(obj.options) : {};
  143. }
  144. for (var i in options) {
  145. obj.options[i] = options[i];
  146. }
  147. return obj.options;
  148. },
  149. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  150. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  151. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  152. // be appended at the end. If `uppercase` is `true`, the parameter names will
  153. // be uppercased (e.g. `'?A=foo&B=bar'`)
  154. getParamString: function (obj, existingUrl, uppercase) {
  155. var params = [];
  156. for (var i in obj) {
  157. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  158. }
  159. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  160. },
  161. // @function template(str: String, data: Object): String
  162. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  163. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  164. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  165. // data values — they will be evaluated passing `data` as an argument.
  166. template: function (str, data) {
  167. return str.replace(L.Util.templateRe, function (str, key) {
  168. var value = data[key];
  169. if (value === undefined) {
  170. throw new Error('No value provided for variable ' + str);
  171. } else if (typeof value === 'function') {
  172. value = value(data);
  173. }
  174. return value;
  175. });
  176. },
  177. templateRe: /\{ *([\w_\-]+) *\}/g,
  178. // @function isArray(obj): Boolean
  179. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  180. isArray: Array.isArray || function (obj) {
  181. return (Object.prototype.toString.call(obj) === '[object Array]');
  182. },
  183. // @function indexOf(array: Array, el: Object): Number
  184. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  185. indexOf: function (array, el) {
  186. for (var i = 0; i < array.length; i++) {
  187. if (array[i] === el) { return i; }
  188. }
  189. return -1;
  190. },
  191. // @property emptyImageUrl: String
  192. // Data URI string containing a base64-encoded empty GIF image.
  193. // Used as a hack to free memory from unused images on WebKit-powered
  194. // mobile devices (by setting image `src` to this string).
  195. emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
  196. };
  197. (function () {
  198. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  199. function getPrefixed(name) {
  200. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  201. }
  202. var lastTime = 0;
  203. // fallback for IE 7-8
  204. function timeoutDefer(fn) {
  205. var time = +new Date(),
  206. timeToCall = Math.max(0, 16 - (time - lastTime));
  207. lastTime = time + timeToCall;
  208. return window.setTimeout(fn, timeToCall);
  209. }
  210. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer,
  211. cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  212. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  213. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  214. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  215. // `context` if given. When `immediate` is set, `fn` is called immediately if
  216. // the browser doesn't have native support for
  217. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  218. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  219. L.Util.requestAnimFrame = function (fn, context, immediate) {
  220. if (immediate && requestFn === timeoutDefer) {
  221. fn.call(context);
  222. } else {
  223. return requestFn.call(window, L.bind(fn, context));
  224. }
  225. };
  226. // @function cancelAnimFrame(id: Number): undefined
  227. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  228. L.Util.cancelAnimFrame = function (id) {
  229. if (id) {
  230. cancelFn.call(window, id);
  231. }
  232. };
  233. })();
  234. // shortcuts for most used utility functions
  235. L.extend = L.Util.extend;
  236. L.bind = L.Util.bind;
  237. L.stamp = L.Util.stamp;
  238. L.setOptions = L.Util.setOptions;
  239. // @class Class
  240. // @aka L.Class
  241. // @section
  242. // @uninheritable
  243. // Thanks to John Resig and Dean Edwards for inspiration!
  244. L.Class = function () {};
  245. L.Class.extend = function (props) {
  246. // @function extend(props: Object): Function
  247. // [Extends the current class](#class-inheritance) given the properties to be included.
  248. // Returns a Javascript function that is a class constructor (to be called with `new`).
  249. var NewClass = function () {
  250. // call the constructor
  251. if (this.initialize) {
  252. this.initialize.apply(this, arguments);
  253. }
  254. // call all constructor hooks
  255. this.callInitHooks();
  256. };
  257. var parentProto = NewClass.__super__ = this.prototype;
  258. var proto = L.Util.create(parentProto);
  259. proto.constructor = NewClass;
  260. NewClass.prototype = proto;
  261. // inherit parent's statics
  262. for (var i in this) {
  263. if (this.hasOwnProperty(i) && i !== 'prototype') {
  264. NewClass[i] = this[i];
  265. }
  266. }
  267. // mix static properties into the class
  268. if (props.statics) {
  269. L.extend(NewClass, props.statics);
  270. delete props.statics;
  271. }
  272. // mix includes into the prototype
  273. if (props.includes) {
  274. L.Util.extend.apply(null, [proto].concat(props.includes));
  275. delete props.includes;
  276. }
  277. // merge options
  278. if (proto.options) {
  279. props.options = L.Util.extend(L.Util.create(proto.options), props.options);
  280. }
  281. // mix given properties into the prototype
  282. L.extend(proto, props);
  283. proto._initHooks = [];
  284. // add method for calling all hooks
  285. proto.callInitHooks = function () {
  286. if (this._initHooksCalled) { return; }
  287. if (parentProto.callInitHooks) {
  288. parentProto.callInitHooks.call(this);
  289. }
  290. this._initHooksCalled = true;
  291. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  292. proto._initHooks[i].call(this);
  293. }
  294. };
  295. return NewClass;
  296. };
  297. // @function include(properties: Object): this
  298. // [Includes a mixin](#class-includes) into the current class.
  299. L.Class.include = function (props) {
  300. L.extend(this.prototype, props);
  301. return this;
  302. };
  303. // @function mergeOptions(options: Object): this
  304. // [Merges `options`](#class-options) into the defaults of the class.
  305. L.Class.mergeOptions = function (options) {
  306. L.extend(this.prototype.options, options);
  307. return this;
  308. };
  309. // @function addInitHook(fn: Function): this
  310. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  311. L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
  312. var args = Array.prototype.slice.call(arguments, 1);
  313. var init = typeof fn === 'function' ? fn : function () {
  314. this[fn].apply(this, args);
  315. };
  316. this.prototype._initHooks = this.prototype._initHooks || [];
  317. this.prototype._initHooks.push(init);
  318. return this;
  319. };
  320. /*
  321. * @class Evented
  322. * @aka L.Evented
  323. * @inherits Class
  324. *
  325. * 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).
  326. *
  327. * @example
  328. *
  329. * ```js
  330. * map.on('click', function(e) {
  331. * alert(e.latlng);
  332. * } );
  333. * ```
  334. *
  335. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  336. *
  337. * ```js
  338. * function onClick(e) { ... }
  339. *
  340. * map.on('click', onClick);
  341. * map.off('click', onClick);
  342. * ```
  343. */
  344. L.Evented = L.Class.extend({
  345. /* @method on(type: String, fn: Function, context?: Object): this
  346. * 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'`).
  347. *
  348. * @alternative
  349. * @method on(eventMap: Object): this
  350. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  351. */
  352. on: function (types, fn, context) {
  353. // types can be a map of types/handlers
  354. if (typeof types === 'object') {
  355. for (var type in types) {
  356. // we don't process space-separated events here for performance;
  357. // it's a hot path since Layer uses the on(obj) syntax
  358. this._on(type, types[type], fn);
  359. }
  360. } else {
  361. // types can be a string of space-separated words
  362. types = L.Util.splitWords(types);
  363. for (var i = 0, len = types.length; i < len; i++) {
  364. this._on(types[i], fn, context);
  365. }
  366. }
  367. return this;
  368. },
  369. /* @method off(type: String, fn?: Function, context?: Object): this
  370. * 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.
  371. *
  372. * @alternative
  373. * @method off(eventMap: Object): this
  374. * Removes a set of type/listener pairs.
  375. *
  376. * @alternative
  377. * @method off: this
  378. * Removes all listeners to all events on the object.
  379. */
  380. off: function (types, fn, context) {
  381. if (!types) {
  382. // clear all listeners if called without arguments
  383. delete this._events;
  384. } else if (typeof types === 'object') {
  385. for (var type in types) {
  386. this._off(type, types[type], fn);
  387. }
  388. } else {
  389. types = L.Util.splitWords(types);
  390. for (var i = 0, len = types.length; i < len; i++) {
  391. this._off(types[i], fn, context);
  392. }
  393. }
  394. return this;
  395. },
  396. // attach listener (without syntactic sugar now)
  397. _on: function (type, fn, context) {
  398. this._events = this._events || {};
  399. /* get/init listeners for type */
  400. var typeListeners = this._events[type];
  401. if (!typeListeners) {
  402. typeListeners = [];
  403. this._events[type] = typeListeners;
  404. }
  405. if (context === this) {
  406. // Less memory footprint.
  407. context = undefined;
  408. }
  409. var newListener = {fn: fn, ctx: context},
  410. listeners = typeListeners;
  411. // check if fn already there
  412. for (var i = 0, len = listeners.length; i < len; i++) {
  413. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  414. return;
  415. }
  416. }
  417. listeners.push(newListener);
  418. typeListeners.count++;
  419. },
  420. _off: function (type, fn, context) {
  421. var listeners,
  422. i,
  423. len;
  424. if (!this._events) { return; }
  425. listeners = this._events[type];
  426. if (!listeners) {
  427. return;
  428. }
  429. if (!fn) {
  430. // Set all removed listeners to noop so they are not called if remove happens in fire
  431. for (i = 0, len = listeners.length; i < len; i++) {
  432. listeners[i].fn = L.Util.falseFn;
  433. }
  434. // clear all listeners for a type if function isn't specified
  435. delete this._events[type];
  436. return;
  437. }
  438. if (context === this) {
  439. context = undefined;
  440. }
  441. if (listeners) {
  442. // find fn and remove it
  443. for (i = 0, len = listeners.length; i < len; i++) {
  444. var l = listeners[i];
  445. if (l.ctx !== context) { continue; }
  446. if (l.fn === fn) {
  447. // set the removed listener to noop so that's not called if remove happens in fire
  448. l.fn = L.Util.falseFn;
  449. if (this._firingCount) {
  450. /* copy array in case events are being fired */
  451. this._events[type] = listeners = listeners.slice();
  452. }
  453. listeners.splice(i, 1);
  454. return;
  455. }
  456. }
  457. }
  458. },
  459. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  460. // Fires an event of the specified type. You can optionally provide an data
  461. // object — the first argument of the listener function will contain its
  462. // properties. The event might can optionally be propagated to event parents.
  463. fire: function (type, data, propagate) {
  464. if (!this.listens(type, propagate)) { return this; }
  465. var event = L.Util.extend({}, data, {type: type, target: this});
  466. if (this._events) {
  467. var listeners = this._events[type];
  468. if (listeners) {
  469. this._firingCount = (this._firingCount + 1) || 1;
  470. for (var i = 0, len = listeners.length; i < len; i++) {
  471. var l = listeners[i];
  472. l.fn.call(l.ctx || this, event);
  473. }
  474. this._firingCount--;
  475. }
  476. }
  477. if (propagate) {
  478. // propagate the event to parents (set with addEventParent)
  479. this._propagateEvent(event);
  480. }
  481. return this;
  482. },
  483. // @method listens(type: String): Boolean
  484. // Returns `true` if a particular event type has any listeners attached to it.
  485. listens: function (type, propagate) {
  486. var listeners = this._events && this._events[type];
  487. if (listeners && listeners.length) { return true; }
  488. if (propagate) {
  489. // also check parents for listeners if event propagates
  490. for (var id in this._eventParents) {
  491. if (this._eventParents[id].listens(type, propagate)) { return true; }
  492. }
  493. }
  494. return false;
  495. },
  496. // @method once(…): this
  497. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  498. once: function (types, fn, context) {
  499. if (typeof types === 'object') {
  500. for (var type in types) {
  501. this.once(type, types[type], fn);
  502. }
  503. return this;
  504. }
  505. var handler = L.bind(function () {
  506. this
  507. .off(types, fn, context)
  508. .off(types, handler, context);
  509. }, this);
  510. // add a listener that's executed once and removed after that
  511. return this
  512. .on(types, fn, context)
  513. .on(types, handler, context);
  514. },
  515. // @method addEventParent(obj: Evented): this
  516. // Adds an event parent - an `Evented` that will receive propagated events
  517. addEventParent: function (obj) {
  518. this._eventParents = this._eventParents || {};
  519. this._eventParents[L.stamp(obj)] = obj;
  520. return this;
  521. },
  522. // @method removeEventParent(obj: Evented): this
  523. // Removes an event parent, so it will stop receiving propagated events
  524. removeEventParent: function (obj) {
  525. if (this._eventParents) {
  526. delete this._eventParents[L.stamp(obj)];
  527. }
  528. return this;
  529. },
  530. _propagateEvent: function (e) {
  531. for (var id in this._eventParents) {
  532. this._eventParents[id].fire(e.type, L.extend({layer: e.target}, e), true);
  533. }
  534. }
  535. });
  536. var proto = L.Evented.prototype;
  537. // aliases; we should ditch those eventually
  538. // @method addEventListener(…): this
  539. // Alias to [`on(…)`](#evented-on)
  540. proto.addEventListener = proto.on;
  541. // @method removeEventListener(…): this
  542. // Alias to [`off(…)`](#evented-off)
  543. // @method clearAllEventListeners(…): this
  544. // Alias to [`off()`](#evented-off)
  545. proto.removeEventListener = proto.clearAllEventListeners = proto.off;
  546. // @method addOneTimeEventListener(…): this
  547. // Alias to [`once(…)`](#evented-once)
  548. proto.addOneTimeEventListener = proto.once;
  549. // @method fireEvent(…): this
  550. // Alias to [`fire(…)`](#evented-fire)
  551. proto.fireEvent = proto.fire;
  552. // @method hasEventListeners(…): Boolean
  553. // Alias to [`listens(…)`](#evented-listens)
  554. proto.hasEventListeners = proto.listens;
  555. L.Mixin = {Events: proto};
  556. /*
  557. * @namespace Browser
  558. * @aka L.Browser
  559. *
  560. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  561. *
  562. * @example
  563. *
  564. * ```js
  565. * if (L.Browser.ielt9) {
  566. * alert('Upgrade your browser, dude!');
  567. * }
  568. * ```
  569. */
  570. (function () {
  571. var ua = navigator.userAgent.toLowerCase(),
  572. doc = document.documentElement,
  573. ie = 'ActiveXObject' in window,
  574. webkit = ua.indexOf('webkit') !== -1,
  575. phantomjs = ua.indexOf('phantom') !== -1,
  576. android23 = ua.search('android [23]') !== -1,
  577. chrome = ua.indexOf('chrome') !== -1,
  578. gecko = ua.indexOf('gecko') !== -1 && !webkit && !window.opera && !ie,
  579. win = navigator.platform.indexOf('Win') === 0,
  580. mobile = typeof orientation !== 'undefined' || ua.indexOf('mobile') !== -1,
  581. msPointer = !window.PointerEvent && window.MSPointerEvent,
  582. pointer = window.PointerEvent || msPointer,
  583. ie3d = ie && ('transition' in doc.style),
  584. webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23,
  585. gecko3d = 'MozPerspective' in doc.style,
  586. opera12 = 'OTransition' in doc.style;
  587. var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
  588. (window.DocumentTouch && document instanceof window.DocumentTouch));
  589. L.Browser = {
  590. // @property ie: Boolean
  591. // `true` for all Internet Explorer versions (not Edge).
  592. ie: ie,
  593. // @property ielt9: Boolean
  594. // `true` for Internet Explorer versions less than 9.
  595. ielt9: ie && !document.addEventListener,
  596. // @property edge: Boolean
  597. // `true` for the Edge web browser.
  598. edge: 'msLaunchUri' in navigator && !('documentMode' in document),
  599. // @property webkit: Boolean
  600. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  601. webkit: webkit,
  602. // @property gecko: Boolean
  603. // `true` for gecko-based browsers like Firefox.
  604. gecko: gecko,
  605. // @property android: Boolean
  606. // `true` for any browser running on an Android platform.
  607. android: ua.indexOf('android') !== -1,
  608. // @property android23: Boolean
  609. // `true` for browsers running on Android 2 or Android 3.
  610. android23: android23,
  611. // @property chrome: Boolean
  612. // `true` for the Chrome browser.
  613. chrome: chrome,
  614. // @property safari: Boolean
  615. // `true` for the Safari browser.
  616. safari: !chrome && ua.indexOf('safari') !== -1,
  617. // @property win: Boolean
  618. // `true` when the browser is running in a Windows platform
  619. win: win,
  620. // @property ie3d: Boolean
  621. // `true` for all Internet Explorer versions supporting CSS transforms.
  622. ie3d: ie3d,
  623. // @property webkit3d: Boolean
  624. // `true` for webkit-based browsers supporting CSS transforms.
  625. webkit3d: webkit3d,
  626. // @property gecko3d: Boolean
  627. // `true` for gecko-based browsers supporting CSS transforms.
  628. gecko3d: gecko3d,
  629. // @property opera12: Boolean
  630. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  631. opera12: opera12,
  632. // @property any3d: Boolean
  633. // `true` for all browsers supporting CSS transforms.
  634. any3d: !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantomjs,
  635. // @property mobile: Boolean
  636. // `true` for all browsers running in a mobile device.
  637. mobile: mobile,
  638. // @property mobileWebkit: Boolean
  639. // `true` for all webkit-based browsers in a mobile device.
  640. mobileWebkit: mobile && webkit,
  641. // @property mobileWebkit3d: Boolean
  642. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  643. mobileWebkit3d: mobile && webkit3d,
  644. // @property mobileOpera: Boolean
  645. // `true` for the Opera browser in a mobile device.
  646. mobileOpera: mobile && window.opera,
  647. // @property mobileGecko: Boolean
  648. // `true` for gecko-based browsers running in a mobile device.
  649. mobileGecko: mobile && gecko,
  650. // @property touch: Boolean
  651. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  652. touch: !!touch,
  653. // @property msPointer: Boolean
  654. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  655. msPointer: !!msPointer,
  656. // @property pointer: Boolean
  657. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  658. pointer: !!pointer,
  659. // @property retina: Boolean
  660. // `true` for browsers on a high-resolution "retina" screen.
  661. retina: (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1
  662. };
  663. }());
  664. /*
  665. * @class Point
  666. * @aka L.Point
  667. *
  668. * Represents a point with `x` and `y` coordinates in pixels.
  669. *
  670. * @example
  671. *
  672. * ```js
  673. * var point = L.point(200, 300);
  674. * ```
  675. *
  676. * 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:
  677. *
  678. * ```js
  679. * map.panBy([200, 300]);
  680. * map.panBy(L.point(200, 300));
  681. * ```
  682. */
  683. L.Point = function (x, y, round) {
  684. this.x = (round ? Math.round(x) : x);
  685. this.y = (round ? Math.round(y) : y);
  686. };
  687. L.Point.prototype = {
  688. // @method clone(): Point
  689. // Returns a copy of the current point.
  690. clone: function () {
  691. return new L.Point(this.x, this.y);
  692. },
  693. // @method add(otherPoint: Point): Point
  694. // Returns the result of addition of the current and the given points.
  695. add: function (point) {
  696. // non-destructive, returns a new point
  697. return this.clone()._add(L.point(point));
  698. },
  699. _add: function (point) {
  700. // destructive, used directly for performance in situations where it's safe to modify existing point
  701. this.x += point.x;
  702. this.y += point.y;
  703. return this;
  704. },
  705. // @method subtract(otherPoint: Point): Point
  706. // Returns the result of subtraction of the given point from the current.
  707. subtract: function (point) {
  708. return this.clone()._subtract(L.point(point));
  709. },
  710. _subtract: function (point) {
  711. this.x -= point.x;
  712. this.y -= point.y;
  713. return this;
  714. },
  715. // @method divideBy(num: Number): Point
  716. // Returns the result of division of the current point by the given number.
  717. divideBy: function (num) {
  718. return this.clone()._divideBy(num);
  719. },
  720. _divideBy: function (num) {
  721. this.x /= num;
  722. this.y /= num;
  723. return this;
  724. },
  725. // @method multiplyBy(num: Number): Point
  726. // Returns the result of multiplication of the current point by the given number.
  727. multiplyBy: function (num) {
  728. return this.clone()._multiplyBy(num);
  729. },
  730. _multiplyBy: function (num) {
  731. this.x *= num;
  732. this.y *= num;
  733. return this;
  734. },
  735. // @method scaleBy(scale: Point): Point
  736. // Multiply each coordinate of the current point by each coordinate of
  737. // `scale`. In linear algebra terms, multiply the point by the
  738. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  739. // defined by `scale`.
  740. scaleBy: function (point) {
  741. return new L.Point(this.x * point.x, this.y * point.y);
  742. },
  743. // @method unscaleBy(scale: Point): Point
  744. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  745. // each coordinate of `scale`.
  746. unscaleBy: function (point) {
  747. return new L.Point(this.x / point.x, this.y / point.y);
  748. },
  749. // @method round(): Point
  750. // Returns a copy of the current point with rounded coordinates.
  751. round: function () {
  752. return this.clone()._round();
  753. },
  754. _round: function () {
  755. this.x = Math.round(this.x);
  756. this.y = Math.round(this.y);
  757. return this;
  758. },
  759. // @method floor(): Point
  760. // Returns a copy of the current point with floored coordinates (rounded down).
  761. floor: function () {
  762. return this.clone()._floor();
  763. },
  764. _floor: function () {
  765. this.x = Math.floor(this.x);
  766. this.y = Math.floor(this.y);
  767. return this;
  768. },
  769. // @method ceil(): Point
  770. // Returns a copy of the current point with ceiled coordinates (rounded up).
  771. ceil: function () {
  772. return this.clone()._ceil();
  773. },
  774. _ceil: function () {
  775. this.x = Math.ceil(this.x);
  776. this.y = Math.ceil(this.y);
  777. return this;
  778. },
  779. // @method distanceTo(otherPoint: Point): Number
  780. // Returns the cartesian distance between the current and the given points.
  781. distanceTo: function (point) {
  782. point = L.point(point);
  783. var x = point.x - this.x,
  784. y = point.y - this.y;
  785. return Math.sqrt(x * x + y * y);
  786. },
  787. // @method equals(otherPoint: Point): Boolean
  788. // Returns `true` if the given point has the same coordinates.
  789. equals: function (point) {
  790. point = L.point(point);
  791. return point.x === this.x &&
  792. point.y === this.y;
  793. },
  794. // @method contains(otherPoint: Point): Boolean
  795. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  796. contains: function (point) {
  797. point = L.point(point);
  798. return Math.abs(point.x) <= Math.abs(this.x) &&
  799. Math.abs(point.y) <= Math.abs(this.y);
  800. },
  801. // @method toString(): String
  802. // Returns a string representation of the point for debugging purposes.
  803. toString: function () {
  804. return 'Point(' +
  805. L.Util.formatNum(this.x) + ', ' +
  806. L.Util.formatNum(this.y) + ')';
  807. }
  808. };
  809. // @factory L.point(x: Number, y: Number, round?: Boolean)
  810. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  811. // @alternative
  812. // @factory L.point(coords: Number[])
  813. // Expects an array of the form `[x, y]` instead.
  814. // @alternative
  815. // @factory L.point(coords: Object)
  816. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  817. L.point = function (x, y, round) {
  818. if (x instanceof L.Point) {
  819. return x;
  820. }
  821. if (L.Util.isArray(x)) {
  822. return new L.Point(x[0], x[1]);
  823. }
  824. if (x === undefined || x === null) {
  825. return x;
  826. }
  827. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  828. return new L.Point(x.x, x.y);
  829. }
  830. return new L.Point(x, y, round);
  831. };
  832. /*
  833. * @class Bounds
  834. * @aka L.Bounds
  835. *
  836. * Represents a rectangular area in pixel coordinates.
  837. *
  838. * @example
  839. *
  840. * ```js
  841. * var p1 = L.point(10, 10),
  842. * p2 = L.point(40, 60),
  843. * bounds = L.bounds(p1, p2);
  844. * ```
  845. *
  846. * 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:
  847. *
  848. * ```js
  849. * otherBounds.intersects([[10, 10], [40, 60]]);
  850. * ```
  851. */
  852. L.Bounds = function (a, b) {
  853. if (!a) { return; }
  854. var points = b ? [a, b] : a;
  855. for (var i = 0, len = points.length; i < len; i++) {
  856. this.extend(points[i]);
  857. }
  858. };
  859. L.Bounds.prototype = {
  860. // @method extend(point: Point): this
  861. // Extends the bounds to contain the given point.
  862. extend: function (point) { // (Point)
  863. point = L.point(point);
  864. // @property min: Point
  865. // The top left corner of the rectangle.
  866. // @property max: Point
  867. // The bottom right corner of the rectangle.
  868. if (!this.min && !this.max) {
  869. this.min = point.clone();
  870. this.max = point.clone();
  871. } else {
  872. this.min.x = Math.min(point.x, this.min.x);
  873. this.max.x = Math.max(point.x, this.max.x);
  874. this.min.y = Math.min(point.y, this.min.y);
  875. this.max.y = Math.max(point.y, this.max.y);
  876. }
  877. return this;
  878. },
  879. // @method getCenter(round?: Boolean): Point
  880. // Returns the center point of the bounds.
  881. getCenter: function (round) {
  882. return new L.Point(
  883. (this.min.x + this.max.x) / 2,
  884. (this.min.y + this.max.y) / 2, round);
  885. },
  886. // @method getBottomLeft(): Point
  887. // Returns the bottom-left point of the bounds.
  888. getBottomLeft: function () {
  889. return new L.Point(this.min.x, this.max.y);
  890. },
  891. // @method getTopRight(): Point
  892. // Returns the top-right point of the bounds.
  893. getTopRight: function () { // -> Point
  894. return new L.Point(this.max.x, this.min.y);
  895. },
  896. // @method getSize(): Point
  897. // Returns the size of the given bounds
  898. getSize: function () {
  899. return this.max.subtract(this.min);
  900. },
  901. // @method contains(otherBounds: Bounds): Boolean
  902. // Returns `true` if the rectangle contains the given one.
  903. // @alternative
  904. // @method contains(point: Point): Boolean
  905. // Returns `true` if the rectangle contains the given point.
  906. contains: function (obj) {
  907. var min, max;
  908. if (typeof obj[0] === 'number' || obj instanceof L.Point) {
  909. obj = L.point(obj);
  910. } else {
  911. obj = L.bounds(obj);
  912. }
  913. if (obj instanceof L.Bounds) {
  914. min = obj.min;
  915. max = obj.max;
  916. } else {
  917. min = max = obj;
  918. }
  919. return (min.x >= this.min.x) &&
  920. (max.x <= this.max.x) &&
  921. (min.y >= this.min.y) &&
  922. (max.y <= this.max.y);
  923. },
  924. // @method intersects(otherBounds: Bounds): Boolean
  925. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  926. // intersect if they have at least one point in common.
  927. intersects: function (bounds) { // (Bounds) -> Boolean
  928. bounds = L.bounds(bounds);
  929. var min = this.min,
  930. max = this.max,
  931. min2 = bounds.min,
  932. max2 = bounds.max,
  933. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  934. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  935. return xIntersects && yIntersects;
  936. },
  937. // @method overlaps(otherBounds: Bounds): Boolean
  938. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  939. // overlap if their intersection is an area.
  940. overlaps: function (bounds) { // (Bounds) -> Boolean
  941. bounds = L.bounds(bounds);
  942. var min = this.min,
  943. max = this.max,
  944. min2 = bounds.min,
  945. max2 = bounds.max,
  946. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  947. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  948. return xOverlaps && yOverlaps;
  949. },
  950. isValid: function () {
  951. return !!(this.min && this.max);
  952. }
  953. };
  954. // @factory L.bounds(topLeft: Point, bottomRight: Point)
  955. // Creates a Bounds object from two coordinates (usually top-left and bottom-right corners).
  956. // @alternative
  957. // @factory L.bounds(points: Point[])
  958. // Creates a Bounds object from the points it contains
  959. L.bounds = function (a, b) {
  960. if (!a || a instanceof L.Bounds) {
  961. return a;
  962. }
  963. return new L.Bounds(a, b);
  964. };
  965. /*
  966. * @class Transformation
  967. * @aka L.Transformation
  968. *
  969. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  970. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  971. * the reverse. Used by Leaflet in its projections code.
  972. *
  973. * @example
  974. *
  975. * ```js
  976. * var transformation = new L.Transformation(2, 5, -1, 10),
  977. * p = L.point(1, 2),
  978. * p2 = transformation.transform(p), // L.point(7, 8)
  979. * p3 = transformation.untransform(p2); // L.point(1, 2)
  980. * ```
  981. */
  982. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  983. // Creates a `Transformation` object with the given coefficients.
  984. L.Transformation = function (a, b, c, d) {
  985. this._a = a;
  986. this._b = b;
  987. this._c = c;
  988. this._d = d;
  989. };
  990. L.Transformation.prototype = {
  991. // @method transform(point: Point, scale?: Number): Point
  992. // Returns a transformed point, optionally multiplied by the given scale.
  993. // Only accepts real `L.Point` instances, not arrays.
  994. transform: function (point, scale) { // (Point, Number) -> Point
  995. return this._transform(point.clone(), scale);
  996. },
  997. // destructive transform (faster)
  998. _transform: function (point, scale) {
  999. scale = scale || 1;
  1000. point.x = scale * (this._a * point.x + this._b);
  1001. point.y = scale * (this._c * point.y + this._d);
  1002. return point;
  1003. },
  1004. // @method untransform(point: Point, scale?: Number): Point
  1005. // Returns the reverse transformation of the given point, optionally divided
  1006. // by the given scale. Only accepts real `L.Point` instances, not arrays.
  1007. untransform: function (point, scale) {
  1008. scale = scale || 1;
  1009. return new L.Point(
  1010. (point.x / scale - this._b) / this._a,
  1011. (point.y / scale - this._d) / this._c);
  1012. }
  1013. };
  1014. /*
  1015. * @namespace DomUtil
  1016. *
  1017. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1018. * tree, used by Leaflet internally.
  1019. *
  1020. * Most functions expecting or returning a `HTMLElement` also work for
  1021. * SVG elements. The only difference is that classes refer to CSS classes
  1022. * in HTML and SVG classes in SVG.
  1023. */
  1024. L.DomUtil = {
  1025. // @function get(id: String|HTMLElement): HTMLElement
  1026. // Returns an element given its DOM id, or returns the element itself
  1027. // if it was passed directly.
  1028. get: function (id) {
  1029. return typeof id === 'string' ? document.getElementById(id) : id;
  1030. },
  1031. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1032. // Returns the value for a certain style attribute on an element,
  1033. // including computed values or values set through CSS.
  1034. getStyle: function (el, style) {
  1035. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1036. if ((!value || value === 'auto') && document.defaultView) {
  1037. var css = document.defaultView.getComputedStyle(el, null);
  1038. value = css ? css[style] : null;
  1039. }
  1040. return value === 'auto' ? null : value;
  1041. },
  1042. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1043. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1044. create: function (tagName, className, container) {
  1045. var el = document.createElement(tagName);
  1046. el.className = className || '';
  1047. if (container) {
  1048. container.appendChild(el);
  1049. }
  1050. return el;
  1051. },
  1052. // @function remove(el: HTMLElement)
  1053. // Removes `el` from its parent element
  1054. remove: function (el) {
  1055. var parent = el.parentNode;
  1056. if (parent) {
  1057. parent.removeChild(el);
  1058. }
  1059. },
  1060. // @function empty(el: HTMLElement)
  1061. // Removes all of `el`'s children elements from `el`
  1062. empty: function (el) {
  1063. while (el.firstChild) {
  1064. el.removeChild(el.firstChild);
  1065. }
  1066. },
  1067. // @function toFront(el: HTMLElement)
  1068. // Makes `el` the last children of its parent, so it renders in front of the other children.
  1069. toFront: function (el) {
  1070. el.parentNode.appendChild(el);
  1071. },
  1072. // @function toBack(el: HTMLElement)
  1073. // Makes `el` the first children of its parent, so it renders back from the other children.
  1074. toBack: function (el) {
  1075. var parent = el.parentNode;
  1076. parent.insertBefore(el, parent.firstChild);
  1077. },
  1078. // @function hasClass(el: HTMLElement, name: String): Boolean
  1079. // Returns `true` if the element's class attribute contains `name`.
  1080. hasClass: function (el, name) {
  1081. if (el.classList !== undefined) {
  1082. return el.classList.contains(name);
  1083. }
  1084. var className = L.DomUtil.getClass(el);
  1085. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  1086. },
  1087. // @function addClass(el: HTMLElement, name: String)
  1088. // Adds `name` to the element's class attribute.
  1089. addClass: function (el, name) {
  1090. if (el.classList !== undefined) {
  1091. var classes = L.Util.splitWords(name);
  1092. for (var i = 0, len = classes.length; i < len; i++) {
  1093. el.classList.add(classes[i]);
  1094. }
  1095. } else if (!L.DomUtil.hasClass(el, name)) {
  1096. var className = L.DomUtil.getClass(el);
  1097. L.DomUtil.setClass(el, (className ? className + ' ' : '') + name);
  1098. }
  1099. },
  1100. // @function removeClass(el: HTMLElement, name: String)
  1101. // Removes `name` from the element's class attribute.
  1102. removeClass: function (el, name) {
  1103. if (el.classList !== undefined) {
  1104. el.classList.remove(name);
  1105. } else {
  1106. L.DomUtil.setClass(el, L.Util.trim((' ' + L.DomUtil.getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  1107. }
  1108. },
  1109. // @function setClass(el: HTMLElement, name: String)
  1110. // Sets the element's class.
  1111. setClass: function (el, name) {
  1112. if (el.className.baseVal === undefined) {
  1113. el.className = name;
  1114. } else {
  1115. // in case of SVG element
  1116. el.className.baseVal = name;
  1117. }
  1118. },
  1119. // @function getClass(el: HTMLElement): String
  1120. // Returns the element's class.
  1121. getClass: function (el) {
  1122. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  1123. },
  1124. // @function setOpacity(el: HTMLElement, opacity: Number)
  1125. // Set the opacity of an element (including old IE support).
  1126. // `opacity` must be a number from `0` to `1`.
  1127. setOpacity: function (el, value) {
  1128. if ('opacity' in el.style) {
  1129. el.style.opacity = value;
  1130. } else if ('filter' in el.style) {
  1131. L.DomUtil._setOpacityIE(el, value);
  1132. }
  1133. },
  1134. _setOpacityIE: function (el, value) {
  1135. var filter = false,
  1136. filterName = 'DXImageTransform.Microsoft.Alpha';
  1137. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  1138. try {
  1139. filter = el.filters.item(filterName);
  1140. } catch (e) {
  1141. // don't set opacity to 1 if we haven't already set an opacity,
  1142. // it isn't needed and breaks transparent pngs.
  1143. if (value === 1) { return; }
  1144. }
  1145. value = Math.round(value * 100);
  1146. if (filter) {
  1147. filter.Enabled = (value !== 100);
  1148. filter.Opacity = value;
  1149. } else {
  1150. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  1151. }
  1152. },
  1153. // @function testProp(props: String[]): String|false
  1154. // Goes through the array of style names and returns the first name
  1155. // that is a valid style name for an element. If no such name is found,
  1156. // it returns false. Useful for vendor-prefixed styles like `transform`.
  1157. testProp: function (props) {
  1158. var style = document.documentElement.style;
  1159. for (var i = 0; i < props.length; i++) {
  1160. if (props[i] in style) {
  1161. return props[i];
  1162. }
  1163. }
  1164. return false;
  1165. },
  1166. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  1167. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  1168. // and optionally scaled by `scale`. Does not have an effect if the
  1169. // browser doesn't support 3D CSS transforms.
  1170. setTransform: function (el, offset, scale) {
  1171. var pos = offset || new L.Point(0, 0);
  1172. el.style[L.DomUtil.TRANSFORM] =
  1173. (L.Browser.ie3d ?
  1174. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  1175. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  1176. (scale ? ' scale(' + scale + ')' : '');
  1177. },
  1178. // @function setPosition(el: HTMLElement, position: Point)
  1179. // Sets the position of `el` to coordinates specified by `position`,
  1180. // using CSS translate or top/left positioning depending on the browser
  1181. // (used by Leaflet internally to position its layers).
  1182. setPosition: function (el, point) { // (HTMLElement, Point[, Boolean])
  1183. /*eslint-disable */
  1184. el._leaflet_pos = point;
  1185. /*eslint-enable */
  1186. if (L.Browser.any3d) {
  1187. L.DomUtil.setTransform(el, point);
  1188. } else {
  1189. el.style.left = point.x + 'px';
  1190. el.style.top = point.y + 'px';
  1191. }
  1192. },
  1193. // @function getPosition(el: HTMLElement): Point
  1194. // Returns the coordinates of an element previously positioned with setPosition.
  1195. getPosition: function (el) {
  1196. // this method is only used for elements previously positioned using setPosition,
  1197. // so it's safe to cache the position for performance
  1198. return el._leaflet_pos || new L.Point(0, 0);
  1199. }
  1200. };
  1201. (function () {
  1202. // prefix style property names
  1203. // @property TRANSFORM: String
  1204. // Vendor-prefixed fransform style name (e.g. `'webkitTransform'` for WebKit).
  1205. L.DomUtil.TRANSFORM = L.DomUtil.testProp(
  1206. ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1207. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1208. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1209. // @property TRANSITION: String
  1210. // Vendor-prefixed transform style name.
  1211. var transition = L.DomUtil.TRANSITION = L.DomUtil.testProp(
  1212. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1213. L.DomUtil.TRANSITION_END =
  1214. transition === 'webkitTransition' || transition === 'OTransition' ? transition + 'End' : 'transitionend';
  1215. // @function disableTextSelection()
  1216. // Prevents the user from generating `selectstart` DOM events, usually generated
  1217. // when the user drags the mouse through a page with text. Used internally
  1218. // by Leaflet to override the behaviour of any click-and-drag interaction on
  1219. // the map. Affects drag interactions on the whole document.
  1220. // @function enableTextSelection()
  1221. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  1222. if ('onselectstart' in document) {
  1223. L.DomUtil.disableTextSelection = function () {
  1224. L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
  1225. };
  1226. L.DomUtil.enableTextSelection = function () {
  1227. L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
  1228. };
  1229. } else {
  1230. var userSelectProperty = L.DomUtil.testProp(
  1231. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  1232. L.DomUtil.disableTextSelection = function () {
  1233. if (userSelectProperty) {
  1234. var style = document.documentElement.style;
  1235. this._userSelect = style[userSelectProperty];
  1236. style[userSelectProperty] = 'none';
  1237. }
  1238. };
  1239. L.DomUtil.enableTextSelection = function () {
  1240. if (userSelectProperty) {
  1241. document.documentElement.style[userSelectProperty] = this._userSelect;
  1242. delete this._userSelect;
  1243. }
  1244. };
  1245. }
  1246. // @function disableImageDrag()
  1247. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  1248. // for `dragstart` DOM events, usually generated when the user drags an image.
  1249. L.DomUtil.disableImageDrag = function () {
  1250. L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
  1251. };
  1252. // @function enableImageDrag()
  1253. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  1254. L.DomUtil.enableImageDrag = function () {
  1255. L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
  1256. };
  1257. // @function preventOutline(el: HTMLElement)
  1258. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  1259. // of the element `el` invisible. Used internally by Leaflet to prevent
  1260. // focusable elements from displaying an outline when the user performs a
  1261. // drag interaction on them.
  1262. L.DomUtil.preventOutline = function (element) {
  1263. while (element.tabIndex === -1) {
  1264. element = element.parentNode;
  1265. }
  1266. if (!element || !element.style) { return; }
  1267. L.DomUtil.restoreOutline();
  1268. this._outlineElement = element;
  1269. this._outlineStyle = element.style.outline;
  1270. element.style.outline = 'none';
  1271. L.DomEvent.on(window, 'keydown', L.DomUtil.restoreOutline, this);
  1272. };
  1273. // @function restoreOutline()
  1274. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  1275. L.DomUtil.restoreOutline = function () {
  1276. if (!this._outlineElement) { return; }
  1277. this._outlineElement.style.outline = this._outlineStyle;
  1278. delete this._outlineElement;
  1279. delete this._outlineStyle;
  1280. L.DomEvent.off(window, 'keydown', L.DomUtil.restoreOutline, this);
  1281. };
  1282. })();
  1283. /* @class LatLng
  1284. * @aka L.LatLng
  1285. *
  1286. * Represents a geographical point with a certain latitude and longitude.
  1287. *
  1288. * @example
  1289. *
  1290. * ```
  1291. * var latlng = L.latLng(50.5, 30.5);
  1292. * ```
  1293. *
  1294. * 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:
  1295. *
  1296. * ```
  1297. * map.panTo([50, 30]);
  1298. * map.panTo({lon: 30, lat: 50});
  1299. * map.panTo({lat: 50, lng: 30});
  1300. * map.panTo(L.latLng(50, 30));
  1301. * ```
  1302. */
  1303. L.LatLng = function (lat, lng, alt) {
  1304. if (isNaN(lat) || isNaN(lng)) {
  1305. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1306. }
  1307. // @property lat: Number
  1308. // Latitude in degrees
  1309. this.lat = +lat;
  1310. // @property lng: Number
  1311. // Longitude in degrees
  1312. this.lng = +lng;
  1313. // @property alt: Number
  1314. // Altitude in meters (optional)
  1315. if (alt !== undefined) {
  1316. this.alt = +alt;
  1317. }
  1318. };
  1319. L.LatLng.prototype = {
  1320. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1321. // 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.
  1322. equals: function (obj, maxMargin) {
  1323. if (!obj) { return false; }
  1324. obj = L.latLng(obj);
  1325. var margin = Math.max(
  1326. Math.abs(this.lat - obj.lat),
  1327. Math.abs(this.lng - obj.lng));
  1328. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1329. },
  1330. // @method toString(): String
  1331. // Returns a string representation of the point (for debugging purposes).
  1332. toString: function (precision) {
  1333. return 'LatLng(' +
  1334. L.Util.formatNum(this.lat, precision) + ', ' +
  1335. L.Util.formatNum(this.lng, precision) + ')';
  1336. },
  1337. // @method distanceTo(otherLatLng: LatLng): Number
  1338. // Returns the distance (in meters) to the given `LatLng` calculated using the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula).
  1339. distanceTo: function (other) {
  1340. return L.CRS.Earth.distance(this, L.latLng(other));
  1341. },
  1342. // @method wrap(): LatLng
  1343. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1344. wrap: function () {
  1345. return L.CRS.Earth.wrapLatLng(this);
  1346. },
  1347. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1348. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters` meters apart from the `LatLng`.
  1349. toBounds: function (sizeInMeters) {
  1350. var latAccuracy = 180 * sizeInMeters / 40075017,
  1351. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1352. return L.latLngBounds(
  1353. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1354. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1355. },
  1356. clone: function () {
  1357. return new L.LatLng(this.lat, this.lng, this.alt);
  1358. }
  1359. };
  1360. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1361. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1362. // @alternative
  1363. // @factory L.latLng(coords: Array): LatLng
  1364. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1365. // @alternative
  1366. // @factory L.latLng(coords: Object): LatLng
  1367. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1368. L.latLng = function (a, b, c) {
  1369. if (a instanceof L.LatLng) {
  1370. return a;
  1371. }
  1372. if (L.Util.isArray(a) && typeof a[0] !== 'object') {
  1373. if (a.length === 3) {
  1374. return new L.LatLng(a[0], a[1], a[2]);
  1375. }
  1376. if (a.length === 2) {
  1377. return new L.LatLng(a[0], a[1]);
  1378. }
  1379. return null;
  1380. }
  1381. if (a === undefined || a === null) {
  1382. return a;
  1383. }
  1384. if (typeof a === 'object' && 'lat' in a) {
  1385. return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1386. }
  1387. if (b === undefined) {
  1388. return null;
  1389. }
  1390. return new L.LatLng(a, b, c);
  1391. };
  1392. /*
  1393. * @class LatLngBounds
  1394. * @aka L.LatLngBounds
  1395. *
  1396. * Represents a rectangular geographical area on a map.
  1397. *
  1398. * @example
  1399. *
  1400. * ```js
  1401. * var southWest = L.latLng(40.712, -74.227),
  1402. * northEast = L.latLng(40.774, -74.125),
  1403. * bounds = L.latLngBounds(southWest, northEast);
  1404. * ```
  1405. *
  1406. * 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:
  1407. *
  1408. * ```js
  1409. * map.fitBounds([
  1410. * [40.712, -74.227],
  1411. * [40.774, -74.125]
  1412. * ]);
  1413. * ```
  1414. */
  1415. L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
  1416. if (!southWest) { return; }
  1417. var latlngs = northEast ? [southWest, northEast] : southWest;
  1418. for (var i = 0, len = latlngs.length; i < len; i++) {
  1419. this.extend(latlngs[i]);
  1420. }
  1421. };
  1422. L.LatLngBounds.prototype = {
  1423. // @method extend(latlng: LatLng): this
  1424. // Extend the bounds to contain the given point
  1425. // @alternative
  1426. // @method extend(otherBounds: LatLngBounds): this
  1427. // Extend the bounds to contain the given bounds
  1428. extend: function (obj) {
  1429. var sw = this._southWest,
  1430. ne = this._northEast,
  1431. sw2, ne2;
  1432. if (obj instanceof L.LatLng) {
  1433. sw2 = obj;
  1434. ne2 = obj;
  1435. } else if (obj instanceof L.LatLngBounds) {
  1436. sw2 = obj._southWest;
  1437. ne2 = obj._northEast;
  1438. if (!sw2 || !ne2) { return this; }
  1439. } else {
  1440. return obj ? this.extend(L.latLng(obj) || L.latLngBounds(obj)) : this;
  1441. }
  1442. if (!sw && !ne) {
  1443. this._southWest = new L.LatLng(sw2.lat, sw2.lng);
  1444. this._northEast = new L.LatLng(ne2.lat, ne2.lng);
  1445. } else {
  1446. sw.lat = Math.min(sw2.lat, sw.lat);
  1447. sw.lng = Math.min(sw2.lng, sw.lng);
  1448. ne.lat = Math.max(ne2.lat, ne.lat);
  1449. ne.lng = Math.max(ne2.lng, ne.lng);
  1450. }
  1451. return this;
  1452. },
  1453. // @method pad(bufferRatio: Number): LatLngBounds
  1454. // Returns bigger bounds created by extending the current bounds by a given percentage in each direction.
  1455. pad: function (bufferRatio) {
  1456. var sw = this._southWest,
  1457. ne = this._northEast,
  1458. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  1459. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  1460. return new L.LatLngBounds(
  1461. new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  1462. new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  1463. },
  1464. // @method getCenter(): LatLng
  1465. // Returns the center point of the bounds.
  1466. getCenter: function () {
  1467. return new L.LatLng(
  1468. (this._southWest.lat + this._northEast.lat) / 2,
  1469. (this._southWest.lng + this._northEast.lng) / 2);
  1470. },
  1471. // @method getSouthWest(): LatLng
  1472. // Returns the south-west point of the bounds.
  1473. getSouthWest: function () {
  1474. return this._southWest;
  1475. },
  1476. // @method getNorthEast(): LatLng
  1477. // Returns the north-east point of the bounds.
  1478. getNorthEast: function () {
  1479. return this._northEast;
  1480. },
  1481. // @method getNorthWest(): LatLng
  1482. // Returns the north-west point of the bounds.
  1483. getNorthWest: function () {
  1484. return new L.LatLng(this.getNorth(), this.getWest());
  1485. },
  1486. // @method getSouthEast(): LatLng
  1487. // Returns the south-east point of the bounds.
  1488. getSouthEast: function () {
  1489. return new L.LatLng(this.getSouth(), this.getEast());
  1490. },
  1491. // @method getWest(): Number
  1492. // Returns the west longitude of the bounds
  1493. getWest: function () {
  1494. return this._southWest.lng;
  1495. },
  1496. // @method getSouth(): Number
  1497. // Returns the south latitude of the bounds
  1498. getSouth: function () {
  1499. return this._southWest.lat;
  1500. },
  1501. // @method getEast(): Number
  1502. // Returns the east longitude of the bounds
  1503. getEast: function () {
  1504. return this._northEast.lng;
  1505. },
  1506. // @method getNorth(): Number
  1507. // Returns the north latitude of the bounds
  1508. getNorth: function () {
  1509. return this._northEast.lat;
  1510. },
  1511. // @method contains(otherBounds: LatLngBounds): Boolean
  1512. // Returns `true` if the rectangle contains the given one.
  1513. // @alternative
  1514. // @method contains (latlng: LatLng): Boolean
  1515. // Returns `true` if the rectangle contains the given point.
  1516. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1517. if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
  1518. obj = L.latLng(obj);
  1519. } else {
  1520. obj = L.latLngBounds(obj);
  1521. }
  1522. var sw = this._southWest,
  1523. ne = this._northEast,
  1524. sw2, ne2;
  1525. if (obj instanceof L.LatLngBounds) {
  1526. sw2 = obj.getSouthWest();
  1527. ne2 = obj.getNorthEast();
  1528. } else {
  1529. sw2 = ne2 = obj;
  1530. }
  1531. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1532. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1533. },
  1534. // @method intersects(otherBounds: LatLngBounds): Boolean
  1535. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1536. intersects: function (bounds) {
  1537. bounds = L.latLngBounds(bounds);
  1538. var sw = this._southWest,
  1539. ne = this._northEast,
  1540. sw2 = bounds.getSouthWest(),
  1541. ne2 = bounds.getNorthEast(),
  1542. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1543. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1544. return latIntersects && lngIntersects;
  1545. },
  1546. // @method overlaps(otherBounds: Bounds): Boolean
  1547. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1548. overlaps: function (bounds) {
  1549. bounds = L.latLngBounds(bounds);
  1550. var sw = this._southWest,
  1551. ne = this._northEast,
  1552. sw2 = bounds.getSouthWest(),
  1553. ne2 = bounds.getNorthEast(),
  1554. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1555. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1556. return latOverlaps && lngOverlaps;
  1557. },
  1558. // @method toBBoxString(): String
  1559. // 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.
  1560. toBBoxString: function () {
  1561. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1562. },
  1563. // @method equals(otherBounds: LatLngBounds): Boolean
  1564. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds.
  1565. equals: function (bounds) {
  1566. if (!bounds) { return false; }
  1567. bounds = L.latLngBounds(bounds);
  1568. return this._southWest.equals(bounds.getSouthWest()) &&
  1569. this._northEast.equals(bounds.getNorthEast());
  1570. },
  1571. // @method isValid(): Boolean
  1572. // Returns `true` if the bounds are properly initialized.
  1573. isValid: function () {
  1574. return !!(this._southWest && this._northEast);
  1575. }
  1576. };
  1577. // TODO International date line?
  1578. // @factory L.latLngBounds(southWest: LatLng, northEast: LatLng)
  1579. // Creates a `LatLngBounds` object by defining south-west and north-east corners of the rectangle.
  1580. // @alternative
  1581. // @factory L.latLngBounds(latlngs: LatLng[])
  1582. // 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).
  1583. L.latLngBounds = function (a, b) {
  1584. if (a instanceof L.LatLngBounds) {
  1585. return a;
  1586. }
  1587. return new L.LatLngBounds(a, b);
  1588. };
  1589. /*
  1590. * @namespace Projection
  1591. * @section
  1592. * Leaflet comes with a set of already defined Projections out of the box:
  1593. *
  1594. * @projection L.Projection.LonLat
  1595. *
  1596. * Equirectangular, or Plate Carree projection — the most simple projection,
  1597. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  1598. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  1599. * `EPSG:3395` and `Simple` CRS.
  1600. */
  1601. L.Projection = {};
  1602. L.Projection.LonLat = {
  1603. project: function (latlng) {
  1604. return new L.Point(latlng.lng, latlng.lat);
  1605. },
  1606. unproject: function (point) {
  1607. return new L.LatLng(point.y, point.x);
  1608. },
  1609. bounds: L.bounds([-180, -90], [180, 90])
  1610. };
  1611. /*
  1612. * @namespace Projection
  1613. * @projection L.Projection.SphericalMercator
  1614. *
  1615. * Spherical Mercator projection — the most common projection for online maps,
  1616. * used by almost all free and commercial tile providers. Assumes that Earth is
  1617. * a sphere. Used by the `EPSG:3857` CRS.
  1618. */
  1619. L.Projection.SphericalMercator = {
  1620. R: 6378137,
  1621. MAX_LATITUDE: 85.0511287798,
  1622. project: function (latlng) {
  1623. var d = Math.PI / 180,
  1624. max = this.MAX_LATITUDE,
  1625. lat = Math.max(Math.min(max, latlng.lat), -max),
  1626. sin = Math.sin(lat * d);
  1627. return new L.Point(
  1628. this.R * latlng.lng * d,
  1629. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1630. },
  1631. unproject: function (point) {
  1632. var d = 180 / Math.PI;
  1633. return new L.LatLng(
  1634. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1635. point.x * d / this.R);
  1636. },
  1637. bounds: (function () {
  1638. var d = 6378137 * Math.PI;
  1639. return L.bounds([-d, -d], [d, d]);
  1640. })()
  1641. };
  1642. /*
  1643. * @class CRS
  1644. * @aka L.CRS
  1645. * Abstract class that defines coordinate reference systems for projecting
  1646. * geographical points into pixel (screen) coordinates and back (and to
  1647. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1648. * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
  1649. *
  1650. * Leaflet defines the most usual CRSs by default. If you want to use a
  1651. * CRS not defined by default, take a look at the
  1652. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1653. */
  1654. L.CRS = {
  1655. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1656. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1657. latLngToPoint: function (latlng, zoom) {
  1658. var projectedPoint = this.projection.project(latlng),
  1659. scale = this.scale(zoom);
  1660. return this.transformation._transform(projectedPoint, scale);
  1661. },
  1662. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1663. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1664. // zoom into geographical coordinates.
  1665. pointToLatLng: function (point, zoom) {
  1666. var scale = this.scale(zoom),
  1667. untransformedPoint = this.transformation.untransform(point, scale);
  1668. return this.projection.unproject(untransformedPoint);
  1669. },
  1670. // @method project(latlng: LatLng): Point
  1671. // Projects geographical coordinates into coordinates in units accepted for
  1672. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1673. project: function (latlng) {
  1674. return this.projection.project(latlng);
  1675. },
  1676. // @method unproject(point: Point): LatLng
  1677. // Given a projected coordinate returns the corresponding LatLng.
  1678. // The inverse of `project`.
  1679. unproject: function (point) {
  1680. return this.projection.unproject(point);
  1681. },
  1682. // @method scale(zoom: Number): Number
  1683. // Returns the scale used when transforming projected coordinates into
  1684. // pixel coordinates for a particular zoom. For example, it returns
  1685. // `256 * 2^zoom` for Mercator-based CRS.
  1686. scale: function (zoom) {
  1687. return 256 * Math.pow(2, zoom);
  1688. },
  1689. // @method zoom(scale: Number): Number
  1690. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1691. // factor of `scale`.
  1692. zoom: function (scale) {
  1693. return Math.log(scale / 256) / Math.LN2;
  1694. },
  1695. // @method getProjectedBounds(zoom: Number): Bounds
  1696. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1697. getProjectedBounds: function (zoom) {
  1698. if (this.infinite) { return null; }
  1699. var b = this.projection.bounds,
  1700. s = this.scale(zoom),
  1701. min = this.transformation.transform(b.min, s),
  1702. max = this.transformation.transform(b.max, s);
  1703. return L.bounds(min, max);
  1704. },
  1705. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1706. // Returns the distance between two geographical coordinates.
  1707. // @property code: String
  1708. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1709. //
  1710. // @property wrapLng: Number[]
  1711. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1712. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1713. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1714. //
  1715. // @property wrapLat: Number[]
  1716. // Like `wrapLng`, but for the latitude (vertical) axis.
  1717. // wrapLng: [min, max],
  1718. // wrapLat: [min, max],
  1719. // @property infinite: Boolean
  1720. // If true, the coordinate space will be unbounded (infinite in both axes)
  1721. infinite: false,
  1722. // @method wrapLatLng(latlng: LatLng): LatLng
  1723. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1724. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1725. wrapLatLng: function (latlng) {
  1726. var lng = this.wrapLng ? L.Util.wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1727. lat = this.wrapLat ? L.Util.wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1728. alt = latlng.alt;
  1729. return L.latLng(lat, lng, alt);
  1730. }
  1731. };
  1732. /*
  1733. * @namespace CRS
  1734. * @crs L.CRS.Simple
  1735. *
  1736. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  1737. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  1738. * axis should still be inverted (going from bottom to top). `distance()` returns
  1739. * simple euclidean distance.
  1740. */
  1741. L.CRS.Simple = L.extend({}, L.CRS, {
  1742. projection: L.Projection.LonLat,
  1743. transformation: new L.Transformation(1, 0, -1, 0),
  1744. scale: function (zoom) {
  1745. return Math.pow(2, zoom);
  1746. },
  1747. zoom: function (scale) {
  1748. return Math.log(scale) / Math.LN2;
  1749. },
  1750. distance: function (latlng1, latlng2) {
  1751. var dx = latlng2.lng - latlng1.lng,
  1752. dy = latlng2.lat - latlng1.lat;
  1753. return Math.sqrt(dx * dx + dy * dy);
  1754. },
  1755. infinite: true
  1756. });
  1757. /*
  1758. * @namespace CRS
  1759. * @crs L.CRS.Earth
  1760. *
  1761. * Serves as the base for CRS that are global such that they cover the earth.
  1762. * Can only be used as the base for other CRS and cannot be used directly,
  1763. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1764. * meters.
  1765. */
  1766. L.CRS.Earth = L.extend({}, L.CRS, {
  1767. wrapLng: [-180, 180],
  1768. // Mean Earth Radius, as recommended for use by
  1769. // the International Union of Geodesy and Geophysics,
  1770. // see http://rosettacode.org/wiki/Haversine_formula
  1771. R: 6371000,
  1772. // distance between two geographical points using spherical law of cosines approximation
  1773. distance: function (latlng1, latlng2) {
  1774. var rad = Math.PI / 180,
  1775. lat1 = latlng1.lat * rad,
  1776. lat2 = latlng2.lat * rad,
  1777. a = Math.sin(lat1) * Math.sin(lat2) +
  1778. Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad);
  1779. return this.R * Math.acos(Math.min(a, 1));
  1780. }
  1781. });
  1782. /*
  1783. * @namespace CRS
  1784. * @crs L.CRS.EPSG3857
  1785. *
  1786. * The most common CRS for online maps, used by almost all free and commercial
  1787. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1788. * Map's `crs` option.
  1789. */
  1790. L.CRS.EPSG3857 = L.extend({}, L.CRS.Earth, {
  1791. code: 'EPSG:3857',
  1792. projection: L.Projection.SphericalMercator,
  1793. transformation: (function () {
  1794. var scale = 0.5 / (Math.PI * L.Projection.SphericalMercator.R);
  1795. return new L.Transformation(scale, 0.5, -scale, 0.5);
  1796. }())
  1797. });
  1798. L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
  1799. code: 'EPSG:900913'
  1800. });
  1801. /*
  1802. * @namespace CRS
  1803. * @crs L.CRS.EPSG4326
  1804. *
  1805. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  1806. */
  1807. L.CRS.EPSG4326 = L.extend({}, L.CRS.Earth, {
  1808. code: 'EPSG:4326',
  1809. projection: L.Projection.LonLat,
  1810. transformation: new L.Transformation(1 / 180, 1, -1 / 180, 0.5)
  1811. });
  1812. /*
  1813. * @class Map
  1814. * @aka L.Map
  1815. * @inherits Evented
  1816. *
  1817. * The central class of the API — it is used to create a map on a page and manipulate it.
  1818. *
  1819. * @example
  1820. *
  1821. * ```js
  1822. * // initialize the map on the "map" div with a given center and zoom
  1823. * var map = L.map('map', {
  1824. * center: [51.505, -0.09],
  1825. * zoom: 13
  1826. * });
  1827. * ```
  1828. *
  1829. */
  1830. L.Map = L.Evented.extend({
  1831. options: {
  1832. // @section Map State Options
  1833. // @option crs: CRS = L.CRS.EPSG3857
  1834. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  1835. // sure what it means.
  1836. crs: L.CRS.EPSG3857,
  1837. // @option center: LatLng = undefined
  1838. // Initial geographic center of the map
  1839. center: undefined,
  1840. // @option zoom: Number = undefined
  1841. // Initial map zoom level
  1842. zoom: undefined,
  1843. // @option minZoom: Number = undefined
  1844. // Minimum zoom level of the map. Overrides any `minZoom` option set on map layers.
  1845. minZoom: undefined,
  1846. // @option maxZoom: Number = undefined
  1847. // Maximum zoom level of the map. Overrides any `maxZoom` option set on map layers.
  1848. maxZoom: undefined,
  1849. // @option layers: Layer[] = []
  1850. // Array of layers that will be added to the map initially
  1851. layers: [],
  1852. // @option maxBounds: LatLngBounds = null
  1853. // When this option is set, the map restricts the view to the given
  1854. // geographical bounds, bouncing the user back when he tries to pan
  1855. // outside the view. To set the restriction dynamically, use
  1856. // [`setMaxBounds`](#map-setmaxbounds) method.
  1857. maxBounds: undefined,
  1858. // @option renderer: Renderer = *
  1859. // The default method for drawing vector layers on the map. `L.SVG`
  1860. // or `L.Canvas` by default depending on browser support.
  1861. renderer: undefined,
  1862. // @section Animation Options
  1863. // @option fadeAnimation: Boolean = true
  1864. // Whether the tile fade animation is enabled. By default it's enabled
  1865. // in all browsers that support CSS3 Transitions except Android.
  1866. fadeAnimation: true,
  1867. // @option markerZoomAnimation: Boolean = true
  1868. // Whether markers animate their zoom with the zoom animation, if disabled
  1869. // they will disappear for the length of the animation. By default it's
  1870. // enabled in all browsers that support CSS3 Transitions except Android.
  1871. markerZoomAnimation: true,
  1872. // @option transform3DLimit: Number = 2^23
  1873. // Defines the maximum size of a CSS translation transform. The default
  1874. // value should not be changed unless a web browser positions layers in
  1875. // the wrong place after doing a large `panBy`.
  1876. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  1877. // @section Interaction Options
  1878. // @option zoomSnap: Number = 1
  1879. // Forces the map's zoom level to always be a multiple of this, particularly
  1880. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  1881. // By default, the zoom level snaps to the nearest integer; lower values
  1882. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  1883. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  1884. zoomSnap: 1,
  1885. // @option zoomDelta: Number = 1
  1886. // Controls how much the map's zoom level will change after a
  1887. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  1888. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  1889. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  1890. zoomDelta: 1,
  1891. // @option trackResize: Boolean = true
  1892. // Whether the map automatically handles browser window resize to update itself.
  1893. trackResize: true
  1894. },
  1895. initialize: function (id, options) { // (HTMLElement or String, Object)
  1896. options = L.setOptions(this, options);
  1897. this._initContainer(id);
  1898. this._initLayout();
  1899. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  1900. this._onResize = L.bind(this._onResize, this);
  1901. this._initEvents();
  1902. if (options.maxBounds) {
  1903. this.setMaxBounds(options.maxBounds);
  1904. }
  1905. if (options.zoom !== undefined) {
  1906. this._zoom = this._limitZoom(options.zoom);
  1907. }
  1908. if (options.center && options.zoom !== undefined) {
  1909. this.setView(L.latLng(options.center), options.zoom, {reset: true});
  1910. }
  1911. this._handlers = [];
  1912. this._layers = {};
  1913. this._zoomBoundLayers = {};
  1914. this._sizeChanged = true;
  1915. this.callInitHooks();
  1916. this._addLayers(this.options.layers);
  1917. },
  1918. // @section Methods for modifying map state
  1919. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  1920. // Sets the view of the map (geographical center and zoom) with the given
  1921. // animation options.
  1922. setView: function (center, zoom) {
  1923. // replaced by animation-powered implementation in Map.PanAnimation.js
  1924. zoom = zoom === undefined ? this.getZoom() : zoom;
  1925. this._resetView(L.latLng(center), zoom);
  1926. return this;
  1927. },
  1928. // @method setZoom(zoom: Number, options: Zoom/pan options): this
  1929. // Sets the zoom of the map.
  1930. setZoom: function (zoom, options) {
  1931. if (!this._loaded) {
  1932. this._zoom = zoom;
  1933. return this;
  1934. }
  1935. return this.setView(this.getCenter(), zoom, {zoom: options});
  1936. },
  1937. // @method zoomIn(delta?: Number, options?: Zoom options): this
  1938. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  1939. zoomIn: function (delta, options) {
  1940. delta = delta || (L.Browser.any3d ? this.options.zoomDelta : 1);
  1941. return this.setZoom(this._zoom + delta, options);
  1942. },
  1943. // @method zoomOut(delta?: Number, options?: Zoom options): this
  1944. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  1945. zoomOut: function (delta, options) {
  1946. delta = delta || (L.Browser.any3d ? this.options.zoomDelta : 1);
  1947. return this.setZoom(this._zoom - delta, options);
  1948. },
  1949. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  1950. // Zooms the map while keeping a specified geographical point on the map
  1951. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  1952. // @alternative
  1953. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  1954. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  1955. setZoomAround: function (latlng, zoom, options) {
  1956. var scale = this.getZoomScale(zoom),
  1957. viewHalf = this.getSize().divideBy(2),
  1958. containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
  1959. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  1960. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  1961. return this.setView(newCenter, zoom, {zoom: options});
  1962. },
  1963. _getBoundsCenterZoom: function (bounds, options) {
  1964. options = options || {};
  1965. bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
  1966. var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
  1967. paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
  1968. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  1969. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  1970. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  1971. swPoint = this.project(bounds.getSouthWest(), zoom),
  1972. nePoint = this.project(bounds.getNorthEast(), zoom),
  1973. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  1974. return {
  1975. center: center,
  1976. zoom: zoom
  1977. };
  1978. },
  1979. // @method fitBounds(bounds: LatLngBounds, options: fitBounds options): this
  1980. // Sets a map view that contains the given geographical bounds with the
  1981. // maximum zoom level possible.
  1982. fitBounds: function (bounds, options) {
  1983. bounds = L.latLngBounds(bounds);
  1984. if (!bounds.isValid()) {
  1985. throw new Error('Bounds are not valid.');
  1986. }
  1987. var target = this._getBoundsCenterZoom(bounds, options);
  1988. return this.setView(target.center, target.zoom, options);
  1989. },
  1990. // @method fitWorld(options?: fitBounds options): this
  1991. // Sets a map view that mostly contains the whole world with the maximum
  1992. // zoom level possible.
  1993. fitWorld: function (options) {
  1994. return this.fitBounds([[-90, -180], [90, 180]], options);
  1995. },
  1996. // @method panTo(latlng: LatLng, options?: Pan options): this
  1997. // Pans the map to a given center.
  1998. panTo: function (center, options) { // (LatLng)
  1999. return this.setView(center, this._zoom, {pan: options});
  2000. },
  2001. // @method panBy(offset: Point): this
  2002. // Pans the map by a given number of pixels (animated).
  2003. panBy: function (offset) { // (Point)
  2004. // replaced with animated panBy in Map.PanAnimation.js
  2005. this.fire('movestart');
  2006. this._rawPanBy(L.point(offset));
  2007. this.fire('move');
  2008. return this.fire('moveend');
  2009. },
  2010. // @method setMaxBounds(bounds: Bounds): this
  2011. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2012. setMaxBounds: function (bounds) {
  2013. bounds = L.latLngBounds(bounds);
  2014. if (!bounds.isValid()) {
  2015. this.options.maxBounds = null;
  2016. return this.off('moveend', this._panInsideMaxBounds);
  2017. } else if (this.options.maxBounds) {
  2018. this.off('moveend', this._panInsideMaxBounds);
  2019. }
  2020. this.options.maxBounds = bounds;
  2021. if (this._loaded) {
  2022. this._panInsideMaxBounds();
  2023. }
  2024. return this.on('moveend', this._panInsideMaxBounds);
  2025. },
  2026. // @method setMinZoom(zoom: Number): this
  2027. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2028. setMinZoom: function (zoom) {
  2029. this.options.minZoom = zoom;
  2030. if (this._loaded && this.getZoom() < this.options.minZoom) {
  2031. return this.setZoom(zoom);
  2032. }
  2033. return this;
  2034. },
  2035. // @method setMaxZoom(zoom: Number): this
  2036. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2037. setMaxZoom: function (zoom) {
  2038. this.options.maxZoom = zoom;
  2039. if (this._loaded && (this.getZoom() > this.options.maxZoom)) {
  2040. return this.setZoom(zoom);
  2041. }
  2042. return this;
  2043. },
  2044. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2045. // 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.
  2046. panInsideBounds: function (bounds, options) {
  2047. this._enforcingBounds = true;
  2048. var center = this.getCenter(),
  2049. newCenter = this._limitCenter(center, this._zoom, L.latLngBounds(bounds));
  2050. if (!center.equals(newCenter)) {
  2051. this.panTo(newCenter, options);
  2052. }
  2053. this._enforcingBounds = false;
  2054. return this;
  2055. },
  2056. // @method invalidateSize(options: Zoom/Pan options): this
  2057. // Checks if the map container size changed and updates the map if so —
  2058. // call it after you've changed the map size dynamically, also animating
  2059. // pan by default. If `options.pan` is `false`, panning will not occur.
  2060. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2061. // that it doesn't happen often even if the method is called many
  2062. // times in a row.
  2063. // @alternative
  2064. // @method invalidateSize(animate: Boolean): this
  2065. // Checks if the map container size changed and updates the map if so —
  2066. // call it after you've changed the map size dynamically, also animating
  2067. // pan by default.
  2068. invalidateSize: function (options) {
  2069. if (!this._loaded) { return this; }
  2070. options = L.extend({
  2071. animate: false,
  2072. pan: true
  2073. }, options === true ? {animate: true} : options);
  2074. var oldSize = this.getSize();
  2075. this._sizeChanged = true;
  2076. this._lastCenter = null;
  2077. var newSize = this.getSize(),
  2078. oldCenter = oldSize.divideBy(2).round(),
  2079. newCenter = newSize.divideBy(2).round(),
  2080. offset = oldCenter.subtract(newCenter);
  2081. if (!offset.x && !offset.y) { return this; }
  2082. if (options.animate && options.pan) {
  2083. this.panBy(offset);
  2084. } else {
  2085. if (options.pan) {
  2086. this._rawPanBy(offset);
  2087. }
  2088. this.fire('move');
  2089. if (options.debounceMoveend) {
  2090. clearTimeout(this._sizeTimer);
  2091. this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
  2092. } else {
  2093. this.fire('moveend');
  2094. }
  2095. }
  2096. // @section Map state change events
  2097. // @event resize: ResizeEvent
  2098. // Fired when the map is resized.
  2099. return this.fire('resize', {
  2100. oldSize: oldSize,
  2101. newSize: newSize
  2102. });
  2103. },
  2104. // @section Methods for modifying map state
  2105. // @method stop(): this
  2106. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2107. stop: function () {
  2108. this.setZoom(this._limitZoom(this._zoom));
  2109. if (!this.options.zoomSnap) {
  2110. this.fire('viewreset');
  2111. }
  2112. return this._stop();
  2113. },
  2114. // TODO handler.addTo
  2115. // TODO Appropiate docs section?
  2116. // @section Other Methods
  2117. // @method addHandler(name: String, HandlerClass: Function): this
  2118. // Adds a new `Handler` to the map, given its name and constructor function.
  2119. addHandler: function (name, HandlerClass) {
  2120. if (!HandlerClass) { return this; }
  2121. var handler = this[name] = new HandlerClass(this);
  2122. this._handlers.push(handler);
  2123. if (this.options[name]) {
  2124. handler.enable();
  2125. }
  2126. return this;
  2127. },
  2128. // @method remove(): this
  2129. // Destroys the map and clears all related event listeners.
  2130. remove: function () {
  2131. this._initEvents(true);
  2132. if (this._containerId !== this._container._leaflet_id) {
  2133. throw new Error('Map container is being reused by another instance');
  2134. }
  2135. try {
  2136. // throws error in IE6-8
  2137. delete this._container._leaflet_id;
  2138. delete this._containerId;
  2139. } catch (e) {
  2140. /*eslint-disable */
  2141. this._container._leaflet_id = undefined;
  2142. /*eslint-enable */
  2143. this._containerId = undefined;
  2144. }
  2145. L.DomUtil.remove(this._mapPane);
  2146. if (this._clearControlPos) {
  2147. this._clearControlPos();
  2148. }
  2149. this._clearHandlers();
  2150. if (this._loaded) {
  2151. // @section Map state change events
  2152. // @event unload: Event
  2153. // Fired when the map is destroyed with [remove](#map-remove) method.
  2154. this.fire('unload');
  2155. }
  2156. for (var i in this._layers) {
  2157. this._layers[i].remove();
  2158. }
  2159. return this;
  2160. },
  2161. // @section Other Methods
  2162. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  2163. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  2164. // then returns it. The pane is created as a children of `container`, or
  2165. // as a children of the main map pane if not set.
  2166. createPane: function (name, container) {
  2167. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  2168. pane = L.DomUtil.create('div', className, container || this._mapPane);
  2169. if (name) {
  2170. this._panes[name] = pane;
  2171. }
  2172. return pane;
  2173. },
  2174. // @section Methods for Getting Map State
  2175. // @method getCenter(): LatLng
  2176. // Returns the geographical center of the map view
  2177. getCenter: function () {
  2178. this._checkIfLoaded();
  2179. if (this._lastCenter && !this._moved()) {
  2180. return this._lastCenter;
  2181. }
  2182. return this.layerPointToLatLng(this._getCenterLayerPoint());
  2183. },
  2184. // @method getZoom(): Number
  2185. // Returns the current zoom level of the map view
  2186. getZoom: function () {
  2187. return this._zoom;
  2188. },
  2189. // @method getBounds(): LatLngBounds
  2190. // Returns the geographical bounds visible in the current map view
  2191. getBounds: function () {
  2192. var bounds = this.getPixelBounds(),
  2193. sw = this.unproject(bounds.getBottomLeft()),
  2194. ne = this.unproject(bounds.getTopRight());
  2195. return new L.LatLngBounds(sw, ne);
  2196. },
  2197. // @method getMinZoom(): Number
  2198. // 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.
  2199. getMinZoom: function () {
  2200. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  2201. },
  2202. // @method getMaxZoom(): Number
  2203. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  2204. getMaxZoom: function () {
  2205. return this.options.maxZoom === undefined ?
  2206. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  2207. this.options.maxZoom;
  2208. },
  2209. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean): Number
  2210. // Returns the maximum zoom level on which the given bounds fit to the map
  2211. // view in its entirety. If `inside` (optional) is set to `true`, the method
  2212. // instead returns the minimum zoom level on which the map view fits into
  2213. // the given bounds in its entirety.
  2214. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  2215. bounds = L.latLngBounds(bounds);
  2216. padding = L.point(padding || [0, 0]);
  2217. var zoom = this.getZoom() || 0,
  2218. min = this.getMinZoom(),
  2219. max = this.getMaxZoom(),
  2220. nw = bounds.getNorthWest(),
  2221. se = bounds.getSouthEast(),
  2222. size = this.getSize().subtract(padding),
  2223. boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)),
  2224. snap = L.Browser.any3d ? this.options.zoomSnap : 1;
  2225. var scale = Math.min(size.x / boundsSize.x, size.y / boundsSize.y);
  2226. zoom = this.getScaleZoom(scale, zoom);
  2227. if (snap) {
  2228. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  2229. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  2230. }
  2231. return Math.max(min, Math.min(max, zoom));
  2232. },
  2233. // @method getSize(): Point
  2234. // Returns the current size of the map container (in pixels).
  2235. getSize: function () {
  2236. if (!this._size || this._sizeChanged) {
  2237. this._size = new L.Point(
  2238. this._container.clientWidth,
  2239. this._container.clientHeight);
  2240. this._sizeChanged = false;
  2241. }
  2242. return this._size.clone();
  2243. },
  2244. // @method getPixelBounds(): Bounds
  2245. // Returns the bounds of the current map view in projected pixel
  2246. // coordinates (sometimes useful in layer and overlay implementations).
  2247. getPixelBounds: function (center, zoom) {
  2248. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  2249. return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  2250. },
  2251. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  2252. // the map pane? "left point of the map layer" can be confusing, specially
  2253. // since there can be negative offsets.
  2254. // @method getPixelOrigin(): Point
  2255. // Returns the projected pixel coordinates of the top left point of
  2256. // the map layer (useful in custom layer and overlay implementations).
  2257. getPixelOrigin: function () {
  2258. this._checkIfLoaded();
  2259. return this._pixelOrigin;
  2260. },
  2261. // @method getPixelWorldBounds(zoom?: Number): Bounds
  2262. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  2263. // If `zoom` is omitted, the map's current zoom level is used.
  2264. getPixelWorldBounds: function (zoom) {
  2265. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  2266. },
  2267. // @section Other Methods
  2268. // @method getPane(pane: String|HTMLElement): HTMLElement
  2269. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  2270. getPane: function (pane) {
  2271. return typeof pane === 'string' ? this._panes[pane] : pane;
  2272. },
  2273. // @method getPanes(): Object
  2274. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  2275. // the panes as values.
  2276. getPanes: function () {
  2277. return this._panes;
  2278. },
  2279. // @method getContainer: HTMLElement
  2280. // Returns the HTML element that contains the map.
  2281. getContainer: function () {
  2282. return this._container;
  2283. },
  2284. // @section Conversion Methods
  2285. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  2286. // Returns the scale factor to be applied to a map transition from zoom level
  2287. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  2288. getZoomScale: function (toZoom, fromZoom) {
  2289. // TODO replace with universal implementation after refactoring projections
  2290. var crs = this.options.crs;
  2291. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  2292. return crs.scale(toZoom) / crs.scale(fromZoom);
  2293. },
  2294. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  2295. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  2296. // level and everything is scaled by a factor of `scale`. Inverse of
  2297. // [`getZoomScale`](#map-getZoomScale).
  2298. getScaleZoom: function (scale, fromZoom) {
  2299. var crs = this.options.crs;
  2300. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  2301. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  2302. return isNaN(zoom) ? Infinity : zoom;
  2303. },
  2304. // @method project(latlng: LatLng, zoom: Number): Point
  2305. // Projects a geographical coordinate `LatLng` according to the projection
  2306. // of the map's CRS, then scales it according to `zoom` and the CRS's
  2307. // `Transformation`. The result is pixel coordinate relative to
  2308. // the CRS origin.
  2309. project: function (latlng, zoom) {
  2310. zoom = zoom === undefined ? this._zoom : zoom;
  2311. return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
  2312. },
  2313. // @method unproject(point: Point, zoom: Number): LatLng
  2314. // Inverse of [`project`](#map-project).
  2315. unproject: function (point, zoom) {
  2316. zoom = zoom === undefined ? this._zoom : zoom;
  2317. return this.options.crs.pointToLatLng(L.point(point), zoom);
  2318. },
  2319. // @method layerPointToLatLng(point: Point): LatLng
  2320. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  2321. // returns the corresponding geographical coordinate (for the current zoom level).
  2322. layerPointToLatLng: function (point) {
  2323. var projectedPoint = L.point(point).add(this.getPixelOrigin());
  2324. return this.unproject(projectedPoint);
  2325. },
  2326. // @method latLngToLayerPoint(latlng: LatLng): Point
  2327. // Given a geographical coordinate, returns the corresponding pixel coordinate
  2328. // relative to the [origin pixel](#map-getpixelorigin).
  2329. latLngToLayerPoint: function (latlng) {
  2330. var projectedPoint = this.project(L.latLng(latlng))._round();
  2331. return projectedPoint._subtract(this.getPixelOrigin());
  2332. },
  2333. // @method wrapLatLng(latlng: LatLng): LatLng
  2334. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  2335. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  2336. // CRS's bounds.
  2337. // By default this means longitude is wrapped around the dateline so its
  2338. // value is between -180 and +180 degrees.
  2339. wrapLatLng: function (latlng) {
  2340. return this.options.crs.wrapLatLng(L.latLng(latlng));
  2341. },
  2342. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  2343. // Returns the distance between two geographical coordinates according to
  2344. // the map's CRS. By default this measures distance in meters.
  2345. distance: function (latlng1, latlng2) {
  2346. return this.options.crs.distance(L.latLng(latlng1), L.latLng(latlng2));
  2347. },
  2348. // @method containerPointToLayerPoint(point: Point): Point
  2349. // Given a pixel coordinate relative to the map container, returns the corresponding
  2350. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  2351. containerPointToLayerPoint: function (point) { // (Point)
  2352. return L.point(point).subtract(this._getMapPanePos());
  2353. },
  2354. // @method layerPointToContainerPoint(point: Point): Point
  2355. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  2356. // returns the corresponding pixel coordinate relative to the map container.
  2357. layerPointToContainerPoint: function (point) { // (Point)
  2358. return L.point(point).add(this._getMapPanePos());
  2359. },
  2360. // @method containerPointToLatLng(point: Point): Point
  2361. // Given a pixel coordinate relative to the map container, returns
  2362. // the corresponding geographical coordinate (for the current zoom level).
  2363. containerPointToLatLng: function (point) {
  2364. var layerPoint = this.containerPointToLayerPoint(L.point(point));
  2365. return this.layerPointToLatLng(layerPoint);
  2366. },
  2367. // @method latLngToContainerPoint(latlng: LatLng): Point
  2368. // Given a geographical coordinate, returns the corresponding pixel coordinate
  2369. // relative to the map container.
  2370. latLngToContainerPoint: function (latlng) {
  2371. return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
  2372. },
  2373. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  2374. // Given a MouseEvent object, returns the pixel coordinate relative to the
  2375. // map container where the event took place.
  2376. mouseEventToContainerPoint: function (e) {
  2377. return L.DomEvent.getMousePosition(e, this._container);
  2378. },
  2379. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  2380. // Given a MouseEvent object, returns the pixel coordinate relative to
  2381. // the [origin pixel](#map-getpixelorigin) where the event took place.
  2382. mouseEventToLayerPoint: function (e) {
  2383. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  2384. },
  2385. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  2386. // Given a MouseEvent object, returns geographical coordinate where the
  2387. // event took place.
  2388. mouseEventToLatLng: function (e) { // (MouseEvent)
  2389. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  2390. },
  2391. // map initialization methods
  2392. _initContainer: function (id) {
  2393. var container = this._container = L.DomUtil.get(id);
  2394. if (!container) {
  2395. throw new Error('Map container not found.');
  2396. } else if (container._leaflet_id) {
  2397. throw new Error('Map container is already initialized.');
  2398. }
  2399. L.DomEvent.addListener(container, 'scroll', this._onScroll, this);
  2400. this._containerId = L.Util.stamp(container);
  2401. },
  2402. _initLayout: function () {
  2403. var container = this._container;
  2404. this._fadeAnimated = this.options.fadeAnimation && L.Browser.any3d;
  2405. L.DomUtil.addClass(container, 'leaflet-container' +
  2406. (L.Browser.touch ? ' leaflet-touch' : '') +
  2407. (L.Browser.retina ? ' leaflet-retina' : '') +
  2408. (L.Browser.ielt9 ? ' leaflet-oldie' : '') +
  2409. (L.Browser.safari ? ' leaflet-safari' : '') +
  2410. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  2411. var position = L.DomUtil.getStyle(container, 'position');
  2412. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  2413. container.style.position = 'relative';
  2414. }
  2415. this._initPanes();
  2416. if (this._initControlPos) {
  2417. this._initControlPos();
  2418. }
  2419. },
  2420. _initPanes: function () {
  2421. var panes = this._panes = {};
  2422. this._paneRenderers = {};
  2423. // @section
  2424. //
  2425. // Panes are DOM elements used to control the ordering of layers on the map. You
  2426. // can access panes with [`map.getPane`](#map-getpane) or
  2427. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  2428. // [`map.createPane`](#map-createpane) method.
  2429. //
  2430. // Every map has the following default panes that differ only in zIndex.
  2431. //
  2432. // @pane mapPane: HTMLElement = 'auto'
  2433. // Pane that contains all other map panes
  2434. this._mapPane = this.createPane('mapPane', this._container);
  2435. L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
  2436. // @pane tilePane: HTMLElement = 200
  2437. // Pane for `GridLayer`s and `TileLayer`s
  2438. this.createPane('tilePane');
  2439. // @pane overlayPane: HTMLElement = 400
  2440. // Pane for vector overlays (`Path`s), like `Polyline`s and `Polygon`s
  2441. this.createPane('shadowPane');
  2442. // @pane shadowPane: HTMLElement = 500
  2443. // Pane for overlay shadows (e.g. `Marker` shadows)
  2444. this.createPane('overlayPane');
  2445. // @pane markerPane: HTMLElement = 600
  2446. // Pane for `Icon`s of `Marker`s
  2447. this.createPane('markerPane');
  2448. // @pane tooltipPane: HTMLElement = 650
  2449. // Pane for tooltip.
  2450. this.createPane('tooltipPane');
  2451. // @pane popupPane: HTMLElement = 700
  2452. // Pane for `Popup`s.
  2453. this.createPane('popupPane');
  2454. if (!this.options.markerZoomAnimation) {
  2455. L.DomUtil.addClass(panes.markerPane, 'leaflet-zoom-hide');
  2456. L.DomUtil.addClass(panes.shadowPane, 'leaflet-zoom-hide');
  2457. }
  2458. },
  2459. // private methods that modify map state
  2460. // @section Map state change events
  2461. _resetView: function (center, zoom) {
  2462. L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
  2463. var loading = !this._loaded;
  2464. this._loaded = true;
  2465. zoom = this._limitZoom(zoom);
  2466. this.fire('viewprereset');
  2467. var zoomChanged = this._zoom !== zoom;
  2468. this
  2469. ._moveStart(zoomChanged)
  2470. ._move(center, zoom)
  2471. ._moveEnd(zoomChanged);
  2472. // @event viewreset: Event
  2473. // Fired when the map needs to redraw its content (this usually happens
  2474. // on map zoom or load). Very useful for creating custom overlays.
  2475. this.fire('viewreset');
  2476. // @event load: Event
  2477. // Fired when the map is initialized (when its center and zoom are set
  2478. // for the first time).
  2479. if (loading) {
  2480. this.fire('load');
  2481. }
  2482. },
  2483. _moveStart: function (zoomChanged) {
  2484. // @event zoomstart: Event
  2485. // Fired when the map zoom is about to change (e.g. before zoom animation).
  2486. // @event movestart: Event
  2487. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  2488. if (zoomChanged) {
  2489. this.fire('zoomstart');
  2490. }
  2491. return this.fire('movestart');
  2492. },
  2493. _move: function (center, zoom, data) {
  2494. if (zoom === undefined) {
  2495. zoom = this._zoom;
  2496. }
  2497. var zoomChanged = this._zoom !== zoom;
  2498. this._zoom = zoom;
  2499. this._lastCenter = center;
  2500. this._pixelOrigin = this._getNewPixelOrigin(center);
  2501. // @event zoom: Event
  2502. // Fired repeatedly during any change in zoom level, including zoom
  2503. // and fly animations.
  2504. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  2505. this.fire('zoom', data);
  2506. }
  2507. // @event move: Event
  2508. // Fired repeatedly during any movement of the map, including pan and
  2509. // fly animations.
  2510. return this.fire('move', data);
  2511. },
  2512. _moveEnd: function (zoomChanged) {
  2513. // @event zoomend: Event
  2514. // Fired when the map has changed, after any animations.
  2515. if (zoomChanged) {
  2516. this.fire('zoomend');
  2517. }
  2518. // @event moveend: Event
  2519. // Fired when the center of the map stops changing (e.g. user stopped
  2520. // dragging the map).
  2521. return this.fire('moveend');
  2522. },
  2523. _stop: function () {
  2524. L.Util.cancelAnimFrame(this._flyToFrame);
  2525. if (this._panAnim) {
  2526. this._panAnim.stop();
  2527. }
  2528. return this;
  2529. },
  2530. _rawPanBy: function (offset) {
  2531. L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  2532. },
  2533. _getZoomSpan: function () {
  2534. return this.getMaxZoom() - this.getMinZoom();
  2535. },
  2536. _panInsideMaxBounds: function () {
  2537. if (!this._enforcingBounds) {
  2538. this.panInsideBounds(this.options.maxBounds);
  2539. }
  2540. },
  2541. _checkIfLoaded: function () {
  2542. if (!this._loaded) {
  2543. throw new Error('Set map center and zoom first.');
  2544. }
  2545. },
  2546. // DOM event handling
  2547. // @section Interaction events
  2548. _initEvents: function (remove) {
  2549. if (!L.DomEvent) { return; }
  2550. this._targets = {};
  2551. this._targets[L.stamp(this._container)] = this;
  2552. var onOff = remove ? 'off' : 'on';
  2553. // @event click: MouseEvent
  2554. // Fired when the user clicks (or taps) the map.
  2555. // @event dblclick: MouseEvent
  2556. // Fired when the user double-clicks (or double-taps) the map.
  2557. // @event mousedown: MouseEvent
  2558. // Fired when the user pushes the mouse button on the map.
  2559. // @event mouseup: MouseEvent
  2560. // Fired when the user releases the mouse button on the map.
  2561. // @event mouseover: MouseEvent
  2562. // Fired when the mouse enters the map.
  2563. // @event mouseout: MouseEvent
  2564. // Fired when the mouse leaves the map.
  2565. // @event mousemove: MouseEvent
  2566. // Fired while the mouse moves over the map.
  2567. // @event contextmenu: MouseEvent
  2568. // Fired when the user pushes the right mouse button on the map, prevents
  2569. // default browser context menu from showing if there are listeners on
  2570. // this event. Also fired on mobile when the user holds a single touch
  2571. // for a second (also called long press).
  2572. // @event keypress: KeyboardEvent
  2573. // Fired when the user presses a key from the keyboard while the map is focused.
  2574. L.DomEvent[onOff](this._container, 'click dblclick mousedown mouseup ' +
  2575. 'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this);
  2576. if (this.options.trackResize) {
  2577. L.DomEvent[onOff](window, 'resize', this._onResize, this);
  2578. }
  2579. if (L.Browser.any3d && this.options.transform3DLimit) {
  2580. this[onOff]('moveend', this._onMoveEnd);
  2581. }
  2582. },
  2583. _onResize: function () {
  2584. L.Util.cancelAnimFrame(this._resizeRequest);
  2585. this._resizeRequest = L.Util.requestAnimFrame(
  2586. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  2587. },
  2588. _onScroll: function () {
  2589. this._container.scrollTop = 0;
  2590. this._container.scrollLeft = 0;
  2591. },
  2592. _onMoveEnd: function () {
  2593. var pos = this._getMapPanePos();
  2594. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  2595. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  2596. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  2597. this._resetView(this.getCenter(), this.getZoom());
  2598. }
  2599. },
  2600. _findEventTargets: function (e, type) {
  2601. var targets = [],
  2602. target,
  2603. isHover = type === 'mouseout' || type === 'mouseover',
  2604. src = e.target || e.srcElement,
  2605. dragging = false;
  2606. while (src) {
  2607. target = this._targets[L.stamp(src)];
  2608. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  2609. // Prevent firing click after you just dragged an object.
  2610. dragging = true;
  2611. break;
  2612. }
  2613. if (target && target.listens(type, true)) {
  2614. if (isHover && !L.DomEvent._isExternalTarget(src, e)) { break; }
  2615. targets.push(target);
  2616. if (isHover) { break; }
  2617. }
  2618. if (src === this._container) { break; }
  2619. src = src.parentNode;
  2620. }
  2621. if (!targets.length && !dragging && !isHover && L.DomEvent._isExternalTarget(src, e)) {
  2622. targets = [this];
  2623. }
  2624. return targets;
  2625. },
  2626. _handleDOMEvent: function (e) {
  2627. if (!this._loaded || L.DomEvent._skipped(e)) { return; }
  2628. var type = e.type === 'keypress' && e.keyCode === 13 ? 'click' : e.type;
  2629. if (type === 'mousedown') {
  2630. // prevents outline when clicking on keyboard-focusable element
  2631. L.DomUtil.preventOutline(e.target || e.srcElement);
  2632. }
  2633. this._fireDOMEvent(e, type);
  2634. },
  2635. _fireDOMEvent: function (e, type, targets) {
  2636. if (e.type === 'click') {
  2637. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  2638. // @event preclick: MouseEvent
  2639. // Fired before mouse click on the map (sometimes useful when you
  2640. // want something to happen on click before any existing click
  2641. // handlers start running).
  2642. var synth = L.Util.extend({}, e);
  2643. synth.type = 'preclick';
  2644. this._fireDOMEvent(synth, synth.type, targets);
  2645. }
  2646. if (e._stopped) { return; }
  2647. // Find the layer the event is propagating from and its parents.
  2648. targets = (targets || []).concat(this._findEventTargets(e, type));
  2649. if (!targets.length) { return; }
  2650. var target = targets[0];
  2651. if (type === 'contextmenu' && target.listens(type, true)) {
  2652. L.DomEvent.preventDefault(e);
  2653. }
  2654. var data = {
  2655. originalEvent: e
  2656. };
  2657. if (e.type !== 'keypress') {
  2658. var isMarker = target instanceof L.Marker;
  2659. data.containerPoint = isMarker ?
  2660. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  2661. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  2662. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  2663. }
  2664. for (var i = 0; i < targets.length; i++) {
  2665. targets[i].fire(type, data, true);
  2666. if (data.originalEvent._stopped ||
  2667. (targets[i].options.nonBubblingEvents && L.Util.indexOf(targets[i].options.nonBubblingEvents, type) !== -1)) { return; }
  2668. }
  2669. },
  2670. _draggableMoved: function (obj) {
  2671. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  2672. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  2673. },
  2674. _clearHandlers: function () {
  2675. for (var i = 0, len = this._handlers.length; i < len; i++) {
  2676. this._handlers[i].disable();
  2677. }
  2678. },
  2679. // @section Other Methods
  2680. // @method whenReady(fn: Function, context?: Object): this
  2681. // Runs the given function `fn` when the map gets initialized with
  2682. // a view (center and zoom) and at least one layer, or immediately
  2683. // if it's already initialized, optionally passing a function context.
  2684. whenReady: function (callback, context) {
  2685. if (this._loaded) {
  2686. callback.call(context || this, {target: this});
  2687. } else {
  2688. this.on('load', callback, context);
  2689. }
  2690. return this;
  2691. },
  2692. // private methods for getting map state
  2693. _getMapPanePos: function () {
  2694. return L.DomUtil.getPosition(this._mapPane) || new L.Point(0, 0);
  2695. },
  2696. _moved: function () {
  2697. var pos = this._getMapPanePos();
  2698. return pos && !pos.equals([0, 0]);
  2699. },
  2700. _getTopLeftPoint: function (center, zoom) {
  2701. var pixelOrigin = center && zoom !== undefined ?
  2702. this._getNewPixelOrigin(center, zoom) :
  2703. this.getPixelOrigin();
  2704. return pixelOrigin.subtract(this._getMapPanePos());
  2705. },
  2706. _getNewPixelOrigin: function (center, zoom) {
  2707. var viewHalf = this.getSize()._divideBy(2);
  2708. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  2709. },
  2710. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  2711. var topLeft = this._getNewPixelOrigin(center, zoom);
  2712. return this.project(latlng, zoom)._subtract(topLeft);
  2713. },
  2714. // layer point of the current center
  2715. _getCenterLayerPoint: function () {
  2716. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  2717. },
  2718. // offset of the specified place to the current center in pixels
  2719. _getCenterOffset: function (latlng) {
  2720. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  2721. },
  2722. // adjust center for view to get inside bounds
  2723. _limitCenter: function (center, zoom, bounds) {
  2724. if (!bounds) { return center; }
  2725. var centerPoint = this.project(center, zoom),
  2726. viewHalf = this.getSize().divideBy(2),
  2727. viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  2728. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  2729. // If offset is less than a pixel, ignore.
  2730. // This prevents unstable projections from getting into
  2731. // an infinite loop of tiny offsets.
  2732. if (offset.round().equals([0, 0])) {
  2733. return center;
  2734. }
  2735. return this.unproject(centerPoint.add(offset), zoom);
  2736. },
  2737. // adjust offset for view to get inside bounds
  2738. _limitOffset: function (offset, bounds) {
  2739. if (!bounds) { return offset; }
  2740. var viewBounds = this.getPixelBounds(),
  2741. newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  2742. return offset.add(this._getBoundsOffset(newBounds, bounds));
  2743. },
  2744. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  2745. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  2746. var projectedMaxBounds = L.bounds(
  2747. this.project(maxBounds.getNorthEast(), zoom),
  2748. this.project(maxBounds.getSouthWest(), zoom)
  2749. ),
  2750. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  2751. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  2752. dx = this._rebound(minOffset.x, -maxOffset.x),
  2753. dy = this._rebound(minOffset.y, -maxOffset.y);
  2754. return new L.Point(dx, dy);
  2755. },
  2756. _rebound: function (left, right) {
  2757. return left + right > 0 ?
  2758. Math.round(left - right) / 2 :
  2759. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  2760. },
  2761. _limitZoom: function (zoom) {
  2762. var min = this.getMinZoom(),
  2763. max = this.getMaxZoom(),
  2764. snap = L.Browser.any3d ? this.options.zoomSnap : 1;
  2765. if (snap) {
  2766. zoom = Math.round(zoom / snap) * snap;
  2767. }
  2768. return Math.max(min, Math.min(max, zoom));
  2769. }
  2770. });
  2771. // @section
  2772. // @factory L.map(id: String, options?: Map options)
  2773. // Instantiates a map object given the DOM ID of a `<div>` element
  2774. // and optionally an object literal with `Map options`.
  2775. //
  2776. // @alternative
  2777. // @factory L.map(el: HTMLElement, options?: Map options)
  2778. // Instantiates a map object given an instance of a `<div>` HTML element
  2779. // and optionally an object literal with `Map options`.
  2780. L.map = function (id, options) {
  2781. return new L.Map(id, options);
  2782. };
  2783. /*
  2784. * @class Layer
  2785. * @inherits Evented
  2786. * @aka L.Layer
  2787. * @aka ILayer
  2788. *
  2789. * A set of methods from the Layer base class that all Leaflet layers use.
  2790. * Inherits all methods, options and events from `L.Evented`.
  2791. *
  2792. * @example
  2793. *
  2794. * ```js
  2795. * var layer = L.Marker(latlng).addTo(map);
  2796. * layer.addTo(map);
  2797. * layer.remove();
  2798. * ```
  2799. *
  2800. * @event add: Event
  2801. * Fired after the layer is added to a map
  2802. *
  2803. * @event remove: Event
  2804. * Fired after the layer is removed from a map
  2805. */
  2806. L.Layer = L.Evented.extend({
  2807. // Classes extending `L.Layer` will inherit the following options:
  2808. options: {
  2809. // @option pane: String = 'overlayPane'
  2810. // 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.
  2811. pane: 'overlayPane',
  2812. nonBubblingEvents: [] // Array of events that should not be bubbled to DOM parents (like the map)
  2813. },
  2814. /* @section
  2815. * Classes extending `L.Layer` will inherit the following methods:
  2816. *
  2817. * @method addTo(map: Map): this
  2818. * Adds the layer to the given map
  2819. */
  2820. addTo: function (map) {
  2821. map.addLayer(this);
  2822. return this;
  2823. },
  2824. // @method remove: this
  2825. // Removes the layer from the map it is currently active on.
  2826. remove: function () {
  2827. return this.removeFrom(this._map || this._mapToAdd);
  2828. },
  2829. // @method removeFrom(map: Map): this
  2830. // Removes the layer from the given map
  2831. removeFrom: function (obj) {
  2832. if (obj) {
  2833. obj.removeLayer(this);
  2834. }
  2835. return this;
  2836. },
  2837. // @method getPane(name? : String): HTMLElement
  2838. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  2839. getPane: function (name) {
  2840. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  2841. },
  2842. addInteractiveTarget: function (targetEl) {
  2843. this._map._targets[L.stamp(targetEl)] = this;
  2844. return this;
  2845. },
  2846. removeInteractiveTarget: function (targetEl) {
  2847. delete this._map._targets[L.stamp(targetEl)];
  2848. return this;
  2849. },
  2850. _layerAdd: function (e) {
  2851. var map = e.target;
  2852. // check in case layer gets added and then removed before the map is ready
  2853. if (!map.hasLayer(this)) { return; }
  2854. this._map = map;
  2855. this._zoomAnimated = map._zoomAnimated;
  2856. if (this.getEvents) {
  2857. var events = this.getEvents();
  2858. map.on(events, this);
  2859. this.once('remove', function () {
  2860. map.off(events, this);
  2861. }, this);
  2862. }
  2863. this.onAdd(map);
  2864. if (this.getAttribution && this._map.attributionControl) {
  2865. this._map.attributionControl.addAttribution(this.getAttribution());
  2866. }
  2867. this.fire('add');
  2868. map.fire('layeradd', {layer: this});
  2869. }
  2870. });
  2871. /* @section Extension methods
  2872. * @uninheritable
  2873. *
  2874. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  2875. *
  2876. * @method onAdd(map: Map): this
  2877. * 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).
  2878. *
  2879. * @method onRemove(map: Map): this
  2880. * 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).
  2881. *
  2882. * @method getEvents(): Object
  2883. * 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.
  2884. *
  2885. * @method getAttribution(): String
  2886. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  2887. *
  2888. * @method beforeAdd(map: Map): this
  2889. * 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.
  2890. */
  2891. /* @namespace Map
  2892. * @section Layer events
  2893. *
  2894. * @event layeradd: LayerEvent
  2895. * Fired when a new layer is added to the map.
  2896. *
  2897. * @event layerremove: LayerEvent
  2898. * Fired when some layer is removed from the map
  2899. *
  2900. * @section Methods for Layers and Controls
  2901. */
  2902. L.Map.include({
  2903. // @method addLayer(layer: Layer): this
  2904. // Adds the given layer to the map
  2905. addLayer: function (layer) {
  2906. var id = L.stamp(layer);
  2907. if (this._layers[id]) { return this; }
  2908. this._layers[id] = layer;
  2909. layer._mapToAdd = this;
  2910. if (layer.beforeAdd) {
  2911. layer.beforeAdd(this);
  2912. }
  2913. this.whenReady(layer._layerAdd, layer);
  2914. return this;
  2915. },
  2916. // @method removeLayer(layer: Layer): this
  2917. // Removes the given layer from the map.
  2918. removeLayer: function (layer) {
  2919. var id = L.stamp(layer);
  2920. if (!this._layers[id]) { return this; }
  2921. if (this._loaded) {
  2922. layer.onRemove(this);
  2923. }
  2924. if (layer.getAttribution && this.attributionControl) {
  2925. this.attributionControl.removeAttribution(layer.getAttribution());
  2926. }
  2927. delete this._layers[id];
  2928. if (this._loaded) {
  2929. this.fire('layerremove', {layer: layer});
  2930. layer.fire('remove');
  2931. }
  2932. layer._map = layer._mapToAdd = null;
  2933. return this;
  2934. },
  2935. // @method hasLayer(layer: Layer): Boolean
  2936. // Returns `true` if the given layer is currently added to the map
  2937. hasLayer: function (layer) {
  2938. return !!layer && (L.stamp(layer) in this._layers);
  2939. },
  2940. /* @method eachLayer(fn: Function, context?: Object): this
  2941. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  2942. * ```
  2943. * map.eachLayer(function(layer){
  2944. * layer.bindPopup('Hello');
  2945. * });
  2946. * ```
  2947. */
  2948. eachLayer: function (method, context) {
  2949. for (var i in this._layers) {
  2950. method.call(context, this._layers[i]);
  2951. }
  2952. return this;
  2953. },
  2954. _addLayers: function (layers) {
  2955. layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
  2956. for (var i = 0, len = layers.length; i < len; i++) {
  2957. this.addLayer(layers[i]);
  2958. }
  2959. },
  2960. _addZoomLimit: function (layer) {
  2961. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  2962. this._zoomBoundLayers[L.stamp(layer)] = layer;
  2963. this._updateZoomLevels();
  2964. }
  2965. },
  2966. _removeZoomLimit: function (layer) {
  2967. var id = L.stamp(layer);
  2968. if (this._zoomBoundLayers[id]) {
  2969. delete this._zoomBoundLayers[id];
  2970. this._updateZoomLevels();
  2971. }
  2972. },
  2973. _updateZoomLevels: function () {
  2974. var minZoom = Infinity,
  2975. maxZoom = -Infinity,
  2976. oldZoomSpan = this._getZoomSpan();
  2977. for (var i in this._zoomBoundLayers) {
  2978. var options = this._zoomBoundLayers[i].options;
  2979. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  2980. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  2981. }
  2982. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  2983. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  2984. // @section Map state change events
  2985. // @event zoomlevelschange: Event
  2986. // Fired when the number of zoomlevels on the map is changed due
  2987. // to adding or removing a layer.
  2988. if (oldZoomSpan !== this._getZoomSpan()) {
  2989. this.fire('zoomlevelschange');
  2990. }
  2991. }
  2992. });
  2993. /*
  2994. * @namespace Projection
  2995. * @projection L.Projection.Mercator
  2996. *
  2997. * 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.
  2998. */
  2999. L.Projection.Mercator = {
  3000. R: 6378137,
  3001. R_MINOR: 6356752.314245179,
  3002. bounds: L.bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  3003. project: function (latlng) {
  3004. var d = Math.PI / 180,
  3005. r = this.R,
  3006. y = latlng.lat * d,
  3007. tmp = this.R_MINOR / r,
  3008. e = Math.sqrt(1 - tmp * tmp),
  3009. con = e * Math.sin(y);
  3010. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  3011. y = -r * Math.log(Math.max(ts, 1E-10));
  3012. return new L.Point(latlng.lng * d * r, y);
  3013. },
  3014. unproject: function (point) {
  3015. var d = 180 / Math.PI,
  3016. r = this.R,
  3017. tmp = this.R_MINOR / r,
  3018. e = Math.sqrt(1 - tmp * tmp),
  3019. ts = Math.exp(-point.y / r),
  3020. phi = Math.PI / 2 - 2 * Math.atan(ts);
  3021. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  3022. con = e * Math.sin(phi);
  3023. con = Math.pow((1 - con) / (1 + con), e / 2);
  3024. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  3025. phi += dphi;
  3026. }
  3027. return new L.LatLng(phi * d, point.x * d / r);
  3028. }
  3029. };
  3030. /*
  3031. * @namespace CRS
  3032. * @crs L.CRS.EPSG3395
  3033. *
  3034. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  3035. */
  3036. L.CRS.EPSG3395 = L.extend({}, L.CRS.Earth, {
  3037. code: 'EPSG:3395',
  3038. projection: L.Projection.Mercator,
  3039. transformation: (function () {
  3040. var scale = 0.5 / (Math.PI * L.Projection.Mercator.R);
  3041. return new L.Transformation(scale, 0.5, -scale, 0.5);
  3042. }())
  3043. });
  3044. /*
  3045. * @class GridLayer
  3046. * @inherits Layer
  3047. * @aka L.GridLayer
  3048. *
  3049. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  3050. * 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.
  3051. *
  3052. *
  3053. * @section Synchronous usage
  3054. * @example
  3055. *
  3056. * 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.
  3057. *
  3058. * ```js
  3059. * var CanvasLayer = L.GridLayer.extend({
  3060. * createTile: function(coords){
  3061. * // create a <canvas> element for drawing
  3062. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  3063. *
  3064. * // setup tile width and height according to the options
  3065. * var size = this.getTileSize();
  3066. * tile.width = size.x;
  3067. * tile.height = size.y;
  3068. *
  3069. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  3070. * var ctx = tile.getContext('2d');
  3071. *
  3072. * // return the tile so it can be rendered on screen
  3073. * return tile;
  3074. * }
  3075. * });
  3076. * ```
  3077. *
  3078. * @section Asynchronous usage
  3079. * @example
  3080. *
  3081. * 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.
  3082. *
  3083. * ```js
  3084. * var CanvasLayer = L.GridLayer.extend({
  3085. * createTile: function(coords, done){
  3086. * var error;
  3087. *
  3088. * // create a <canvas> element for drawing
  3089. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  3090. *
  3091. * // setup tile width and height according to the options
  3092. * var size = this.getTileSize();
  3093. * tile.width = size.x;
  3094. * tile.height = size.y;
  3095. *
  3096. * // draw something asynchronously and pass the tile to the done() callback
  3097. * setTimeout(function() {
  3098. * done(error, tile);
  3099. * }, 1000);
  3100. *
  3101. * return tile;
  3102. * }
  3103. * });
  3104. * ```
  3105. *
  3106. * @section
  3107. */
  3108. L.GridLayer = L.Layer.extend({
  3109. // @section
  3110. // @aka GridLayer options
  3111. options: {
  3112. // @option tileSize: Number|Point = 256
  3113. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  3114. tileSize: 256,
  3115. // @option opacity: Number = 1.0
  3116. // Opacity of the tiles. Can be used in the `createTile()` function.
  3117. opacity: 1,
  3118. // @option updateWhenIdle: Boolean = depends
  3119. // If `false`, new tiles are loaded during panning, otherwise only after it (for better performance). `true` by default on mobile browsers, otherwise `false`.
  3120. updateWhenIdle: L.Browser.mobile,
  3121. // @option updateWhenZooming: Boolean = true
  3122. // 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.
  3123. updateWhenZooming: true,
  3124. // @option updateInterval: Number = 200
  3125. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  3126. updateInterval: 200,
  3127. // @option attribution: String = null
  3128. // String to be shown in the attribution control, describes the layer data, e.g. "© Mapbox".
  3129. attribution: null,
  3130. // @option zIndex: Number = 1
  3131. // The explicit zIndex of the tile layer.
  3132. zIndex: 1,
  3133. // @option bounds: LatLngBounds = undefined
  3134. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  3135. bounds: null,
  3136. // @option minZoom: Number = 0
  3137. // The minimum zoom level that tiles will be loaded at. By default the entire map.
  3138. minZoom: 0,
  3139. // @option maxZoom: Number = undefined
  3140. // The maximum zoom level that tiles will be loaded at.
  3141. maxZoom: undefined,
  3142. // @option noWrap: Boolean = false
  3143. // Whether the layer is wrapped around the antimeridian. If `true`, the
  3144. // GridLayer will only be displayed once at low zoom levels. Has no
  3145. // effect when the [map CRS](#map-crs) doesn't wrap around.
  3146. noWrap: false,
  3147. // @option pane: String = 'tilePane'
  3148. // `Map pane` where the grid layer will be added.
  3149. pane: 'tilePane',
  3150. // @option className: String = ''
  3151. // A custom class name to assign to the tile layer. Empty by default.
  3152. className: '',
  3153. // @option keepBuffer: Number = 2
  3154. // When panning the map, keep this many rows and columns of tiles before unloading them.
  3155. keepBuffer: 2
  3156. },
  3157. initialize: function (options) {
  3158. L.setOptions(this, options);
  3159. },
  3160. onAdd: function () {
  3161. this._initContainer();
  3162. this._levels = {};
  3163. this._tiles = {};
  3164. this._resetView();
  3165. this._update();
  3166. },
  3167. beforeAdd: function (map) {
  3168. map._addZoomLimit(this);
  3169. },
  3170. onRemove: function (map) {
  3171. this._removeAllTiles();
  3172. L.DomUtil.remove(this._container);
  3173. map._removeZoomLimit(this);
  3174. this._container = null;
  3175. this._tileZoom = null;
  3176. },
  3177. // @method bringToFront: this
  3178. // Brings the tile layer to the top of all tile layers.
  3179. bringToFront: function () {
  3180. if (this._map) {
  3181. L.DomUtil.toFront(this._container);
  3182. this._setAutoZIndex(Math.max);
  3183. }
  3184. return this;
  3185. },
  3186. // @method bringToBack: this
  3187. // Brings the tile layer to the bottom of all tile layers.
  3188. bringToBack: function () {
  3189. if (this._map) {
  3190. L.DomUtil.toBack(this._container);
  3191. this._setAutoZIndex(Math.min);
  3192. }
  3193. return this;
  3194. },
  3195. // @method getAttribution: String
  3196. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  3197. getAttribution: function () {
  3198. return this.options.attribution;
  3199. },
  3200. // @method getContainer: HTMLElement
  3201. // Returns the HTML element that contains the tiles for this layer.
  3202. getContainer: function () {
  3203. return this._container;
  3204. },
  3205. // @method setOpacity(opacity: Number): this
  3206. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  3207. setOpacity: function (opacity) {
  3208. this.options.opacity = opacity;
  3209. this._updateOpacity();
  3210. return this;
  3211. },
  3212. // @method setZIndex(zIndex: Number): this
  3213. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  3214. setZIndex: function (zIndex) {
  3215. this.options.zIndex = zIndex;
  3216. this._updateZIndex();
  3217. return this;
  3218. },
  3219. // @method isLoading: Boolean
  3220. // Returns `true` if any tile in the grid layer has not finished loading.
  3221. isLoading: function () {
  3222. return this._loading;
  3223. },
  3224. // @method redraw: this
  3225. // Causes the layer to clear all the tiles and request them again.
  3226. redraw: function () {
  3227. if (this._map) {
  3228. this._removeAllTiles();
  3229. this._update();
  3230. }
  3231. return this;
  3232. },
  3233. getEvents: function () {
  3234. var events = {
  3235. viewprereset: this._invalidateAll,
  3236. viewreset: this._resetView,
  3237. zoom: this._resetView,
  3238. moveend: this._onMoveEnd
  3239. };
  3240. if (!this.options.updateWhenIdle) {
  3241. // update tiles on move, but not more often than once per given interval
  3242. if (!this._onMove) {
  3243. this._onMove = L.Util.throttle(this._onMoveEnd, this.options.updateInterval, this);
  3244. }
  3245. events.move = this._onMove;
  3246. }
  3247. if (this._zoomAnimated) {
  3248. events.zoomanim = this._animateZoom;
  3249. }
  3250. return events;
  3251. },
  3252. // @section Extension methods
  3253. // Layers extending `GridLayer` shall reimplement the following method.
  3254. // @method createTile(coords: Object, done?: Function): HTMLElement
  3255. // Called only internally, must be overriden by classes extending `GridLayer`.
  3256. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  3257. // is specified, it must be called when the tile has finished loading and drawing.
  3258. createTile: function () {
  3259. return document.createElement('div');
  3260. },
  3261. // @section
  3262. // @method getTileSize: Point
  3263. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  3264. getTileSize: function () {
  3265. var s = this.options.tileSize;
  3266. return s instanceof L.Point ? s : new L.Point(s, s);
  3267. },
  3268. _updateZIndex: function () {
  3269. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  3270. this._container.style.zIndex = this.options.zIndex;
  3271. }
  3272. },
  3273. _setAutoZIndex: function (compare) {
  3274. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  3275. var layers = this.getPane().children,
  3276. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  3277. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  3278. zIndex = layers[i].style.zIndex;
  3279. if (layers[i] !== this._container && zIndex) {
  3280. edgeZIndex = compare(edgeZIndex, +zIndex);
  3281. }
  3282. }
  3283. if (isFinite(edgeZIndex)) {
  3284. this.options.zIndex = edgeZIndex + compare(-1, 1);
  3285. this._updateZIndex();
  3286. }
  3287. },
  3288. _updateOpacity: function () {
  3289. if (!this._map) { return; }
  3290. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  3291. if (L.Browser.ielt9) { return; }
  3292. L.DomUtil.setOpacity(this._container, this.options.opacity);
  3293. var now = +new Date(),
  3294. nextFrame = false,
  3295. willPrune = false;
  3296. for (var key in this._tiles) {
  3297. var tile = this._tiles[key];
  3298. if (!tile.current || !tile.loaded) { continue; }
  3299. var fade = Math.min(1, (now - tile.loaded) / 200);
  3300. L.DomUtil.setOpacity(tile.el, fade);
  3301. if (fade < 1) {
  3302. nextFrame = true;
  3303. } else {
  3304. if (tile.active) { willPrune = true; }
  3305. tile.active = true;
  3306. }
  3307. }
  3308. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  3309. if (nextFrame) {
  3310. L.Util.cancelAnimFrame(this._fadeFrame);
  3311. this._fadeFrame = L.Util.requestAnimFrame(this._updateOpacity, this);
  3312. }
  3313. },
  3314. _initContainer: function () {
  3315. if (this._container) { return; }
  3316. this._container = L.DomUtil.create('div', 'leaflet-layer ' + (this.options.className || ''));
  3317. this._updateZIndex();
  3318. if (this.options.opacity < 1) {
  3319. this._updateOpacity();
  3320. }
  3321. this.getPane().appendChild(this._container);
  3322. },
  3323. _updateLevels: function () {
  3324. var zoom = this._tileZoom,
  3325. maxZoom = this.options.maxZoom;
  3326. if (zoom === undefined) { return undefined; }
  3327. for (var z in this._levels) {
  3328. if (this._levels[z].el.children.length || z === zoom) {
  3329. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  3330. } else {
  3331. L.DomUtil.remove(this._levels[z].el);
  3332. this._removeTilesAtZoom(z);
  3333. delete this._levels[z];
  3334. }
  3335. }
  3336. var level = this._levels[zoom],
  3337. map = this._map;
  3338. if (!level) {
  3339. level = this._levels[zoom] = {};
  3340. level.el = L.DomUtil.create('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  3341. level.el.style.zIndex = maxZoom;
  3342. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  3343. level.zoom = zoom;
  3344. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  3345. // force the browser to consider the newly added element for transition
  3346. L.Util.falseFn(level.el.offsetWidth);
  3347. }
  3348. this._level = level;
  3349. return level;
  3350. },
  3351. _pruneTiles: function () {
  3352. if (!this._map) {
  3353. return;
  3354. }
  3355. var key, tile;
  3356. var zoom = this._map.getZoom();
  3357. if (zoom > this.options.maxZoom ||
  3358. zoom < this.options.minZoom) {
  3359. this._removeAllTiles();
  3360. return;
  3361. }
  3362. for (key in this._tiles) {
  3363. tile = this._tiles[key];
  3364. tile.retain = tile.current;
  3365. }
  3366. for (key in this._tiles) {
  3367. tile = this._tiles[key];
  3368. if (tile.current && !tile.active) {
  3369. var coords = tile.coords;
  3370. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  3371. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  3372. }
  3373. }
  3374. }
  3375. for (key in this._tiles) {
  3376. if (!this._tiles[key].retain) {
  3377. this._removeTile(key);
  3378. }
  3379. }
  3380. },
  3381. _removeTilesAtZoom: function (zoom) {
  3382. for (var key in this._tiles) {
  3383. if (this._tiles[key].coords.z !== zoom) {
  3384. continue;
  3385. }
  3386. this._removeTile(key);
  3387. }
  3388. },
  3389. _removeAllTiles: function () {
  3390. for (var key in this._tiles) {
  3391. this._removeTile(key);
  3392. }
  3393. },
  3394. _invalidateAll: function () {
  3395. for (var z in this._levels) {
  3396. L.DomUtil.remove(this._levels[z].el);
  3397. delete this._levels[z];
  3398. }
  3399. this._removeAllTiles();
  3400. this._tileZoom = null;
  3401. },
  3402. _retainParent: function (x, y, z, minZoom) {
  3403. var x2 = Math.floor(x / 2),
  3404. y2 = Math.floor(y / 2),
  3405. z2 = z - 1,
  3406. coords2 = new L.Point(+x2, +y2);
  3407. coords2.z = +z2;
  3408. var key = this._tileCoordsToKey(coords2),
  3409. tile = this._tiles[key];
  3410. if (tile && tile.active) {
  3411. tile.retain = true;
  3412. return true;
  3413. } else if (tile && tile.loaded) {
  3414. tile.retain = true;
  3415. }
  3416. if (z2 > minZoom) {
  3417. return this._retainParent(x2, y2, z2, minZoom);
  3418. }
  3419. return false;
  3420. },
  3421. _retainChildren: function (x, y, z, maxZoom) {
  3422. for (var i = 2 * x; i < 2 * x + 2; i++) {
  3423. for (var j = 2 * y; j < 2 * y + 2; j++) {
  3424. var coords = new L.Point(i, j);
  3425. coords.z = z + 1;
  3426. var key = this._tileCoordsToKey(coords),
  3427. tile = this._tiles[key];
  3428. if (tile && tile.active) {
  3429. tile.retain = true;
  3430. continue;
  3431. } else if (tile && tile.loaded) {
  3432. tile.retain = true;
  3433. }
  3434. if (z + 1 < maxZoom) {
  3435. this._retainChildren(i, j, z + 1, maxZoom);
  3436. }
  3437. }
  3438. }
  3439. },
  3440. _resetView: function (e) {
  3441. var animating = e && (e.pinch || e.flyTo);
  3442. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  3443. },
  3444. _animateZoom: function (e) {
  3445. this._setView(e.center, e.zoom, true, e.noUpdate);
  3446. },
  3447. _setView: function (center, zoom, noPrune, noUpdate) {
  3448. var tileZoom = Math.round(zoom);
  3449. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  3450. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  3451. tileZoom = undefined;
  3452. }
  3453. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  3454. if (!noUpdate || tileZoomChanged) {
  3455. this._tileZoom = tileZoom;
  3456. if (this._abortLoading) {
  3457. this._abortLoading();
  3458. }
  3459. this._updateLevels();
  3460. this._resetGrid();
  3461. if (tileZoom !== undefined) {
  3462. this._update(center);
  3463. }
  3464. if (!noPrune) {
  3465. this._pruneTiles();
  3466. }
  3467. // Flag to prevent _updateOpacity from pruning tiles during
  3468. // a zoom anim or a pinch gesture
  3469. this._noPrune = !!noPrune;
  3470. }
  3471. this._setZoomTransforms(center, zoom);
  3472. },
  3473. _setZoomTransforms: function (center, zoom) {
  3474. for (var i in this._levels) {
  3475. this._setZoomTransform(this._levels[i], center, zoom);
  3476. }
  3477. },
  3478. _setZoomTransform: function (level, center, zoom) {
  3479. var scale = this._map.getZoomScale(zoom, level.zoom),
  3480. translate = level.origin.multiplyBy(scale)
  3481. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  3482. if (L.Browser.any3d) {
  3483. L.DomUtil.setTransform(level.el, translate, scale);
  3484. } else {
  3485. L.DomUtil.setPosition(level.el, translate);
  3486. }
  3487. },
  3488. _resetGrid: function () {
  3489. var map = this._map,
  3490. crs = map.options.crs,
  3491. tileSize = this._tileSize = this.getTileSize(),
  3492. tileZoom = this._tileZoom;
  3493. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  3494. if (bounds) {
  3495. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  3496. }
  3497. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  3498. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  3499. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  3500. ];
  3501. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  3502. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  3503. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  3504. ];
  3505. },
  3506. _onMoveEnd: function () {
  3507. if (!this._map || this._map._animatingZoom) { return; }
  3508. this._update();
  3509. },
  3510. _getTiledPixelBounds: function (center) {
  3511. var map = this._map,
  3512. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  3513. scale = map.getZoomScale(mapZoom, this._tileZoom),
  3514. pixelCenter = map.project(center, this._tileZoom).floor(),
  3515. halfSize = map.getSize().divideBy(scale * 2);
  3516. return new L.Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  3517. },
  3518. // Private method to load tiles in the grid's active zoom level according to map bounds
  3519. _update: function (center) {
  3520. var map = this._map;
  3521. if (!map) { return; }
  3522. var zoom = map.getZoom();
  3523. if (center === undefined) { center = map.getCenter(); }
  3524. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  3525. var pixelBounds = this._getTiledPixelBounds(center),
  3526. tileRange = this._pxBoundsToTileRange(pixelBounds),
  3527. tileCenter = tileRange.getCenter(),
  3528. queue = [],
  3529. margin = this.options.keepBuffer,
  3530. noPruneRange = new L.Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  3531. tileRange.getTopRight().add([margin, -margin]));
  3532. for (var key in this._tiles) {
  3533. var c = this._tiles[key].coords;
  3534. if (c.z !== this._tileZoom || !noPruneRange.contains(L.point(c.x, c.y))) {
  3535. this._tiles[key].current = false;
  3536. }
  3537. }
  3538. // _update just loads more tiles. If the tile zoom level differs too much
  3539. // from the map's, let _setView reset levels and prune old tiles.
  3540. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  3541. // create a queue of coordinates to load tiles from
  3542. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  3543. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  3544. var coords = new L.Point(i, j);
  3545. coords.z = this._tileZoom;
  3546. if (!this._isValidTile(coords)) { continue; }
  3547. var tile = this._tiles[this._tileCoordsToKey(coords)];
  3548. if (tile) {
  3549. tile.current = true;
  3550. } else {
  3551. queue.push(coords);
  3552. }
  3553. }
  3554. }
  3555. // sort tile queue to load tiles in order of their distance to center
  3556. queue.sort(function (a, b) {
  3557. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  3558. });
  3559. if (queue.length !== 0) {
  3560. // if it's the first batch of tiles to load
  3561. if (!this._loading) {
  3562. this._loading = true;
  3563. // @event loading: Event
  3564. // Fired when the grid layer starts loading tiles.
  3565. this.fire('loading');
  3566. }
  3567. // create DOM fragment to append tiles in one batch
  3568. var fragment = document.createDocumentFragment();
  3569. for (i = 0; i < queue.length; i++) {
  3570. this._addTile(queue[i], fragment);
  3571. }
  3572. this._level.el.appendChild(fragment);
  3573. }
  3574. },
  3575. _isValidTile: function (coords) {
  3576. var crs = this._map.options.crs;
  3577. if (!crs.infinite) {
  3578. // don't load tile if it's out of bounds and not wrapped
  3579. var bounds = this._globalTileRange;
  3580. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  3581. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  3582. }
  3583. if (!this.options.bounds) { return true; }
  3584. // don't load tile if it doesn't intersect the bounds in options
  3585. var tileBounds = this._tileCoordsToBounds(coords);
  3586. return L.latLngBounds(this.options.bounds).overlaps(tileBounds);
  3587. },
  3588. _keyToBounds: function (key) {
  3589. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  3590. },
  3591. // converts tile coordinates to its geographical bounds
  3592. _tileCoordsToBounds: function (coords) {
  3593. var map = this._map,
  3594. tileSize = this.getTileSize(),
  3595. nwPoint = coords.scaleBy(tileSize),
  3596. sePoint = nwPoint.add(tileSize),
  3597. nw = map.unproject(nwPoint, coords.z),
  3598. se = map.unproject(sePoint, coords.z);
  3599. if (!this.options.noWrap) {
  3600. nw = map.wrapLatLng(nw);
  3601. se = map.wrapLatLng(se);
  3602. }
  3603. return new L.LatLngBounds(nw, se);
  3604. },
  3605. // converts tile coordinates to key for the tile cache
  3606. _tileCoordsToKey: function (coords) {
  3607. return coords.x + ':' + coords.y + ':' + coords.z;
  3608. },
  3609. // converts tile cache key to coordinates
  3610. _keyToTileCoords: function (key) {
  3611. var k = key.split(':'),
  3612. coords = new L.Point(+k[0], +k[1]);
  3613. coords.z = +k[2];
  3614. return coords;
  3615. },
  3616. _removeTile: function (key) {
  3617. var tile = this._tiles[key];
  3618. if (!tile) { return; }
  3619. L.DomUtil.remove(tile.el);
  3620. delete this._tiles[key];
  3621. // @event tileunload: TileEvent
  3622. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  3623. this.fire('tileunload', {
  3624. tile: tile.el,
  3625. coords: this._keyToTileCoords(key)
  3626. });
  3627. },
  3628. _initTile: function (tile) {
  3629. L.DomUtil.addClass(tile, 'leaflet-tile');
  3630. var tileSize = this.getTileSize();
  3631. tile.style.width = tileSize.x + 'px';
  3632. tile.style.height = tileSize.y + 'px';
  3633. tile.onselectstart = L.Util.falseFn;
  3634. tile.onmousemove = L.Util.falseFn;
  3635. // update opacity on tiles in IE7-8 because of filter inheritance problems
  3636. if (L.Browser.ielt9 && this.options.opacity < 1) {
  3637. L.DomUtil.setOpacity(tile, this.options.opacity);
  3638. }
  3639. // without this hack, tiles disappear after zoom on Chrome for Android
  3640. // https://github.com/Leaflet/Leaflet/issues/2078
  3641. if (L.Browser.android && !L.Browser.android23) {
  3642. tile.style.WebkitBackfaceVisibility = 'hidden';
  3643. }
  3644. },
  3645. _addTile: function (coords, container) {
  3646. var tilePos = this._getTilePos(coords),
  3647. key = this._tileCoordsToKey(coords);
  3648. var tile = this.createTile(this._wrapCoords(coords), L.bind(this._tileReady, this, coords));
  3649. this._initTile(tile);
  3650. // if createTile is defined with a second argument ("done" callback),
  3651. // we know that tile is async and will be ready later; otherwise
  3652. if (this.createTile.length < 2) {
  3653. // mark tile as ready, but delay one frame for opacity animation to happen
  3654. L.Util.requestAnimFrame(L.bind(this._tileReady, this, coords, null, tile));
  3655. }
  3656. L.DomUtil.setPosition(tile, tilePos);
  3657. // save tile in cache
  3658. this._tiles[key] = {
  3659. el: tile,
  3660. coords: coords,
  3661. current: true
  3662. };
  3663. container.appendChild(tile);
  3664. // @event tileloadstart: TileEvent
  3665. // Fired when a tile is requested and starts loading.
  3666. this.fire('tileloadstart', {
  3667. tile: tile,
  3668. coords: coords
  3669. });
  3670. },
  3671. _tileReady: function (coords, err, tile) {
  3672. if (!this._map) { return; }
  3673. if (err) {
  3674. // @event tileerror: TileErrorEvent
  3675. // Fired when there is an error loading a tile.
  3676. this.fire('tileerror', {
  3677. error: err,
  3678. tile: tile,
  3679. coords: coords
  3680. });
  3681. }
  3682. var key = this._tileCoordsToKey(coords);
  3683. tile = this._tiles[key];
  3684. if (!tile) { return; }
  3685. tile.loaded = +new Date();
  3686. if (this._map._fadeAnimated) {
  3687. L.DomUtil.setOpacity(tile.el, 0);
  3688. L.Util.cancelAnimFrame(this._fadeFrame);
  3689. this._fadeFrame = L.Util.requestAnimFrame(this._updateOpacity, this);
  3690. } else {
  3691. tile.active = true;
  3692. this._pruneTiles();
  3693. }
  3694. if (!err) {
  3695. L.DomUtil.addClass(tile.el, 'leaflet-tile-loaded');
  3696. // @event tileload: TileEvent
  3697. // Fired when a tile loads.
  3698. this.fire('tileload', {
  3699. tile: tile.el,
  3700. coords: coords
  3701. });
  3702. }
  3703. if (this._noTilesToLoad()) {
  3704. this._loading = false;
  3705. // @event load: Event
  3706. // Fired when the grid layer loaded all visible tiles.
  3707. this.fire('load');
  3708. if (L.Browser.ielt9 || !this._map._fadeAnimated) {
  3709. L.Util.requestAnimFrame(this._pruneTiles, this);
  3710. } else {
  3711. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  3712. // to trigger a pruning.
  3713. setTimeout(L.bind(this._pruneTiles, this), 250);
  3714. }
  3715. }
  3716. },
  3717. _getTilePos: function (coords) {
  3718. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  3719. },
  3720. _wrapCoords: function (coords) {
  3721. var newCoords = new L.Point(
  3722. this._wrapX ? L.Util.wrapNum(coords.x, this._wrapX) : coords.x,
  3723. this._wrapY ? L.Util.wrapNum(coords.y, this._wrapY) : coords.y);
  3724. newCoords.z = coords.z;
  3725. return newCoords;
  3726. },
  3727. _pxBoundsToTileRange: function (bounds) {
  3728. var tileSize = this.getTileSize();
  3729. return new L.Bounds(
  3730. bounds.min.unscaleBy(tileSize).floor(),
  3731. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  3732. },
  3733. _noTilesToLoad: function () {
  3734. for (var key in this._tiles) {
  3735. if (!this._tiles[key].loaded) { return false; }
  3736. }
  3737. return true;
  3738. }
  3739. });
  3740. // @factory L.gridLayer(options?: GridLayer options)
  3741. // Creates a new instance of GridLayer with the supplied options.
  3742. L.gridLayer = function (options) {
  3743. return new L.GridLayer(options);
  3744. };
  3745. /*
  3746. * @class TileLayer
  3747. * @inherits GridLayer
  3748. * @aka L.TileLayer
  3749. * Used to load and display tile layers on the map. Extends `GridLayer`.
  3750. *
  3751. * @example
  3752. *
  3753. * ```js
  3754. * L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map);
  3755. * ```
  3756. *
  3757. * @section URL template
  3758. * @example
  3759. *
  3760. * A string of the following form:
  3761. *
  3762. * ```
  3763. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  3764. * ```
  3765. *
  3766. * `{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 @2x to the URL to load retina tiles.
  3767. *
  3768. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  3769. *
  3770. * ```
  3771. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  3772. * ```
  3773. */
  3774. L.TileLayer = L.GridLayer.extend({
  3775. // @section
  3776. // @aka TileLayer options
  3777. options: {
  3778. // @option minZoom: Number = 0
  3779. // Minimum zoom number.
  3780. minZoom: 0,
  3781. // @option maxZoom: Number = 18
  3782. // Maximum zoom number.
  3783. maxZoom: 18,
  3784. // @option maxNativeZoom: Number = null
  3785. // Maximum zoom number the tile source has available. If it is specified,
  3786. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  3787. // from `maxNativeZoom` level and auto-scaled.
  3788. maxNativeZoom: null,
  3789. // @option subdomains: String|String[] = 'abc'
  3790. // 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.
  3791. subdomains: 'abc',
  3792. // @option errorTileUrl: String = ''
  3793. // URL to the tile image to show in place of the tile that failed to load.
  3794. errorTileUrl: '',
  3795. // @option zoomOffset: Number = 0
  3796. // The zoom number used in tile URLs will be offset with this value.
  3797. zoomOffset: 0,
  3798. // @option tms: Boolean = false
  3799. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  3800. tms: false,
  3801. // @option zoomReverse: Boolean = false
  3802. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  3803. zoomReverse: false,
  3804. // @option detectRetina: Boolean = false
  3805. // 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.
  3806. detectRetina: false,
  3807. // @option crossOrigin: Boolean = false
  3808. // If true, all tiles will have their crossOrigin attribute set to ''. This is needed if you want to access tile pixel data.
  3809. crossOrigin: false
  3810. },
  3811. initialize: function (url, options) {
  3812. this._url = url;
  3813. options = L.setOptions(this, options);
  3814. // detecting retina displays, adjusting tileSize and zoom levels
  3815. if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
  3816. options.tileSize = Math.floor(options.tileSize / 2);
  3817. if (!options.zoomReverse) {
  3818. options.zoomOffset++;
  3819. options.maxZoom--;
  3820. } else {
  3821. options.zoomOffset--;
  3822. options.minZoom++;
  3823. }
  3824. options.minZoom = Math.max(0, options.minZoom);
  3825. }
  3826. if (typeof options.subdomains === 'string') {
  3827. options.subdomains = options.subdomains.split('');
  3828. }
  3829. // for https://github.com/Leaflet/Leaflet/issues/137
  3830. if (!L.Browser.android) {
  3831. this.on('tileunload', this._onTileRemove);
  3832. }
  3833. },
  3834. // @method setUrl(url: String, noRedraw?: Boolean): this
  3835. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  3836. setUrl: function (url, noRedraw) {
  3837. this._url = url;
  3838. if (!noRedraw) {
  3839. this.redraw();
  3840. }
  3841. return this;
  3842. },
  3843. // @method createTile(coords: Object, done?: Function): HTMLElement
  3844. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  3845. // to return an `<img>` HTML element with the appropiate image URL given `coords`. The `done`
  3846. // callback is called when the tile has been loaded.
  3847. createTile: function (coords, done) {
  3848. var tile = document.createElement('img');
  3849. L.DomEvent.on(tile, 'load', L.bind(this._tileOnLoad, this, done, tile));
  3850. L.DomEvent.on(tile, 'error', L.bind(this._tileOnError, this, done, tile));
  3851. if (this.options.crossOrigin) {
  3852. tile.crossOrigin = '';
  3853. }
  3854. /*
  3855. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  3856. http://www.w3.org/TR/WCAG20-TECHS/H67
  3857. */
  3858. tile.alt = '';
  3859. tile.src = this.getTileUrl(coords);
  3860. return tile;
  3861. },
  3862. // @section Extension methods
  3863. // @uninheritable
  3864. // Layers extending `TileLayer` might reimplement the following method.
  3865. // @method getTileUrl(coords: Object): String
  3866. // Called only internally, returns the URL for a tile given its coordinates.
  3867. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  3868. getTileUrl: function (coords) {
  3869. var data = {
  3870. r: L.Browser.retina ? '@2x' : '',
  3871. s: this._getSubdomain(coords),
  3872. x: coords.x,
  3873. y: coords.y,
  3874. z: this._getZoomForUrl()
  3875. };
  3876. if (this._map && !this._map.options.crs.infinite) {
  3877. var invertedY = this._globalTileRange.max.y - coords.y;
  3878. if (this.options.tms) {
  3879. data['y'] = invertedY;
  3880. }
  3881. data['-y'] = invertedY;
  3882. }
  3883. return L.Util.template(this._url, L.extend(data, this.options));
  3884. },
  3885. _tileOnLoad: function (done, tile) {
  3886. // For https://github.com/Leaflet/Leaflet/issues/3332
  3887. if (L.Browser.ielt9) {
  3888. setTimeout(L.bind(done, this, null, tile), 0);
  3889. } else {
  3890. done(null, tile);
  3891. }
  3892. },
  3893. _tileOnError: function (done, tile, e) {
  3894. var errorUrl = this.options.errorTileUrl;
  3895. if (errorUrl) {
  3896. tile.src = errorUrl;
  3897. }
  3898. done(e, tile);
  3899. },
  3900. getTileSize: function () {
  3901. var map = this._map,
  3902. tileSize = L.GridLayer.prototype.getTileSize.call(this),
  3903. zoom = this._tileZoom + this.options.zoomOffset,
  3904. zoomN = this.options.maxNativeZoom;
  3905. // increase tile size when overscaling
  3906. return zoomN !== null && zoom > zoomN ?
  3907. tileSize.divideBy(map.getZoomScale(zoomN, zoom)).round() :
  3908. tileSize;
  3909. },
  3910. _onTileRemove: function (e) {
  3911. e.tile.onload = null;
  3912. },
  3913. _getZoomForUrl: function () {
  3914. var options = this.options,
  3915. zoom = this._tileZoom;
  3916. if (options.zoomReverse) {
  3917. zoom = options.maxZoom - zoom;
  3918. }
  3919. zoom += options.zoomOffset;
  3920. return options.maxNativeZoom !== null ? Math.min(zoom, options.maxNativeZoom) : zoom;
  3921. },
  3922. _getSubdomain: function (tilePoint) {
  3923. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  3924. return this.options.subdomains[index];
  3925. },
  3926. // stops loading all tiles in the background layer
  3927. _abortLoading: function () {
  3928. var i, tile;
  3929. for (i in this._tiles) {
  3930. if (this._tiles[i].coords.z !== this._tileZoom) {
  3931. tile = this._tiles[i].el;
  3932. tile.onload = L.Util.falseFn;
  3933. tile.onerror = L.Util.falseFn;
  3934. if (!tile.complete) {
  3935. tile.src = L.Util.emptyImageUrl;
  3936. L.DomUtil.remove(tile);
  3937. }
  3938. }
  3939. }
  3940. }
  3941. });
  3942. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  3943. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  3944. L.tileLayer = function (url, options) {
  3945. return new L.TileLayer(url, options);
  3946. };
  3947. /*
  3948. * @class TileLayer.WMS
  3949. * @inherits TileLayer
  3950. * @aka L.TileLayer.WMS
  3951. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  3952. *
  3953. * @example
  3954. *
  3955. * ```js
  3956. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  3957. * layers: 'nexrad-n0r-900913',
  3958. * format: 'image/png',
  3959. * transparent: true,
  3960. * attribution: "Weather data © 2012 IEM Nexrad"
  3961. * });
  3962. * ```
  3963. */
  3964. L.TileLayer.WMS = L.TileLayer.extend({
  3965. // @section
  3966. // @aka TileLayer.WMS options
  3967. // If any custom options not documented here are used, they will be sent to the
  3968. // WMS server as extra parameters in each request URL. This can be useful for
  3969. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  3970. defaultWmsParams: {
  3971. service: 'WMS',
  3972. request: 'GetMap',
  3973. // @option layers: String = ''
  3974. // **(required)** Comma-separated list of WMS layers to show.
  3975. layers: '',
  3976. // @option styles: String = ''
  3977. // Comma-separated list of WMS styles.
  3978. styles: '',
  3979. // @option format: String = 'image/jpeg'
  3980. // WMS image format (use `'image/png'` for layers with transparency).
  3981. format: 'image/jpeg',
  3982. // @option transparent: Boolean = false
  3983. // If `true`, the WMS service will return images with transparency.
  3984. transparent: false,
  3985. // @option version: String = '1.1.1'
  3986. // Version of the WMS service to use
  3987. version: '1.1.1'
  3988. },
  3989. options: {
  3990. // @option crs: CRS = null
  3991. // Coordinate Reference System to use for the WMS requests, defaults to
  3992. // map CRS. Don't change this if you're not sure what it means.
  3993. crs: null,
  3994. // @option uppercase: Boolean = false
  3995. // If `true`, WMS request parameter keys will be uppercase.
  3996. uppercase: false
  3997. },
  3998. initialize: function (url, options) {
  3999. this._url = url;
  4000. var wmsParams = L.extend({}, this.defaultWmsParams);
  4001. // all keys that are not TileLayer options go to WMS params
  4002. for (var i in options) {
  4003. if (!(i in this.options)) {
  4004. wmsParams[i] = options[i];
  4005. }
  4006. }
  4007. options = L.setOptions(this, options);
  4008. wmsParams.width = wmsParams.height = options.tileSize * (options.detectRetina && L.Browser.retina ? 2 : 1);
  4009. this.wmsParams = wmsParams;
  4010. },
  4011. onAdd: function (map) {
  4012. this._crs = this.options.crs || map.options.crs;
  4013. this._wmsVersion = parseFloat(this.wmsParams.version);
  4014. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  4015. this.wmsParams[projectionKey] = this._crs.code;
  4016. L.TileLayer.prototype.onAdd.call(this, map);
  4017. },
  4018. getTileUrl: function (coords) {
  4019. var tileBounds = this._tileCoordsToBounds(coords),
  4020. nw = this._crs.project(tileBounds.getNorthWest()),
  4021. se = this._crs.project(tileBounds.getSouthEast()),
  4022. bbox = (this._wmsVersion >= 1.3 && this._crs === L.CRS.EPSG4326 ?
  4023. [se.y, nw.x, nw.y, se.x] :
  4024. [nw.x, se.y, se.x, nw.y]).join(','),
  4025. url = L.TileLayer.prototype.getTileUrl.call(this, coords);
  4026. return url +
  4027. L.Util.getParamString(this.wmsParams, url, this.options.uppercase) +
  4028. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  4029. },
  4030. // @method setParams(params: Object, noRedraw?: Boolean): this
  4031. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  4032. setParams: function (params, noRedraw) {
  4033. L.extend(this.wmsParams, params);
  4034. if (!noRedraw) {
  4035. this.redraw();
  4036. }
  4037. return this;
  4038. }
  4039. });
  4040. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  4041. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  4042. L.tileLayer.wms = function (url, options) {
  4043. return new L.TileLayer.WMS(url, options);
  4044. };
  4045. /*
  4046. * @class ImageOverlay
  4047. * @aka L.ImageOverlay
  4048. * @inherits Interactive layer
  4049. *
  4050. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  4051. *
  4052. * @example
  4053. *
  4054. * ```js
  4055. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  4056. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  4057. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  4058. * ```
  4059. */
  4060. L.ImageOverlay = L.Layer.extend({
  4061. // @section
  4062. // @aka ImageOverlay options
  4063. options: {
  4064. // @option opacity: Number = 1.0
  4065. // The opacity of the image overlay.
  4066. opacity: 1,
  4067. // @option alt: String = ''
  4068. // Text for the `alt` attribute of the image (useful for accessibility).
  4069. alt: '',
  4070. // @option interactive: Boolean = false
  4071. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  4072. interactive: false,
  4073. // @option attribution: String = null
  4074. // An optional string containing HTML to be shown on the `Attribution control`
  4075. attribution: null,
  4076. // @option crossOrigin: Boolean = false
  4077. // If true, the image will have its crossOrigin attribute set to ''. This is needed if you want to access image pixel data.
  4078. crossOrigin: false
  4079. },
  4080. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  4081. this._url = url;
  4082. this._bounds = L.latLngBounds(bounds);
  4083. L.setOptions(this, options);
  4084. },
  4085. onAdd: function () {
  4086. if (!this._image) {
  4087. this._initImage();
  4088. if (this.options.opacity < 1) {
  4089. this._updateOpacity();
  4090. }
  4091. }
  4092. if (this.options.interactive) {
  4093. L.DomUtil.addClass(this._image, 'leaflet-interactive');
  4094. this.addInteractiveTarget(this._image);
  4095. }
  4096. this.getPane().appendChild(this._image);
  4097. this._reset();
  4098. },
  4099. onRemove: function () {
  4100. L.DomUtil.remove(this._image);
  4101. if (this.options.interactive) {
  4102. this.removeInteractiveTarget(this._image);
  4103. }
  4104. },
  4105. // @method setOpacity(opacity: Number): this
  4106. // Sets the opacity of the overlay.
  4107. setOpacity: function (opacity) {
  4108. this.options.opacity = opacity;
  4109. if (this._image) {
  4110. this._updateOpacity();
  4111. }
  4112. return this;
  4113. },
  4114. setStyle: function (styleOpts) {
  4115. if (styleOpts.opacity) {
  4116. this.setOpacity(styleOpts.opacity);
  4117. }
  4118. return this;
  4119. },
  4120. // @method bringToFront(): this
  4121. // Brings the layer to the top of all overlays.
  4122. bringToFront: function () {
  4123. if (this._map) {
  4124. L.DomUtil.toFront(this._image);
  4125. }
  4126. return this;
  4127. },
  4128. // @method bringToBack(): this
  4129. // Brings the layer to the bottom of all overlays.
  4130. bringToBack: function () {
  4131. if (this._map) {
  4132. L.DomUtil.toBack(this._image);
  4133. }
  4134. return this;
  4135. },
  4136. // @method setUrl(url: String): this
  4137. // Changes the URL of the image.
  4138. setUrl: function (url) {
  4139. this._url = url;
  4140. if (this._image) {
  4141. this._image.src = url;
  4142. }
  4143. return this;
  4144. },
  4145. setBounds: function (bounds) {
  4146. this._bounds = bounds;
  4147. if (this._map) {
  4148. this._reset();
  4149. }
  4150. return this;
  4151. },
  4152. getAttribution: function () {
  4153. return this.options.attribution;
  4154. },
  4155. getEvents: function () {
  4156. var events = {
  4157. zoom: this._reset,
  4158. viewreset: this._reset
  4159. };
  4160. if (this._zoomAnimated) {
  4161. events.zoomanim = this._animateZoom;
  4162. }
  4163. return events;
  4164. },
  4165. getBounds: function () {
  4166. return this._bounds;
  4167. },
  4168. getElement: function () {
  4169. return this._image;
  4170. },
  4171. _initImage: function () {
  4172. var img = this._image = L.DomUtil.create('img',
  4173. 'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated' : ''));
  4174. img.onselectstart = L.Util.falseFn;
  4175. img.onmousemove = L.Util.falseFn;
  4176. img.onload = L.bind(this.fire, this, 'load');
  4177. if (this.options.crossOrigin) {
  4178. img.crossOrigin = '';
  4179. }
  4180. img.src = this._url;
  4181. img.alt = this.options.alt;
  4182. },
  4183. _animateZoom: function (e) {
  4184. var scale = this._map.getZoomScale(e.zoom),
  4185. offset = this._map._latLngToNewLayerPoint(this._bounds.getNorthWest(), e.zoom, e.center);
  4186. L.DomUtil.setTransform(this._image, offset, scale);
  4187. },
  4188. _reset: function () {
  4189. var image = this._image,
  4190. bounds = new L.Bounds(
  4191. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  4192. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  4193. size = bounds.getSize();
  4194. L.DomUtil.setPosition(image, bounds.min);
  4195. image.style.width = size.x + 'px';
  4196. image.style.height = size.y + 'px';
  4197. },
  4198. _updateOpacity: function () {
  4199. L.DomUtil.setOpacity(this._image, this.options.opacity);
  4200. }
  4201. });
  4202. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  4203. // Instantiates an image overlay object given the URL of the image and the
  4204. // geographical bounds it is tied to.
  4205. L.imageOverlay = function (url, bounds, options) {
  4206. return new L.ImageOverlay(url, bounds, options);
  4207. };
  4208. /*
  4209. * @class Icon
  4210. * @aka L.Icon
  4211. * @inherits Layer
  4212. *
  4213. * Represents an icon to provide when creating a marker.
  4214. *
  4215. * @example
  4216. *
  4217. * ```js
  4218. * var myIcon = L.icon({
  4219. * iconUrl: 'my-icon.png',
  4220. * iconRetinaUrl: 'my-icon@2x.png',
  4221. * iconSize: [38, 95],
  4222. * iconAnchor: [22, 94],
  4223. * popupAnchor: [-3, -76],
  4224. * shadowUrl: 'my-icon-shadow.png',
  4225. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  4226. * shadowSize: [68, 95],
  4227. * shadowAnchor: [22, 94]
  4228. * });
  4229. *
  4230. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  4231. * ```
  4232. *
  4233. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  4234. *
  4235. */
  4236. L.Icon = L.Class.extend({
  4237. /* @section
  4238. * @aka Icon options
  4239. *
  4240. * @option iconUrl: String = null
  4241. * **(required)** The URL to the icon image (absolute or relative to your script path).
  4242. *
  4243. * @option iconRetinaUrl: String = null
  4244. * The URL to a retina sized version of the icon image (absolute or relative to your
  4245. * script path). Used for Retina screen devices.
  4246. *
  4247. * @option iconSize: Point = null
  4248. * Size of the icon image in pixels.
  4249. *
  4250. * @option iconAnchor: Point = null
  4251. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  4252. * will be aligned so that this point is at the marker's geographical location. Centered
  4253. * by default if size is specified, also can be set in CSS with negative margins.
  4254. *
  4255. * @option popupAnchor: Point = null
  4256. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  4257. *
  4258. * @option shadowUrl: String = null
  4259. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  4260. *
  4261. * @option shadowRetinaUrl: String = null
  4262. *
  4263. * @option shadowSize: Point = null
  4264. * Size of the shadow image in pixels.
  4265. *
  4266. * @option shadowAnchor: Point = null
  4267. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  4268. * as iconAnchor if not specified).
  4269. *
  4270. * @option className: String = ''
  4271. * A custom class name to assign to both icon and shadow images. Empty by default.
  4272. */
  4273. initialize: function (options) {
  4274. L.setOptions(this, options);
  4275. },
  4276. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  4277. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  4278. // styled according to the options.
  4279. createIcon: function (oldIcon) {
  4280. return this._createIcon('icon', oldIcon);
  4281. },
  4282. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  4283. // As `createIcon`, but for the shadow beneath it.
  4284. createShadow: function (oldIcon) {
  4285. return this._createIcon('shadow', oldIcon);
  4286. },
  4287. _createIcon: function (name, oldIcon) {
  4288. var src = this._getIconUrl(name);
  4289. if (!src) {
  4290. if (name === 'icon') {
  4291. throw new Error('iconUrl not set in Icon options (see the docs).');
  4292. }
  4293. return null;
  4294. }
  4295. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  4296. this._setIconStyles(img, name);
  4297. return img;
  4298. },
  4299. _setIconStyles: function (img, name) {
  4300. var options = this.options;
  4301. var sizeOption = options[name + 'Size'];
  4302. if (typeof sizeOption === 'number') {
  4303. sizeOption = [sizeOption, sizeOption];
  4304. }
  4305. var size = L.point(sizeOption),
  4306. anchor = L.point(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  4307. size && size.divideBy(2, true));
  4308. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  4309. if (anchor) {
  4310. img.style.marginLeft = (-anchor.x) + 'px';
  4311. img.style.marginTop = (-anchor.y) + 'px';
  4312. }
  4313. if (size) {
  4314. img.style.width = size.x + 'px';
  4315. img.style.height = size.y + 'px';
  4316. }
  4317. },
  4318. _createImg: function (src, el) {
  4319. el = el || document.createElement('img');
  4320. el.src = src;
  4321. return el;
  4322. },
  4323. _getIconUrl: function (name) {
  4324. return L.Browser.retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  4325. }
  4326. });
  4327. // @factory L.icon(options: Icon options)
  4328. // Creates an icon instance with the given options.
  4329. L.icon = function (options) {
  4330. return new L.Icon(options);
  4331. };
  4332. /*
  4333. * @miniclass Icon.Default (Icon)
  4334. * @aka L.Icon.Default
  4335. * @section
  4336. *
  4337. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  4338. * no icon is specified. Points to the blue marker image distributed with Leaflet
  4339. * releases.
  4340. *
  4341. * In order to change the default icon, just change the properties of `L.Icon.Default.prototype.options`
  4342. * (which is a set of `Icon options`).
  4343. */
  4344. L.Icon.Default = L.Icon.extend({
  4345. options: {
  4346. iconUrl: 'marker-icon.png',
  4347. iconRetinaUrl: 'marker-icon-2x.png',
  4348. shadowUrl: 'marker-shadow.png',
  4349. iconSize: [25, 41],
  4350. iconAnchor: [12, 41],
  4351. popupAnchor: [1, -34],
  4352. tooltipAnchor: [16, -28],
  4353. shadowSize: [41, 41]
  4354. },
  4355. _getIconUrl: function (name) {
  4356. if (!L.Icon.Default.imagePath) { // Deprecated, backwards-compatibility only
  4357. L.Icon.Default.imagePath = this._detectIconPath();
  4358. }
  4359. // @option imagePath: String
  4360. // `L.Icon.Default` will try to auto-detect the absolute location of the
  4361. // blue icon images. If you are placing these images in a non-standard
  4362. // way, set this option to point to the right absolute path.
  4363. return (this.options.imagePath || L.Icon.Default.imagePath) + L.Icon.prototype._getIconUrl.call(this, name);
  4364. },
  4365. _detectIconPath: function () {
  4366. var el = L.DomUtil.create('div', 'leaflet-default-icon-path', document.body);
  4367. var path = L.DomUtil.getStyle(el, 'background-image') ||
  4368. L.DomUtil.getStyle(el, 'backgroundImage'); // IE8
  4369. document.body.removeChild(el);
  4370. return path.indexOf('url') === 0 ?
  4371. path.replace(/^url\([\"\']?/, '').replace(/marker-icon\.png[\"\']?\)$/, '') : '';
  4372. }
  4373. });
  4374. /*
  4375. * @class Marker
  4376. * @inherits Interactive layer
  4377. * @aka L.Marker
  4378. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  4379. *
  4380. * @example
  4381. *
  4382. * ```js
  4383. * L.marker([50.5, 30.5]).addTo(map);
  4384. * ```
  4385. */
  4386. L.Marker = L.Layer.extend({
  4387. // @section
  4388. // @aka Marker options
  4389. options: {
  4390. // @option icon: Icon = *
  4391. // Icon class to use for rendering the marker. See [Icon documentation](#L.Icon) for details on how to customize the marker icon. If not specified, a new `L.Icon.Default` is used.
  4392. icon: new L.Icon.Default(),
  4393. // Option inherited from "Interactive layer" abstract class
  4394. interactive: true,
  4395. // @option draggable: Boolean = false
  4396. // Whether the marker is draggable with mouse/touch or not.
  4397. draggable: false,
  4398. // @option keyboard: Boolean = true
  4399. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  4400. keyboard: true,
  4401. // @option title: String = ''
  4402. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  4403. title: '',
  4404. // @option alt: String = ''
  4405. // Text for the `alt` attribute of the icon image (useful for accessibility).
  4406. alt: '',
  4407. // @option zIndexOffset: Number = 0
  4408. // 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).
  4409. zIndexOffset: 0,
  4410. // @option opacity: Number = 1.0
  4411. // The opacity of the marker.
  4412. opacity: 1,
  4413. // @option riseOnHover: Boolean = false
  4414. // If `true`, the marker will get on top of others when you hover the mouse over it.
  4415. riseOnHover: false,
  4416. // @option riseOffset: Number = 250
  4417. // The z-index offset used for the `riseOnHover` feature.
  4418. riseOffset: 250,
  4419. // @option pane: String = 'markerPane'
  4420. // `Map pane` where the markers icon will be added.
  4421. pane: 'markerPane',
  4422. // FIXME: shadowPane is no longer a valid option
  4423. nonBubblingEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu']
  4424. },
  4425. /* @section
  4426. *
  4427. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  4428. */
  4429. initialize: function (latlng, options) {
  4430. L.setOptions(this, options);
  4431. this._latlng = L.latLng(latlng);
  4432. },
  4433. onAdd: function (map) {
  4434. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  4435. if (this._zoomAnimated) {
  4436. map.on('zoomanim', this._animateZoom, this);
  4437. }
  4438. this._initIcon();
  4439. this.update();
  4440. },
  4441. onRemove: function (map) {
  4442. if (this.dragging && this.dragging.enabled()) {
  4443. this.options.draggable = true;
  4444. this.dragging.removeHooks();
  4445. }
  4446. if (this._zoomAnimated) {
  4447. map.off('zoomanim', this._animateZoom, this);
  4448. }
  4449. this._removeIcon();
  4450. this._removeShadow();
  4451. },
  4452. getEvents: function () {
  4453. return {
  4454. zoom: this.update,
  4455. viewreset: this.update
  4456. };
  4457. },
  4458. // @method getLatLng: LatLng
  4459. // Returns the current geographical position of the marker.
  4460. getLatLng: function () {
  4461. return this._latlng;
  4462. },
  4463. // @method setLatLng(latlng: LatLng): this
  4464. // Changes the marker position to the given point.
  4465. setLatLng: function (latlng) {
  4466. var oldLatLng = this._latlng;
  4467. this._latlng = L.latLng(latlng);
  4468. this.update();
  4469. // @event move: Event
  4470. // 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`.
  4471. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  4472. },
  4473. // @method setZIndexOffset(offset: Number): this
  4474. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  4475. setZIndexOffset: function (offset) {
  4476. this.options.zIndexOffset = offset;
  4477. return this.update();
  4478. },
  4479. // @method setIcon(icon: Icon): this
  4480. // Changes the marker icon.
  4481. setIcon: function (icon) {
  4482. this.options.icon = icon;
  4483. if (this._map) {
  4484. this._initIcon();
  4485. this.update();
  4486. }
  4487. if (this._popup) {
  4488. this.bindPopup(this._popup, this._popup.options);
  4489. }
  4490. return this;
  4491. },
  4492. getElement: function () {
  4493. return this._icon;
  4494. },
  4495. update: function () {
  4496. if (this._icon) {
  4497. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  4498. this._setPos(pos);
  4499. }
  4500. return this;
  4501. },
  4502. _initIcon: function () {
  4503. var options = this.options,
  4504. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  4505. var icon = options.icon.createIcon(this._icon),
  4506. addIcon = false;
  4507. // if we're not reusing the icon, remove the old one and init new one
  4508. if (icon !== this._icon) {
  4509. if (this._icon) {
  4510. this._removeIcon();
  4511. }
  4512. addIcon = true;
  4513. if (options.title) {
  4514. icon.title = options.title;
  4515. }
  4516. if (options.alt) {
  4517. icon.alt = options.alt;
  4518. }
  4519. }
  4520. L.DomUtil.addClass(icon, classToAdd);
  4521. if (options.keyboard) {
  4522. icon.tabIndex = '0';
  4523. }
  4524. this._icon = icon;
  4525. if (options.riseOnHover) {
  4526. this.on({
  4527. mouseover: this._bringToFront,
  4528. mouseout: this._resetZIndex
  4529. });
  4530. }
  4531. var newShadow = options.icon.createShadow(this._shadow),
  4532. addShadow = false;
  4533. if (newShadow !== this._shadow) {
  4534. this._removeShadow();
  4535. addShadow = true;
  4536. }
  4537. if (newShadow) {
  4538. L.DomUtil.addClass(newShadow, classToAdd);
  4539. }
  4540. this._shadow = newShadow;
  4541. if (options.opacity < 1) {
  4542. this._updateOpacity();
  4543. }
  4544. if (addIcon) {
  4545. this.getPane().appendChild(this._icon);
  4546. }
  4547. this._initInteraction();
  4548. if (newShadow && addShadow) {
  4549. this.getPane('shadowPane').appendChild(this._shadow);
  4550. }
  4551. },
  4552. _removeIcon: function () {
  4553. if (this.options.riseOnHover) {
  4554. this.off({
  4555. mouseover: this._bringToFront,
  4556. mouseout: this._resetZIndex
  4557. });
  4558. }
  4559. L.DomUtil.remove(this._icon);
  4560. this.removeInteractiveTarget(this._icon);
  4561. this._icon = null;
  4562. },
  4563. _removeShadow: function () {
  4564. if (this._shadow) {
  4565. L.DomUtil.remove(this._shadow);
  4566. }
  4567. this._shadow = null;
  4568. },
  4569. _setPos: function (pos) {
  4570. L.DomUtil.setPosition(this._icon, pos);
  4571. if (this._shadow) {
  4572. L.DomUtil.setPosition(this._shadow, pos);
  4573. }
  4574. this._zIndex = pos.y + this.options.zIndexOffset;
  4575. this._resetZIndex();
  4576. },
  4577. _updateZIndex: function (offset) {
  4578. this._icon.style.zIndex = this._zIndex + offset;
  4579. },
  4580. _animateZoom: function (opt) {
  4581. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  4582. this._setPos(pos);
  4583. },
  4584. _initInteraction: function () {
  4585. if (!this.options.interactive) { return; }
  4586. L.DomUtil.addClass(this._icon, 'leaflet-interactive');
  4587. this.addInteractiveTarget(this._icon);
  4588. if (L.Handler.MarkerDrag) {
  4589. var draggable = this.options.draggable;
  4590. if (this.dragging) {
  4591. draggable = this.dragging.enabled();
  4592. this.dragging.disable();
  4593. }
  4594. this.dragging = new L.Handler.MarkerDrag(this);
  4595. if (draggable) {
  4596. this.dragging.enable();
  4597. }
  4598. }
  4599. },
  4600. // @method setOpacity(opacity: Number): this
  4601. // Changes the opacity of the marker.
  4602. setOpacity: function (opacity) {
  4603. this.options.opacity = opacity;
  4604. if (this._map) {
  4605. this._updateOpacity();
  4606. }
  4607. return this;
  4608. },
  4609. _updateOpacity: function () {
  4610. var opacity = this.options.opacity;
  4611. L.DomUtil.setOpacity(this._icon, opacity);
  4612. if (this._shadow) {
  4613. L.DomUtil.setOpacity(this._shadow, opacity);
  4614. }
  4615. },
  4616. _bringToFront: function () {
  4617. this._updateZIndex(this.options.riseOffset);
  4618. },
  4619. _resetZIndex: function () {
  4620. this._updateZIndex(0);
  4621. }
  4622. });
  4623. // factory L.marker(latlng: LatLng, options? : Marker options)
  4624. // @factory L.marker(latlng: LatLng, options? : Marker options)
  4625. // Instantiates a Marker object given a geographical point and optionally an options object.
  4626. L.marker = function (latlng, options) {
  4627. return new L.Marker(latlng, options);
  4628. };
  4629. /*
  4630. * @class DivIcon
  4631. * @aka L.DivIcon
  4632. * @inherits Icon
  4633. *
  4634. * Represents a lightweight icon for markers that uses a simple `<div>`
  4635. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  4636. *
  4637. * @example
  4638. * ```js
  4639. * var myIcon = L.divIcon({className: 'my-div-icon'});
  4640. * // you can set .my-div-icon styles in CSS
  4641. *
  4642. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  4643. * ```
  4644. *
  4645. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  4646. */
  4647. L.DivIcon = L.Icon.extend({
  4648. options: {
  4649. // @section
  4650. // @aka DivIcon options
  4651. iconSize: [12, 12], // also can be set through CSS
  4652. // iconAnchor: (Point),
  4653. // popupAnchor: (Point),
  4654. // @option html: String = ''
  4655. // Custom HTML code to put inside the div element, empty by default.
  4656. html: false,
  4657. // @option bgPos: Point = [0, 0]
  4658. // Optional relative position of the background, in pixels
  4659. bgPos: null,
  4660. className: 'leaflet-div-icon'
  4661. },
  4662. createIcon: function (oldIcon) {
  4663. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  4664. options = this.options;
  4665. div.innerHTML = options.html !== false ? options.html : '';
  4666. if (options.bgPos) {
  4667. var bgPos = L.point(options.bgPos);
  4668. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  4669. }
  4670. this._setIconStyles(div, 'icon');
  4671. return div;
  4672. },
  4673. createShadow: function () {
  4674. return null;
  4675. }
  4676. });
  4677. // @factory L.divIcon(options: DivIcon options)
  4678. // Creates a `DivIcon` instance with the given options.
  4679. L.divIcon = function (options) {
  4680. return new L.DivIcon(options);
  4681. };
  4682. /*
  4683. * @class DivOverlay
  4684. * @inherits Layer
  4685. * @aka L.DivOverlay
  4686. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  4687. */
  4688. // @namespace DivOverlay
  4689. L.DivOverlay = L.Layer.extend({
  4690. // @section
  4691. // @aka DivOverlay options
  4692. options: {
  4693. // @option offset: Point = Point(0, 7)
  4694. // The offset of the popup position. Useful to control the anchor
  4695. // of the popup when opening it on some overlays.
  4696. offset: [0, 7],
  4697. // @option className: String = ''
  4698. // A custom CSS class name to assign to the popup.
  4699. className: '',
  4700. // @option pane: String = 'popupPane'
  4701. // `Map pane` where the popup will be added.
  4702. pane: 'popupPane'
  4703. },
  4704. initialize: function (options, source) {
  4705. L.setOptions(this, options);
  4706. this._source = source;
  4707. },
  4708. onAdd: function (map) {
  4709. this._zoomAnimated = map._zoomAnimated;
  4710. if (!this._container) {
  4711. this._initLayout();
  4712. }
  4713. if (map._fadeAnimated) {
  4714. L.DomUtil.setOpacity(this._container, 0);
  4715. }
  4716. clearTimeout(this._removeTimeout);
  4717. this.getPane().appendChild(this._container);
  4718. this.update();
  4719. if (map._fadeAnimated) {
  4720. L.DomUtil.setOpacity(this._container, 1);
  4721. }
  4722. this.bringToFront();
  4723. },
  4724. onRemove: function (map) {
  4725. if (map._fadeAnimated) {
  4726. L.DomUtil.setOpacity(this._container, 0);
  4727. this._removeTimeout = setTimeout(L.bind(L.DomUtil.remove, L.DomUtil, this._container), 200);
  4728. } else {
  4729. L.DomUtil.remove(this._container);
  4730. }
  4731. },
  4732. // @namespace Popup
  4733. // @method getLatLng: LatLng
  4734. // Returns the geographical point of popup.
  4735. getLatLng: function () {
  4736. return this._latlng;
  4737. },
  4738. // @method setLatLng(latlng: LatLng): this
  4739. // Sets the geographical point where the popup will open.
  4740. setLatLng: function (latlng) {
  4741. this._latlng = L.latLng(latlng);
  4742. if (this._map) {
  4743. this._updatePosition();
  4744. this._adjustPan();
  4745. }
  4746. return this;
  4747. },
  4748. // @method getContent: String|HTMLElement
  4749. // Returns the content of the popup.
  4750. getContent: function () {
  4751. return this._content;
  4752. },
  4753. // @method setContent(htmlContent: String|HTMLElement|Function): this
  4754. // 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.
  4755. setContent: function (content) {
  4756. this._content = content;
  4757. this.update();
  4758. return this;
  4759. },
  4760. // @method getElement: String|HTMLElement
  4761. // Alias for [getContent()](#popup-getcontent)
  4762. getElement: function () {
  4763. return this._container;
  4764. },
  4765. // @method update: null
  4766. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  4767. update: function () {
  4768. if (!this._map) { return; }
  4769. this._container.style.visibility = 'hidden';
  4770. this._updateContent();
  4771. this._updateLayout();
  4772. this._updatePosition();
  4773. this._container.style.visibility = '';
  4774. this._adjustPan();
  4775. },
  4776. getEvents: function () {
  4777. var events = {
  4778. zoom: this._updatePosition,
  4779. viewreset: this._updatePosition
  4780. };
  4781. if (this._zoomAnimated) {
  4782. events.zoomanim = this._animateZoom;
  4783. }
  4784. return events;
  4785. },
  4786. // @method isOpen: Boolean
  4787. // Returns `true` when the popup is visible on the map.
  4788. isOpen: function () {
  4789. return !!this._map && this._map.hasLayer(this);
  4790. },
  4791. // @method bringToFront: this
  4792. // Brings this popup in front of other popups (in the same map pane).
  4793. bringToFront: function () {
  4794. if (this._map) {
  4795. L.DomUtil.toFront(this._container);
  4796. }
  4797. return this;
  4798. },
  4799. // @method bringToBack: this
  4800. // Brings this popup to the back of other popups (in the same map pane).
  4801. bringToBack: function () {
  4802. if (this._map) {
  4803. L.DomUtil.toBack(this._container);
  4804. }
  4805. return this;
  4806. },
  4807. _updateContent: function () {
  4808. if (!this._content) { return; }
  4809. var node = this._contentNode;
  4810. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  4811. if (typeof content === 'string') {
  4812. node.innerHTML = content;
  4813. } else {
  4814. while (node.hasChildNodes()) {
  4815. node.removeChild(node.firstChild);
  4816. }
  4817. node.appendChild(content);
  4818. }
  4819. this.fire('contentupdate');
  4820. },
  4821. _updatePosition: function () {
  4822. if (!this._map) { return; }
  4823. var pos = this._map.latLngToLayerPoint(this._latlng),
  4824. offset = L.point(this.options.offset),
  4825. anchor = this._getAnchor();
  4826. if (this._zoomAnimated) {
  4827. L.DomUtil.setPosition(this._container, pos.add(anchor));
  4828. } else {
  4829. offset = offset.add(pos).add(anchor);
  4830. }
  4831. var bottom = this._containerBottom = -offset.y,
  4832. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  4833. // bottom position the popup in case the height of the popup changes (images loading etc)
  4834. this._container.style.bottom = bottom + 'px';
  4835. this._container.style.left = left + 'px';
  4836. },
  4837. _getAnchor: function () {
  4838. return [0, 0];
  4839. }
  4840. });
  4841. /*
  4842. * @class Popup
  4843. * @inherits DivOverlay
  4844. * @aka L.Popup
  4845. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  4846. * open popups while making sure that only one popup is open at one time
  4847. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  4848. *
  4849. * @example
  4850. *
  4851. * If you want to just bind a popup to marker click and then open it, it's really easy:
  4852. *
  4853. * ```js
  4854. * marker.bindPopup(popupContent).openPopup();
  4855. * ```
  4856. * Path overlays like polylines also have a `bindPopup` method.
  4857. * Here's a more complicated way to open a popup on a map:
  4858. *
  4859. * ```js
  4860. * var popup = L.popup()
  4861. * .setLatLng(latlng)
  4862. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  4863. * .openOn(map);
  4864. * ```
  4865. */
  4866. // @namespace Popup
  4867. L.Popup = L.DivOverlay.extend({
  4868. // @section
  4869. // @aka Popup options
  4870. options: {
  4871. // @option maxWidth: Number = 300
  4872. // Max width of the popup, in pixels.
  4873. maxWidth: 300,
  4874. // @option minWidth: Number = 50
  4875. // Min width of the popup, in pixels.
  4876. minWidth: 50,
  4877. // @option maxHeight: Number = null
  4878. // If set, creates a scrollable container of the given height
  4879. // inside a popup if its content exceeds it.
  4880. maxHeight: null,
  4881. // @option autoPan: Boolean = true
  4882. // Set it to `false` if you don't want the map to do panning animation
  4883. // to fit the opened popup.
  4884. autoPan: true,
  4885. // @option autoPanPaddingTopLeft: Point = null
  4886. // The margin between the popup and the top left corner of the map
  4887. // view after autopanning was performed.
  4888. autoPanPaddingTopLeft: null,
  4889. // @option autoPanPaddingBottomRight: Point = null
  4890. // The margin between the popup and the bottom right corner of the map
  4891. // view after autopanning was performed.
  4892. autoPanPaddingBottomRight: null,
  4893. // @option autoPanPadding: Point = Point(5, 5)
  4894. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  4895. autoPanPadding: [5, 5],
  4896. // @option keepInView: Boolean = false
  4897. // Set it to `true` if you want to prevent users from panning the popup
  4898. // off of the screen while it is open.
  4899. keepInView: false,
  4900. // @option closeButton: Boolean = true
  4901. // Controls the presence of a close button in the popup.
  4902. closeButton: true,
  4903. // @option autoClose: Boolean = true
  4904. // Set it to `false` if you want to override the default behavior of
  4905. // the popup closing when user clicks the map (set globally by
  4906. // the Map's [closePopupOnClick](#map-closepopuponclick) option).
  4907. autoClose: true,
  4908. // @option className: String = ''
  4909. // A custom CSS class name to assign to the popup.
  4910. className: ''
  4911. },
  4912. // @namespace Popup
  4913. // @method openOn(map: Map): this
  4914. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  4915. openOn: function (map) {
  4916. map.openPopup(this);
  4917. return this;
  4918. },
  4919. onAdd: function (map) {
  4920. L.DivOverlay.prototype.onAdd.call(this, map);
  4921. // @namespace Map
  4922. // @section Popup events
  4923. // @event popupopen: PopupEvent
  4924. // Fired when a popup is opened in the map
  4925. map.fire('popupopen', {popup: this});
  4926. if (this._source) {
  4927. // @namespace Layer
  4928. // @section Popup events
  4929. // @event popupopen: PopupEvent
  4930. // Fired when a popup bound to this layer is opened
  4931. this._source.fire('popupopen', {popup: this}, true);
  4932. // For non-path layers, we toggle the popup when clicking
  4933. // again the layer, so prevent the map to reopen it.
  4934. if (!(this._source instanceof L.Path)) {
  4935. this._source.on('preclick', L.DomEvent.stopPropagation);
  4936. }
  4937. }
  4938. },
  4939. onRemove: function (map) {
  4940. L.DivOverlay.prototype.onRemove.call(this, map);
  4941. // @namespace Map
  4942. // @section Popup events
  4943. // @event popupclose: PopupEvent
  4944. // Fired when a popup in the map is closed
  4945. map.fire('popupclose', {popup: this});
  4946. if (this._source) {
  4947. // @namespace Layer
  4948. // @section Popup events
  4949. // @event popupclose: PopupEvent
  4950. // Fired when a popup bound to this layer is closed
  4951. this._source.fire('popupclose', {popup: this}, true);
  4952. if (!(this._source instanceof L.Path)) {
  4953. this._source.off('preclick', L.DomEvent.stopPropagation);
  4954. }
  4955. }
  4956. },
  4957. getEvents: function () {
  4958. var events = L.DivOverlay.prototype.getEvents.call(this);
  4959. if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  4960. events.preclick = this._close;
  4961. }
  4962. if (this.options.keepInView) {
  4963. events.moveend = this._adjustPan;
  4964. }
  4965. return events;
  4966. },
  4967. _close: function () {
  4968. if (this._map) {
  4969. this._map.closePopup(this);
  4970. }
  4971. },
  4972. _initLayout: function () {
  4973. var prefix = 'leaflet-popup',
  4974. container = this._container = L.DomUtil.create('div',
  4975. prefix + ' ' + (this.options.className || '') +
  4976. ' leaflet-zoom-animated');
  4977. if (this.options.closeButton) {
  4978. var closeButton = this._closeButton = L.DomUtil.create('a', prefix + '-close-button', container);
  4979. closeButton.href = '#close';
  4980. closeButton.innerHTML = '&#215;';
  4981. L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
  4982. }
  4983. var wrapper = this._wrapper = L.DomUtil.create('div', prefix + '-content-wrapper', container);
  4984. this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
  4985. L.DomEvent
  4986. .disableClickPropagation(wrapper)
  4987. .disableScrollPropagation(this._contentNode)
  4988. .on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
  4989. this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
  4990. this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
  4991. },
  4992. _updateLayout: function () {
  4993. var container = this._contentNode,
  4994. style = container.style;
  4995. style.width = '';
  4996. style.whiteSpace = 'nowrap';
  4997. var width = container.offsetWidth;
  4998. width = Math.min(width, this.options.maxWidth);
  4999. width = Math.max(width, this.options.minWidth);
  5000. style.width = (width + 1) + 'px';
  5001. style.whiteSpace = '';
  5002. style.height = '';
  5003. var height = container.offsetHeight,
  5004. maxHeight = this.options.maxHeight,
  5005. scrolledClass = 'leaflet-popup-scrolled';
  5006. if (maxHeight && height > maxHeight) {
  5007. style.height = maxHeight + 'px';
  5008. L.DomUtil.addClass(container, scrolledClass);
  5009. } else {
  5010. L.DomUtil.removeClass(container, scrolledClass);
  5011. }
  5012. this._containerWidth = this._container.offsetWidth;
  5013. },
  5014. _animateZoom: function (e) {
  5015. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  5016. anchor = this._getAnchor();
  5017. L.DomUtil.setPosition(this._container, pos.add(anchor));
  5018. },
  5019. _adjustPan: function () {
  5020. if (!this.options.autoPan || (this._map._panAnim && this._map._panAnim._inProgress)) { return; }
  5021. var map = this._map,
  5022. marginBottom = parseInt(L.DomUtil.getStyle(this._container, 'marginBottom'), 10) || 0,
  5023. containerHeight = this._container.offsetHeight + marginBottom,
  5024. containerWidth = this._containerWidth,
  5025. layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
  5026. layerPos._add(L.DomUtil.getPosition(this._container));
  5027. var containerPos = map.layerPointToContainerPoint(layerPos),
  5028. padding = L.point(this.options.autoPanPadding),
  5029. paddingTL = L.point(this.options.autoPanPaddingTopLeft || padding),
  5030. paddingBR = L.point(this.options.autoPanPaddingBottomRight || padding),
  5031. size = map.getSize(),
  5032. dx = 0,
  5033. dy = 0;
  5034. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  5035. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  5036. }
  5037. if (containerPos.x - dx - paddingTL.x < 0) { // left
  5038. dx = containerPos.x - paddingTL.x;
  5039. }
  5040. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  5041. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  5042. }
  5043. if (containerPos.y - dy - paddingTL.y < 0) { // top
  5044. dy = containerPos.y - paddingTL.y;
  5045. }
  5046. // @namespace Map
  5047. // @section Popup events
  5048. // @event autopanstart: Event
  5049. // Fired when the map starts autopanning when opening a popup.
  5050. if (dx || dy) {
  5051. map
  5052. .fire('autopanstart')
  5053. .panBy([dx, dy]);
  5054. }
  5055. },
  5056. _onCloseButtonClick: function (e) {
  5057. this._close();
  5058. L.DomEvent.stop(e);
  5059. },
  5060. _getAnchor: function () {
  5061. // Where should we anchor the popup on the source layer?
  5062. return L.point(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  5063. }
  5064. });
  5065. // @namespace Popup
  5066. // @factory L.popup(options?: Popup options, source?: Layer)
  5067. // 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.
  5068. L.popup = function (options, source) {
  5069. return new L.Popup(options, source);
  5070. };
  5071. /* @namespace Map
  5072. * @section Interaction Options
  5073. * @option closePopupOnClick: Boolean = true
  5074. * Set it to `false` if you don't want popups to close when user clicks the map.
  5075. */
  5076. L.Map.mergeOptions({
  5077. closePopupOnClick: true
  5078. });
  5079. // @namespace Map
  5080. // @section Methods for Layers and Controls
  5081. L.Map.include({
  5082. // @method openPopup(popup: Popup): this
  5083. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  5084. // @alternative
  5085. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  5086. // Creates a popup with the specified content and options and opens it in the given point on a map.
  5087. openPopup: function (popup, latlng, options) {
  5088. if (!(popup instanceof L.Popup)) {
  5089. popup = new L.Popup(options).setContent(popup);
  5090. }
  5091. if (latlng) {
  5092. popup.setLatLng(latlng);
  5093. }
  5094. if (this.hasLayer(popup)) {
  5095. return this;
  5096. }
  5097. if (this._popup && this._popup.options.autoClose) {
  5098. this.closePopup();
  5099. }
  5100. this._popup = popup;
  5101. return this.addLayer(popup);
  5102. },
  5103. // @method closePopup(popup?: Popup): this
  5104. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  5105. closePopup: function (popup) {
  5106. if (!popup || popup === this._popup) {
  5107. popup = this._popup;
  5108. this._popup = null;
  5109. }
  5110. if (popup) {
  5111. this.removeLayer(popup);
  5112. }
  5113. return this;
  5114. }
  5115. });
  5116. /*
  5117. * @namespace Layer
  5118. * @section Popup methods example
  5119. *
  5120. * All layers share a set of methods convenient for binding popups to it.
  5121. *
  5122. * ```js
  5123. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  5124. * layer.openPopup();
  5125. * layer.closePopup();
  5126. * ```
  5127. *
  5128. * 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.
  5129. */
  5130. // @section Popup methods
  5131. L.Layer.include({
  5132. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  5133. // Binds a popup to the layer with the passed `content` and sets up the
  5134. // neccessary event listeners. If a `Function` is passed it will receive
  5135. // the layer as the first argument and should return a `String` or `HTMLElement`.
  5136. bindPopup: function (content, options) {
  5137. if (content instanceof L.Popup) {
  5138. L.setOptions(content, options);
  5139. this._popup = content;
  5140. content._source = this;
  5141. } else {
  5142. if (!this._popup || options) {
  5143. this._popup = new L.Popup(options, this);
  5144. }
  5145. this._popup.setContent(content);
  5146. }
  5147. if (!this._popupHandlersAdded) {
  5148. this.on({
  5149. click: this._openPopup,
  5150. remove: this.closePopup,
  5151. move: this._movePopup
  5152. });
  5153. this._popupHandlersAdded = true;
  5154. }
  5155. return this;
  5156. },
  5157. // @method unbindPopup(): this
  5158. // Removes the popup previously bound with `bindPopup`.
  5159. unbindPopup: function () {
  5160. if (this._popup) {
  5161. this.off({
  5162. click: this._openPopup,
  5163. remove: this.closePopup,
  5164. move: this._movePopup
  5165. });
  5166. this._popupHandlersAdded = false;
  5167. this._popup = null;
  5168. }
  5169. return this;
  5170. },
  5171. // @method openPopup(latlng?: LatLng): this
  5172. // Opens the bound popup at the specificed `latlng` or at the default popup anchor if no `latlng` is passed.
  5173. openPopup: function (layer, latlng) {
  5174. if (!(layer instanceof L.Layer)) {
  5175. latlng = layer;
  5176. layer = this;
  5177. }
  5178. if (layer instanceof L.FeatureGroup) {
  5179. for (var id in this._layers) {
  5180. layer = this._layers[id];
  5181. break;
  5182. }
  5183. }
  5184. if (!latlng) {
  5185. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  5186. }
  5187. if (this._popup && this._map) {
  5188. // set popup source to this layer
  5189. this._popup._source = layer;
  5190. // update the popup (content, layout, ect...)
  5191. this._popup.update();
  5192. // open the popup on the map
  5193. this._map.openPopup(this._popup, latlng);
  5194. }
  5195. return this;
  5196. },
  5197. // @method closePopup(): this
  5198. // Closes the popup bound to this layer if it is open.
  5199. closePopup: function () {
  5200. if (this._popup) {
  5201. this._popup._close();
  5202. }
  5203. return this;
  5204. },
  5205. // @method togglePopup(): this
  5206. // Opens or closes the popup bound to this layer depending on its current state.
  5207. togglePopup: function (target) {
  5208. if (this._popup) {
  5209. if (this._popup._map) {
  5210. this.closePopup();
  5211. } else {
  5212. this.openPopup(target);
  5213. }
  5214. }
  5215. return this;
  5216. },
  5217. // @method isPopupOpen(): boolean
  5218. // Returns `true` if the popup bound to this layer is currently open.
  5219. isPopupOpen: function () {
  5220. return this._popup.isOpen();
  5221. },
  5222. // @method setPopupContent(content: String|HTMLElement|Popup): this
  5223. // Sets the content of the popup bound to this layer.
  5224. setPopupContent: function (content) {
  5225. if (this._popup) {
  5226. this._popup.setContent(content);
  5227. }
  5228. return this;
  5229. },
  5230. // @method getPopup(): Popup
  5231. // Returns the popup bound to this layer.
  5232. getPopup: function () {
  5233. return this._popup;
  5234. },
  5235. _openPopup: function (e) {
  5236. var layer = e.layer || e.target;
  5237. if (!this._popup) {
  5238. return;
  5239. }
  5240. if (!this._map) {
  5241. return;
  5242. }
  5243. // prevent map click
  5244. L.DomEvent.stop(e);
  5245. // if this inherits from Path its a vector and we can just
  5246. // open the popup at the new location
  5247. if (layer instanceof L.Path) {
  5248. this.openPopup(e.layer || e.target, e.latlng);
  5249. return;
  5250. }
  5251. // otherwise treat it like a marker and figure out
  5252. // if we should toggle it open/closed
  5253. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  5254. this.closePopup();
  5255. } else {
  5256. this.openPopup(layer, e.latlng);
  5257. }
  5258. },
  5259. _movePopup: function (e) {
  5260. this._popup.setLatLng(e.latlng);
  5261. }
  5262. });
  5263. /*
  5264. * Popup extension to L.Marker, adding popup-related methods.
  5265. */
  5266. L.Marker.include({
  5267. _getPopupAnchor: function () {
  5268. return this.options.icon.options.popupAnchor || [0, 0];
  5269. }
  5270. });
  5271. /*
  5272. * @class Tooltip
  5273. * @inherits DivOverlay
  5274. * @aka L.Tooltip
  5275. * Used to display small texts on top of map layers.
  5276. *
  5277. * @example
  5278. *
  5279. * ```js
  5280. * marker.bindTooltip("my tooltip text").openTooltip();
  5281. * ```
  5282. * Note about tooltip offset. Leaflet takes two options in consideration
  5283. * for computing tooltip offseting:
  5284. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  5285. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  5286. * move it to the bottom. Negatives will move to the left and top.
  5287. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  5288. * should adapt this value if you use a custom icon.
  5289. */
  5290. // @namespace Tooltip
  5291. L.Tooltip = L.DivOverlay.extend({
  5292. // @section
  5293. // @aka Tooltip options
  5294. options: {
  5295. // @option pane: String = 'tooltipPane'
  5296. // `Map pane` where the tooltip will be added.
  5297. pane: 'tooltipPane',
  5298. // @option offset: Point = Point(0, 0)
  5299. // Optional offset of the tooltip position.
  5300. offset: [0, 0],
  5301. // @option direction: String = 'auto'
  5302. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  5303. // `top`, `bottom`, `center`, `auto`.
  5304. // `auto` will dynamicaly switch between `right` and `left` according to the tooltip
  5305. // position on the map.
  5306. direction: 'auto',
  5307. // @option permanent: Boolean = false
  5308. // Whether to open the tooltip permanently or only on mouseover.
  5309. permanent: false,
  5310. // @option sticky: Boolean = false
  5311. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  5312. sticky: false,
  5313. // @option interactive: Boolean = false
  5314. // If true, the tooltip will listen to the feature events.
  5315. interactive: false,
  5316. // @option opacity: Number = 0.9
  5317. // Tooltip container opacity.
  5318. opacity: 0.9
  5319. },
  5320. onAdd: function (map) {
  5321. L.DivOverlay.prototype.onAdd.call(this, map);
  5322. this.setOpacity(this.options.opacity);
  5323. // @namespace Map
  5324. // @section Tooltip events
  5325. // @event tooltipopen: TooltipEvent
  5326. // Fired when a tooltip is opened in the map.
  5327. map.fire('tooltipopen', {tooltip: this});
  5328. if (this._source) {
  5329. // @namespace Layer
  5330. // @section Tooltip events
  5331. // @event tooltipopen: TooltipEvent
  5332. // Fired when a tooltip bound to this layer is opened.
  5333. this._source.fire('tooltipopen', {tooltip: this}, true);
  5334. }
  5335. },
  5336. onRemove: function (map) {
  5337. L.DivOverlay.prototype.onRemove.call(this, map);
  5338. // @namespace Map
  5339. // @section Tooltip events
  5340. // @event tooltipclose: TooltipEvent
  5341. // Fired when a tooltip in the map is closed.
  5342. map.fire('tooltipclose', {tooltip: this});
  5343. if (this._source) {
  5344. // @namespace Layer
  5345. // @section Tooltip events
  5346. // @event tooltipclose: TooltipEvent
  5347. // Fired when a tooltip bound to this layer is closed.
  5348. this._source.fire('tooltipclose', {tooltip: this}, true);
  5349. }
  5350. },
  5351. getEvents: function () {
  5352. var events = L.DivOverlay.prototype.getEvents.call(this);
  5353. if (L.Browser.touch && !this.options.permanent) {
  5354. events.preclick = this._close;
  5355. }
  5356. return events;
  5357. },
  5358. _close: function () {
  5359. if (this._map) {
  5360. this._map.closeTooltip(this);
  5361. }
  5362. },
  5363. _initLayout: function () {
  5364. var prefix = 'leaflet-tooltip',
  5365. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  5366. this._contentNode = this._container = L.DomUtil.create('div', className);
  5367. },
  5368. _updateLayout: function () {},
  5369. _adjustPan: function () {},
  5370. _setPosition: function (pos) {
  5371. var map = this._map,
  5372. container = this._container,
  5373. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  5374. tooltipPoint = map.layerPointToContainerPoint(pos),
  5375. direction = this.options.direction,
  5376. tooltipWidth = container.offsetWidth,
  5377. tooltipHeight = container.offsetHeight,
  5378. offset = L.point(this.options.offset),
  5379. anchor = this._getAnchor();
  5380. if (direction === 'top') {
  5381. pos = pos.add(L.point(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y));
  5382. } else if (direction === 'bottom') {
  5383. pos = pos.subtract(L.point(tooltipWidth / 2 - offset.x, -offset.y));
  5384. } else if (direction === 'center') {
  5385. pos = pos.subtract(L.point(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y));
  5386. } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
  5387. direction = 'right';
  5388. pos = pos.add([offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y]);
  5389. } else {
  5390. direction = 'left';
  5391. pos = pos.subtract(L.point(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y));
  5392. }
  5393. L.DomUtil.removeClass(container, 'leaflet-tooltip-right');
  5394. L.DomUtil.removeClass(container, 'leaflet-tooltip-left');
  5395. L.DomUtil.removeClass(container, 'leaflet-tooltip-top');
  5396. L.DomUtil.removeClass(container, 'leaflet-tooltip-bottom');
  5397. L.DomUtil.addClass(container, 'leaflet-tooltip-' + direction);
  5398. L.DomUtil.setPosition(container, pos);
  5399. },
  5400. _updatePosition: function () {
  5401. var pos = this._map.latLngToLayerPoint(this._latlng);
  5402. this._setPosition(pos);
  5403. },
  5404. setOpacity: function (opacity) {
  5405. this.options.opacity = opacity;
  5406. if (this._container) {
  5407. L.DomUtil.setOpacity(this._container, opacity);
  5408. }
  5409. },
  5410. _animateZoom: function (e) {
  5411. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  5412. this._setPosition(pos);
  5413. },
  5414. _getAnchor: function () {
  5415. // Where should we anchor the tooltip on the source layer?
  5416. return L.point(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  5417. }
  5418. });
  5419. // @namespace Tooltip
  5420. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  5421. // 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.
  5422. L.tooltip = function (options, source) {
  5423. return new L.Tooltip(options, source);
  5424. };
  5425. // @namespace Map
  5426. // @section Methods for Layers and Controls
  5427. L.Map.include({
  5428. // @method openTooltip(tooltip: Tooltip): this
  5429. // Opens the specified tooltip.
  5430. // @alternative
  5431. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  5432. // Creates a tooltip with the specified content and options and open it.
  5433. openTooltip: function (tooltip, latlng, options) {
  5434. if (!(tooltip instanceof L.Tooltip)) {
  5435. tooltip = new L.Tooltip(options).setContent(tooltip);
  5436. }
  5437. if (latlng) {
  5438. tooltip.setLatLng(latlng);
  5439. }
  5440. if (this.hasLayer(tooltip)) {
  5441. return this;
  5442. }
  5443. return this.addLayer(tooltip);
  5444. },
  5445. // @method closeTooltip(tooltip?: Tooltip): this
  5446. // Closes the tooltip given as parameter.
  5447. closeTooltip: function (tooltip) {
  5448. if (tooltip) {
  5449. this.removeLayer(tooltip);
  5450. }
  5451. return this;
  5452. }
  5453. });
  5454. /*
  5455. * @namespace Layer
  5456. * @section Tooltip methods example
  5457. *
  5458. * All layers share a set of methods convenient for binding tooltips to it.
  5459. *
  5460. * ```js
  5461. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  5462. * layer.openTooltip();
  5463. * layer.closeTooltip();
  5464. * ```
  5465. */
  5466. // @section Tooltip methods
  5467. L.Layer.include({
  5468. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  5469. // Binds a tooltip to the layer with the passed `content` and sets up the
  5470. // neccessary event listeners. If a `Function` is passed it will receive
  5471. // the layer as the first argument and should return a `String` or `HTMLElement`.
  5472. bindTooltip: function (content, options) {
  5473. if (content instanceof L.Tooltip) {
  5474. L.setOptions(content, options);
  5475. this._tooltip = content;
  5476. content._source = this;
  5477. } else {
  5478. if (!this._tooltip || options) {
  5479. this._tooltip = L.tooltip(options, this);
  5480. }
  5481. this._tooltip.setContent(content);
  5482. }
  5483. this._initTooltipInteractions();
  5484. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  5485. this.openTooltip();
  5486. }
  5487. return this;
  5488. },
  5489. // @method unbindTooltip(): this
  5490. // Removes the tooltip previously bound with `bindTooltip`.
  5491. unbindTooltip: function () {
  5492. if (this._tooltip) {
  5493. this._initTooltipInteractions(true);
  5494. this.closeTooltip();
  5495. this._tooltip = null;
  5496. }
  5497. return this;
  5498. },
  5499. _initTooltipInteractions: function (remove) {
  5500. if (!remove && this._tooltipHandlersAdded) { return; }
  5501. var onOff = remove ? 'off' : 'on',
  5502. events = {
  5503. remove: this.closeTooltip,
  5504. move: this._moveTooltip
  5505. };
  5506. if (!this._tooltip.options.permanent) {
  5507. events.mouseover = this._openTooltip;
  5508. events.mouseout = this.closeTooltip;
  5509. if (this._tooltip.options.sticky) {
  5510. events.mousemove = this._moveTooltip;
  5511. }
  5512. if (L.Browser.touch) {
  5513. events.click = this._openTooltip;
  5514. }
  5515. } else {
  5516. events.add = this._openTooltip;
  5517. }
  5518. this[onOff](events);
  5519. this._tooltipHandlersAdded = !remove;
  5520. },
  5521. // @method openTooltip(latlng?: LatLng): this
  5522. // Opens the bound tooltip at the specificed `latlng` or at the default tooltip anchor if no `latlng` is passed.
  5523. openTooltip: function (layer, latlng) {
  5524. if (!(layer instanceof L.Layer)) {
  5525. latlng = layer;
  5526. layer = this;
  5527. }
  5528. if (layer instanceof L.FeatureGroup) {
  5529. for (var id in this._layers) {
  5530. layer = this._layers[id];
  5531. break;
  5532. }
  5533. }
  5534. if (!latlng) {
  5535. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  5536. }
  5537. if (this._tooltip && this._map) {
  5538. // set tooltip source to this layer
  5539. this._tooltip._source = layer;
  5540. // update the tooltip (content, layout, ect...)
  5541. this._tooltip.update();
  5542. // open the tooltip on the map
  5543. this._map.openTooltip(this._tooltip, latlng);
  5544. // Tooltip container may not be defined if not permanent and never
  5545. // opened.
  5546. if (this._tooltip.options.interactive && this._tooltip._container) {
  5547. L.DomUtil.addClass(this._tooltip._container, 'leaflet-clickable');
  5548. this.addInteractiveTarget(this._tooltip._container);
  5549. }
  5550. }
  5551. return this;
  5552. },
  5553. // @method closeTooltip(): this
  5554. // Closes the tooltip bound to this layer if it is open.
  5555. closeTooltip: function () {
  5556. if (this._tooltip) {
  5557. this._tooltip._close();
  5558. if (this._tooltip.options.interactive && this._tooltip._container) {
  5559. L.DomUtil.removeClass(this._tooltip._container, 'leaflet-clickable');
  5560. this.removeInteractiveTarget(this._tooltip._container);
  5561. }
  5562. }
  5563. return this;
  5564. },
  5565. // @method toggleTooltip(): this
  5566. // Opens or closes the tooltip bound to this layer depending on its current state.
  5567. toggleTooltip: function (target) {
  5568. if (this._tooltip) {
  5569. if (this._tooltip._map) {
  5570. this.closeTooltip();
  5571. } else {
  5572. this.openTooltip(target);
  5573. }
  5574. }
  5575. return this;
  5576. },
  5577. // @method isTooltipOpen(): boolean
  5578. // Returns `true` if the tooltip bound to this layer is currently open.
  5579. isTooltipOpen: function () {
  5580. return this._tooltip.isOpen();
  5581. },
  5582. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  5583. // Sets the content of the tooltip bound to this layer.
  5584. setTooltipContent: function (content) {
  5585. if (this._tooltip) {
  5586. this._tooltip.setContent(content);
  5587. }
  5588. return this;
  5589. },
  5590. // @method getTooltip(): Tooltip
  5591. // Returns the tooltip bound to this layer.
  5592. getTooltip: function () {
  5593. return this._tooltip;
  5594. },
  5595. _openTooltip: function (e) {
  5596. var layer = e.layer || e.target;
  5597. if (!this._tooltip || !this._map) {
  5598. return;
  5599. }
  5600. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  5601. },
  5602. _moveTooltip: function (e) {
  5603. var latlng = e.latlng, containerPoint, layerPoint;
  5604. if (this._tooltip.options.sticky && e.originalEvent) {
  5605. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  5606. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  5607. latlng = this._map.layerPointToLatLng(layerPoint);
  5608. }
  5609. this._tooltip.setLatLng(latlng);
  5610. }
  5611. });
  5612. /*
  5613. * Tooltip extension to L.Marker, adding tooltip-related methods.
  5614. */
  5615. L.Marker.include({
  5616. _getTooltipAnchor: function () {
  5617. return this.options.icon.options.tooltipAnchor || [0, 0];
  5618. }
  5619. });
  5620. /*
  5621. * @class LayerGroup
  5622. * @aka L.LayerGroup
  5623. * @inherits Layer
  5624. *
  5625. * Used to group several layers and handle them as one. If you add it to the map,
  5626. * any layers added or removed from the group will be added/removed on the map as
  5627. * well. Extends `Layer`.
  5628. *
  5629. * @example
  5630. *
  5631. * ```js
  5632. * L.layerGroup([marker1, marker2])
  5633. * .addLayer(polyline)
  5634. * .addTo(map);
  5635. * ```
  5636. */
  5637. L.LayerGroup = L.Layer.extend({
  5638. initialize: function (layers) {
  5639. this._layers = {};
  5640. var i, len;
  5641. if (layers) {
  5642. for (i = 0, len = layers.length; i < len; i++) {
  5643. this.addLayer(layers[i]);
  5644. }
  5645. }
  5646. },
  5647. // @method addLayer(layer: Layer): this
  5648. // Adds the given layer to the group.
  5649. addLayer: function (layer) {
  5650. var id = this.getLayerId(layer);
  5651. this._layers[id] = layer;
  5652. if (this._map) {
  5653. this._map.addLayer(layer);
  5654. }
  5655. return this;
  5656. },
  5657. // @method removeLayer(layer: Layer): this
  5658. // Removes the given layer from the group.
  5659. // @alternative
  5660. // @method removeLayer(id: Number): this
  5661. // Removes the layer with the given internal ID from the group.
  5662. removeLayer: function (layer) {
  5663. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5664. if (this._map && this._layers[id]) {
  5665. this._map.removeLayer(this._layers[id]);
  5666. }
  5667. delete this._layers[id];
  5668. return this;
  5669. },
  5670. // @method hasLayer(layer: Layer): Boolean
  5671. // Returns `true` if the given layer is currently added to the group.
  5672. hasLayer: function (layer) {
  5673. return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
  5674. },
  5675. // @method clearLayers(): this
  5676. // Removes all the layers from the group.
  5677. clearLayers: function () {
  5678. for (var i in this._layers) {
  5679. this.removeLayer(this._layers[i]);
  5680. }
  5681. return this;
  5682. },
  5683. // @method invoke(methodName: String, …): this
  5684. // Calls `methodName` on every layer contained in this group, passing any
  5685. // additional parameters. Has no effect if the layers contained do not
  5686. // implement `methodName`.
  5687. invoke: function (methodName) {
  5688. var args = Array.prototype.slice.call(arguments, 1),
  5689. i, layer;
  5690. for (i in this._layers) {
  5691. layer = this._layers[i];
  5692. if (layer[methodName]) {
  5693. layer[methodName].apply(layer, args);
  5694. }
  5695. }
  5696. return this;
  5697. },
  5698. onAdd: function (map) {
  5699. for (var i in this._layers) {
  5700. map.addLayer(this._layers[i]);
  5701. }
  5702. },
  5703. onRemove: function (map) {
  5704. for (var i in this._layers) {
  5705. map.removeLayer(this._layers[i]);
  5706. }
  5707. },
  5708. // @method eachLayer(fn: Function, context?: Object): this
  5709. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5710. // ```js
  5711. // group.eachLayer(function (layer) {
  5712. // layer.bindPopup('Hello');
  5713. // });
  5714. // ```
  5715. eachLayer: function (method, context) {
  5716. for (var i in this._layers) {
  5717. method.call(context, this._layers[i]);
  5718. }
  5719. return this;
  5720. },
  5721. // @method getLayer(id: Number): Layer
  5722. // Returns the layer with the given internal ID.
  5723. getLayer: function (id) {
  5724. return this._layers[id];
  5725. },
  5726. // @method getLayers(): Layer[]
  5727. // Returns an array of all the layers added to the group.
  5728. getLayers: function () {
  5729. var layers = [];
  5730. for (var i in this._layers) {
  5731. layers.push(this._layers[i]);
  5732. }
  5733. return layers;
  5734. },
  5735. // @method setZIndex(zIndex: Number): this
  5736. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5737. setZIndex: function (zIndex) {
  5738. return this.invoke('setZIndex', zIndex);
  5739. },
  5740. // @method getLayerId(layer: Layer): Number
  5741. // Returns the internal ID for a layer
  5742. getLayerId: function (layer) {
  5743. return L.stamp(layer);
  5744. }
  5745. });
  5746. // @factory L.layerGroup(layers: Layer[])
  5747. // Create a layer group, optionally given an initial set of layers.
  5748. L.layerGroup = function (layers) {
  5749. return new L.LayerGroup(layers);
  5750. };
  5751. /*
  5752. * @class FeatureGroup
  5753. * @aka L.FeatureGroup
  5754. * @inherits LayerGroup
  5755. *
  5756. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5757. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5758. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5759. * handler, it will handle events from any of the layers. This includes mouse events
  5760. * and custom events.
  5761. * * Has `layeradd` and `layerremove` events
  5762. *
  5763. * @example
  5764. *
  5765. * ```js
  5766. * L.featureGroup([marker1, marker2, polyline])
  5767. * .bindPopup('Hello world!')
  5768. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5769. * .addTo(map);
  5770. * ```
  5771. */
  5772. L.FeatureGroup = L.LayerGroup.extend({
  5773. addLayer: function (layer) {
  5774. if (this.hasLayer(layer)) {
  5775. return this;
  5776. }
  5777. layer.addEventParent(this);
  5778. L.LayerGroup.prototype.addLayer.call(this, layer);
  5779. // @event layeradd: LayerEvent
  5780. // Fired when a layer is added to this `FeatureGroup`
  5781. return this.fire('layeradd', {layer: layer});
  5782. },
  5783. removeLayer: function (layer) {
  5784. if (!this.hasLayer(layer)) {
  5785. return this;
  5786. }
  5787. if (layer in this._layers) {
  5788. layer = this._layers[layer];
  5789. }
  5790. layer.removeEventParent(this);
  5791. L.LayerGroup.prototype.removeLayer.call(this, layer);
  5792. // @event layerremove: LayerEvent
  5793. // Fired when a layer is removed from this `FeatureGroup`
  5794. return this.fire('layerremove', {layer: layer});
  5795. },
  5796. // @method setStyle(style: Path options): this
  5797. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5798. setStyle: function (style) {
  5799. return this.invoke('setStyle', style);
  5800. },
  5801. // @method bringToFront(): this
  5802. // Brings the layer group to the top of all other layers
  5803. bringToFront: function () {
  5804. return this.invoke('bringToFront');
  5805. },
  5806. // @method bringToBack(): this
  5807. // Brings the layer group to the top of all other layers
  5808. bringToBack: function () {
  5809. return this.invoke('bringToBack');
  5810. },
  5811. // @method getBounds(): LatLngBounds
  5812. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5813. getBounds: function () {
  5814. var bounds = new L.LatLngBounds();
  5815. for (var id in this._layers) {
  5816. var layer = this._layers[id];
  5817. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5818. }
  5819. return bounds;
  5820. }
  5821. });
  5822. // @factory L.featureGroup(layers: Layer[])
  5823. // Create a feature group, optionally given an initial set of layers.
  5824. L.featureGroup = function (layers) {
  5825. return new L.FeatureGroup(layers);
  5826. };
  5827. /*
  5828. * @class Renderer
  5829. * @inherits Layer
  5830. * @aka L.Renderer
  5831. *
  5832. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  5833. * DOM container of the renderer, its bounds, and its zoom animation.
  5834. *
  5835. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  5836. * itself can be added or removed to the map. All paths use a renderer, which can
  5837. * be implicit (the map will decide the type of renderer and use it automatically)
  5838. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  5839. *
  5840. * Do not use this class directly, use `SVG` and `Canvas` instead.
  5841. *
  5842. * @event update: Event
  5843. * Fired when the renderer updates its bounds, center and zoom, for example when
  5844. * its map has moved
  5845. */
  5846. L.Renderer = L.Layer.extend({
  5847. // @section
  5848. // @aka Renderer options
  5849. options: {
  5850. // @option padding: Number = 0.1
  5851. // How much to extend the clip area around the map view (relative to its size)
  5852. // e.g. 0.1 would be 10% of map view in each direction
  5853. padding: 0.1
  5854. },
  5855. initialize: function (options) {
  5856. L.setOptions(this, options);
  5857. L.stamp(this);
  5858. },
  5859. onAdd: function () {
  5860. if (!this._container) {
  5861. this._initContainer(); // defined by renderer implementations
  5862. if (this._zoomAnimated) {
  5863. L.DomUtil.addClass(this._container, 'leaflet-zoom-animated');
  5864. }
  5865. }
  5866. this.getPane().appendChild(this._container);
  5867. this._update();
  5868. },
  5869. onRemove: function () {
  5870. L.DomUtil.remove(this._container);
  5871. },
  5872. getEvents: function () {
  5873. var events = {
  5874. viewreset: this._reset,
  5875. zoom: this._onZoom,
  5876. moveend: this._update
  5877. };
  5878. if (this._zoomAnimated) {
  5879. events.zoomanim = this._onAnimZoom;
  5880. }
  5881. return events;
  5882. },
  5883. _onAnimZoom: function (ev) {
  5884. this._updateTransform(ev.center, ev.zoom);
  5885. },
  5886. _onZoom: function () {
  5887. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  5888. },
  5889. _updateTransform: function (center, zoom) {
  5890. var scale = this._map.getZoomScale(zoom, this._zoom),
  5891. position = L.DomUtil.getPosition(this._container),
  5892. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  5893. currentCenterPoint = this._map.project(this._center, zoom),
  5894. destCenterPoint = this._map.project(center, zoom),
  5895. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  5896. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  5897. if (L.Browser.any3d) {
  5898. L.DomUtil.setTransform(this._container, topLeftOffset, scale);
  5899. } else {
  5900. L.DomUtil.setPosition(this._container, topLeftOffset);
  5901. }
  5902. },
  5903. _reset: function () {
  5904. this._update();
  5905. this._updateTransform(this._center, this._zoom);
  5906. },
  5907. _update: function () {
  5908. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  5909. // Subclasses are responsible of firing the 'update' event.
  5910. var p = this.options.padding,
  5911. size = this._map.getSize(),
  5912. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  5913. this._bounds = new L.Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  5914. this._center = this._map.getCenter();
  5915. this._zoom = this._map.getZoom();
  5916. }
  5917. });
  5918. L.Map.include({
  5919. // @namespace Map; @method getRenderer(layer: Path): Renderer
  5920. // Returns the instance of `Renderer` that should be used to render the given
  5921. // `Path`. It will ensure that the `renderer` options of the map and paths
  5922. // are respected, and that the renderers do exist on the map.
  5923. getRenderer: function (layer) {
  5924. // @namespace Path; @option renderer: Renderer
  5925. // Use this specific instance of `Renderer` for this path. Takes
  5926. // precedence over the map's [default renderer](#map-renderer).
  5927. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  5928. if (!renderer) {
  5929. // @namespace Map; @option preferCanvas: Boolean = false
  5930. // Whether `Path`s should be rendered on a `Canvas` renderer.
  5931. // By default, all `Path`s are rendered in a `SVG` renderer.
  5932. renderer = this._renderer = (this.options.preferCanvas && L.canvas()) || L.svg();
  5933. }
  5934. if (!this.hasLayer(renderer)) {
  5935. this.addLayer(renderer);
  5936. }
  5937. return renderer;
  5938. },
  5939. _getPaneRenderer: function (name) {
  5940. if (name === 'overlayPane' || name === undefined) {
  5941. return false;
  5942. }
  5943. var renderer = this._paneRenderers[name];
  5944. if (renderer === undefined) {
  5945. renderer = (L.SVG && L.svg({pane: name})) || (L.Canvas && L.canvas({pane: name}));
  5946. this._paneRenderers[name] = renderer;
  5947. }
  5948. return renderer;
  5949. }
  5950. });
  5951. /*
  5952. * @class Path
  5953. * @aka L.Path
  5954. * @inherits Interactive layer
  5955. *
  5956. * An abstract class that contains options and constants shared between vector
  5957. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  5958. */
  5959. L.Path = L.Layer.extend({
  5960. // @section
  5961. // @aka Path options
  5962. options: {
  5963. // @option stroke: Boolean = true
  5964. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  5965. stroke: true,
  5966. // @option color: String = '#3388ff'
  5967. // Stroke color
  5968. color: '#3388ff',
  5969. // @option weight: Number = 3
  5970. // Stroke width in pixels
  5971. weight: 3,
  5972. // @option opacity: Number = 1.0
  5973. // Stroke opacity
  5974. opacity: 1,
  5975. // @option lineCap: String= 'round'
  5976. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  5977. lineCap: 'round',
  5978. // @option lineJoin: String = 'round'
  5979. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  5980. lineJoin: 'round',
  5981. // @option dashArray: String = null
  5982. // 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).
  5983. dashArray: null,
  5984. // @option dashOffset: String = null
  5985. // 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).
  5986. dashOffset: null,
  5987. // @option fill: Boolean = depends
  5988. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  5989. fill: false,
  5990. // @option fillColor: String = *
  5991. // Fill color. Defaults to the value of the [`color`](#path-color) option
  5992. fillColor: null,
  5993. // @option fillOpacity: Number = 0.2
  5994. // Fill opacity.
  5995. fillOpacity: 0.2,
  5996. // @option fillRule: String = 'evenodd'
  5997. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  5998. fillRule: 'evenodd',
  5999. // className: '',
  6000. // Option inherited from "Interactive layer" abstract class
  6001. interactive: true
  6002. },
  6003. beforeAdd: function (map) {
  6004. // Renderer is set here because we need to call renderer.getEvents
  6005. // before this.getEvents.
  6006. this._renderer = map.getRenderer(this);
  6007. },
  6008. onAdd: function () {
  6009. this._renderer._initPath(this);
  6010. this._reset();
  6011. this._renderer._addPath(this);
  6012. this._renderer.on('update', this._update, this);
  6013. },
  6014. onRemove: function () {
  6015. this._renderer._removePath(this);
  6016. this._renderer.off('update', this._update, this);
  6017. },
  6018. getEvents: function () {
  6019. return {
  6020. zoomend: this._project,
  6021. viewreset: this._reset
  6022. };
  6023. },
  6024. // @method redraw(): this
  6025. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6026. redraw: function () {
  6027. if (this._map) {
  6028. this._renderer._updatePath(this);
  6029. }
  6030. return this;
  6031. },
  6032. // @method setStyle(style: Path options): this
  6033. // Changes the appearance of a Path based on the options in the `Path options` object.
  6034. setStyle: function (style) {
  6035. L.setOptions(this, style);
  6036. if (this._renderer) {
  6037. this._renderer._updateStyle(this);
  6038. }
  6039. return this;
  6040. },
  6041. // @method bringToFront(): this
  6042. // Brings the layer to the top of all path layers.
  6043. bringToFront: function () {
  6044. if (this._renderer) {
  6045. this._renderer._bringToFront(this);
  6046. }
  6047. return this;
  6048. },
  6049. // @method bringToBack(): this
  6050. // Brings the layer to the bottom of all path layers.
  6051. bringToBack: function () {
  6052. if (this._renderer) {
  6053. this._renderer._bringToBack(this);
  6054. }
  6055. return this;
  6056. },
  6057. getElement: function () {
  6058. return this._path;
  6059. },
  6060. _reset: function () {
  6061. // defined in children classes
  6062. this._project();
  6063. this._update();
  6064. },
  6065. _clickTolerance: function () {
  6066. // used when doing hit detection for Canvas layers
  6067. return (this.options.stroke ? this.options.weight / 2 : 0) + (L.Browser.touch ? 10 : 0);
  6068. }
  6069. });
  6070. /*
  6071. * @namespace LineUtil
  6072. *
  6073. * Various utility functions for polyine points processing, used by Leaflet internally to make polylines lightning-fast.
  6074. */
  6075. L.LineUtil = {
  6076. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  6077. // Improves rendering performance dramatically by lessening the number of points to draw.
  6078. // @function simplify(points: Point[], tolerance: Number): Point[]
  6079. // Dramatically reduces the number of points in a polyline while retaining
  6080. // its shape and returns a new array of simplified points, using the
  6081. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  6082. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  6083. // each zoom level and also reducing visual noise. tolerance affects the amount of
  6084. // simplification (lesser value means higher quality but slower and with more points).
  6085. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  6086. simplify: function (points, tolerance) {
  6087. if (!tolerance || !points.length) {
  6088. return points.slice();
  6089. }
  6090. var sqTolerance = tolerance * tolerance;
  6091. // stage 1: vertex reduction
  6092. points = this._reducePoints(points, sqTolerance);
  6093. // stage 2: Douglas-Peucker simplification
  6094. points = this._simplifyDP(points, sqTolerance);
  6095. return points;
  6096. },
  6097. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  6098. // Returns the distance between point `p` and segment `p1` to `p2`.
  6099. pointToSegmentDistance: function (p, p1, p2) {
  6100. return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
  6101. },
  6102. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  6103. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  6104. closestPointOnSegment: function (p, p1, p2) {
  6105. return this._sqClosestPointOnSegment(p, p1, p2);
  6106. },
  6107. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  6108. _simplifyDP: function (points, sqTolerance) {
  6109. var len = points.length,
  6110. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  6111. markers = new ArrayConstructor(len);
  6112. markers[0] = markers[len - 1] = 1;
  6113. this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  6114. var i,
  6115. newPoints = [];
  6116. for (i = 0; i < len; i++) {
  6117. if (markers[i]) {
  6118. newPoints.push(points[i]);
  6119. }
  6120. }
  6121. return newPoints;
  6122. },
  6123. _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
  6124. var maxSqDist = 0,
  6125. index, i, sqDist;
  6126. for (i = first + 1; i <= last - 1; i++) {
  6127. sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
  6128. if (sqDist > maxSqDist) {
  6129. index = i;
  6130. maxSqDist = sqDist;
  6131. }
  6132. }
  6133. if (maxSqDist > sqTolerance) {
  6134. markers[index] = 1;
  6135. this._simplifyDPStep(points, markers, sqTolerance, first, index);
  6136. this._simplifyDPStep(points, markers, sqTolerance, index, last);
  6137. }
  6138. },
  6139. // reduce points that are too close to each other to a single point
  6140. _reducePoints: function (points, sqTolerance) {
  6141. var reducedPoints = [points[0]];
  6142. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  6143. if (this._sqDist(points[i], points[prev]) > sqTolerance) {
  6144. reducedPoints.push(points[i]);
  6145. prev = i;
  6146. }
  6147. }
  6148. if (prev < len - 1) {
  6149. reducedPoints.push(points[len - 1]);
  6150. }
  6151. return reducedPoints;
  6152. },
  6153. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  6154. // Clips the segment a to b by rectangular bounds with the
  6155. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  6156. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  6157. // points that are on the screen or near, increasing performance.
  6158. clipSegment: function (a, b, bounds, useLastCode, round) {
  6159. var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
  6160. codeB = this._getBitCode(b, bounds),
  6161. codeOut, p, newCode;
  6162. // save 2nd code to avoid calculating it on the next segment
  6163. this._lastCode = codeB;
  6164. while (true) {
  6165. // if a,b is inside the clip window (trivial accept)
  6166. if (!(codeA | codeB)) {
  6167. return [a, b];
  6168. }
  6169. // if a,b is outside the clip window (trivial reject)
  6170. if (codeA & codeB) {
  6171. return false;
  6172. }
  6173. // other cases
  6174. codeOut = codeA || codeB;
  6175. p = this._getEdgeIntersection(a, b, codeOut, bounds, round);
  6176. newCode = this._getBitCode(p, bounds);
  6177. if (codeOut === codeA) {
  6178. a = p;
  6179. codeA = newCode;
  6180. } else {
  6181. b = p;
  6182. codeB = newCode;
  6183. }
  6184. }
  6185. },
  6186. _getEdgeIntersection: function (a, b, code, bounds, round) {
  6187. var dx = b.x - a.x,
  6188. dy = b.y - a.y,
  6189. min = bounds.min,
  6190. max = bounds.max,
  6191. x, y;
  6192. if (code & 8) { // top
  6193. x = a.x + dx * (max.y - a.y) / dy;
  6194. y = max.y;
  6195. } else if (code & 4) { // bottom
  6196. x = a.x + dx * (min.y - a.y) / dy;
  6197. y = min.y;
  6198. } else if (code & 2) { // right
  6199. x = max.x;
  6200. y = a.y + dy * (max.x - a.x) / dx;
  6201. } else if (code & 1) { // left
  6202. x = min.x;
  6203. y = a.y + dy * (min.x - a.x) / dx;
  6204. }
  6205. return new L.Point(x, y, round);
  6206. },
  6207. _getBitCode: function (p, bounds) {
  6208. var code = 0;
  6209. if (p.x < bounds.min.x) { // left
  6210. code |= 1;
  6211. } else if (p.x > bounds.max.x) { // right
  6212. code |= 2;
  6213. }
  6214. if (p.y < bounds.min.y) { // bottom
  6215. code |= 4;
  6216. } else if (p.y > bounds.max.y) { // top
  6217. code |= 8;
  6218. }
  6219. return code;
  6220. },
  6221. // square distance (to avoid unnecessary Math.sqrt calls)
  6222. _sqDist: function (p1, p2) {
  6223. var dx = p2.x - p1.x,
  6224. dy = p2.y - p1.y;
  6225. return dx * dx + dy * dy;
  6226. },
  6227. // return closest point on segment or distance to that point
  6228. _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
  6229. var x = p1.x,
  6230. y = p1.y,
  6231. dx = p2.x - x,
  6232. dy = p2.y - y,
  6233. dot = dx * dx + dy * dy,
  6234. t;
  6235. if (dot > 0) {
  6236. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  6237. if (t > 1) {
  6238. x = p2.x;
  6239. y = p2.y;
  6240. } else if (t > 0) {
  6241. x += dx * t;
  6242. y += dy * t;
  6243. }
  6244. }
  6245. dx = p.x - x;
  6246. dy = p.y - y;
  6247. return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
  6248. }
  6249. };
  6250. /*
  6251. * @class Polyline
  6252. * @aka L.Polyline
  6253. * @inherits Path
  6254. *
  6255. * A class for drawing polyline overlays on a map. Extends `Path`.
  6256. *
  6257. * @example
  6258. *
  6259. * ```js
  6260. * // create a red polyline from an array of LatLng points
  6261. * var latlngs = [
  6262. * [-122.68, 45.51],
  6263. * [-122.43, 37.77],
  6264. * [-118.2, 34.04]
  6265. * ];
  6266. *
  6267. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6268. *
  6269. * // zoom the map to the polyline
  6270. * map.fitBounds(polyline.getBounds());
  6271. * ```
  6272. *
  6273. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6274. *
  6275. * ```js
  6276. * // create a red polyline from an array of arrays of LatLng points
  6277. * var latlngs = [
  6278. * [[-122.68, 45.51],
  6279. * [-122.43, 37.77],
  6280. * [-118.2, 34.04]],
  6281. * [[-73.91, 40.78],
  6282. * [-87.62, 41.83],
  6283. * [-96.72, 32.76]]
  6284. * ];
  6285. * ```
  6286. */
  6287. L.Polyline = L.Path.extend({
  6288. // @section
  6289. // @aka Polyline options
  6290. options: {
  6291. // @option smoothFactor: Number = 1.0
  6292. // How much to simplify the polyline on each zoom level. More means
  6293. // better performance and smoother look, and less means more accurate representation.
  6294. smoothFactor: 1.0,
  6295. // @option noClip: Boolean = false
  6296. // Disable polyline clipping.
  6297. noClip: false
  6298. },
  6299. initialize: function (latlngs, options) {
  6300. L.setOptions(this, options);
  6301. this._setLatLngs(latlngs);
  6302. },
  6303. // @method getLatLngs(): LatLng[]
  6304. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6305. getLatLngs: function () {
  6306. return this._latlngs;
  6307. },
  6308. // @method setLatLngs(latlngs: LatLng[]): this
  6309. // Replaces all the points in the polyline with the given array of geographical points.
  6310. setLatLngs: function (latlngs) {
  6311. this._setLatLngs(latlngs);
  6312. return this.redraw();
  6313. },
  6314. // @method isEmpty(): Boolean
  6315. // Returns `true` if the Polyline has no LatLngs.
  6316. isEmpty: function () {
  6317. return !this._latlngs.length;
  6318. },
  6319. closestLayerPoint: function (p) {
  6320. var minDistance = Infinity,
  6321. minPoint = null,
  6322. closest = L.LineUtil._sqClosestPointOnSegment,
  6323. p1, p2;
  6324. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6325. var points = this._parts[j];
  6326. for (var i = 1, len = points.length; i < len; i++) {
  6327. p1 = points[i - 1];
  6328. p2 = points[i];
  6329. var sqDist = closest(p, p1, p2, true);
  6330. if (sqDist < minDistance) {
  6331. minDistance = sqDist;
  6332. minPoint = closest(p, p1, p2);
  6333. }
  6334. }
  6335. }
  6336. if (minPoint) {
  6337. minPoint.distance = Math.sqrt(minDistance);
  6338. }
  6339. return minPoint;
  6340. },
  6341. // @method getCenter(): LatLng
  6342. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6343. getCenter: function () {
  6344. // throws error when not yet added to map as this center calculation requires projected coordinates
  6345. if (!this._map) {
  6346. throw new Error('Must add layer to map before using getCenter()');
  6347. }
  6348. var i, halfDist, segDist, dist, p1, p2, ratio,
  6349. points = this._rings[0],
  6350. len = points.length;
  6351. if (!len) { return null; }
  6352. // polyline centroid algorithm; only uses the first ring if there are multiple
  6353. for (i = 0, halfDist = 0; i < len - 1; i++) {
  6354. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  6355. }
  6356. // The line is so small in the current view that all points are on the same pixel.
  6357. if (halfDist === 0) {
  6358. return this._map.layerPointToLatLng(points[0]);
  6359. }
  6360. for (i = 0, dist = 0; i < len - 1; i++) {
  6361. p1 = points[i];
  6362. p2 = points[i + 1];
  6363. segDist = p1.distanceTo(p2);
  6364. dist += segDist;
  6365. if (dist > halfDist) {
  6366. ratio = (dist - halfDist) / segDist;
  6367. return this._map.layerPointToLatLng([
  6368. p2.x - ratio * (p2.x - p1.x),
  6369. p2.y - ratio * (p2.y - p1.y)
  6370. ]);
  6371. }
  6372. }
  6373. },
  6374. // @method getBounds(): LatLngBounds
  6375. // Returns the `LatLngBounds` of the path.
  6376. getBounds: function () {
  6377. return this._bounds;
  6378. },
  6379. // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
  6380. // Adds a given point to the polyline. By default, adds to the first ring of
  6381. // the polyline in case of a multi-polyline, but can be overridden by passing
  6382. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6383. addLatLng: function (latlng, latlngs) {
  6384. latlngs = latlngs || this._defaultShape();
  6385. latlng = L.latLng(latlng);
  6386. latlngs.push(latlng);
  6387. this._bounds.extend(latlng);
  6388. return this.redraw();
  6389. },
  6390. _setLatLngs: function (latlngs) {
  6391. this._bounds = new L.LatLngBounds();
  6392. this._latlngs = this._convertLatLngs(latlngs);
  6393. },
  6394. _defaultShape: function () {
  6395. return L.Polyline._flat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6396. },
  6397. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6398. _convertLatLngs: function (latlngs) {
  6399. var result = [],
  6400. flat = L.Polyline._flat(latlngs);
  6401. for (var i = 0, len = latlngs.length; i < len; i++) {
  6402. if (flat) {
  6403. result[i] = L.latLng(latlngs[i]);
  6404. this._bounds.extend(result[i]);
  6405. } else {
  6406. result[i] = this._convertLatLngs(latlngs[i]);
  6407. }
  6408. }
  6409. return result;
  6410. },
  6411. _project: function () {
  6412. var pxBounds = new L.Bounds();
  6413. this._rings = [];
  6414. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  6415. var w = this._clickTolerance(),
  6416. p = new L.Point(w, w);
  6417. if (this._bounds.isValid() && pxBounds.isValid()) {
  6418. pxBounds.min._subtract(p);
  6419. pxBounds.max._add(p);
  6420. this._pxBounds = pxBounds;
  6421. }
  6422. },
  6423. // recursively turns latlngs into a set of rings with projected coordinates
  6424. _projectLatlngs: function (latlngs, result, projectedBounds) {
  6425. var flat = latlngs[0] instanceof L.LatLng,
  6426. len = latlngs.length,
  6427. i, ring;
  6428. if (flat) {
  6429. ring = [];
  6430. for (i = 0; i < len; i++) {
  6431. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  6432. projectedBounds.extend(ring[i]);
  6433. }
  6434. result.push(ring);
  6435. } else {
  6436. for (i = 0; i < len; i++) {
  6437. this._projectLatlngs(latlngs[i], result, projectedBounds);
  6438. }
  6439. }
  6440. },
  6441. // clip polyline by renderer bounds so that we have less to render for performance
  6442. _clipPoints: function () {
  6443. var bounds = this._renderer._bounds;
  6444. this._parts = [];
  6445. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6446. return;
  6447. }
  6448. if (this.options.noClip) {
  6449. this._parts = this._rings;
  6450. return;
  6451. }
  6452. var parts = this._parts,
  6453. i, j, k, len, len2, segment, points;
  6454. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  6455. points = this._rings[i];
  6456. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  6457. segment = L.LineUtil.clipSegment(points[j], points[j + 1], bounds, j, true);
  6458. if (!segment) { continue; }
  6459. parts[k] = parts[k] || [];
  6460. parts[k].push(segment[0]);
  6461. // if segment goes out of screen, or it's the last one, it's the end of the line part
  6462. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  6463. parts[k].push(segment[1]);
  6464. k++;
  6465. }
  6466. }
  6467. }
  6468. },
  6469. // simplify each clipped part of the polyline for performance
  6470. _simplifyPoints: function () {
  6471. var parts = this._parts,
  6472. tolerance = this.options.smoothFactor;
  6473. for (var i = 0, len = parts.length; i < len; i++) {
  6474. parts[i] = L.LineUtil.simplify(parts[i], tolerance);
  6475. }
  6476. },
  6477. _update: function () {
  6478. if (!this._map) { return; }
  6479. this._clipPoints();
  6480. this._simplifyPoints();
  6481. this._updatePath();
  6482. },
  6483. _updatePath: function () {
  6484. this._renderer._updatePoly(this);
  6485. }
  6486. });
  6487. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  6488. // Instantiates a polyline object given an array of geographical points and
  6489. // optionally an options object. You can create a `Polyline` object with
  6490. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  6491. // of geographic points.
  6492. L.polyline = function (latlngs, options) {
  6493. return new L.Polyline(latlngs, options);
  6494. };
  6495. L.Polyline._flat = function (latlngs) {
  6496. // true if it's a flat array of latlngs; false if nested
  6497. return !L.Util.isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  6498. };
  6499. /*
  6500. * @namespace PolyUtil
  6501. * Various utility functions for polygon geometries.
  6502. */
  6503. L.PolyUtil = {};
  6504. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  6505. * 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)).
  6506. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  6507. * performance. Note that polygon points needs different algorithm for clipping
  6508. * than polyline, so there's a seperate method for it.
  6509. */
  6510. L.PolyUtil.clipPolygon = function (points, bounds, round) {
  6511. var clippedPoints,
  6512. edges = [1, 4, 2, 8],
  6513. i, j, k,
  6514. a, b,
  6515. len, edge, p,
  6516. lu = L.LineUtil;
  6517. for (i = 0, len = points.length; i < len; i++) {
  6518. points[i]._code = lu._getBitCode(points[i], bounds);
  6519. }
  6520. // for each edge (left, bottom, right, top)
  6521. for (k = 0; k < 4; k++) {
  6522. edge = edges[k];
  6523. clippedPoints = [];
  6524. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  6525. a = points[i];
  6526. b = points[j];
  6527. // if a is inside the clip window
  6528. if (!(a._code & edge)) {
  6529. // if b is outside the clip window (a->b goes out of screen)
  6530. if (b._code & edge) {
  6531. p = lu._getEdgeIntersection(b, a, edge, bounds, round);
  6532. p._code = lu._getBitCode(p, bounds);
  6533. clippedPoints.push(p);
  6534. }
  6535. clippedPoints.push(a);
  6536. // else if b is inside the clip window (a->b enters the screen)
  6537. } else if (!(b._code & edge)) {
  6538. p = lu._getEdgeIntersection(b, a, edge, bounds, round);
  6539. p._code = lu._getBitCode(p, bounds);
  6540. clippedPoints.push(p);
  6541. }
  6542. }
  6543. points = clippedPoints;
  6544. }
  6545. return points;
  6546. };
  6547. /*
  6548. * @class Polygon
  6549. * @aka L.Polygon
  6550. * @inherits Polyline
  6551. *
  6552. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  6553. *
  6554. * 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.
  6555. *
  6556. *
  6557. * @example
  6558. *
  6559. * ```js
  6560. * // create a red polygon from an array of LatLng points
  6561. * var latlngs = [[-111.03, 41],[-111.04, 45],[-104.05, 45],[-104.05, 41]];
  6562. *
  6563. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  6564. *
  6565. * // zoom the map to the polygon
  6566. * map.fitBounds(polygon.getBounds());
  6567. * ```
  6568. *
  6569. * 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:
  6570. *
  6571. * ```js
  6572. * var latlngs = [
  6573. * [[-111.03, 41],[-111.04, 45],[-104.05, 45],[-104.05, 41]], // outer ring
  6574. * [[-108.58,37.29],[-108.58,40.71],[-102.50,40.71],[-102.50,37.29]] // hole
  6575. * ];
  6576. * ```
  6577. *
  6578. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  6579. *
  6580. * ```js
  6581. * var latlngs = [
  6582. * [ // first polygon
  6583. * [[-111.03, 41],[-111.04, 45],[-104.05, 45],[-104.05, 41]], // outer ring
  6584. * [[-108.58,37.29],[-108.58,40.71],[-102.50,40.71],[-102.50,37.29]] // hole
  6585. * ],
  6586. * [ // second polygon
  6587. * [[-109.05, 37],[-109.03, 41],[-102.05, 41],[-102.04, 37],[-109.05, 38]]
  6588. * ]
  6589. * ];
  6590. * ```
  6591. */
  6592. L.Polygon = L.Polyline.extend({
  6593. options: {
  6594. fill: true
  6595. },
  6596. isEmpty: function () {
  6597. return !this._latlngs.length || !this._latlngs[0].length;
  6598. },
  6599. getCenter: function () {
  6600. // throws error when not yet added to map as this center calculation requires projected coordinates
  6601. if (!this._map) {
  6602. throw new Error('Must add layer to map before using getCenter()');
  6603. }
  6604. var i, j, p1, p2, f, area, x, y, center,
  6605. points = this._rings[0],
  6606. len = points.length;
  6607. if (!len) { return null; }
  6608. // polygon centroid algorithm; only uses the first ring if there are multiple
  6609. area = x = y = 0;
  6610. for (i = 0, j = len - 1; i < len; j = i++) {
  6611. p1 = points[i];
  6612. p2 = points[j];
  6613. f = p1.y * p2.x - p2.y * p1.x;
  6614. x += (p1.x + p2.x) * f;
  6615. y += (p1.y + p2.y) * f;
  6616. area += f * 3;
  6617. }
  6618. if (area === 0) {
  6619. // Polygon is so small that all points are on same pixel.
  6620. center = points[0];
  6621. } else {
  6622. center = [x / area, y / area];
  6623. }
  6624. return this._map.layerPointToLatLng(center);
  6625. },
  6626. _convertLatLngs: function (latlngs) {
  6627. var result = L.Polyline.prototype._convertLatLngs.call(this, latlngs),
  6628. len = result.length;
  6629. // remove last point if it equals first one
  6630. if (len >= 2 && result[0] instanceof L.LatLng && result[0].equals(result[len - 1])) {
  6631. result.pop();
  6632. }
  6633. return result;
  6634. },
  6635. _setLatLngs: function (latlngs) {
  6636. L.Polyline.prototype._setLatLngs.call(this, latlngs);
  6637. if (L.Polyline._flat(this._latlngs)) {
  6638. this._latlngs = [this._latlngs];
  6639. }
  6640. },
  6641. _defaultShape: function () {
  6642. return L.Polyline._flat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  6643. },
  6644. _clipPoints: function () {
  6645. // polygons need a different clipping algorithm so we redefine that
  6646. var bounds = this._renderer._bounds,
  6647. w = this.options.weight,
  6648. p = new L.Point(w, w);
  6649. // increase clip padding by stroke width to avoid stroke on clip edges
  6650. bounds = new L.Bounds(bounds.min.subtract(p), bounds.max.add(p));
  6651. this._parts = [];
  6652. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6653. return;
  6654. }
  6655. if (this.options.noClip) {
  6656. this._parts = this._rings;
  6657. return;
  6658. }
  6659. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  6660. clipped = L.PolyUtil.clipPolygon(this._rings[i], bounds, true);
  6661. if (clipped.length) {
  6662. this._parts.push(clipped);
  6663. }
  6664. }
  6665. },
  6666. _updatePath: function () {
  6667. this._renderer._updatePoly(this, true);
  6668. }
  6669. });
  6670. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  6671. L.polygon = function (latlngs, options) {
  6672. return new L.Polygon(latlngs, options);
  6673. };
  6674. /*
  6675. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  6676. */
  6677. /*
  6678. * @class Rectangle
  6679. * @aka L.Retangle
  6680. * @inherits Polygon
  6681. *
  6682. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  6683. *
  6684. * @example
  6685. *
  6686. * ```js
  6687. * // define rectangle geographical bounds
  6688. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  6689. *
  6690. * // create an orange rectangle
  6691. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  6692. *
  6693. * // zoom the map to the rectangle bounds
  6694. * map.fitBounds(bounds);
  6695. * ```
  6696. *
  6697. */
  6698. L.Rectangle = L.Polygon.extend({
  6699. initialize: function (latLngBounds, options) {
  6700. L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  6701. },
  6702. // @method setBounds(latLngBounds: LatLngBounds): this
  6703. // Redraws the rectangle with the passed bounds.
  6704. setBounds: function (latLngBounds) {
  6705. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  6706. },
  6707. _boundsToLatLngs: function (latLngBounds) {
  6708. latLngBounds = L.latLngBounds(latLngBounds);
  6709. return [
  6710. latLngBounds.getSouthWest(),
  6711. latLngBounds.getNorthWest(),
  6712. latLngBounds.getNorthEast(),
  6713. latLngBounds.getSouthEast()
  6714. ];
  6715. }
  6716. });
  6717. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  6718. L.rectangle = function (latLngBounds, options) {
  6719. return new L.Rectangle(latLngBounds, options);
  6720. };
  6721. /*
  6722. * @class CircleMarker
  6723. * @aka L.CircleMarker
  6724. * @inherits Path
  6725. *
  6726. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6727. */
  6728. L.CircleMarker = L.Path.extend({
  6729. // @section
  6730. // @aka CircleMarker options
  6731. options: {
  6732. fill: true,
  6733. // @option radius: Number = 10
  6734. // Radius of the circle marker, in pixels
  6735. radius: 10
  6736. },
  6737. initialize: function (latlng, options) {
  6738. L.setOptions(this, options);
  6739. this._latlng = L.latLng(latlng);
  6740. this._radius = this.options.radius;
  6741. },
  6742. // @method setLatLng(latLng: LatLng): this
  6743. // Sets the position of a circle marker to a new location.
  6744. setLatLng: function (latlng) {
  6745. this._latlng = L.latLng(latlng);
  6746. this.redraw();
  6747. return this.fire('move', {latlng: this._latlng});
  6748. },
  6749. // @method getLatLng(): LatLng
  6750. // Returns the current geographical position of the circle marker
  6751. getLatLng: function () {
  6752. return this._latlng;
  6753. },
  6754. // @method setRadius(radius: Number): this
  6755. // Sets the radius of a circle marker. Units are in pixels.
  6756. setRadius: function (radius) {
  6757. this.options.radius = this._radius = radius;
  6758. return this.redraw();
  6759. },
  6760. // @method getRadius(): Number
  6761. // Returns the current radius of the circle
  6762. getRadius: function () {
  6763. return this._radius;
  6764. },
  6765. setStyle : function (options) {
  6766. var radius = options && options.radius || this._radius;
  6767. L.Path.prototype.setStyle.call(this, options);
  6768. this.setRadius(radius);
  6769. return this;
  6770. },
  6771. _project: function () {
  6772. this._point = this._map.latLngToLayerPoint(this._latlng);
  6773. this._updateBounds();
  6774. },
  6775. _updateBounds: function () {
  6776. var r = this._radius,
  6777. r2 = this._radiusY || r,
  6778. w = this._clickTolerance(),
  6779. p = [r + w, r2 + w];
  6780. this._pxBounds = new L.Bounds(this._point.subtract(p), this._point.add(p));
  6781. },
  6782. _update: function () {
  6783. if (this._map) {
  6784. this._updatePath();
  6785. }
  6786. },
  6787. _updatePath: function () {
  6788. this._renderer._updateCircle(this);
  6789. },
  6790. _empty: function () {
  6791. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6792. }
  6793. });
  6794. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6795. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6796. L.circleMarker = function (latlng, options) {
  6797. return new L.CircleMarker(latlng, options);
  6798. };
  6799. /*
  6800. * @class Circle
  6801. * @aka L.Circle
  6802. * @inherits CircleMarker
  6803. *
  6804. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6805. *
  6806. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6807. *
  6808. * @example
  6809. *
  6810. * ```js
  6811. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6812. * ```
  6813. */
  6814. L.Circle = L.CircleMarker.extend({
  6815. initialize: function (latlng, options, legacyOptions) {
  6816. if (typeof options === 'number') {
  6817. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6818. options = L.extend({}, legacyOptions, {radius: options});
  6819. }
  6820. L.setOptions(this, options);
  6821. this._latlng = L.latLng(latlng);
  6822. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6823. // @section
  6824. // @aka Circle options
  6825. // @option radius: Number; Radius of the circle, in meters.
  6826. this._mRadius = this.options.radius;
  6827. },
  6828. // @method setRadius(radius: Number): this
  6829. // Sets the radius of a circle. Units are in meters.
  6830. setRadius: function (radius) {
  6831. this._mRadius = radius;
  6832. return this.redraw();
  6833. },
  6834. // @method getRadius(): Number
  6835. // Returns the current radius of a circle. Units are in meters.
  6836. getRadius: function () {
  6837. return this._mRadius;
  6838. },
  6839. // @method getBounds(): LatLngBounds
  6840. // Returns the `LatLngBounds` of the path.
  6841. getBounds: function () {
  6842. var half = [this._radius, this._radiusY || this._radius];
  6843. return new L.LatLngBounds(
  6844. this._map.layerPointToLatLng(this._point.subtract(half)),
  6845. this._map.layerPointToLatLng(this._point.add(half)));
  6846. },
  6847. setStyle: L.Path.prototype.setStyle,
  6848. _project: function () {
  6849. var lng = this._latlng.lng,
  6850. lat = this._latlng.lat,
  6851. map = this._map,
  6852. crs = map.options.crs;
  6853. if (crs.distance === L.CRS.Earth.distance) {
  6854. var d = Math.PI / 180,
  6855. latR = (this._mRadius / L.CRS.Earth.R) / d,
  6856. top = map.project([lat + latR, lng]),
  6857. bottom = map.project([lat - latR, lng]),
  6858. p = top.add(bottom).divideBy(2),
  6859. lat2 = map.unproject(p).lat,
  6860. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6861. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6862. if (isNaN(lngR) || lngR === 0) {
  6863. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6864. }
  6865. this._point = p.subtract(map.getPixelOrigin());
  6866. this._radius = isNaN(lngR) ? 0 : Math.max(Math.round(p.x - map.project([lat2, lng - lngR]).x), 1);
  6867. this._radiusY = Math.max(Math.round(p.y - top.y), 1);
  6868. } else {
  6869. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6870. this._point = map.latLngToLayerPoint(this._latlng);
  6871. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6872. }
  6873. this._updateBounds();
  6874. }
  6875. });
  6876. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6877. // Instantiates a circle object given a geographical point, and an options object
  6878. // which contains the circle radius.
  6879. // @alternative
  6880. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6881. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6882. // Do not use in new applications or plugins.
  6883. L.circle = function (latlng, options, legacyOptions) {
  6884. return new L.Circle(latlng, options, legacyOptions);
  6885. };
  6886. /*
  6887. * @class SVG
  6888. * @inherits Renderer
  6889. * @aka L.SVG
  6890. *
  6891. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  6892. * Inherits `Renderer`.
  6893. *
  6894. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  6895. * available in all web browsers, notably Android 2.x and 3.x.
  6896. *
  6897. * Although SVG is not available on IE7 and IE8, these browsers support
  6898. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  6899. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  6900. * this case.
  6901. *
  6902. * @example
  6903. *
  6904. * Use SVG by default for all paths in the map:
  6905. *
  6906. * ```js
  6907. * var map = L.map('map', {
  6908. * renderer: L.svg()
  6909. * });
  6910. * ```
  6911. *
  6912. * Use a SVG renderer with extra padding for specific vector geometries:
  6913. *
  6914. * ```js
  6915. * var map = L.map('map');
  6916. * var myRenderer = L.svg({ padding: 0.5 });
  6917. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  6918. * var circle = L.circle( center, { renderer: myRenderer } );
  6919. * ```
  6920. */
  6921. L.SVG = L.Renderer.extend({
  6922. getEvents: function () {
  6923. var events = L.Renderer.prototype.getEvents.call(this);
  6924. events.zoomstart = this._onZoomStart;
  6925. return events;
  6926. },
  6927. _initContainer: function () {
  6928. this._container = L.SVG.create('svg');
  6929. // makes it possible to click through svg root; we'll reset it back in individual paths
  6930. this._container.setAttribute('pointer-events', 'none');
  6931. this._rootGroup = L.SVG.create('g');
  6932. this._container.appendChild(this._rootGroup);
  6933. },
  6934. _onZoomStart: function () {
  6935. // Drag-then-pinch interactions might mess up the center and zoom.
  6936. // In this case, the easiest way to prevent this is re-do the renderer
  6937. // bounds and padding when the zooming starts.
  6938. this._update();
  6939. },
  6940. _update: function () {
  6941. if (this._map._animatingZoom && this._bounds) { return; }
  6942. L.Renderer.prototype._update.call(this);
  6943. var b = this._bounds,
  6944. size = b.getSize(),
  6945. container = this._container;
  6946. // set size of svg-container if changed
  6947. if (!this._svgSize || !this._svgSize.equals(size)) {
  6948. this._svgSize = size;
  6949. container.setAttribute('width', size.x);
  6950. container.setAttribute('height', size.y);
  6951. }
  6952. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  6953. L.DomUtil.setPosition(container, b.min);
  6954. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  6955. this.fire('update');
  6956. },
  6957. // methods below are called by vector layers implementations
  6958. _initPath: function (layer) {
  6959. var path = layer._path = L.SVG.create('path');
  6960. // @namespace Path
  6961. // @option className: String = null
  6962. // Custom class name set on an element. Only for SVG renderer.
  6963. if (layer.options.className) {
  6964. L.DomUtil.addClass(path, layer.options.className);
  6965. }
  6966. if (layer.options.interactive) {
  6967. L.DomUtil.addClass(path, 'leaflet-interactive');
  6968. }
  6969. this._updateStyle(layer);
  6970. },
  6971. _addPath: function (layer) {
  6972. this._rootGroup.appendChild(layer._path);
  6973. layer.addInteractiveTarget(layer._path);
  6974. },
  6975. _removePath: function (layer) {
  6976. L.DomUtil.remove(layer._path);
  6977. layer.removeInteractiveTarget(layer._path);
  6978. },
  6979. _updatePath: function (layer) {
  6980. layer._project();
  6981. layer._update();
  6982. },
  6983. _updateStyle: function (layer) {
  6984. var path = layer._path,
  6985. options = layer.options;
  6986. if (!path) { return; }
  6987. if (options.stroke) {
  6988. path.setAttribute('stroke', options.color);
  6989. path.setAttribute('stroke-opacity', options.opacity);
  6990. path.setAttribute('stroke-width', options.weight);
  6991. path.setAttribute('stroke-linecap', options.lineCap);
  6992. path.setAttribute('stroke-linejoin', options.lineJoin);
  6993. if (options.dashArray) {
  6994. path.setAttribute('stroke-dasharray', options.dashArray);
  6995. } else {
  6996. path.removeAttribute('stroke-dasharray');
  6997. }
  6998. if (options.dashOffset) {
  6999. path.setAttribute('stroke-dashoffset', options.dashOffset);
  7000. } else {
  7001. path.removeAttribute('stroke-dashoffset');
  7002. }
  7003. } else {
  7004. path.setAttribute('stroke', 'none');
  7005. }
  7006. if (options.fill) {
  7007. path.setAttribute('fill', options.fillColor || options.color);
  7008. path.setAttribute('fill-opacity', options.fillOpacity);
  7009. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  7010. } else {
  7011. path.setAttribute('fill', 'none');
  7012. }
  7013. },
  7014. _updatePoly: function (layer, closed) {
  7015. this._setPath(layer, L.SVG.pointsToPath(layer._parts, closed));
  7016. },
  7017. _updateCircle: function (layer) {
  7018. var p = layer._point,
  7019. r = layer._radius,
  7020. r2 = layer._radiusY || r,
  7021. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  7022. // drawing a circle with two half-arcs
  7023. var d = layer._empty() ? 'M0 0' :
  7024. 'M' + (p.x - r) + ',' + p.y +
  7025. arc + (r * 2) + ',0 ' +
  7026. arc + (-r * 2) + ',0 ';
  7027. this._setPath(layer, d);
  7028. },
  7029. _setPath: function (layer, path) {
  7030. layer._path.setAttribute('d', path);
  7031. },
  7032. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  7033. _bringToFront: function (layer) {
  7034. L.DomUtil.toFront(layer._path);
  7035. },
  7036. _bringToBack: function (layer) {
  7037. L.DomUtil.toBack(layer._path);
  7038. }
  7039. });
  7040. // @namespace SVG; @section
  7041. // There are several static functions which can be called without instantiating L.SVG:
  7042. L.extend(L.SVG, {
  7043. // @function create(name: String): SVGElement
  7044. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  7045. // corresponding to the class name passed. For example, using 'line' will return
  7046. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  7047. create: function (name) {
  7048. return document.createElementNS('http://www.w3.org/2000/svg', name);
  7049. },
  7050. // @function pointsToPath(rings: Point[], closed: Boolean): String
  7051. // Generates a SVG path string for multiple rings, with each ring turning
  7052. // into "M..L..L.." instructions
  7053. pointsToPath: function (rings, closed) {
  7054. var str = '',
  7055. i, j, len, len2, points, p;
  7056. for (i = 0, len = rings.length; i < len; i++) {
  7057. points = rings[i];
  7058. for (j = 0, len2 = points.length; j < len2; j++) {
  7059. p = points[j];
  7060. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  7061. }
  7062. // closes the ring for polygons; "x" is VML syntax
  7063. str += closed ? (L.Browser.svg ? 'z' : 'x') : '';
  7064. }
  7065. // SVG complains about empty path strings
  7066. return str || 'M0 0';
  7067. }
  7068. });
  7069. // @namespace Browser; @property svg: Boolean
  7070. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  7071. L.Browser.svg = !!(document.createElementNS && L.SVG.create('svg').createSVGRect);
  7072. // @namespace SVG
  7073. // @factory L.svg(options?: Renderer options)
  7074. // Creates a SVG renderer with the given options.
  7075. L.svg = function (options) {
  7076. return L.Browser.svg || L.Browser.vml ? new L.SVG(options) : null;
  7077. };
  7078. /*
  7079. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  7080. */
  7081. /*
  7082. * @class SVG
  7083. *
  7084. * 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.
  7085. *
  7086. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  7087. * with old versions of Internet Explorer.
  7088. */
  7089. // @namespace Browser; @property vml: Boolean
  7090. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  7091. L.Browser.vml = !L.Browser.svg && (function () {
  7092. try {
  7093. var div = document.createElement('div');
  7094. div.innerHTML = '<v:shape adj="1"/>';
  7095. var shape = div.firstChild;
  7096. shape.style.behavior = 'url(#default#VML)';
  7097. return shape && (typeof shape.adj === 'object');
  7098. } catch (e) {
  7099. return false;
  7100. }
  7101. }());
  7102. // redefine some SVG methods to handle VML syntax which is similar but with some differences
  7103. L.SVG.include(!L.Browser.vml ? {} : {
  7104. _initContainer: function () {
  7105. this._container = L.DomUtil.create('div', 'leaflet-vml-container');
  7106. },
  7107. _update: function () {
  7108. if (this._map._animatingZoom) { return; }
  7109. L.Renderer.prototype._update.call(this);
  7110. this.fire('update');
  7111. },
  7112. _initPath: function (layer) {
  7113. var container = layer._container = L.SVG.create('shape');
  7114. L.DomUtil.addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  7115. container.coordsize = '1 1';
  7116. layer._path = L.SVG.create('path');
  7117. container.appendChild(layer._path);
  7118. this._updateStyle(layer);
  7119. },
  7120. _addPath: function (layer) {
  7121. var container = layer._container;
  7122. this._container.appendChild(container);
  7123. if (layer.options.interactive) {
  7124. layer.addInteractiveTarget(container);
  7125. }
  7126. },
  7127. _removePath: function (layer) {
  7128. var container = layer._container;
  7129. L.DomUtil.remove(container);
  7130. layer.removeInteractiveTarget(container);
  7131. },
  7132. _updateStyle: function (layer) {
  7133. var stroke = layer._stroke,
  7134. fill = layer._fill,
  7135. options = layer.options,
  7136. container = layer._container;
  7137. container.stroked = !!options.stroke;
  7138. container.filled = !!options.fill;
  7139. if (options.stroke) {
  7140. if (!stroke) {
  7141. stroke = layer._stroke = L.SVG.create('stroke');
  7142. }
  7143. container.appendChild(stroke);
  7144. stroke.weight = options.weight + 'px';
  7145. stroke.color = options.color;
  7146. stroke.opacity = options.opacity;
  7147. if (options.dashArray) {
  7148. stroke.dashStyle = L.Util.isArray(options.dashArray) ?
  7149. options.dashArray.join(' ') :
  7150. options.dashArray.replace(/( *, *)/g, ' ');
  7151. } else {
  7152. stroke.dashStyle = '';
  7153. }
  7154. stroke.endcap = options.lineCap.replace('butt', 'flat');
  7155. stroke.joinstyle = options.lineJoin;
  7156. } else if (stroke) {
  7157. container.removeChild(stroke);
  7158. layer._stroke = null;
  7159. }
  7160. if (options.fill) {
  7161. if (!fill) {
  7162. fill = layer._fill = L.SVG.create('fill');
  7163. }
  7164. container.appendChild(fill);
  7165. fill.color = options.fillColor || options.color;
  7166. fill.opacity = options.fillOpacity;
  7167. } else if (fill) {
  7168. container.removeChild(fill);
  7169. layer._fill = null;
  7170. }
  7171. },
  7172. _updateCircle: function (layer) {
  7173. var p = layer._point.round(),
  7174. r = Math.round(layer._radius),
  7175. r2 = Math.round(layer._radiusY || r);
  7176. this._setPath(layer, layer._empty() ? 'M0 0' :
  7177. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  7178. },
  7179. _setPath: function (layer, path) {
  7180. layer._path.v = path;
  7181. },
  7182. _bringToFront: function (layer) {
  7183. L.DomUtil.toFront(layer._container);
  7184. },
  7185. _bringToBack: function (layer) {
  7186. L.DomUtil.toBack(layer._container);
  7187. }
  7188. });
  7189. if (L.Browser.vml) {
  7190. L.SVG.create = (function () {
  7191. try {
  7192. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  7193. return function (name) {
  7194. return document.createElement('<lvml:' + name + ' class="lvml">');
  7195. };
  7196. } catch (e) {
  7197. return function (name) {
  7198. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  7199. };
  7200. }
  7201. })();
  7202. }
  7203. /*
  7204. * @class Canvas
  7205. * @inherits Renderer
  7206. * @aka L.Canvas
  7207. *
  7208. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  7209. * Inherits `Renderer`.
  7210. *
  7211. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  7212. * available in all web browsers, notably IE8, and overlapping geometries might
  7213. * not display properly in some edge cases.
  7214. *
  7215. * @example
  7216. *
  7217. * Use Canvas by default for all paths in the map:
  7218. *
  7219. * ```js
  7220. * var map = L.map('map', {
  7221. * renderer: L.canvas()
  7222. * });
  7223. * ```
  7224. *
  7225. * Use a Canvas renderer with extra padding for specific vector geometries:
  7226. *
  7227. * ```js
  7228. * var map = L.map('map');
  7229. * var myRenderer = L.canvas({ padding: 0.5 });
  7230. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  7231. * var circle = L.circle( center, { renderer: myRenderer } );
  7232. * ```
  7233. */
  7234. L.Canvas = L.Renderer.extend({
  7235. onAdd: function () {
  7236. L.Renderer.prototype.onAdd.call(this);
  7237. this._layers = this._layers || {};
  7238. // Redraw vectors since canvas is cleared upon removal,
  7239. // in case of removing the renderer itself from the map.
  7240. this._draw();
  7241. },
  7242. _initContainer: function () {
  7243. var container = this._container = document.createElement('canvas');
  7244. L.DomEvent
  7245. .on(container, 'mousemove', L.Util.throttle(this._onMouseMove, 32, this), this)
  7246. .on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this)
  7247. .on(container, 'mouseout', this._handleMouseOut, this);
  7248. this._ctx = container.getContext('2d');
  7249. },
  7250. _update: function () {
  7251. if (this._map._animatingZoom && this._bounds) { return; }
  7252. this._drawnLayers = {};
  7253. L.Renderer.prototype._update.call(this);
  7254. var b = this._bounds,
  7255. container = this._container,
  7256. size = b.getSize(),
  7257. m = L.Browser.retina ? 2 : 1;
  7258. L.DomUtil.setPosition(container, b.min);
  7259. // set canvas size (also clearing it); use double size on retina
  7260. container.width = m * size.x;
  7261. container.height = m * size.y;
  7262. container.style.width = size.x + 'px';
  7263. container.style.height = size.y + 'px';
  7264. if (L.Browser.retina) {
  7265. this._ctx.scale(2, 2);
  7266. }
  7267. // translate so we use the same path coordinates after canvas element moves
  7268. this._ctx.translate(-b.min.x, -b.min.y);
  7269. // Tell paths to redraw themselves
  7270. this.fire('update');
  7271. },
  7272. _initPath: function (layer) {
  7273. this._updateDashArray(layer);
  7274. this._layers[L.stamp(layer)] = layer;
  7275. },
  7276. _addPath: L.Util.falseFn,
  7277. _removePath: function (layer) {
  7278. layer._removed = true;
  7279. this._requestRedraw(layer);
  7280. },
  7281. _updatePath: function (layer) {
  7282. this._redrawBounds = layer._pxBounds;
  7283. this._draw(true);
  7284. layer._project();
  7285. layer._update();
  7286. this._draw();
  7287. this._redrawBounds = null;
  7288. },
  7289. _updateStyle: function (layer) {
  7290. this._updateDashArray(layer);
  7291. this._requestRedraw(layer);
  7292. },
  7293. _updateDashArray: function (layer) {
  7294. if (layer.options.dashArray) {
  7295. var parts = layer.options.dashArray.split(','),
  7296. dashArray = [],
  7297. i;
  7298. for (i = 0; i < parts.length; i++) {
  7299. dashArray.push(Number(parts[i]));
  7300. }
  7301. layer.options._dashArray = dashArray;
  7302. }
  7303. },
  7304. _requestRedraw: function (layer) {
  7305. if (!this._map) { return; }
  7306. var padding = (layer.options.weight || 0) + 1;
  7307. this._redrawBounds = this._redrawBounds || new L.Bounds();
  7308. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  7309. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  7310. this._redrawRequest = this._redrawRequest || L.Util.requestAnimFrame(this._redraw, this);
  7311. },
  7312. _redraw: function () {
  7313. this._redrawRequest = null;
  7314. this._draw(true); // clear layers in redraw bounds
  7315. this._draw(); // draw layers
  7316. this._redrawBounds = null;
  7317. },
  7318. _draw: function (clear) {
  7319. this._clear = clear;
  7320. var layer, bounds = this._redrawBounds;
  7321. this._ctx.save();
  7322. if (bounds) {
  7323. this._ctx.beginPath();
  7324. this._ctx.rect(bounds.min.x, bounds.min.y, bounds.max.x - bounds.min.x, bounds.max.y - bounds.min.y);
  7325. this._ctx.clip();
  7326. }
  7327. for (var id in this._layers) {
  7328. layer = this._layers[id];
  7329. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  7330. layer._updatePath();
  7331. }
  7332. if (clear && layer._removed) {
  7333. delete layer._removed;
  7334. delete this._layers[id];
  7335. }
  7336. }
  7337. this._ctx.restore(); // Restore state before clipping.
  7338. },
  7339. _updatePoly: function (layer, closed) {
  7340. var i, j, len2, p,
  7341. parts = layer._parts,
  7342. len = parts.length,
  7343. ctx = this._ctx;
  7344. if (!len) { return; }
  7345. this._drawnLayers[layer._leaflet_id] = layer;
  7346. ctx.beginPath();
  7347. if (ctx.setLineDash) {
  7348. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  7349. }
  7350. for (i = 0; i < len; i++) {
  7351. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  7352. p = parts[i][j];
  7353. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  7354. }
  7355. if (closed) {
  7356. ctx.closePath();
  7357. }
  7358. }
  7359. this._fillStroke(ctx, layer);
  7360. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  7361. },
  7362. _updateCircle: function (layer) {
  7363. if (layer._empty()) { return; }
  7364. var p = layer._point,
  7365. ctx = this._ctx,
  7366. r = layer._radius,
  7367. s = (layer._radiusY || r) / r;
  7368. this._drawnLayers[layer._leaflet_id] = layer;
  7369. if (s !== 1) {
  7370. ctx.save();
  7371. ctx.scale(1, s);
  7372. }
  7373. ctx.beginPath();
  7374. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  7375. if (s !== 1) {
  7376. ctx.restore();
  7377. }
  7378. this._fillStroke(ctx, layer);
  7379. },
  7380. _fillStroke: function (ctx, layer) {
  7381. var clear = this._clear,
  7382. options = layer.options;
  7383. ctx.globalCompositeOperation = clear ? 'destination-out' : 'source-over';
  7384. if (options.fill) {
  7385. ctx.globalAlpha = clear ? 1 : options.fillOpacity;
  7386. ctx.fillStyle = options.fillColor || options.color;
  7387. ctx.fill(options.fillRule || 'evenodd');
  7388. }
  7389. if (options.stroke && options.weight !== 0) {
  7390. ctx.globalAlpha = clear ? 1 : options.opacity;
  7391. // if clearing shape, do it with the previously drawn line width
  7392. layer._prevWeight = ctx.lineWidth = clear ? layer._prevWeight + 1 : options.weight;
  7393. ctx.strokeStyle = options.color;
  7394. ctx.lineCap = options.lineCap;
  7395. ctx.lineJoin = options.lineJoin;
  7396. ctx.stroke();
  7397. }
  7398. },
  7399. // Canvas obviously doesn't have mouse events for individual drawn objects,
  7400. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  7401. _onClick: function (e) {
  7402. var point = this._map.mouseEventToLayerPoint(e), layers = [], layer;
  7403. for (var id in this._layers) {
  7404. layer = this._layers[id];
  7405. if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
  7406. L.DomEvent._fakeStop(e);
  7407. layers.push(layer);
  7408. }
  7409. }
  7410. if (layers.length) {
  7411. this._fireEvent(layers, e);
  7412. }
  7413. },
  7414. _onMouseMove: function (e) {
  7415. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  7416. var point = this._map.mouseEventToLayerPoint(e);
  7417. this._handleMouseOut(e, point);
  7418. this._handleMouseHover(e, point);
  7419. },
  7420. _handleMouseOut: function (e, point) {
  7421. var layer = this._hoveredLayer;
  7422. if (layer && (e.type === 'mouseout' || !layer._containsPoint(point))) {
  7423. // if we're leaving the layer, fire mouseout
  7424. L.DomUtil.removeClass(this._container, 'leaflet-interactive');
  7425. this._fireEvent([layer], e, 'mouseout');
  7426. this._hoveredLayer = null;
  7427. }
  7428. },
  7429. _handleMouseHover: function (e, point) {
  7430. var id, layer;
  7431. for (id in this._drawnLayers) {
  7432. layer = this._drawnLayers[id];
  7433. if (layer.options.interactive && layer._containsPoint(point)) {
  7434. L.DomUtil.addClass(this._container, 'leaflet-interactive'); // change cursor
  7435. this._fireEvent([layer], e, 'mouseover');
  7436. this._hoveredLayer = layer;
  7437. }
  7438. }
  7439. if (this._hoveredLayer) {
  7440. this._fireEvent([this._hoveredLayer], e);
  7441. }
  7442. },
  7443. _fireEvent: function (layers, e, type) {
  7444. this._map._fireDOMEvent(e, type || e.type, layers);
  7445. },
  7446. // TODO _bringToFront & _bringToBack, pretty tricky
  7447. _bringToFront: L.Util.falseFn,
  7448. _bringToBack: L.Util.falseFn
  7449. });
  7450. // @namespace Browser; @property canvas: Boolean
  7451. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  7452. L.Browser.canvas = (function () {
  7453. return !!document.createElement('canvas').getContext;
  7454. }());
  7455. // @namespace Canvas
  7456. // @factory L.canvas(options?: Renderer options)
  7457. // Creates a Canvas renderer with the given options.
  7458. L.canvas = function (options) {
  7459. return L.Browser.canvas ? new L.Canvas(options) : null;
  7460. };
  7461. L.Polyline.prototype._containsPoint = function (p, closed) {
  7462. var i, j, k, len, len2, part,
  7463. w = this._clickTolerance();
  7464. if (!this._pxBounds.contains(p)) { return false; }
  7465. // hit detection for polylines
  7466. for (i = 0, len = this._parts.length; i < len; i++) {
  7467. part = this._parts[i];
  7468. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7469. if (!closed && (j === 0)) { continue; }
  7470. if (L.LineUtil.pointToSegmentDistance(p, part[k], part[j]) <= w) {
  7471. return true;
  7472. }
  7473. }
  7474. }
  7475. return false;
  7476. };
  7477. L.Polygon.prototype._containsPoint = function (p) {
  7478. var inside = false,
  7479. part, p1, p2, i, j, k, len, len2;
  7480. if (!this._pxBounds.contains(p)) { return false; }
  7481. // ray casting algorithm for detecting if point is in polygon
  7482. for (i = 0, len = this._parts.length; i < len; i++) {
  7483. part = this._parts[i];
  7484. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7485. p1 = part[j];
  7486. p2 = part[k];
  7487. 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)) {
  7488. inside = !inside;
  7489. }
  7490. }
  7491. }
  7492. // also check if it's on polygon stroke
  7493. return inside || L.Polyline.prototype._containsPoint.call(this, p, true);
  7494. };
  7495. L.CircleMarker.prototype._containsPoint = function (p) {
  7496. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  7497. };
  7498. /*
  7499. * @class GeoJSON
  7500. * @aka L.GeoJSON
  7501. * @inherits FeatureGroup
  7502. *
  7503. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  7504. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  7505. *
  7506. * @example
  7507. *
  7508. * ```js
  7509. * L.geoJSON(data, {
  7510. * style: function (feature) {
  7511. * return {color: feature.properties.color};
  7512. * }
  7513. * }).bindPopup(function (layer) {
  7514. * return layer.feature.properties.description;
  7515. * }).addTo(map);
  7516. * ```
  7517. */
  7518. L.GeoJSON = L.FeatureGroup.extend({
  7519. /* @section
  7520. * @aka GeoJSON options
  7521. *
  7522. * @option pointToLayer: Function = *
  7523. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  7524. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  7525. * The default is to spawn a default `Marker`:
  7526. * ```js
  7527. * function(geoJsonPoint, latlng) {
  7528. * return L.marker(latlng);
  7529. * }
  7530. * ```
  7531. *
  7532. * @option style: Function = *
  7533. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  7534. * called internally when data is added.
  7535. * The default value is to not override any defaults:
  7536. * ```js
  7537. * function (geoJsonFeature) {
  7538. * return {}
  7539. * }
  7540. * ```
  7541. *
  7542. * @option onEachFeature: Function = *
  7543. * A `Function` that will be called once for each created `Feature`, after it has
  7544. * been created and styled. Useful for attaching events and popups to features.
  7545. * The default is to do nothing with the newly created layers:
  7546. * ```js
  7547. * function (feature, layer) {}
  7548. * ```
  7549. *
  7550. * @option filter: Function = *
  7551. * A `Function` that will be used to decide whether to include a feature or not.
  7552. * The default is to include all features:
  7553. * ```js
  7554. * function (geoJsonFeature) {
  7555. * return true;
  7556. * }
  7557. * ```
  7558. * Note: dynamically changing the `filter` option will have effect only on newly
  7559. * added data. It will _not_ re-evaluate already included features.
  7560. *
  7561. * @option coordsToLatLng: Function = *
  7562. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  7563. * The default is the `coordsToLatLng` static method.
  7564. */
  7565. initialize: function (geojson, options) {
  7566. L.setOptions(this, options);
  7567. this._layers = {};
  7568. if (geojson) {
  7569. this.addData(geojson);
  7570. }
  7571. },
  7572. // @method addData( <GeoJSON> data ): Layer
  7573. // Adds a GeoJSON object to the layer.
  7574. addData: function (geojson) {
  7575. var features = L.Util.isArray(geojson) ? geojson : geojson.features,
  7576. i, len, feature;
  7577. if (features) {
  7578. for (i = 0, len = features.length; i < len; i++) {
  7579. // only add this if geometry or geometries are set and not null
  7580. feature = features[i];
  7581. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  7582. this.addData(feature);
  7583. }
  7584. }
  7585. return this;
  7586. }
  7587. var options = this.options;
  7588. if (options.filter && !options.filter(geojson)) { return this; }
  7589. var layer = L.GeoJSON.geometryToLayer(geojson, options);
  7590. if (!layer) {
  7591. return this;
  7592. }
  7593. layer.feature = L.GeoJSON.asFeature(geojson);
  7594. layer.defaultOptions = layer.options;
  7595. this.resetStyle(layer);
  7596. if (options.onEachFeature) {
  7597. options.onEachFeature(geojson, layer);
  7598. }
  7599. return this.addLayer(layer);
  7600. },
  7601. // @method resetStyle( <Path> layer ): Layer
  7602. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7603. resetStyle: function (layer) {
  7604. // reset any custom styles
  7605. layer.options = L.Util.extend({}, layer.defaultOptions);
  7606. this._setLayerStyle(layer, this.options.style);
  7607. return this;
  7608. },
  7609. // @method setStyle( <Function> style ): Layer
  7610. // Changes styles of GeoJSON vector layers with the given style function.
  7611. setStyle: function (style) {
  7612. return this.eachLayer(function (layer) {
  7613. this._setLayerStyle(layer, style);
  7614. }, this);
  7615. },
  7616. _setLayerStyle: function (layer, style) {
  7617. if (typeof style === 'function') {
  7618. style = style(layer.feature);
  7619. }
  7620. if (layer.setStyle) {
  7621. layer.setStyle(style);
  7622. }
  7623. }
  7624. });
  7625. // @section
  7626. // There are several static functions which can be called without instantiating L.GeoJSON:
  7627. L.extend(L.GeoJSON, {
  7628. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7629. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7630. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7631. // functions if provided as options.
  7632. geometryToLayer: function (geojson, options) {
  7633. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7634. coords = geometry ? geometry.coordinates : null,
  7635. layers = [],
  7636. pointToLayer = options && options.pointToLayer,
  7637. coordsToLatLng = options && options.coordsToLatLng || this.coordsToLatLng,
  7638. latlng, latlngs, i, len;
  7639. if (!coords && !geometry) {
  7640. return null;
  7641. }
  7642. switch (geometry.type) {
  7643. case 'Point':
  7644. latlng = coordsToLatLng(coords);
  7645. return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
  7646. case 'MultiPoint':
  7647. for (i = 0, len = coords.length; i < len; i++) {
  7648. latlng = coordsToLatLng(coords[i]);
  7649. layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng));
  7650. }
  7651. return new L.FeatureGroup(layers);
  7652. case 'LineString':
  7653. case 'MultiLineString':
  7654. latlngs = this.coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, coordsToLatLng);
  7655. return new L.Polyline(latlngs, options);
  7656. case 'Polygon':
  7657. case 'MultiPolygon':
  7658. latlngs = this.coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, coordsToLatLng);
  7659. return new L.Polygon(latlngs, options);
  7660. case 'GeometryCollection':
  7661. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7662. var layer = this.geometryToLayer({
  7663. geometry: geometry.geometries[i],
  7664. type: 'Feature',
  7665. properties: geojson.properties
  7666. }, options);
  7667. if (layer) {
  7668. layers.push(layer);
  7669. }
  7670. }
  7671. return new L.FeatureGroup(layers);
  7672. default:
  7673. throw new Error('Invalid GeoJSON object.');
  7674. }
  7675. },
  7676. // @function coordsToLatLng(coords: Array): LatLng
  7677. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7678. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7679. coordsToLatLng: function (coords) {
  7680. return new L.LatLng(coords[1], coords[0], coords[2]);
  7681. },
  7682. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7683. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7684. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7685. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7686. coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) {
  7687. var latlngs = [];
  7688. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7689. latlng = levelsDeep ?
  7690. this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
  7691. (coordsToLatLng || this.coordsToLatLng)(coords[i]);
  7692. latlngs.push(latlng);
  7693. }
  7694. return latlngs;
  7695. },
  7696. // @function latLngToCoords(latlng: LatLng): Array
  7697. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7698. latLngToCoords: function (latlng) {
  7699. return latlng.alt !== undefined ?
  7700. [latlng.lng, latlng.lat, latlng.alt] :
  7701. [latlng.lng, latlng.lat];
  7702. },
  7703. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  7704. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7705. // `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.
  7706. latLngsToCoords: function (latlngs, levelsDeep, closed) {
  7707. var coords = [];
  7708. for (var i = 0, len = latlngs.length; i < len; i++) {
  7709. coords.push(levelsDeep ?
  7710. L.GeoJSON.latLngsToCoords(latlngs[i], levelsDeep - 1, closed) :
  7711. L.GeoJSON.latLngToCoords(latlngs[i]));
  7712. }
  7713. if (!levelsDeep && closed) {
  7714. coords.push(coords[0]);
  7715. }
  7716. return coords;
  7717. },
  7718. getFeature: function (layer, newGeometry) {
  7719. return layer.feature ?
  7720. L.extend({}, layer.feature, {geometry: newGeometry}) :
  7721. L.GeoJSON.asFeature(newGeometry);
  7722. },
  7723. // @function asFeature(geojson: Object): Object
  7724. // Normalize GeoJSON geometries/features into GeoJSON features.
  7725. asFeature: function (geojson) {
  7726. if (geojson.type === 'Feature') {
  7727. return geojson;
  7728. }
  7729. return {
  7730. type: 'Feature',
  7731. properties: {},
  7732. geometry: geojson
  7733. };
  7734. }
  7735. });
  7736. var PointToGeoJSON = {
  7737. toGeoJSON: function () {
  7738. return L.GeoJSON.getFeature(this, {
  7739. type: 'Point',
  7740. coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
  7741. });
  7742. }
  7743. };
  7744. L.Marker.include(PointToGeoJSON);
  7745. // @namespace CircleMarker
  7746. // @method toGeoJSON(): Object
  7747. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7748. L.Circle.include(PointToGeoJSON);
  7749. L.CircleMarker.include(PointToGeoJSON);
  7750. // @namespace Polyline
  7751. // @method toGeoJSON(): Object
  7752. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7753. L.Polyline.prototype.toGeoJSON = function () {
  7754. var multi = !L.Polyline._flat(this._latlngs);
  7755. var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 1 : 0);
  7756. return L.GeoJSON.getFeature(this, {
  7757. type: (multi ? 'Multi' : '') + 'LineString',
  7758. coordinates: coords
  7759. });
  7760. };
  7761. // @namespace Polygon
  7762. // @method toGeoJSON(): Object
  7763. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7764. L.Polygon.prototype.toGeoJSON = function () {
  7765. var holes = !L.Polyline._flat(this._latlngs),
  7766. multi = holes && !L.Polyline._flat(this._latlngs[0]);
  7767. var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true);
  7768. if (!holes) {
  7769. coords = [coords];
  7770. }
  7771. return L.GeoJSON.getFeature(this, {
  7772. type: (multi ? 'Multi' : '') + 'Polygon',
  7773. coordinates: coords
  7774. });
  7775. };
  7776. // @namespace LayerGroup
  7777. L.LayerGroup.include({
  7778. toMultiPoint: function () {
  7779. var coords = [];
  7780. this.eachLayer(function (layer) {
  7781. coords.push(layer.toGeoJSON().geometry.coordinates);
  7782. });
  7783. return L.GeoJSON.getFeature(this, {
  7784. type: 'MultiPoint',
  7785. coordinates: coords
  7786. });
  7787. },
  7788. // @method toGeoJSON(): Object
  7789. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `GeometryCollection`).
  7790. toGeoJSON: function () {
  7791. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7792. if (type === 'MultiPoint') {
  7793. return this.toMultiPoint();
  7794. }
  7795. var isGeometryCollection = type === 'GeometryCollection',
  7796. jsons = [];
  7797. this.eachLayer(function (layer) {
  7798. if (layer.toGeoJSON) {
  7799. var json = layer.toGeoJSON();
  7800. jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json));
  7801. }
  7802. });
  7803. if (isGeometryCollection) {
  7804. return L.GeoJSON.getFeature(this, {
  7805. geometries: jsons,
  7806. type: 'GeometryCollection'
  7807. });
  7808. }
  7809. return {
  7810. type: 'FeatureCollection',
  7811. features: jsons
  7812. };
  7813. }
  7814. });
  7815. // @namespace GeoJSON
  7816. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7817. // Creates a GeoJSON layer. Optionally accepts an object in
  7818. // [GeoJSON format](http://geojson.org/geojson-spec.html) to display on the map
  7819. // (you can alternatively add it later with `addData` method) and an `options` object.
  7820. L.geoJSON = function (geojson, options) {
  7821. return new L.GeoJSON(geojson, options);
  7822. };
  7823. // Backward compatibility.
  7824. L.geoJson = L.geoJSON;
  7825. /*
  7826. * @namespace DomEvent
  7827. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  7828. */
  7829. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  7830. var eventsKey = '_leaflet_events';
  7831. L.DomEvent = {
  7832. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  7833. // Adds a listener function (`fn`) to a particular DOM event type of the
  7834. // element `el`. You can optionally specify the context of the listener
  7835. // (object the `this` keyword will point to). You can also pass several
  7836. // space-separated types (e.g. `'click dblclick'`).
  7837. // @alternative
  7838. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  7839. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  7840. on: function (obj, types, fn, context) {
  7841. if (typeof types === 'object') {
  7842. for (var type in types) {
  7843. this._on(obj, type, types[type], fn);
  7844. }
  7845. } else {
  7846. types = L.Util.splitWords(types);
  7847. for (var i = 0, len = types.length; i < len; i++) {
  7848. this._on(obj, types[i], fn, context);
  7849. }
  7850. }
  7851. return this;
  7852. },
  7853. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  7854. // Removes a previously added listener function. If no function is specified,
  7855. // it will remove all the listeners of that particular DOM event from the element.
  7856. // Note that if you passed a custom context to on, you must pass the same
  7857. // context to `off` in order to remove the listener.
  7858. // @alternative
  7859. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  7860. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  7861. off: function (obj, types, fn, context) {
  7862. if (typeof types === 'object') {
  7863. for (var type in types) {
  7864. this._off(obj, type, types[type], fn);
  7865. }
  7866. } else {
  7867. types = L.Util.splitWords(types);
  7868. for (var i = 0, len = types.length; i < len; i++) {
  7869. this._off(obj, types[i], fn, context);
  7870. }
  7871. }
  7872. return this;
  7873. },
  7874. _on: function (obj, type, fn, context) {
  7875. var id = type + L.stamp(fn) + (context ? '_' + L.stamp(context) : '');
  7876. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  7877. var handler = function (e) {
  7878. return fn.call(context || obj, e || window.event);
  7879. };
  7880. var originalHandler = handler;
  7881. if (L.Browser.pointer && type.indexOf('touch') === 0) {
  7882. this.addPointerListener(obj, type, handler, id);
  7883. } else if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
  7884. this.addDoubleTapListener(obj, handler, id);
  7885. } else if ('addEventListener' in obj) {
  7886. if (type === 'mousewheel') {
  7887. obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  7888. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  7889. handler = function (e) {
  7890. e = e || window.event;
  7891. if (L.DomEvent._isExternalTarget(obj, e)) {
  7892. originalHandler(e);
  7893. }
  7894. };
  7895. obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
  7896. } else {
  7897. if (type === 'click' && L.Browser.android) {
  7898. handler = function (e) {
  7899. return L.DomEvent._filterClick(e, originalHandler);
  7900. };
  7901. }
  7902. obj.addEventListener(type, handler, false);
  7903. }
  7904. } else if ('attachEvent' in obj) {
  7905. obj.attachEvent('on' + type, handler);
  7906. }
  7907. obj[eventsKey] = obj[eventsKey] || {};
  7908. obj[eventsKey][id] = handler;
  7909. return this;
  7910. },
  7911. _off: function (obj, type, fn, context) {
  7912. var id = type + L.stamp(fn) + (context ? '_' + L.stamp(context) : ''),
  7913. handler = obj[eventsKey] && obj[eventsKey][id];
  7914. if (!handler) { return this; }
  7915. if (L.Browser.pointer && type.indexOf('touch') === 0) {
  7916. this.removePointerListener(obj, type, id);
  7917. } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
  7918. this.removeDoubleTapListener(obj, id);
  7919. } else if ('removeEventListener' in obj) {
  7920. if (type === 'mousewheel') {
  7921. obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  7922. } else {
  7923. obj.removeEventListener(
  7924. type === 'mouseenter' ? 'mouseover' :
  7925. type === 'mouseleave' ? 'mouseout' : type, handler, false);
  7926. }
  7927. } else if ('detachEvent' in obj) {
  7928. obj.detachEvent('on' + type, handler);
  7929. }
  7930. obj[eventsKey][id] = null;
  7931. return this;
  7932. },
  7933. // @function stopPropagation(ev: DOMEvent): this
  7934. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  7935. // ```js
  7936. // L.DomEvent.on(div, 'click', function (ev) {
  7937. // L.DomEvent.stopPropagation(ev);
  7938. // });
  7939. // ```
  7940. stopPropagation: function (e) {
  7941. if (e.stopPropagation) {
  7942. e.stopPropagation();
  7943. } else if (e.originalEvent) { // In case of Leaflet event.
  7944. e.originalEvent._stopped = true;
  7945. } else {
  7946. e.cancelBubble = true;
  7947. }
  7948. L.DomEvent._skipped(e);
  7949. return this;
  7950. },
  7951. // @function disableScrollPropagation(el: HTMLElement): this
  7952. // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
  7953. disableScrollPropagation: function (el) {
  7954. return L.DomEvent.on(el, 'mousewheel', L.DomEvent.stopPropagation);
  7955. },
  7956. // @function disableClickPropagation(el: HTMLElement): this
  7957. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  7958. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  7959. disableClickPropagation: function (el) {
  7960. var stop = L.DomEvent.stopPropagation;
  7961. L.DomEvent.on(el, L.Draggable.START.join(' '), stop);
  7962. return L.DomEvent.on(el, {
  7963. click: L.DomEvent._fakeStop,
  7964. dblclick: stop
  7965. });
  7966. },
  7967. // @function preventDefault(ev: DOMEvent): this
  7968. // Prevents the default action of the DOM Event `ev` from happening (such as
  7969. // following a link in the href of the a element, or doing a POST request
  7970. // with page reload when a `<form>` is submitted).
  7971. // Use it inside listener functions.
  7972. preventDefault: function (e) {
  7973. if (e.preventDefault) {
  7974. e.preventDefault();
  7975. } else {
  7976. e.returnValue = false;
  7977. }
  7978. return this;
  7979. },
  7980. // @function stop(ev): this
  7981. // Does `stopPropagation` and `preventDefault` at the same time.
  7982. stop: function (e) {
  7983. return L.DomEvent
  7984. .preventDefault(e)
  7985. .stopPropagation(e);
  7986. },
  7987. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  7988. // Gets normalized mouse position from a DOM event relative to the
  7989. // `container` or to the whole page if not specified.
  7990. getMousePosition: function (e, container) {
  7991. if (!container) {
  7992. return new L.Point(e.clientX, e.clientY);
  7993. }
  7994. var rect = container.getBoundingClientRect();
  7995. return new L.Point(
  7996. e.clientX - rect.left - container.clientLeft,
  7997. e.clientY - rect.top - container.clientTop);
  7998. },
  7999. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  8000. // and Firefox scrolls device pixels, not CSS pixels
  8001. _wheelPxFactor: (L.Browser.win && L.Browser.chrome) ? 2 :
  8002. L.Browser.gecko ? window.devicePixelRatio :
  8003. 1,
  8004. // @function getWheelDelta(ev: DOMEvent): Number
  8005. // Gets normalized wheel delta from a mousewheel DOM event, in vertical
  8006. // pixels scrolled (negative if scrolling down).
  8007. // Events from pointing devices without precise scrolling are mapped to
  8008. // a best guess of 60 pixels.
  8009. getWheelDelta: function (e) {
  8010. return (L.Browser.edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  8011. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / L.DomEvent._wheelPxFactor : // Pixels
  8012. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  8013. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  8014. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  8015. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  8016. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  8017. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  8018. 0;
  8019. },
  8020. _skipEvents: {},
  8021. _fakeStop: function (e) {
  8022. // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e)
  8023. L.DomEvent._skipEvents[e.type] = true;
  8024. },
  8025. _skipped: function (e) {
  8026. var skipped = this._skipEvents[e.type];
  8027. // reset when checking, as it's only used in map container and propagates outside of the map
  8028. this._skipEvents[e.type] = false;
  8029. return skipped;
  8030. },
  8031. // check if element really left/entered the event target (for mouseenter/mouseleave)
  8032. _isExternalTarget: function (el, e) {
  8033. var related = e.relatedTarget;
  8034. if (!related) { return true; }
  8035. try {
  8036. while (related && (related !== el)) {
  8037. related = related.parentNode;
  8038. }
  8039. } catch (err) {
  8040. return false;
  8041. }
  8042. return (related !== el);
  8043. },
  8044. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  8045. _filterClick: function (e, handler) {
  8046. var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
  8047. elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
  8048. // are they closer together than 500ms yet more than 100ms?
  8049. // Android typically triggers them ~300ms apart while multiple listeners
  8050. // on the same event should be triggered far faster;
  8051. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  8052. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  8053. L.DomEvent.stop(e);
  8054. return;
  8055. }
  8056. L.DomEvent._lastClick = timeStamp;
  8057. handler(e);
  8058. }
  8059. };
  8060. // @function addListener(…): this
  8061. // Alias to [`L.DomEvent.on`](#domevent-on)
  8062. L.DomEvent.addListener = L.DomEvent.on;
  8063. // @function removeListener(…): this
  8064. // Alias to [`L.DomEvent.off`](#domevent-off)
  8065. L.DomEvent.removeListener = L.DomEvent.off;
  8066. /*
  8067. * @class Draggable
  8068. * @aka L.Draggable
  8069. * @inherits Evented
  8070. *
  8071. * A class for making DOM elements draggable (including touch support).
  8072. * Used internally for map and marker dragging. Only works for elements
  8073. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  8074. *
  8075. * @example
  8076. * ```js
  8077. * var draggable = new L.Draggable(elementToDrag);
  8078. * draggable.enable();
  8079. * ```
  8080. */
  8081. L.Draggable = L.Evented.extend({
  8082. options: {
  8083. // @option clickTolerance: Number = 3
  8084. // The max number of pixels a user can shift the mouse pointer during a click
  8085. // for it to be considered a valid click (as opposed to a mouse drag).
  8086. clickTolerance: 3
  8087. },
  8088. statics: {
  8089. START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
  8090. END: {
  8091. mousedown: 'mouseup',
  8092. touchstart: 'touchend',
  8093. pointerdown: 'touchend',
  8094. MSPointerDown: 'touchend'
  8095. },
  8096. MOVE: {
  8097. mousedown: 'mousemove',
  8098. touchstart: 'touchmove',
  8099. pointerdown: 'touchmove',
  8100. MSPointerDown: 'touchmove'
  8101. }
  8102. },
  8103. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline: Boolean)
  8104. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  8105. initialize: function (element, dragStartTarget, preventOutline) {
  8106. this._element = element;
  8107. this._dragStartTarget = dragStartTarget || element;
  8108. this._preventOutline = preventOutline;
  8109. },
  8110. // @method enable()
  8111. // Enables the dragging ability
  8112. enable: function () {
  8113. if (this._enabled) { return; }
  8114. L.DomEvent.on(this._dragStartTarget, L.Draggable.START.join(' '), this._onDown, this);
  8115. this._enabled = true;
  8116. },
  8117. // @method disable()
  8118. // Disables the dragging ability
  8119. disable: function () {
  8120. if (!this._enabled) { return; }
  8121. L.DomEvent.off(this._dragStartTarget, L.Draggable.START.join(' '), this._onDown, this);
  8122. this._enabled = false;
  8123. this._moved = false;
  8124. },
  8125. _onDown: function (e) {
  8126. // Ignore simulated events, since we handle both touch and
  8127. // mouse explicitly; otherwise we risk getting duplicates of
  8128. // touch events, see #4315.
  8129. // Also ignore the event if disabled; this happens in IE11
  8130. // under some circumstances, see #3666.
  8131. if (e._simulated || !this._enabled) { return; }
  8132. this._moved = false;
  8133. if (L.DomUtil.hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  8134. if (L.Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches) || !this._enabled) { return; }
  8135. L.Draggable._dragging = true; // Prevent dragging multiple objects at once.
  8136. if (this._preventOutline) {
  8137. L.DomUtil.preventOutline(this._element);
  8138. }
  8139. L.DomUtil.disableImageDrag();
  8140. L.DomUtil.disableTextSelection();
  8141. if (this._moving) { return; }
  8142. // @event down: Event
  8143. // Fired when a drag is about to start.
  8144. this.fire('down');
  8145. var first = e.touches ? e.touches[0] : e;
  8146. this._startPoint = new L.Point(first.clientX, first.clientY);
  8147. L.DomEvent
  8148. .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
  8149. .on(document, L.Draggable.END[e.type], this._onUp, this);
  8150. },
  8151. _onMove: function (e) {
  8152. // Ignore simulated events, since we handle both touch and
  8153. // mouse explicitly; otherwise we risk getting duplicates of
  8154. // touch events, see #4315.
  8155. // Also ignore the event if disabled; this happens in IE11
  8156. // under some circumstances, see #3666.
  8157. if (e._simulated || !this._enabled) { return; }
  8158. if (e.touches && e.touches.length > 1) {
  8159. this._moved = true;
  8160. return;
  8161. }
  8162. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  8163. newPoint = new L.Point(first.clientX, first.clientY),
  8164. offset = newPoint.subtract(this._startPoint);
  8165. if (!offset.x && !offset.y) { return; }
  8166. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  8167. L.DomEvent.preventDefault(e);
  8168. if (!this._moved) {
  8169. // @event dragstart: Event
  8170. // Fired when a drag starts
  8171. this.fire('dragstart');
  8172. this._moved = true;
  8173. this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
  8174. L.DomUtil.addClass(document.body, 'leaflet-dragging');
  8175. this._lastTarget = e.target || e.srcElement;
  8176. // IE and Edge do not give the <use> element, so fetch it
  8177. // if necessary
  8178. if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
  8179. this._lastTarget = this._lastTarget.correspondingUseElement;
  8180. }
  8181. L.DomUtil.addClass(this._lastTarget, 'leaflet-drag-target');
  8182. }
  8183. this._newPos = this._startPos.add(offset);
  8184. this._moving = true;
  8185. L.Util.cancelAnimFrame(this._animRequest);
  8186. this._lastEvent = e;
  8187. this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true);
  8188. },
  8189. _updatePosition: function () {
  8190. var e = {originalEvent: this._lastEvent};
  8191. // @event predrag: Event
  8192. // Fired continuously during dragging *before* each corresponding
  8193. // update of the element's position.
  8194. this.fire('predrag', e);
  8195. L.DomUtil.setPosition(this._element, this._newPos);
  8196. // @event drag: Event
  8197. // Fired continuously during dragging.
  8198. this.fire('drag', e);
  8199. },
  8200. _onUp: function (e) {
  8201. // Ignore simulated events, since we handle both touch and
  8202. // mouse explicitly; otherwise we risk getting duplicates of
  8203. // touch events, see #4315.
  8204. // Also ignore the event if disabled; this happens in IE11
  8205. // under some circumstances, see #3666.
  8206. if (e._simulated || !this._enabled) { return; }
  8207. L.DomUtil.removeClass(document.body, 'leaflet-dragging');
  8208. if (this._lastTarget) {
  8209. L.DomUtil.removeClass(this._lastTarget, 'leaflet-drag-target');
  8210. this._lastTarget = null;
  8211. }
  8212. for (var i in L.Draggable.MOVE) {
  8213. L.DomEvent
  8214. .off(document, L.Draggable.MOVE[i], this._onMove, this)
  8215. .off(document, L.Draggable.END[i], this._onUp, this);
  8216. }
  8217. L.DomUtil.enableImageDrag();
  8218. L.DomUtil.enableTextSelection();
  8219. if (this._moved && this._moving) {
  8220. // ensure drag is not fired after dragend
  8221. L.Util.cancelAnimFrame(this._animRequest);
  8222. // @event dragend: DragEndEvent
  8223. // Fired when the drag ends.
  8224. this.fire('dragend', {
  8225. distance: this._newPos.distanceTo(this._startPos)
  8226. });
  8227. }
  8228. this._moving = false;
  8229. L.Draggable._dragging = false;
  8230. }
  8231. });
  8232. /*
  8233. L.Handler is a base class for handler classes that are used internally to inject
  8234. interaction features like dragging to classes like Map and Marker.
  8235. */
  8236. // @class Handler
  8237. // @aka L.Handler
  8238. // Abstract class for map interaction handlers
  8239. L.Handler = L.Class.extend({
  8240. initialize: function (map) {
  8241. this._map = map;
  8242. },
  8243. // @method enable(): this
  8244. // Enables the handler
  8245. enable: function () {
  8246. if (this._enabled) { return this; }
  8247. this._enabled = true;
  8248. this.addHooks();
  8249. return this;
  8250. },
  8251. // @method disable(): this
  8252. // Disables the handler
  8253. disable: function () {
  8254. if (!this._enabled) { return this; }
  8255. this._enabled = false;
  8256. this.removeHooks();
  8257. return this;
  8258. },
  8259. // @method enabled(): Boolean
  8260. // Returns `true` if the handler is enabled
  8261. enabled: function () {
  8262. return !!this._enabled;
  8263. }
  8264. // @section Extension methods
  8265. // Classes inheriting from `Handler` must implement the two following methods:
  8266. // @method addHooks()
  8267. // Called when the handler is enabled, should add event hooks.
  8268. // @method removeHooks()
  8269. // Called when the handler is disabled, should remove the event hooks added previously.
  8270. });
  8271. /*
  8272. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  8273. */
  8274. // @namespace Map
  8275. // @section Interaction Options
  8276. L.Map.mergeOptions({
  8277. // @option dragging: Boolean = true
  8278. // Whether the map be draggable with mouse/touch or not.
  8279. dragging: true,
  8280. // @section Panning Inertia Options
  8281. // @option inertia: Boolean = *
  8282. // If enabled, panning of the map will have an inertia effect where
  8283. // the map builds momentum while dragging and continues moving in
  8284. // the same direction for some time. Feels especially nice on touch
  8285. // devices. Enabled by default unless running on old Android devices.
  8286. inertia: !L.Browser.android23,
  8287. // @option inertiaDeceleration: Number = 3000
  8288. // The rate with which the inertial movement slows down, in pixels/second².
  8289. inertiaDeceleration: 3400, // px/s^2
  8290. // @option inertiaMaxSpeed: Number = Infinity
  8291. // Max speed of the inertial movement, in pixels/second.
  8292. inertiaMaxSpeed: Infinity, // px/s
  8293. // @option easeLinearity: Number = 0.2
  8294. easeLinearity: 0.2,
  8295. // TODO refactor, move to CRS
  8296. // @option worldCopyJump: Boolean = false
  8297. // With this option enabled, the map tracks when you pan to another "copy"
  8298. // of the world and seamlessly jumps to the original one so that all overlays
  8299. // like markers and vector layers are still visible.
  8300. worldCopyJump: false,
  8301. // @option maxBoundsViscosity: Number = 0.0
  8302. // If `maxBounds` is set, this option will control how solid the bounds
  8303. // are when dragging the map around. The default value of `0.0` allows the
  8304. // user to drag outside the bounds at normal speed, higher values will
  8305. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  8306. // solid, preventing the user from dragging outside the bounds.
  8307. maxBoundsViscosity: 0.0
  8308. });
  8309. L.Map.Drag = L.Handler.extend({
  8310. addHooks: function () {
  8311. if (!this._draggable) {
  8312. var map = this._map;
  8313. this._draggable = new L.Draggable(map._mapPane, map._container);
  8314. this._draggable.on({
  8315. down: this._onDown,
  8316. dragstart: this._onDragStart,
  8317. drag: this._onDrag,
  8318. dragend: this._onDragEnd
  8319. }, this);
  8320. this._draggable.on('predrag', this._onPreDragLimit, this);
  8321. if (map.options.worldCopyJump) {
  8322. this._draggable.on('predrag', this._onPreDragWrap, this);
  8323. map.on('zoomend', this._onZoomEnd, this);
  8324. map.whenReady(this._onZoomEnd, this);
  8325. }
  8326. }
  8327. L.DomUtil.addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  8328. this._draggable.enable();
  8329. this._positions = [];
  8330. this._times = [];
  8331. },
  8332. removeHooks: function () {
  8333. L.DomUtil.removeClass(this._map._container, 'leaflet-grab');
  8334. L.DomUtil.removeClass(this._map._container, 'leaflet-touch-drag');
  8335. this._draggable.disable();
  8336. },
  8337. moved: function () {
  8338. return this._draggable && this._draggable._moved;
  8339. },
  8340. moving: function () {
  8341. return this._draggable && this._draggable._moving;
  8342. },
  8343. _onDown: function () {
  8344. this._map._stop();
  8345. },
  8346. _onDragStart: function () {
  8347. var map = this._map;
  8348. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  8349. var bounds = L.latLngBounds(this._map.options.maxBounds);
  8350. this._offsetLimit = L.bounds(
  8351. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  8352. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  8353. .add(this._map.getSize()));
  8354. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  8355. } else {
  8356. this._offsetLimit = null;
  8357. }
  8358. map
  8359. .fire('movestart')
  8360. .fire('dragstart');
  8361. if (map.options.inertia) {
  8362. this._positions = [];
  8363. this._times = [];
  8364. }
  8365. },
  8366. _onDrag: function (e) {
  8367. if (this._map.options.inertia) {
  8368. var time = this._lastTime = +new Date(),
  8369. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  8370. this._positions.push(pos);
  8371. this._times.push(time);
  8372. if (time - this._times[0] > 50) {
  8373. this._positions.shift();
  8374. this._times.shift();
  8375. }
  8376. }
  8377. this._map
  8378. .fire('move', e)
  8379. .fire('drag', e);
  8380. },
  8381. _onZoomEnd: function () {
  8382. var pxCenter = this._map.getSize().divideBy(2),
  8383. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  8384. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  8385. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  8386. },
  8387. _viscousLimit: function (value, threshold) {
  8388. return value - (value - threshold) * this._viscosity;
  8389. },
  8390. _onPreDragLimit: function () {
  8391. if (!this._viscosity || !this._offsetLimit) { return; }
  8392. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  8393. var limit = this._offsetLimit;
  8394. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  8395. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  8396. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  8397. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  8398. this._draggable._newPos = this._draggable._startPos.add(offset);
  8399. },
  8400. _onPreDragWrap: function () {
  8401. // TODO refactor to be able to adjust map pane position after zoom
  8402. var worldWidth = this._worldWidth,
  8403. halfWidth = Math.round(worldWidth / 2),
  8404. dx = this._initialWorldOffset,
  8405. x = this._draggable._newPos.x,
  8406. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  8407. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  8408. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  8409. this._draggable._absPos = this._draggable._newPos.clone();
  8410. this._draggable._newPos.x = newX;
  8411. },
  8412. _onDragEnd: function (e) {
  8413. var map = this._map,
  8414. options = map.options,
  8415. noInertia = !options.inertia || this._times.length < 2;
  8416. map.fire('dragend', e);
  8417. if (noInertia) {
  8418. map.fire('moveend');
  8419. } else {
  8420. var direction = this._lastPos.subtract(this._positions[0]),
  8421. duration = (this._lastTime - this._times[0]) / 1000,
  8422. ease = options.easeLinearity,
  8423. speedVector = direction.multiplyBy(ease / duration),
  8424. speed = speedVector.distanceTo([0, 0]),
  8425. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  8426. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  8427. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  8428. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  8429. if (!offset.x && !offset.y) {
  8430. map.fire('moveend');
  8431. } else {
  8432. offset = map._limitOffset(offset, map.options.maxBounds);
  8433. L.Util.requestAnimFrame(function () {
  8434. map.panBy(offset, {
  8435. duration: decelerationDuration,
  8436. easeLinearity: ease,
  8437. noMoveStart: true,
  8438. animate: true
  8439. });
  8440. });
  8441. }
  8442. }
  8443. }
  8444. });
  8445. // @section Handlers
  8446. // @property dragging: Handler
  8447. // Map dragging handler (by both mouse and touch).
  8448. L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
  8449. /*
  8450. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  8451. */
  8452. // @namespace Map
  8453. // @section Interaction Options
  8454. L.Map.mergeOptions({
  8455. // @option doubleClickZoom: Boolean|String = true
  8456. // Whether the map can be zoomed in by double clicking on it and
  8457. // zoomed out by double clicking while holding shift. If passed
  8458. // `'center'`, double-click zoom will zoom to the center of the
  8459. // view regardless of where the mouse was.
  8460. doubleClickZoom: true
  8461. });
  8462. L.Map.DoubleClickZoom = L.Handler.extend({
  8463. addHooks: function () {
  8464. this._map.on('dblclick', this._onDoubleClick, this);
  8465. },
  8466. removeHooks: function () {
  8467. this._map.off('dblclick', this._onDoubleClick, this);
  8468. },
  8469. _onDoubleClick: function (e) {
  8470. var map = this._map,
  8471. oldZoom = map.getZoom(),
  8472. delta = map.options.zoomDelta,
  8473. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  8474. if (map.options.doubleClickZoom === 'center') {
  8475. map.setZoom(zoom);
  8476. } else {
  8477. map.setZoomAround(e.containerPoint, zoom);
  8478. }
  8479. }
  8480. });
  8481. // @section Handlers
  8482. //
  8483. // Map properties include interaction handlers that allow you to control
  8484. // interaction behavior in runtime, enabling or disabling certain features such
  8485. // as dragging or touch zoom (see `Handler` methods). For example:
  8486. //
  8487. // ```js
  8488. // map.doubleClickZoom.disable();
  8489. // ```
  8490. //
  8491. // @property doubleClickZoom: Handler
  8492. // Double click zoom handler.
  8493. L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
  8494. /*
  8495. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  8496. */
  8497. // @namespace Map
  8498. // @section Interaction Options
  8499. L.Map.mergeOptions({
  8500. // @section Mousewheel options
  8501. // @option scrollWheelZoom: Boolean|String = true
  8502. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  8503. // it will zoom to the center of the view regardless of where the mouse was.
  8504. scrollWheelZoom: true,
  8505. // @option wheelDebounceTime: Number = 40
  8506. // Limits the rate at which a wheel can fire (in milliseconds). By default
  8507. // user can't zoom via wheel more often than once per 40 ms.
  8508. wheelDebounceTime: 40,
  8509. // @option wheelPxPerZoomLevel: Number = 60
  8510. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  8511. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  8512. // faster (and vice versa).
  8513. wheelPxPerZoomLevel: 60
  8514. });
  8515. L.Map.ScrollWheelZoom = L.Handler.extend({
  8516. addHooks: function () {
  8517. L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  8518. this._delta = 0;
  8519. },
  8520. removeHooks: function () {
  8521. L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll, this);
  8522. },
  8523. _onWheelScroll: function (e) {
  8524. var delta = L.DomEvent.getWheelDelta(e);
  8525. var debounce = this._map.options.wheelDebounceTime;
  8526. this._delta += delta;
  8527. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  8528. if (!this._startTime) {
  8529. this._startTime = +new Date();
  8530. }
  8531. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  8532. clearTimeout(this._timer);
  8533. this._timer = setTimeout(L.bind(this._performZoom, this), left);
  8534. L.DomEvent.stop(e);
  8535. },
  8536. _performZoom: function () {
  8537. var map = this._map,
  8538. zoom = map.getZoom(),
  8539. snap = this._map.options.zoomSnap || 0;
  8540. map._stop(); // stop panning and fly animations if any
  8541. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  8542. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  8543. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  8544. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  8545. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  8546. this._delta = 0;
  8547. this._startTime = null;
  8548. if (!delta) { return; }
  8549. if (map.options.scrollWheelZoom === 'center') {
  8550. map.setZoom(zoom + delta);
  8551. } else {
  8552. map.setZoomAround(this._lastMousePos, zoom + delta);
  8553. }
  8554. }
  8555. });
  8556. // @section Handlers
  8557. // @property scrollWheelZoom: Handler
  8558. // Scroll wheel zoom handler.
  8559. L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
  8560. /*
  8561. * Extends the event handling code with double tap support for mobile browsers.
  8562. */
  8563. L.extend(L.DomEvent, {
  8564. _touchstart: L.Browser.msPointer ? 'MSPointerDown' : L.Browser.pointer ? 'pointerdown' : 'touchstart',
  8565. _touchend: L.Browser.msPointer ? 'MSPointerUp' : L.Browser.pointer ? 'pointerup' : 'touchend',
  8566. // inspired by Zepto touch code by Thomas Fuchs
  8567. addDoubleTapListener: function (obj, handler, id) {
  8568. var last, touch,
  8569. doubleTap = false,
  8570. delay = 250;
  8571. function onTouchStart(e) {
  8572. var count;
  8573. if (L.Browser.pointer) {
  8574. count = L.DomEvent._pointersCount;
  8575. } else {
  8576. count = e.touches.length;
  8577. }
  8578. if (count > 1) { return; }
  8579. var now = Date.now(),
  8580. delta = now - (last || now);
  8581. touch = e.touches ? e.touches[0] : e;
  8582. doubleTap = (delta > 0 && delta <= delay);
  8583. last = now;
  8584. }
  8585. function onTouchEnd() {
  8586. if (doubleTap && !touch.cancelBubble) {
  8587. if (L.Browser.pointer) {
  8588. // work around .type being readonly with MSPointer* events
  8589. var newTouch = {},
  8590. prop, i;
  8591. for (i in touch) {
  8592. prop = touch[i];
  8593. newTouch[i] = prop && prop.bind ? prop.bind(touch) : prop;
  8594. }
  8595. touch = newTouch;
  8596. }
  8597. touch.type = 'dblclick';
  8598. handler(touch);
  8599. last = null;
  8600. }
  8601. }
  8602. var pre = '_leaflet_',
  8603. touchstart = this._touchstart,
  8604. touchend = this._touchend;
  8605. obj[pre + touchstart + id] = onTouchStart;
  8606. obj[pre + touchend + id] = onTouchEnd;
  8607. obj[pre + 'dblclick' + id] = handler;
  8608. obj.addEventListener(touchstart, onTouchStart, false);
  8609. obj.addEventListener(touchend, onTouchEnd, false);
  8610. // On some platforms (notably, chrome on win10 + touchscreen + mouse),
  8611. // the browser doesn't fire touchend/pointerup events but does fire
  8612. // native dblclicks. See #4127.
  8613. if (!L.Browser.edge) {
  8614. obj.addEventListener('dblclick', handler, false);
  8615. }
  8616. return this;
  8617. },
  8618. removeDoubleTapListener: function (obj, id) {
  8619. var pre = '_leaflet_',
  8620. touchstart = obj[pre + this._touchstart + id],
  8621. touchend = obj[pre + this._touchend + id],
  8622. dblclick = obj[pre + 'dblclick' + id];
  8623. obj.removeEventListener(this._touchstart, touchstart, false);
  8624. obj.removeEventListener(this._touchend, touchend, false);
  8625. if (!L.Browser.edge) {
  8626. obj.removeEventListener('dblclick', dblclick, false);
  8627. }
  8628. return this;
  8629. }
  8630. });
  8631. /*
  8632. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  8633. */
  8634. L.extend(L.DomEvent, {
  8635. POINTER_DOWN: L.Browser.msPointer ? 'MSPointerDown' : 'pointerdown',
  8636. POINTER_MOVE: L.Browser.msPointer ? 'MSPointerMove' : 'pointermove',
  8637. POINTER_UP: L.Browser.msPointer ? 'MSPointerUp' : 'pointerup',
  8638. POINTER_CANCEL: L.Browser.msPointer ? 'MSPointerCancel' : 'pointercancel',
  8639. TAG_WHITE_LIST: ['INPUT', 'SELECT', 'OPTION'],
  8640. _pointers: {},
  8641. _pointersCount: 0,
  8642. // Provides a touch events wrapper for (ms)pointer events.
  8643. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  8644. addPointerListener: function (obj, type, handler, id) {
  8645. if (type === 'touchstart') {
  8646. this._addPointerStart(obj, handler, id);
  8647. } else if (type === 'touchmove') {
  8648. this._addPointerMove(obj, handler, id);
  8649. } else if (type === 'touchend') {
  8650. this._addPointerEnd(obj, handler, id);
  8651. }
  8652. return this;
  8653. },
  8654. removePointerListener: function (obj, type, id) {
  8655. var handler = obj['_leaflet_' + type + id];
  8656. if (type === 'touchstart') {
  8657. obj.removeEventListener(this.POINTER_DOWN, handler, false);
  8658. } else if (type === 'touchmove') {
  8659. obj.removeEventListener(this.POINTER_MOVE, handler, false);
  8660. } else if (type === 'touchend') {
  8661. obj.removeEventListener(this.POINTER_UP, handler, false);
  8662. obj.removeEventListener(this.POINTER_CANCEL, handler, false);
  8663. }
  8664. return this;
  8665. },
  8666. _addPointerStart: function (obj, handler, id) {
  8667. var onDown = L.bind(function (e) {
  8668. if (e.pointerType !== 'mouse' && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
  8669. // In IE11, some touch events needs to fire for form controls, or
  8670. // the controls will stop working. We keep a whitelist of tag names that
  8671. // need these events. For other target tags, we prevent default on the event.
  8672. if (this.TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
  8673. L.DomEvent.preventDefault(e);
  8674. } else {
  8675. return;
  8676. }
  8677. }
  8678. this._handlePointer(e, handler);
  8679. }, this);
  8680. obj['_leaflet_touchstart' + id] = onDown;
  8681. obj.addEventListener(this.POINTER_DOWN, onDown, false);
  8682. // need to keep track of what pointers and how many are active to provide e.touches emulation
  8683. if (!this._pointerDocListener) {
  8684. var pointerUp = L.bind(this._globalPointerUp, this);
  8685. // we listen documentElement as any drags that end by moving the touch off the screen get fired there
  8686. document.documentElement.addEventListener(this.POINTER_DOWN, L.bind(this._globalPointerDown, this), true);
  8687. document.documentElement.addEventListener(this.POINTER_MOVE, L.bind(this._globalPointerMove, this), true);
  8688. document.documentElement.addEventListener(this.POINTER_UP, pointerUp, true);
  8689. document.documentElement.addEventListener(this.POINTER_CANCEL, pointerUp, true);
  8690. this._pointerDocListener = true;
  8691. }
  8692. },
  8693. _globalPointerDown: function (e) {
  8694. this._pointers[e.pointerId] = e;
  8695. this._pointersCount++;
  8696. },
  8697. _globalPointerMove: function (e) {
  8698. if (this._pointers[e.pointerId]) {
  8699. this._pointers[e.pointerId] = e;
  8700. }
  8701. },
  8702. _globalPointerUp: function (e) {
  8703. delete this._pointers[e.pointerId];
  8704. this._pointersCount--;
  8705. },
  8706. _handlePointer: function (e, handler) {
  8707. e.touches = [];
  8708. for (var i in this._pointers) {
  8709. e.touches.push(this._pointers[i]);
  8710. }
  8711. e.changedTouches = [e];
  8712. handler(e);
  8713. },
  8714. _addPointerMove: function (obj, handler, id) {
  8715. var onMove = L.bind(function (e) {
  8716. // don't fire touch moves when mouse isn't down
  8717. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
  8718. this._handlePointer(e, handler);
  8719. }, this);
  8720. obj['_leaflet_touchmove' + id] = onMove;
  8721. obj.addEventListener(this.POINTER_MOVE, onMove, false);
  8722. },
  8723. _addPointerEnd: function (obj, handler, id) {
  8724. var onUp = L.bind(function (e) {
  8725. this._handlePointer(e, handler);
  8726. }, this);
  8727. obj['_leaflet_touchend' + id] = onUp;
  8728. obj.addEventListener(this.POINTER_UP, onUp, false);
  8729. obj.addEventListener(this.POINTER_CANCEL, onUp, false);
  8730. }
  8731. });
  8732. /*
  8733. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  8734. */
  8735. // @namespace Map
  8736. // @section Interaction Options
  8737. L.Map.mergeOptions({
  8738. // @section Touch interaction options
  8739. // @option touchZoom: Boolean|String = *
  8740. // Whether the map can be zoomed by touch-dragging with two fingers. If
  8741. // passed `'center'`, it will zoom to the center of the view regardless of
  8742. // where the touch events (fingers) were. Enabled for touch-capable web
  8743. // browsers except for old Androids.
  8744. touchZoom: L.Browser.touch && !L.Browser.android23,
  8745. // @option bounceAtZoomLimits: Boolean = true
  8746. // Set it to false if you don't want the map to zoom beyond min/max zoom
  8747. // and then bounce back when pinch-zooming.
  8748. bounceAtZoomLimits: true
  8749. });
  8750. L.Map.TouchZoom = L.Handler.extend({
  8751. addHooks: function () {
  8752. L.DomUtil.addClass(this._map._container, 'leaflet-touch-zoom');
  8753. L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
  8754. },
  8755. removeHooks: function () {
  8756. L.DomUtil.removeClass(this._map._container, 'leaflet-touch-zoom');
  8757. L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
  8758. },
  8759. _onTouchStart: function (e) {
  8760. var map = this._map;
  8761. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  8762. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  8763. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  8764. this._centerPoint = map.getSize()._divideBy(2);
  8765. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  8766. if (map.options.touchZoom !== 'center') {
  8767. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  8768. }
  8769. this._startDist = p1.distanceTo(p2);
  8770. this._startZoom = map.getZoom();
  8771. this._moved = false;
  8772. this._zooming = true;
  8773. map._stop();
  8774. L.DomEvent
  8775. .on(document, 'touchmove', this._onTouchMove, this)
  8776. .on(document, 'touchend', this._onTouchEnd, this);
  8777. L.DomEvent.preventDefault(e);
  8778. },
  8779. _onTouchMove: function (e) {
  8780. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  8781. var map = this._map,
  8782. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  8783. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  8784. scale = p1.distanceTo(p2) / this._startDist;
  8785. this._zoom = map.getScaleZoom(scale, this._startZoom);
  8786. if (!map.options.bounceAtZoomLimits && (
  8787. (this._zoom < map.getMinZoom() && scale < 1) ||
  8788. (this._zoom > map.getMaxZoom() && scale > 1))) {
  8789. this._zoom = map._limitZoom(this._zoom);
  8790. }
  8791. if (map.options.touchZoom === 'center') {
  8792. this._center = this._startLatLng;
  8793. if (scale === 1) { return; }
  8794. } else {
  8795. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  8796. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  8797. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  8798. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  8799. }
  8800. if (!this._moved) {
  8801. map._moveStart(true);
  8802. this._moved = true;
  8803. }
  8804. L.Util.cancelAnimFrame(this._animRequest);
  8805. var moveFn = L.bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  8806. this._animRequest = L.Util.requestAnimFrame(moveFn, this, true);
  8807. L.DomEvent.preventDefault(e);
  8808. },
  8809. _onTouchEnd: function () {
  8810. if (!this._moved || !this._zooming) {
  8811. this._zooming = false;
  8812. return;
  8813. }
  8814. this._zooming = false;
  8815. L.Util.cancelAnimFrame(this._animRequest);
  8816. L.DomEvent
  8817. .off(document, 'touchmove', this._onTouchMove)
  8818. .off(document, 'touchend', this._onTouchEnd);
  8819. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  8820. if (this._map.options.zoomAnimation) {
  8821. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  8822. } else {
  8823. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  8824. }
  8825. }
  8826. });
  8827. // @section Handlers
  8828. // @property touchZoom: Handler
  8829. // Touch zoom handler.
  8830. L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
  8831. /*
  8832. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  8833. */
  8834. // @namespace Map
  8835. // @section Interaction Options
  8836. L.Map.mergeOptions({
  8837. // @section Touch interaction options
  8838. // @option tap: Boolean = true
  8839. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  8840. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  8841. tap: true,
  8842. // @option tapTolerance: Number = 15
  8843. // The max number of pixels a user can shift his finger during touch
  8844. // for it to be considered a valid tap.
  8845. tapTolerance: 15
  8846. });
  8847. L.Map.Tap = L.Handler.extend({
  8848. addHooks: function () {
  8849. L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
  8850. },
  8851. removeHooks: function () {
  8852. L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
  8853. },
  8854. _onDown: function (e) {
  8855. if (!e.touches) { return; }
  8856. L.DomEvent.preventDefault(e);
  8857. this._fireClick = true;
  8858. // don't simulate click or track longpress if more than 1 touch
  8859. if (e.touches.length > 1) {
  8860. this._fireClick = false;
  8861. clearTimeout(this._holdTimeout);
  8862. return;
  8863. }
  8864. var first = e.touches[0],
  8865. el = first.target;
  8866. this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
  8867. // if touching a link, highlight it
  8868. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  8869. L.DomUtil.addClass(el, 'leaflet-active');
  8870. }
  8871. // simulate long hold but setting a timeout
  8872. this._holdTimeout = setTimeout(L.bind(function () {
  8873. if (this._isTapValid()) {
  8874. this._fireClick = false;
  8875. this._onUp();
  8876. this._simulateEvent('contextmenu', first);
  8877. }
  8878. }, this), 1000);
  8879. this._simulateEvent('mousedown', first);
  8880. L.DomEvent.on(document, {
  8881. touchmove: this._onMove,
  8882. touchend: this._onUp
  8883. }, this);
  8884. },
  8885. _onUp: function (e) {
  8886. clearTimeout(this._holdTimeout);
  8887. L.DomEvent.off(document, {
  8888. touchmove: this._onMove,
  8889. touchend: this._onUp
  8890. }, this);
  8891. if (this._fireClick && e && e.changedTouches) {
  8892. var first = e.changedTouches[0],
  8893. el = first.target;
  8894. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  8895. L.DomUtil.removeClass(el, 'leaflet-active');
  8896. }
  8897. this._simulateEvent('mouseup', first);
  8898. // simulate click if the touch didn't move too much
  8899. if (this._isTapValid()) {
  8900. this._simulateEvent('click', first);
  8901. }
  8902. }
  8903. },
  8904. _isTapValid: function () {
  8905. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  8906. },
  8907. _onMove: function (e) {
  8908. var first = e.touches[0];
  8909. this._newPos = new L.Point(first.clientX, first.clientY);
  8910. this._simulateEvent('mousemove', first);
  8911. },
  8912. _simulateEvent: function (type, e) {
  8913. var simulatedEvent = document.createEvent('MouseEvents');
  8914. simulatedEvent._simulated = true;
  8915. e.target._simulatedClick = true;
  8916. simulatedEvent.initMouseEvent(
  8917. type, true, true, window, 1,
  8918. e.screenX, e.screenY,
  8919. e.clientX, e.clientY,
  8920. false, false, false, false, 0, null);
  8921. e.target.dispatchEvent(simulatedEvent);
  8922. }
  8923. });
  8924. // @section Handlers
  8925. // @property tap: Handler
  8926. // Mobile touch hacks (quick tap and touch hold) handler.
  8927. if (L.Browser.touch && !L.Browser.pointer) {
  8928. L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
  8929. }
  8930. /*
  8931. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  8932. * (zoom to a selected bounding box), enabled by default.
  8933. */
  8934. // @namespace Map
  8935. // @section Interaction Options
  8936. L.Map.mergeOptions({
  8937. // @option boxZoom: Boolean = true
  8938. // Whether the map can be zoomed to a rectangular area specified by
  8939. // dragging the mouse while pressing the shift key.
  8940. boxZoom: true
  8941. });
  8942. L.Map.BoxZoom = L.Handler.extend({
  8943. initialize: function (map) {
  8944. this._map = map;
  8945. this._container = map._container;
  8946. this._pane = map._panes.overlayPane;
  8947. },
  8948. addHooks: function () {
  8949. L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
  8950. },
  8951. removeHooks: function () {
  8952. L.DomEvent.off(this._container, 'mousedown', this._onMouseDown, this);
  8953. },
  8954. moved: function () {
  8955. return this._moved;
  8956. },
  8957. _resetState: function () {
  8958. this._moved = false;
  8959. },
  8960. _onMouseDown: function (e) {
  8961. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  8962. this._resetState();
  8963. L.DomUtil.disableTextSelection();
  8964. L.DomUtil.disableImageDrag();
  8965. this._startPoint = this._map.mouseEventToContainerPoint(e);
  8966. L.DomEvent.on(document, {
  8967. contextmenu: L.DomEvent.stop,
  8968. mousemove: this._onMouseMove,
  8969. mouseup: this._onMouseUp,
  8970. keydown: this._onKeyDown
  8971. }, this);
  8972. },
  8973. _onMouseMove: function (e) {
  8974. if (!this._moved) {
  8975. this._moved = true;
  8976. this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._container);
  8977. L.DomUtil.addClass(this._container, 'leaflet-crosshair');
  8978. this._map.fire('boxzoomstart');
  8979. }
  8980. this._point = this._map.mouseEventToContainerPoint(e);
  8981. var bounds = new L.Bounds(this._point, this._startPoint),
  8982. size = bounds.getSize();
  8983. L.DomUtil.setPosition(this._box, bounds.min);
  8984. this._box.style.width = size.x + 'px';
  8985. this._box.style.height = size.y + 'px';
  8986. },
  8987. _finish: function () {
  8988. if (this._moved) {
  8989. L.DomUtil.remove(this._box);
  8990. L.DomUtil.removeClass(this._container, 'leaflet-crosshair');
  8991. }
  8992. L.DomUtil.enableTextSelection();
  8993. L.DomUtil.enableImageDrag();
  8994. L.DomEvent.off(document, {
  8995. contextmenu: L.DomEvent.stop,
  8996. mousemove: this._onMouseMove,
  8997. mouseup: this._onMouseUp,
  8998. keydown: this._onKeyDown
  8999. }, this);
  9000. },
  9001. _onMouseUp: function (e) {
  9002. if ((e.which !== 1) && (e.button !== 1)) { return; }
  9003. this._finish();
  9004. if (!this._moved) { return; }
  9005. // Postpone to next JS tick so internal click event handling
  9006. // still see it as "moved".
  9007. setTimeout(L.bind(this._resetState, this), 0);
  9008. var bounds = new L.LatLngBounds(
  9009. this._map.containerPointToLatLng(this._startPoint),
  9010. this._map.containerPointToLatLng(this._point));
  9011. this._map
  9012. .fitBounds(bounds)
  9013. .fire('boxzoomend', {boxZoomBounds: bounds});
  9014. },
  9015. _onKeyDown: function (e) {
  9016. if (e.keyCode === 27) {
  9017. this._finish();
  9018. }
  9019. }
  9020. });
  9021. // @section Handlers
  9022. // @property boxZoom: Handler
  9023. // Box (shift-drag with mouse) zoom handler.
  9024. L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
  9025. /*
  9026. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  9027. */
  9028. // @namespace Map
  9029. // @section Keyboard Navigation Options
  9030. L.Map.mergeOptions({
  9031. // @option keyboard: Boolean = true
  9032. // Makes the map focusable and allows users to navigate the map with keyboard
  9033. // arrows and `+`/`-` keys.
  9034. keyboard: true,
  9035. // @option keyboardPanDelta: Number = 80
  9036. // Amount of pixels to pan when pressing an arrow key.
  9037. keyboardPanDelta: 80
  9038. });
  9039. L.Map.Keyboard = L.Handler.extend({
  9040. keyCodes: {
  9041. left: [37],
  9042. right: [39],
  9043. down: [40],
  9044. up: [38],
  9045. zoomIn: [187, 107, 61, 171],
  9046. zoomOut: [189, 109, 54, 173]
  9047. },
  9048. initialize: function (map) {
  9049. this._map = map;
  9050. this._setPanDelta(map.options.keyboardPanDelta);
  9051. this._setZoomDelta(map.options.zoomDelta);
  9052. },
  9053. addHooks: function () {
  9054. var container = this._map._container;
  9055. // make the container focusable by tabbing
  9056. if (container.tabIndex <= 0) {
  9057. container.tabIndex = '0';
  9058. }
  9059. L.DomEvent.on(container, {
  9060. focus: this._onFocus,
  9061. blur: this._onBlur,
  9062. mousedown: this._onMouseDown
  9063. }, this);
  9064. this._map.on({
  9065. focus: this._addHooks,
  9066. blur: this._removeHooks
  9067. }, this);
  9068. },
  9069. removeHooks: function () {
  9070. this._removeHooks();
  9071. L.DomEvent.off(this._map._container, {
  9072. focus: this._onFocus,
  9073. blur: this._onBlur,
  9074. mousedown: this._onMouseDown
  9075. }, this);
  9076. this._map.off({
  9077. focus: this._addHooks,
  9078. blur: this._removeHooks
  9079. }, this);
  9080. },
  9081. _onMouseDown: function () {
  9082. if (this._focused) { return; }
  9083. var body = document.body,
  9084. docEl = document.documentElement,
  9085. top = body.scrollTop || docEl.scrollTop,
  9086. left = body.scrollLeft || docEl.scrollLeft;
  9087. this._map._container.focus();
  9088. window.scrollTo(left, top);
  9089. },
  9090. _onFocus: function () {
  9091. this._focused = true;
  9092. this._map.fire('focus');
  9093. },
  9094. _onBlur: function () {
  9095. this._focused = false;
  9096. this._map.fire('blur');
  9097. },
  9098. _setPanDelta: function (panDelta) {
  9099. var keys = this._panKeys = {},
  9100. codes = this.keyCodes,
  9101. i, len;
  9102. for (i = 0, len = codes.left.length; i < len; i++) {
  9103. keys[codes.left[i]] = [-1 * panDelta, 0];
  9104. }
  9105. for (i = 0, len = codes.right.length; i < len; i++) {
  9106. keys[codes.right[i]] = [panDelta, 0];
  9107. }
  9108. for (i = 0, len = codes.down.length; i < len; i++) {
  9109. keys[codes.down[i]] = [0, panDelta];
  9110. }
  9111. for (i = 0, len = codes.up.length; i < len; i++) {
  9112. keys[codes.up[i]] = [0, -1 * panDelta];
  9113. }
  9114. },
  9115. _setZoomDelta: function (zoomDelta) {
  9116. var keys = this._zoomKeys = {},
  9117. codes = this.keyCodes,
  9118. i, len;
  9119. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  9120. keys[codes.zoomIn[i]] = zoomDelta;
  9121. }
  9122. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  9123. keys[codes.zoomOut[i]] = -zoomDelta;
  9124. }
  9125. },
  9126. _addHooks: function () {
  9127. L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
  9128. },
  9129. _removeHooks: function () {
  9130. L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
  9131. },
  9132. _onKeyDown: function (e) {
  9133. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  9134. var key = e.keyCode,
  9135. map = this._map,
  9136. offset;
  9137. if (key in this._panKeys) {
  9138. if (map._panAnim && map._panAnim._inProgress) { return; }
  9139. offset = this._panKeys[key];
  9140. if (e.shiftKey) {
  9141. offset = L.point(offset).multiplyBy(3);
  9142. }
  9143. map.panBy(offset);
  9144. if (map.options.maxBounds) {
  9145. map.panInsideBounds(map.options.maxBounds);
  9146. }
  9147. } else if (key in this._zoomKeys) {
  9148. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  9149. } else if (key === 27) {
  9150. map.closePopup();
  9151. } else {
  9152. return;
  9153. }
  9154. L.DomEvent.stop(e);
  9155. }
  9156. });
  9157. // @section Handlers
  9158. // @section Handlers
  9159. // @property keyboard: Handler
  9160. // Keyboard navigation handler.
  9161. L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
  9162. /*
  9163. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  9164. */
  9165. /* @namespace Marker
  9166. * @section Interaction handlers
  9167. *
  9168. * 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:
  9169. *
  9170. * ```js
  9171. * marker.dragging.disable();
  9172. * ```
  9173. *
  9174. * @property dragging: Handler
  9175. * Marker dragging handler (by both mouse and touch).
  9176. */
  9177. L.Handler.MarkerDrag = L.Handler.extend({
  9178. initialize: function (marker) {
  9179. this._marker = marker;
  9180. },
  9181. addHooks: function () {
  9182. var icon = this._marker._icon;
  9183. if (!this._draggable) {
  9184. this._draggable = new L.Draggable(icon, icon, true);
  9185. }
  9186. this._draggable.on({
  9187. dragstart: this._onDragStart,
  9188. drag: this._onDrag,
  9189. dragend: this._onDragEnd
  9190. }, this).enable();
  9191. L.DomUtil.addClass(icon, 'leaflet-marker-draggable');
  9192. },
  9193. removeHooks: function () {
  9194. this._draggable.off({
  9195. dragstart: this._onDragStart,
  9196. drag: this._onDrag,
  9197. dragend: this._onDragEnd
  9198. }, this).disable();
  9199. if (this._marker._icon) {
  9200. L.DomUtil.removeClass(this._marker._icon, 'leaflet-marker-draggable');
  9201. }
  9202. },
  9203. moved: function () {
  9204. return this._draggable && this._draggable._moved;
  9205. },
  9206. _onDragStart: function () {
  9207. // @section Dragging events
  9208. // @event dragstart: Event
  9209. // Fired when the user starts dragging the marker.
  9210. // @event movestart: Event
  9211. // Fired when the marker starts moving (because of dragging).
  9212. this._oldLatLng = this._marker.getLatLng();
  9213. this._marker
  9214. .closePopup()
  9215. .fire('movestart')
  9216. .fire('dragstart');
  9217. },
  9218. _onDrag: function (e) {
  9219. var marker = this._marker,
  9220. shadow = marker._shadow,
  9221. iconPos = L.DomUtil.getPosition(marker._icon),
  9222. latlng = marker._map.layerPointToLatLng(iconPos);
  9223. // update shadow position
  9224. if (shadow) {
  9225. L.DomUtil.setPosition(shadow, iconPos);
  9226. }
  9227. marker._latlng = latlng;
  9228. e.latlng = latlng;
  9229. e.oldLatLng = this._oldLatLng;
  9230. // @event drag: Event
  9231. // Fired repeatedly while the user drags the marker.
  9232. marker
  9233. .fire('move', e)
  9234. .fire('drag', e);
  9235. },
  9236. _onDragEnd: function (e) {
  9237. // @event dragend: DragEndEvent
  9238. // Fired when the user stops dragging the marker.
  9239. // @event moveend: Event
  9240. // Fired when the marker stops moving (because of dragging).
  9241. delete this._oldLatLng;
  9242. this._marker
  9243. .fire('moveend')
  9244. .fire('dragend', e);
  9245. }
  9246. });
  9247. /*
  9248. * @class Control
  9249. * @aka L.Control
  9250. *
  9251. * L.Control is a base class for implementing map controls. Handles positioning.
  9252. * All other controls extend from this class.
  9253. */
  9254. L.Control = L.Class.extend({
  9255. // @section
  9256. // @aka Control options
  9257. options: {
  9258. // @option position: String = 'topright'
  9259. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  9260. // `'topright'`, `'bottomleft'` or `'bottomright'`
  9261. position: 'topright'
  9262. },
  9263. initialize: function (options) {
  9264. L.setOptions(this, options);
  9265. },
  9266. /* @section
  9267. * Classes extending L.Control will inherit the following methods:
  9268. *
  9269. * @method getPosition: string
  9270. * Returns the position of the control.
  9271. */
  9272. getPosition: function () {
  9273. return this.options.position;
  9274. },
  9275. // @method setPosition(position: string): this
  9276. // Sets the position of the control.
  9277. setPosition: function (position) {
  9278. var map = this._map;
  9279. if (map) {
  9280. map.removeControl(this);
  9281. }
  9282. this.options.position = position;
  9283. if (map) {
  9284. map.addControl(this);
  9285. }
  9286. return this;
  9287. },
  9288. // @method getContainer: HTMLElement
  9289. // Returns the HTMLElement that contains the control.
  9290. getContainer: function () {
  9291. return this._container;
  9292. },
  9293. // @method addTo(map: Map): this
  9294. // Adds the control to the given map.
  9295. addTo: function (map) {
  9296. this.remove();
  9297. this._map = map;
  9298. var container = this._container = this.onAdd(map),
  9299. pos = this.getPosition(),
  9300. corner = map._controlCorners[pos];
  9301. L.DomUtil.addClass(container, 'leaflet-control');
  9302. if (pos.indexOf('bottom') !== -1) {
  9303. corner.insertBefore(container, corner.firstChild);
  9304. } else {
  9305. corner.appendChild(container);
  9306. }
  9307. return this;
  9308. },
  9309. // @method remove: this
  9310. // Removes the control from the map it is currently active on.
  9311. remove: function () {
  9312. if (!this._map) {
  9313. return this;
  9314. }
  9315. L.DomUtil.remove(this._container);
  9316. if (this.onRemove) {
  9317. this.onRemove(this._map);
  9318. }
  9319. this._map = null;
  9320. return this;
  9321. },
  9322. _refocusOnMap: function (e) {
  9323. // if map exists and event is not a keyboard event
  9324. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  9325. this._map.getContainer().focus();
  9326. }
  9327. }
  9328. });
  9329. L.control = function (options) {
  9330. return new L.Control(options);
  9331. };
  9332. /* @section Extension methods
  9333. * @uninheritable
  9334. *
  9335. * Every control should extend from `L.Control` and (re-)implement the following methods.
  9336. *
  9337. * @method onAdd(map: Map): HTMLElement
  9338. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  9339. *
  9340. * @method onRemove(map: Map)
  9341. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  9342. */
  9343. /* @namespace Map
  9344. * @section Methods for Layers and Controls
  9345. */
  9346. L.Map.include({
  9347. // @method addControl(control: Control): this
  9348. // Adds the given control to the map
  9349. addControl: function (control) {
  9350. control.addTo(this);
  9351. return this;
  9352. },
  9353. // @method removeControl(control: Control): this
  9354. // Removes the given control from the map
  9355. removeControl: function (control) {
  9356. control.remove();
  9357. return this;
  9358. },
  9359. _initControlPos: function () {
  9360. var corners = this._controlCorners = {},
  9361. l = 'leaflet-',
  9362. container = this._controlContainer =
  9363. L.DomUtil.create('div', l + 'control-container', this._container);
  9364. function createCorner(vSide, hSide) {
  9365. var className = l + vSide + ' ' + l + hSide;
  9366. corners[vSide + hSide] = L.DomUtil.create('div', className, container);
  9367. }
  9368. createCorner('top', 'left');
  9369. createCorner('top', 'right');
  9370. createCorner('bottom', 'left');
  9371. createCorner('bottom', 'right');
  9372. },
  9373. _clearControlPos: function () {
  9374. L.DomUtil.remove(this._controlContainer);
  9375. }
  9376. });
  9377. /*
  9378. * @class Control.Zoom
  9379. * @aka L.Control.Zoom
  9380. * @inherits Control
  9381. *
  9382. * 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`.
  9383. */
  9384. L.Control.Zoom = L.Control.extend({
  9385. // @section
  9386. // @aka Control.Zoom options
  9387. options: {
  9388. position: 'topleft',
  9389. // @option zoomInText: String = '+'
  9390. // The text set on the 'zoom in' button.
  9391. zoomInText: '+',
  9392. // @option zoomInTitle: String = 'Zoom in'
  9393. // The title set on the 'zoom in' button.
  9394. zoomInTitle: 'Zoom in',
  9395. // @option zoomOutText: String = '-'
  9396. // The text set on the 'zoom out' button.
  9397. zoomOutText: '-',
  9398. // @option zoomOutTitle: String = 'Zoom out'
  9399. // The title set on the 'zoom out' button.
  9400. zoomOutTitle: 'Zoom out'
  9401. },
  9402. onAdd: function (map) {
  9403. var zoomName = 'leaflet-control-zoom',
  9404. container = L.DomUtil.create('div', zoomName + ' leaflet-bar'),
  9405. options = this.options;
  9406. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  9407. zoomName + '-in', container, this._zoomIn);
  9408. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  9409. zoomName + '-out', container, this._zoomOut);
  9410. this._updateDisabled();
  9411. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  9412. return container;
  9413. },
  9414. onRemove: function (map) {
  9415. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  9416. },
  9417. disable: function () {
  9418. this._disabled = true;
  9419. this._updateDisabled();
  9420. return this;
  9421. },
  9422. enable: function () {
  9423. this._disabled = false;
  9424. this._updateDisabled();
  9425. return this;
  9426. },
  9427. _zoomIn: function (e) {
  9428. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  9429. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  9430. }
  9431. },
  9432. _zoomOut: function (e) {
  9433. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  9434. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  9435. }
  9436. },
  9437. _createButton: function (html, title, className, container, fn) {
  9438. var link = L.DomUtil.create('a', className, container);
  9439. link.innerHTML = html;
  9440. link.href = '#';
  9441. link.title = title;
  9442. L.DomEvent
  9443. .on(link, 'mousedown dblclick', L.DomEvent.stopPropagation)
  9444. .on(link, 'click', L.DomEvent.stop)
  9445. .on(link, 'click', fn, this)
  9446. .on(link, 'click', this._refocusOnMap, this);
  9447. return link;
  9448. },
  9449. _updateDisabled: function () {
  9450. var map = this._map,
  9451. className = 'leaflet-disabled';
  9452. L.DomUtil.removeClass(this._zoomInButton, className);
  9453. L.DomUtil.removeClass(this._zoomOutButton, className);
  9454. if (this._disabled || map._zoom === map.getMinZoom()) {
  9455. L.DomUtil.addClass(this._zoomOutButton, className);
  9456. }
  9457. if (this._disabled || map._zoom === map.getMaxZoom()) {
  9458. L.DomUtil.addClass(this._zoomInButton, className);
  9459. }
  9460. }
  9461. });
  9462. // @namespace Map
  9463. // @section Control options
  9464. // @option zoomControl: Boolean = true
  9465. // Whether a [zoom control](#control-zoom) is added to the map by default.
  9466. L.Map.mergeOptions({
  9467. zoomControl: true
  9468. });
  9469. L.Map.addInitHook(function () {
  9470. if (this.options.zoomControl) {
  9471. this.zoomControl = new L.Control.Zoom();
  9472. this.addControl(this.zoomControl);
  9473. }
  9474. });
  9475. // @namespace Control.Zoom
  9476. // @factory L.control.zoom(options: Control.Zoom options)
  9477. // Creates a zoom control
  9478. L.control.zoom = function (options) {
  9479. return new L.Control.Zoom(options);
  9480. };
  9481. /*
  9482. * @class Control.Attribution
  9483. * @aka L.Control.Attribution
  9484. * @inherits Control
  9485. *
  9486. * 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.
  9487. */
  9488. L.Control.Attribution = L.Control.extend({
  9489. // @section
  9490. // @aka Control.Attribution options
  9491. options: {
  9492. position: 'bottomright',
  9493. // @option prefix: String = 'Leaflet'
  9494. // The HTML text shown before the attributions. Pass `false` to disable.
  9495. prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  9496. },
  9497. initialize: function (options) {
  9498. L.setOptions(this, options);
  9499. this._attributions = {};
  9500. },
  9501. onAdd: function (map) {
  9502. map.attributionControl = this;
  9503. this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
  9504. if (L.DomEvent) {
  9505. L.DomEvent.disableClickPropagation(this._container);
  9506. }
  9507. // TODO ugly, refactor
  9508. for (var i in map._layers) {
  9509. if (map._layers[i].getAttribution) {
  9510. this.addAttribution(map._layers[i].getAttribution());
  9511. }
  9512. }
  9513. this._update();
  9514. return this._container;
  9515. },
  9516. // @method setPrefix(prefix: String): this
  9517. // Sets the text before the attributions.
  9518. setPrefix: function (prefix) {
  9519. this.options.prefix = prefix;
  9520. this._update();
  9521. return this;
  9522. },
  9523. // @method addAttribution(text: String): this
  9524. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  9525. addAttribution: function (text) {
  9526. if (!text) { return this; }
  9527. if (!this._attributions[text]) {
  9528. this._attributions[text] = 0;
  9529. }
  9530. this._attributions[text]++;
  9531. this._update();
  9532. return this;
  9533. },
  9534. // @method removeAttribution(text: String): this
  9535. // Removes an attribution text.
  9536. removeAttribution: function (text) {
  9537. if (!text) { return this; }
  9538. if (this._attributions[text]) {
  9539. this._attributions[text]--;
  9540. this._update();
  9541. }
  9542. return this;
  9543. },
  9544. _update: function () {
  9545. if (!this._map) { return; }
  9546. var attribs = [];
  9547. for (var i in this._attributions) {
  9548. if (this._attributions[i]) {
  9549. attribs.push(i);
  9550. }
  9551. }
  9552. var prefixAndAttribs = [];
  9553. if (this.options.prefix) {
  9554. prefixAndAttribs.push(this.options.prefix);
  9555. }
  9556. if (attribs.length) {
  9557. prefixAndAttribs.push(attribs.join(', '));
  9558. }
  9559. this._container.innerHTML = prefixAndAttribs.join(' | ');
  9560. }
  9561. });
  9562. // @namespace Map
  9563. // @section Control options
  9564. // @option attributionControl: Boolean = true
  9565. // Whether a [attribution control](#control-attribution) is added to the map by default.
  9566. L.Map.mergeOptions({
  9567. attributionControl: true
  9568. });
  9569. L.Map.addInitHook(function () {
  9570. if (this.options.attributionControl) {
  9571. new L.Control.Attribution().addTo(this);
  9572. }
  9573. });
  9574. // @namespace Control.Attribution
  9575. // @factory L.control.attribution(options: Control.Attribution options)
  9576. // Creates an attribution control.
  9577. L.control.attribution = function (options) {
  9578. return new L.Control.Attribution(options);
  9579. };
  9580. /*
  9581. * @class Control.Scale
  9582. * @aka L.Control.Scale
  9583. * @inherits Control
  9584. *
  9585. * 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`.
  9586. *
  9587. * @example
  9588. *
  9589. * ```js
  9590. * L.control.scale().addTo(map);
  9591. * ```
  9592. */
  9593. L.Control.Scale = L.Control.extend({
  9594. // @section
  9595. // @aka Control.Scale options
  9596. options: {
  9597. position: 'bottomleft',
  9598. // @option maxWidth: Number = 100
  9599. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  9600. maxWidth: 100,
  9601. // @option metric: Boolean = True
  9602. // Whether to show the metric scale line (m/km).
  9603. metric: true,
  9604. // @option imperial: Boolean = True
  9605. // Whether to show the imperial scale line (mi/ft).
  9606. imperial: true
  9607. // @option updateWhenIdle: Boolean = false
  9608. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  9609. },
  9610. onAdd: function (map) {
  9611. var className = 'leaflet-control-scale',
  9612. container = L.DomUtil.create('div', className),
  9613. options = this.options;
  9614. this._addScales(options, className + '-line', container);
  9615. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  9616. map.whenReady(this._update, this);
  9617. return container;
  9618. },
  9619. onRemove: function (map) {
  9620. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  9621. },
  9622. _addScales: function (options, className, container) {
  9623. if (options.metric) {
  9624. this._mScale = L.DomUtil.create('div', className, container);
  9625. }
  9626. if (options.imperial) {
  9627. this._iScale = L.DomUtil.create('div', className, container);
  9628. }
  9629. },
  9630. _update: function () {
  9631. var map = this._map,
  9632. y = map.getSize().y / 2;
  9633. var maxMeters = map.distance(
  9634. map.containerPointToLatLng([0, y]),
  9635. map.containerPointToLatLng([this.options.maxWidth, y]));
  9636. this._updateScales(maxMeters);
  9637. },
  9638. _updateScales: function (maxMeters) {
  9639. if (this.options.metric && maxMeters) {
  9640. this._updateMetric(maxMeters);
  9641. }
  9642. if (this.options.imperial && maxMeters) {
  9643. this._updateImperial(maxMeters);
  9644. }
  9645. },
  9646. _updateMetric: function (maxMeters) {
  9647. var meters = this._getRoundNum(maxMeters),
  9648. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  9649. this._updateScale(this._mScale, label, meters / maxMeters);
  9650. },
  9651. _updateImperial: function (maxMeters) {
  9652. var maxFeet = maxMeters * 3.2808399,
  9653. maxMiles, miles, feet;
  9654. if (maxFeet > 5280) {
  9655. maxMiles = maxFeet / 5280;
  9656. miles = this._getRoundNum(maxMiles);
  9657. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  9658. } else {
  9659. feet = this._getRoundNum(maxFeet);
  9660. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  9661. }
  9662. },
  9663. _updateScale: function (scale, text, ratio) {
  9664. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  9665. scale.innerHTML = text;
  9666. },
  9667. _getRoundNum: function (num) {
  9668. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  9669. d = num / pow10;
  9670. d = d >= 10 ? 10 :
  9671. d >= 5 ? 5 :
  9672. d >= 3 ? 3 :
  9673. d >= 2 ? 2 : 1;
  9674. return pow10 * d;
  9675. }
  9676. });
  9677. // @factory L.control.scale(options?: Control.Scale options)
  9678. // Creates an scale control with the given options.
  9679. L.control.scale = function (options) {
  9680. return new L.Control.Scale(options);
  9681. };
  9682. /*
  9683. * @class Control.Layers
  9684. * @aka L.Control.Layers
  9685. * @inherits Control
  9686. *
  9687. * 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.html)). Extends `Control`.
  9688. *
  9689. * @example
  9690. *
  9691. * ```js
  9692. * var baseLayers = {
  9693. * "Mapbox": mapbox,
  9694. * "OpenStreetMap": osm
  9695. * };
  9696. *
  9697. * var overlays = {
  9698. * "Marker": marker,
  9699. * "Roads": roadsLayer
  9700. * };
  9701. *
  9702. * L.control.layers(baseLayers, overlays).addTo(map);
  9703. * ```
  9704. *
  9705. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  9706. *
  9707. * ```js
  9708. * {
  9709. * "<someName1>": layer1,
  9710. * "<someName2>": layer2
  9711. * }
  9712. * ```
  9713. *
  9714. * The layer names can contain HTML, which allows you to add additional styling to the items:
  9715. *
  9716. * ```js
  9717. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  9718. * ```
  9719. */
  9720. L.Control.Layers = L.Control.extend({
  9721. // @section
  9722. // @aka Control.Layers options
  9723. options: {
  9724. // @option collapsed: Boolean = true
  9725. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  9726. collapsed: true,
  9727. position: 'topright',
  9728. // @option autoZIndex: Boolean = true
  9729. // 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.
  9730. autoZIndex: true,
  9731. // @option hideSingleBase: Boolean = false
  9732. // If `true`, the base layers in the control will be hidden when there is only one.
  9733. hideSingleBase: false
  9734. },
  9735. initialize: function (baseLayers, overlays, options) {
  9736. L.setOptions(this, options);
  9737. this._layers = [];
  9738. this._lastZIndex = 0;
  9739. this._handlingClick = false;
  9740. for (var i in baseLayers) {
  9741. this._addLayer(baseLayers[i], i);
  9742. }
  9743. for (i in overlays) {
  9744. this._addLayer(overlays[i], i, true);
  9745. }
  9746. },
  9747. onAdd: function (map) {
  9748. this._initLayout();
  9749. this._update();
  9750. this._map = map;
  9751. map.on('zoomend', this._checkDisabledLayers, this);
  9752. return this._container;
  9753. },
  9754. onRemove: function () {
  9755. this._map.off('zoomend', this._checkDisabledLayers, this);
  9756. for (var i = 0; i < this._layers.length; i++) {
  9757. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  9758. }
  9759. },
  9760. // @method addBaseLayer(layer: Layer, name: String): this
  9761. // Adds a base layer (radio button entry) with the given name to the control.
  9762. addBaseLayer: function (layer, name) {
  9763. this._addLayer(layer, name);
  9764. return (this._map) ? this._update() : this;
  9765. },
  9766. // @method addOverlay(layer: Layer, name: String): this
  9767. // Adds an overlay (checkbox entry) with the given name to the control.
  9768. addOverlay: function (layer, name) {
  9769. this._addLayer(layer, name, true);
  9770. return (this._map) ? this._update() : this;
  9771. },
  9772. // @method removeLayer(layer: Layer): this
  9773. // Remove the given layer from the control.
  9774. removeLayer: function (layer) {
  9775. layer.off('add remove', this._onLayerChange, this);
  9776. var obj = this._getLayer(L.stamp(layer));
  9777. if (obj) {
  9778. this._layers.splice(this._layers.indexOf(obj), 1);
  9779. }
  9780. return (this._map) ? this._update() : this;
  9781. },
  9782. // @method expand(): this
  9783. // Expand the control container if collapsed.
  9784. expand: function () {
  9785. L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
  9786. this._form.style.height = null;
  9787. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  9788. if (acceptableHeight < this._form.clientHeight) {
  9789. L.DomUtil.addClass(this._form, 'leaflet-control-layers-scrollbar');
  9790. this._form.style.height = acceptableHeight + 'px';
  9791. } else {
  9792. L.DomUtil.removeClass(this._form, 'leaflet-control-layers-scrollbar');
  9793. }
  9794. this._checkDisabledLayers();
  9795. return this;
  9796. },
  9797. // @method collapse(): this
  9798. // Collapse the control container if expanded.
  9799. collapse: function () {
  9800. L.DomUtil.removeClass(this._container, 'leaflet-control-layers-expanded');
  9801. return this;
  9802. },
  9803. _initLayout: function () {
  9804. var className = 'leaflet-control-layers',
  9805. container = this._container = L.DomUtil.create('div', className);
  9806. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  9807. container.setAttribute('aria-haspopup', true);
  9808. L.DomEvent.disableClickPropagation(container);
  9809. if (!L.Browser.touch) {
  9810. L.DomEvent.disableScrollPropagation(container);
  9811. }
  9812. var form = this._form = L.DomUtil.create('form', className + '-list');
  9813. if (this.options.collapsed) {
  9814. if (!L.Browser.android) {
  9815. L.DomEvent.on(container, {
  9816. mouseenter: this.expand,
  9817. mouseleave: this.collapse
  9818. }, this);
  9819. }
  9820. var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
  9821. link.href = '#';
  9822. link.title = 'Layers';
  9823. if (L.Browser.touch) {
  9824. L.DomEvent
  9825. .on(link, 'click', L.DomEvent.stop)
  9826. .on(link, 'click', this.expand, this);
  9827. } else {
  9828. L.DomEvent.on(link, 'focus', this.expand, this);
  9829. }
  9830. // work around for Firefox Android issue https://github.com/Leaflet/Leaflet/issues/2033
  9831. L.DomEvent.on(form, 'click', function () {
  9832. setTimeout(L.bind(this._onInputClick, this), 0);
  9833. }, this);
  9834. this._map.on('click', this.collapse, this);
  9835. // TODO keyboard accessibility
  9836. } else {
  9837. this.expand();
  9838. }
  9839. this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
  9840. this._separator = L.DomUtil.create('div', className + '-separator', form);
  9841. this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
  9842. container.appendChild(form);
  9843. },
  9844. _getLayer: function (id) {
  9845. for (var i = 0; i < this._layers.length; i++) {
  9846. if (this._layers[i] && L.stamp(this._layers[i].layer) === id) {
  9847. return this._layers[i];
  9848. }
  9849. }
  9850. },
  9851. _addLayer: function (layer, name, overlay) {
  9852. layer.on('add remove', this._onLayerChange, this);
  9853. this._layers.push({
  9854. layer: layer,
  9855. name: name,
  9856. overlay: overlay
  9857. });
  9858. if (this.options.autoZIndex && layer.setZIndex) {
  9859. this._lastZIndex++;
  9860. layer.setZIndex(this._lastZIndex);
  9861. }
  9862. },
  9863. _update: function () {
  9864. if (!this._container) { return this; }
  9865. L.DomUtil.empty(this._baseLayersList);
  9866. L.DomUtil.empty(this._overlaysList);
  9867. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  9868. for (i = 0; i < this._layers.length; i++) {
  9869. obj = this._layers[i];
  9870. this._addItem(obj);
  9871. overlaysPresent = overlaysPresent || obj.overlay;
  9872. baseLayersPresent = baseLayersPresent || !obj.overlay;
  9873. baseLayersCount += !obj.overlay ? 1 : 0;
  9874. }
  9875. // Hide base layers section if there's only one layer.
  9876. if (this.options.hideSingleBase) {
  9877. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  9878. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  9879. }
  9880. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  9881. return this;
  9882. },
  9883. _onLayerChange: function (e) {
  9884. if (!this._handlingClick) {
  9885. this._update();
  9886. }
  9887. var obj = this._getLayer(L.stamp(e.target));
  9888. // @namespace Map
  9889. // @section Layer events
  9890. // @event baselayerchange: LayersControlEvent
  9891. // Fired when the base layer is changed through the [layer control](#control-layers).
  9892. // @event overlayadd: LayersControlEvent
  9893. // Fired when an overlay is selected through the [layer control](#control-layers).
  9894. // @event overlayremove: LayersControlEvent
  9895. // Fired when an overlay is deselected through the [layer control](#control-layers).
  9896. // @namespace Control.Layers
  9897. var type = obj.overlay ?
  9898. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  9899. (e.type === 'add' ? 'baselayerchange' : null);
  9900. if (type) {
  9901. this._map.fire(type, obj);
  9902. }
  9903. },
  9904. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  9905. _createRadioElement: function (name, checked) {
  9906. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  9907. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  9908. var radioFragment = document.createElement('div');
  9909. radioFragment.innerHTML = radioHtml;
  9910. return radioFragment.firstChild;
  9911. },
  9912. _addItem: function (obj) {
  9913. var label = document.createElement('label'),
  9914. checked = this._map.hasLayer(obj.layer),
  9915. input;
  9916. if (obj.overlay) {
  9917. input = document.createElement('input');
  9918. input.type = 'checkbox';
  9919. input.className = 'leaflet-control-layers-selector';
  9920. input.defaultChecked = checked;
  9921. } else {
  9922. input = this._createRadioElement('leaflet-base-layers', checked);
  9923. }
  9924. input.layerId = L.stamp(obj.layer);
  9925. L.DomEvent.on(input, 'click', this._onInputClick, this);
  9926. var name = document.createElement('span');
  9927. name.innerHTML = ' ' + obj.name;
  9928. // Helps from preventing layer control flicker when checkboxes are disabled
  9929. // https://github.com/Leaflet/Leaflet/issues/2771
  9930. var holder = document.createElement('div');
  9931. label.appendChild(holder);
  9932. holder.appendChild(input);
  9933. holder.appendChild(name);
  9934. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  9935. container.appendChild(label);
  9936. this._checkDisabledLayers();
  9937. return label;
  9938. },
  9939. _onInputClick: function () {
  9940. var inputs = this._form.getElementsByTagName('input'),
  9941. input, layer, hasLayer;
  9942. var addedLayers = [],
  9943. removedLayers = [];
  9944. this._handlingClick = true;
  9945. for (var i = inputs.length - 1; i >= 0; i--) {
  9946. input = inputs[i];
  9947. layer = this._getLayer(input.layerId).layer;
  9948. hasLayer = this._map.hasLayer(layer);
  9949. if (input.checked && !hasLayer) {
  9950. addedLayers.push(layer);
  9951. } else if (!input.checked && hasLayer) {
  9952. removedLayers.push(layer);
  9953. }
  9954. }
  9955. // Bugfix issue 2318: Should remove all old layers before readding new ones
  9956. for (i = 0; i < removedLayers.length; i++) {
  9957. this._map.removeLayer(removedLayers[i]);
  9958. }
  9959. for (i = 0; i < addedLayers.length; i++) {
  9960. this._map.addLayer(addedLayers[i]);
  9961. }
  9962. this._handlingClick = false;
  9963. this._refocusOnMap();
  9964. },
  9965. _checkDisabledLayers: function () {
  9966. var inputs = this._form.getElementsByTagName('input'),
  9967. input,
  9968. layer,
  9969. zoom = this._map.getZoom();
  9970. for (var i = inputs.length - 1; i >= 0; i--) {
  9971. input = inputs[i];
  9972. layer = this._getLayer(input.layerId).layer;
  9973. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  9974. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  9975. }
  9976. },
  9977. _expand: function () {
  9978. // Backward compatibility, remove me in 1.1.
  9979. return this.expand();
  9980. },
  9981. _collapse: function () {
  9982. // Backward compatibility, remove me in 1.1.
  9983. return this.collapse();
  9984. }
  9985. });
  9986. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  9987. // 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.
  9988. L.control.layers = function (baseLayers, overlays, options) {
  9989. return new L.Control.Layers(baseLayers, overlays, options);
  9990. };
  9991. /*
  9992. * @class PosAnimation
  9993. * @aka L.PosAnimation
  9994. * @inherits Evented
  9995. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  9996. *
  9997. * @example
  9998. * ```js
  9999. * var fx = new L.PosAnimation();
  10000. * fx.run(el, [300, 500], 0.5);
  10001. * ```
  10002. *
  10003. * @constructor L.PosAnimation()
  10004. * Creates a `PosAnimation` object.
  10005. *
  10006. */
  10007. L.PosAnimation = L.Evented.extend({
  10008. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  10009. // Run an animation of a given element to a new position, optionally setting
  10010. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  10011. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  10012. // `0.5` by default).
  10013. run: function (el, newPos, duration, easeLinearity) {
  10014. this.stop();
  10015. this._el = el;
  10016. this._inProgress = true;
  10017. this._duration = duration || 0.25;
  10018. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  10019. this._startPos = L.DomUtil.getPosition(el);
  10020. this._offset = newPos.subtract(this._startPos);
  10021. this._startTime = +new Date();
  10022. // @event start: Event
  10023. // Fired when the animation starts
  10024. this.fire('start');
  10025. this._animate();
  10026. },
  10027. // @method stop()
  10028. // Stops the animation (if currently running).
  10029. stop: function () {
  10030. if (!this._inProgress) { return; }
  10031. this._step(true);
  10032. this._complete();
  10033. },
  10034. _animate: function () {
  10035. // animation loop
  10036. this._animId = L.Util.requestAnimFrame(this._animate, this);
  10037. this._step();
  10038. },
  10039. _step: function (round) {
  10040. var elapsed = (+new Date()) - this._startTime,
  10041. duration = this._duration * 1000;
  10042. if (elapsed < duration) {
  10043. this._runFrame(this._easeOut(elapsed / duration), round);
  10044. } else {
  10045. this._runFrame(1);
  10046. this._complete();
  10047. }
  10048. },
  10049. _runFrame: function (progress, round) {
  10050. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  10051. if (round) {
  10052. pos._round();
  10053. }
  10054. L.DomUtil.setPosition(this._el, pos);
  10055. // @event step: Event
  10056. // Fired continuously during the animation.
  10057. this.fire('step');
  10058. },
  10059. _complete: function () {
  10060. L.Util.cancelAnimFrame(this._animId);
  10061. this._inProgress = false;
  10062. // @event end: Event
  10063. // Fired when the animation ends.
  10064. this.fire('end');
  10065. },
  10066. _easeOut: function (t) {
  10067. return 1 - Math.pow(1 - t, this._easeOutPower);
  10068. }
  10069. });
  10070. /*
  10071. * Extends L.Map to handle panning animations.
  10072. */
  10073. L.Map.include({
  10074. setView: function (center, zoom, options) {
  10075. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  10076. center = this._limitCenter(L.latLng(center), zoom, this.options.maxBounds);
  10077. options = options || {};
  10078. this._stop();
  10079. if (this._loaded && !options.reset && options !== true) {
  10080. if (options.animate !== undefined) {
  10081. options.zoom = L.extend({animate: options.animate}, options.zoom);
  10082. options.pan = L.extend({animate: options.animate, duration: options.duration}, options.pan);
  10083. }
  10084. // try animating pan or zoom
  10085. var moved = (this._zoom !== zoom) ?
  10086. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  10087. this._tryAnimatedPan(center, options.pan);
  10088. if (moved) {
  10089. // prevent resize handler call, the view will refresh after animation anyway
  10090. clearTimeout(this._sizeTimer);
  10091. return this;
  10092. }
  10093. }
  10094. // animation didn't start, just reset the map view
  10095. this._resetView(center, zoom);
  10096. return this;
  10097. },
  10098. panBy: function (offset, options) {
  10099. offset = L.point(offset).round();
  10100. options = options || {};
  10101. if (!offset.x && !offset.y) {
  10102. return this.fire('moveend');
  10103. }
  10104. // If we pan too far, Chrome gets issues with tiles
  10105. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  10106. if (options.animate !== true && !this.getSize().contains(offset)) {
  10107. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  10108. return this;
  10109. }
  10110. if (!this._panAnim) {
  10111. this._panAnim = new L.PosAnimation();
  10112. this._panAnim.on({
  10113. 'step': this._onPanTransitionStep,
  10114. 'end': this._onPanTransitionEnd
  10115. }, this);
  10116. }
  10117. // don't fire movestart if animating inertia
  10118. if (!options.noMoveStart) {
  10119. this.fire('movestart');
  10120. }
  10121. // animate pan unless animate: false specified
  10122. if (options.animate !== false) {
  10123. L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
  10124. var newPos = this._getMapPanePos().subtract(offset).round();
  10125. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  10126. } else {
  10127. this._rawPanBy(offset);
  10128. this.fire('move').fire('moveend');
  10129. }
  10130. return this;
  10131. },
  10132. _onPanTransitionStep: function () {
  10133. this.fire('move');
  10134. },
  10135. _onPanTransitionEnd: function () {
  10136. L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
  10137. this.fire('moveend');
  10138. },
  10139. _tryAnimatedPan: function (center, options) {
  10140. // difference between the new and current centers in pixels
  10141. var offset = this._getCenterOffset(center)._floor();
  10142. // don't animate too far unless animate: true specified in options
  10143. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  10144. this.panBy(offset, options);
  10145. return true;
  10146. }
  10147. });
  10148. /*
  10149. * Extends L.Map to handle zoom animations.
  10150. */
  10151. // @namespace Map
  10152. // @section Animation Options
  10153. L.Map.mergeOptions({
  10154. // @option zoomAnimation: Boolean = true
  10155. // Whether the map zoom animation is enabled. By default it's enabled
  10156. // in all browsers that support CSS3 Transitions except Android.
  10157. zoomAnimation: true,
  10158. // @option zoomAnimationThreshold: Number = 4
  10159. // Won't animate zoom if the zoom difference exceeds this value.
  10160. zoomAnimationThreshold: 4
  10161. });
  10162. var zoomAnimated = L.DomUtil.TRANSITION && L.Browser.any3d && !L.Browser.mobileOpera;
  10163. if (zoomAnimated) {
  10164. L.Map.addInitHook(function () {
  10165. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  10166. this._zoomAnimated = this.options.zoomAnimation;
  10167. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  10168. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  10169. if (this._zoomAnimated) {
  10170. this._createAnimProxy();
  10171. L.DomEvent.on(this._proxy, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
  10172. }
  10173. });
  10174. }
  10175. L.Map.include(!zoomAnimated ? {} : {
  10176. _createAnimProxy: function () {
  10177. var proxy = this._proxy = L.DomUtil.create('div', 'leaflet-proxy leaflet-zoom-animated');
  10178. this._panes.mapPane.appendChild(proxy);
  10179. this.on('zoomanim', function (e) {
  10180. var prop = L.DomUtil.TRANSFORM,
  10181. transform = proxy.style[prop];
  10182. L.DomUtil.setTransform(proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  10183. // workaround for case when transform is the same and so transitionend event is not fired
  10184. if (transform === proxy.style[prop] && this._animatingZoom) {
  10185. this._onZoomTransitionEnd();
  10186. }
  10187. }, this);
  10188. this.on('load moveend', function () {
  10189. var c = this.getCenter(),
  10190. z = this.getZoom();
  10191. L.DomUtil.setTransform(proxy, this.project(c, z), this.getZoomScale(z, 1));
  10192. }, this);
  10193. },
  10194. _catchTransitionEnd: function (e) {
  10195. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  10196. this._onZoomTransitionEnd();
  10197. }
  10198. },
  10199. _nothingToAnimate: function () {
  10200. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  10201. },
  10202. _tryAnimatedZoom: function (center, zoom, options) {
  10203. if (this._animatingZoom) { return true; }
  10204. options = options || {};
  10205. // don't animate if disabled, not supported or zoom difference is too large
  10206. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  10207. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  10208. // offset is the pixel coords of the zoom origin relative to the current center
  10209. var scale = this.getZoomScale(zoom),
  10210. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  10211. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  10212. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  10213. L.Util.requestAnimFrame(function () {
  10214. this
  10215. ._moveStart(true)
  10216. ._animateZoom(center, zoom, true);
  10217. }, this);
  10218. return true;
  10219. },
  10220. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  10221. if (startAnim) {
  10222. this._animatingZoom = true;
  10223. // remember what center/zoom to set after animation
  10224. this._animateToCenter = center;
  10225. this._animateToZoom = zoom;
  10226. L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
  10227. }
  10228. // @event zoomanim: ZoomAnimEvent
  10229. // Fired on every frame of a zoom animation
  10230. this.fire('zoomanim', {
  10231. center: center,
  10232. zoom: zoom,
  10233. noUpdate: noUpdate
  10234. });
  10235. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  10236. setTimeout(L.bind(this._onZoomTransitionEnd, this), 250);
  10237. },
  10238. _onZoomTransitionEnd: function () {
  10239. if (!this._animatingZoom) { return; }
  10240. L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
  10241. this._animatingZoom = false;
  10242. this._move(this._animateToCenter, this._animateToZoom);
  10243. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  10244. L.Util.requestAnimFrame(function () {
  10245. this._moveEnd(true);
  10246. }, this);
  10247. }
  10248. });
  10249. // @namespace Map
  10250. // @section Methods for modifying map state
  10251. L.Map.include({
  10252. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  10253. // Sets the view of the map (geographical center and zoom) performing a smooth
  10254. // pan-zoom animation.
  10255. flyTo: function (targetCenter, targetZoom, options) {
  10256. options = options || {};
  10257. if (options.animate === false || !L.Browser.any3d) {
  10258. return this.setView(targetCenter, targetZoom, options);
  10259. }
  10260. this._stop();
  10261. var from = this.project(this.getCenter()),
  10262. to = this.project(targetCenter),
  10263. size = this.getSize(),
  10264. startZoom = this._zoom;
  10265. targetCenter = L.latLng(targetCenter);
  10266. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  10267. var w0 = Math.max(size.x, size.y),
  10268. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  10269. u1 = (to.distanceTo(from)) || 1,
  10270. rho = 1.42,
  10271. rho2 = rho * rho;
  10272. function r(i) {
  10273. var s1 = i ? -1 : 1,
  10274. s2 = i ? w1 : w0,
  10275. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  10276. b1 = 2 * s2 * rho2 * u1,
  10277. b = t1 / b1,
  10278. sq = Math.sqrt(b * b + 1) - b;
  10279. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  10280. // thus triggering an infinite loop in flyTo
  10281. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  10282. return log;
  10283. }
  10284. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  10285. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  10286. function tanh(n) { return sinh(n) / cosh(n); }
  10287. var r0 = r(0);
  10288. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  10289. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  10290. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  10291. var start = Date.now(),
  10292. S = (r(1) - r0) / rho,
  10293. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  10294. function frame() {
  10295. var t = (Date.now() - start) / duration,
  10296. s = easeOut(t) * S;
  10297. if (t <= 1) {
  10298. this._flyToFrame = L.Util.requestAnimFrame(frame, this);
  10299. this._move(
  10300. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  10301. this.getScaleZoom(w0 / w(s), startZoom),
  10302. {flyTo: true});
  10303. } else {
  10304. this
  10305. ._move(targetCenter, targetZoom)
  10306. ._moveEnd(true);
  10307. }
  10308. }
  10309. this._moveStart(true);
  10310. frame.call(this);
  10311. return this;
  10312. },
  10313. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  10314. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  10315. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  10316. flyToBounds: function (bounds, options) {
  10317. var target = this._getBoundsCenterZoom(bounds, options);
  10318. return this.flyTo(target.center, target.zoom, options);
  10319. }
  10320. });
  10321. /*
  10322. * Provides L.Map with convenient shortcuts for using browser geolocation features.
  10323. */
  10324. // @namespace Map
  10325. L.Map.include({
  10326. // @section Geolocation methods
  10327. _defaultLocateOptions: {
  10328. timeout: 10000,
  10329. watch: false
  10330. // setView: false
  10331. // maxZoom: <Number>
  10332. // maximumAge: 0
  10333. // enableHighAccuracy: false
  10334. },
  10335. // @method locate(options?: Locate options): this
  10336. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  10337. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  10338. // and optionally sets the map view to the user's location with respect to
  10339. // detection accuracy (or to the world view if geolocation failed).
  10340. // Note that, if your page doesn't use HTTPS, this method will fail in
  10341. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  10342. // See `Locate options` for more details.
  10343. locate: function (options) {
  10344. options = this._locateOptions = L.extend({}, this._defaultLocateOptions, options);
  10345. if (!('geolocation' in navigator)) {
  10346. this._handleGeolocationError({
  10347. code: 0,
  10348. message: 'Geolocation not supported.'
  10349. });
  10350. return this;
  10351. }
  10352. var onResponse = L.bind(this._handleGeolocationResponse, this),
  10353. onError = L.bind(this._handleGeolocationError, this);
  10354. if (options.watch) {
  10355. this._locationWatchId =
  10356. navigator.geolocation.watchPosition(onResponse, onError, options);
  10357. } else {
  10358. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  10359. }
  10360. return this;
  10361. },
  10362. // @method stopLocate(): this
  10363. // Stops watching location previously initiated by `map.locate({watch: true})`
  10364. // and aborts resetting the map view if map.locate was called with
  10365. // `{setView: true}`.
  10366. stopLocate: function () {
  10367. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  10368. navigator.geolocation.clearWatch(this._locationWatchId);
  10369. }
  10370. if (this._locateOptions) {
  10371. this._locateOptions.setView = false;
  10372. }
  10373. return this;
  10374. },
  10375. _handleGeolocationError: function (error) {
  10376. var c = error.code,
  10377. message = error.message ||
  10378. (c === 1 ? 'permission denied' :
  10379. (c === 2 ? 'position unavailable' : 'timeout'));
  10380. if (this._locateOptions.setView && !this._loaded) {
  10381. this.fitWorld();
  10382. }
  10383. // @section Location events
  10384. // @event locationerror: ErrorEvent
  10385. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  10386. this.fire('locationerror', {
  10387. code: c,
  10388. message: 'Geolocation error: ' + message + '.'
  10389. });
  10390. },
  10391. _handleGeolocationResponse: function (pos) {
  10392. var lat = pos.coords.latitude,
  10393. lng = pos.coords.longitude,
  10394. latlng = new L.LatLng(lat, lng),
  10395. bounds = latlng.toBounds(pos.coords.accuracy),
  10396. options = this._locateOptions;
  10397. if (options.setView) {
  10398. var zoom = this.getBoundsZoom(bounds);
  10399. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  10400. }
  10401. var data = {
  10402. latlng: latlng,
  10403. bounds: bounds,
  10404. timestamp: pos.timestamp
  10405. };
  10406. for (var i in pos.coords) {
  10407. if (typeof pos.coords[i] === 'number') {
  10408. data[i] = pos.coords[i];
  10409. }
  10410. }
  10411. // @event locationfound: LocationEvent
  10412. // Fired when geolocation (using the [`locate`](#map-locate) method)
  10413. // went successfully.
  10414. this.fire('locationfound', data);
  10415. }
  10416. });
  10417. }(window, document));
  10418. //# sourceMappingURL=leaflet-src.map