leaflet-src.esm.js 404 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356
  1. /* @preserve
  2. * Leaflet 1.9.3, a JS library for interactive maps. https://leafletjs.com
  3. * (c) 2010-2022 Vladimir Agafonkin, (c) 2010-2011 CloudMade
  4. */
  5. var version = "1.9.3";
  6. /*
  7. * @namespace Util
  8. *
  9. * Various utility functions, used by Leaflet internally.
  10. */
  11. // @function extend(dest: Object, src?: Object): Object
  12. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  13. function extend(dest) {
  14. var i, j, len, src;
  15. for (j = 1, len = arguments.length; j < len; j++) {
  16. src = arguments[j];
  17. for (i in src) {
  18. dest[i] = src[i];
  19. }
  20. }
  21. return dest;
  22. }
  23. // @function create(proto: Object, properties?: Object): Object
  24. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  25. var create$2 = Object.create || (function () {
  26. function F() {}
  27. return function (proto) {
  28. F.prototype = proto;
  29. return new F();
  30. };
  31. })();
  32. // @function bind(fn: Function, …): Function
  33. // Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
  34. // Has a `L.bind()` shortcut.
  35. function bind(fn, obj) {
  36. var slice = Array.prototype.slice;
  37. if (fn.bind) {
  38. return fn.bind.apply(fn, slice.call(arguments, 1));
  39. }
  40. var args = slice.call(arguments, 2);
  41. return function () {
  42. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  43. };
  44. }
  45. // @property lastId: Number
  46. // Last unique ID used by [`stamp()`](#util-stamp)
  47. var lastId = 0;
  48. // @function stamp(obj: Object): Number
  49. // Returns the unique ID of an object, assigning it one if it doesn't have it.
  50. function stamp(obj) {
  51. if (!('_leaflet_id' in obj)) {
  52. obj['_leaflet_id'] = ++lastId;
  53. }
  54. return obj._leaflet_id;
  55. }
  56. // @function throttle(fn: Function, time: Number, context: Object): Function
  57. // Returns a function which executes function `fn` with the given scope `context`
  58. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  59. // `fn` will be called no more than one time per given amount of `time`. The arguments
  60. // received by the bound function will be any arguments passed when binding the
  61. // function, followed by any arguments passed when invoking the bound function.
  62. // Has an `L.throttle` shortcut.
  63. function throttle(fn, time, context) {
  64. var lock, args, wrapperFn, later;
  65. later = function () {
  66. // reset lock and call if queued
  67. lock = false;
  68. if (args) {
  69. wrapperFn.apply(context, args);
  70. args = false;
  71. }
  72. };
  73. wrapperFn = function () {
  74. if (lock) {
  75. // called too soon, queue to call later
  76. args = arguments;
  77. } else {
  78. // call and lock until later
  79. fn.apply(context, arguments);
  80. setTimeout(later, time);
  81. lock = true;
  82. }
  83. };
  84. return wrapperFn;
  85. }
  86. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  87. // Returns the number `num` modulo `range` in such a way so it lies within
  88. // `range[0]` and `range[1]`. The returned value will be always smaller than
  89. // `range[1]` unless `includeMax` is set to `true`.
  90. function wrapNum(x, range, includeMax) {
  91. var max = range[1],
  92. min = range[0],
  93. d = max - min;
  94. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  95. }
  96. // @function falseFn(): Function
  97. // Returns a function which always returns `false`.
  98. function falseFn() { return false; }
  99. // @function formatNum(num: Number, precision?: Number|false): Number
  100. // Returns the number `num` rounded with specified `precision`.
  101. // The default `precision` value is 6 decimal places.
  102. // `false` can be passed to skip any processing (can be useful to avoid round-off errors).
  103. function formatNum(num, precision) {
  104. if (precision === false) { return num; }
  105. var pow = Math.pow(10, precision === undefined ? 6 : precision);
  106. return Math.round(num * pow) / pow;
  107. }
  108. // @function trim(str: String): String
  109. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  110. function trim(str) {
  111. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  112. }
  113. // @function splitWords(str: String): String[]
  114. // Trims and splits the string on whitespace and returns the array of parts.
  115. function splitWords(str) {
  116. return trim(str).split(/\s+/);
  117. }
  118. // @function setOptions(obj: Object, options: Object): Object
  119. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  120. function setOptions(obj, options) {
  121. if (!Object.prototype.hasOwnProperty.call(obj, 'options')) {
  122. obj.options = obj.options ? create$2(obj.options) : {};
  123. }
  124. for (var i in options) {
  125. obj.options[i] = options[i];
  126. }
  127. return obj.options;
  128. }
  129. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  130. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  131. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  132. // be appended at the end. If `uppercase` is `true`, the parameter names will
  133. // be uppercased (e.g. `'?A=foo&B=bar'`)
  134. function getParamString(obj, existingUrl, uppercase) {
  135. var params = [];
  136. for (var i in obj) {
  137. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  138. }
  139. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  140. }
  141. var templateRe = /\{ *([\w_ -]+) *\}/g;
  142. // @function template(str: String, data: Object): String
  143. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  144. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  145. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  146. // data values — they will be evaluated passing `data` as an argument.
  147. function template(str, data) {
  148. return str.replace(templateRe, function (str, key) {
  149. var value = data[key];
  150. if (value === undefined) {
  151. throw new Error('No value provided for variable ' + str);
  152. } else if (typeof value === 'function') {
  153. value = value(data);
  154. }
  155. return value;
  156. });
  157. }
  158. // @function isArray(obj): Boolean
  159. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  160. var isArray = Array.isArray || function (obj) {
  161. return (Object.prototype.toString.call(obj) === '[object Array]');
  162. };
  163. // @function indexOf(array: Array, el: Object): Number
  164. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  165. function indexOf(array, el) {
  166. for (var i = 0; i < array.length; i++) {
  167. if (array[i] === el) { return i; }
  168. }
  169. return -1;
  170. }
  171. // @property emptyImageUrl: String
  172. // Data URI string containing a base64-encoded empty GIF image.
  173. // Used as a hack to free memory from unused images on WebKit-powered
  174. // mobile devices (by setting image `src` to this string).
  175. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  176. // inspired by https://paulirish.com/2011/requestanimationframe-for-smart-animating/
  177. function getPrefixed(name) {
  178. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  179. }
  180. var lastTime = 0;
  181. // fallback for IE 7-8
  182. function timeoutDefer(fn) {
  183. var time = +new Date(),
  184. timeToCall = Math.max(0, 16 - (time - lastTime));
  185. lastTime = time + timeToCall;
  186. return window.setTimeout(fn, timeToCall);
  187. }
  188. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  189. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  190. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  191. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  192. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  193. // `context` if given. When `immediate` is set, `fn` is called immediately if
  194. // the browser doesn't have native support for
  195. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  196. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  197. function requestAnimFrame(fn, context, immediate) {
  198. if (immediate && requestFn === timeoutDefer) {
  199. fn.call(context);
  200. } else {
  201. return requestFn.call(window, bind(fn, context));
  202. }
  203. }
  204. // @function cancelAnimFrame(id: Number): undefined
  205. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  206. function cancelAnimFrame(id) {
  207. if (id) {
  208. cancelFn.call(window, id);
  209. }
  210. }
  211. var Util = {
  212. __proto__: null,
  213. extend: extend,
  214. create: create$2,
  215. bind: bind,
  216. get lastId () { return lastId; },
  217. stamp: stamp,
  218. throttle: throttle,
  219. wrapNum: wrapNum,
  220. falseFn: falseFn,
  221. formatNum: formatNum,
  222. trim: trim,
  223. splitWords: splitWords,
  224. setOptions: setOptions,
  225. getParamString: getParamString,
  226. template: template,
  227. isArray: isArray,
  228. indexOf: indexOf,
  229. emptyImageUrl: emptyImageUrl,
  230. requestFn: requestFn,
  231. cancelFn: cancelFn,
  232. requestAnimFrame: requestAnimFrame,
  233. cancelAnimFrame: cancelAnimFrame
  234. };
  235. // @class Class
  236. // @aka L.Class
  237. // @section
  238. // @uninheritable
  239. // Thanks to John Resig and Dean Edwards for inspiration!
  240. function Class() {}
  241. Class.extend = function (props) {
  242. // @function extend(props: Object): Function
  243. // [Extends the current class](#class-inheritance) given the properties to be included.
  244. // Returns a Javascript function that is a class constructor (to be called with `new`).
  245. var NewClass = function () {
  246. setOptions(this);
  247. // call the constructor
  248. if (this.initialize) {
  249. this.initialize.apply(this, arguments);
  250. }
  251. // call all constructor hooks
  252. this.callInitHooks();
  253. };
  254. var parentProto = NewClass.__super__ = this.prototype;
  255. var proto = create$2(parentProto);
  256. proto.constructor = NewClass;
  257. NewClass.prototype = proto;
  258. // inherit parent's statics
  259. for (var i in this) {
  260. if (Object.prototype.hasOwnProperty.call(this, i) && i !== 'prototype' && i !== '__super__') {
  261. NewClass[i] = this[i];
  262. }
  263. }
  264. // mix static properties into the class
  265. if (props.statics) {
  266. extend(NewClass, props.statics);
  267. }
  268. // mix includes into the prototype
  269. if (props.includes) {
  270. checkDeprecatedMixinEvents(props.includes);
  271. extend.apply(null, [proto].concat(props.includes));
  272. }
  273. // mix given properties into the prototype
  274. extend(proto, props);
  275. delete proto.statics;
  276. delete proto.includes;
  277. // merge options
  278. if (proto.options) {
  279. proto.options = parentProto.options ? create$2(parentProto.options) : {};
  280. extend(proto.options, props.options);
  281. }
  282. proto._initHooks = [];
  283. // add method for calling all hooks
  284. proto.callInitHooks = function () {
  285. if (this._initHooksCalled) { return; }
  286. if (parentProto.callInitHooks) {
  287. parentProto.callInitHooks.call(this);
  288. }
  289. this._initHooksCalled = true;
  290. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  291. proto._initHooks[i].call(this);
  292. }
  293. };
  294. return NewClass;
  295. };
  296. // @function include(properties: Object): this
  297. // [Includes a mixin](#class-includes) into the current class.
  298. Class.include = function (props) {
  299. var parentOptions = this.prototype.options;
  300. extend(this.prototype, props);
  301. if (props.options) {
  302. this.prototype.options = parentOptions;
  303. this.mergeOptions(props.options);
  304. }
  305. return this;
  306. };
  307. // @function mergeOptions(options: Object): this
  308. // [Merges `options`](#class-options) into the defaults of the class.
  309. Class.mergeOptions = function (options) {
  310. extend(this.prototype.options, options);
  311. return this;
  312. };
  313. // @function addInitHook(fn: Function): this
  314. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  315. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  316. var args = Array.prototype.slice.call(arguments, 1);
  317. var init = typeof fn === 'function' ? fn : function () {
  318. this[fn].apply(this, args);
  319. };
  320. this.prototype._initHooks = this.prototype._initHooks || [];
  321. this.prototype._initHooks.push(init);
  322. return this;
  323. };
  324. function checkDeprecatedMixinEvents(includes) {
  325. /* global L: true */
  326. if (typeof L === 'undefined' || !L || !L.Mixin) { return; }
  327. includes = isArray(includes) ? includes : [includes];
  328. for (var i = 0; i < includes.length; i++) {
  329. if (includes[i] === L.Mixin.Events) {
  330. console.warn('Deprecated include of L.Mixin.Events: ' +
  331. 'this property will be removed in future releases, ' +
  332. 'please inherit from L.Evented instead.', new Error().stack);
  333. }
  334. }
  335. }
  336. /*
  337. * @class Evented
  338. * @aka L.Evented
  339. * @inherits Class
  340. *
  341. * 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).
  342. *
  343. * @example
  344. *
  345. * ```js
  346. * map.on('click', function(e) {
  347. * alert(e.latlng);
  348. * } );
  349. * ```
  350. *
  351. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  352. *
  353. * ```js
  354. * function onClick(e) { ... }
  355. *
  356. * map.on('click', onClick);
  357. * map.off('click', onClick);
  358. * ```
  359. */
  360. var Events = {
  361. /* @method on(type: String, fn: Function, context?: Object): this
  362. * 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'`).
  363. *
  364. * @alternative
  365. * @method on(eventMap: Object): this
  366. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  367. */
  368. on: function (types, fn, context) {
  369. // types can be a map of types/handlers
  370. if (typeof types === 'object') {
  371. for (var type in types) {
  372. // we don't process space-separated events here for performance;
  373. // it's a hot path since Layer uses the on(obj) syntax
  374. this._on(type, types[type], fn);
  375. }
  376. } else {
  377. // types can be a string of space-separated words
  378. types = splitWords(types);
  379. for (var i = 0, len = types.length; i < len; i++) {
  380. this._on(types[i], fn, context);
  381. }
  382. }
  383. return this;
  384. },
  385. /* @method off(type: String, fn?: Function, context?: Object): this
  386. * 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.
  387. *
  388. * @alternative
  389. * @method off(eventMap: Object): this
  390. * Removes a set of type/listener pairs.
  391. *
  392. * @alternative
  393. * @method off: this
  394. * Removes all listeners to all events on the object. This includes implicitly attached events.
  395. */
  396. off: function (types, fn, context) {
  397. if (!arguments.length) {
  398. // clear all listeners if called without arguments
  399. delete this._events;
  400. } else if (typeof types === 'object') {
  401. for (var type in types) {
  402. this._off(type, types[type], fn);
  403. }
  404. } else {
  405. types = splitWords(types);
  406. var removeAll = arguments.length === 1;
  407. for (var i = 0, len = types.length; i < len; i++) {
  408. if (removeAll) {
  409. this._off(types[i]);
  410. } else {
  411. this._off(types[i], fn, context);
  412. }
  413. }
  414. }
  415. return this;
  416. },
  417. // attach listener (without syntactic sugar now)
  418. _on: function (type, fn, context, _once) {
  419. if (typeof fn !== 'function') {
  420. console.warn('wrong listener type: ' + typeof fn);
  421. return;
  422. }
  423. // check if fn already there
  424. if (this._listens(type, fn, context) !== false) {
  425. return;
  426. }
  427. if (context === this) {
  428. // Less memory footprint.
  429. context = undefined;
  430. }
  431. var newListener = {fn: fn, ctx: context};
  432. if (_once) {
  433. newListener.once = true;
  434. }
  435. this._events = this._events || {};
  436. this._events[type] = this._events[type] || [];
  437. this._events[type].push(newListener);
  438. },
  439. _off: function (type, fn, context) {
  440. var listeners,
  441. i,
  442. len;
  443. if (!this._events) {
  444. return;
  445. }
  446. listeners = this._events[type];
  447. if (!listeners) {
  448. return;
  449. }
  450. if (arguments.length === 1) { // remove all
  451. if (this._firingCount) {
  452. // Set all removed listeners to noop
  453. // so they are not called if remove happens in fire
  454. for (i = 0, len = listeners.length; i < len; i++) {
  455. listeners[i].fn = falseFn;
  456. }
  457. }
  458. // clear all listeners for a type if function isn't specified
  459. delete this._events[type];
  460. return;
  461. }
  462. if (typeof fn !== 'function') {
  463. console.warn('wrong listener type: ' + typeof fn);
  464. return;
  465. }
  466. // find fn and remove it
  467. var index = this._listens(type, fn, context);
  468. if (index !== false) {
  469. var listener = listeners[index];
  470. if (this._firingCount) {
  471. // set the removed listener to noop so that's not called if remove happens in fire
  472. listener.fn = falseFn;
  473. /* copy array in case events are being fired */
  474. this._events[type] = listeners = listeners.slice();
  475. }
  476. listeners.splice(index, 1);
  477. }
  478. },
  479. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  480. // Fires an event of the specified type. You can optionally provide a data
  481. // object — the first argument of the listener function will contain its
  482. // properties. The event can optionally be propagated to event parents.
  483. fire: function (type, data, propagate) {
  484. if (!this.listens(type, propagate)) { return this; }
  485. var event = extend({}, data, {
  486. type: type,
  487. target: this,
  488. sourceTarget: data && data.sourceTarget || this
  489. });
  490. if (this._events) {
  491. var listeners = this._events[type];
  492. if (listeners) {
  493. this._firingCount = (this._firingCount + 1) || 1;
  494. for (var i = 0, len = listeners.length; i < len; i++) {
  495. var l = listeners[i];
  496. // off overwrites l.fn, so we need to copy fn to a var
  497. var fn = l.fn;
  498. if (l.once) {
  499. this.off(type, fn, l.ctx);
  500. }
  501. fn.call(l.ctx || this, event);
  502. }
  503. this._firingCount--;
  504. }
  505. }
  506. if (propagate) {
  507. // propagate the event to parents (set with addEventParent)
  508. this._propagateEvent(event);
  509. }
  510. return this;
  511. },
  512. // @method listens(type: String, propagate?: Boolean): Boolean
  513. // @method listens(type: String, fn: Function, context?: Object, propagate?: Boolean): Boolean
  514. // Returns `true` if a particular event type has any listeners attached to it.
  515. // The verification can optionally be propagated, it will return `true` if parents have the listener attached to it.
  516. listens: function (type, fn, context, propagate) {
  517. if (typeof type !== 'string') {
  518. console.warn('"string" type argument expected');
  519. }
  520. // we don't overwrite the input `fn` value, because we need to use it for propagation
  521. var _fn = fn;
  522. if (typeof fn !== 'function') {
  523. propagate = !!fn;
  524. _fn = undefined;
  525. context = undefined;
  526. }
  527. var listeners = this._events && this._events[type];
  528. if (listeners && listeners.length) {
  529. if (this._listens(type, _fn, context) !== false) {
  530. return true;
  531. }
  532. }
  533. if (propagate) {
  534. // also check parents for listeners if event propagates
  535. for (var id in this._eventParents) {
  536. if (this._eventParents[id].listens(type, fn, context, propagate)) { return true; }
  537. }
  538. }
  539. return false;
  540. },
  541. // returns the index (number) or false
  542. _listens: function (type, fn, context) {
  543. if (!this._events) {
  544. return false;
  545. }
  546. var listeners = this._events[type] || [];
  547. if (!fn) {
  548. return !!listeners.length;
  549. }
  550. if (context === this) {
  551. // Less memory footprint.
  552. context = undefined;
  553. }
  554. for (var i = 0, len = listeners.length; i < len; i++) {
  555. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  556. return i;
  557. }
  558. }
  559. return false;
  560. },
  561. // @method once(…): this
  562. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  563. once: function (types, fn, context) {
  564. // types can be a map of types/handlers
  565. if (typeof types === 'object') {
  566. for (var type in types) {
  567. // we don't process space-separated events here for performance;
  568. // it's a hot path since Layer uses the on(obj) syntax
  569. this._on(type, types[type], fn, true);
  570. }
  571. } else {
  572. // types can be a string of space-separated words
  573. types = splitWords(types);
  574. for (var i = 0, len = types.length; i < len; i++) {
  575. this._on(types[i], fn, context, true);
  576. }
  577. }
  578. return this;
  579. },
  580. // @method addEventParent(obj: Evented): this
  581. // Adds an event parent - an `Evented` that will receive propagated events
  582. addEventParent: function (obj) {
  583. this._eventParents = this._eventParents || {};
  584. this._eventParents[stamp(obj)] = obj;
  585. return this;
  586. },
  587. // @method removeEventParent(obj: Evented): this
  588. // Removes an event parent, so it will stop receiving propagated events
  589. removeEventParent: function (obj) {
  590. if (this._eventParents) {
  591. delete this._eventParents[stamp(obj)];
  592. }
  593. return this;
  594. },
  595. _propagateEvent: function (e) {
  596. for (var id in this._eventParents) {
  597. this._eventParents[id].fire(e.type, extend({
  598. layer: e.target,
  599. propagatedFrom: e.target
  600. }, e), true);
  601. }
  602. }
  603. };
  604. // aliases; we should ditch those eventually
  605. // @method addEventListener(…): this
  606. // Alias to [`on(…)`](#evented-on)
  607. Events.addEventListener = Events.on;
  608. // @method removeEventListener(…): this
  609. // Alias to [`off(…)`](#evented-off)
  610. // @method clearAllEventListeners(…): this
  611. // Alias to [`off()`](#evented-off)
  612. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  613. // @method addOneTimeEventListener(…): this
  614. // Alias to [`once(…)`](#evented-once)
  615. Events.addOneTimeEventListener = Events.once;
  616. // @method fireEvent(…): this
  617. // Alias to [`fire(…)`](#evented-fire)
  618. Events.fireEvent = Events.fire;
  619. // @method hasEventListeners(…): Boolean
  620. // Alias to [`listens(…)`](#evented-listens)
  621. Events.hasEventListeners = Events.listens;
  622. var Evented = Class.extend(Events);
  623. /*
  624. * @class Point
  625. * @aka L.Point
  626. *
  627. * Represents a point with `x` and `y` coordinates in pixels.
  628. *
  629. * @example
  630. *
  631. * ```js
  632. * var point = L.point(200, 300);
  633. * ```
  634. *
  635. * 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:
  636. *
  637. * ```js
  638. * map.panBy([200, 300]);
  639. * map.panBy(L.point(200, 300));
  640. * ```
  641. *
  642. * Note that `Point` does not inherit from Leaflet's `Class` object,
  643. * which means new classes can't inherit from it, and new methods
  644. * can't be added to it with the `include` function.
  645. */
  646. function Point(x, y, round) {
  647. // @property x: Number; The `x` coordinate of the point
  648. this.x = (round ? Math.round(x) : x);
  649. // @property y: Number; The `y` coordinate of the point
  650. this.y = (round ? Math.round(y) : y);
  651. }
  652. var trunc = Math.trunc || function (v) {
  653. return v > 0 ? Math.floor(v) : Math.ceil(v);
  654. };
  655. Point.prototype = {
  656. // @method clone(): Point
  657. // Returns a copy of the current point.
  658. clone: function () {
  659. return new Point(this.x, this.y);
  660. },
  661. // @method add(otherPoint: Point): Point
  662. // Returns the result of addition of the current and the given points.
  663. add: function (point) {
  664. // non-destructive, returns a new point
  665. return this.clone()._add(toPoint(point));
  666. },
  667. _add: function (point) {
  668. // destructive, used directly for performance in situations where it's safe to modify existing point
  669. this.x += point.x;
  670. this.y += point.y;
  671. return this;
  672. },
  673. // @method subtract(otherPoint: Point): Point
  674. // Returns the result of subtraction of the given point from the current.
  675. subtract: function (point) {
  676. return this.clone()._subtract(toPoint(point));
  677. },
  678. _subtract: function (point) {
  679. this.x -= point.x;
  680. this.y -= point.y;
  681. return this;
  682. },
  683. // @method divideBy(num: Number): Point
  684. // Returns the result of division of the current point by the given number.
  685. divideBy: function (num) {
  686. return this.clone()._divideBy(num);
  687. },
  688. _divideBy: function (num) {
  689. this.x /= num;
  690. this.y /= num;
  691. return this;
  692. },
  693. // @method multiplyBy(num: Number): Point
  694. // Returns the result of multiplication of the current point by the given number.
  695. multiplyBy: function (num) {
  696. return this.clone()._multiplyBy(num);
  697. },
  698. _multiplyBy: function (num) {
  699. this.x *= num;
  700. this.y *= num;
  701. return this;
  702. },
  703. // @method scaleBy(scale: Point): Point
  704. // Multiply each coordinate of the current point by each coordinate of
  705. // `scale`. In linear algebra terms, multiply the point by the
  706. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  707. // defined by `scale`.
  708. scaleBy: function (point) {
  709. return new Point(this.x * point.x, this.y * point.y);
  710. },
  711. // @method unscaleBy(scale: Point): Point
  712. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  713. // each coordinate of `scale`.
  714. unscaleBy: function (point) {
  715. return new Point(this.x / point.x, this.y / point.y);
  716. },
  717. // @method round(): Point
  718. // Returns a copy of the current point with rounded coordinates.
  719. round: function () {
  720. return this.clone()._round();
  721. },
  722. _round: function () {
  723. this.x = Math.round(this.x);
  724. this.y = Math.round(this.y);
  725. return this;
  726. },
  727. // @method floor(): Point
  728. // Returns a copy of the current point with floored coordinates (rounded down).
  729. floor: function () {
  730. return this.clone()._floor();
  731. },
  732. _floor: function () {
  733. this.x = Math.floor(this.x);
  734. this.y = Math.floor(this.y);
  735. return this;
  736. },
  737. // @method ceil(): Point
  738. // Returns a copy of the current point with ceiled coordinates (rounded up).
  739. ceil: function () {
  740. return this.clone()._ceil();
  741. },
  742. _ceil: function () {
  743. this.x = Math.ceil(this.x);
  744. this.y = Math.ceil(this.y);
  745. return this;
  746. },
  747. // @method trunc(): Point
  748. // Returns a copy of the current point with truncated coordinates (rounded towards zero).
  749. trunc: function () {
  750. return this.clone()._trunc();
  751. },
  752. _trunc: function () {
  753. this.x = trunc(this.x);
  754. this.y = trunc(this.y);
  755. return this;
  756. },
  757. // @method distanceTo(otherPoint: Point): Number
  758. // Returns the cartesian distance between the current and the given points.
  759. distanceTo: function (point) {
  760. point = toPoint(point);
  761. var x = point.x - this.x,
  762. y = point.y - this.y;
  763. return Math.sqrt(x * x + y * y);
  764. },
  765. // @method equals(otherPoint: Point): Boolean
  766. // Returns `true` if the given point has the same coordinates.
  767. equals: function (point) {
  768. point = toPoint(point);
  769. return point.x === this.x &&
  770. point.y === this.y;
  771. },
  772. // @method contains(otherPoint: Point): Boolean
  773. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  774. contains: function (point) {
  775. point = toPoint(point);
  776. return Math.abs(point.x) <= Math.abs(this.x) &&
  777. Math.abs(point.y) <= Math.abs(this.y);
  778. },
  779. // @method toString(): String
  780. // Returns a string representation of the point for debugging purposes.
  781. toString: function () {
  782. return 'Point(' +
  783. formatNum(this.x) + ', ' +
  784. formatNum(this.y) + ')';
  785. }
  786. };
  787. // @factory L.point(x: Number, y: Number, round?: Boolean)
  788. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  789. // @alternative
  790. // @factory L.point(coords: Number[])
  791. // Expects an array of the form `[x, y]` instead.
  792. // @alternative
  793. // @factory L.point(coords: Object)
  794. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  795. function toPoint(x, y, round) {
  796. if (x instanceof Point) {
  797. return x;
  798. }
  799. if (isArray(x)) {
  800. return new Point(x[0], x[1]);
  801. }
  802. if (x === undefined || x === null) {
  803. return x;
  804. }
  805. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  806. return new Point(x.x, x.y);
  807. }
  808. return new Point(x, y, round);
  809. }
  810. /*
  811. * @class Bounds
  812. * @aka L.Bounds
  813. *
  814. * Represents a rectangular area in pixel coordinates.
  815. *
  816. * @example
  817. *
  818. * ```js
  819. * var p1 = L.point(10, 10),
  820. * p2 = L.point(40, 60),
  821. * bounds = L.bounds(p1, p2);
  822. * ```
  823. *
  824. * 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:
  825. *
  826. * ```js
  827. * otherBounds.intersects([[10, 10], [40, 60]]);
  828. * ```
  829. *
  830. * Note that `Bounds` does not inherit from Leaflet's `Class` object,
  831. * which means new classes can't inherit from it, and new methods
  832. * can't be added to it with the `include` function.
  833. */
  834. function Bounds(a, b) {
  835. if (!a) { return; }
  836. var points = b ? [a, b] : a;
  837. for (var i = 0, len = points.length; i < len; i++) {
  838. this.extend(points[i]);
  839. }
  840. }
  841. Bounds.prototype = {
  842. // @method extend(point: Point): this
  843. // Extends the bounds to contain the given point.
  844. // @alternative
  845. // @method extend(otherBounds: Bounds): this
  846. // Extend the bounds to contain the given bounds
  847. extend: function (obj) {
  848. var min2, max2;
  849. if (!obj) { return this; }
  850. if (obj instanceof Point || typeof obj[0] === 'number' || 'x' in obj) {
  851. min2 = max2 = toPoint(obj);
  852. } else {
  853. obj = toBounds(obj);
  854. min2 = obj.min;
  855. max2 = obj.max;
  856. if (!min2 || !max2) { return this; }
  857. }
  858. // @property min: Point
  859. // The top left corner of the rectangle.
  860. // @property max: Point
  861. // The bottom right corner of the rectangle.
  862. if (!this.min && !this.max) {
  863. this.min = min2.clone();
  864. this.max = max2.clone();
  865. } else {
  866. this.min.x = Math.min(min2.x, this.min.x);
  867. this.max.x = Math.max(max2.x, this.max.x);
  868. this.min.y = Math.min(min2.y, this.min.y);
  869. this.max.y = Math.max(max2.y, this.max.y);
  870. }
  871. return this;
  872. },
  873. // @method getCenter(round?: Boolean): Point
  874. // Returns the center point of the bounds.
  875. getCenter: function (round) {
  876. return toPoint(
  877. (this.min.x + this.max.x) / 2,
  878. (this.min.y + this.max.y) / 2, round);
  879. },
  880. // @method getBottomLeft(): Point
  881. // Returns the bottom-left point of the bounds.
  882. getBottomLeft: function () {
  883. return toPoint(this.min.x, this.max.y);
  884. },
  885. // @method getTopRight(): Point
  886. // Returns the top-right point of the bounds.
  887. getTopRight: function () { // -> Point
  888. return toPoint(this.max.x, this.min.y);
  889. },
  890. // @method getTopLeft(): Point
  891. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  892. getTopLeft: function () {
  893. return this.min; // left, top
  894. },
  895. // @method getBottomRight(): Point
  896. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  897. getBottomRight: function () {
  898. return this.max; // right, bottom
  899. },
  900. // @method getSize(): Point
  901. // Returns the size of the given bounds
  902. getSize: function () {
  903. return this.max.subtract(this.min);
  904. },
  905. // @method contains(otherBounds: Bounds): Boolean
  906. // Returns `true` if the rectangle contains the given one.
  907. // @alternative
  908. // @method contains(point: Point): Boolean
  909. // Returns `true` if the rectangle contains the given point.
  910. contains: function (obj) {
  911. var min, max;
  912. if (typeof obj[0] === 'number' || obj instanceof Point) {
  913. obj = toPoint(obj);
  914. } else {
  915. obj = toBounds(obj);
  916. }
  917. if (obj instanceof Bounds) {
  918. min = obj.min;
  919. max = obj.max;
  920. } else {
  921. min = max = obj;
  922. }
  923. return (min.x >= this.min.x) &&
  924. (max.x <= this.max.x) &&
  925. (min.y >= this.min.y) &&
  926. (max.y <= this.max.y);
  927. },
  928. // @method intersects(otherBounds: Bounds): Boolean
  929. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  930. // intersect if they have at least one point in common.
  931. intersects: function (bounds) { // (Bounds) -> Boolean
  932. bounds = toBounds(bounds);
  933. var min = this.min,
  934. max = this.max,
  935. min2 = bounds.min,
  936. max2 = bounds.max,
  937. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  938. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  939. return xIntersects && yIntersects;
  940. },
  941. // @method overlaps(otherBounds: Bounds): Boolean
  942. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  943. // overlap if their intersection is an area.
  944. overlaps: function (bounds) { // (Bounds) -> Boolean
  945. bounds = toBounds(bounds);
  946. var min = this.min,
  947. max = this.max,
  948. min2 = bounds.min,
  949. max2 = bounds.max,
  950. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  951. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  952. return xOverlaps && yOverlaps;
  953. },
  954. // @method isValid(): Boolean
  955. // Returns `true` if the bounds are properly initialized.
  956. isValid: function () {
  957. return !!(this.min && this.max);
  958. },
  959. // @method pad(bufferRatio: Number): Bounds
  960. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  961. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  962. // Negative values will retract the bounds.
  963. pad: function (bufferRatio) {
  964. var min = this.min,
  965. max = this.max,
  966. heightBuffer = Math.abs(min.x - max.x) * bufferRatio,
  967. widthBuffer = Math.abs(min.y - max.y) * bufferRatio;
  968. return toBounds(
  969. toPoint(min.x - heightBuffer, min.y - widthBuffer),
  970. toPoint(max.x + heightBuffer, max.y + widthBuffer));
  971. },
  972. // @method equals(otherBounds: Bounds): Boolean
  973. // Returns `true` if the rectangle is equivalent to the given bounds.
  974. equals: function (bounds) {
  975. if (!bounds) { return false; }
  976. bounds = toBounds(bounds);
  977. return this.min.equals(bounds.getTopLeft()) &&
  978. this.max.equals(bounds.getBottomRight());
  979. },
  980. };
  981. // @factory L.bounds(corner1: Point, corner2: Point)
  982. // Creates a Bounds object from two corners coordinate pairs.
  983. // @alternative
  984. // @factory L.bounds(points: Point[])
  985. // Creates a Bounds object from the given array of points.
  986. function toBounds(a, b) {
  987. if (!a || a instanceof Bounds) {
  988. return a;
  989. }
  990. return new Bounds(a, b);
  991. }
  992. /*
  993. * @class LatLngBounds
  994. * @aka L.LatLngBounds
  995. *
  996. * Represents a rectangular geographical area on a map.
  997. *
  998. * @example
  999. *
  1000. * ```js
  1001. * var corner1 = L.latLng(40.712, -74.227),
  1002. * corner2 = L.latLng(40.774, -74.125),
  1003. * bounds = L.latLngBounds(corner1, corner2);
  1004. * ```
  1005. *
  1006. * 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:
  1007. *
  1008. * ```js
  1009. * map.fitBounds([
  1010. * [40.712, -74.227],
  1011. * [40.774, -74.125]
  1012. * ]);
  1013. * ```
  1014. *
  1015. * Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range.
  1016. *
  1017. * Note that `LatLngBounds` does not inherit from Leaflet's `Class` object,
  1018. * which means new classes can't inherit from it, and new methods
  1019. * can't be added to it with the `include` function.
  1020. */
  1021. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  1022. if (!corner1) { return; }
  1023. var latlngs = corner2 ? [corner1, corner2] : corner1;
  1024. for (var i = 0, len = latlngs.length; i < len; i++) {
  1025. this.extend(latlngs[i]);
  1026. }
  1027. }
  1028. LatLngBounds.prototype = {
  1029. // @method extend(latlng: LatLng): this
  1030. // Extend the bounds to contain the given point
  1031. // @alternative
  1032. // @method extend(otherBounds: LatLngBounds): this
  1033. // Extend the bounds to contain the given bounds
  1034. extend: function (obj) {
  1035. var sw = this._southWest,
  1036. ne = this._northEast,
  1037. sw2, ne2;
  1038. if (obj instanceof LatLng) {
  1039. sw2 = obj;
  1040. ne2 = obj;
  1041. } else if (obj instanceof LatLngBounds) {
  1042. sw2 = obj._southWest;
  1043. ne2 = obj._northEast;
  1044. if (!sw2 || !ne2) { return this; }
  1045. } else {
  1046. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  1047. }
  1048. if (!sw && !ne) {
  1049. this._southWest = new LatLng(sw2.lat, sw2.lng);
  1050. this._northEast = new LatLng(ne2.lat, ne2.lng);
  1051. } else {
  1052. sw.lat = Math.min(sw2.lat, sw.lat);
  1053. sw.lng = Math.min(sw2.lng, sw.lng);
  1054. ne.lat = Math.max(ne2.lat, ne.lat);
  1055. ne.lng = Math.max(ne2.lng, ne.lng);
  1056. }
  1057. return this;
  1058. },
  1059. // @method pad(bufferRatio: Number): LatLngBounds
  1060. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  1061. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  1062. // Negative values will retract the bounds.
  1063. pad: function (bufferRatio) {
  1064. var sw = this._southWest,
  1065. ne = this._northEast,
  1066. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  1067. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  1068. return new LatLngBounds(
  1069. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  1070. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  1071. },
  1072. // @method getCenter(): LatLng
  1073. // Returns the center point of the bounds.
  1074. getCenter: function () {
  1075. return new LatLng(
  1076. (this._southWest.lat + this._northEast.lat) / 2,
  1077. (this._southWest.lng + this._northEast.lng) / 2);
  1078. },
  1079. // @method getSouthWest(): LatLng
  1080. // Returns the south-west point of the bounds.
  1081. getSouthWest: function () {
  1082. return this._southWest;
  1083. },
  1084. // @method getNorthEast(): LatLng
  1085. // Returns the north-east point of the bounds.
  1086. getNorthEast: function () {
  1087. return this._northEast;
  1088. },
  1089. // @method getNorthWest(): LatLng
  1090. // Returns the north-west point of the bounds.
  1091. getNorthWest: function () {
  1092. return new LatLng(this.getNorth(), this.getWest());
  1093. },
  1094. // @method getSouthEast(): LatLng
  1095. // Returns the south-east point of the bounds.
  1096. getSouthEast: function () {
  1097. return new LatLng(this.getSouth(), this.getEast());
  1098. },
  1099. // @method getWest(): Number
  1100. // Returns the west longitude of the bounds
  1101. getWest: function () {
  1102. return this._southWest.lng;
  1103. },
  1104. // @method getSouth(): Number
  1105. // Returns the south latitude of the bounds
  1106. getSouth: function () {
  1107. return this._southWest.lat;
  1108. },
  1109. // @method getEast(): Number
  1110. // Returns the east longitude of the bounds
  1111. getEast: function () {
  1112. return this._northEast.lng;
  1113. },
  1114. // @method getNorth(): Number
  1115. // Returns the north latitude of the bounds
  1116. getNorth: function () {
  1117. return this._northEast.lat;
  1118. },
  1119. // @method contains(otherBounds: LatLngBounds): Boolean
  1120. // Returns `true` if the rectangle contains the given one.
  1121. // @alternative
  1122. // @method contains (latlng: LatLng): Boolean
  1123. // Returns `true` if the rectangle contains the given point.
  1124. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1125. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1126. obj = toLatLng(obj);
  1127. } else {
  1128. obj = toLatLngBounds(obj);
  1129. }
  1130. var sw = this._southWest,
  1131. ne = this._northEast,
  1132. sw2, ne2;
  1133. if (obj instanceof LatLngBounds) {
  1134. sw2 = obj.getSouthWest();
  1135. ne2 = obj.getNorthEast();
  1136. } else {
  1137. sw2 = ne2 = obj;
  1138. }
  1139. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1140. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1141. },
  1142. // @method intersects(otherBounds: LatLngBounds): Boolean
  1143. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1144. intersects: function (bounds) {
  1145. bounds = toLatLngBounds(bounds);
  1146. var sw = this._southWest,
  1147. ne = this._northEast,
  1148. sw2 = bounds.getSouthWest(),
  1149. ne2 = bounds.getNorthEast(),
  1150. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1151. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1152. return latIntersects && lngIntersects;
  1153. },
  1154. // @method overlaps(otherBounds: LatLngBounds): Boolean
  1155. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1156. overlaps: function (bounds) {
  1157. bounds = toLatLngBounds(bounds);
  1158. var sw = this._southWest,
  1159. ne = this._northEast,
  1160. sw2 = bounds.getSouthWest(),
  1161. ne2 = bounds.getNorthEast(),
  1162. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1163. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1164. return latOverlaps && lngOverlaps;
  1165. },
  1166. // @method toBBoxString(): String
  1167. // 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.
  1168. toBBoxString: function () {
  1169. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1170. },
  1171. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1172. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.
  1173. equals: function (bounds, maxMargin) {
  1174. if (!bounds) { return false; }
  1175. bounds = toLatLngBounds(bounds);
  1176. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1177. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1178. },
  1179. // @method isValid(): Boolean
  1180. // Returns `true` if the bounds are properly initialized.
  1181. isValid: function () {
  1182. return !!(this._southWest && this._northEast);
  1183. }
  1184. };
  1185. // TODO International date line?
  1186. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1187. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1188. // @alternative
  1189. // @factory L.latLngBounds(latlngs: LatLng[])
  1190. // 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).
  1191. function toLatLngBounds(a, b) {
  1192. if (a instanceof LatLngBounds) {
  1193. return a;
  1194. }
  1195. return new LatLngBounds(a, b);
  1196. }
  1197. /* @class LatLng
  1198. * @aka L.LatLng
  1199. *
  1200. * Represents a geographical point with a certain latitude and longitude.
  1201. *
  1202. * @example
  1203. *
  1204. * ```
  1205. * var latlng = L.latLng(50.5, 30.5);
  1206. * ```
  1207. *
  1208. * 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:
  1209. *
  1210. * ```
  1211. * map.panTo([50, 30]);
  1212. * map.panTo({lon: 30, lat: 50});
  1213. * map.panTo({lat: 50, lng: 30});
  1214. * map.panTo(L.latLng(50, 30));
  1215. * ```
  1216. *
  1217. * Note that `LatLng` does not inherit from Leaflet's `Class` object,
  1218. * which means new classes can't inherit from it, and new methods
  1219. * can't be added to it with the `include` function.
  1220. */
  1221. function LatLng(lat, lng, alt) {
  1222. if (isNaN(lat) || isNaN(lng)) {
  1223. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1224. }
  1225. // @property lat: Number
  1226. // Latitude in degrees
  1227. this.lat = +lat;
  1228. // @property lng: Number
  1229. // Longitude in degrees
  1230. this.lng = +lng;
  1231. // @property alt: Number
  1232. // Altitude in meters (optional)
  1233. if (alt !== undefined) {
  1234. this.alt = +alt;
  1235. }
  1236. }
  1237. LatLng.prototype = {
  1238. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1239. // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.
  1240. equals: function (obj, maxMargin) {
  1241. if (!obj) { return false; }
  1242. obj = toLatLng(obj);
  1243. var margin = Math.max(
  1244. Math.abs(this.lat - obj.lat),
  1245. Math.abs(this.lng - obj.lng));
  1246. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1247. },
  1248. // @method toString(): String
  1249. // Returns a string representation of the point (for debugging purposes).
  1250. toString: function (precision) {
  1251. return 'LatLng(' +
  1252. formatNum(this.lat, precision) + ', ' +
  1253. formatNum(this.lng, precision) + ')';
  1254. },
  1255. // @method distanceTo(otherLatLng: LatLng): Number
  1256. // Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).
  1257. distanceTo: function (other) {
  1258. return Earth.distance(this, toLatLng(other));
  1259. },
  1260. // @method wrap(): LatLng
  1261. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1262. wrap: function () {
  1263. return Earth.wrapLatLng(this);
  1264. },
  1265. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1266. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1267. toBounds: function (sizeInMeters) {
  1268. var latAccuracy = 180 * sizeInMeters / 40075017,
  1269. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1270. return toLatLngBounds(
  1271. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1272. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1273. },
  1274. clone: function () {
  1275. return new LatLng(this.lat, this.lng, this.alt);
  1276. }
  1277. };
  1278. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1279. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1280. // @alternative
  1281. // @factory L.latLng(coords: Array): LatLng
  1282. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1283. // @alternative
  1284. // @factory L.latLng(coords: Object): LatLng
  1285. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1286. function toLatLng(a, b, c) {
  1287. if (a instanceof LatLng) {
  1288. return a;
  1289. }
  1290. if (isArray(a) && typeof a[0] !== 'object') {
  1291. if (a.length === 3) {
  1292. return new LatLng(a[0], a[1], a[2]);
  1293. }
  1294. if (a.length === 2) {
  1295. return new LatLng(a[0], a[1]);
  1296. }
  1297. return null;
  1298. }
  1299. if (a === undefined || a === null) {
  1300. return a;
  1301. }
  1302. if (typeof a === 'object' && 'lat' in a) {
  1303. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1304. }
  1305. if (b === undefined) {
  1306. return null;
  1307. }
  1308. return new LatLng(a, b, c);
  1309. }
  1310. /*
  1311. * @namespace CRS
  1312. * @crs L.CRS.Base
  1313. * Object that defines coordinate reference systems for projecting
  1314. * geographical points into pixel (screen) coordinates and back (and to
  1315. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1316. * [spatial reference system](https://en.wikipedia.org/wiki/Spatial_reference_system).
  1317. *
  1318. * Leaflet defines the most usual CRSs by default. If you want to use a
  1319. * CRS not defined by default, take a look at the
  1320. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1321. *
  1322. * Note that the CRS instances do not inherit from Leaflet's `Class` object,
  1323. * and can't be instantiated. Also, new classes can't inherit from them,
  1324. * and methods can't be added to them with the `include` function.
  1325. */
  1326. var CRS = {
  1327. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1328. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1329. latLngToPoint: function (latlng, zoom) {
  1330. var projectedPoint = this.projection.project(latlng),
  1331. scale = this.scale(zoom);
  1332. return this.transformation._transform(projectedPoint, scale);
  1333. },
  1334. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1335. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1336. // zoom into geographical coordinates.
  1337. pointToLatLng: function (point, zoom) {
  1338. var scale = this.scale(zoom),
  1339. untransformedPoint = this.transformation.untransform(point, scale);
  1340. return this.projection.unproject(untransformedPoint);
  1341. },
  1342. // @method project(latlng: LatLng): Point
  1343. // Projects geographical coordinates into coordinates in units accepted for
  1344. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1345. project: function (latlng) {
  1346. return this.projection.project(latlng);
  1347. },
  1348. // @method unproject(point: Point): LatLng
  1349. // Given a projected coordinate returns the corresponding LatLng.
  1350. // The inverse of `project`.
  1351. unproject: function (point) {
  1352. return this.projection.unproject(point);
  1353. },
  1354. // @method scale(zoom: Number): Number
  1355. // Returns the scale used when transforming projected coordinates into
  1356. // pixel coordinates for a particular zoom. For example, it returns
  1357. // `256 * 2^zoom` for Mercator-based CRS.
  1358. scale: function (zoom) {
  1359. return 256 * Math.pow(2, zoom);
  1360. },
  1361. // @method zoom(scale: Number): Number
  1362. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1363. // factor of `scale`.
  1364. zoom: function (scale) {
  1365. return Math.log(scale / 256) / Math.LN2;
  1366. },
  1367. // @method getProjectedBounds(zoom: Number): Bounds
  1368. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1369. getProjectedBounds: function (zoom) {
  1370. if (this.infinite) { return null; }
  1371. var b = this.projection.bounds,
  1372. s = this.scale(zoom),
  1373. min = this.transformation.transform(b.min, s),
  1374. max = this.transformation.transform(b.max, s);
  1375. return new Bounds(min, max);
  1376. },
  1377. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1378. // Returns the distance between two geographical coordinates.
  1379. // @property code: String
  1380. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1381. //
  1382. // @property wrapLng: Number[]
  1383. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1384. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1385. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1386. //
  1387. // @property wrapLat: Number[]
  1388. // Like `wrapLng`, but for the latitude (vertical) axis.
  1389. // wrapLng: [min, max],
  1390. // wrapLat: [min, max],
  1391. // @property infinite: Boolean
  1392. // If true, the coordinate space will be unbounded (infinite in both axes)
  1393. infinite: false,
  1394. // @method wrapLatLng(latlng: LatLng): LatLng
  1395. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1396. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1397. wrapLatLng: function (latlng) {
  1398. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1399. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1400. alt = latlng.alt;
  1401. return new LatLng(lat, lng, alt);
  1402. },
  1403. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1404. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1405. // that its center is within the CRS's bounds.
  1406. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1407. wrapLatLngBounds: function (bounds) {
  1408. var center = bounds.getCenter(),
  1409. newCenter = this.wrapLatLng(center),
  1410. latShift = center.lat - newCenter.lat,
  1411. lngShift = center.lng - newCenter.lng;
  1412. if (latShift === 0 && lngShift === 0) {
  1413. return bounds;
  1414. }
  1415. var sw = bounds.getSouthWest(),
  1416. ne = bounds.getNorthEast(),
  1417. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1418. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1419. return new LatLngBounds(newSw, newNe);
  1420. }
  1421. };
  1422. /*
  1423. * @namespace CRS
  1424. * @crs L.CRS.Earth
  1425. *
  1426. * Serves as the base for CRS that are global such that they cover the earth.
  1427. * Can only be used as the base for other CRS and cannot be used directly,
  1428. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1429. * meters.
  1430. */
  1431. var Earth = extend({}, CRS, {
  1432. wrapLng: [-180, 180],
  1433. // Mean Earth Radius, as recommended for use by
  1434. // the International Union of Geodesy and Geophysics,
  1435. // see https://rosettacode.org/wiki/Haversine_formula
  1436. R: 6371000,
  1437. // distance between two geographical points using spherical law of cosines approximation
  1438. distance: function (latlng1, latlng2) {
  1439. var rad = Math.PI / 180,
  1440. lat1 = latlng1.lat * rad,
  1441. lat2 = latlng2.lat * rad,
  1442. sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
  1443. sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
  1444. a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
  1445. c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1446. return this.R * c;
  1447. }
  1448. });
  1449. /*
  1450. * @namespace Projection
  1451. * @projection L.Projection.SphericalMercator
  1452. *
  1453. * Spherical Mercator projection — the most common projection for online maps,
  1454. * used by almost all free and commercial tile providers. Assumes that Earth is
  1455. * a sphere. Used by the `EPSG:3857` CRS.
  1456. */
  1457. var earthRadius = 6378137;
  1458. var SphericalMercator = {
  1459. R: earthRadius,
  1460. MAX_LATITUDE: 85.0511287798,
  1461. project: function (latlng) {
  1462. var d = Math.PI / 180,
  1463. max = this.MAX_LATITUDE,
  1464. lat = Math.max(Math.min(max, latlng.lat), -max),
  1465. sin = Math.sin(lat * d);
  1466. return new Point(
  1467. this.R * latlng.lng * d,
  1468. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1469. },
  1470. unproject: function (point) {
  1471. var d = 180 / Math.PI;
  1472. return new LatLng(
  1473. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1474. point.x * d / this.R);
  1475. },
  1476. bounds: (function () {
  1477. var d = earthRadius * Math.PI;
  1478. return new Bounds([-d, -d], [d, d]);
  1479. })()
  1480. };
  1481. /*
  1482. * @class Transformation
  1483. * @aka L.Transformation
  1484. *
  1485. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1486. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1487. * the reverse. Used by Leaflet in its projections code.
  1488. *
  1489. * @example
  1490. *
  1491. * ```js
  1492. * var transformation = L.transformation(2, 5, -1, 10),
  1493. * p = L.point(1, 2),
  1494. * p2 = transformation.transform(p), // L.point(7, 8)
  1495. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1496. * ```
  1497. */
  1498. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1499. // Creates a `Transformation` object with the given coefficients.
  1500. function Transformation(a, b, c, d) {
  1501. if (isArray(a)) {
  1502. // use array properties
  1503. this._a = a[0];
  1504. this._b = a[1];
  1505. this._c = a[2];
  1506. this._d = a[3];
  1507. return;
  1508. }
  1509. this._a = a;
  1510. this._b = b;
  1511. this._c = c;
  1512. this._d = d;
  1513. }
  1514. Transformation.prototype = {
  1515. // @method transform(point: Point, scale?: Number): Point
  1516. // Returns a transformed point, optionally multiplied by the given scale.
  1517. // Only accepts actual `L.Point` instances, not arrays.
  1518. transform: function (point, scale) { // (Point, Number) -> Point
  1519. return this._transform(point.clone(), scale);
  1520. },
  1521. // destructive transform (faster)
  1522. _transform: function (point, scale) {
  1523. scale = scale || 1;
  1524. point.x = scale * (this._a * point.x + this._b);
  1525. point.y = scale * (this._c * point.y + this._d);
  1526. return point;
  1527. },
  1528. // @method untransform(point: Point, scale?: Number): Point
  1529. // Returns the reverse transformation of the given point, optionally divided
  1530. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1531. untransform: function (point, scale) {
  1532. scale = scale || 1;
  1533. return new Point(
  1534. (point.x / scale - this._b) / this._a,
  1535. (point.y / scale - this._d) / this._c);
  1536. }
  1537. };
  1538. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1539. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1540. // Instantiates a Transformation object with the given coefficients.
  1541. // @alternative
  1542. // @factory L.transformation(coefficients: Array): Transformation
  1543. // Expects an coefficients array of the form
  1544. // `[a: Number, b: Number, c: Number, d: Number]`.
  1545. function toTransformation(a, b, c, d) {
  1546. return new Transformation(a, b, c, d);
  1547. }
  1548. /*
  1549. * @namespace CRS
  1550. * @crs L.CRS.EPSG3857
  1551. *
  1552. * The most common CRS for online maps, used by almost all free and commercial
  1553. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1554. * Map's `crs` option.
  1555. */
  1556. var EPSG3857 = extend({}, Earth, {
  1557. code: 'EPSG:3857',
  1558. projection: SphericalMercator,
  1559. transformation: (function () {
  1560. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1561. return toTransformation(scale, 0.5, -scale, 0.5);
  1562. }())
  1563. });
  1564. var EPSG900913 = extend({}, EPSG3857, {
  1565. code: 'EPSG:900913'
  1566. });
  1567. // @namespace SVG; @section
  1568. // There are several static functions which can be called without instantiating L.SVG:
  1569. // @function create(name: String): SVGElement
  1570. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1571. // corresponding to the class name passed. For example, using 'line' will return
  1572. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1573. function svgCreate(name) {
  1574. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1575. }
  1576. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1577. // Generates a SVG path string for multiple rings, with each ring turning
  1578. // into "M..L..L.." instructions
  1579. function pointsToPath(rings, closed) {
  1580. var str = '',
  1581. i, j, len, len2, points, p;
  1582. for (i = 0, len = rings.length; i < len; i++) {
  1583. points = rings[i];
  1584. for (j = 0, len2 = points.length; j < len2; j++) {
  1585. p = points[j];
  1586. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1587. }
  1588. // closes the ring for polygons; "x" is VML syntax
  1589. str += closed ? (Browser.svg ? 'z' : 'x') : '';
  1590. }
  1591. // SVG complains about empty path strings
  1592. return str || 'M0 0';
  1593. }
  1594. /*
  1595. * @namespace Browser
  1596. * @aka L.Browser
  1597. *
  1598. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1599. *
  1600. * @example
  1601. *
  1602. * ```js
  1603. * if (L.Browser.ielt9) {
  1604. * alert('Upgrade your browser, dude!');
  1605. * }
  1606. * ```
  1607. */
  1608. var style = document.documentElement.style;
  1609. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1610. var ie = 'ActiveXObject' in window;
  1611. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1612. var ielt9 = ie && !document.addEventListener;
  1613. // @property edge: Boolean; `true` for the Edge web browser.
  1614. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1615. // @property webkit: Boolean;
  1616. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1617. var webkit = userAgentContains('webkit');
  1618. // @property android: Boolean
  1619. // **Deprecated.** `true` for any browser running on an Android platform.
  1620. var android = userAgentContains('android');
  1621. // @property android23: Boolean; **Deprecated.** `true` for browsers running on Android 2 or Android 3.
  1622. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1623. /* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */
  1624. var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit
  1625. // @property androidStock: Boolean; **Deprecated.** `true` for the Android stock browser (i.e. not Chrome)
  1626. var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);
  1627. // @property opera: Boolean; `true` for the Opera browser
  1628. var opera = !!window.opera;
  1629. // @property chrome: Boolean; `true` for the Chrome browser.
  1630. var chrome = !edge && userAgentContains('chrome');
  1631. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1632. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1633. // @property safari: Boolean; `true` for the Safari browser.
  1634. var safari = !chrome && userAgentContains('safari');
  1635. var phantom = userAgentContains('phantom');
  1636. // @property opera12: Boolean
  1637. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1638. var opera12 = 'OTransition' in style;
  1639. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1640. var win = navigator.platform.indexOf('Win') === 0;
  1641. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1642. var ie3d = ie && ('transition' in style);
  1643. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1644. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1645. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1646. var gecko3d = 'MozPerspective' in style;
  1647. // @property any3d: Boolean
  1648. // `true` for all browsers supporting CSS transforms.
  1649. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1650. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1651. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1652. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1653. var mobileWebkit = mobile && webkit;
  1654. // @property mobileWebkit3d: Boolean
  1655. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1656. var mobileWebkit3d = mobile && webkit3d;
  1657. // @property msPointer: Boolean
  1658. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1659. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1660. // @property pointer: Boolean
  1661. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1662. var pointer = !!(window.PointerEvent || msPointer);
  1663. // @property touchNative: Boolean
  1664. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1665. // **This does not necessarily mean** that the browser is running in a computer with
  1666. // a touchscreen, it only means that the browser is capable of understanding
  1667. // touch events.
  1668. var touchNative = 'ontouchstart' in window || !!window.TouchEvent;
  1669. // @property touch: Boolean
  1670. // `true` for all browsers supporting either [touch](#browser-touch) or [pointer](#browser-pointer) events.
  1671. // Note: pointer events will be preferred (if available), and processed for all `touch*` listeners.
  1672. var touch = !window.L_NO_TOUCH && (touchNative || pointer);
  1673. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1674. var mobileOpera = mobile && opera;
  1675. // @property mobileGecko: Boolean
  1676. // `true` for gecko-based browsers running in a mobile device.
  1677. var mobileGecko = mobile && gecko;
  1678. // @property retina: Boolean
  1679. // `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%.
  1680. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1681. // @property passiveEvents: Boolean
  1682. // `true` for browsers that support passive events.
  1683. var passiveEvents = (function () {
  1684. var supportsPassiveOption = false;
  1685. try {
  1686. var opts = Object.defineProperty({}, 'passive', {
  1687. get: function () { // eslint-disable-line getter-return
  1688. supportsPassiveOption = true;
  1689. }
  1690. });
  1691. window.addEventListener('testPassiveEventSupport', falseFn, opts);
  1692. window.removeEventListener('testPassiveEventSupport', falseFn, opts);
  1693. } catch (e) {
  1694. // Errors can safely be ignored since this is only a browser support test.
  1695. }
  1696. return supportsPassiveOption;
  1697. }());
  1698. // @property canvas: Boolean
  1699. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1700. var canvas$1 = (function () {
  1701. return !!document.createElement('canvas').getContext;
  1702. }());
  1703. // @property svg: Boolean
  1704. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1705. var svg$1 = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1706. var inlineSvg = !!svg$1 && (function () {
  1707. var div = document.createElement('div');
  1708. div.innerHTML = '<svg/>';
  1709. return (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg';
  1710. })();
  1711. // @property vml: Boolean
  1712. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1713. var vml = !svg$1 && (function () {
  1714. try {
  1715. var div = document.createElement('div');
  1716. div.innerHTML = '<v:shape adj="1"/>';
  1717. var shape = div.firstChild;
  1718. shape.style.behavior = 'url(#default#VML)';
  1719. return shape && (typeof shape.adj === 'object');
  1720. } catch (e) {
  1721. return false;
  1722. }
  1723. }());
  1724. // @property mac: Boolean; `true` when the browser is running in a Mac platform
  1725. var mac = navigator.platform.indexOf('Mac') === 0;
  1726. // @property mac: Boolean; `true` when the browser is running in a Linux platform
  1727. var linux = navigator.platform.indexOf('Linux') === 0;
  1728. function userAgentContains(str) {
  1729. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1730. }
  1731. var Browser = {
  1732. ie: ie,
  1733. ielt9: ielt9,
  1734. edge: edge,
  1735. webkit: webkit,
  1736. android: android,
  1737. android23: android23,
  1738. androidStock: androidStock,
  1739. opera: opera,
  1740. chrome: chrome,
  1741. gecko: gecko,
  1742. safari: safari,
  1743. phantom: phantom,
  1744. opera12: opera12,
  1745. win: win,
  1746. ie3d: ie3d,
  1747. webkit3d: webkit3d,
  1748. gecko3d: gecko3d,
  1749. any3d: any3d,
  1750. mobile: mobile,
  1751. mobileWebkit: mobileWebkit,
  1752. mobileWebkit3d: mobileWebkit3d,
  1753. msPointer: msPointer,
  1754. pointer: pointer,
  1755. touch: touch,
  1756. touchNative: touchNative,
  1757. mobileOpera: mobileOpera,
  1758. mobileGecko: mobileGecko,
  1759. retina: retina,
  1760. passiveEvents: passiveEvents,
  1761. canvas: canvas$1,
  1762. svg: svg$1,
  1763. vml: vml,
  1764. inlineSvg: inlineSvg,
  1765. mac: mac,
  1766. linux: linux
  1767. };
  1768. /*
  1769. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1770. */
  1771. var POINTER_DOWN = Browser.msPointer ? 'MSPointerDown' : 'pointerdown';
  1772. var POINTER_MOVE = Browser.msPointer ? 'MSPointerMove' : 'pointermove';
  1773. var POINTER_UP = Browser.msPointer ? 'MSPointerUp' : 'pointerup';
  1774. var POINTER_CANCEL = Browser.msPointer ? 'MSPointerCancel' : 'pointercancel';
  1775. var pEvent = {
  1776. touchstart : POINTER_DOWN,
  1777. touchmove : POINTER_MOVE,
  1778. touchend : POINTER_UP,
  1779. touchcancel : POINTER_CANCEL
  1780. };
  1781. var handle = {
  1782. touchstart : _onPointerStart,
  1783. touchmove : _handlePointer,
  1784. touchend : _handlePointer,
  1785. touchcancel : _handlePointer
  1786. };
  1787. var _pointers = {};
  1788. var _pointerDocListener = false;
  1789. // Provides a touch events wrapper for (ms)pointer events.
  1790. // ref https://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1791. function addPointerListener(obj, type, handler) {
  1792. if (type === 'touchstart') {
  1793. _addPointerDocListener();
  1794. }
  1795. if (!handle[type]) {
  1796. console.warn('wrong event specified:', type);
  1797. return falseFn;
  1798. }
  1799. handler = handle[type].bind(this, handler);
  1800. obj.addEventListener(pEvent[type], handler, false);
  1801. return handler;
  1802. }
  1803. function removePointerListener(obj, type, handler) {
  1804. if (!pEvent[type]) {
  1805. console.warn('wrong event specified:', type);
  1806. return;
  1807. }
  1808. obj.removeEventListener(pEvent[type], handler, false);
  1809. }
  1810. function _globalPointerDown(e) {
  1811. _pointers[e.pointerId] = e;
  1812. }
  1813. function _globalPointerMove(e) {
  1814. if (_pointers[e.pointerId]) {
  1815. _pointers[e.pointerId] = e;
  1816. }
  1817. }
  1818. function _globalPointerUp(e) {
  1819. delete _pointers[e.pointerId];
  1820. }
  1821. function _addPointerDocListener() {
  1822. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1823. if (!_pointerDocListener) {
  1824. // we listen document as any drags that end by moving the touch off the screen get fired there
  1825. document.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1826. document.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1827. document.addEventListener(POINTER_UP, _globalPointerUp, true);
  1828. document.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1829. _pointerDocListener = true;
  1830. }
  1831. }
  1832. function _handlePointer(handler, e) {
  1833. if (e.pointerType === (e.MSPOINTER_TYPE_MOUSE || 'mouse')) { return; }
  1834. e.touches = [];
  1835. for (var i in _pointers) {
  1836. e.touches.push(_pointers[i]);
  1837. }
  1838. e.changedTouches = [e];
  1839. handler(e);
  1840. }
  1841. function _onPointerStart(handler, e) {
  1842. // IE10 specific: MsTouch needs preventDefault. See #2000
  1843. if (e.MSPOINTER_TYPE_TOUCH && e.pointerType === e.MSPOINTER_TYPE_TOUCH) {
  1844. preventDefault(e);
  1845. }
  1846. _handlePointer(handler, e);
  1847. }
  1848. /*
  1849. * Extends the event handling code with double tap support for mobile browsers.
  1850. *
  1851. * Note: currently most browsers fire native dblclick, with only a few exceptions
  1852. * (see https://github.com/Leaflet/Leaflet/issues/7012#issuecomment-595087386)
  1853. */
  1854. function makeDblclick(event) {
  1855. // in modern browsers `type` cannot be just overridden:
  1856. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only
  1857. var newEvent = {},
  1858. prop, i;
  1859. for (i in event) {
  1860. prop = event[i];
  1861. newEvent[i] = prop && prop.bind ? prop.bind(event) : prop;
  1862. }
  1863. event = newEvent;
  1864. newEvent.type = 'dblclick';
  1865. newEvent.detail = 2;
  1866. newEvent.isTrusted = false;
  1867. newEvent._simulated = true; // for debug purposes
  1868. return newEvent;
  1869. }
  1870. var delay = 200;
  1871. function addDoubleTapListener(obj, handler) {
  1872. // Most browsers handle double tap natively
  1873. obj.addEventListener('dblclick', handler);
  1874. // On some platforms the browser doesn't fire native dblclicks for touch events.
  1875. // It seems that in all such cases `detail` property of `click` event is always `1`.
  1876. // So here we rely on that fact to avoid excessive 'dblclick' simulation when not needed.
  1877. var last = 0,
  1878. detail;
  1879. function simDblclick(e) {
  1880. if (e.detail !== 1) {
  1881. detail = e.detail; // keep in sync to avoid false dblclick in some cases
  1882. return;
  1883. }
  1884. if (e.pointerType === 'mouse' ||
  1885. (e.sourceCapabilities && !e.sourceCapabilities.firesTouchEvents)) {
  1886. return;
  1887. }
  1888. // When clicking on an <input>, the browser generates a click on its
  1889. // <label> (and vice versa) triggering two clicks in quick succession.
  1890. // This ignores clicks on elements which are a label with a 'for'
  1891. // attribute (or children of such a label), but not children of
  1892. // a <input>.
  1893. var path = getPropagationPath(e);
  1894. if (path.some(function (el) {
  1895. return el instanceof HTMLLabelElement && el.attributes.for;
  1896. }) &&
  1897. !path.some(function (el) {
  1898. return (
  1899. el instanceof HTMLInputElement ||
  1900. el instanceof HTMLSelectElement
  1901. );
  1902. })
  1903. ) {
  1904. return;
  1905. }
  1906. var now = Date.now();
  1907. if (now - last <= delay) {
  1908. detail++;
  1909. if (detail === 2) {
  1910. handler(makeDblclick(e));
  1911. }
  1912. } else {
  1913. detail = 1;
  1914. }
  1915. last = now;
  1916. }
  1917. obj.addEventListener('click', simDblclick);
  1918. return {
  1919. dblclick: handler,
  1920. simDblclick: simDblclick
  1921. };
  1922. }
  1923. function removeDoubleTapListener(obj, handlers) {
  1924. obj.removeEventListener('dblclick', handlers.dblclick);
  1925. obj.removeEventListener('click', handlers.simDblclick);
  1926. }
  1927. /*
  1928. * @namespace DomUtil
  1929. *
  1930. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1931. * tree, used by Leaflet internally.
  1932. *
  1933. * Most functions expecting or returning a `HTMLElement` also work for
  1934. * SVG elements. The only difference is that classes refer to CSS classes
  1935. * in HTML and SVG classes in SVG.
  1936. */
  1937. // @property TRANSFORM: String
  1938. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  1939. var TRANSFORM = testProp(
  1940. ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1941. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1942. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1943. // @property TRANSITION: String
  1944. // Vendor-prefixed transition style name.
  1945. var TRANSITION = testProp(
  1946. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1947. // @property TRANSITION_END: String
  1948. // Vendor-prefixed transitionend event name.
  1949. var TRANSITION_END =
  1950. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  1951. // @function get(id: String|HTMLElement): HTMLElement
  1952. // Returns an element given its DOM id, or returns the element itself
  1953. // if it was passed directly.
  1954. function get(id) {
  1955. return typeof id === 'string' ? document.getElementById(id) : id;
  1956. }
  1957. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1958. // Returns the value for a certain style attribute on an element,
  1959. // including computed values or values set through CSS.
  1960. function getStyle(el, style) {
  1961. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1962. if ((!value || value === 'auto') && document.defaultView) {
  1963. var css = document.defaultView.getComputedStyle(el, null);
  1964. value = css ? css[style] : null;
  1965. }
  1966. return value === 'auto' ? null : value;
  1967. }
  1968. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1969. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1970. function create$1(tagName, className, container) {
  1971. var el = document.createElement(tagName);
  1972. el.className = className || '';
  1973. if (container) {
  1974. container.appendChild(el);
  1975. }
  1976. return el;
  1977. }
  1978. // @function remove(el: HTMLElement)
  1979. // Removes `el` from its parent element
  1980. function remove(el) {
  1981. var parent = el.parentNode;
  1982. if (parent) {
  1983. parent.removeChild(el);
  1984. }
  1985. }
  1986. // @function empty(el: HTMLElement)
  1987. // Removes all of `el`'s children elements from `el`
  1988. function empty(el) {
  1989. while (el.firstChild) {
  1990. el.removeChild(el.firstChild);
  1991. }
  1992. }
  1993. // @function toFront(el: HTMLElement)
  1994. // Makes `el` the last child of its parent, so it renders in front of the other children.
  1995. function toFront(el) {
  1996. var parent = el.parentNode;
  1997. if (parent && parent.lastChild !== el) {
  1998. parent.appendChild(el);
  1999. }
  2000. }
  2001. // @function toBack(el: HTMLElement)
  2002. // Makes `el` the first child of its parent, so it renders behind the other children.
  2003. function toBack(el) {
  2004. var parent = el.parentNode;
  2005. if (parent && parent.firstChild !== el) {
  2006. parent.insertBefore(el, parent.firstChild);
  2007. }
  2008. }
  2009. // @function hasClass(el: HTMLElement, name: String): Boolean
  2010. // Returns `true` if the element's class attribute contains `name`.
  2011. function hasClass(el, name) {
  2012. if (el.classList !== undefined) {
  2013. return el.classList.contains(name);
  2014. }
  2015. var className = getClass(el);
  2016. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  2017. }
  2018. // @function addClass(el: HTMLElement, name: String)
  2019. // Adds `name` to the element's class attribute.
  2020. function addClass(el, name) {
  2021. if (el.classList !== undefined) {
  2022. var classes = splitWords(name);
  2023. for (var i = 0, len = classes.length; i < len; i++) {
  2024. el.classList.add(classes[i]);
  2025. }
  2026. } else if (!hasClass(el, name)) {
  2027. var className = getClass(el);
  2028. setClass(el, (className ? className + ' ' : '') + name);
  2029. }
  2030. }
  2031. // @function removeClass(el: HTMLElement, name: String)
  2032. // Removes `name` from the element's class attribute.
  2033. function removeClass(el, name) {
  2034. if (el.classList !== undefined) {
  2035. el.classList.remove(name);
  2036. } else {
  2037. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  2038. }
  2039. }
  2040. // @function setClass(el: HTMLElement, name: String)
  2041. // Sets the element's class.
  2042. function setClass(el, name) {
  2043. if (el.className.baseVal === undefined) {
  2044. el.className = name;
  2045. } else {
  2046. // in case of SVG element
  2047. el.className.baseVal = name;
  2048. }
  2049. }
  2050. // @function getClass(el: HTMLElement): String
  2051. // Returns the element's class.
  2052. function getClass(el) {
  2053. // Check if the element is an SVGElementInstance and use the correspondingElement instead
  2054. // (Required for linked SVG elements in IE11.)
  2055. if (el.correspondingElement) {
  2056. el = el.correspondingElement;
  2057. }
  2058. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  2059. }
  2060. // @function setOpacity(el: HTMLElement, opacity: Number)
  2061. // Set the opacity of an element (including old IE support).
  2062. // `opacity` must be a number from `0` to `1`.
  2063. function setOpacity(el, value) {
  2064. if ('opacity' in el.style) {
  2065. el.style.opacity = value;
  2066. } else if ('filter' in el.style) {
  2067. _setOpacityIE(el, value);
  2068. }
  2069. }
  2070. function _setOpacityIE(el, value) {
  2071. var filter = false,
  2072. filterName = 'DXImageTransform.Microsoft.Alpha';
  2073. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  2074. try {
  2075. filter = el.filters.item(filterName);
  2076. } catch (e) {
  2077. // don't set opacity to 1 if we haven't already set an opacity,
  2078. // it isn't needed and breaks transparent pngs.
  2079. if (value === 1) { return; }
  2080. }
  2081. value = Math.round(value * 100);
  2082. if (filter) {
  2083. filter.Enabled = (value !== 100);
  2084. filter.Opacity = value;
  2085. } else {
  2086. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  2087. }
  2088. }
  2089. // @function testProp(props: String[]): String|false
  2090. // Goes through the array of style names and returns the first name
  2091. // that is a valid style name for an element. If no such name is found,
  2092. // it returns false. Useful for vendor-prefixed styles like `transform`.
  2093. function testProp(props) {
  2094. var style = document.documentElement.style;
  2095. for (var i = 0; i < props.length; i++) {
  2096. if (props[i] in style) {
  2097. return props[i];
  2098. }
  2099. }
  2100. return false;
  2101. }
  2102. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  2103. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  2104. // and optionally scaled by `scale`. Does not have an effect if the
  2105. // browser doesn't support 3D CSS transforms.
  2106. function setTransform(el, offset, scale) {
  2107. var pos = offset || new Point(0, 0);
  2108. el.style[TRANSFORM] =
  2109. (Browser.ie3d ?
  2110. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2111. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2112. (scale ? ' scale(' + scale + ')' : '');
  2113. }
  2114. // @function setPosition(el: HTMLElement, position: Point)
  2115. // Sets the position of `el` to coordinates specified by `position`,
  2116. // using CSS translate or top/left positioning depending on the browser
  2117. // (used by Leaflet internally to position its layers).
  2118. function setPosition(el, point) {
  2119. /*eslint-disable */
  2120. el._leaflet_pos = point;
  2121. /* eslint-enable */
  2122. if (Browser.any3d) {
  2123. setTransform(el, point);
  2124. } else {
  2125. el.style.left = point.x + 'px';
  2126. el.style.top = point.y + 'px';
  2127. }
  2128. }
  2129. // @function getPosition(el: HTMLElement): Point
  2130. // Returns the coordinates of an element previously positioned with setPosition.
  2131. function getPosition(el) {
  2132. // this method is only used for elements previously positioned using setPosition,
  2133. // so it's safe to cache the position for performance
  2134. return el._leaflet_pos || new Point(0, 0);
  2135. }
  2136. // @function disableTextSelection()
  2137. // Prevents the user from generating `selectstart` DOM events, usually generated
  2138. // when the user drags the mouse through a page with text. Used internally
  2139. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2140. // the map. Affects drag interactions on the whole document.
  2141. // @function enableTextSelection()
  2142. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2143. var disableTextSelection;
  2144. var enableTextSelection;
  2145. var _userSelect;
  2146. if ('onselectstart' in document) {
  2147. disableTextSelection = function () {
  2148. on(window, 'selectstart', preventDefault);
  2149. };
  2150. enableTextSelection = function () {
  2151. off(window, 'selectstart', preventDefault);
  2152. };
  2153. } else {
  2154. var userSelectProperty = testProp(
  2155. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2156. disableTextSelection = function () {
  2157. if (userSelectProperty) {
  2158. var style = document.documentElement.style;
  2159. _userSelect = style[userSelectProperty];
  2160. style[userSelectProperty] = 'none';
  2161. }
  2162. };
  2163. enableTextSelection = function () {
  2164. if (userSelectProperty) {
  2165. document.documentElement.style[userSelectProperty] = _userSelect;
  2166. _userSelect = undefined;
  2167. }
  2168. };
  2169. }
  2170. // @function disableImageDrag()
  2171. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2172. // for `dragstart` DOM events, usually generated when the user drags an image.
  2173. function disableImageDrag() {
  2174. on(window, 'dragstart', preventDefault);
  2175. }
  2176. // @function enableImageDrag()
  2177. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2178. function enableImageDrag() {
  2179. off(window, 'dragstart', preventDefault);
  2180. }
  2181. var _outlineElement, _outlineStyle;
  2182. // @function preventOutline(el: HTMLElement)
  2183. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2184. // of the element `el` invisible. Used internally by Leaflet to prevent
  2185. // focusable elements from displaying an outline when the user performs a
  2186. // drag interaction on them.
  2187. function preventOutline(element) {
  2188. while (element.tabIndex === -1) {
  2189. element = element.parentNode;
  2190. }
  2191. if (!element.style) { return; }
  2192. restoreOutline();
  2193. _outlineElement = element;
  2194. _outlineStyle = element.style.outline;
  2195. element.style.outline = 'none';
  2196. on(window, 'keydown', restoreOutline);
  2197. }
  2198. // @function restoreOutline()
  2199. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2200. function restoreOutline() {
  2201. if (!_outlineElement) { return; }
  2202. _outlineElement.style.outline = _outlineStyle;
  2203. _outlineElement = undefined;
  2204. _outlineStyle = undefined;
  2205. off(window, 'keydown', restoreOutline);
  2206. }
  2207. // @function getSizedParentNode(el: HTMLElement): HTMLElement
  2208. // Finds the closest parent node which size (width and height) is not null.
  2209. function getSizedParentNode(element) {
  2210. do {
  2211. element = element.parentNode;
  2212. } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);
  2213. return element;
  2214. }
  2215. // @function getScale(el: HTMLElement): Object
  2216. // Computes the CSS scale currently applied on the element.
  2217. // Returns an object with `x` and `y` members as horizontal and vertical scales respectively,
  2218. // and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2219. function getScale(element) {
  2220. var rect = element.getBoundingClientRect(); // Read-only in old browsers.
  2221. return {
  2222. x: rect.width / element.offsetWidth || 1,
  2223. y: rect.height / element.offsetHeight || 1,
  2224. boundingClientRect: rect
  2225. };
  2226. }
  2227. var DomUtil = {
  2228. __proto__: null,
  2229. TRANSFORM: TRANSFORM,
  2230. TRANSITION: TRANSITION,
  2231. TRANSITION_END: TRANSITION_END,
  2232. get: get,
  2233. getStyle: getStyle,
  2234. create: create$1,
  2235. remove: remove,
  2236. empty: empty,
  2237. toFront: toFront,
  2238. toBack: toBack,
  2239. hasClass: hasClass,
  2240. addClass: addClass,
  2241. removeClass: removeClass,
  2242. setClass: setClass,
  2243. getClass: getClass,
  2244. setOpacity: setOpacity,
  2245. testProp: testProp,
  2246. setTransform: setTransform,
  2247. setPosition: setPosition,
  2248. getPosition: getPosition,
  2249. get disableTextSelection () { return disableTextSelection; },
  2250. get enableTextSelection () { return enableTextSelection; },
  2251. disableImageDrag: disableImageDrag,
  2252. enableImageDrag: enableImageDrag,
  2253. preventOutline: preventOutline,
  2254. restoreOutline: restoreOutline,
  2255. getSizedParentNode: getSizedParentNode,
  2256. getScale: getScale
  2257. };
  2258. /*
  2259. * @namespace DomEvent
  2260. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  2261. */
  2262. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  2263. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2264. // Adds a listener function (`fn`) to a particular DOM event type of the
  2265. // element `el`. You can optionally specify the context of the listener
  2266. // (object the `this` keyword will point to). You can also pass several
  2267. // space-separated types (e.g. `'click dblclick'`).
  2268. // @alternative
  2269. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  2270. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2271. function on(obj, types, fn, context) {
  2272. if (types && typeof types === 'object') {
  2273. for (var type in types) {
  2274. addOne(obj, type, types[type], fn);
  2275. }
  2276. } else {
  2277. types = splitWords(types);
  2278. for (var i = 0, len = types.length; i < len; i++) {
  2279. addOne(obj, types[i], fn, context);
  2280. }
  2281. }
  2282. return this;
  2283. }
  2284. var eventsKey = '_leaflet_events';
  2285. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2286. // Removes a previously added listener function.
  2287. // Note that if you passed a custom context to on, you must pass the same
  2288. // context to `off` in order to remove the listener.
  2289. // @alternative
  2290. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  2291. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2292. // @alternative
  2293. // @function off(el: HTMLElement, types: String): this
  2294. // Removes all previously added listeners of given types.
  2295. // @alternative
  2296. // @function off(el: HTMLElement): this
  2297. // Removes all previously added listeners from given HTMLElement
  2298. function off(obj, types, fn, context) {
  2299. if (arguments.length === 1) {
  2300. batchRemove(obj);
  2301. delete obj[eventsKey];
  2302. } else if (types && typeof types === 'object') {
  2303. for (var type in types) {
  2304. removeOne(obj, type, types[type], fn);
  2305. }
  2306. } else {
  2307. types = splitWords(types);
  2308. if (arguments.length === 2) {
  2309. batchRemove(obj, function (type) {
  2310. return indexOf(types, type) !== -1;
  2311. });
  2312. } else {
  2313. for (var i = 0, len = types.length; i < len; i++) {
  2314. removeOne(obj, types[i], fn, context);
  2315. }
  2316. }
  2317. }
  2318. return this;
  2319. }
  2320. function batchRemove(obj, filterFn) {
  2321. for (var id in obj[eventsKey]) {
  2322. var type = id.split(/\d/)[0];
  2323. if (!filterFn || filterFn(type)) {
  2324. removeOne(obj, type, null, null, id);
  2325. }
  2326. }
  2327. }
  2328. var mouseSubst = {
  2329. mouseenter: 'mouseover',
  2330. mouseleave: 'mouseout',
  2331. wheel: !('onwheel' in window) && 'mousewheel'
  2332. };
  2333. function addOne(obj, type, fn, context) {
  2334. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2335. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  2336. var handler = function (e) {
  2337. return fn.call(context || obj, e || window.event);
  2338. };
  2339. var originalHandler = handler;
  2340. if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {
  2341. // Needs DomEvent.Pointer.js
  2342. handler = addPointerListener(obj, type, handler);
  2343. } else if (Browser.touch && (type === 'dblclick')) {
  2344. handler = addDoubleTapListener(obj, handler);
  2345. } else if ('addEventListener' in obj) {
  2346. if (type === 'touchstart' || type === 'touchmove' || type === 'wheel' || type === 'mousewheel') {
  2347. obj.addEventListener(mouseSubst[type] || type, handler, Browser.passiveEvents ? {passive: false} : false);
  2348. } else if (type === 'mouseenter' || type === 'mouseleave') {
  2349. handler = function (e) {
  2350. e = e || window.event;
  2351. if (isExternalTarget(obj, e)) {
  2352. originalHandler(e);
  2353. }
  2354. };
  2355. obj.addEventListener(mouseSubst[type], handler, false);
  2356. } else {
  2357. obj.addEventListener(type, originalHandler, false);
  2358. }
  2359. } else {
  2360. obj.attachEvent('on' + type, handler);
  2361. }
  2362. obj[eventsKey] = obj[eventsKey] || {};
  2363. obj[eventsKey][id] = handler;
  2364. }
  2365. function removeOne(obj, type, fn, context, id) {
  2366. id = id || type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2367. var handler = obj[eventsKey] && obj[eventsKey][id];
  2368. if (!handler) { return this; }
  2369. if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {
  2370. removePointerListener(obj, type, handler);
  2371. } else if (Browser.touch && (type === 'dblclick')) {
  2372. removeDoubleTapListener(obj, handler);
  2373. } else if ('removeEventListener' in obj) {
  2374. obj.removeEventListener(mouseSubst[type] || type, handler, false);
  2375. } else {
  2376. obj.detachEvent('on' + type, handler);
  2377. }
  2378. obj[eventsKey][id] = null;
  2379. }
  2380. // @function stopPropagation(ev: DOMEvent): this
  2381. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  2382. // ```js
  2383. // L.DomEvent.on(div, 'click', function (ev) {
  2384. // L.DomEvent.stopPropagation(ev);
  2385. // });
  2386. // ```
  2387. function stopPropagation(e) {
  2388. if (e.stopPropagation) {
  2389. e.stopPropagation();
  2390. } else if (e.originalEvent) { // In case of Leaflet event.
  2391. e.originalEvent._stopped = true;
  2392. } else {
  2393. e.cancelBubble = true;
  2394. }
  2395. return this;
  2396. }
  2397. // @function disableScrollPropagation(el: HTMLElement): this
  2398. // Adds `stopPropagation` to the element's `'wheel'` events (plus browser variants).
  2399. function disableScrollPropagation(el) {
  2400. addOne(el, 'wheel', stopPropagation);
  2401. return this;
  2402. }
  2403. // @function disableClickPropagation(el: HTMLElement): this
  2404. // Adds `stopPropagation` to the element's `'click'`, `'dblclick'`, `'contextmenu'`,
  2405. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  2406. function disableClickPropagation(el) {
  2407. on(el, 'mousedown touchstart dblclick contextmenu', stopPropagation);
  2408. el['_leaflet_disable_click'] = true;
  2409. return this;
  2410. }
  2411. // @function preventDefault(ev: DOMEvent): this
  2412. // Prevents the default action of the DOM Event `ev` from happening (such as
  2413. // following a link in the href of the a element, or doing a POST request
  2414. // with page reload when a `<form>` is submitted).
  2415. // Use it inside listener functions.
  2416. function preventDefault(e) {
  2417. if (e.preventDefault) {
  2418. e.preventDefault();
  2419. } else {
  2420. e.returnValue = false;
  2421. }
  2422. return this;
  2423. }
  2424. // @function stop(ev: DOMEvent): this
  2425. // Does `stopPropagation` and `preventDefault` at the same time.
  2426. function stop(e) {
  2427. preventDefault(e);
  2428. stopPropagation(e);
  2429. return this;
  2430. }
  2431. // @function getPropagationPath(ev: DOMEvent): Array
  2432. // Compatibility polyfill for [`Event.composedPath()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath).
  2433. // Returns an array containing the `HTMLElement`s that the given DOM event
  2434. // should propagate to (if not stopped).
  2435. function getPropagationPath(ev) {
  2436. if (ev.composedPath) {
  2437. return ev.composedPath();
  2438. }
  2439. var path = [];
  2440. var el = ev.target;
  2441. while (el) {
  2442. path.push(el);
  2443. el = el.parentNode;
  2444. }
  2445. return path;
  2446. }
  2447. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  2448. // Gets normalized mouse position from a DOM event relative to the
  2449. // `container` (border excluded) or to the whole page if not specified.
  2450. function getMousePosition(e, container) {
  2451. if (!container) {
  2452. return new Point(e.clientX, e.clientY);
  2453. }
  2454. var scale = getScale(container),
  2455. offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)
  2456. return new Point(
  2457. // offset.left/top values are in page scale (like clientX/Y),
  2458. // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
  2459. (e.clientX - offset.left) / scale.x - container.clientLeft,
  2460. (e.clientY - offset.top) / scale.y - container.clientTop
  2461. );
  2462. }
  2463. // except , Safari and
  2464. // We need double the scroll pixels (see #7403 and #4538) for all Browsers
  2465. // except OSX (Mac) -> 3x, Chrome running on Linux 1x
  2466. var wheelPxFactor =
  2467. (Browser.linux && Browser.chrome) ? window.devicePixelRatio :
  2468. Browser.mac ? window.devicePixelRatio * 3 :
  2469. window.devicePixelRatio > 0 ? 2 * window.devicePixelRatio : 1;
  2470. // @function getWheelDelta(ev: DOMEvent): Number
  2471. // Gets normalized wheel delta from a wheel DOM event, in vertical
  2472. // pixels scrolled (negative if scrolling down).
  2473. // Events from pointing devices without precise scrolling are mapped to
  2474. // a best guess of 60 pixels.
  2475. function getWheelDelta(e) {
  2476. return (Browser.edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2477. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2478. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2479. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2480. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2481. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2482. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2483. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2484. 0;
  2485. }
  2486. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2487. function isExternalTarget(el, e) {
  2488. var related = e.relatedTarget;
  2489. if (!related) { return true; }
  2490. try {
  2491. while (related && (related !== el)) {
  2492. related = related.parentNode;
  2493. }
  2494. } catch (err) {
  2495. return false;
  2496. }
  2497. return (related !== el);
  2498. }
  2499. var DomEvent = {
  2500. __proto__: null,
  2501. on: on,
  2502. off: off,
  2503. stopPropagation: stopPropagation,
  2504. disableScrollPropagation: disableScrollPropagation,
  2505. disableClickPropagation: disableClickPropagation,
  2506. preventDefault: preventDefault,
  2507. stop: stop,
  2508. getPropagationPath: getPropagationPath,
  2509. getMousePosition: getMousePosition,
  2510. getWheelDelta: getWheelDelta,
  2511. isExternalTarget: isExternalTarget,
  2512. addListener: on,
  2513. removeListener: off
  2514. };
  2515. /*
  2516. * @class PosAnimation
  2517. * @aka L.PosAnimation
  2518. * @inherits Evented
  2519. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2520. *
  2521. * @example
  2522. * ```js
  2523. * var myPositionMarker = L.marker([48.864716, 2.294694]).addTo(map);
  2524. *
  2525. * myPositionMarker.on("click", function() {
  2526. * var pos = map.latLngToLayerPoint(myPositionMarker.getLatLng());
  2527. * pos.y -= 25;
  2528. * var fx = new L.PosAnimation();
  2529. *
  2530. * fx.once('end',function() {
  2531. * pos.y += 25;
  2532. * fx.run(myPositionMarker._icon, pos, 0.8);
  2533. * });
  2534. *
  2535. * fx.run(myPositionMarker._icon, pos, 0.3);
  2536. * });
  2537. *
  2538. * ```
  2539. *
  2540. * @constructor L.PosAnimation()
  2541. * Creates a `PosAnimation` object.
  2542. *
  2543. */
  2544. var PosAnimation = Evented.extend({
  2545. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2546. // Run an animation of a given element to a new position, optionally setting
  2547. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2548. // argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1),
  2549. // `0.5` by default).
  2550. run: function (el, newPos, duration, easeLinearity) {
  2551. this.stop();
  2552. this._el = el;
  2553. this._inProgress = true;
  2554. this._duration = duration || 0.25;
  2555. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2556. this._startPos = getPosition(el);
  2557. this._offset = newPos.subtract(this._startPos);
  2558. this._startTime = +new Date();
  2559. // @event start: Event
  2560. // Fired when the animation starts
  2561. this.fire('start');
  2562. this._animate();
  2563. },
  2564. // @method stop()
  2565. // Stops the animation (if currently running).
  2566. stop: function () {
  2567. if (!this._inProgress) { return; }
  2568. this._step(true);
  2569. this._complete();
  2570. },
  2571. _animate: function () {
  2572. // animation loop
  2573. this._animId = requestAnimFrame(this._animate, this);
  2574. this._step();
  2575. },
  2576. _step: function (round) {
  2577. var elapsed = (+new Date()) - this._startTime,
  2578. duration = this._duration * 1000;
  2579. if (elapsed < duration) {
  2580. this._runFrame(this._easeOut(elapsed / duration), round);
  2581. } else {
  2582. this._runFrame(1);
  2583. this._complete();
  2584. }
  2585. },
  2586. _runFrame: function (progress, round) {
  2587. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2588. if (round) {
  2589. pos._round();
  2590. }
  2591. setPosition(this._el, pos);
  2592. // @event step: Event
  2593. // Fired continuously during the animation.
  2594. this.fire('step');
  2595. },
  2596. _complete: function () {
  2597. cancelAnimFrame(this._animId);
  2598. this._inProgress = false;
  2599. // @event end: Event
  2600. // Fired when the animation ends.
  2601. this.fire('end');
  2602. },
  2603. _easeOut: function (t) {
  2604. return 1 - Math.pow(1 - t, this._easeOutPower);
  2605. }
  2606. });
  2607. /*
  2608. * @class Map
  2609. * @aka L.Map
  2610. * @inherits Evented
  2611. *
  2612. * The central class of the API — it is used to create a map on a page and manipulate it.
  2613. *
  2614. * @example
  2615. *
  2616. * ```js
  2617. * // initialize the map on the "map" div with a given center and zoom
  2618. * var map = L.map('map', {
  2619. * center: [51.505, -0.09],
  2620. * zoom: 13
  2621. * });
  2622. * ```
  2623. *
  2624. */
  2625. var Map = Evented.extend({
  2626. options: {
  2627. // @section Map State Options
  2628. // @option crs: CRS = L.CRS.EPSG3857
  2629. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2630. // sure what it means.
  2631. crs: EPSG3857,
  2632. // @option center: LatLng = undefined
  2633. // Initial geographic center of the map
  2634. center: undefined,
  2635. // @option zoom: Number = undefined
  2636. // Initial map zoom level
  2637. zoom: undefined,
  2638. // @option minZoom: Number = *
  2639. // Minimum zoom level of the map.
  2640. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2641. // the lowest of their `minZoom` options will be used instead.
  2642. minZoom: undefined,
  2643. // @option maxZoom: Number = *
  2644. // Maximum zoom level of the map.
  2645. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2646. // the highest of their `maxZoom` options will be used instead.
  2647. maxZoom: undefined,
  2648. // @option layers: Layer[] = []
  2649. // Array of layers that will be added to the map initially
  2650. layers: [],
  2651. // @option maxBounds: LatLngBounds = null
  2652. // When this option is set, the map restricts the view to the given
  2653. // geographical bounds, bouncing the user back if the user tries to pan
  2654. // outside the view. To set the restriction dynamically, use
  2655. // [`setMaxBounds`](#map-setmaxbounds) method.
  2656. maxBounds: undefined,
  2657. // @option renderer: Renderer = *
  2658. // The default method for drawing vector layers on the map. `L.SVG`
  2659. // or `L.Canvas` by default depending on browser support.
  2660. renderer: undefined,
  2661. // @section Animation Options
  2662. // @option zoomAnimation: Boolean = true
  2663. // Whether the map zoom animation is enabled. By default it's enabled
  2664. // in all browsers that support CSS3 Transitions except Android.
  2665. zoomAnimation: true,
  2666. // @option zoomAnimationThreshold: Number = 4
  2667. // Won't animate zoom if the zoom difference exceeds this value.
  2668. zoomAnimationThreshold: 4,
  2669. // @option fadeAnimation: Boolean = true
  2670. // Whether the tile fade animation is enabled. By default it's enabled
  2671. // in all browsers that support CSS3 Transitions except Android.
  2672. fadeAnimation: true,
  2673. // @option markerZoomAnimation: Boolean = true
  2674. // Whether markers animate their zoom with the zoom animation, if disabled
  2675. // they will disappear for the length of the animation. By default it's
  2676. // enabled in all browsers that support CSS3 Transitions except Android.
  2677. markerZoomAnimation: true,
  2678. // @option transform3DLimit: Number = 2^23
  2679. // Defines the maximum size of a CSS translation transform. The default
  2680. // value should not be changed unless a web browser positions layers in
  2681. // the wrong place after doing a large `panBy`.
  2682. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2683. // @section Interaction Options
  2684. // @option zoomSnap: Number = 1
  2685. // Forces the map's zoom level to always be a multiple of this, particularly
  2686. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2687. // By default, the zoom level snaps to the nearest integer; lower values
  2688. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2689. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2690. zoomSnap: 1,
  2691. // @option zoomDelta: Number = 1
  2692. // Controls how much the map's zoom level will change after a
  2693. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2694. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2695. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2696. zoomDelta: 1,
  2697. // @option trackResize: Boolean = true
  2698. // Whether the map automatically handles browser window resize to update itself.
  2699. trackResize: true
  2700. },
  2701. initialize: function (id, options) { // (HTMLElement or String, Object)
  2702. options = setOptions(this, options);
  2703. // Make sure to assign internal flags at the beginning,
  2704. // to avoid inconsistent state in some edge cases.
  2705. this._handlers = [];
  2706. this._layers = {};
  2707. this._zoomBoundLayers = {};
  2708. this._sizeChanged = true;
  2709. this._initContainer(id);
  2710. this._initLayout();
  2711. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2712. this._onResize = bind(this._onResize, this);
  2713. this._initEvents();
  2714. if (options.maxBounds) {
  2715. this.setMaxBounds(options.maxBounds);
  2716. }
  2717. if (options.zoom !== undefined) {
  2718. this._zoom = this._limitZoom(options.zoom);
  2719. }
  2720. if (options.center && options.zoom !== undefined) {
  2721. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2722. }
  2723. this.callInitHooks();
  2724. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2725. this._zoomAnimated = TRANSITION && Browser.any3d && !Browser.mobileOpera &&
  2726. this.options.zoomAnimation;
  2727. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2728. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2729. if (this._zoomAnimated) {
  2730. this._createAnimProxy();
  2731. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2732. }
  2733. this._addLayers(this.options.layers);
  2734. },
  2735. // @section Methods for modifying map state
  2736. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2737. // Sets the view of the map (geographical center and zoom) with the given
  2738. // animation options.
  2739. setView: function (center, zoom, options) {
  2740. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2741. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2742. options = options || {};
  2743. this._stop();
  2744. if (this._loaded && !options.reset && options !== true) {
  2745. if (options.animate !== undefined) {
  2746. options.zoom = extend({animate: options.animate}, options.zoom);
  2747. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2748. }
  2749. // try animating pan or zoom
  2750. var moved = (this._zoom !== zoom) ?
  2751. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2752. this._tryAnimatedPan(center, options.pan);
  2753. if (moved) {
  2754. // prevent resize handler call, the view will refresh after animation anyway
  2755. clearTimeout(this._sizeTimer);
  2756. return this;
  2757. }
  2758. }
  2759. // animation didn't start, just reset the map view
  2760. this._resetView(center, zoom, options.pan && options.pan.noMoveStart);
  2761. return this;
  2762. },
  2763. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2764. // Sets the zoom of the map.
  2765. setZoom: function (zoom, options) {
  2766. if (!this._loaded) {
  2767. this._zoom = zoom;
  2768. return this;
  2769. }
  2770. return this.setView(this.getCenter(), zoom, {zoom: options});
  2771. },
  2772. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2773. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2774. zoomIn: function (delta, options) {
  2775. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  2776. return this.setZoom(this._zoom + delta, options);
  2777. },
  2778. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2779. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2780. zoomOut: function (delta, options) {
  2781. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  2782. return this.setZoom(this._zoom - delta, options);
  2783. },
  2784. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2785. // Zooms the map while keeping a specified geographical point on the map
  2786. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2787. // @alternative
  2788. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2789. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2790. setZoomAround: function (latlng, zoom, options) {
  2791. var scale = this.getZoomScale(zoom),
  2792. viewHalf = this.getSize().divideBy(2),
  2793. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2794. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2795. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2796. return this.setView(newCenter, zoom, {zoom: options});
  2797. },
  2798. _getBoundsCenterZoom: function (bounds, options) {
  2799. options = options || {};
  2800. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2801. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2802. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2803. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2804. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2805. if (zoom === Infinity) {
  2806. return {
  2807. center: bounds.getCenter(),
  2808. zoom: zoom
  2809. };
  2810. }
  2811. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2812. swPoint = this.project(bounds.getSouthWest(), zoom),
  2813. nePoint = this.project(bounds.getNorthEast(), zoom),
  2814. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2815. return {
  2816. center: center,
  2817. zoom: zoom
  2818. };
  2819. },
  2820. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2821. // Sets a map view that contains the given geographical bounds with the
  2822. // maximum zoom level possible.
  2823. fitBounds: function (bounds, options) {
  2824. bounds = toLatLngBounds(bounds);
  2825. if (!bounds.isValid()) {
  2826. throw new Error('Bounds are not valid.');
  2827. }
  2828. var target = this._getBoundsCenterZoom(bounds, options);
  2829. return this.setView(target.center, target.zoom, options);
  2830. },
  2831. // @method fitWorld(options?: fitBounds options): this
  2832. // Sets a map view that mostly contains the whole world with the maximum
  2833. // zoom level possible.
  2834. fitWorld: function (options) {
  2835. return this.fitBounds([[-90, -180], [90, 180]], options);
  2836. },
  2837. // @method panTo(latlng: LatLng, options?: Pan options): this
  2838. // Pans the map to a given center.
  2839. panTo: function (center, options) { // (LatLng)
  2840. return this.setView(center, this._zoom, {pan: options});
  2841. },
  2842. // @method panBy(offset: Point, options?: Pan options): this
  2843. // Pans the map by a given number of pixels (animated).
  2844. panBy: function (offset, options) {
  2845. offset = toPoint(offset).round();
  2846. options = options || {};
  2847. if (!offset.x && !offset.y) {
  2848. return this.fire('moveend');
  2849. }
  2850. // If we pan too far, Chrome gets issues with tiles
  2851. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2852. if (options.animate !== true && !this.getSize().contains(offset)) {
  2853. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2854. return this;
  2855. }
  2856. if (!this._panAnim) {
  2857. this._panAnim = new PosAnimation();
  2858. this._panAnim.on({
  2859. 'step': this._onPanTransitionStep,
  2860. 'end': this._onPanTransitionEnd
  2861. }, this);
  2862. }
  2863. // don't fire movestart if animating inertia
  2864. if (!options.noMoveStart) {
  2865. this.fire('movestart');
  2866. }
  2867. // animate pan unless animate: false specified
  2868. if (options.animate !== false) {
  2869. addClass(this._mapPane, 'leaflet-pan-anim');
  2870. var newPos = this._getMapPanePos().subtract(offset).round();
  2871. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2872. } else {
  2873. this._rawPanBy(offset);
  2874. this.fire('move').fire('moveend');
  2875. }
  2876. return this;
  2877. },
  2878. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2879. // Sets the view of the map (geographical center and zoom) performing a smooth
  2880. // pan-zoom animation.
  2881. flyTo: function (targetCenter, targetZoom, options) {
  2882. options = options || {};
  2883. if (options.animate === false || !Browser.any3d) {
  2884. return this.setView(targetCenter, targetZoom, options);
  2885. }
  2886. this._stop();
  2887. var from = this.project(this.getCenter()),
  2888. to = this.project(targetCenter),
  2889. size = this.getSize(),
  2890. startZoom = this._zoom;
  2891. targetCenter = toLatLng(targetCenter);
  2892. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2893. var w0 = Math.max(size.x, size.y),
  2894. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2895. u1 = (to.distanceTo(from)) || 1,
  2896. rho = 1.42,
  2897. rho2 = rho * rho;
  2898. function r(i) {
  2899. var s1 = i ? -1 : 1,
  2900. s2 = i ? w1 : w0,
  2901. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2902. b1 = 2 * s2 * rho2 * u1,
  2903. b = t1 / b1,
  2904. sq = Math.sqrt(b * b + 1) - b;
  2905. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2906. // thus triggering an infinite loop in flyTo
  2907. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2908. return log;
  2909. }
  2910. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2911. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2912. function tanh(n) { return sinh(n) / cosh(n); }
  2913. var r0 = r(0);
  2914. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2915. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2916. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2917. var start = Date.now(),
  2918. S = (r(1) - r0) / rho,
  2919. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2920. function frame() {
  2921. var t = (Date.now() - start) / duration,
  2922. s = easeOut(t) * S;
  2923. if (t <= 1) {
  2924. this._flyToFrame = requestAnimFrame(frame, this);
  2925. this._move(
  2926. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2927. this.getScaleZoom(w0 / w(s), startZoom),
  2928. {flyTo: true});
  2929. } else {
  2930. this
  2931. ._move(targetCenter, targetZoom)
  2932. ._moveEnd(true);
  2933. }
  2934. }
  2935. this._moveStart(true, options.noMoveStart);
  2936. frame.call(this);
  2937. return this;
  2938. },
  2939. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2940. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2941. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2942. flyToBounds: function (bounds, options) {
  2943. var target = this._getBoundsCenterZoom(bounds, options);
  2944. return this.flyTo(target.center, target.zoom, options);
  2945. },
  2946. // @method setMaxBounds(bounds: LatLngBounds): this
  2947. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2948. setMaxBounds: function (bounds) {
  2949. bounds = toLatLngBounds(bounds);
  2950. if (this.listens('moveend', this._panInsideMaxBounds)) {
  2951. this.off('moveend', this._panInsideMaxBounds);
  2952. }
  2953. if (!bounds.isValid()) {
  2954. this.options.maxBounds = null;
  2955. return this;
  2956. }
  2957. this.options.maxBounds = bounds;
  2958. if (this._loaded) {
  2959. this._panInsideMaxBounds();
  2960. }
  2961. return this.on('moveend', this._panInsideMaxBounds);
  2962. },
  2963. // @method setMinZoom(zoom: Number): this
  2964. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2965. setMinZoom: function (zoom) {
  2966. var oldZoom = this.options.minZoom;
  2967. this.options.minZoom = zoom;
  2968. if (this._loaded && oldZoom !== zoom) {
  2969. this.fire('zoomlevelschange');
  2970. if (this.getZoom() < this.options.minZoom) {
  2971. return this.setZoom(zoom);
  2972. }
  2973. }
  2974. return this;
  2975. },
  2976. // @method setMaxZoom(zoom: Number): this
  2977. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2978. setMaxZoom: function (zoom) {
  2979. var oldZoom = this.options.maxZoom;
  2980. this.options.maxZoom = zoom;
  2981. if (this._loaded && oldZoom !== zoom) {
  2982. this.fire('zoomlevelschange');
  2983. if (this.getZoom() > this.options.maxZoom) {
  2984. return this.setZoom(zoom);
  2985. }
  2986. }
  2987. return this;
  2988. },
  2989. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2990. // 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.
  2991. panInsideBounds: function (bounds, options) {
  2992. this._enforcingBounds = true;
  2993. var center = this.getCenter(),
  2994. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2995. if (!center.equals(newCenter)) {
  2996. this.panTo(newCenter, options);
  2997. }
  2998. this._enforcingBounds = false;
  2999. return this;
  3000. },
  3001. // @method panInside(latlng: LatLng, options?: padding options): this
  3002. // Pans the map the minimum amount to make the `latlng` visible. Use
  3003. // padding options to fit the display to more restricted bounds.
  3004. // If `latlng` is already within the (optionally padded) display bounds,
  3005. // the map will not be panned.
  3006. panInside: function (latlng, options) {
  3007. options = options || {};
  3008. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  3009. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  3010. pixelCenter = this.project(this.getCenter()),
  3011. pixelPoint = this.project(latlng),
  3012. pixelBounds = this.getPixelBounds(),
  3013. paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]),
  3014. paddedSize = paddedBounds.getSize();
  3015. if (!paddedBounds.contains(pixelPoint)) {
  3016. this._enforcingBounds = true;
  3017. var centerOffset = pixelPoint.subtract(paddedBounds.getCenter());
  3018. var offset = paddedBounds.extend(pixelPoint).getSize().subtract(paddedSize);
  3019. pixelCenter.x += centerOffset.x < 0 ? -offset.x : offset.x;
  3020. pixelCenter.y += centerOffset.y < 0 ? -offset.y : offset.y;
  3021. this.panTo(this.unproject(pixelCenter), options);
  3022. this._enforcingBounds = false;
  3023. }
  3024. return this;
  3025. },
  3026. // @method invalidateSize(options: Zoom/pan options): this
  3027. // Checks if the map container size changed and updates the map if so —
  3028. // call it after you've changed the map size dynamically, also animating
  3029. // pan by default. If `options.pan` is `false`, panning will not occur.
  3030. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  3031. // that it doesn't happen often even if the method is called many
  3032. // times in a row.
  3033. // @alternative
  3034. // @method invalidateSize(animate: Boolean): this
  3035. // Checks if the map container size changed and updates the map if so —
  3036. // call it after you've changed the map size dynamically, also animating
  3037. // pan by default.
  3038. invalidateSize: function (options) {
  3039. if (!this._loaded) { return this; }
  3040. options = extend({
  3041. animate: false,
  3042. pan: true
  3043. }, options === true ? {animate: true} : options);
  3044. var oldSize = this.getSize();
  3045. this._sizeChanged = true;
  3046. this._lastCenter = null;
  3047. var newSize = this.getSize(),
  3048. oldCenter = oldSize.divideBy(2).round(),
  3049. newCenter = newSize.divideBy(2).round(),
  3050. offset = oldCenter.subtract(newCenter);
  3051. if (!offset.x && !offset.y) { return this; }
  3052. if (options.animate && options.pan) {
  3053. this.panBy(offset);
  3054. } else {
  3055. if (options.pan) {
  3056. this._rawPanBy(offset);
  3057. }
  3058. this.fire('move');
  3059. if (options.debounceMoveend) {
  3060. clearTimeout(this._sizeTimer);
  3061. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  3062. } else {
  3063. this.fire('moveend');
  3064. }
  3065. }
  3066. // @section Map state change events
  3067. // @event resize: ResizeEvent
  3068. // Fired when the map is resized.
  3069. return this.fire('resize', {
  3070. oldSize: oldSize,
  3071. newSize: newSize
  3072. });
  3073. },
  3074. // @section Methods for modifying map state
  3075. // @method stop(): this
  3076. // Stops the currently running `panTo` or `flyTo` animation, if any.
  3077. stop: function () {
  3078. this.setZoom(this._limitZoom(this._zoom));
  3079. if (!this.options.zoomSnap) {
  3080. this.fire('viewreset');
  3081. }
  3082. return this._stop();
  3083. },
  3084. // @section Geolocation methods
  3085. // @method locate(options?: Locate options): this
  3086. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  3087. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  3088. // and optionally sets the map view to the user's location with respect to
  3089. // detection accuracy (or to the world view if geolocation failed).
  3090. // Note that, if your page doesn't use HTTPS, this method will fail in
  3091. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  3092. // See `Locate options` for more details.
  3093. locate: function (options) {
  3094. options = this._locateOptions = extend({
  3095. timeout: 10000,
  3096. watch: false
  3097. // setView: false
  3098. // maxZoom: <Number>
  3099. // maximumAge: 0
  3100. // enableHighAccuracy: false
  3101. }, options);
  3102. if (!('geolocation' in navigator)) {
  3103. this._handleGeolocationError({
  3104. code: 0,
  3105. message: 'Geolocation not supported.'
  3106. });
  3107. return this;
  3108. }
  3109. var onResponse = bind(this._handleGeolocationResponse, this),
  3110. onError = bind(this._handleGeolocationError, this);
  3111. if (options.watch) {
  3112. this._locationWatchId =
  3113. navigator.geolocation.watchPosition(onResponse, onError, options);
  3114. } else {
  3115. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  3116. }
  3117. return this;
  3118. },
  3119. // @method stopLocate(): this
  3120. // Stops watching location previously initiated by `map.locate({watch: true})`
  3121. // and aborts resetting the map view if map.locate was called with
  3122. // `{setView: true}`.
  3123. stopLocate: function () {
  3124. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  3125. navigator.geolocation.clearWatch(this._locationWatchId);
  3126. }
  3127. if (this._locateOptions) {
  3128. this._locateOptions.setView = false;
  3129. }
  3130. return this;
  3131. },
  3132. _handleGeolocationError: function (error) {
  3133. if (!this._container._leaflet_id) { return; }
  3134. var c = error.code,
  3135. message = error.message ||
  3136. (c === 1 ? 'permission denied' :
  3137. (c === 2 ? 'position unavailable' : 'timeout'));
  3138. if (this._locateOptions.setView && !this._loaded) {
  3139. this.fitWorld();
  3140. }
  3141. // @section Location events
  3142. // @event locationerror: ErrorEvent
  3143. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  3144. this.fire('locationerror', {
  3145. code: c,
  3146. message: 'Geolocation error: ' + message + '.'
  3147. });
  3148. },
  3149. _handleGeolocationResponse: function (pos) {
  3150. if (!this._container._leaflet_id) { return; }
  3151. var lat = pos.coords.latitude,
  3152. lng = pos.coords.longitude,
  3153. latlng = new LatLng(lat, lng),
  3154. bounds = latlng.toBounds(pos.coords.accuracy * 2),
  3155. options = this._locateOptions;
  3156. if (options.setView) {
  3157. var zoom = this.getBoundsZoom(bounds);
  3158. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  3159. }
  3160. var data = {
  3161. latlng: latlng,
  3162. bounds: bounds,
  3163. timestamp: pos.timestamp
  3164. };
  3165. for (var i in pos.coords) {
  3166. if (typeof pos.coords[i] === 'number') {
  3167. data[i] = pos.coords[i];
  3168. }
  3169. }
  3170. // @event locationfound: LocationEvent
  3171. // Fired when geolocation (using the [`locate`](#map-locate) method)
  3172. // went successfully.
  3173. this.fire('locationfound', data);
  3174. },
  3175. // TODO Appropriate docs section?
  3176. // @section Other Methods
  3177. // @method addHandler(name: String, HandlerClass: Function): this
  3178. // Adds a new `Handler` to the map, given its name and constructor function.
  3179. addHandler: function (name, HandlerClass) {
  3180. if (!HandlerClass) { return this; }
  3181. var handler = this[name] = new HandlerClass(this);
  3182. this._handlers.push(handler);
  3183. if (this.options[name]) {
  3184. handler.enable();
  3185. }
  3186. return this;
  3187. },
  3188. // @method remove(): this
  3189. // Destroys the map and clears all related event listeners.
  3190. remove: function () {
  3191. this._initEvents(true);
  3192. if (this.options.maxBounds) { this.off('moveend', this._panInsideMaxBounds); }
  3193. if (this._containerId !== this._container._leaflet_id) {
  3194. throw new Error('Map container is being reused by another instance');
  3195. }
  3196. try {
  3197. // throws error in IE6-8
  3198. delete this._container._leaflet_id;
  3199. delete this._containerId;
  3200. } catch (e) {
  3201. /*eslint-disable */
  3202. this._container._leaflet_id = undefined;
  3203. /* eslint-enable */
  3204. this._containerId = undefined;
  3205. }
  3206. if (this._locationWatchId !== undefined) {
  3207. this.stopLocate();
  3208. }
  3209. this._stop();
  3210. remove(this._mapPane);
  3211. if (this._clearControlPos) {
  3212. this._clearControlPos();
  3213. }
  3214. if (this._resizeRequest) {
  3215. cancelAnimFrame(this._resizeRequest);
  3216. this._resizeRequest = null;
  3217. }
  3218. this._clearHandlers();
  3219. if (this._loaded) {
  3220. // @section Map state change events
  3221. // @event unload: Event
  3222. // Fired when the map is destroyed with [remove](#map-remove) method.
  3223. this.fire('unload');
  3224. }
  3225. var i;
  3226. for (i in this._layers) {
  3227. this._layers[i].remove();
  3228. }
  3229. for (i in this._panes) {
  3230. remove(this._panes[i]);
  3231. }
  3232. this._layers = [];
  3233. this._panes = [];
  3234. delete this._mapPane;
  3235. delete this._renderer;
  3236. return this;
  3237. },
  3238. // @section Other Methods
  3239. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3240. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3241. // then returns it. The pane is created as a child of `container`, or
  3242. // as a child of the main map pane if not set.
  3243. createPane: function (name, container) {
  3244. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3245. pane = create$1('div', className, container || this._mapPane);
  3246. if (name) {
  3247. this._panes[name] = pane;
  3248. }
  3249. return pane;
  3250. },
  3251. // @section Methods for Getting Map State
  3252. // @method getCenter(): LatLng
  3253. // Returns the geographical center of the map view
  3254. getCenter: function () {
  3255. this._checkIfLoaded();
  3256. if (this._lastCenter && !this._moved()) {
  3257. return this._lastCenter.clone();
  3258. }
  3259. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3260. },
  3261. // @method getZoom(): Number
  3262. // Returns the current zoom level of the map view
  3263. getZoom: function () {
  3264. return this._zoom;
  3265. },
  3266. // @method getBounds(): LatLngBounds
  3267. // Returns the geographical bounds visible in the current map view
  3268. getBounds: function () {
  3269. var bounds = this.getPixelBounds(),
  3270. sw = this.unproject(bounds.getBottomLeft()),
  3271. ne = this.unproject(bounds.getTopRight());
  3272. return new LatLngBounds(sw, ne);
  3273. },
  3274. // @method getMinZoom(): Number
  3275. // 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.
  3276. getMinZoom: function () {
  3277. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3278. },
  3279. // @method getMaxZoom(): Number
  3280. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3281. getMaxZoom: function () {
  3282. return this.options.maxZoom === undefined ?
  3283. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3284. this.options.maxZoom;
  3285. },
  3286. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
  3287. // Returns the maximum zoom level on which the given bounds fit to the map
  3288. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3289. // instead returns the minimum zoom level on which the map view fits into
  3290. // the given bounds in its entirety.
  3291. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3292. bounds = toLatLngBounds(bounds);
  3293. padding = toPoint(padding || [0, 0]);
  3294. var zoom = this.getZoom() || 0,
  3295. min = this.getMinZoom(),
  3296. max = this.getMaxZoom(),
  3297. nw = bounds.getNorthWest(),
  3298. se = bounds.getSouthEast(),
  3299. size = this.getSize().subtract(padding),
  3300. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3301. snap = Browser.any3d ? this.options.zoomSnap : 1,
  3302. scalex = size.x / boundsSize.x,
  3303. scaley = size.y / boundsSize.y,
  3304. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3305. zoom = this.getScaleZoom(scale, zoom);
  3306. if (snap) {
  3307. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3308. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3309. }
  3310. return Math.max(min, Math.min(max, zoom));
  3311. },
  3312. // @method getSize(): Point
  3313. // Returns the current size of the map container (in pixels).
  3314. getSize: function () {
  3315. if (!this._size || this._sizeChanged) {
  3316. this._size = new Point(
  3317. this._container.clientWidth || 0,
  3318. this._container.clientHeight || 0);
  3319. this._sizeChanged = false;
  3320. }
  3321. return this._size.clone();
  3322. },
  3323. // @method getPixelBounds(): Bounds
  3324. // Returns the bounds of the current map view in projected pixel
  3325. // coordinates (sometimes useful in layer and overlay implementations).
  3326. getPixelBounds: function (center, zoom) {
  3327. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3328. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3329. },
  3330. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3331. // the map pane? "left point of the map layer" can be confusing, specially
  3332. // since there can be negative offsets.
  3333. // @method getPixelOrigin(): Point
  3334. // Returns the projected pixel coordinates of the top left point of
  3335. // the map layer (useful in custom layer and overlay implementations).
  3336. getPixelOrigin: function () {
  3337. this._checkIfLoaded();
  3338. return this._pixelOrigin;
  3339. },
  3340. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3341. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3342. // If `zoom` is omitted, the map's current zoom level is used.
  3343. getPixelWorldBounds: function (zoom) {
  3344. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3345. },
  3346. // @section Other Methods
  3347. // @method getPane(pane: String|HTMLElement): HTMLElement
  3348. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3349. getPane: function (pane) {
  3350. return typeof pane === 'string' ? this._panes[pane] : pane;
  3351. },
  3352. // @method getPanes(): Object
  3353. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3354. // the panes as values.
  3355. getPanes: function () {
  3356. return this._panes;
  3357. },
  3358. // @method getContainer: HTMLElement
  3359. // Returns the HTML element that contains the map.
  3360. getContainer: function () {
  3361. return this._container;
  3362. },
  3363. // @section Conversion Methods
  3364. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3365. // Returns the scale factor to be applied to a map transition from zoom level
  3366. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3367. getZoomScale: function (toZoom, fromZoom) {
  3368. // TODO replace with universal implementation after refactoring projections
  3369. var crs = this.options.crs;
  3370. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3371. return crs.scale(toZoom) / crs.scale(fromZoom);
  3372. },
  3373. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3374. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3375. // level and everything is scaled by a factor of `scale`. Inverse of
  3376. // [`getZoomScale`](#map-getZoomScale).
  3377. getScaleZoom: function (scale, fromZoom) {
  3378. var crs = this.options.crs;
  3379. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3380. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3381. return isNaN(zoom) ? Infinity : zoom;
  3382. },
  3383. // @method project(latlng: LatLng, zoom: Number): Point
  3384. // Projects a geographical coordinate `LatLng` according to the projection
  3385. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3386. // `Transformation`. The result is pixel coordinate relative to
  3387. // the CRS origin.
  3388. project: function (latlng, zoom) {
  3389. zoom = zoom === undefined ? this._zoom : zoom;
  3390. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3391. },
  3392. // @method unproject(point: Point, zoom: Number): LatLng
  3393. // Inverse of [`project`](#map-project).
  3394. unproject: function (point, zoom) {
  3395. zoom = zoom === undefined ? this._zoom : zoom;
  3396. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3397. },
  3398. // @method layerPointToLatLng(point: Point): LatLng
  3399. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3400. // returns the corresponding geographical coordinate (for the current zoom level).
  3401. layerPointToLatLng: function (point) {
  3402. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3403. return this.unproject(projectedPoint);
  3404. },
  3405. // @method latLngToLayerPoint(latlng: LatLng): Point
  3406. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3407. // relative to the [origin pixel](#map-getpixelorigin).
  3408. latLngToLayerPoint: function (latlng) {
  3409. var projectedPoint = this.project(toLatLng(latlng))._round();
  3410. return projectedPoint._subtract(this.getPixelOrigin());
  3411. },
  3412. // @method wrapLatLng(latlng: LatLng): LatLng
  3413. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3414. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3415. // CRS's bounds.
  3416. // By default this means longitude is wrapped around the dateline so its
  3417. // value is between -180 and +180 degrees.
  3418. wrapLatLng: function (latlng) {
  3419. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3420. },
  3421. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3422. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3423. // its center is within the CRS's bounds.
  3424. // By default this means the center longitude is wrapped around the dateline so its
  3425. // value is between -180 and +180 degrees, and the majority of the bounds
  3426. // overlaps the CRS's bounds.
  3427. wrapLatLngBounds: function (latlng) {
  3428. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3429. },
  3430. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3431. // Returns the distance between two geographical coordinates according to
  3432. // the map's CRS. By default this measures distance in meters.
  3433. distance: function (latlng1, latlng2) {
  3434. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3435. },
  3436. // @method containerPointToLayerPoint(point: Point): Point
  3437. // Given a pixel coordinate relative to the map container, returns the corresponding
  3438. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3439. containerPointToLayerPoint: function (point) { // (Point)
  3440. return toPoint(point).subtract(this._getMapPanePos());
  3441. },
  3442. // @method layerPointToContainerPoint(point: Point): Point
  3443. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3444. // returns the corresponding pixel coordinate relative to the map container.
  3445. layerPointToContainerPoint: function (point) { // (Point)
  3446. return toPoint(point).add(this._getMapPanePos());
  3447. },
  3448. // @method containerPointToLatLng(point: Point): LatLng
  3449. // Given a pixel coordinate relative to the map container, returns
  3450. // the corresponding geographical coordinate (for the current zoom level).
  3451. containerPointToLatLng: function (point) {
  3452. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3453. return this.layerPointToLatLng(layerPoint);
  3454. },
  3455. // @method latLngToContainerPoint(latlng: LatLng): Point
  3456. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3457. // relative to the map container.
  3458. latLngToContainerPoint: function (latlng) {
  3459. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3460. },
  3461. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3462. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3463. // map container where the event took place.
  3464. mouseEventToContainerPoint: function (e) {
  3465. return getMousePosition(e, this._container);
  3466. },
  3467. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3468. // Given a MouseEvent object, returns the pixel coordinate relative to
  3469. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3470. mouseEventToLayerPoint: function (e) {
  3471. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3472. },
  3473. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3474. // Given a MouseEvent object, returns geographical coordinate where the
  3475. // event took place.
  3476. mouseEventToLatLng: function (e) { // (MouseEvent)
  3477. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3478. },
  3479. // map initialization methods
  3480. _initContainer: function (id) {
  3481. var container = this._container = get(id);
  3482. if (!container) {
  3483. throw new Error('Map container not found.');
  3484. } else if (container._leaflet_id) {
  3485. throw new Error('Map container is already initialized.');
  3486. }
  3487. on(container, 'scroll', this._onScroll, this);
  3488. this._containerId = stamp(container);
  3489. },
  3490. _initLayout: function () {
  3491. var container = this._container;
  3492. this._fadeAnimated = this.options.fadeAnimation && Browser.any3d;
  3493. addClass(container, 'leaflet-container' +
  3494. (Browser.touch ? ' leaflet-touch' : '') +
  3495. (Browser.retina ? ' leaflet-retina' : '') +
  3496. (Browser.ielt9 ? ' leaflet-oldie' : '') +
  3497. (Browser.safari ? ' leaflet-safari' : '') +
  3498. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3499. var position = getStyle(container, 'position');
  3500. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed' && position !== 'sticky') {
  3501. container.style.position = 'relative';
  3502. }
  3503. this._initPanes();
  3504. if (this._initControlPos) {
  3505. this._initControlPos();
  3506. }
  3507. },
  3508. _initPanes: function () {
  3509. var panes = this._panes = {};
  3510. this._paneRenderers = {};
  3511. // @section
  3512. //
  3513. // Panes are DOM elements used to control the ordering of layers on the map. You
  3514. // can access panes with [`map.getPane`](#map-getpane) or
  3515. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3516. // [`map.createPane`](#map-createpane) method.
  3517. //
  3518. // Every map has the following default panes that differ only in zIndex.
  3519. //
  3520. // @pane mapPane: HTMLElement = 'auto'
  3521. // Pane that contains all other map panes
  3522. this._mapPane = this.createPane('mapPane', this._container);
  3523. setPosition(this._mapPane, new Point(0, 0));
  3524. // @pane tilePane: HTMLElement = 200
  3525. // Pane for `GridLayer`s and `TileLayer`s
  3526. this.createPane('tilePane');
  3527. // @pane overlayPane: HTMLElement = 400
  3528. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  3529. this.createPane('overlayPane');
  3530. // @pane shadowPane: HTMLElement = 500
  3531. // Pane for overlay shadows (e.g. `Marker` shadows)
  3532. this.createPane('shadowPane');
  3533. // @pane markerPane: HTMLElement = 600
  3534. // Pane for `Icon`s of `Marker`s
  3535. this.createPane('markerPane');
  3536. // @pane tooltipPane: HTMLElement = 650
  3537. // Pane for `Tooltip`s.
  3538. this.createPane('tooltipPane');
  3539. // @pane popupPane: HTMLElement = 700
  3540. // Pane for `Popup`s.
  3541. this.createPane('popupPane');
  3542. if (!this.options.markerZoomAnimation) {
  3543. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3544. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3545. }
  3546. },
  3547. // private methods that modify map state
  3548. // @section Map state change events
  3549. _resetView: function (center, zoom, noMoveStart) {
  3550. setPosition(this._mapPane, new Point(0, 0));
  3551. var loading = !this._loaded;
  3552. this._loaded = true;
  3553. zoom = this._limitZoom(zoom);
  3554. this.fire('viewprereset');
  3555. var zoomChanged = this._zoom !== zoom;
  3556. this
  3557. ._moveStart(zoomChanged, noMoveStart)
  3558. ._move(center, zoom)
  3559. ._moveEnd(zoomChanged);
  3560. // @event viewreset: Event
  3561. // Fired when the map needs to redraw its content (this usually happens
  3562. // on map zoom or load). Very useful for creating custom overlays.
  3563. this.fire('viewreset');
  3564. // @event load: Event
  3565. // Fired when the map is initialized (when its center and zoom are set
  3566. // for the first time).
  3567. if (loading) {
  3568. this.fire('load');
  3569. }
  3570. },
  3571. _moveStart: function (zoomChanged, noMoveStart) {
  3572. // @event zoomstart: Event
  3573. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3574. // @event movestart: Event
  3575. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3576. if (zoomChanged) {
  3577. this.fire('zoomstart');
  3578. }
  3579. if (!noMoveStart) {
  3580. this.fire('movestart');
  3581. }
  3582. return this;
  3583. },
  3584. _move: function (center, zoom, data, supressEvent) {
  3585. if (zoom === undefined) {
  3586. zoom = this._zoom;
  3587. }
  3588. var zoomChanged = this._zoom !== zoom;
  3589. this._zoom = zoom;
  3590. this._lastCenter = center;
  3591. this._pixelOrigin = this._getNewPixelOrigin(center);
  3592. if (!supressEvent) {
  3593. // @event zoom: Event
  3594. // Fired repeatedly during any change in zoom level,
  3595. // including zoom and fly animations.
  3596. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3597. this.fire('zoom', data);
  3598. }
  3599. // @event move: Event
  3600. // Fired repeatedly during any movement of the map,
  3601. // including pan and fly animations.
  3602. this.fire('move', data);
  3603. } else if (data && data.pinch) { // Always fire 'zoom' if pinching because #3530
  3604. this.fire('zoom', data);
  3605. }
  3606. return this;
  3607. },
  3608. _moveEnd: function (zoomChanged) {
  3609. // @event zoomend: Event
  3610. // Fired when the map zoom changed, after any animations.
  3611. if (zoomChanged) {
  3612. this.fire('zoomend');
  3613. }
  3614. // @event moveend: Event
  3615. // Fired when the center of the map stops changing
  3616. // (e.g. user stopped dragging the map or after non-centered zoom).
  3617. return this.fire('moveend');
  3618. },
  3619. _stop: function () {
  3620. cancelAnimFrame(this._flyToFrame);
  3621. if (this._panAnim) {
  3622. this._panAnim.stop();
  3623. }
  3624. return this;
  3625. },
  3626. _rawPanBy: function (offset) {
  3627. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3628. },
  3629. _getZoomSpan: function () {
  3630. return this.getMaxZoom() - this.getMinZoom();
  3631. },
  3632. _panInsideMaxBounds: function () {
  3633. if (!this._enforcingBounds) {
  3634. this.panInsideBounds(this.options.maxBounds);
  3635. }
  3636. },
  3637. _checkIfLoaded: function () {
  3638. if (!this._loaded) {
  3639. throw new Error('Set map center and zoom first.');
  3640. }
  3641. },
  3642. // DOM event handling
  3643. // @section Interaction events
  3644. _initEvents: function (remove) {
  3645. this._targets = {};
  3646. this._targets[stamp(this._container)] = this;
  3647. var onOff = remove ? off : on;
  3648. // @event click: MouseEvent
  3649. // Fired when the user clicks (or taps) the map.
  3650. // @event dblclick: MouseEvent
  3651. // Fired when the user double-clicks (or double-taps) the map.
  3652. // @event mousedown: MouseEvent
  3653. // Fired when the user pushes the mouse button on the map.
  3654. // @event mouseup: MouseEvent
  3655. // Fired when the user releases the mouse button on the map.
  3656. // @event mouseover: MouseEvent
  3657. // Fired when the mouse enters the map.
  3658. // @event mouseout: MouseEvent
  3659. // Fired when the mouse leaves the map.
  3660. // @event mousemove: MouseEvent
  3661. // Fired while the mouse moves over the map.
  3662. // @event contextmenu: MouseEvent
  3663. // Fired when the user pushes the right mouse button on the map, prevents
  3664. // default browser context menu from showing if there are listeners on
  3665. // this event. Also fired on mobile when the user holds a single touch
  3666. // for a second (also called long press).
  3667. // @event keypress: KeyboardEvent
  3668. // Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
  3669. // @event keydown: KeyboardEvent
  3670. // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
  3671. // the `keydown` event is fired for keys that produce a character value and for keys
  3672. // that do not produce a character value.
  3673. // @event keyup: KeyboardEvent
  3674. // Fired when the user releases a key from the keyboard while the map is focused.
  3675. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3676. 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
  3677. if (this.options.trackResize) {
  3678. onOff(window, 'resize', this._onResize, this);
  3679. }
  3680. if (Browser.any3d && this.options.transform3DLimit) {
  3681. (remove ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3682. }
  3683. },
  3684. _onResize: function () {
  3685. cancelAnimFrame(this._resizeRequest);
  3686. this._resizeRequest = requestAnimFrame(
  3687. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3688. },
  3689. _onScroll: function () {
  3690. this._container.scrollTop = 0;
  3691. this._container.scrollLeft = 0;
  3692. },
  3693. _onMoveEnd: function () {
  3694. var pos = this._getMapPanePos();
  3695. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3696. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3697. // a pixel offset on very high values, see: https://jsfiddle.net/dg6r5hhb/
  3698. this._resetView(this.getCenter(), this.getZoom());
  3699. }
  3700. },
  3701. _findEventTargets: function (e, type) {
  3702. var targets = [],
  3703. target,
  3704. isHover = type === 'mouseout' || type === 'mouseover',
  3705. src = e.target || e.srcElement,
  3706. dragging = false;
  3707. while (src) {
  3708. target = this._targets[stamp(src)];
  3709. if (target && (type === 'click' || type === 'preclick') && this._draggableMoved(target)) {
  3710. // Prevent firing click after you just dragged an object.
  3711. dragging = true;
  3712. break;
  3713. }
  3714. if (target && target.listens(type, true)) {
  3715. if (isHover && !isExternalTarget(src, e)) { break; }
  3716. targets.push(target);
  3717. if (isHover) { break; }
  3718. }
  3719. if (src === this._container) { break; }
  3720. src = src.parentNode;
  3721. }
  3722. if (!targets.length && !dragging && !isHover && this.listens(type, true)) {
  3723. targets = [this];
  3724. }
  3725. return targets;
  3726. },
  3727. _isClickDisabled: function (el) {
  3728. while (el && el !== this._container) {
  3729. if (el['_leaflet_disable_click']) { return true; }
  3730. el = el.parentNode;
  3731. }
  3732. },
  3733. _handleDOMEvent: function (e) {
  3734. var el = (e.target || e.srcElement);
  3735. if (!this._loaded || el['_leaflet_disable_events'] || e.type === 'click' && this._isClickDisabled(el)) {
  3736. return;
  3737. }
  3738. var type = e.type;
  3739. if (type === 'mousedown') {
  3740. // prevents outline when clicking on keyboard-focusable element
  3741. preventOutline(el);
  3742. }
  3743. this._fireDOMEvent(e, type);
  3744. },
  3745. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3746. _fireDOMEvent: function (e, type, canvasTargets) {
  3747. if (e.type === 'click') {
  3748. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3749. // @event preclick: MouseEvent
  3750. // Fired before mouse click on the map (sometimes useful when you
  3751. // want something to happen on click before any existing click
  3752. // handlers start running).
  3753. var synth = extend({}, e);
  3754. synth.type = 'preclick';
  3755. this._fireDOMEvent(synth, synth.type, canvasTargets);
  3756. }
  3757. // Find the layer the event is propagating from and its parents.
  3758. var targets = this._findEventTargets(e, type);
  3759. if (canvasTargets) {
  3760. var filtered = []; // pick only targets with listeners
  3761. for (var i = 0; i < canvasTargets.length; i++) {
  3762. if (canvasTargets[i].listens(type, true)) {
  3763. filtered.push(canvasTargets[i]);
  3764. }
  3765. }
  3766. targets = filtered.concat(targets);
  3767. }
  3768. if (!targets.length) { return; }
  3769. if (type === 'contextmenu') {
  3770. preventDefault(e);
  3771. }
  3772. var target = targets[0];
  3773. var data = {
  3774. originalEvent: e
  3775. };
  3776. if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
  3777. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  3778. data.containerPoint = isMarker ?
  3779. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3780. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3781. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3782. }
  3783. for (i = 0; i < targets.length; i++) {
  3784. targets[i].fire(type, data, true);
  3785. if (data.originalEvent._stopped ||
  3786. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3787. }
  3788. },
  3789. _draggableMoved: function (obj) {
  3790. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3791. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3792. },
  3793. _clearHandlers: function () {
  3794. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3795. this._handlers[i].disable();
  3796. }
  3797. },
  3798. // @section Other Methods
  3799. // @method whenReady(fn: Function, context?: Object): this
  3800. // Runs the given function `fn` when the map gets initialized with
  3801. // a view (center and zoom) and at least one layer, or immediately
  3802. // if it's already initialized, optionally passing a function context.
  3803. whenReady: function (callback, context) {
  3804. if (this._loaded) {
  3805. callback.call(context || this, {target: this});
  3806. } else {
  3807. this.on('load', callback, context);
  3808. }
  3809. return this;
  3810. },
  3811. // private methods for getting map state
  3812. _getMapPanePos: function () {
  3813. return getPosition(this._mapPane) || new Point(0, 0);
  3814. },
  3815. _moved: function () {
  3816. var pos = this._getMapPanePos();
  3817. return pos && !pos.equals([0, 0]);
  3818. },
  3819. _getTopLeftPoint: function (center, zoom) {
  3820. var pixelOrigin = center && zoom !== undefined ?
  3821. this._getNewPixelOrigin(center, zoom) :
  3822. this.getPixelOrigin();
  3823. return pixelOrigin.subtract(this._getMapPanePos());
  3824. },
  3825. _getNewPixelOrigin: function (center, zoom) {
  3826. var viewHalf = this.getSize()._divideBy(2);
  3827. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3828. },
  3829. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3830. var topLeft = this._getNewPixelOrigin(center, zoom);
  3831. return this.project(latlng, zoom)._subtract(topLeft);
  3832. },
  3833. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3834. var topLeft = this._getNewPixelOrigin(center, zoom);
  3835. return toBounds([
  3836. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3837. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3838. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3839. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3840. ]);
  3841. },
  3842. // layer point of the current center
  3843. _getCenterLayerPoint: function () {
  3844. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3845. },
  3846. // offset of the specified place to the current center in pixels
  3847. _getCenterOffset: function (latlng) {
  3848. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3849. },
  3850. // adjust center for view to get inside bounds
  3851. _limitCenter: function (center, zoom, bounds) {
  3852. if (!bounds) { return center; }
  3853. var centerPoint = this.project(center, zoom),
  3854. viewHalf = this.getSize().divideBy(2),
  3855. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3856. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3857. // If offset is less than a pixel, ignore.
  3858. // This prevents unstable projections from getting into
  3859. // an infinite loop of tiny offsets.
  3860. if (Math.abs(offset.x) <= 1 && Math.abs(offset.y) <= 1) {
  3861. return center;
  3862. }
  3863. return this.unproject(centerPoint.add(offset), zoom);
  3864. },
  3865. // adjust offset for view to get inside bounds
  3866. _limitOffset: function (offset, bounds) {
  3867. if (!bounds) { return offset; }
  3868. var viewBounds = this.getPixelBounds(),
  3869. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3870. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3871. },
  3872. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3873. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3874. var projectedMaxBounds = toBounds(
  3875. this.project(maxBounds.getNorthEast(), zoom),
  3876. this.project(maxBounds.getSouthWest(), zoom)
  3877. ),
  3878. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3879. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3880. dx = this._rebound(minOffset.x, -maxOffset.x),
  3881. dy = this._rebound(minOffset.y, -maxOffset.y);
  3882. return new Point(dx, dy);
  3883. },
  3884. _rebound: function (left, right) {
  3885. return left + right > 0 ?
  3886. Math.round(left - right) / 2 :
  3887. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3888. },
  3889. _limitZoom: function (zoom) {
  3890. var min = this.getMinZoom(),
  3891. max = this.getMaxZoom(),
  3892. snap = Browser.any3d ? this.options.zoomSnap : 1;
  3893. if (snap) {
  3894. zoom = Math.round(zoom / snap) * snap;
  3895. }
  3896. return Math.max(min, Math.min(max, zoom));
  3897. },
  3898. _onPanTransitionStep: function () {
  3899. this.fire('move');
  3900. },
  3901. _onPanTransitionEnd: function () {
  3902. removeClass(this._mapPane, 'leaflet-pan-anim');
  3903. this.fire('moveend');
  3904. },
  3905. _tryAnimatedPan: function (center, options) {
  3906. // difference between the new and current centers in pixels
  3907. var offset = this._getCenterOffset(center)._trunc();
  3908. // don't animate too far unless animate: true specified in options
  3909. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3910. this.panBy(offset, options);
  3911. return true;
  3912. },
  3913. _createAnimProxy: function () {
  3914. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3915. this._panes.mapPane.appendChild(proxy);
  3916. this.on('zoomanim', function (e) {
  3917. var prop = TRANSFORM,
  3918. transform = this._proxy.style[prop];
  3919. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3920. // workaround for case when transform is the same and so transitionend event is not fired
  3921. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3922. this._onZoomTransitionEnd();
  3923. }
  3924. }, this);
  3925. this.on('load moveend', this._animMoveEnd, this);
  3926. this._on('unload', this._destroyAnimProxy, this);
  3927. },
  3928. _destroyAnimProxy: function () {
  3929. remove(this._proxy);
  3930. this.off('load moveend', this._animMoveEnd, this);
  3931. delete this._proxy;
  3932. },
  3933. _animMoveEnd: function () {
  3934. var c = this.getCenter(),
  3935. z = this.getZoom();
  3936. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3937. },
  3938. _catchTransitionEnd: function (e) {
  3939. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3940. this._onZoomTransitionEnd();
  3941. }
  3942. },
  3943. _nothingToAnimate: function () {
  3944. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3945. },
  3946. _tryAnimatedZoom: function (center, zoom, options) {
  3947. if (this._animatingZoom) { return true; }
  3948. options = options || {};
  3949. // don't animate if disabled, not supported or zoom difference is too large
  3950. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3951. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3952. // offset is the pixel coords of the zoom origin relative to the current center
  3953. var scale = this.getZoomScale(zoom),
  3954. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3955. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3956. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3957. requestAnimFrame(function () {
  3958. this
  3959. ._moveStart(true, false)
  3960. ._animateZoom(center, zoom, true);
  3961. }, this);
  3962. return true;
  3963. },
  3964. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3965. if (!this._mapPane) { return; }
  3966. if (startAnim) {
  3967. this._animatingZoom = true;
  3968. // remember what center/zoom to set after animation
  3969. this._animateToCenter = center;
  3970. this._animateToZoom = zoom;
  3971. addClass(this._mapPane, 'leaflet-zoom-anim');
  3972. }
  3973. // @section Other Events
  3974. // @event zoomanim: ZoomAnimEvent
  3975. // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
  3976. this.fire('zoomanim', {
  3977. center: center,
  3978. zoom: zoom,
  3979. noUpdate: noUpdate
  3980. });
  3981. if (!this._tempFireZoomEvent) {
  3982. this._tempFireZoomEvent = this._zoom !== this._animateToZoom;
  3983. }
  3984. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  3985. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3986. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3987. },
  3988. _onZoomTransitionEnd: function () {
  3989. if (!this._animatingZoom) { return; }
  3990. if (this._mapPane) {
  3991. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3992. }
  3993. this._animatingZoom = false;
  3994. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  3995. if (this._tempFireZoomEvent) {
  3996. this.fire('zoom');
  3997. }
  3998. delete this._tempFireZoomEvent;
  3999. this.fire('move');
  4000. this._moveEnd(true);
  4001. }
  4002. });
  4003. // @section
  4004. // @factory L.map(id: String, options?: Map options)
  4005. // Instantiates a map object given the DOM ID of a `<div>` element
  4006. // and optionally an object literal with `Map options`.
  4007. //
  4008. // @alternative
  4009. // @factory L.map(el: HTMLElement, options?: Map options)
  4010. // Instantiates a map object given an instance of a `<div>` HTML element
  4011. // and optionally an object literal with `Map options`.
  4012. function createMap(id, options) {
  4013. return new Map(id, options);
  4014. }
  4015. /*
  4016. * @class Control
  4017. * @aka L.Control
  4018. * @inherits Class
  4019. *
  4020. * L.Control is a base class for implementing map controls. Handles positioning.
  4021. * All other controls extend from this class.
  4022. */
  4023. var Control = Class.extend({
  4024. // @section
  4025. // @aka Control Options
  4026. options: {
  4027. // @option position: String = 'topright'
  4028. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  4029. // `'topright'`, `'bottomleft'` or `'bottomright'`
  4030. position: 'topright'
  4031. },
  4032. initialize: function (options) {
  4033. setOptions(this, options);
  4034. },
  4035. /* @section
  4036. * Classes extending L.Control will inherit the following methods:
  4037. *
  4038. * @method getPosition: string
  4039. * Returns the position of the control.
  4040. */
  4041. getPosition: function () {
  4042. return this.options.position;
  4043. },
  4044. // @method setPosition(position: string): this
  4045. // Sets the position of the control.
  4046. setPosition: function (position) {
  4047. var map = this._map;
  4048. if (map) {
  4049. map.removeControl(this);
  4050. }
  4051. this.options.position = position;
  4052. if (map) {
  4053. map.addControl(this);
  4054. }
  4055. return this;
  4056. },
  4057. // @method getContainer: HTMLElement
  4058. // Returns the HTMLElement that contains the control.
  4059. getContainer: function () {
  4060. return this._container;
  4061. },
  4062. // @method addTo(map: Map): this
  4063. // Adds the control to the given map.
  4064. addTo: function (map) {
  4065. this.remove();
  4066. this._map = map;
  4067. var container = this._container = this.onAdd(map),
  4068. pos = this.getPosition(),
  4069. corner = map._controlCorners[pos];
  4070. addClass(container, 'leaflet-control');
  4071. if (pos.indexOf('bottom') !== -1) {
  4072. corner.insertBefore(container, corner.firstChild);
  4073. } else {
  4074. corner.appendChild(container);
  4075. }
  4076. this._map.on('unload', this.remove, this);
  4077. return this;
  4078. },
  4079. // @method remove: this
  4080. // Removes the control from the map it is currently active on.
  4081. remove: function () {
  4082. if (!this._map) {
  4083. return this;
  4084. }
  4085. remove(this._container);
  4086. if (this.onRemove) {
  4087. this.onRemove(this._map);
  4088. }
  4089. this._map.off('unload', this.remove, this);
  4090. this._map = null;
  4091. return this;
  4092. },
  4093. _refocusOnMap: function (e) {
  4094. // if map exists and event is not a keyboard event
  4095. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  4096. this._map.getContainer().focus();
  4097. }
  4098. }
  4099. });
  4100. var control = function (options) {
  4101. return new Control(options);
  4102. };
  4103. /* @section Extension methods
  4104. * @uninheritable
  4105. *
  4106. * Every control should extend from `L.Control` and (re-)implement the following methods.
  4107. *
  4108. * @method onAdd(map: Map): HTMLElement
  4109. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  4110. *
  4111. * @method onRemove(map: Map)
  4112. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  4113. */
  4114. /* @namespace Map
  4115. * @section Methods for Layers and Controls
  4116. */
  4117. Map.include({
  4118. // @method addControl(control: Control): this
  4119. // Adds the given control to the map
  4120. addControl: function (control) {
  4121. control.addTo(this);
  4122. return this;
  4123. },
  4124. // @method removeControl(control: Control): this
  4125. // Removes the given control from the map
  4126. removeControl: function (control) {
  4127. control.remove();
  4128. return this;
  4129. },
  4130. _initControlPos: function () {
  4131. var corners = this._controlCorners = {},
  4132. l = 'leaflet-',
  4133. container = this._controlContainer =
  4134. create$1('div', l + 'control-container', this._container);
  4135. function createCorner(vSide, hSide) {
  4136. var className = l + vSide + ' ' + l + hSide;
  4137. corners[vSide + hSide] = create$1('div', className, container);
  4138. }
  4139. createCorner('top', 'left');
  4140. createCorner('top', 'right');
  4141. createCorner('bottom', 'left');
  4142. createCorner('bottom', 'right');
  4143. },
  4144. _clearControlPos: function () {
  4145. for (var i in this._controlCorners) {
  4146. remove(this._controlCorners[i]);
  4147. }
  4148. remove(this._controlContainer);
  4149. delete this._controlCorners;
  4150. delete this._controlContainer;
  4151. }
  4152. });
  4153. /*
  4154. * @class Control.Layers
  4155. * @aka L.Control.Layers
  4156. * @inherits Control
  4157. *
  4158. * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](https://leafletjs.com/examples/layers-control/)). Extends `Control`.
  4159. *
  4160. * @example
  4161. *
  4162. * ```js
  4163. * var baseLayers = {
  4164. * "Mapbox": mapbox,
  4165. * "OpenStreetMap": osm
  4166. * };
  4167. *
  4168. * var overlays = {
  4169. * "Marker": marker,
  4170. * "Roads": roadsLayer
  4171. * };
  4172. *
  4173. * L.control.layers(baseLayers, overlays).addTo(map);
  4174. * ```
  4175. *
  4176. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  4177. *
  4178. * ```js
  4179. * {
  4180. * "<someName1>": layer1,
  4181. * "<someName2>": layer2
  4182. * }
  4183. * ```
  4184. *
  4185. * The layer names can contain HTML, which allows you to add additional styling to the items:
  4186. *
  4187. * ```js
  4188. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  4189. * ```
  4190. */
  4191. var Layers = Control.extend({
  4192. // @section
  4193. // @aka Control.Layers options
  4194. options: {
  4195. // @option collapsed: Boolean = true
  4196. // If `true`, the control will be collapsed into an icon and expanded on mouse hover, touch, or keyboard activation.
  4197. collapsed: true,
  4198. position: 'topright',
  4199. // @option autoZIndex: Boolean = true
  4200. // 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.
  4201. autoZIndex: true,
  4202. // @option hideSingleBase: Boolean = false
  4203. // If `true`, the base layers in the control will be hidden when there is only one.
  4204. hideSingleBase: false,
  4205. // @option sortLayers: Boolean = false
  4206. // Whether to sort the layers. When `false`, layers will keep the order
  4207. // in which they were added to the control.
  4208. sortLayers: false,
  4209. // @option sortFunction: Function = *
  4210. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  4211. // that will be used for sorting the layers, when `sortLayers` is `true`.
  4212. // The function receives both the `L.Layer` instances and their names, as in
  4213. // `sortFunction(layerA, layerB, nameA, nameB)`.
  4214. // By default, it sorts layers alphabetically by their name.
  4215. sortFunction: function (layerA, layerB, nameA, nameB) {
  4216. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  4217. }
  4218. },
  4219. initialize: function (baseLayers, overlays, options) {
  4220. setOptions(this, options);
  4221. this._layerControlInputs = [];
  4222. this._layers = [];
  4223. this._lastZIndex = 0;
  4224. this._handlingClick = false;
  4225. for (var i in baseLayers) {
  4226. this._addLayer(baseLayers[i], i);
  4227. }
  4228. for (i in overlays) {
  4229. this._addLayer(overlays[i], i, true);
  4230. }
  4231. },
  4232. onAdd: function (map) {
  4233. this._initLayout();
  4234. this._update();
  4235. this._map = map;
  4236. map.on('zoomend', this._checkDisabledLayers, this);
  4237. for (var i = 0; i < this._layers.length; i++) {
  4238. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4239. }
  4240. return this._container;
  4241. },
  4242. addTo: function (map) {
  4243. Control.prototype.addTo.call(this, map);
  4244. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4245. return this._expandIfNotCollapsed();
  4246. },
  4247. onRemove: function () {
  4248. this._map.off('zoomend', this._checkDisabledLayers, this);
  4249. for (var i = 0; i < this._layers.length; i++) {
  4250. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4251. }
  4252. },
  4253. // @method addBaseLayer(layer: Layer, name: String): this
  4254. // Adds a base layer (radio button entry) with the given name to the control.
  4255. addBaseLayer: function (layer, name) {
  4256. this._addLayer(layer, name);
  4257. return (this._map) ? this._update() : this;
  4258. },
  4259. // @method addOverlay(layer: Layer, name: String): this
  4260. // Adds an overlay (checkbox entry) with the given name to the control.
  4261. addOverlay: function (layer, name) {
  4262. this._addLayer(layer, name, true);
  4263. return (this._map) ? this._update() : this;
  4264. },
  4265. // @method removeLayer(layer: Layer): this
  4266. // Remove the given layer from the control.
  4267. removeLayer: function (layer) {
  4268. layer.off('add remove', this._onLayerChange, this);
  4269. var obj = this._getLayer(stamp(layer));
  4270. if (obj) {
  4271. this._layers.splice(this._layers.indexOf(obj), 1);
  4272. }
  4273. return (this._map) ? this._update() : this;
  4274. },
  4275. // @method expand(): this
  4276. // Expand the control container if collapsed.
  4277. expand: function () {
  4278. addClass(this._container, 'leaflet-control-layers-expanded');
  4279. this._section.style.height = null;
  4280. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4281. if (acceptableHeight < this._section.clientHeight) {
  4282. addClass(this._section, 'leaflet-control-layers-scrollbar');
  4283. this._section.style.height = acceptableHeight + 'px';
  4284. } else {
  4285. removeClass(this._section, 'leaflet-control-layers-scrollbar');
  4286. }
  4287. this._checkDisabledLayers();
  4288. return this;
  4289. },
  4290. // @method collapse(): this
  4291. // Collapse the control container if expanded.
  4292. collapse: function () {
  4293. removeClass(this._container, 'leaflet-control-layers-expanded');
  4294. return this;
  4295. },
  4296. _initLayout: function () {
  4297. var className = 'leaflet-control-layers',
  4298. container = this._container = create$1('div', className),
  4299. collapsed = this.options.collapsed;
  4300. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4301. container.setAttribute('aria-haspopup', true);
  4302. disableClickPropagation(container);
  4303. disableScrollPropagation(container);
  4304. var section = this._section = create$1('section', className + '-list');
  4305. if (collapsed) {
  4306. this._map.on('click', this.collapse, this);
  4307. on(container, {
  4308. mouseenter: this._expandSafely,
  4309. mouseleave: this.collapse
  4310. }, this);
  4311. }
  4312. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4313. link.href = '#';
  4314. link.title = 'Layers';
  4315. link.setAttribute('role', 'button');
  4316. on(link, {
  4317. keydown: function (e) {
  4318. if (e.keyCode === 13) {
  4319. this._expandSafely();
  4320. }
  4321. },
  4322. // Certain screen readers intercept the key event and instead send a click event
  4323. click: function (e) {
  4324. preventDefault(e);
  4325. this._expandSafely();
  4326. }
  4327. }, this);
  4328. if (!collapsed) {
  4329. this.expand();
  4330. }
  4331. this._baseLayersList = create$1('div', className + '-base', section);
  4332. this._separator = create$1('div', className + '-separator', section);
  4333. this._overlaysList = create$1('div', className + '-overlays', section);
  4334. container.appendChild(section);
  4335. },
  4336. _getLayer: function (id) {
  4337. for (var i = 0; i < this._layers.length; i++) {
  4338. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4339. return this._layers[i];
  4340. }
  4341. }
  4342. },
  4343. _addLayer: function (layer, name, overlay) {
  4344. if (this._map) {
  4345. layer.on('add remove', this._onLayerChange, this);
  4346. }
  4347. this._layers.push({
  4348. layer: layer,
  4349. name: name,
  4350. overlay: overlay
  4351. });
  4352. if (this.options.sortLayers) {
  4353. this._layers.sort(bind(function (a, b) {
  4354. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4355. }, this));
  4356. }
  4357. if (this.options.autoZIndex && layer.setZIndex) {
  4358. this._lastZIndex++;
  4359. layer.setZIndex(this._lastZIndex);
  4360. }
  4361. this._expandIfNotCollapsed();
  4362. },
  4363. _update: function () {
  4364. if (!this._container) { return this; }
  4365. empty(this._baseLayersList);
  4366. empty(this._overlaysList);
  4367. this._layerControlInputs = [];
  4368. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4369. for (i = 0; i < this._layers.length; i++) {
  4370. obj = this._layers[i];
  4371. this._addItem(obj);
  4372. overlaysPresent = overlaysPresent || obj.overlay;
  4373. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4374. baseLayersCount += !obj.overlay ? 1 : 0;
  4375. }
  4376. // Hide base layers section if there's only one layer.
  4377. if (this.options.hideSingleBase) {
  4378. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4379. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4380. }
  4381. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4382. return this;
  4383. },
  4384. _onLayerChange: function (e) {
  4385. if (!this._handlingClick) {
  4386. this._update();
  4387. }
  4388. var obj = this._getLayer(stamp(e.target));
  4389. // @namespace Map
  4390. // @section Layer events
  4391. // @event baselayerchange: LayersControlEvent
  4392. // Fired when the base layer is changed through the [layers control](#control-layers).
  4393. // @event overlayadd: LayersControlEvent
  4394. // Fired when an overlay is selected through the [layers control](#control-layers).
  4395. // @event overlayremove: LayersControlEvent
  4396. // Fired when an overlay is deselected through the [layers control](#control-layers).
  4397. // @namespace Control.Layers
  4398. var type = obj.overlay ?
  4399. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4400. (e.type === 'add' ? 'baselayerchange' : null);
  4401. if (type) {
  4402. this._map.fire(type, obj);
  4403. }
  4404. },
  4405. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see https://stackoverflow.com/a/119079)
  4406. _createRadioElement: function (name, checked) {
  4407. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4408. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4409. var radioFragment = document.createElement('div');
  4410. radioFragment.innerHTML = radioHtml;
  4411. return radioFragment.firstChild;
  4412. },
  4413. _addItem: function (obj) {
  4414. var label = document.createElement('label'),
  4415. checked = this._map.hasLayer(obj.layer),
  4416. input;
  4417. if (obj.overlay) {
  4418. input = document.createElement('input');
  4419. input.type = 'checkbox';
  4420. input.className = 'leaflet-control-layers-selector';
  4421. input.defaultChecked = checked;
  4422. } else {
  4423. input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);
  4424. }
  4425. this._layerControlInputs.push(input);
  4426. input.layerId = stamp(obj.layer);
  4427. on(input, 'click', this._onInputClick, this);
  4428. var name = document.createElement('span');
  4429. name.innerHTML = ' ' + obj.name;
  4430. // Helps from preventing layer control flicker when checkboxes are disabled
  4431. // https://github.com/Leaflet/Leaflet/issues/2771
  4432. var holder = document.createElement('span');
  4433. label.appendChild(holder);
  4434. holder.appendChild(input);
  4435. holder.appendChild(name);
  4436. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4437. container.appendChild(label);
  4438. this._checkDisabledLayers();
  4439. return label;
  4440. },
  4441. _onInputClick: function () {
  4442. var inputs = this._layerControlInputs,
  4443. input, layer;
  4444. var addedLayers = [],
  4445. removedLayers = [];
  4446. this._handlingClick = true;
  4447. for (var i = inputs.length - 1; i >= 0; i--) {
  4448. input = inputs[i];
  4449. layer = this._getLayer(input.layerId).layer;
  4450. if (input.checked) {
  4451. addedLayers.push(layer);
  4452. } else if (!input.checked) {
  4453. removedLayers.push(layer);
  4454. }
  4455. }
  4456. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4457. for (i = 0; i < removedLayers.length; i++) {
  4458. if (this._map.hasLayer(removedLayers[i])) {
  4459. this._map.removeLayer(removedLayers[i]);
  4460. }
  4461. }
  4462. for (i = 0; i < addedLayers.length; i++) {
  4463. if (!this._map.hasLayer(addedLayers[i])) {
  4464. this._map.addLayer(addedLayers[i]);
  4465. }
  4466. }
  4467. this._handlingClick = false;
  4468. this._refocusOnMap();
  4469. },
  4470. _checkDisabledLayers: function () {
  4471. var inputs = this._layerControlInputs,
  4472. input,
  4473. layer,
  4474. zoom = this._map.getZoom();
  4475. for (var i = inputs.length - 1; i >= 0; i--) {
  4476. input = inputs[i];
  4477. layer = this._getLayer(input.layerId).layer;
  4478. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4479. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4480. }
  4481. },
  4482. _expandIfNotCollapsed: function () {
  4483. if (this._map && !this.options.collapsed) {
  4484. this.expand();
  4485. }
  4486. return this;
  4487. },
  4488. _expandSafely: function () {
  4489. var section = this._section;
  4490. on(section, 'click', preventDefault);
  4491. this.expand();
  4492. setTimeout(function () {
  4493. off(section, 'click', preventDefault);
  4494. });
  4495. }
  4496. });
  4497. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4498. // Creates a layers control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
  4499. var layers = function (baseLayers, overlays, options) {
  4500. return new Layers(baseLayers, overlays, options);
  4501. };
  4502. /*
  4503. * @class Control.Zoom
  4504. * @aka L.Control.Zoom
  4505. * @inherits Control
  4506. *
  4507. * 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`.
  4508. */
  4509. var Zoom = Control.extend({
  4510. // @section
  4511. // @aka Control.Zoom options
  4512. options: {
  4513. position: 'topleft',
  4514. // @option zoomInText: String = '<span aria-hidden="true">+</span>'
  4515. // The text set on the 'zoom in' button.
  4516. zoomInText: '<span aria-hidden="true">+</span>',
  4517. // @option zoomInTitle: String = 'Zoom in'
  4518. // The title set on the 'zoom in' button.
  4519. zoomInTitle: 'Zoom in',
  4520. // @option zoomOutText: String = '<span aria-hidden="true">&#x2212;</span>'
  4521. // The text set on the 'zoom out' button.
  4522. zoomOutText: '<span aria-hidden="true">&#x2212;</span>',
  4523. // @option zoomOutTitle: String = 'Zoom out'
  4524. // The title set on the 'zoom out' button.
  4525. zoomOutTitle: 'Zoom out'
  4526. },
  4527. onAdd: function (map) {
  4528. var zoomName = 'leaflet-control-zoom',
  4529. container = create$1('div', zoomName + ' leaflet-bar'),
  4530. options = this.options;
  4531. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4532. zoomName + '-in', container, this._zoomIn);
  4533. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4534. zoomName + '-out', container, this._zoomOut);
  4535. this._updateDisabled();
  4536. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4537. return container;
  4538. },
  4539. onRemove: function (map) {
  4540. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4541. },
  4542. disable: function () {
  4543. this._disabled = true;
  4544. this._updateDisabled();
  4545. return this;
  4546. },
  4547. enable: function () {
  4548. this._disabled = false;
  4549. this._updateDisabled();
  4550. return this;
  4551. },
  4552. _zoomIn: function (e) {
  4553. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4554. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4555. }
  4556. },
  4557. _zoomOut: function (e) {
  4558. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4559. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4560. }
  4561. },
  4562. _createButton: function (html, title, className, container, fn) {
  4563. var link = create$1('a', className, container);
  4564. link.innerHTML = html;
  4565. link.href = '#';
  4566. link.title = title;
  4567. /*
  4568. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4569. */
  4570. link.setAttribute('role', 'button');
  4571. link.setAttribute('aria-label', title);
  4572. disableClickPropagation(link);
  4573. on(link, 'click', stop);
  4574. on(link, 'click', fn, this);
  4575. on(link, 'click', this._refocusOnMap, this);
  4576. return link;
  4577. },
  4578. _updateDisabled: function () {
  4579. var map = this._map,
  4580. className = 'leaflet-disabled';
  4581. removeClass(this._zoomInButton, className);
  4582. removeClass(this._zoomOutButton, className);
  4583. this._zoomInButton.setAttribute('aria-disabled', 'false');
  4584. this._zoomOutButton.setAttribute('aria-disabled', 'false');
  4585. if (this._disabled || map._zoom === map.getMinZoom()) {
  4586. addClass(this._zoomOutButton, className);
  4587. this._zoomOutButton.setAttribute('aria-disabled', 'true');
  4588. }
  4589. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4590. addClass(this._zoomInButton, className);
  4591. this._zoomInButton.setAttribute('aria-disabled', 'true');
  4592. }
  4593. }
  4594. });
  4595. // @namespace Map
  4596. // @section Control options
  4597. // @option zoomControl: Boolean = true
  4598. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4599. Map.mergeOptions({
  4600. zoomControl: true
  4601. });
  4602. Map.addInitHook(function () {
  4603. if (this.options.zoomControl) {
  4604. // @section Controls
  4605. // @property zoomControl: Control.Zoom
  4606. // The default zoom control (only available if the
  4607. // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
  4608. this.zoomControl = new Zoom();
  4609. this.addControl(this.zoomControl);
  4610. }
  4611. });
  4612. // @namespace Control.Zoom
  4613. // @factory L.control.zoom(options: Control.Zoom options)
  4614. // Creates a zoom control
  4615. var zoom = function (options) {
  4616. return new Zoom(options);
  4617. };
  4618. /*
  4619. * @class Control.Scale
  4620. * @aka L.Control.Scale
  4621. * @inherits Control
  4622. *
  4623. * 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`.
  4624. *
  4625. * @example
  4626. *
  4627. * ```js
  4628. * L.control.scale().addTo(map);
  4629. * ```
  4630. */
  4631. var Scale = Control.extend({
  4632. // @section
  4633. // @aka Control.Scale options
  4634. options: {
  4635. position: 'bottomleft',
  4636. // @option maxWidth: Number = 100
  4637. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4638. maxWidth: 100,
  4639. // @option metric: Boolean = True
  4640. // Whether to show the metric scale line (m/km).
  4641. metric: true,
  4642. // @option imperial: Boolean = True
  4643. // Whether to show the imperial scale line (mi/ft).
  4644. imperial: true
  4645. // @option updateWhenIdle: Boolean = false
  4646. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4647. },
  4648. onAdd: function (map) {
  4649. var className = 'leaflet-control-scale',
  4650. container = create$1('div', className),
  4651. options = this.options;
  4652. this._addScales(options, className + '-line', container);
  4653. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4654. map.whenReady(this._update, this);
  4655. return container;
  4656. },
  4657. onRemove: function (map) {
  4658. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4659. },
  4660. _addScales: function (options, className, container) {
  4661. if (options.metric) {
  4662. this._mScale = create$1('div', className, container);
  4663. }
  4664. if (options.imperial) {
  4665. this._iScale = create$1('div', className, container);
  4666. }
  4667. },
  4668. _update: function () {
  4669. var map = this._map,
  4670. y = map.getSize().y / 2;
  4671. var maxMeters = map.distance(
  4672. map.containerPointToLatLng([0, y]),
  4673. map.containerPointToLatLng([this.options.maxWidth, y]));
  4674. this._updateScales(maxMeters);
  4675. },
  4676. _updateScales: function (maxMeters) {
  4677. if (this.options.metric && maxMeters) {
  4678. this._updateMetric(maxMeters);
  4679. }
  4680. if (this.options.imperial && maxMeters) {
  4681. this._updateImperial(maxMeters);
  4682. }
  4683. },
  4684. _updateMetric: function (maxMeters) {
  4685. var meters = this._getRoundNum(maxMeters),
  4686. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4687. this._updateScale(this._mScale, label, meters / maxMeters);
  4688. },
  4689. _updateImperial: function (maxMeters) {
  4690. var maxFeet = maxMeters * 3.2808399,
  4691. maxMiles, miles, feet;
  4692. if (maxFeet > 5280) {
  4693. maxMiles = maxFeet / 5280;
  4694. miles = this._getRoundNum(maxMiles);
  4695. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4696. } else {
  4697. feet = this._getRoundNum(maxFeet);
  4698. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4699. }
  4700. },
  4701. _updateScale: function (scale, text, ratio) {
  4702. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4703. scale.innerHTML = text;
  4704. },
  4705. _getRoundNum: function (num) {
  4706. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4707. d = num / pow10;
  4708. d = d >= 10 ? 10 :
  4709. d >= 5 ? 5 :
  4710. d >= 3 ? 3 :
  4711. d >= 2 ? 2 : 1;
  4712. return pow10 * d;
  4713. }
  4714. });
  4715. // @factory L.control.scale(options?: Control.Scale options)
  4716. // Creates an scale control with the given options.
  4717. var scale = function (options) {
  4718. return new Scale(options);
  4719. };
  4720. var ukrainianFlag = '<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="12" height="8" viewBox="0 0 12 8" class="leaflet-attribution-flag"><path fill="#4C7BE1" d="M0 0h12v4H0z"/><path fill="#FFD500" d="M0 4h12v3H0z"/><path fill="#E0BC00" d="M0 7h12v1H0z"/></svg>';
  4721. /*
  4722. * @class Control.Attribution
  4723. * @aka L.Control.Attribution
  4724. * @inherits Control
  4725. *
  4726. * 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.
  4727. */
  4728. var Attribution = Control.extend({
  4729. // @section
  4730. // @aka Control.Attribution options
  4731. options: {
  4732. position: 'bottomright',
  4733. // @option prefix: String|false = 'Leaflet'
  4734. // The HTML text shown before the attributions. Pass `false` to disable.
  4735. prefix: '<a href="https://leafletjs.com" title="A JavaScript library for interactive maps">' + (Browser.inlineSvg ? ukrainianFlag + ' ' : '') + 'Leaflet</a>'
  4736. },
  4737. initialize: function (options) {
  4738. setOptions(this, options);
  4739. this._attributions = {};
  4740. },
  4741. onAdd: function (map) {
  4742. map.attributionControl = this;
  4743. this._container = create$1('div', 'leaflet-control-attribution');
  4744. disableClickPropagation(this._container);
  4745. // TODO ugly, refactor
  4746. for (var i in map._layers) {
  4747. if (map._layers[i].getAttribution) {
  4748. this.addAttribution(map._layers[i].getAttribution());
  4749. }
  4750. }
  4751. this._update();
  4752. map.on('layeradd', this._addAttribution, this);
  4753. return this._container;
  4754. },
  4755. onRemove: function (map) {
  4756. map.off('layeradd', this._addAttribution, this);
  4757. },
  4758. _addAttribution: function (ev) {
  4759. if (ev.layer.getAttribution) {
  4760. this.addAttribution(ev.layer.getAttribution());
  4761. ev.layer.once('remove', function () {
  4762. this.removeAttribution(ev.layer.getAttribution());
  4763. }, this);
  4764. }
  4765. },
  4766. // @method setPrefix(prefix: String|false): this
  4767. // The HTML text shown before the attributions. Pass `false` to disable.
  4768. setPrefix: function (prefix) {
  4769. this.options.prefix = prefix;
  4770. this._update();
  4771. return this;
  4772. },
  4773. // @method addAttribution(text: String): this
  4774. // Adds an attribution text (e.g. `'&copy; OpenStreetMap contributors'`).
  4775. addAttribution: function (text) {
  4776. if (!text) { return this; }
  4777. if (!this._attributions[text]) {
  4778. this._attributions[text] = 0;
  4779. }
  4780. this._attributions[text]++;
  4781. this._update();
  4782. return this;
  4783. },
  4784. // @method removeAttribution(text: String): this
  4785. // Removes an attribution text.
  4786. removeAttribution: function (text) {
  4787. if (!text) { return this; }
  4788. if (this._attributions[text]) {
  4789. this._attributions[text]--;
  4790. this._update();
  4791. }
  4792. return this;
  4793. },
  4794. _update: function () {
  4795. if (!this._map) { return; }
  4796. var attribs = [];
  4797. for (var i in this._attributions) {
  4798. if (this._attributions[i]) {
  4799. attribs.push(i);
  4800. }
  4801. }
  4802. var prefixAndAttribs = [];
  4803. if (this.options.prefix) {
  4804. prefixAndAttribs.push(this.options.prefix);
  4805. }
  4806. if (attribs.length) {
  4807. prefixAndAttribs.push(attribs.join(', '));
  4808. }
  4809. this._container.innerHTML = prefixAndAttribs.join(' <span aria-hidden="true">|</span> ');
  4810. }
  4811. });
  4812. // @namespace Map
  4813. // @section Control options
  4814. // @option attributionControl: Boolean = true
  4815. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4816. Map.mergeOptions({
  4817. attributionControl: true
  4818. });
  4819. Map.addInitHook(function () {
  4820. if (this.options.attributionControl) {
  4821. new Attribution().addTo(this);
  4822. }
  4823. });
  4824. // @namespace Control.Attribution
  4825. // @factory L.control.attribution(options: Control.Attribution options)
  4826. // Creates an attribution control.
  4827. var attribution = function (options) {
  4828. return new Attribution(options);
  4829. };
  4830. Control.Layers = Layers;
  4831. Control.Zoom = Zoom;
  4832. Control.Scale = Scale;
  4833. Control.Attribution = Attribution;
  4834. control.layers = layers;
  4835. control.zoom = zoom;
  4836. control.scale = scale;
  4837. control.attribution = attribution;
  4838. /*
  4839. L.Handler is a base class for handler classes that are used internally to inject
  4840. interaction features like dragging to classes like Map and Marker.
  4841. */
  4842. // @class Handler
  4843. // @aka L.Handler
  4844. // Abstract class for map interaction handlers
  4845. var Handler = Class.extend({
  4846. initialize: function (map) {
  4847. this._map = map;
  4848. },
  4849. // @method enable(): this
  4850. // Enables the handler
  4851. enable: function () {
  4852. if (this._enabled) { return this; }
  4853. this._enabled = true;
  4854. this.addHooks();
  4855. return this;
  4856. },
  4857. // @method disable(): this
  4858. // Disables the handler
  4859. disable: function () {
  4860. if (!this._enabled) { return this; }
  4861. this._enabled = false;
  4862. this.removeHooks();
  4863. return this;
  4864. },
  4865. // @method enabled(): Boolean
  4866. // Returns `true` if the handler is enabled
  4867. enabled: function () {
  4868. return !!this._enabled;
  4869. }
  4870. // @section Extension methods
  4871. // Classes inheriting from `Handler` must implement the two following methods:
  4872. // @method addHooks()
  4873. // Called when the handler is enabled, should add event hooks.
  4874. // @method removeHooks()
  4875. // Called when the handler is disabled, should remove the event hooks added previously.
  4876. });
  4877. // @section There is static function which can be called without instantiating L.Handler:
  4878. // @function addTo(map: Map, name: String): this
  4879. // Adds a new Handler to the given map with the given name.
  4880. Handler.addTo = function (map, name) {
  4881. map.addHandler(name, this);
  4882. return this;
  4883. };
  4884. var Mixin = {Events: Events};
  4885. /*
  4886. * @class Draggable
  4887. * @aka L.Draggable
  4888. * @inherits Evented
  4889. *
  4890. * A class for making DOM elements draggable (including touch support).
  4891. * Used internally for map and marker dragging. Only works for elements
  4892. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4893. *
  4894. * @example
  4895. * ```js
  4896. * var draggable = new L.Draggable(elementToDrag);
  4897. * draggable.enable();
  4898. * ```
  4899. */
  4900. var START = Browser.touch ? 'touchstart mousedown' : 'mousedown';
  4901. var Draggable = Evented.extend({
  4902. options: {
  4903. // @section
  4904. // @aka Draggable options
  4905. // @option clickTolerance: Number = 3
  4906. // The max number of pixels a user can shift the mouse pointer during a click
  4907. // for it to be considered a valid click (as opposed to a mouse drag).
  4908. clickTolerance: 3
  4909. },
  4910. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4911. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4912. initialize: function (element, dragStartTarget, preventOutline, options) {
  4913. setOptions(this, options);
  4914. this._element = element;
  4915. this._dragStartTarget = dragStartTarget || element;
  4916. this._preventOutline = preventOutline;
  4917. },
  4918. // @method enable()
  4919. // Enables the dragging ability
  4920. enable: function () {
  4921. if (this._enabled) { return; }
  4922. on(this._dragStartTarget, START, this._onDown, this);
  4923. this._enabled = true;
  4924. },
  4925. // @method disable()
  4926. // Disables the dragging ability
  4927. disable: function () {
  4928. if (!this._enabled) { return; }
  4929. // If we're currently dragging this draggable,
  4930. // disabling it counts as first ending the drag.
  4931. if (Draggable._dragging === this) {
  4932. this.finishDrag(true);
  4933. }
  4934. off(this._dragStartTarget, START, this._onDown, this);
  4935. this._enabled = false;
  4936. this._moved = false;
  4937. },
  4938. _onDown: function (e) {
  4939. // Ignore the event if disabled; this happens in IE11
  4940. // under some circumstances, see #3666.
  4941. if (!this._enabled) { return; }
  4942. this._moved = false;
  4943. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4944. if (e.touches && e.touches.length !== 1) {
  4945. // Finish dragging to avoid conflict with touchZoom
  4946. if (Draggable._dragging === this) {
  4947. this.finishDrag();
  4948. }
  4949. return;
  4950. }
  4951. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4952. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4953. if (this._preventOutline) {
  4954. preventOutline(this._element);
  4955. }
  4956. disableImageDrag();
  4957. disableTextSelection();
  4958. if (this._moving) { return; }
  4959. // @event down: Event
  4960. // Fired when a drag is about to start.
  4961. this.fire('down');
  4962. var first = e.touches ? e.touches[0] : e,
  4963. sizedParent = getSizedParentNode(this._element);
  4964. this._startPoint = new Point(first.clientX, first.clientY);
  4965. this._startPos = getPosition(this._element);
  4966. // Cache the scale, so that we can continuously compensate for it during drag (_onMove).
  4967. this._parentScale = getScale(sizedParent);
  4968. var mouseevent = e.type === 'mousedown';
  4969. on(document, mouseevent ? 'mousemove' : 'touchmove', this._onMove, this);
  4970. on(document, mouseevent ? 'mouseup' : 'touchend touchcancel', this._onUp, this);
  4971. },
  4972. _onMove: function (e) {
  4973. // Ignore the event if disabled; this happens in IE11
  4974. // under some circumstances, see #3666.
  4975. if (!this._enabled) { return; }
  4976. if (e.touches && e.touches.length > 1) {
  4977. this._moved = true;
  4978. return;
  4979. }
  4980. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4981. offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);
  4982. if (!offset.x && !offset.y) { return; }
  4983. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4984. // We assume that the parent container's position, border and scale do not change for the duration of the drag.
  4985. // Therefore there is no need to account for the position and border (they are eliminated by the subtraction)
  4986. // and we can use the cached value for the scale.
  4987. offset.x /= this._parentScale.x;
  4988. offset.y /= this._parentScale.y;
  4989. preventDefault(e);
  4990. if (!this._moved) {
  4991. // @event dragstart: Event
  4992. // Fired when a drag starts
  4993. this.fire('dragstart');
  4994. this._moved = true;
  4995. addClass(document.body, 'leaflet-dragging');
  4996. this._lastTarget = e.target || e.srcElement;
  4997. // IE and Edge do not give the <use> element, so fetch it
  4998. // if necessary
  4999. if (window.SVGElementInstance && this._lastTarget instanceof window.SVGElementInstance) {
  5000. this._lastTarget = this._lastTarget.correspondingUseElement;
  5001. }
  5002. addClass(this._lastTarget, 'leaflet-drag-target');
  5003. }
  5004. this._newPos = this._startPos.add(offset);
  5005. this._moving = true;
  5006. this._lastEvent = e;
  5007. this._updatePosition();
  5008. },
  5009. _updatePosition: function () {
  5010. var e = {originalEvent: this._lastEvent};
  5011. // @event predrag: Event
  5012. // Fired continuously during dragging *before* each corresponding
  5013. // update of the element's position.
  5014. this.fire('predrag', e);
  5015. setPosition(this._element, this._newPos);
  5016. // @event drag: Event
  5017. // Fired continuously during dragging.
  5018. this.fire('drag', e);
  5019. },
  5020. _onUp: function () {
  5021. // Ignore the event if disabled; this happens in IE11
  5022. // under some circumstances, see #3666.
  5023. if (!this._enabled) { return; }
  5024. this.finishDrag();
  5025. },
  5026. finishDrag: function (noInertia) {
  5027. removeClass(document.body, 'leaflet-dragging');
  5028. if (this._lastTarget) {
  5029. removeClass(this._lastTarget, 'leaflet-drag-target');
  5030. this._lastTarget = null;
  5031. }
  5032. off(document, 'mousemove touchmove', this._onMove, this);
  5033. off(document, 'mouseup touchend touchcancel', this._onUp, this);
  5034. enableImageDrag();
  5035. enableTextSelection();
  5036. if (this._moved && this._moving) {
  5037. // @event dragend: DragEndEvent
  5038. // Fired when the drag ends.
  5039. this.fire('dragend', {
  5040. noInertia: noInertia,
  5041. distance: this._newPos.distanceTo(this._startPos)
  5042. });
  5043. }
  5044. this._moving = false;
  5045. Draggable._dragging = false;
  5046. }
  5047. });
  5048. /*
  5049. * @namespace LineUtil
  5050. *
  5051. * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
  5052. */
  5053. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  5054. // Improves rendering performance dramatically by lessening the number of points to draw.
  5055. // @function simplify(points: Point[], tolerance: Number): Point[]
  5056. // Dramatically reduces the number of points in a polyline while retaining
  5057. // its shape and returns a new array of simplified points, using the
  5058. // [Ramer-Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm).
  5059. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  5060. // each zoom level and also reducing visual noise. tolerance affects the amount of
  5061. // simplification (lesser value means higher quality but slower and with more points).
  5062. // Also released as a separated micro-library [Simplify.js](https://mourner.github.io/simplify-js/).
  5063. function simplify(points, tolerance) {
  5064. if (!tolerance || !points.length) {
  5065. return points.slice();
  5066. }
  5067. var sqTolerance = tolerance * tolerance;
  5068. // stage 1: vertex reduction
  5069. points = _reducePoints(points, sqTolerance);
  5070. // stage 2: Douglas-Peucker simplification
  5071. points = _simplifyDP(points, sqTolerance);
  5072. return points;
  5073. }
  5074. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  5075. // Returns the distance between point `p` and segment `p1` to `p2`.
  5076. function pointToSegmentDistance(p, p1, p2) {
  5077. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  5078. }
  5079. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  5080. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  5081. function closestPointOnSegment(p, p1, p2) {
  5082. return _sqClosestPointOnSegment(p, p1, p2);
  5083. }
  5084. // Ramer-Douglas-Peucker simplification, see https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
  5085. function _simplifyDP(points, sqTolerance) {
  5086. var len = points.length,
  5087. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  5088. markers = new ArrayConstructor(len);
  5089. markers[0] = markers[len - 1] = 1;
  5090. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  5091. var i,
  5092. newPoints = [];
  5093. for (i = 0; i < len; i++) {
  5094. if (markers[i]) {
  5095. newPoints.push(points[i]);
  5096. }
  5097. }
  5098. return newPoints;
  5099. }
  5100. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  5101. var maxSqDist = 0,
  5102. index, i, sqDist;
  5103. for (i = first + 1; i <= last - 1; i++) {
  5104. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  5105. if (sqDist > maxSqDist) {
  5106. index = i;
  5107. maxSqDist = sqDist;
  5108. }
  5109. }
  5110. if (maxSqDist > sqTolerance) {
  5111. markers[index] = 1;
  5112. _simplifyDPStep(points, markers, sqTolerance, first, index);
  5113. _simplifyDPStep(points, markers, sqTolerance, index, last);
  5114. }
  5115. }
  5116. // reduce points that are too close to each other to a single point
  5117. function _reducePoints(points, sqTolerance) {
  5118. var reducedPoints = [points[0]];
  5119. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  5120. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  5121. reducedPoints.push(points[i]);
  5122. prev = i;
  5123. }
  5124. }
  5125. if (prev < len - 1) {
  5126. reducedPoints.push(points[len - 1]);
  5127. }
  5128. return reducedPoints;
  5129. }
  5130. var _lastCode;
  5131. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  5132. // Clips the segment a to b by rectangular bounds with the
  5133. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  5134. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  5135. // points that are on the screen or near, increasing performance.
  5136. function clipSegment(a, b, bounds, useLastCode, round) {
  5137. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  5138. codeB = _getBitCode(b, bounds),
  5139. codeOut, p, newCode;
  5140. // save 2nd code to avoid calculating it on the next segment
  5141. _lastCode = codeB;
  5142. while (true) {
  5143. // if a,b is inside the clip window (trivial accept)
  5144. if (!(codeA | codeB)) {
  5145. return [a, b];
  5146. }
  5147. // if a,b is outside the clip window (trivial reject)
  5148. if (codeA & codeB) {
  5149. return false;
  5150. }
  5151. // other cases
  5152. codeOut = codeA || codeB;
  5153. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  5154. newCode = _getBitCode(p, bounds);
  5155. if (codeOut === codeA) {
  5156. a = p;
  5157. codeA = newCode;
  5158. } else {
  5159. b = p;
  5160. codeB = newCode;
  5161. }
  5162. }
  5163. }
  5164. function _getEdgeIntersection(a, b, code, bounds, round) {
  5165. var dx = b.x - a.x,
  5166. dy = b.y - a.y,
  5167. min = bounds.min,
  5168. max = bounds.max,
  5169. x, y;
  5170. if (code & 8) { // top
  5171. x = a.x + dx * (max.y - a.y) / dy;
  5172. y = max.y;
  5173. } else if (code & 4) { // bottom
  5174. x = a.x + dx * (min.y - a.y) / dy;
  5175. y = min.y;
  5176. } else if (code & 2) { // right
  5177. x = max.x;
  5178. y = a.y + dy * (max.x - a.x) / dx;
  5179. } else if (code & 1) { // left
  5180. x = min.x;
  5181. y = a.y + dy * (min.x - a.x) / dx;
  5182. }
  5183. return new Point(x, y, round);
  5184. }
  5185. function _getBitCode(p, bounds) {
  5186. var code = 0;
  5187. if (p.x < bounds.min.x) { // left
  5188. code |= 1;
  5189. } else if (p.x > bounds.max.x) { // right
  5190. code |= 2;
  5191. }
  5192. if (p.y < bounds.min.y) { // bottom
  5193. code |= 4;
  5194. } else if (p.y > bounds.max.y) { // top
  5195. code |= 8;
  5196. }
  5197. return code;
  5198. }
  5199. // square distance (to avoid unnecessary Math.sqrt calls)
  5200. function _sqDist(p1, p2) {
  5201. var dx = p2.x - p1.x,
  5202. dy = p2.y - p1.y;
  5203. return dx * dx + dy * dy;
  5204. }
  5205. // return closest point on segment or distance to that point
  5206. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  5207. var x = p1.x,
  5208. y = p1.y,
  5209. dx = p2.x - x,
  5210. dy = p2.y - y,
  5211. dot = dx * dx + dy * dy,
  5212. t;
  5213. if (dot > 0) {
  5214. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  5215. if (t > 1) {
  5216. x = p2.x;
  5217. y = p2.y;
  5218. } else if (t > 0) {
  5219. x += dx * t;
  5220. y += dy * t;
  5221. }
  5222. }
  5223. dx = p.x - x;
  5224. dy = p.y - y;
  5225. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  5226. }
  5227. // @function isFlat(latlngs: LatLng[]): Boolean
  5228. // Returns true if `latlngs` is a flat array, false is nested.
  5229. function isFlat(latlngs) {
  5230. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  5231. }
  5232. function _flat(latlngs) {
  5233. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  5234. return isFlat(latlngs);
  5235. }
  5236. /* @function polylineCenter(latlngs: LatLng[], crs: CRS): LatLng
  5237. * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polyline.
  5238. */
  5239. function polylineCenter(latlngs, crs) {
  5240. var i, halfDist, segDist, dist, p1, p2, ratio, center;
  5241. if (!latlngs || latlngs.length === 0) {
  5242. throw new Error('latlngs not passed');
  5243. }
  5244. if (!isFlat(latlngs)) {
  5245. console.warn('latlngs are not flat! Only the first ring will be used');
  5246. latlngs = latlngs[0];
  5247. }
  5248. var points = [];
  5249. for (var j in latlngs) {
  5250. points.push(crs.project(toLatLng(latlngs[j])));
  5251. }
  5252. var len = points.length;
  5253. for (i = 0, halfDist = 0; i < len - 1; i++) {
  5254. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  5255. }
  5256. // The line is so small in the current view that all points are on the same pixel.
  5257. if (halfDist === 0) {
  5258. center = points[0];
  5259. } else {
  5260. for (i = 0, dist = 0; i < len - 1; i++) {
  5261. p1 = points[i];
  5262. p2 = points[i + 1];
  5263. segDist = p1.distanceTo(p2);
  5264. dist += segDist;
  5265. if (dist > halfDist) {
  5266. ratio = (dist - halfDist) / segDist;
  5267. center = [
  5268. p2.x - ratio * (p2.x - p1.x),
  5269. p2.y - ratio * (p2.y - p1.y)
  5270. ];
  5271. break;
  5272. }
  5273. }
  5274. }
  5275. return crs.unproject(toPoint(center));
  5276. }
  5277. var LineUtil = {
  5278. __proto__: null,
  5279. simplify: simplify,
  5280. pointToSegmentDistance: pointToSegmentDistance,
  5281. closestPointOnSegment: closestPointOnSegment,
  5282. clipSegment: clipSegment,
  5283. _getEdgeIntersection: _getEdgeIntersection,
  5284. _getBitCode: _getBitCode,
  5285. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5286. isFlat: isFlat,
  5287. _flat: _flat,
  5288. polylineCenter: polylineCenter
  5289. };
  5290. /*
  5291. * @namespace PolyUtil
  5292. * Various utility functions for polygon geometries.
  5293. */
  5294. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5295. * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).
  5296. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5297. * performance. Note that polygon points needs different algorithm for clipping
  5298. * than polyline, so there's a separate method for it.
  5299. */
  5300. function clipPolygon(points, bounds, round) {
  5301. var clippedPoints,
  5302. edges = [1, 4, 2, 8],
  5303. i, j, k,
  5304. a, b,
  5305. len, edge, p;
  5306. for (i = 0, len = points.length; i < len; i++) {
  5307. points[i]._code = _getBitCode(points[i], bounds);
  5308. }
  5309. // for each edge (left, bottom, right, top)
  5310. for (k = 0; k < 4; k++) {
  5311. edge = edges[k];
  5312. clippedPoints = [];
  5313. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5314. a = points[i];
  5315. b = points[j];
  5316. // if a is inside the clip window
  5317. if (!(a._code & edge)) {
  5318. // if b is outside the clip window (a->b goes out of screen)
  5319. if (b._code & edge) {
  5320. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5321. p._code = _getBitCode(p, bounds);
  5322. clippedPoints.push(p);
  5323. }
  5324. clippedPoints.push(a);
  5325. // else if b is inside the clip window (a->b enters the screen)
  5326. } else if (!(b._code & edge)) {
  5327. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5328. p._code = _getBitCode(p, bounds);
  5329. clippedPoints.push(p);
  5330. }
  5331. }
  5332. points = clippedPoints;
  5333. }
  5334. return points;
  5335. }
  5336. /* @function polygonCenter(latlngs: LatLng[] crs: CRS): LatLng
  5337. * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polygon.
  5338. */
  5339. function polygonCenter(latlngs, crs) {
  5340. var i, j, p1, p2, f, area, x, y, center;
  5341. if (!latlngs || latlngs.length === 0) {
  5342. throw new Error('latlngs not passed');
  5343. }
  5344. if (!isFlat(latlngs)) {
  5345. console.warn('latlngs are not flat! Only the first ring will be used');
  5346. latlngs = latlngs[0];
  5347. }
  5348. var points = [];
  5349. for (var k in latlngs) {
  5350. points.push(crs.project(toLatLng(latlngs[k])));
  5351. }
  5352. var len = points.length;
  5353. area = x = y = 0;
  5354. // polygon centroid algorithm;
  5355. for (i = 0, j = len - 1; i < len; j = i++) {
  5356. p1 = points[i];
  5357. p2 = points[j];
  5358. f = p1.y * p2.x - p2.y * p1.x;
  5359. x += (p1.x + p2.x) * f;
  5360. y += (p1.y + p2.y) * f;
  5361. area += f * 3;
  5362. }
  5363. if (area === 0) {
  5364. // Polygon is so small that all points are on same pixel.
  5365. center = points[0];
  5366. } else {
  5367. center = [x / area, y / area];
  5368. }
  5369. return crs.unproject(toPoint(center));
  5370. }
  5371. var PolyUtil = {
  5372. __proto__: null,
  5373. clipPolygon: clipPolygon,
  5374. polygonCenter: polygonCenter
  5375. };
  5376. /*
  5377. * @namespace Projection
  5378. * @section
  5379. * Leaflet comes with a set of already defined Projections out of the box:
  5380. *
  5381. * @projection L.Projection.LonLat
  5382. *
  5383. * Equirectangular, or Plate Carree projection — the most simple projection,
  5384. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5385. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5386. * `EPSG:4326` and `Simple` CRS.
  5387. */
  5388. var LonLat = {
  5389. project: function (latlng) {
  5390. return new Point(latlng.lng, latlng.lat);
  5391. },
  5392. unproject: function (point) {
  5393. return new LatLng(point.y, point.x);
  5394. },
  5395. bounds: new Bounds([-180, -90], [180, 90])
  5396. };
  5397. /*
  5398. * @namespace Projection
  5399. * @projection L.Projection.Mercator
  5400. *
  5401. * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.
  5402. */
  5403. var Mercator = {
  5404. R: 6378137,
  5405. R_MINOR: 6356752.314245179,
  5406. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5407. project: function (latlng) {
  5408. var d = Math.PI / 180,
  5409. r = this.R,
  5410. y = latlng.lat * d,
  5411. tmp = this.R_MINOR / r,
  5412. e = Math.sqrt(1 - tmp * tmp),
  5413. con = e * Math.sin(y);
  5414. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5415. y = -r * Math.log(Math.max(ts, 1E-10));
  5416. return new Point(latlng.lng * d * r, y);
  5417. },
  5418. unproject: function (point) {
  5419. var d = 180 / Math.PI,
  5420. r = this.R,
  5421. tmp = this.R_MINOR / r,
  5422. e = Math.sqrt(1 - tmp * tmp),
  5423. ts = Math.exp(-point.y / r),
  5424. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5425. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5426. con = e * Math.sin(phi);
  5427. con = Math.pow((1 - con) / (1 + con), e / 2);
  5428. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5429. phi += dphi;
  5430. }
  5431. return new LatLng(phi * d, point.x * d / r);
  5432. }
  5433. };
  5434. /*
  5435. * @class Projection
  5436. * An object with methods for projecting geographical coordinates of the world onto
  5437. * a flat surface (and back). See [Map projection](https://en.wikipedia.org/wiki/Map_projection).
  5438. * @property bounds: Bounds
  5439. * The bounds (specified in CRS units) where the projection is valid
  5440. * @method project(latlng: LatLng): Point
  5441. * Projects geographical coordinates into a 2D point.
  5442. * Only accepts actual `L.LatLng` instances, not arrays.
  5443. * @method unproject(point: Point): LatLng
  5444. * The inverse of `project`. Projects a 2D point into a geographical location.
  5445. * Only accepts actual `L.Point` instances, not arrays.
  5446. * Note that the projection instances do not inherit from Leaflet's `Class` object,
  5447. * and can't be instantiated. Also, new classes can't inherit from them,
  5448. * and methods can't be added to them with the `include` function.
  5449. */
  5450. var index = {
  5451. __proto__: null,
  5452. LonLat: LonLat,
  5453. Mercator: Mercator,
  5454. SphericalMercator: SphericalMercator
  5455. };
  5456. /*
  5457. * @namespace CRS
  5458. * @crs L.CRS.EPSG3395
  5459. *
  5460. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5461. */
  5462. var EPSG3395 = extend({}, Earth, {
  5463. code: 'EPSG:3395',
  5464. projection: Mercator,
  5465. transformation: (function () {
  5466. var scale = 0.5 / (Math.PI * Mercator.R);
  5467. return toTransformation(scale, 0.5, -scale, 0.5);
  5468. }())
  5469. });
  5470. /*
  5471. * @namespace CRS
  5472. * @crs L.CRS.EPSG4326
  5473. *
  5474. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5475. *
  5476. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5477. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5478. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5479. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5480. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5481. */
  5482. var EPSG4326 = extend({}, Earth, {
  5483. code: 'EPSG:4326',
  5484. projection: LonLat,
  5485. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5486. });
  5487. /*
  5488. * @namespace CRS
  5489. * @crs L.CRS.Simple
  5490. *
  5491. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5492. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5493. * axis should still be inverted (going from bottom to top). `distance()` returns
  5494. * simple euclidean distance.
  5495. */
  5496. var Simple = extend({}, CRS, {
  5497. projection: LonLat,
  5498. transformation: toTransformation(1, 0, -1, 0),
  5499. scale: function (zoom) {
  5500. return Math.pow(2, zoom);
  5501. },
  5502. zoom: function (scale) {
  5503. return Math.log(scale) / Math.LN2;
  5504. },
  5505. distance: function (latlng1, latlng2) {
  5506. var dx = latlng2.lng - latlng1.lng,
  5507. dy = latlng2.lat - latlng1.lat;
  5508. return Math.sqrt(dx * dx + dy * dy);
  5509. },
  5510. infinite: true
  5511. });
  5512. CRS.Earth = Earth;
  5513. CRS.EPSG3395 = EPSG3395;
  5514. CRS.EPSG3857 = EPSG3857;
  5515. CRS.EPSG900913 = EPSG900913;
  5516. CRS.EPSG4326 = EPSG4326;
  5517. CRS.Simple = Simple;
  5518. /*
  5519. * @class Layer
  5520. * @inherits Evented
  5521. * @aka L.Layer
  5522. * @aka ILayer
  5523. *
  5524. * A set of methods from the Layer base class that all Leaflet layers use.
  5525. * Inherits all methods, options and events from `L.Evented`.
  5526. *
  5527. * @example
  5528. *
  5529. * ```js
  5530. * var layer = L.marker(latlng).addTo(map);
  5531. * layer.addTo(map);
  5532. * layer.remove();
  5533. * ```
  5534. *
  5535. * @event add: Event
  5536. * Fired after the layer is added to a map
  5537. *
  5538. * @event remove: Event
  5539. * Fired after the layer is removed from a map
  5540. */
  5541. var Layer = Evented.extend({
  5542. // Classes extending `L.Layer` will inherit the following options:
  5543. options: {
  5544. // @option pane: String = 'overlayPane'
  5545. // 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.
  5546. pane: 'overlayPane',
  5547. // @option attribution: String = null
  5548. // String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.
  5549. attribution: null,
  5550. bubblingMouseEvents: true
  5551. },
  5552. /* @section
  5553. * Classes extending `L.Layer` will inherit the following methods:
  5554. *
  5555. * @method addTo(map: Map|LayerGroup): this
  5556. * Adds the layer to the given map or layer group.
  5557. */
  5558. addTo: function (map) {
  5559. map.addLayer(this);
  5560. return this;
  5561. },
  5562. // @method remove: this
  5563. // Removes the layer from the map it is currently active on.
  5564. remove: function () {
  5565. return this.removeFrom(this._map || this._mapToAdd);
  5566. },
  5567. // @method removeFrom(map: Map): this
  5568. // Removes the layer from the given map
  5569. //
  5570. // @alternative
  5571. // @method removeFrom(group: LayerGroup): this
  5572. // Removes the layer from the given `LayerGroup`
  5573. removeFrom: function (obj) {
  5574. if (obj) {
  5575. obj.removeLayer(this);
  5576. }
  5577. return this;
  5578. },
  5579. // @method getPane(name? : String): HTMLElement
  5580. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5581. getPane: function (name) {
  5582. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5583. },
  5584. addInteractiveTarget: function (targetEl) {
  5585. this._map._targets[stamp(targetEl)] = this;
  5586. return this;
  5587. },
  5588. removeInteractiveTarget: function (targetEl) {
  5589. delete this._map._targets[stamp(targetEl)];
  5590. return this;
  5591. },
  5592. // @method getAttribution: String
  5593. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5594. getAttribution: function () {
  5595. return this.options.attribution;
  5596. },
  5597. _layerAdd: function (e) {
  5598. var map = e.target;
  5599. // check in case layer gets added and then removed before the map is ready
  5600. if (!map.hasLayer(this)) { return; }
  5601. this._map = map;
  5602. this._zoomAnimated = map._zoomAnimated;
  5603. if (this.getEvents) {
  5604. var events = this.getEvents();
  5605. map.on(events, this);
  5606. this.once('remove', function () {
  5607. map.off(events, this);
  5608. }, this);
  5609. }
  5610. this.onAdd(map);
  5611. this.fire('add');
  5612. map.fire('layeradd', {layer: this});
  5613. }
  5614. });
  5615. /* @section Extension methods
  5616. * @uninheritable
  5617. *
  5618. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5619. *
  5620. * @method onAdd(map: Map): this
  5621. * 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).
  5622. *
  5623. * @method onRemove(map: Map): this
  5624. * 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).
  5625. *
  5626. * @method getEvents(): Object
  5627. * 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.
  5628. *
  5629. * @method getAttribution(): String
  5630. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5631. *
  5632. * @method beforeAdd(map: Map): this
  5633. * 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.
  5634. */
  5635. /* @namespace Map
  5636. * @section Layer events
  5637. *
  5638. * @event layeradd: LayerEvent
  5639. * Fired when a new layer is added to the map.
  5640. *
  5641. * @event layerremove: LayerEvent
  5642. * Fired when some layer is removed from the map
  5643. *
  5644. * @section Methods for Layers and Controls
  5645. */
  5646. Map.include({
  5647. // @method addLayer(layer: Layer): this
  5648. // Adds the given layer to the map
  5649. addLayer: function (layer) {
  5650. if (!layer._layerAdd) {
  5651. throw new Error('The provided object is not a Layer.');
  5652. }
  5653. var id = stamp(layer);
  5654. if (this._layers[id]) { return this; }
  5655. this._layers[id] = layer;
  5656. layer._mapToAdd = this;
  5657. if (layer.beforeAdd) {
  5658. layer.beforeAdd(this);
  5659. }
  5660. this.whenReady(layer._layerAdd, layer);
  5661. return this;
  5662. },
  5663. // @method removeLayer(layer: Layer): this
  5664. // Removes the given layer from the map.
  5665. removeLayer: function (layer) {
  5666. var id = stamp(layer);
  5667. if (!this._layers[id]) { return this; }
  5668. if (this._loaded) {
  5669. layer.onRemove(this);
  5670. }
  5671. delete this._layers[id];
  5672. if (this._loaded) {
  5673. this.fire('layerremove', {layer: layer});
  5674. layer.fire('remove');
  5675. }
  5676. layer._map = layer._mapToAdd = null;
  5677. return this;
  5678. },
  5679. // @method hasLayer(layer: Layer): Boolean
  5680. // Returns `true` if the given layer is currently added to the map
  5681. hasLayer: function (layer) {
  5682. return stamp(layer) in this._layers;
  5683. },
  5684. /* @method eachLayer(fn: Function, context?: Object): this
  5685. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5686. * ```
  5687. * map.eachLayer(function(layer){
  5688. * layer.bindPopup('Hello');
  5689. * });
  5690. * ```
  5691. */
  5692. eachLayer: function (method, context) {
  5693. for (var i in this._layers) {
  5694. method.call(context, this._layers[i]);
  5695. }
  5696. return this;
  5697. },
  5698. _addLayers: function (layers) {
  5699. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5700. for (var i = 0, len = layers.length; i < len; i++) {
  5701. this.addLayer(layers[i]);
  5702. }
  5703. },
  5704. _addZoomLimit: function (layer) {
  5705. if (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5706. this._zoomBoundLayers[stamp(layer)] = layer;
  5707. this._updateZoomLevels();
  5708. }
  5709. },
  5710. _removeZoomLimit: function (layer) {
  5711. var id = stamp(layer);
  5712. if (this._zoomBoundLayers[id]) {
  5713. delete this._zoomBoundLayers[id];
  5714. this._updateZoomLevels();
  5715. }
  5716. },
  5717. _updateZoomLevels: function () {
  5718. var minZoom = Infinity,
  5719. maxZoom = -Infinity,
  5720. oldZoomSpan = this._getZoomSpan();
  5721. for (var i in this._zoomBoundLayers) {
  5722. var options = this._zoomBoundLayers[i].options;
  5723. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5724. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5725. }
  5726. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5727. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5728. // @section Map state change events
  5729. // @event zoomlevelschange: Event
  5730. // Fired when the number of zoomlevels on the map is changed due
  5731. // to adding or removing a layer.
  5732. if (oldZoomSpan !== this._getZoomSpan()) {
  5733. this.fire('zoomlevelschange');
  5734. }
  5735. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5736. this.setZoom(this._layersMaxZoom);
  5737. }
  5738. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5739. this.setZoom(this._layersMinZoom);
  5740. }
  5741. }
  5742. });
  5743. /*
  5744. * @class LayerGroup
  5745. * @aka L.LayerGroup
  5746. * @inherits Interactive layer
  5747. *
  5748. * Used to group several layers and handle them as one. If you add it to the map,
  5749. * any layers added or removed from the group will be added/removed on the map as
  5750. * well. Extends `Layer`.
  5751. *
  5752. * @example
  5753. *
  5754. * ```js
  5755. * L.layerGroup([marker1, marker2])
  5756. * .addLayer(polyline)
  5757. * .addTo(map);
  5758. * ```
  5759. */
  5760. var LayerGroup = Layer.extend({
  5761. initialize: function (layers, options) {
  5762. setOptions(this, options);
  5763. this._layers = {};
  5764. var i, len;
  5765. if (layers) {
  5766. for (i = 0, len = layers.length; i < len; i++) {
  5767. this.addLayer(layers[i]);
  5768. }
  5769. }
  5770. },
  5771. // @method addLayer(layer: Layer): this
  5772. // Adds the given layer to the group.
  5773. addLayer: function (layer) {
  5774. var id = this.getLayerId(layer);
  5775. this._layers[id] = layer;
  5776. if (this._map) {
  5777. this._map.addLayer(layer);
  5778. }
  5779. return this;
  5780. },
  5781. // @method removeLayer(layer: Layer): this
  5782. // Removes the given layer from the group.
  5783. // @alternative
  5784. // @method removeLayer(id: Number): this
  5785. // Removes the layer with the given internal ID from the group.
  5786. removeLayer: function (layer) {
  5787. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5788. if (this._map && this._layers[id]) {
  5789. this._map.removeLayer(this._layers[id]);
  5790. }
  5791. delete this._layers[id];
  5792. return this;
  5793. },
  5794. // @method hasLayer(layer: Layer): Boolean
  5795. // Returns `true` if the given layer is currently added to the group.
  5796. // @alternative
  5797. // @method hasLayer(id: Number): Boolean
  5798. // Returns `true` if the given internal ID is currently added to the group.
  5799. hasLayer: function (layer) {
  5800. var layerId = typeof layer === 'number' ? layer : this.getLayerId(layer);
  5801. return layerId in this._layers;
  5802. },
  5803. // @method clearLayers(): this
  5804. // Removes all the layers from the group.
  5805. clearLayers: function () {
  5806. return this.eachLayer(this.removeLayer, this);
  5807. },
  5808. // @method invoke(methodName: String, …): this
  5809. // Calls `methodName` on every layer contained in this group, passing any
  5810. // additional parameters. Has no effect if the layers contained do not
  5811. // implement `methodName`.
  5812. invoke: function (methodName) {
  5813. var args = Array.prototype.slice.call(arguments, 1),
  5814. i, layer;
  5815. for (i in this._layers) {
  5816. layer = this._layers[i];
  5817. if (layer[methodName]) {
  5818. layer[methodName].apply(layer, args);
  5819. }
  5820. }
  5821. return this;
  5822. },
  5823. onAdd: function (map) {
  5824. this.eachLayer(map.addLayer, map);
  5825. },
  5826. onRemove: function (map) {
  5827. this.eachLayer(map.removeLayer, map);
  5828. },
  5829. // @method eachLayer(fn: Function, context?: Object): this
  5830. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5831. // ```js
  5832. // group.eachLayer(function (layer) {
  5833. // layer.bindPopup('Hello');
  5834. // });
  5835. // ```
  5836. eachLayer: function (method, context) {
  5837. for (var i in this._layers) {
  5838. method.call(context, this._layers[i]);
  5839. }
  5840. return this;
  5841. },
  5842. // @method getLayer(id: Number): Layer
  5843. // Returns the layer with the given internal ID.
  5844. getLayer: function (id) {
  5845. return this._layers[id];
  5846. },
  5847. // @method getLayers(): Layer[]
  5848. // Returns an array of all the layers added to the group.
  5849. getLayers: function () {
  5850. var layers = [];
  5851. this.eachLayer(layers.push, layers);
  5852. return layers;
  5853. },
  5854. // @method setZIndex(zIndex: Number): this
  5855. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5856. setZIndex: function (zIndex) {
  5857. return this.invoke('setZIndex', zIndex);
  5858. },
  5859. // @method getLayerId(layer: Layer): Number
  5860. // Returns the internal ID for a layer
  5861. getLayerId: function (layer) {
  5862. return stamp(layer);
  5863. }
  5864. });
  5865. // @factory L.layerGroup(layers?: Layer[], options?: Object)
  5866. // Create a layer group, optionally given an initial set of layers and an `options` object.
  5867. var layerGroup = function (layers, options) {
  5868. return new LayerGroup(layers, options);
  5869. };
  5870. /*
  5871. * @class FeatureGroup
  5872. * @aka L.FeatureGroup
  5873. * @inherits LayerGroup
  5874. *
  5875. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5876. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5877. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5878. * handler, it will handle events from any of the layers. This includes mouse events
  5879. * and custom events.
  5880. * * Has `layeradd` and `layerremove` events
  5881. *
  5882. * @example
  5883. *
  5884. * ```js
  5885. * L.featureGroup([marker1, marker2, polyline])
  5886. * .bindPopup('Hello world!')
  5887. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5888. * .addTo(map);
  5889. * ```
  5890. */
  5891. var FeatureGroup = LayerGroup.extend({
  5892. addLayer: function (layer) {
  5893. if (this.hasLayer(layer)) {
  5894. return this;
  5895. }
  5896. layer.addEventParent(this);
  5897. LayerGroup.prototype.addLayer.call(this, layer);
  5898. // @event layeradd: LayerEvent
  5899. // Fired when a layer is added to this `FeatureGroup`
  5900. return this.fire('layeradd', {layer: layer});
  5901. },
  5902. removeLayer: function (layer) {
  5903. if (!this.hasLayer(layer)) {
  5904. return this;
  5905. }
  5906. if (layer in this._layers) {
  5907. layer = this._layers[layer];
  5908. }
  5909. layer.removeEventParent(this);
  5910. LayerGroup.prototype.removeLayer.call(this, layer);
  5911. // @event layerremove: LayerEvent
  5912. // Fired when a layer is removed from this `FeatureGroup`
  5913. return this.fire('layerremove', {layer: layer});
  5914. },
  5915. // @method setStyle(style: Path options): this
  5916. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5917. setStyle: function (style) {
  5918. return this.invoke('setStyle', style);
  5919. },
  5920. // @method bringToFront(): this
  5921. // Brings the layer group to the top of all other layers
  5922. bringToFront: function () {
  5923. return this.invoke('bringToFront');
  5924. },
  5925. // @method bringToBack(): this
  5926. // Brings the layer group to the back of all other layers
  5927. bringToBack: function () {
  5928. return this.invoke('bringToBack');
  5929. },
  5930. // @method getBounds(): LatLngBounds
  5931. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5932. getBounds: function () {
  5933. var bounds = new LatLngBounds();
  5934. for (var id in this._layers) {
  5935. var layer = this._layers[id];
  5936. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5937. }
  5938. return bounds;
  5939. }
  5940. });
  5941. // @factory L.featureGroup(layers?: Layer[], options?: Object)
  5942. // Create a feature group, optionally given an initial set of layers and an `options` object.
  5943. var featureGroup = function (layers, options) {
  5944. return new FeatureGroup(layers, options);
  5945. };
  5946. /*
  5947. * @class Icon
  5948. * @aka L.Icon
  5949. *
  5950. * Represents an icon to provide when creating a marker.
  5951. *
  5952. * @example
  5953. *
  5954. * ```js
  5955. * var myIcon = L.icon({
  5956. * iconUrl: 'my-icon.png',
  5957. * iconRetinaUrl: 'my-icon@2x.png',
  5958. * iconSize: [38, 95],
  5959. * iconAnchor: [22, 94],
  5960. * popupAnchor: [-3, -76],
  5961. * shadowUrl: 'my-icon-shadow.png',
  5962. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5963. * shadowSize: [68, 95],
  5964. * shadowAnchor: [22, 94]
  5965. * });
  5966. *
  5967. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5968. * ```
  5969. *
  5970. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5971. *
  5972. */
  5973. var Icon = Class.extend({
  5974. /* @section
  5975. * @aka Icon options
  5976. *
  5977. * @option iconUrl: String = null
  5978. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5979. *
  5980. * @option iconRetinaUrl: String = null
  5981. * The URL to a retina sized version of the icon image (absolute or relative to your
  5982. * script path). Used for Retina screen devices.
  5983. *
  5984. * @option iconSize: Point = null
  5985. * Size of the icon image in pixels.
  5986. *
  5987. * @option iconAnchor: Point = null
  5988. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5989. * will be aligned so that this point is at the marker's geographical location. Centered
  5990. * by default if size is specified, also can be set in CSS with negative margins.
  5991. *
  5992. * @option popupAnchor: Point = [0, 0]
  5993. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5994. *
  5995. * @option tooltipAnchor: Point = [0, 0]
  5996. * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
  5997. *
  5998. * @option shadowUrl: String = null
  5999. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  6000. *
  6001. * @option shadowRetinaUrl: String = null
  6002. *
  6003. * @option shadowSize: Point = null
  6004. * Size of the shadow image in pixels.
  6005. *
  6006. * @option shadowAnchor: Point = null
  6007. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  6008. * as iconAnchor if not specified).
  6009. *
  6010. * @option className: String = ''
  6011. * A custom class name to assign to both icon and shadow images. Empty by default.
  6012. */
  6013. options: {
  6014. popupAnchor: [0, 0],
  6015. tooltipAnchor: [0, 0],
  6016. // @option crossOrigin: Boolean|String = false
  6017. // Whether the crossOrigin attribute will be added to the tiles.
  6018. // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
  6019. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  6020. crossOrigin: false
  6021. },
  6022. initialize: function (options) {
  6023. setOptions(this, options);
  6024. },
  6025. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  6026. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  6027. // styled according to the options.
  6028. createIcon: function (oldIcon) {
  6029. return this._createIcon('icon', oldIcon);
  6030. },
  6031. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  6032. // As `createIcon`, but for the shadow beneath it.
  6033. createShadow: function (oldIcon) {
  6034. return this._createIcon('shadow', oldIcon);
  6035. },
  6036. _createIcon: function (name, oldIcon) {
  6037. var src = this._getIconUrl(name);
  6038. if (!src) {
  6039. if (name === 'icon') {
  6040. throw new Error('iconUrl not set in Icon options (see the docs).');
  6041. }
  6042. return null;
  6043. }
  6044. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  6045. this._setIconStyles(img, name);
  6046. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  6047. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  6048. }
  6049. return img;
  6050. },
  6051. _setIconStyles: function (img, name) {
  6052. var options = this.options;
  6053. var sizeOption = options[name + 'Size'];
  6054. if (typeof sizeOption === 'number') {
  6055. sizeOption = [sizeOption, sizeOption];
  6056. }
  6057. var size = toPoint(sizeOption),
  6058. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  6059. size && size.divideBy(2, true));
  6060. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  6061. if (anchor) {
  6062. img.style.marginLeft = (-anchor.x) + 'px';
  6063. img.style.marginTop = (-anchor.y) + 'px';
  6064. }
  6065. if (size) {
  6066. img.style.width = size.x + 'px';
  6067. img.style.height = size.y + 'px';
  6068. }
  6069. },
  6070. _createImg: function (src, el) {
  6071. el = el || document.createElement('img');
  6072. el.src = src;
  6073. return el;
  6074. },
  6075. _getIconUrl: function (name) {
  6076. return Browser.retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  6077. }
  6078. });
  6079. // @factory L.icon(options: Icon options)
  6080. // Creates an icon instance with the given options.
  6081. function icon(options) {
  6082. return new Icon(options);
  6083. }
  6084. /*
  6085. * @miniclass Icon.Default (Icon)
  6086. * @aka L.Icon.Default
  6087. * @section
  6088. *
  6089. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  6090. * no icon is specified. Points to the blue marker image distributed with Leaflet
  6091. * releases.
  6092. *
  6093. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  6094. * (which is a set of `Icon options`).
  6095. *
  6096. * If you want to _completely_ replace the default icon, override the
  6097. * `L.Marker.prototype.options.icon` with your own icon instead.
  6098. */
  6099. var IconDefault = Icon.extend({
  6100. options: {
  6101. iconUrl: 'marker-icon.png',
  6102. iconRetinaUrl: 'marker-icon-2x.png',
  6103. shadowUrl: 'marker-shadow.png',
  6104. iconSize: [25, 41],
  6105. iconAnchor: [12, 41],
  6106. popupAnchor: [1, -34],
  6107. tooltipAnchor: [16, -28],
  6108. shadowSize: [41, 41]
  6109. },
  6110. _getIconUrl: function (name) {
  6111. if (typeof IconDefault.imagePath !== 'string') { // Deprecated, backwards-compatibility only
  6112. IconDefault.imagePath = this._detectIconPath();
  6113. }
  6114. // @option imagePath: String
  6115. // `Icon.Default` will try to auto-detect the location of the
  6116. // blue icon images. If you are placing these images in a non-standard
  6117. // way, set this option to point to the right path.
  6118. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  6119. },
  6120. _stripUrl: function (path) { // separate function to use in tests
  6121. var strip = function (str, re, idx) {
  6122. var match = re.exec(str);
  6123. return match && match[idx];
  6124. };
  6125. path = strip(path, /^url\((['"])?(.+)\1\)$/, 2);
  6126. return path && strip(path, /^(.*)marker-icon\.png$/, 1);
  6127. },
  6128. _detectIconPath: function () {
  6129. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  6130. var path = getStyle(el, 'background-image') ||
  6131. getStyle(el, 'backgroundImage'); // IE8
  6132. document.body.removeChild(el);
  6133. path = this._stripUrl(path);
  6134. if (path) { return path; }
  6135. var link = document.querySelector('link[href$="leaflet.css"]');
  6136. if (!link) { return ''; }
  6137. return link.href.substring(0, link.href.length - 'leaflet.css'.length - 1);
  6138. }
  6139. });
  6140. /*
  6141. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  6142. */
  6143. /* @namespace Marker
  6144. * @section Interaction handlers
  6145. *
  6146. * 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:
  6147. *
  6148. * ```js
  6149. * marker.dragging.disable();
  6150. * ```
  6151. *
  6152. * @property dragging: Handler
  6153. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  6154. */
  6155. var MarkerDrag = Handler.extend({
  6156. initialize: function (marker) {
  6157. this._marker = marker;
  6158. },
  6159. addHooks: function () {
  6160. var icon = this._marker._icon;
  6161. if (!this._draggable) {
  6162. this._draggable = new Draggable(icon, icon, true);
  6163. }
  6164. this._draggable.on({
  6165. dragstart: this._onDragStart,
  6166. predrag: this._onPreDrag,
  6167. drag: this._onDrag,
  6168. dragend: this._onDragEnd
  6169. }, this).enable();
  6170. addClass(icon, 'leaflet-marker-draggable');
  6171. },
  6172. removeHooks: function () {
  6173. this._draggable.off({
  6174. dragstart: this._onDragStart,
  6175. predrag: this._onPreDrag,
  6176. drag: this._onDrag,
  6177. dragend: this._onDragEnd
  6178. }, this).disable();
  6179. if (this._marker._icon) {
  6180. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  6181. }
  6182. },
  6183. moved: function () {
  6184. return this._draggable && this._draggable._moved;
  6185. },
  6186. _adjustPan: function (e) {
  6187. var marker = this._marker,
  6188. map = marker._map,
  6189. speed = this._marker.options.autoPanSpeed,
  6190. padding = this._marker.options.autoPanPadding,
  6191. iconPos = getPosition(marker._icon),
  6192. bounds = map.getPixelBounds(),
  6193. origin = map.getPixelOrigin();
  6194. var panBounds = toBounds(
  6195. bounds.min._subtract(origin).add(padding),
  6196. bounds.max._subtract(origin).subtract(padding)
  6197. );
  6198. if (!panBounds.contains(iconPos)) {
  6199. // Compute incremental movement
  6200. var movement = toPoint(
  6201. (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
  6202. (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
  6203. (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
  6204. (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
  6205. ).multiplyBy(speed);
  6206. map.panBy(movement, {animate: false});
  6207. this._draggable._newPos._add(movement);
  6208. this._draggable._startPos._add(movement);
  6209. setPosition(marker._icon, this._draggable._newPos);
  6210. this._onDrag(e);
  6211. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  6212. }
  6213. },
  6214. _onDragStart: function () {
  6215. // @section Dragging events
  6216. // @event dragstart: Event
  6217. // Fired when the user starts dragging the marker.
  6218. // @event movestart: Event
  6219. // Fired when the marker starts moving (because of dragging).
  6220. this._oldLatLng = this._marker.getLatLng();
  6221. // When using ES6 imports it could not be set when `Popup` was not imported as well
  6222. this._marker.closePopup && this._marker.closePopup();
  6223. this._marker
  6224. .fire('movestart')
  6225. .fire('dragstart');
  6226. },
  6227. _onPreDrag: function (e) {
  6228. if (this._marker.options.autoPan) {
  6229. cancelAnimFrame(this._panRequest);
  6230. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  6231. }
  6232. },
  6233. _onDrag: function (e) {
  6234. var marker = this._marker,
  6235. shadow = marker._shadow,
  6236. iconPos = getPosition(marker._icon),
  6237. latlng = marker._map.layerPointToLatLng(iconPos);
  6238. // update shadow position
  6239. if (shadow) {
  6240. setPosition(shadow, iconPos);
  6241. }
  6242. marker._latlng = latlng;
  6243. e.latlng = latlng;
  6244. e.oldLatLng = this._oldLatLng;
  6245. // @event drag: Event
  6246. // Fired repeatedly while the user drags the marker.
  6247. marker
  6248. .fire('move', e)
  6249. .fire('drag', e);
  6250. },
  6251. _onDragEnd: function (e) {
  6252. // @event dragend: DragEndEvent
  6253. // Fired when the user stops dragging the marker.
  6254. cancelAnimFrame(this._panRequest);
  6255. // @event moveend: Event
  6256. // Fired when the marker stops moving (because of dragging).
  6257. delete this._oldLatLng;
  6258. this._marker
  6259. .fire('moveend')
  6260. .fire('dragend', e);
  6261. }
  6262. });
  6263. /*
  6264. * @class Marker
  6265. * @inherits Interactive layer
  6266. * @aka L.Marker
  6267. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  6268. *
  6269. * @example
  6270. *
  6271. * ```js
  6272. * L.marker([50.5, 30.5]).addTo(map);
  6273. * ```
  6274. */
  6275. var Marker = Layer.extend({
  6276. // @section
  6277. // @aka Marker options
  6278. options: {
  6279. // @option icon: Icon = *
  6280. // Icon instance to use for rendering the marker.
  6281. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  6282. // If not specified, a common instance of `L.Icon.Default` is used.
  6283. icon: new IconDefault(),
  6284. // Option inherited from "Interactive layer" abstract class
  6285. interactive: true,
  6286. // @option keyboard: Boolean = true
  6287. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  6288. keyboard: true,
  6289. // @option title: String = ''
  6290. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  6291. // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
  6292. title: '',
  6293. // @option alt: String = 'Marker'
  6294. // Text for the `alt` attribute of the icon image.
  6295. // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
  6296. alt: 'Marker',
  6297. // @option zIndexOffset: Number = 0
  6298. // 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).
  6299. zIndexOffset: 0,
  6300. // @option opacity: Number = 1.0
  6301. // The opacity of the marker.
  6302. opacity: 1,
  6303. // @option riseOnHover: Boolean = false
  6304. // If `true`, the marker will get on top of others when you hover the mouse over it.
  6305. riseOnHover: false,
  6306. // @option riseOffset: Number = 250
  6307. // The z-index offset used for the `riseOnHover` feature.
  6308. riseOffset: 250,
  6309. // @option pane: String = 'markerPane'
  6310. // `Map pane` where the markers icon will be added.
  6311. pane: 'markerPane',
  6312. // @option shadowPane: String = 'shadowPane'
  6313. // `Map pane` where the markers shadow will be added.
  6314. shadowPane: 'shadowPane',
  6315. // @option bubblingMouseEvents: Boolean = false
  6316. // When `true`, a mouse event on this marker will trigger the same event on the map
  6317. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6318. bubblingMouseEvents: false,
  6319. // @option autoPanOnFocus: Boolean = true
  6320. // When `true`, the map will pan whenever the marker is focused (via
  6321. // e.g. pressing `tab` on the keyboard) to ensure the marker is
  6322. // visible within the map's bounds
  6323. autoPanOnFocus: true,
  6324. // @section Draggable marker options
  6325. // @option draggable: Boolean = false
  6326. // Whether the marker is draggable with mouse/touch or not.
  6327. draggable: false,
  6328. // @option autoPan: Boolean = false
  6329. // Whether to pan the map when dragging this marker near its edge or not.
  6330. autoPan: false,
  6331. // @option autoPanPadding: Point = Point(50, 50)
  6332. // Distance (in pixels to the left/right and to the top/bottom) of the
  6333. // map edge to start panning the map.
  6334. autoPanPadding: [50, 50],
  6335. // @option autoPanSpeed: Number = 10
  6336. // Number of pixels the map should pan by.
  6337. autoPanSpeed: 10
  6338. },
  6339. /* @section
  6340. *
  6341. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  6342. */
  6343. initialize: function (latlng, options) {
  6344. setOptions(this, options);
  6345. this._latlng = toLatLng(latlng);
  6346. },
  6347. onAdd: function (map) {
  6348. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  6349. if (this._zoomAnimated) {
  6350. map.on('zoomanim', this._animateZoom, this);
  6351. }
  6352. this._initIcon();
  6353. this.update();
  6354. },
  6355. onRemove: function (map) {
  6356. if (this.dragging && this.dragging.enabled()) {
  6357. this.options.draggable = true;
  6358. this.dragging.removeHooks();
  6359. }
  6360. delete this.dragging;
  6361. if (this._zoomAnimated) {
  6362. map.off('zoomanim', this._animateZoom, this);
  6363. }
  6364. this._removeIcon();
  6365. this._removeShadow();
  6366. },
  6367. getEvents: function () {
  6368. return {
  6369. zoom: this.update,
  6370. viewreset: this.update
  6371. };
  6372. },
  6373. // @method getLatLng: LatLng
  6374. // Returns the current geographical position of the marker.
  6375. getLatLng: function () {
  6376. return this._latlng;
  6377. },
  6378. // @method setLatLng(latlng: LatLng): this
  6379. // Changes the marker position to the given point.
  6380. setLatLng: function (latlng) {
  6381. var oldLatLng = this._latlng;
  6382. this._latlng = toLatLng(latlng);
  6383. this.update();
  6384. // @event move: Event
  6385. // 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`.
  6386. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6387. },
  6388. // @method setZIndexOffset(offset: Number): this
  6389. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6390. setZIndexOffset: function (offset) {
  6391. this.options.zIndexOffset = offset;
  6392. return this.update();
  6393. },
  6394. // @method getIcon: Icon
  6395. // Returns the current icon used by the marker
  6396. getIcon: function () {
  6397. return this.options.icon;
  6398. },
  6399. // @method setIcon(icon: Icon): this
  6400. // Changes the marker icon.
  6401. setIcon: function (icon) {
  6402. this.options.icon = icon;
  6403. if (this._map) {
  6404. this._initIcon();
  6405. this.update();
  6406. }
  6407. if (this._popup) {
  6408. this.bindPopup(this._popup, this._popup.options);
  6409. }
  6410. return this;
  6411. },
  6412. getElement: function () {
  6413. return this._icon;
  6414. },
  6415. update: function () {
  6416. if (this._icon && this._map) {
  6417. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6418. this._setPos(pos);
  6419. }
  6420. return this;
  6421. },
  6422. _initIcon: function () {
  6423. var options = this.options,
  6424. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6425. var icon = options.icon.createIcon(this._icon),
  6426. addIcon = false;
  6427. // if we're not reusing the icon, remove the old one and init new one
  6428. if (icon !== this._icon) {
  6429. if (this._icon) {
  6430. this._removeIcon();
  6431. }
  6432. addIcon = true;
  6433. if (options.title) {
  6434. icon.title = options.title;
  6435. }
  6436. if (icon.tagName === 'IMG') {
  6437. icon.alt = options.alt || '';
  6438. }
  6439. }
  6440. addClass(icon, classToAdd);
  6441. if (options.keyboard) {
  6442. icon.tabIndex = '0';
  6443. icon.setAttribute('role', 'button');
  6444. }
  6445. this._icon = icon;
  6446. if (options.riseOnHover) {
  6447. this.on({
  6448. mouseover: this._bringToFront,
  6449. mouseout: this._resetZIndex
  6450. });
  6451. }
  6452. if (this.options.autoPanOnFocus) {
  6453. on(icon, 'focus', this._panOnFocus, this);
  6454. }
  6455. var newShadow = options.icon.createShadow(this._shadow),
  6456. addShadow = false;
  6457. if (newShadow !== this._shadow) {
  6458. this._removeShadow();
  6459. addShadow = true;
  6460. }
  6461. if (newShadow) {
  6462. addClass(newShadow, classToAdd);
  6463. newShadow.alt = '';
  6464. }
  6465. this._shadow = newShadow;
  6466. if (options.opacity < 1) {
  6467. this._updateOpacity();
  6468. }
  6469. if (addIcon) {
  6470. this.getPane().appendChild(this._icon);
  6471. }
  6472. this._initInteraction();
  6473. if (newShadow && addShadow) {
  6474. this.getPane(options.shadowPane).appendChild(this._shadow);
  6475. }
  6476. },
  6477. _removeIcon: function () {
  6478. if (this.options.riseOnHover) {
  6479. this.off({
  6480. mouseover: this._bringToFront,
  6481. mouseout: this._resetZIndex
  6482. });
  6483. }
  6484. if (this.options.autoPanOnFocus) {
  6485. off(this._icon, 'focus', this._panOnFocus, this);
  6486. }
  6487. remove(this._icon);
  6488. this.removeInteractiveTarget(this._icon);
  6489. this._icon = null;
  6490. },
  6491. _removeShadow: function () {
  6492. if (this._shadow) {
  6493. remove(this._shadow);
  6494. }
  6495. this._shadow = null;
  6496. },
  6497. _setPos: function (pos) {
  6498. if (this._icon) {
  6499. setPosition(this._icon, pos);
  6500. }
  6501. if (this._shadow) {
  6502. setPosition(this._shadow, pos);
  6503. }
  6504. this._zIndex = pos.y + this.options.zIndexOffset;
  6505. this._resetZIndex();
  6506. },
  6507. _updateZIndex: function (offset) {
  6508. if (this._icon) {
  6509. this._icon.style.zIndex = this._zIndex + offset;
  6510. }
  6511. },
  6512. _animateZoom: function (opt) {
  6513. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6514. this._setPos(pos);
  6515. },
  6516. _initInteraction: function () {
  6517. if (!this.options.interactive) { return; }
  6518. addClass(this._icon, 'leaflet-interactive');
  6519. this.addInteractiveTarget(this._icon);
  6520. if (MarkerDrag) {
  6521. var draggable = this.options.draggable;
  6522. if (this.dragging) {
  6523. draggable = this.dragging.enabled();
  6524. this.dragging.disable();
  6525. }
  6526. this.dragging = new MarkerDrag(this);
  6527. if (draggable) {
  6528. this.dragging.enable();
  6529. }
  6530. }
  6531. },
  6532. // @method setOpacity(opacity: Number): this
  6533. // Changes the opacity of the marker.
  6534. setOpacity: function (opacity) {
  6535. this.options.opacity = opacity;
  6536. if (this._map) {
  6537. this._updateOpacity();
  6538. }
  6539. return this;
  6540. },
  6541. _updateOpacity: function () {
  6542. var opacity = this.options.opacity;
  6543. if (this._icon) {
  6544. setOpacity(this._icon, opacity);
  6545. }
  6546. if (this._shadow) {
  6547. setOpacity(this._shadow, opacity);
  6548. }
  6549. },
  6550. _bringToFront: function () {
  6551. this._updateZIndex(this.options.riseOffset);
  6552. },
  6553. _resetZIndex: function () {
  6554. this._updateZIndex(0);
  6555. },
  6556. _panOnFocus: function () {
  6557. var map = this._map;
  6558. if (!map) { return; }
  6559. var iconOpts = this.options.icon.options;
  6560. var size = iconOpts.iconSize ? toPoint(iconOpts.iconSize) : toPoint(0, 0);
  6561. var anchor = iconOpts.iconAnchor ? toPoint(iconOpts.iconAnchor) : toPoint(0, 0);
  6562. map.panInside(this._latlng, {
  6563. paddingTopLeft: anchor,
  6564. paddingBottomRight: size.subtract(anchor)
  6565. });
  6566. },
  6567. _getPopupAnchor: function () {
  6568. return this.options.icon.options.popupAnchor;
  6569. },
  6570. _getTooltipAnchor: function () {
  6571. return this.options.icon.options.tooltipAnchor;
  6572. }
  6573. });
  6574. // factory L.marker(latlng: LatLng, options? : Marker options)
  6575. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6576. // Instantiates a Marker object given a geographical point and optionally an options object.
  6577. function marker(latlng, options) {
  6578. return new Marker(latlng, options);
  6579. }
  6580. /*
  6581. * @class Path
  6582. * @aka L.Path
  6583. * @inherits Interactive layer
  6584. *
  6585. * An abstract class that contains options and constants shared between vector
  6586. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6587. */
  6588. var Path = Layer.extend({
  6589. // @section
  6590. // @aka Path options
  6591. options: {
  6592. // @option stroke: Boolean = true
  6593. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6594. stroke: true,
  6595. // @option color: String = '#3388ff'
  6596. // Stroke color
  6597. color: '#3388ff',
  6598. // @option weight: Number = 3
  6599. // Stroke width in pixels
  6600. weight: 3,
  6601. // @option opacity: Number = 1.0
  6602. // Stroke opacity
  6603. opacity: 1,
  6604. // @option lineCap: String= 'round'
  6605. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6606. lineCap: 'round',
  6607. // @option lineJoin: String = 'round'
  6608. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6609. lineJoin: 'round',
  6610. // @option dashArray: String = null
  6611. // 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).
  6612. dashArray: null,
  6613. // @option dashOffset: String = null
  6614. // 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).
  6615. dashOffset: null,
  6616. // @option fill: Boolean = depends
  6617. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6618. fill: false,
  6619. // @option fillColor: String = *
  6620. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6621. fillColor: null,
  6622. // @option fillOpacity: Number = 0.2
  6623. // Fill opacity.
  6624. fillOpacity: 0.2,
  6625. // @option fillRule: String = 'evenodd'
  6626. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6627. fillRule: 'evenodd',
  6628. // className: '',
  6629. // Option inherited from "Interactive layer" abstract class
  6630. interactive: true,
  6631. // @option bubblingMouseEvents: Boolean = true
  6632. // When `true`, a mouse event on this path will trigger the same event on the map
  6633. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6634. bubblingMouseEvents: true
  6635. },
  6636. beforeAdd: function (map) {
  6637. // Renderer is set here because we need to call renderer.getEvents
  6638. // before this.getEvents.
  6639. this._renderer = map.getRenderer(this);
  6640. },
  6641. onAdd: function () {
  6642. this._renderer._initPath(this);
  6643. this._reset();
  6644. this._renderer._addPath(this);
  6645. },
  6646. onRemove: function () {
  6647. this._renderer._removePath(this);
  6648. },
  6649. // @method redraw(): this
  6650. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6651. redraw: function () {
  6652. if (this._map) {
  6653. this._renderer._updatePath(this);
  6654. }
  6655. return this;
  6656. },
  6657. // @method setStyle(style: Path options): this
  6658. // Changes the appearance of a Path based on the options in the `Path options` object.
  6659. setStyle: function (style) {
  6660. setOptions(this, style);
  6661. if (this._renderer) {
  6662. this._renderer._updateStyle(this);
  6663. if (this.options.stroke && style && Object.prototype.hasOwnProperty.call(style, 'weight')) {
  6664. this._updateBounds();
  6665. }
  6666. }
  6667. return this;
  6668. },
  6669. // @method bringToFront(): this
  6670. // Brings the layer to the top of all path layers.
  6671. bringToFront: function () {
  6672. if (this._renderer) {
  6673. this._renderer._bringToFront(this);
  6674. }
  6675. return this;
  6676. },
  6677. // @method bringToBack(): this
  6678. // Brings the layer to the bottom of all path layers.
  6679. bringToBack: function () {
  6680. if (this._renderer) {
  6681. this._renderer._bringToBack(this);
  6682. }
  6683. return this;
  6684. },
  6685. getElement: function () {
  6686. return this._path;
  6687. },
  6688. _reset: function () {
  6689. // defined in child classes
  6690. this._project();
  6691. this._update();
  6692. },
  6693. _clickTolerance: function () {
  6694. // used when doing hit detection for Canvas layers
  6695. return (this.options.stroke ? this.options.weight / 2 : 0) +
  6696. (this._renderer.options.tolerance || 0);
  6697. }
  6698. });
  6699. /*
  6700. * @class CircleMarker
  6701. * @aka L.CircleMarker
  6702. * @inherits Path
  6703. *
  6704. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6705. */
  6706. var CircleMarker = Path.extend({
  6707. // @section
  6708. // @aka CircleMarker options
  6709. options: {
  6710. fill: true,
  6711. // @option radius: Number = 10
  6712. // Radius of the circle marker, in pixels
  6713. radius: 10
  6714. },
  6715. initialize: function (latlng, options) {
  6716. setOptions(this, options);
  6717. this._latlng = toLatLng(latlng);
  6718. this._radius = this.options.radius;
  6719. },
  6720. // @method setLatLng(latLng: LatLng): this
  6721. // Sets the position of a circle marker to a new location.
  6722. setLatLng: function (latlng) {
  6723. var oldLatLng = this._latlng;
  6724. this._latlng = toLatLng(latlng);
  6725. this.redraw();
  6726. // @event move: Event
  6727. // Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
  6728. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6729. },
  6730. // @method getLatLng(): LatLng
  6731. // Returns the current geographical position of the circle marker
  6732. getLatLng: function () {
  6733. return this._latlng;
  6734. },
  6735. // @method setRadius(radius: Number): this
  6736. // Sets the radius of a circle marker. Units are in pixels.
  6737. setRadius: function (radius) {
  6738. this.options.radius = this._radius = radius;
  6739. return this.redraw();
  6740. },
  6741. // @method getRadius(): Number
  6742. // Returns the current radius of the circle
  6743. getRadius: function () {
  6744. return this._radius;
  6745. },
  6746. setStyle : function (options) {
  6747. var radius = options && options.radius || this._radius;
  6748. Path.prototype.setStyle.call(this, options);
  6749. this.setRadius(radius);
  6750. return this;
  6751. },
  6752. _project: function () {
  6753. this._point = this._map.latLngToLayerPoint(this._latlng);
  6754. this._updateBounds();
  6755. },
  6756. _updateBounds: function () {
  6757. var r = this._radius,
  6758. r2 = this._radiusY || r,
  6759. w = this._clickTolerance(),
  6760. p = [r + w, r2 + w];
  6761. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6762. },
  6763. _update: function () {
  6764. if (this._map) {
  6765. this._updatePath();
  6766. }
  6767. },
  6768. _updatePath: function () {
  6769. this._renderer._updateCircle(this);
  6770. },
  6771. _empty: function () {
  6772. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6773. },
  6774. // Needed by the `Canvas` renderer for interactivity
  6775. _containsPoint: function (p) {
  6776. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6777. }
  6778. });
  6779. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6780. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6781. function circleMarker(latlng, options) {
  6782. return new CircleMarker(latlng, options);
  6783. }
  6784. /*
  6785. * @class Circle
  6786. * @aka L.Circle
  6787. * @inherits CircleMarker
  6788. *
  6789. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6790. *
  6791. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6792. *
  6793. * @example
  6794. *
  6795. * ```js
  6796. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6797. * ```
  6798. */
  6799. var Circle = CircleMarker.extend({
  6800. initialize: function (latlng, options, legacyOptions) {
  6801. if (typeof options === 'number') {
  6802. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6803. options = extend({}, legacyOptions, {radius: options});
  6804. }
  6805. setOptions(this, options);
  6806. this._latlng = toLatLng(latlng);
  6807. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6808. // @section
  6809. // @aka Circle options
  6810. // @option radius: Number; Radius of the circle, in meters.
  6811. this._mRadius = this.options.radius;
  6812. },
  6813. // @method setRadius(radius: Number): this
  6814. // Sets the radius of a circle. Units are in meters.
  6815. setRadius: function (radius) {
  6816. this._mRadius = radius;
  6817. return this.redraw();
  6818. },
  6819. // @method getRadius(): Number
  6820. // Returns the current radius of a circle. Units are in meters.
  6821. getRadius: function () {
  6822. return this._mRadius;
  6823. },
  6824. // @method getBounds(): LatLngBounds
  6825. // Returns the `LatLngBounds` of the path.
  6826. getBounds: function () {
  6827. var half = [this._radius, this._radiusY || this._radius];
  6828. return new LatLngBounds(
  6829. this._map.layerPointToLatLng(this._point.subtract(half)),
  6830. this._map.layerPointToLatLng(this._point.add(half)));
  6831. },
  6832. setStyle: Path.prototype.setStyle,
  6833. _project: function () {
  6834. var lng = this._latlng.lng,
  6835. lat = this._latlng.lat,
  6836. map = this._map,
  6837. crs = map.options.crs;
  6838. if (crs.distance === Earth.distance) {
  6839. var d = Math.PI / 180,
  6840. latR = (this._mRadius / Earth.R) / d,
  6841. top = map.project([lat + latR, lng]),
  6842. bottom = map.project([lat - latR, lng]),
  6843. p = top.add(bottom).divideBy(2),
  6844. lat2 = map.unproject(p).lat,
  6845. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6846. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6847. if (isNaN(lngR) || lngR === 0) {
  6848. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6849. }
  6850. this._point = p.subtract(map.getPixelOrigin());
  6851. this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
  6852. this._radiusY = p.y - top.y;
  6853. } else {
  6854. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6855. this._point = map.latLngToLayerPoint(this._latlng);
  6856. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6857. }
  6858. this._updateBounds();
  6859. }
  6860. });
  6861. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6862. // Instantiates a circle object given a geographical point, and an options object
  6863. // which contains the circle radius.
  6864. // @alternative
  6865. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6866. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6867. // Do not use in new applications or plugins.
  6868. function circle(latlng, options, legacyOptions) {
  6869. return new Circle(latlng, options, legacyOptions);
  6870. }
  6871. /*
  6872. * @class Polyline
  6873. * @aka L.Polyline
  6874. * @inherits Path
  6875. *
  6876. * A class for drawing polyline overlays on a map. Extends `Path`.
  6877. *
  6878. * @example
  6879. *
  6880. * ```js
  6881. * // create a red polyline from an array of LatLng points
  6882. * var latlngs = [
  6883. * [45.51, -122.68],
  6884. * [37.77, -122.43],
  6885. * [34.04, -118.2]
  6886. * ];
  6887. *
  6888. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6889. *
  6890. * // zoom the map to the polyline
  6891. * map.fitBounds(polyline.getBounds());
  6892. * ```
  6893. *
  6894. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6895. *
  6896. * ```js
  6897. * // create a red polyline from an array of arrays of LatLng points
  6898. * var latlngs = [
  6899. * [[45.51, -122.68],
  6900. * [37.77, -122.43],
  6901. * [34.04, -118.2]],
  6902. * [[40.78, -73.91],
  6903. * [41.83, -87.62],
  6904. * [32.76, -96.72]]
  6905. * ];
  6906. * ```
  6907. */
  6908. var Polyline = Path.extend({
  6909. // @section
  6910. // @aka Polyline options
  6911. options: {
  6912. // @option smoothFactor: Number = 1.0
  6913. // How much to simplify the polyline on each zoom level. More means
  6914. // better performance and smoother look, and less means more accurate representation.
  6915. smoothFactor: 1.0,
  6916. // @option noClip: Boolean = false
  6917. // Disable polyline clipping.
  6918. noClip: false
  6919. },
  6920. initialize: function (latlngs, options) {
  6921. setOptions(this, options);
  6922. this._setLatLngs(latlngs);
  6923. },
  6924. // @method getLatLngs(): LatLng[]
  6925. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6926. getLatLngs: function () {
  6927. return this._latlngs;
  6928. },
  6929. // @method setLatLngs(latlngs: LatLng[]): this
  6930. // Replaces all the points in the polyline with the given array of geographical points.
  6931. setLatLngs: function (latlngs) {
  6932. this._setLatLngs(latlngs);
  6933. return this.redraw();
  6934. },
  6935. // @method isEmpty(): Boolean
  6936. // Returns `true` if the Polyline has no LatLngs.
  6937. isEmpty: function () {
  6938. return !this._latlngs.length;
  6939. },
  6940. // @method closestLayerPoint(p: Point): Point
  6941. // Returns the point closest to `p` on the Polyline.
  6942. closestLayerPoint: function (p) {
  6943. var minDistance = Infinity,
  6944. minPoint = null,
  6945. closest = _sqClosestPointOnSegment,
  6946. p1, p2;
  6947. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6948. var points = this._parts[j];
  6949. for (var i = 1, len = points.length; i < len; i++) {
  6950. p1 = points[i - 1];
  6951. p2 = points[i];
  6952. var sqDist = closest(p, p1, p2, true);
  6953. if (sqDist < minDistance) {
  6954. minDistance = sqDist;
  6955. minPoint = closest(p, p1, p2);
  6956. }
  6957. }
  6958. }
  6959. if (minPoint) {
  6960. minPoint.distance = Math.sqrt(minDistance);
  6961. }
  6962. return minPoint;
  6963. },
  6964. // @method getCenter(): LatLng
  6965. // Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6966. getCenter: function () {
  6967. // throws error when not yet added to map as this center calculation requires projected coordinates
  6968. if (!this._map) {
  6969. throw new Error('Must add layer to map before using getCenter()');
  6970. }
  6971. return polylineCenter(this._defaultShape(), this._map.options.crs);
  6972. },
  6973. // @method getBounds(): LatLngBounds
  6974. // Returns the `LatLngBounds` of the path.
  6975. getBounds: function () {
  6976. return this._bounds;
  6977. },
  6978. // @method addLatLng(latlng: LatLng, latlngs?: LatLng[]): this
  6979. // Adds a given point to the polyline. By default, adds to the first ring of
  6980. // the polyline in case of a multi-polyline, but can be overridden by passing
  6981. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6982. addLatLng: function (latlng, latlngs) {
  6983. latlngs = latlngs || this._defaultShape();
  6984. latlng = toLatLng(latlng);
  6985. latlngs.push(latlng);
  6986. this._bounds.extend(latlng);
  6987. return this.redraw();
  6988. },
  6989. _setLatLngs: function (latlngs) {
  6990. this._bounds = new LatLngBounds();
  6991. this._latlngs = this._convertLatLngs(latlngs);
  6992. },
  6993. _defaultShape: function () {
  6994. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6995. },
  6996. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6997. _convertLatLngs: function (latlngs) {
  6998. var result = [],
  6999. flat = isFlat(latlngs);
  7000. for (var i = 0, len = latlngs.length; i < len; i++) {
  7001. if (flat) {
  7002. result[i] = toLatLng(latlngs[i]);
  7003. this._bounds.extend(result[i]);
  7004. } else {
  7005. result[i] = this._convertLatLngs(latlngs[i]);
  7006. }
  7007. }
  7008. return result;
  7009. },
  7010. _project: function () {
  7011. var pxBounds = new Bounds();
  7012. this._rings = [];
  7013. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  7014. if (this._bounds.isValid() && pxBounds.isValid()) {
  7015. this._rawPxBounds = pxBounds;
  7016. this._updateBounds();
  7017. }
  7018. },
  7019. _updateBounds: function () {
  7020. var w = this._clickTolerance(),
  7021. p = new Point(w, w);
  7022. if (!this._rawPxBounds) {
  7023. return;
  7024. }
  7025. this._pxBounds = new Bounds([
  7026. this._rawPxBounds.min.subtract(p),
  7027. this._rawPxBounds.max.add(p)
  7028. ]);
  7029. },
  7030. // recursively turns latlngs into a set of rings with projected coordinates
  7031. _projectLatlngs: function (latlngs, result, projectedBounds) {
  7032. var flat = latlngs[0] instanceof LatLng,
  7033. len = latlngs.length,
  7034. i, ring;
  7035. if (flat) {
  7036. ring = [];
  7037. for (i = 0; i < len; i++) {
  7038. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  7039. projectedBounds.extend(ring[i]);
  7040. }
  7041. result.push(ring);
  7042. } else {
  7043. for (i = 0; i < len; i++) {
  7044. this._projectLatlngs(latlngs[i], result, projectedBounds);
  7045. }
  7046. }
  7047. },
  7048. // clip polyline by renderer bounds so that we have less to render for performance
  7049. _clipPoints: function () {
  7050. var bounds = this._renderer._bounds;
  7051. this._parts = [];
  7052. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7053. return;
  7054. }
  7055. if (this.options.noClip) {
  7056. this._parts = this._rings;
  7057. return;
  7058. }
  7059. var parts = this._parts,
  7060. i, j, k, len, len2, segment, points;
  7061. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  7062. points = this._rings[i];
  7063. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  7064. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  7065. if (!segment) { continue; }
  7066. parts[k] = parts[k] || [];
  7067. parts[k].push(segment[0]);
  7068. // if segment goes out of screen, or it's the last one, it's the end of the line part
  7069. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  7070. parts[k].push(segment[1]);
  7071. k++;
  7072. }
  7073. }
  7074. }
  7075. },
  7076. // simplify each clipped part of the polyline for performance
  7077. _simplifyPoints: function () {
  7078. var parts = this._parts,
  7079. tolerance = this.options.smoothFactor;
  7080. for (var i = 0, len = parts.length; i < len; i++) {
  7081. parts[i] = simplify(parts[i], tolerance);
  7082. }
  7083. },
  7084. _update: function () {
  7085. if (!this._map) { return; }
  7086. this._clipPoints();
  7087. this._simplifyPoints();
  7088. this._updatePath();
  7089. },
  7090. _updatePath: function () {
  7091. this._renderer._updatePoly(this);
  7092. },
  7093. // Needed by the `Canvas` renderer for interactivity
  7094. _containsPoint: function (p, closed) {
  7095. var i, j, k, len, len2, part,
  7096. w = this._clickTolerance();
  7097. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  7098. // hit detection for polylines
  7099. for (i = 0, len = this._parts.length; i < len; i++) {
  7100. part = this._parts[i];
  7101. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7102. if (!closed && (j === 0)) { continue; }
  7103. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  7104. return true;
  7105. }
  7106. }
  7107. }
  7108. return false;
  7109. }
  7110. });
  7111. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  7112. // Instantiates a polyline object given an array of geographical points and
  7113. // optionally an options object. You can create a `Polyline` object with
  7114. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  7115. // of geographic points.
  7116. function polyline(latlngs, options) {
  7117. return new Polyline(latlngs, options);
  7118. }
  7119. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  7120. Polyline._flat = _flat;
  7121. /*
  7122. * @class Polygon
  7123. * @aka L.Polygon
  7124. * @inherits Polyline
  7125. *
  7126. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  7127. *
  7128. * 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.
  7129. *
  7130. *
  7131. * @example
  7132. *
  7133. * ```js
  7134. * // create a red polygon from an array of LatLng points
  7135. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  7136. *
  7137. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  7138. *
  7139. * // zoom the map to the polygon
  7140. * map.fitBounds(polygon.getBounds());
  7141. * ```
  7142. *
  7143. * 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:
  7144. *
  7145. * ```js
  7146. * var latlngs = [
  7147. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7148. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7149. * ];
  7150. * ```
  7151. *
  7152. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  7153. *
  7154. * ```js
  7155. * var latlngs = [
  7156. * [ // first polygon
  7157. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7158. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7159. * ],
  7160. * [ // second polygon
  7161. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  7162. * ]
  7163. * ];
  7164. * ```
  7165. */
  7166. var Polygon = Polyline.extend({
  7167. options: {
  7168. fill: true
  7169. },
  7170. isEmpty: function () {
  7171. return !this._latlngs.length || !this._latlngs[0].length;
  7172. },
  7173. // @method getCenter(): LatLng
  7174. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the Polygon.
  7175. getCenter: function () {
  7176. // throws error when not yet added to map as this center calculation requires projected coordinates
  7177. if (!this._map) {
  7178. throw new Error('Must add layer to map before using getCenter()');
  7179. }
  7180. return polygonCenter(this._defaultShape(), this._map.options.crs);
  7181. },
  7182. _convertLatLngs: function (latlngs) {
  7183. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  7184. len = result.length;
  7185. // remove last point if it equals first one
  7186. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  7187. result.pop();
  7188. }
  7189. return result;
  7190. },
  7191. _setLatLngs: function (latlngs) {
  7192. Polyline.prototype._setLatLngs.call(this, latlngs);
  7193. if (isFlat(this._latlngs)) {
  7194. this._latlngs = [this._latlngs];
  7195. }
  7196. },
  7197. _defaultShape: function () {
  7198. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  7199. },
  7200. _clipPoints: function () {
  7201. // polygons need a different clipping algorithm so we redefine that
  7202. var bounds = this._renderer._bounds,
  7203. w = this.options.weight,
  7204. p = new Point(w, w);
  7205. // increase clip padding by stroke width to avoid stroke on clip edges
  7206. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  7207. this._parts = [];
  7208. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7209. return;
  7210. }
  7211. if (this.options.noClip) {
  7212. this._parts = this._rings;
  7213. return;
  7214. }
  7215. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  7216. clipped = clipPolygon(this._rings[i], bounds, true);
  7217. if (clipped.length) {
  7218. this._parts.push(clipped);
  7219. }
  7220. }
  7221. },
  7222. _updatePath: function () {
  7223. this._renderer._updatePoly(this, true);
  7224. },
  7225. // Needed by the `Canvas` renderer for interactivity
  7226. _containsPoint: function (p) {
  7227. var inside = false,
  7228. part, p1, p2, i, j, k, len, len2;
  7229. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  7230. // ray casting algorithm for detecting if point is in polygon
  7231. for (i = 0, len = this._parts.length; i < len; i++) {
  7232. part = this._parts[i];
  7233. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7234. p1 = part[j];
  7235. p2 = part[k];
  7236. 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)) {
  7237. inside = !inside;
  7238. }
  7239. }
  7240. }
  7241. // also check if it's on polygon stroke
  7242. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  7243. }
  7244. });
  7245. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  7246. function polygon(latlngs, options) {
  7247. return new Polygon(latlngs, options);
  7248. }
  7249. /*
  7250. * @class GeoJSON
  7251. * @aka L.GeoJSON
  7252. * @inherits FeatureGroup
  7253. *
  7254. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  7255. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  7256. *
  7257. * @example
  7258. *
  7259. * ```js
  7260. * L.geoJSON(data, {
  7261. * style: function (feature) {
  7262. * return {color: feature.properties.color};
  7263. * }
  7264. * }).bindPopup(function (layer) {
  7265. * return layer.feature.properties.description;
  7266. * }).addTo(map);
  7267. * ```
  7268. */
  7269. var GeoJSON = FeatureGroup.extend({
  7270. /* @section
  7271. * @aka GeoJSON options
  7272. *
  7273. * @option pointToLayer: Function = *
  7274. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  7275. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  7276. * The default is to spawn a default `Marker`:
  7277. * ```js
  7278. * function(geoJsonPoint, latlng) {
  7279. * return L.marker(latlng);
  7280. * }
  7281. * ```
  7282. *
  7283. * @option style: Function = *
  7284. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  7285. * called internally when data is added.
  7286. * The default value is to not override any defaults:
  7287. * ```js
  7288. * function (geoJsonFeature) {
  7289. * return {}
  7290. * }
  7291. * ```
  7292. *
  7293. * @option onEachFeature: Function = *
  7294. * A `Function` that will be called once for each created `Feature`, after it has
  7295. * been created and styled. Useful for attaching events and popups to features.
  7296. * The default is to do nothing with the newly created layers:
  7297. * ```js
  7298. * function (feature, layer) {}
  7299. * ```
  7300. *
  7301. * @option filter: Function = *
  7302. * A `Function` that will be used to decide whether to include a feature or not.
  7303. * The default is to include all features:
  7304. * ```js
  7305. * function (geoJsonFeature) {
  7306. * return true;
  7307. * }
  7308. * ```
  7309. * Note: dynamically changing the `filter` option will have effect only on newly
  7310. * added data. It will _not_ re-evaluate already included features.
  7311. *
  7312. * @option coordsToLatLng: Function = *
  7313. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  7314. * The default is the `coordsToLatLng` static method.
  7315. *
  7316. * @option markersInheritOptions: Boolean = false
  7317. * Whether default Markers for "Point" type Features inherit from group options.
  7318. */
  7319. initialize: function (geojson, options) {
  7320. setOptions(this, options);
  7321. this._layers = {};
  7322. if (geojson) {
  7323. this.addData(geojson);
  7324. }
  7325. },
  7326. // @method addData( <GeoJSON> data ): this
  7327. // Adds a GeoJSON object to the layer.
  7328. addData: function (geojson) {
  7329. var features = isArray(geojson) ? geojson : geojson.features,
  7330. i, len, feature;
  7331. if (features) {
  7332. for (i = 0, len = features.length; i < len; i++) {
  7333. // only add this if geometry or geometries are set and not null
  7334. feature = features[i];
  7335. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  7336. this.addData(feature);
  7337. }
  7338. }
  7339. return this;
  7340. }
  7341. var options = this.options;
  7342. if (options.filter && !options.filter(geojson)) { return this; }
  7343. var layer = geometryToLayer(geojson, options);
  7344. if (!layer) {
  7345. return this;
  7346. }
  7347. layer.feature = asFeature(geojson);
  7348. layer.defaultOptions = layer.options;
  7349. this.resetStyle(layer);
  7350. if (options.onEachFeature) {
  7351. options.onEachFeature(geojson, layer);
  7352. }
  7353. return this.addLayer(layer);
  7354. },
  7355. // @method resetStyle( <Path> layer? ): this
  7356. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7357. // If `layer` is omitted, the style of all features in the current layer is reset.
  7358. resetStyle: function (layer) {
  7359. if (layer === undefined) {
  7360. return this.eachLayer(this.resetStyle, this);
  7361. }
  7362. // reset any custom styles
  7363. layer.options = extend({}, layer.defaultOptions);
  7364. this._setLayerStyle(layer, this.options.style);
  7365. return this;
  7366. },
  7367. // @method setStyle( <Function> style ): this
  7368. // Changes styles of GeoJSON vector layers with the given style function.
  7369. setStyle: function (style) {
  7370. return this.eachLayer(function (layer) {
  7371. this._setLayerStyle(layer, style);
  7372. }, this);
  7373. },
  7374. _setLayerStyle: function (layer, style) {
  7375. if (layer.setStyle) {
  7376. if (typeof style === 'function') {
  7377. style = style(layer.feature);
  7378. }
  7379. layer.setStyle(style);
  7380. }
  7381. }
  7382. });
  7383. // @section
  7384. // There are several static functions which can be called without instantiating L.GeoJSON:
  7385. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7386. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7387. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7388. // functions if provided as options.
  7389. function geometryToLayer(geojson, options) {
  7390. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7391. coords = geometry ? geometry.coordinates : null,
  7392. layers = [],
  7393. pointToLayer = options && options.pointToLayer,
  7394. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7395. latlng, latlngs, i, len;
  7396. if (!coords && !geometry) {
  7397. return null;
  7398. }
  7399. switch (geometry.type) {
  7400. case 'Point':
  7401. latlng = _coordsToLatLng(coords);
  7402. return _pointToLayer(pointToLayer, geojson, latlng, options);
  7403. case 'MultiPoint':
  7404. for (i = 0, len = coords.length; i < len; i++) {
  7405. latlng = _coordsToLatLng(coords[i]);
  7406. layers.push(_pointToLayer(pointToLayer, geojson, latlng, options));
  7407. }
  7408. return new FeatureGroup(layers);
  7409. case 'LineString':
  7410. case 'MultiLineString':
  7411. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7412. return new Polyline(latlngs, options);
  7413. case 'Polygon':
  7414. case 'MultiPolygon':
  7415. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7416. return new Polygon(latlngs, options);
  7417. case 'GeometryCollection':
  7418. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7419. var geoLayer = geometryToLayer({
  7420. geometry: geometry.geometries[i],
  7421. type: 'Feature',
  7422. properties: geojson.properties
  7423. }, options);
  7424. if (geoLayer) {
  7425. layers.push(geoLayer);
  7426. }
  7427. }
  7428. return new FeatureGroup(layers);
  7429. case 'FeatureCollection':
  7430. for (i = 0, len = geometry.features.length; i < len; i++) {
  7431. var featureLayer = geometryToLayer(geometry.features[i], options);
  7432. if (featureLayer) {
  7433. layers.push(featureLayer);
  7434. }
  7435. }
  7436. return new FeatureGroup(layers);
  7437. default:
  7438. throw new Error('Invalid GeoJSON object.');
  7439. }
  7440. }
  7441. function _pointToLayer(pointToLayerFn, geojson, latlng, options) {
  7442. return pointToLayerFn ?
  7443. pointToLayerFn(geojson, latlng) :
  7444. new Marker(latlng, options && options.markersInheritOptions && options);
  7445. }
  7446. // @function coordsToLatLng(coords: Array): LatLng
  7447. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7448. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7449. function coordsToLatLng(coords) {
  7450. return new LatLng(coords[1], coords[0], coords[2]);
  7451. }
  7452. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7453. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7454. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7455. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7456. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7457. var latlngs = [];
  7458. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7459. latlng = levelsDeep ?
  7460. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7461. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7462. latlngs.push(latlng);
  7463. }
  7464. return latlngs;
  7465. }
  7466. // @function latLngToCoords(latlng: LatLng, precision?: Number|false): Array
  7467. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7468. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function.
  7469. function latLngToCoords(latlng, precision) {
  7470. latlng = toLatLng(latlng);
  7471. return latlng.alt !== undefined ?
  7472. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7473. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7474. }
  7475. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean, precision?: Number|false): Array
  7476. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7477. // `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.
  7478. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function.
  7479. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7480. var coords = [];
  7481. for (var i = 0, len = latlngs.length; i < len; i++) {
  7482. // Check for flat arrays required to ensure unbalanced arrays are correctly converted in recursion
  7483. coords.push(levelsDeep ?
  7484. latLngsToCoords(latlngs[i], isFlat(latlngs[i]) ? 0 : levelsDeep - 1, closed, precision) :
  7485. latLngToCoords(latlngs[i], precision));
  7486. }
  7487. if (!levelsDeep && closed) {
  7488. coords.push(coords[0].slice());
  7489. }
  7490. return coords;
  7491. }
  7492. function getFeature(layer, newGeometry) {
  7493. return layer.feature ?
  7494. extend({}, layer.feature, {geometry: newGeometry}) :
  7495. asFeature(newGeometry);
  7496. }
  7497. // @function asFeature(geojson: Object): Object
  7498. // Normalize GeoJSON geometries/features into GeoJSON features.
  7499. function asFeature(geojson) {
  7500. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7501. return geojson;
  7502. }
  7503. return {
  7504. type: 'Feature',
  7505. properties: {},
  7506. geometry: geojson
  7507. };
  7508. }
  7509. var PointToGeoJSON = {
  7510. toGeoJSON: function (precision) {
  7511. return getFeature(this, {
  7512. type: 'Point',
  7513. coordinates: latLngToCoords(this.getLatLng(), precision)
  7514. });
  7515. }
  7516. };
  7517. // @namespace Marker
  7518. // @section Other methods
  7519. // @method toGeoJSON(precision?: Number|false): Object
  7520. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7521. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7522. Marker.include(PointToGeoJSON);
  7523. // @namespace CircleMarker
  7524. // @method toGeoJSON(precision?: Number|false): Object
  7525. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7526. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7527. Circle.include(PointToGeoJSON);
  7528. CircleMarker.include(PointToGeoJSON);
  7529. // @namespace Polyline
  7530. // @method toGeoJSON(precision?: Number|false): Object
  7531. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7532. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7533. Polyline.include({
  7534. toGeoJSON: function (precision) {
  7535. var multi = !isFlat(this._latlngs);
  7536. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7537. return getFeature(this, {
  7538. type: (multi ? 'Multi' : '') + 'LineString',
  7539. coordinates: coords
  7540. });
  7541. }
  7542. });
  7543. // @namespace Polygon
  7544. // @method toGeoJSON(precision?: Number|false): Object
  7545. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7546. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7547. Polygon.include({
  7548. toGeoJSON: function (precision) {
  7549. var holes = !isFlat(this._latlngs),
  7550. multi = holes && !isFlat(this._latlngs[0]);
  7551. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7552. if (!holes) {
  7553. coords = [coords];
  7554. }
  7555. return getFeature(this, {
  7556. type: (multi ? 'Multi' : '') + 'Polygon',
  7557. coordinates: coords
  7558. });
  7559. }
  7560. });
  7561. // @namespace LayerGroup
  7562. LayerGroup.include({
  7563. toMultiPoint: function (precision) {
  7564. var coords = [];
  7565. this.eachLayer(function (layer) {
  7566. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7567. });
  7568. return getFeature(this, {
  7569. type: 'MultiPoint',
  7570. coordinates: coords
  7571. });
  7572. },
  7573. // @method toGeoJSON(precision?: Number|false): Object
  7574. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7575. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7576. toGeoJSON: function (precision) {
  7577. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7578. if (type === 'MultiPoint') {
  7579. return this.toMultiPoint(precision);
  7580. }
  7581. var isGeometryCollection = type === 'GeometryCollection',
  7582. jsons = [];
  7583. this.eachLayer(function (layer) {
  7584. if (layer.toGeoJSON) {
  7585. var json = layer.toGeoJSON(precision);
  7586. if (isGeometryCollection) {
  7587. jsons.push(json.geometry);
  7588. } else {
  7589. var feature = asFeature(json);
  7590. // Squash nested feature collections
  7591. if (feature.type === 'FeatureCollection') {
  7592. jsons.push.apply(jsons, feature.features);
  7593. } else {
  7594. jsons.push(feature);
  7595. }
  7596. }
  7597. }
  7598. });
  7599. if (isGeometryCollection) {
  7600. return getFeature(this, {
  7601. geometries: jsons,
  7602. type: 'GeometryCollection'
  7603. });
  7604. }
  7605. return {
  7606. type: 'FeatureCollection',
  7607. features: jsons
  7608. };
  7609. }
  7610. });
  7611. // @namespace GeoJSON
  7612. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7613. // Creates a GeoJSON layer. Optionally accepts an object in
  7614. // [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map
  7615. // (you can alternatively add it later with `addData` method) and an `options` object.
  7616. function geoJSON(geojson, options) {
  7617. return new GeoJSON(geojson, options);
  7618. }
  7619. // Backward compatibility.
  7620. var geoJson = geoJSON;
  7621. /*
  7622. * @class ImageOverlay
  7623. * @aka L.ImageOverlay
  7624. * @inherits Interactive layer
  7625. *
  7626. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7627. *
  7628. * @example
  7629. *
  7630. * ```js
  7631. * var imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7632. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7633. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7634. * ```
  7635. */
  7636. var ImageOverlay = Layer.extend({
  7637. // @section
  7638. // @aka ImageOverlay options
  7639. options: {
  7640. // @option opacity: Number = 1.0
  7641. // The opacity of the image overlay.
  7642. opacity: 1,
  7643. // @option alt: String = ''
  7644. // Text for the `alt` attribute of the image (useful for accessibility).
  7645. alt: '',
  7646. // @option interactive: Boolean = false
  7647. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7648. interactive: false,
  7649. // @option crossOrigin: Boolean|String = false
  7650. // Whether the crossOrigin attribute will be added to the image.
  7651. // If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data.
  7652. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  7653. crossOrigin: false,
  7654. // @option errorOverlayUrl: String = ''
  7655. // URL to the overlay image to show in place of the overlay that failed to load.
  7656. errorOverlayUrl: '',
  7657. // @option zIndex: Number = 1
  7658. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
  7659. zIndex: 1,
  7660. // @option className: String = ''
  7661. // A custom class name to assign to the image. Empty by default.
  7662. className: ''
  7663. },
  7664. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7665. this._url = url;
  7666. this._bounds = toLatLngBounds(bounds);
  7667. setOptions(this, options);
  7668. },
  7669. onAdd: function () {
  7670. if (!this._image) {
  7671. this._initImage();
  7672. if (this.options.opacity < 1) {
  7673. this._updateOpacity();
  7674. }
  7675. }
  7676. if (this.options.interactive) {
  7677. addClass(this._image, 'leaflet-interactive');
  7678. this.addInteractiveTarget(this._image);
  7679. }
  7680. this.getPane().appendChild(this._image);
  7681. this._reset();
  7682. },
  7683. onRemove: function () {
  7684. remove(this._image);
  7685. if (this.options.interactive) {
  7686. this.removeInteractiveTarget(this._image);
  7687. }
  7688. },
  7689. // @method setOpacity(opacity: Number): this
  7690. // Sets the opacity of the overlay.
  7691. setOpacity: function (opacity) {
  7692. this.options.opacity = opacity;
  7693. if (this._image) {
  7694. this._updateOpacity();
  7695. }
  7696. return this;
  7697. },
  7698. setStyle: function (styleOpts) {
  7699. if (styleOpts.opacity) {
  7700. this.setOpacity(styleOpts.opacity);
  7701. }
  7702. return this;
  7703. },
  7704. // @method bringToFront(): this
  7705. // Brings the layer to the top of all overlays.
  7706. bringToFront: function () {
  7707. if (this._map) {
  7708. toFront(this._image);
  7709. }
  7710. return this;
  7711. },
  7712. // @method bringToBack(): this
  7713. // Brings the layer to the bottom of all overlays.
  7714. bringToBack: function () {
  7715. if (this._map) {
  7716. toBack(this._image);
  7717. }
  7718. return this;
  7719. },
  7720. // @method setUrl(url: String): this
  7721. // Changes the URL of the image.
  7722. setUrl: function (url) {
  7723. this._url = url;
  7724. if (this._image) {
  7725. this._image.src = url;
  7726. }
  7727. return this;
  7728. },
  7729. // @method setBounds(bounds: LatLngBounds): this
  7730. // Update the bounds that this ImageOverlay covers
  7731. setBounds: function (bounds) {
  7732. this._bounds = toLatLngBounds(bounds);
  7733. if (this._map) {
  7734. this._reset();
  7735. }
  7736. return this;
  7737. },
  7738. getEvents: function () {
  7739. var events = {
  7740. zoom: this._reset,
  7741. viewreset: this._reset
  7742. };
  7743. if (this._zoomAnimated) {
  7744. events.zoomanim = this._animateZoom;
  7745. }
  7746. return events;
  7747. },
  7748. // @method setZIndex(value: Number): this
  7749. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7750. setZIndex: function (value) {
  7751. this.options.zIndex = value;
  7752. this._updateZIndex();
  7753. return this;
  7754. },
  7755. // @method getBounds(): LatLngBounds
  7756. // Get the bounds that this ImageOverlay covers
  7757. getBounds: function () {
  7758. return this._bounds;
  7759. },
  7760. // @method getElement(): HTMLElement
  7761. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7762. // used by this overlay.
  7763. getElement: function () {
  7764. return this._image;
  7765. },
  7766. _initImage: function () {
  7767. var wasElementSupplied = this._url.tagName === 'IMG';
  7768. var img = this._image = wasElementSupplied ? this._url : create$1('img');
  7769. addClass(img, 'leaflet-image-layer');
  7770. if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
  7771. if (this.options.className) { addClass(img, this.options.className); }
  7772. img.onselectstart = falseFn;
  7773. img.onmousemove = falseFn;
  7774. // @event load: Event
  7775. // Fired when the ImageOverlay layer has loaded its image
  7776. img.onload = bind(this.fire, this, 'load');
  7777. img.onerror = bind(this._overlayOnError, this, 'error');
  7778. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  7779. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  7780. }
  7781. if (this.options.zIndex) {
  7782. this._updateZIndex();
  7783. }
  7784. if (wasElementSupplied) {
  7785. this._url = img.src;
  7786. return;
  7787. }
  7788. img.src = this._url;
  7789. img.alt = this.options.alt;
  7790. },
  7791. _animateZoom: function (e) {
  7792. var scale = this._map.getZoomScale(e.zoom),
  7793. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7794. setTransform(this._image, offset, scale);
  7795. },
  7796. _reset: function () {
  7797. var image = this._image,
  7798. bounds = new Bounds(
  7799. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7800. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7801. size = bounds.getSize();
  7802. setPosition(image, bounds.min);
  7803. image.style.width = size.x + 'px';
  7804. image.style.height = size.y + 'px';
  7805. },
  7806. _updateOpacity: function () {
  7807. setOpacity(this._image, this.options.opacity);
  7808. },
  7809. _updateZIndex: function () {
  7810. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7811. this._image.style.zIndex = this.options.zIndex;
  7812. }
  7813. },
  7814. _overlayOnError: function () {
  7815. // @event error: Event
  7816. // Fired when the ImageOverlay layer fails to load its image
  7817. this.fire('error');
  7818. var errorUrl = this.options.errorOverlayUrl;
  7819. if (errorUrl && this._url !== errorUrl) {
  7820. this._url = errorUrl;
  7821. this._image.src = errorUrl;
  7822. }
  7823. },
  7824. // @method getCenter(): LatLng
  7825. // Returns the center of the ImageOverlay.
  7826. getCenter: function () {
  7827. return this._bounds.getCenter();
  7828. }
  7829. });
  7830. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7831. // Instantiates an image overlay object given the URL of the image and the
  7832. // geographical bounds it is tied to.
  7833. var imageOverlay = function (url, bounds, options) {
  7834. return new ImageOverlay(url, bounds, options);
  7835. };
  7836. /*
  7837. * @class VideoOverlay
  7838. * @aka L.VideoOverlay
  7839. * @inherits ImageOverlay
  7840. *
  7841. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7842. *
  7843. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7844. * HTML5 element.
  7845. *
  7846. * @example
  7847. *
  7848. * ```js
  7849. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7850. * videoBounds = [[ 32, -130], [ 13, -100]];
  7851. * L.videoOverlay(videoUrl, videoBounds ).addTo(map);
  7852. * ```
  7853. */
  7854. var VideoOverlay = ImageOverlay.extend({
  7855. // @section
  7856. // @aka VideoOverlay options
  7857. options: {
  7858. // @option autoplay: Boolean = true
  7859. // Whether the video starts playing automatically when loaded.
  7860. // On some browsers autoplay will only work with `muted: true`
  7861. autoplay: true,
  7862. // @option loop: Boolean = true
  7863. // Whether the video will loop back to the beginning when played.
  7864. loop: true,
  7865. // @option keepAspectRatio: Boolean = true
  7866. // Whether the video will save aspect ratio after the projection.
  7867. // Relevant for supported browsers. See [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
  7868. keepAspectRatio: true,
  7869. // @option muted: Boolean = false
  7870. // Whether the video starts on mute when loaded.
  7871. muted: false,
  7872. // @option playsInline: Boolean = true
  7873. // Mobile browsers will play the video right where it is instead of open it up in fullscreen mode.
  7874. playsInline: true
  7875. },
  7876. _initImage: function () {
  7877. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7878. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7879. addClass(vid, 'leaflet-image-layer');
  7880. if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
  7881. if (this.options.className) { addClass(vid, this.options.className); }
  7882. vid.onselectstart = falseFn;
  7883. vid.onmousemove = falseFn;
  7884. // @event load: Event
  7885. // Fired when the video has finished loading the first frame
  7886. vid.onloadeddata = bind(this.fire, this, 'load');
  7887. if (wasElementSupplied) {
  7888. var sourceElements = vid.getElementsByTagName('source');
  7889. var sources = [];
  7890. for (var j = 0; j < sourceElements.length; j++) {
  7891. sources.push(sourceElements[j].src);
  7892. }
  7893. this._url = (sourceElements.length > 0) ? sources : [vid.src];
  7894. return;
  7895. }
  7896. if (!isArray(this._url)) { this._url = [this._url]; }
  7897. if (!this.options.keepAspectRatio && Object.prototype.hasOwnProperty.call(vid.style, 'objectFit')) {
  7898. vid.style['objectFit'] = 'fill';
  7899. }
  7900. vid.autoplay = !!this.options.autoplay;
  7901. vid.loop = !!this.options.loop;
  7902. vid.muted = !!this.options.muted;
  7903. vid.playsInline = !!this.options.playsInline;
  7904. for (var i = 0; i < this._url.length; i++) {
  7905. var source = create$1('source');
  7906. source.src = this._url[i];
  7907. vid.appendChild(source);
  7908. }
  7909. }
  7910. // @method getElement(): HTMLVideoElement
  7911. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7912. // used by this overlay.
  7913. });
  7914. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7915. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7916. // geographical bounds it is tied to.
  7917. function videoOverlay(video, bounds, options) {
  7918. return new VideoOverlay(video, bounds, options);
  7919. }
  7920. /*
  7921. * @class SVGOverlay
  7922. * @aka L.SVGOverlay
  7923. * @inherits ImageOverlay
  7924. *
  7925. * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.
  7926. *
  7927. * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.
  7928. *
  7929. * @example
  7930. *
  7931. * ```js
  7932. * var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  7933. * svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
  7934. * svgElement.setAttribute('viewBox', "0 0 200 200");
  7935. * svgElement.innerHTML = '<rect width="200" height="200"/><rect x="75" y="23" width="50" height="50" style="fill:red"/><rect x="75" y="123" width="50" height="50" style="fill:#0013ff"/>';
  7936. * var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
  7937. * L.svgOverlay(svgElement, svgElementBounds).addTo(map);
  7938. * ```
  7939. */
  7940. var SVGOverlay = ImageOverlay.extend({
  7941. _initImage: function () {
  7942. var el = this._image = this._url;
  7943. addClass(el, 'leaflet-image-layer');
  7944. if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); }
  7945. if (this.options.className) { addClass(el, this.options.className); }
  7946. el.onselectstart = falseFn;
  7947. el.onmousemove = falseFn;
  7948. }
  7949. // @method getElement(): SVGElement
  7950. // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
  7951. // used by this overlay.
  7952. });
  7953. // @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)
  7954. // Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.
  7955. // A viewBox attribute is required on the SVG element to zoom in and out properly.
  7956. function svgOverlay(el, bounds, options) {
  7957. return new SVGOverlay(el, bounds, options);
  7958. }
  7959. /*
  7960. * @class DivOverlay
  7961. * @inherits Interactive layer
  7962. * @aka L.DivOverlay
  7963. * Base model for L.Popup and L.Tooltip. Inherit from it for custom overlays like plugins.
  7964. */
  7965. // @namespace DivOverlay
  7966. var DivOverlay = Layer.extend({
  7967. // @section
  7968. // @aka DivOverlay options
  7969. options: {
  7970. // @option interactive: Boolean = false
  7971. // If true, the popup/tooltip will listen to the mouse events.
  7972. interactive: false,
  7973. // @option offset: Point = Point(0, 0)
  7974. // The offset of the overlay position.
  7975. offset: [0, 0],
  7976. // @option className: String = ''
  7977. // A custom CSS class name to assign to the overlay.
  7978. className: '',
  7979. // @option pane: String = undefined
  7980. // `Map pane` where the overlay will be added.
  7981. pane: undefined,
  7982. // @option content: String|HTMLElement|Function = ''
  7983. // Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be
  7984. // passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay.
  7985. content: ''
  7986. },
  7987. initialize: function (options, source) {
  7988. if (options && (options instanceof LatLng || isArray(options))) {
  7989. this._latlng = toLatLng(options);
  7990. setOptions(this, source);
  7991. } else {
  7992. setOptions(this, options);
  7993. this._source = source;
  7994. }
  7995. if (this.options.content) {
  7996. this._content = this.options.content;
  7997. }
  7998. },
  7999. // @method openOn(map: Map): this
  8000. // Adds the overlay to the map.
  8001. // Alternative to `map.openPopup(popup)`/`.openTooltip(tooltip)`.
  8002. openOn: function (map) {
  8003. map = arguments.length ? map : this._source._map; // experimental, not the part of public api
  8004. if (!map.hasLayer(this)) {
  8005. map.addLayer(this);
  8006. }
  8007. return this;
  8008. },
  8009. // @method close(): this
  8010. // Closes the overlay.
  8011. // Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)`
  8012. // and `layer.closePopup()`/`.closeTooltip()`.
  8013. close: function () {
  8014. if (this._map) {
  8015. this._map.removeLayer(this);
  8016. }
  8017. return this;
  8018. },
  8019. // @method toggle(layer?: Layer): this
  8020. // Opens or closes the overlay bound to layer depending on its current state.
  8021. // Argument may be omitted only for overlay bound to layer.
  8022. // Alternative to `layer.togglePopup()`/`.toggleTooltip()`.
  8023. toggle: function (layer) {
  8024. if (this._map) {
  8025. this.close();
  8026. } else {
  8027. if (arguments.length) {
  8028. this._source = layer;
  8029. } else {
  8030. layer = this._source;
  8031. }
  8032. this._prepareOpen();
  8033. // open the overlay on the map
  8034. this.openOn(layer._map);
  8035. }
  8036. return this;
  8037. },
  8038. onAdd: function (map) {
  8039. this._zoomAnimated = map._zoomAnimated;
  8040. if (!this._container) {
  8041. this._initLayout();
  8042. }
  8043. if (map._fadeAnimated) {
  8044. setOpacity(this._container, 0);
  8045. }
  8046. clearTimeout(this._removeTimeout);
  8047. this.getPane().appendChild(this._container);
  8048. this.update();
  8049. if (map._fadeAnimated) {
  8050. setOpacity(this._container, 1);
  8051. }
  8052. this.bringToFront();
  8053. if (this.options.interactive) {
  8054. addClass(this._container, 'leaflet-interactive');
  8055. this.addInteractiveTarget(this._container);
  8056. }
  8057. },
  8058. onRemove: function (map) {
  8059. if (map._fadeAnimated) {
  8060. setOpacity(this._container, 0);
  8061. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  8062. } else {
  8063. remove(this._container);
  8064. }
  8065. if (this.options.interactive) {
  8066. removeClass(this._container, 'leaflet-interactive');
  8067. this.removeInteractiveTarget(this._container);
  8068. }
  8069. },
  8070. // @namespace DivOverlay
  8071. // @method getLatLng: LatLng
  8072. // Returns the geographical point of the overlay.
  8073. getLatLng: function () {
  8074. return this._latlng;
  8075. },
  8076. // @method setLatLng(latlng: LatLng): this
  8077. // Sets the geographical point where the overlay will open.
  8078. setLatLng: function (latlng) {
  8079. this._latlng = toLatLng(latlng);
  8080. if (this._map) {
  8081. this._updatePosition();
  8082. this._adjustPan();
  8083. }
  8084. return this;
  8085. },
  8086. // @method getContent: String|HTMLElement
  8087. // Returns the content of the overlay.
  8088. getContent: function () {
  8089. return this._content;
  8090. },
  8091. // @method setContent(htmlContent: String|HTMLElement|Function): this
  8092. // Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function.
  8093. // The function should return a `String` or `HTMLElement` to be used in the overlay.
  8094. setContent: function (content) {
  8095. this._content = content;
  8096. this.update();
  8097. return this;
  8098. },
  8099. // @method getElement: String|HTMLElement
  8100. // Returns the HTML container of the overlay.
  8101. getElement: function () {
  8102. return this._container;
  8103. },
  8104. // @method update: null
  8105. // Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded.
  8106. update: function () {
  8107. if (!this._map) { return; }
  8108. this._container.style.visibility = 'hidden';
  8109. this._updateContent();
  8110. this._updateLayout();
  8111. this._updatePosition();
  8112. this._container.style.visibility = '';
  8113. this._adjustPan();
  8114. },
  8115. getEvents: function () {
  8116. var events = {
  8117. zoom: this._updatePosition,
  8118. viewreset: this._updatePosition
  8119. };
  8120. if (this._zoomAnimated) {
  8121. events.zoomanim = this._animateZoom;
  8122. }
  8123. return events;
  8124. },
  8125. // @method isOpen: Boolean
  8126. // Returns `true` when the overlay is visible on the map.
  8127. isOpen: function () {
  8128. return !!this._map && this._map.hasLayer(this);
  8129. },
  8130. // @method bringToFront: this
  8131. // Brings this overlay in front of other overlays (in the same map pane).
  8132. bringToFront: function () {
  8133. if (this._map) {
  8134. toFront(this._container);
  8135. }
  8136. return this;
  8137. },
  8138. // @method bringToBack: this
  8139. // Brings this overlay to the back of other overlays (in the same map pane).
  8140. bringToBack: function () {
  8141. if (this._map) {
  8142. toBack(this._container);
  8143. }
  8144. return this;
  8145. },
  8146. // prepare bound overlay to open: update latlng pos / content source (for FeatureGroup)
  8147. _prepareOpen: function (latlng) {
  8148. var source = this._source;
  8149. if (!source._map) { return false; }
  8150. if (source instanceof FeatureGroup) {
  8151. source = null;
  8152. var layers = this._source._layers;
  8153. for (var id in layers) {
  8154. if (layers[id]._map) {
  8155. source = layers[id];
  8156. break;
  8157. }
  8158. }
  8159. if (!source) { return false; } // Unable to get source layer.
  8160. // set overlay source to this layer
  8161. this._source = source;
  8162. }
  8163. if (!latlng) {
  8164. if (source.getCenter) {
  8165. latlng = source.getCenter();
  8166. } else if (source.getLatLng) {
  8167. latlng = source.getLatLng();
  8168. } else if (source.getBounds) {
  8169. latlng = source.getBounds().getCenter();
  8170. } else {
  8171. throw new Error('Unable to get source layer LatLng.');
  8172. }
  8173. }
  8174. this.setLatLng(latlng);
  8175. if (this._map) {
  8176. // update the overlay (content, layout, etc...)
  8177. this.update();
  8178. }
  8179. return true;
  8180. },
  8181. _updateContent: function () {
  8182. if (!this._content) { return; }
  8183. var node = this._contentNode;
  8184. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  8185. if (typeof content === 'string') {
  8186. node.innerHTML = content;
  8187. } else {
  8188. while (node.hasChildNodes()) {
  8189. node.removeChild(node.firstChild);
  8190. }
  8191. node.appendChild(content);
  8192. }
  8193. // @namespace DivOverlay
  8194. // @section DivOverlay events
  8195. // @event contentupdate: Event
  8196. // Fired when the content of the overlay is updated
  8197. this.fire('contentupdate');
  8198. },
  8199. _updatePosition: function () {
  8200. if (!this._map) { return; }
  8201. var pos = this._map.latLngToLayerPoint(this._latlng),
  8202. offset = toPoint(this.options.offset),
  8203. anchor = this._getAnchor();
  8204. if (this._zoomAnimated) {
  8205. setPosition(this._container, pos.add(anchor));
  8206. } else {
  8207. offset = offset.add(pos).add(anchor);
  8208. }
  8209. var bottom = this._containerBottom = -offset.y,
  8210. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  8211. // bottom position the overlay in case the height of the overlay changes (images loading etc)
  8212. this._container.style.bottom = bottom + 'px';
  8213. this._container.style.left = left + 'px';
  8214. },
  8215. _getAnchor: function () {
  8216. return [0, 0];
  8217. }
  8218. });
  8219. Map.include({
  8220. _initOverlay: function (OverlayClass, content, latlng, options) {
  8221. var overlay = content;
  8222. if (!(overlay instanceof OverlayClass)) {
  8223. overlay = new OverlayClass(options).setContent(content);
  8224. }
  8225. if (latlng) {
  8226. overlay.setLatLng(latlng);
  8227. }
  8228. return overlay;
  8229. }
  8230. });
  8231. Layer.include({
  8232. _initOverlay: function (OverlayClass, old, content, options) {
  8233. var overlay = content;
  8234. if (overlay instanceof OverlayClass) {
  8235. setOptions(overlay, options);
  8236. overlay._source = this;
  8237. } else {
  8238. overlay = (old && !options) ? old : new OverlayClass(options, this);
  8239. overlay.setContent(content);
  8240. }
  8241. return overlay;
  8242. }
  8243. });
  8244. /*
  8245. * @class Popup
  8246. * @inherits DivOverlay
  8247. * @aka L.Popup
  8248. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  8249. * open popups while making sure that only one popup is open at one time
  8250. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  8251. *
  8252. * @example
  8253. *
  8254. * If you want to just bind a popup to marker click and then open it, it's really easy:
  8255. *
  8256. * ```js
  8257. * marker.bindPopup(popupContent).openPopup();
  8258. * ```
  8259. * Path overlays like polylines also have a `bindPopup` method.
  8260. *
  8261. * A popup can be also standalone:
  8262. *
  8263. * ```js
  8264. * var popup = L.popup()
  8265. * .setLatLng(latlng)
  8266. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  8267. * .openOn(map);
  8268. * ```
  8269. * or
  8270. * ```js
  8271. * var popup = L.popup(latlng, {content: '<p>Hello world!<br />This is a nice popup.</p>')
  8272. * .openOn(map);
  8273. * ```
  8274. */
  8275. // @namespace Popup
  8276. var Popup = DivOverlay.extend({
  8277. // @section
  8278. // @aka Popup options
  8279. options: {
  8280. // @option pane: String = 'popupPane'
  8281. // `Map pane` where the popup will be added.
  8282. pane: 'popupPane',
  8283. // @option offset: Point = Point(0, 7)
  8284. // The offset of the popup position.
  8285. offset: [0, 7],
  8286. // @option maxWidth: Number = 300
  8287. // Max width of the popup, in pixels.
  8288. maxWidth: 300,
  8289. // @option minWidth: Number = 50
  8290. // Min width of the popup, in pixels.
  8291. minWidth: 50,
  8292. // @option maxHeight: Number = null
  8293. // If set, creates a scrollable container of the given height
  8294. // inside a popup if its content exceeds it.
  8295. // The scrollable container can be styled using the
  8296. // `leaflet-popup-scrolled` CSS class selector.
  8297. maxHeight: null,
  8298. // @option autoPan: Boolean = true
  8299. // Set it to `false` if you don't want the map to do panning animation
  8300. // to fit the opened popup.
  8301. autoPan: true,
  8302. // @option autoPanPaddingTopLeft: Point = null
  8303. // The margin between the popup and the top left corner of the map
  8304. // view after autopanning was performed.
  8305. autoPanPaddingTopLeft: null,
  8306. // @option autoPanPaddingBottomRight: Point = null
  8307. // The margin between the popup and the bottom right corner of the map
  8308. // view after autopanning was performed.
  8309. autoPanPaddingBottomRight: null,
  8310. // @option autoPanPadding: Point = Point(5, 5)
  8311. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  8312. autoPanPadding: [5, 5],
  8313. // @option keepInView: Boolean = false
  8314. // Set it to `true` if you want to prevent users from panning the popup
  8315. // off of the screen while it is open.
  8316. keepInView: false,
  8317. // @option closeButton: Boolean = true
  8318. // Controls the presence of a close button in the popup.
  8319. closeButton: true,
  8320. // @option autoClose: Boolean = true
  8321. // Set it to `false` if you want to override the default behavior of
  8322. // the popup closing when another popup is opened.
  8323. autoClose: true,
  8324. // @option closeOnEscapeKey: Boolean = true
  8325. // Set it to `false` if you want to override the default behavior of
  8326. // the ESC key for closing of the popup.
  8327. closeOnEscapeKey: true,
  8328. // @option closeOnClick: Boolean = *
  8329. // Set it if you want to override the default behavior of the popup closing when user clicks
  8330. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  8331. // @option className: String = ''
  8332. // A custom CSS class name to assign to the popup.
  8333. className: ''
  8334. },
  8335. // @namespace Popup
  8336. // @method openOn(map: Map): this
  8337. // Alternative to `map.openPopup(popup)`.
  8338. // Adds the popup to the map and closes the previous one.
  8339. openOn: function (map) {
  8340. map = arguments.length ? map : this._source._map; // experimental, not the part of public api
  8341. if (!map.hasLayer(this) && map._popup && map._popup.options.autoClose) {
  8342. map.removeLayer(map._popup);
  8343. }
  8344. map._popup = this;
  8345. return DivOverlay.prototype.openOn.call(this, map);
  8346. },
  8347. onAdd: function (map) {
  8348. DivOverlay.prototype.onAdd.call(this, map);
  8349. // @namespace Map
  8350. // @section Popup events
  8351. // @event popupopen: PopupEvent
  8352. // Fired when a popup is opened in the map
  8353. map.fire('popupopen', {popup: this});
  8354. if (this._source) {
  8355. // @namespace Layer
  8356. // @section Popup events
  8357. // @event popupopen: PopupEvent
  8358. // Fired when a popup bound to this layer is opened
  8359. this._source.fire('popupopen', {popup: this}, true);
  8360. // For non-path layers, we toggle the popup when clicking
  8361. // again the layer, so prevent the map to reopen it.
  8362. if (!(this._source instanceof Path)) {
  8363. this._source.on('preclick', stopPropagation);
  8364. }
  8365. }
  8366. },
  8367. onRemove: function (map) {
  8368. DivOverlay.prototype.onRemove.call(this, map);
  8369. // @namespace Map
  8370. // @section Popup events
  8371. // @event popupclose: PopupEvent
  8372. // Fired when a popup in the map is closed
  8373. map.fire('popupclose', {popup: this});
  8374. if (this._source) {
  8375. // @namespace Layer
  8376. // @section Popup events
  8377. // @event popupclose: PopupEvent
  8378. // Fired when a popup bound to this layer is closed
  8379. this._source.fire('popupclose', {popup: this}, true);
  8380. if (!(this._source instanceof Path)) {
  8381. this._source.off('preclick', stopPropagation);
  8382. }
  8383. }
  8384. },
  8385. getEvents: function () {
  8386. var events = DivOverlay.prototype.getEvents.call(this);
  8387. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  8388. events.preclick = this.close;
  8389. }
  8390. if (this.options.keepInView) {
  8391. events.moveend = this._adjustPan;
  8392. }
  8393. return events;
  8394. },
  8395. _initLayout: function () {
  8396. var prefix = 'leaflet-popup',
  8397. container = this._container = create$1('div',
  8398. prefix + ' ' + (this.options.className || '') +
  8399. ' leaflet-zoom-animated');
  8400. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  8401. this._contentNode = create$1('div', prefix + '-content', wrapper);
  8402. disableClickPropagation(container);
  8403. disableScrollPropagation(this._contentNode);
  8404. on(container, 'contextmenu', stopPropagation);
  8405. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  8406. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  8407. if (this.options.closeButton) {
  8408. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  8409. closeButton.setAttribute('role', 'button'); // overrides the implicit role=link of <a> elements #7399
  8410. closeButton.setAttribute('aria-label', 'Close popup');
  8411. closeButton.href = '#close';
  8412. closeButton.innerHTML = '<span aria-hidden="true">&#215;</span>';
  8413. on(closeButton, 'click', function (ev) {
  8414. preventDefault(ev);
  8415. this.close();
  8416. }, this);
  8417. }
  8418. },
  8419. _updateLayout: function () {
  8420. var container = this._contentNode,
  8421. style = container.style;
  8422. style.width = '';
  8423. style.whiteSpace = 'nowrap';
  8424. var width = container.offsetWidth;
  8425. width = Math.min(width, this.options.maxWidth);
  8426. width = Math.max(width, this.options.minWidth);
  8427. style.width = (width + 1) + 'px';
  8428. style.whiteSpace = '';
  8429. style.height = '';
  8430. var height = container.offsetHeight,
  8431. maxHeight = this.options.maxHeight,
  8432. scrolledClass = 'leaflet-popup-scrolled';
  8433. if (maxHeight && height > maxHeight) {
  8434. style.height = maxHeight + 'px';
  8435. addClass(container, scrolledClass);
  8436. } else {
  8437. removeClass(container, scrolledClass);
  8438. }
  8439. this._containerWidth = this._container.offsetWidth;
  8440. },
  8441. _animateZoom: function (e) {
  8442. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  8443. anchor = this._getAnchor();
  8444. setPosition(this._container, pos.add(anchor));
  8445. },
  8446. _adjustPan: function () {
  8447. if (!this.options.autoPan) { return; }
  8448. if (this._map._panAnim) { this._map._panAnim.stop(); }
  8449. // We can endlessly recurse if keepInView is set and the view resets.
  8450. // Let's guard against that by exiting early if we're responding to our own autopan.
  8451. if (this._autopanning) {
  8452. this._autopanning = false;
  8453. return;
  8454. }
  8455. var map = this._map,
  8456. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  8457. containerHeight = this._container.offsetHeight + marginBottom,
  8458. containerWidth = this._containerWidth,
  8459. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  8460. layerPos._add(getPosition(this._container));
  8461. var containerPos = map.layerPointToContainerPoint(layerPos),
  8462. padding = toPoint(this.options.autoPanPadding),
  8463. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  8464. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  8465. size = map.getSize(),
  8466. dx = 0,
  8467. dy = 0;
  8468. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  8469. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  8470. }
  8471. if (containerPos.x - dx - paddingTL.x < 0) { // left
  8472. dx = containerPos.x - paddingTL.x;
  8473. }
  8474. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  8475. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  8476. }
  8477. if (containerPos.y - dy - paddingTL.y < 0) { // top
  8478. dy = containerPos.y - paddingTL.y;
  8479. }
  8480. // @namespace Map
  8481. // @section Popup events
  8482. // @event autopanstart: Event
  8483. // Fired when the map starts autopanning when opening a popup.
  8484. if (dx || dy) {
  8485. // Track that we're autopanning, as this function will be re-ran on moveend
  8486. if (this.options.keepInView) {
  8487. this._autopanning = true;
  8488. }
  8489. map
  8490. .fire('autopanstart')
  8491. .panBy([dx, dy]);
  8492. }
  8493. },
  8494. _getAnchor: function () {
  8495. // Where should we anchor the popup on the source layer?
  8496. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  8497. }
  8498. });
  8499. // @namespace Popup
  8500. // @factory L.popup(options?: Popup options, source?: Layer)
  8501. // 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.
  8502. // @alternative
  8503. // @factory L.popup(latlng: LatLng, options?: Popup options)
  8504. // Instantiates a `Popup` object given `latlng` where the popup will open and an optional `options` object that describes its appearance and location.
  8505. var popup = function (options, source) {
  8506. return new Popup(options, source);
  8507. };
  8508. /* @namespace Map
  8509. * @section Interaction Options
  8510. * @option closePopupOnClick: Boolean = true
  8511. * Set it to `false` if you don't want popups to close when user clicks the map.
  8512. */
  8513. Map.mergeOptions({
  8514. closePopupOnClick: true
  8515. });
  8516. // @namespace Map
  8517. // @section Methods for Layers and Controls
  8518. Map.include({
  8519. // @method openPopup(popup: Popup): this
  8520. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  8521. // @alternative
  8522. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  8523. // Creates a popup with the specified content and options and opens it in the given point on a map.
  8524. openPopup: function (popup, latlng, options) {
  8525. this._initOverlay(Popup, popup, latlng, options)
  8526. .openOn(this);
  8527. return this;
  8528. },
  8529. // @method closePopup(popup?: Popup): this
  8530. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  8531. closePopup: function (popup) {
  8532. popup = arguments.length ? popup : this._popup;
  8533. if (popup) {
  8534. popup.close();
  8535. }
  8536. return this;
  8537. }
  8538. });
  8539. /*
  8540. * @namespace Layer
  8541. * @section Popup methods example
  8542. *
  8543. * All layers share a set of methods convenient for binding popups to it.
  8544. *
  8545. * ```js
  8546. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  8547. * layer.openPopup();
  8548. * layer.closePopup();
  8549. * ```
  8550. *
  8551. * 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.
  8552. */
  8553. // @section Popup methods
  8554. Layer.include({
  8555. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  8556. // Binds a popup to the layer with the passed `content` and sets up the
  8557. // necessary event listeners. If a `Function` is passed it will receive
  8558. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8559. bindPopup: function (content, options) {
  8560. this._popup = this._initOverlay(Popup, this._popup, content, options);
  8561. if (!this._popupHandlersAdded) {
  8562. this.on({
  8563. click: this._openPopup,
  8564. keypress: this._onKeyPress,
  8565. remove: this.closePopup,
  8566. move: this._movePopup
  8567. });
  8568. this._popupHandlersAdded = true;
  8569. }
  8570. return this;
  8571. },
  8572. // @method unbindPopup(): this
  8573. // Removes the popup previously bound with `bindPopup`.
  8574. unbindPopup: function () {
  8575. if (this._popup) {
  8576. this.off({
  8577. click: this._openPopup,
  8578. keypress: this._onKeyPress,
  8579. remove: this.closePopup,
  8580. move: this._movePopup
  8581. });
  8582. this._popupHandlersAdded = false;
  8583. this._popup = null;
  8584. }
  8585. return this;
  8586. },
  8587. // @method openPopup(latlng?: LatLng): this
  8588. // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
  8589. openPopup: function (latlng) {
  8590. if (this._popup) {
  8591. if (!(this instanceof FeatureGroup)) {
  8592. this._popup._source = this;
  8593. }
  8594. if (this._popup._prepareOpen(latlng || this._latlng)) {
  8595. // open the popup on the map
  8596. this._popup.openOn(this._map);
  8597. }
  8598. }
  8599. return this;
  8600. },
  8601. // @method closePopup(): this
  8602. // Closes the popup bound to this layer if it is open.
  8603. closePopup: function () {
  8604. if (this._popup) {
  8605. this._popup.close();
  8606. }
  8607. return this;
  8608. },
  8609. // @method togglePopup(): this
  8610. // Opens or closes the popup bound to this layer depending on its current state.
  8611. togglePopup: function () {
  8612. if (this._popup) {
  8613. this._popup.toggle(this);
  8614. }
  8615. return this;
  8616. },
  8617. // @method isPopupOpen(): boolean
  8618. // Returns `true` if the popup bound to this layer is currently open.
  8619. isPopupOpen: function () {
  8620. return (this._popup ? this._popup.isOpen() : false);
  8621. },
  8622. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8623. // Sets the content of the popup bound to this layer.
  8624. setPopupContent: function (content) {
  8625. if (this._popup) {
  8626. this._popup.setContent(content);
  8627. }
  8628. return this;
  8629. },
  8630. // @method getPopup(): Popup
  8631. // Returns the popup bound to this layer.
  8632. getPopup: function () {
  8633. return this._popup;
  8634. },
  8635. _openPopup: function (e) {
  8636. if (!this._popup || !this._map) {
  8637. return;
  8638. }
  8639. // prevent map click
  8640. stop(e);
  8641. var target = e.layer || e.target;
  8642. if (this._popup._source === target && !(target instanceof Path)) {
  8643. // treat it like a marker and figure out
  8644. // if we should toggle it open/closed
  8645. if (this._map.hasLayer(this._popup)) {
  8646. this.closePopup();
  8647. } else {
  8648. this.openPopup(e.latlng);
  8649. }
  8650. return;
  8651. }
  8652. this._popup._source = target;
  8653. this.openPopup(e.latlng);
  8654. },
  8655. _movePopup: function (e) {
  8656. this._popup.setLatLng(e.latlng);
  8657. },
  8658. _onKeyPress: function (e) {
  8659. if (e.originalEvent.keyCode === 13) {
  8660. this._openPopup(e);
  8661. }
  8662. }
  8663. });
  8664. /*
  8665. * @class Tooltip
  8666. * @inherits DivOverlay
  8667. * @aka L.Tooltip
  8668. * Used to display small texts on top of map layers.
  8669. *
  8670. * @example
  8671. * If you want to just bind a tooltip to marker:
  8672. *
  8673. * ```js
  8674. * marker.bindTooltip("my tooltip text").openTooltip();
  8675. * ```
  8676. * Path overlays like polylines also have a `bindTooltip` method.
  8677. *
  8678. * A tooltip can be also standalone:
  8679. *
  8680. * ```js
  8681. * var tooltip = L.tooltip()
  8682. * .setLatLng(latlng)
  8683. * .setContent('Hello world!<br />This is a nice tooltip.')
  8684. * .addTo(map);
  8685. * ```
  8686. * or
  8687. * ```js
  8688. * var tooltip = L.tooltip(latlng, {content: 'Hello world!<br />This is a nice tooltip.'})
  8689. * .addTo(map);
  8690. * ```
  8691. *
  8692. *
  8693. * Note about tooltip offset. Leaflet takes two options in consideration
  8694. * for computing tooltip offsetting:
  8695. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8696. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8697. * move it to the bottom. Negatives will move to the left and top.
  8698. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8699. * should adapt this value if you use a custom icon.
  8700. */
  8701. // @namespace Tooltip
  8702. var Tooltip = DivOverlay.extend({
  8703. // @section
  8704. // @aka Tooltip options
  8705. options: {
  8706. // @option pane: String = 'tooltipPane'
  8707. // `Map pane` where the tooltip will be added.
  8708. pane: 'tooltipPane',
  8709. // @option offset: Point = Point(0, 0)
  8710. // Optional offset of the tooltip position.
  8711. offset: [0, 0],
  8712. // @option direction: String = 'auto'
  8713. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8714. // `top`, `bottom`, `center`, `auto`.
  8715. // `auto` will dynamically switch between `right` and `left` according to the tooltip
  8716. // position on the map.
  8717. direction: 'auto',
  8718. // @option permanent: Boolean = false
  8719. // Whether to open the tooltip permanently or only on mouseover.
  8720. permanent: false,
  8721. // @option sticky: Boolean = false
  8722. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8723. sticky: false,
  8724. // @option opacity: Number = 0.9
  8725. // Tooltip container opacity.
  8726. opacity: 0.9
  8727. },
  8728. onAdd: function (map) {
  8729. DivOverlay.prototype.onAdd.call(this, map);
  8730. this.setOpacity(this.options.opacity);
  8731. // @namespace Map
  8732. // @section Tooltip events
  8733. // @event tooltipopen: TooltipEvent
  8734. // Fired when a tooltip is opened in the map.
  8735. map.fire('tooltipopen', {tooltip: this});
  8736. if (this._source) {
  8737. this.addEventParent(this._source);
  8738. // @namespace Layer
  8739. // @section Tooltip events
  8740. // @event tooltipopen: TooltipEvent
  8741. // Fired when a tooltip bound to this layer is opened.
  8742. this._source.fire('tooltipopen', {tooltip: this}, true);
  8743. }
  8744. },
  8745. onRemove: function (map) {
  8746. DivOverlay.prototype.onRemove.call(this, map);
  8747. // @namespace Map
  8748. // @section Tooltip events
  8749. // @event tooltipclose: TooltipEvent
  8750. // Fired when a tooltip in the map is closed.
  8751. map.fire('tooltipclose', {tooltip: this});
  8752. if (this._source) {
  8753. this.removeEventParent(this._source);
  8754. // @namespace Layer
  8755. // @section Tooltip events
  8756. // @event tooltipclose: TooltipEvent
  8757. // Fired when a tooltip bound to this layer is closed.
  8758. this._source.fire('tooltipclose', {tooltip: this}, true);
  8759. }
  8760. },
  8761. getEvents: function () {
  8762. var events = DivOverlay.prototype.getEvents.call(this);
  8763. if (!this.options.permanent) {
  8764. events.preclick = this.close;
  8765. }
  8766. return events;
  8767. },
  8768. _initLayout: function () {
  8769. var prefix = 'leaflet-tooltip',
  8770. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8771. this._contentNode = this._container = create$1('div', className);
  8772. this._container.setAttribute('role', 'tooltip');
  8773. this._container.setAttribute('id', 'leaflet-tooltip-' + stamp(this));
  8774. },
  8775. _updateLayout: function () {},
  8776. _adjustPan: function () {},
  8777. _setPosition: function (pos) {
  8778. var subX, subY,
  8779. map = this._map,
  8780. container = this._container,
  8781. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8782. tooltipPoint = map.layerPointToContainerPoint(pos),
  8783. direction = this.options.direction,
  8784. tooltipWidth = container.offsetWidth,
  8785. tooltipHeight = container.offsetHeight,
  8786. offset = toPoint(this.options.offset),
  8787. anchor = this._getAnchor();
  8788. if (direction === 'top') {
  8789. subX = tooltipWidth / 2;
  8790. subY = tooltipHeight;
  8791. } else if (direction === 'bottom') {
  8792. subX = tooltipWidth / 2;
  8793. subY = 0;
  8794. } else if (direction === 'center') {
  8795. subX = tooltipWidth / 2;
  8796. subY = tooltipHeight / 2;
  8797. } else if (direction === 'right') {
  8798. subX = 0;
  8799. subY = tooltipHeight / 2;
  8800. } else if (direction === 'left') {
  8801. subX = tooltipWidth;
  8802. subY = tooltipHeight / 2;
  8803. } else if (tooltipPoint.x < centerPoint.x) {
  8804. direction = 'right';
  8805. subX = 0;
  8806. subY = tooltipHeight / 2;
  8807. } else {
  8808. direction = 'left';
  8809. subX = tooltipWidth + (offset.x + anchor.x) * 2;
  8810. subY = tooltipHeight / 2;
  8811. }
  8812. pos = pos.subtract(toPoint(subX, subY, true)).add(offset).add(anchor);
  8813. removeClass(container, 'leaflet-tooltip-right');
  8814. removeClass(container, 'leaflet-tooltip-left');
  8815. removeClass(container, 'leaflet-tooltip-top');
  8816. removeClass(container, 'leaflet-tooltip-bottom');
  8817. addClass(container, 'leaflet-tooltip-' + direction);
  8818. setPosition(container, pos);
  8819. },
  8820. _updatePosition: function () {
  8821. var pos = this._map.latLngToLayerPoint(this._latlng);
  8822. this._setPosition(pos);
  8823. },
  8824. setOpacity: function (opacity) {
  8825. this.options.opacity = opacity;
  8826. if (this._container) {
  8827. setOpacity(this._container, opacity);
  8828. }
  8829. },
  8830. _animateZoom: function (e) {
  8831. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8832. this._setPosition(pos);
  8833. },
  8834. _getAnchor: function () {
  8835. // Where should we anchor the tooltip on the source layer?
  8836. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8837. }
  8838. });
  8839. // @namespace Tooltip
  8840. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8841. // 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.
  8842. // @alternative
  8843. // @factory L.tooltip(latlng: LatLng, options?: Tooltip options)
  8844. // Instantiates a `Tooltip` object given `latlng` where the tooltip will open and an optional `options` object that describes its appearance and location.
  8845. var tooltip = function (options, source) {
  8846. return new Tooltip(options, source);
  8847. };
  8848. // @namespace Map
  8849. // @section Methods for Layers and Controls
  8850. Map.include({
  8851. // @method openTooltip(tooltip: Tooltip): this
  8852. // Opens the specified tooltip.
  8853. // @alternative
  8854. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8855. // Creates a tooltip with the specified content and options and open it.
  8856. openTooltip: function (tooltip, latlng, options) {
  8857. this._initOverlay(Tooltip, tooltip, latlng, options)
  8858. .openOn(this);
  8859. return this;
  8860. },
  8861. // @method closeTooltip(tooltip: Tooltip): this
  8862. // Closes the tooltip given as parameter.
  8863. closeTooltip: function (tooltip) {
  8864. tooltip.close();
  8865. return this;
  8866. }
  8867. });
  8868. /*
  8869. * @namespace Layer
  8870. * @section Tooltip methods example
  8871. *
  8872. * All layers share a set of methods convenient for binding tooltips to it.
  8873. *
  8874. * ```js
  8875. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8876. * layer.openTooltip();
  8877. * layer.closeTooltip();
  8878. * ```
  8879. */
  8880. // @section Tooltip methods
  8881. Layer.include({
  8882. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8883. // Binds a tooltip to the layer with the passed `content` and sets up the
  8884. // necessary event listeners. If a `Function` is passed it will receive
  8885. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8886. bindTooltip: function (content, options) {
  8887. if (this._tooltip && this.isTooltipOpen()) {
  8888. this.unbindTooltip();
  8889. }
  8890. this._tooltip = this._initOverlay(Tooltip, this._tooltip, content, options);
  8891. this._initTooltipInteractions();
  8892. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8893. this.openTooltip();
  8894. }
  8895. return this;
  8896. },
  8897. // @method unbindTooltip(): this
  8898. // Removes the tooltip previously bound with `bindTooltip`.
  8899. unbindTooltip: function () {
  8900. if (this._tooltip) {
  8901. this._initTooltipInteractions(true);
  8902. this.closeTooltip();
  8903. this._tooltip = null;
  8904. }
  8905. return this;
  8906. },
  8907. _initTooltipInteractions: function (remove) {
  8908. if (!remove && this._tooltipHandlersAdded) { return; }
  8909. var onOff = remove ? 'off' : 'on',
  8910. events = {
  8911. remove: this.closeTooltip,
  8912. move: this._moveTooltip
  8913. };
  8914. if (!this._tooltip.options.permanent) {
  8915. events.mouseover = this._openTooltip;
  8916. events.mouseout = this.closeTooltip;
  8917. events.click = this._openTooltip;
  8918. if (this._map) {
  8919. this._addFocusListeners();
  8920. } else {
  8921. events.add = this._addFocusListeners;
  8922. }
  8923. } else {
  8924. events.add = this._openTooltip;
  8925. }
  8926. if (this._tooltip.options.sticky) {
  8927. events.mousemove = this._moveTooltip;
  8928. }
  8929. this[onOff](events);
  8930. this._tooltipHandlersAdded = !remove;
  8931. },
  8932. // @method openTooltip(latlng?: LatLng): this
  8933. // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8934. openTooltip: function (latlng) {
  8935. if (this._tooltip) {
  8936. if (!(this instanceof FeatureGroup)) {
  8937. this._tooltip._source = this;
  8938. }
  8939. if (this._tooltip._prepareOpen(latlng)) {
  8940. // open the tooltip on the map
  8941. this._tooltip.openOn(this._map);
  8942. if (this.getElement) {
  8943. this._setAriaDescribedByOnLayer(this);
  8944. } else if (this.eachLayer) {
  8945. this.eachLayer(this._setAriaDescribedByOnLayer, this);
  8946. }
  8947. }
  8948. }
  8949. return this;
  8950. },
  8951. // @method closeTooltip(): this
  8952. // Closes the tooltip bound to this layer if it is open.
  8953. closeTooltip: function () {
  8954. if (this._tooltip) {
  8955. return this._tooltip.close();
  8956. }
  8957. },
  8958. // @method toggleTooltip(): this
  8959. // Opens or closes the tooltip bound to this layer depending on its current state.
  8960. toggleTooltip: function () {
  8961. if (this._tooltip) {
  8962. this._tooltip.toggle(this);
  8963. }
  8964. return this;
  8965. },
  8966. // @method isTooltipOpen(): boolean
  8967. // Returns `true` if the tooltip bound to this layer is currently open.
  8968. isTooltipOpen: function () {
  8969. return this._tooltip.isOpen();
  8970. },
  8971. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8972. // Sets the content of the tooltip bound to this layer.
  8973. setTooltipContent: function (content) {
  8974. if (this._tooltip) {
  8975. this._tooltip.setContent(content);
  8976. }
  8977. return this;
  8978. },
  8979. // @method getTooltip(): Tooltip
  8980. // Returns the tooltip bound to this layer.
  8981. getTooltip: function () {
  8982. return this._tooltip;
  8983. },
  8984. _addFocusListeners: function () {
  8985. if (this.getElement) {
  8986. this._addFocusListenersOnLayer(this);
  8987. } else if (this.eachLayer) {
  8988. this.eachLayer(this._addFocusListenersOnLayer, this);
  8989. }
  8990. },
  8991. _addFocusListenersOnLayer: function (layer) {
  8992. var el = layer.getElement();
  8993. if (el) {
  8994. on(el, 'focus', function () {
  8995. this._tooltip._source = layer;
  8996. this.openTooltip();
  8997. }, this);
  8998. on(el, 'blur', this.closeTooltip, this);
  8999. }
  9000. },
  9001. _setAriaDescribedByOnLayer: function (layer) {
  9002. var el = layer.getElement();
  9003. if (el) {
  9004. el.setAttribute('aria-describedby', this._tooltip._container.id);
  9005. }
  9006. },
  9007. _openTooltip: function (e) {
  9008. if (!this._tooltip || !this._map || (this._map.dragging && this._map.dragging.moving())) {
  9009. return;
  9010. }
  9011. this._tooltip._source = e.layer || e.target;
  9012. this.openTooltip(this._tooltip.options.sticky ? e.latlng : undefined);
  9013. },
  9014. _moveTooltip: function (e) {
  9015. var latlng = e.latlng, containerPoint, layerPoint;
  9016. if (this._tooltip.options.sticky && e.originalEvent) {
  9017. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  9018. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  9019. latlng = this._map.layerPointToLatLng(layerPoint);
  9020. }
  9021. this._tooltip.setLatLng(latlng);
  9022. }
  9023. });
  9024. /*
  9025. * @class DivIcon
  9026. * @aka L.DivIcon
  9027. * @inherits Icon
  9028. *
  9029. * Represents a lightweight icon for markers that uses a simple `<div>`
  9030. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  9031. *
  9032. * @example
  9033. * ```js
  9034. * var myIcon = L.divIcon({className: 'my-div-icon'});
  9035. * // you can set .my-div-icon styles in CSS
  9036. *
  9037. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  9038. * ```
  9039. *
  9040. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  9041. */
  9042. var DivIcon = Icon.extend({
  9043. options: {
  9044. // @section
  9045. // @aka DivIcon options
  9046. iconSize: [12, 12], // also can be set through CSS
  9047. // iconAnchor: (Point),
  9048. // popupAnchor: (Point),
  9049. // @option html: String|HTMLElement = ''
  9050. // Custom HTML code to put inside the div element, empty by default. Alternatively,
  9051. // an instance of `HTMLElement`.
  9052. html: false,
  9053. // @option bgPos: Point = [0, 0]
  9054. // Optional relative position of the background, in pixels
  9055. bgPos: null,
  9056. className: 'leaflet-div-icon'
  9057. },
  9058. createIcon: function (oldIcon) {
  9059. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  9060. options = this.options;
  9061. if (options.html instanceof Element) {
  9062. empty(div);
  9063. div.appendChild(options.html);
  9064. } else {
  9065. div.innerHTML = options.html !== false ? options.html : '';
  9066. }
  9067. if (options.bgPos) {
  9068. var bgPos = toPoint(options.bgPos);
  9069. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  9070. }
  9071. this._setIconStyles(div, 'icon');
  9072. return div;
  9073. },
  9074. createShadow: function () {
  9075. return null;
  9076. }
  9077. });
  9078. // @factory L.divIcon(options: DivIcon options)
  9079. // Creates a `DivIcon` instance with the given options.
  9080. function divIcon(options) {
  9081. return new DivIcon(options);
  9082. }
  9083. Icon.Default = IconDefault;
  9084. /*
  9085. * @class GridLayer
  9086. * @inherits Layer
  9087. * @aka L.GridLayer
  9088. *
  9089. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  9090. * 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.
  9091. *
  9092. *
  9093. * @section Synchronous usage
  9094. * @example
  9095. *
  9096. * 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.
  9097. *
  9098. * ```js
  9099. * var CanvasLayer = L.GridLayer.extend({
  9100. * createTile: function(coords){
  9101. * // create a <canvas> element for drawing
  9102. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  9103. *
  9104. * // setup tile width and height according to the options
  9105. * var size = this.getTileSize();
  9106. * tile.width = size.x;
  9107. * tile.height = size.y;
  9108. *
  9109. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  9110. * var ctx = tile.getContext('2d');
  9111. *
  9112. * // return the tile so it can be rendered on screen
  9113. * return tile;
  9114. * }
  9115. * });
  9116. * ```
  9117. *
  9118. * @section Asynchronous usage
  9119. * @example
  9120. *
  9121. * 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.
  9122. *
  9123. * ```js
  9124. * var CanvasLayer = L.GridLayer.extend({
  9125. * createTile: function(coords, done){
  9126. * var error;
  9127. *
  9128. * // create a <canvas> element for drawing
  9129. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  9130. *
  9131. * // setup tile width and height according to the options
  9132. * var size = this.getTileSize();
  9133. * tile.width = size.x;
  9134. * tile.height = size.y;
  9135. *
  9136. * // draw something asynchronously and pass the tile to the done() callback
  9137. * setTimeout(function() {
  9138. * done(error, tile);
  9139. * }, 1000);
  9140. *
  9141. * return tile;
  9142. * }
  9143. * });
  9144. * ```
  9145. *
  9146. * @section
  9147. */
  9148. var GridLayer = Layer.extend({
  9149. // @section
  9150. // @aka GridLayer options
  9151. options: {
  9152. // @option tileSize: Number|Point = 256
  9153. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  9154. tileSize: 256,
  9155. // @option opacity: Number = 1.0
  9156. // Opacity of the tiles. Can be used in the `createTile()` function.
  9157. opacity: 1,
  9158. // @option updateWhenIdle: Boolean = (depends)
  9159. // Load new tiles only when panning ends.
  9160. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  9161. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  9162. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  9163. updateWhenIdle: Browser.mobile,
  9164. // @option updateWhenZooming: Boolean = true
  9165. // 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.
  9166. updateWhenZooming: true,
  9167. // @option updateInterval: Number = 200
  9168. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  9169. updateInterval: 200,
  9170. // @option zIndex: Number = 1
  9171. // The explicit zIndex of the tile layer.
  9172. zIndex: 1,
  9173. // @option bounds: LatLngBounds = undefined
  9174. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  9175. bounds: null,
  9176. // @option minZoom: Number = 0
  9177. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9178. minZoom: 0,
  9179. // @option maxZoom: Number = undefined
  9180. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9181. maxZoom: undefined,
  9182. // @option maxNativeZoom: Number = undefined
  9183. // Maximum zoom number the tile source has available. If it is specified,
  9184. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  9185. // from `maxNativeZoom` level and auto-scaled.
  9186. maxNativeZoom: undefined,
  9187. // @option minNativeZoom: Number = undefined
  9188. // Minimum zoom number the tile source has available. If it is specified,
  9189. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  9190. // from `minNativeZoom` level and auto-scaled.
  9191. minNativeZoom: undefined,
  9192. // @option noWrap: Boolean = false
  9193. // Whether the layer is wrapped around the antimeridian. If `true`, the
  9194. // GridLayer will only be displayed once at low zoom levels. Has no
  9195. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  9196. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  9197. // tiles outside the CRS limits.
  9198. noWrap: false,
  9199. // @option pane: String = 'tilePane'
  9200. // `Map pane` where the grid layer will be added.
  9201. pane: 'tilePane',
  9202. // @option className: String = ''
  9203. // A custom class name to assign to the tile layer. Empty by default.
  9204. className: '',
  9205. // @option keepBuffer: Number = 2
  9206. // When panning the map, keep this many rows and columns of tiles before unloading them.
  9207. keepBuffer: 2
  9208. },
  9209. initialize: function (options) {
  9210. setOptions(this, options);
  9211. },
  9212. onAdd: function () {
  9213. this._initContainer();
  9214. this._levels = {};
  9215. this._tiles = {};
  9216. this._resetView(); // implicit _update() call
  9217. },
  9218. beforeAdd: function (map) {
  9219. map._addZoomLimit(this);
  9220. },
  9221. onRemove: function (map) {
  9222. this._removeAllTiles();
  9223. remove(this._container);
  9224. map._removeZoomLimit(this);
  9225. this._container = null;
  9226. this._tileZoom = undefined;
  9227. },
  9228. // @method bringToFront: this
  9229. // Brings the tile layer to the top of all tile layers.
  9230. bringToFront: function () {
  9231. if (this._map) {
  9232. toFront(this._container);
  9233. this._setAutoZIndex(Math.max);
  9234. }
  9235. return this;
  9236. },
  9237. // @method bringToBack: this
  9238. // Brings the tile layer to the bottom of all tile layers.
  9239. bringToBack: function () {
  9240. if (this._map) {
  9241. toBack(this._container);
  9242. this._setAutoZIndex(Math.min);
  9243. }
  9244. return this;
  9245. },
  9246. // @method getContainer: HTMLElement
  9247. // Returns the HTML element that contains the tiles for this layer.
  9248. getContainer: function () {
  9249. return this._container;
  9250. },
  9251. // @method setOpacity(opacity: Number): this
  9252. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  9253. setOpacity: function (opacity) {
  9254. this.options.opacity = opacity;
  9255. this._updateOpacity();
  9256. return this;
  9257. },
  9258. // @method setZIndex(zIndex: Number): this
  9259. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  9260. setZIndex: function (zIndex) {
  9261. this.options.zIndex = zIndex;
  9262. this._updateZIndex();
  9263. return this;
  9264. },
  9265. // @method isLoading: Boolean
  9266. // Returns `true` if any tile in the grid layer has not finished loading.
  9267. isLoading: function () {
  9268. return this._loading;
  9269. },
  9270. // @method redraw: this
  9271. // Causes the layer to clear all the tiles and request them again.
  9272. redraw: function () {
  9273. if (this._map) {
  9274. this._removeAllTiles();
  9275. var tileZoom = this._clampZoom(this._map.getZoom());
  9276. if (tileZoom !== this._tileZoom) {
  9277. this._tileZoom = tileZoom;
  9278. this._updateLevels();
  9279. }
  9280. this._update();
  9281. }
  9282. return this;
  9283. },
  9284. getEvents: function () {
  9285. var events = {
  9286. viewprereset: this._invalidateAll,
  9287. viewreset: this._resetView,
  9288. zoom: this._resetView,
  9289. moveend: this._onMoveEnd
  9290. };
  9291. if (!this.options.updateWhenIdle) {
  9292. // update tiles on move, but not more often than once per given interval
  9293. if (!this._onMove) {
  9294. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  9295. }
  9296. events.move = this._onMove;
  9297. }
  9298. if (this._zoomAnimated) {
  9299. events.zoomanim = this._animateZoom;
  9300. }
  9301. return events;
  9302. },
  9303. // @section Extension methods
  9304. // Layers extending `GridLayer` shall reimplement the following method.
  9305. // @method createTile(coords: Object, done?: Function): HTMLElement
  9306. // Called only internally, must be overridden by classes extending `GridLayer`.
  9307. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  9308. // is specified, it must be called when the tile has finished loading and drawing.
  9309. createTile: function () {
  9310. return document.createElement('div');
  9311. },
  9312. // @section
  9313. // @method getTileSize: Point
  9314. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  9315. getTileSize: function () {
  9316. var s = this.options.tileSize;
  9317. return s instanceof Point ? s : new Point(s, s);
  9318. },
  9319. _updateZIndex: function () {
  9320. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  9321. this._container.style.zIndex = this.options.zIndex;
  9322. }
  9323. },
  9324. _setAutoZIndex: function (compare) {
  9325. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  9326. var layers = this.getPane().children,
  9327. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  9328. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  9329. zIndex = layers[i].style.zIndex;
  9330. if (layers[i] !== this._container && zIndex) {
  9331. edgeZIndex = compare(edgeZIndex, +zIndex);
  9332. }
  9333. }
  9334. if (isFinite(edgeZIndex)) {
  9335. this.options.zIndex = edgeZIndex + compare(-1, 1);
  9336. this._updateZIndex();
  9337. }
  9338. },
  9339. _updateOpacity: function () {
  9340. if (!this._map) { return; }
  9341. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  9342. if (Browser.ielt9) { return; }
  9343. setOpacity(this._container, this.options.opacity);
  9344. var now = +new Date(),
  9345. nextFrame = false,
  9346. willPrune = false;
  9347. for (var key in this._tiles) {
  9348. var tile = this._tiles[key];
  9349. if (!tile.current || !tile.loaded) { continue; }
  9350. var fade = Math.min(1, (now - tile.loaded) / 200);
  9351. setOpacity(tile.el, fade);
  9352. if (fade < 1) {
  9353. nextFrame = true;
  9354. } else {
  9355. if (tile.active) {
  9356. willPrune = true;
  9357. } else {
  9358. this._onOpaqueTile(tile);
  9359. }
  9360. tile.active = true;
  9361. }
  9362. }
  9363. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  9364. if (nextFrame) {
  9365. cancelAnimFrame(this._fadeFrame);
  9366. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9367. }
  9368. },
  9369. _onOpaqueTile: falseFn,
  9370. _initContainer: function () {
  9371. if (this._container) { return; }
  9372. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  9373. this._updateZIndex();
  9374. if (this.options.opacity < 1) {
  9375. this._updateOpacity();
  9376. }
  9377. this.getPane().appendChild(this._container);
  9378. },
  9379. _updateLevels: function () {
  9380. var zoom = this._tileZoom,
  9381. maxZoom = this.options.maxZoom;
  9382. if (zoom === undefined) { return undefined; }
  9383. for (var z in this._levels) {
  9384. z = Number(z);
  9385. if (this._levels[z].el.children.length || z === zoom) {
  9386. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  9387. this._onUpdateLevel(z);
  9388. } else {
  9389. remove(this._levels[z].el);
  9390. this._removeTilesAtZoom(z);
  9391. this._onRemoveLevel(z);
  9392. delete this._levels[z];
  9393. }
  9394. }
  9395. var level = this._levels[zoom],
  9396. map = this._map;
  9397. if (!level) {
  9398. level = this._levels[zoom] = {};
  9399. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  9400. level.el.style.zIndex = maxZoom;
  9401. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  9402. level.zoom = zoom;
  9403. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  9404. // force the browser to consider the newly added element for transition
  9405. falseFn(level.el.offsetWidth);
  9406. this._onCreateLevel(level);
  9407. }
  9408. this._level = level;
  9409. return level;
  9410. },
  9411. _onUpdateLevel: falseFn,
  9412. _onRemoveLevel: falseFn,
  9413. _onCreateLevel: falseFn,
  9414. _pruneTiles: function () {
  9415. if (!this._map) {
  9416. return;
  9417. }
  9418. var key, tile;
  9419. var zoom = this._map.getZoom();
  9420. if (zoom > this.options.maxZoom ||
  9421. zoom < this.options.minZoom) {
  9422. this._removeAllTiles();
  9423. return;
  9424. }
  9425. for (key in this._tiles) {
  9426. tile = this._tiles[key];
  9427. tile.retain = tile.current;
  9428. }
  9429. for (key in this._tiles) {
  9430. tile = this._tiles[key];
  9431. if (tile.current && !tile.active) {
  9432. var coords = tile.coords;
  9433. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  9434. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  9435. }
  9436. }
  9437. }
  9438. for (key in this._tiles) {
  9439. if (!this._tiles[key].retain) {
  9440. this._removeTile(key);
  9441. }
  9442. }
  9443. },
  9444. _removeTilesAtZoom: function (zoom) {
  9445. for (var key in this._tiles) {
  9446. if (this._tiles[key].coords.z !== zoom) {
  9447. continue;
  9448. }
  9449. this._removeTile(key);
  9450. }
  9451. },
  9452. _removeAllTiles: function () {
  9453. for (var key in this._tiles) {
  9454. this._removeTile(key);
  9455. }
  9456. },
  9457. _invalidateAll: function () {
  9458. for (var z in this._levels) {
  9459. remove(this._levels[z].el);
  9460. this._onRemoveLevel(Number(z));
  9461. delete this._levels[z];
  9462. }
  9463. this._removeAllTiles();
  9464. this._tileZoom = undefined;
  9465. },
  9466. _retainParent: function (x, y, z, minZoom) {
  9467. var x2 = Math.floor(x / 2),
  9468. y2 = Math.floor(y / 2),
  9469. z2 = z - 1,
  9470. coords2 = new Point(+x2, +y2);
  9471. coords2.z = +z2;
  9472. var key = this._tileCoordsToKey(coords2),
  9473. tile = this._tiles[key];
  9474. if (tile && tile.active) {
  9475. tile.retain = true;
  9476. return true;
  9477. } else if (tile && tile.loaded) {
  9478. tile.retain = true;
  9479. }
  9480. if (z2 > minZoom) {
  9481. return this._retainParent(x2, y2, z2, minZoom);
  9482. }
  9483. return false;
  9484. },
  9485. _retainChildren: function (x, y, z, maxZoom) {
  9486. for (var i = 2 * x; i < 2 * x + 2; i++) {
  9487. for (var j = 2 * y; j < 2 * y + 2; j++) {
  9488. var coords = new Point(i, j);
  9489. coords.z = z + 1;
  9490. var key = this._tileCoordsToKey(coords),
  9491. tile = this._tiles[key];
  9492. if (tile && tile.active) {
  9493. tile.retain = true;
  9494. continue;
  9495. } else if (tile && tile.loaded) {
  9496. tile.retain = true;
  9497. }
  9498. if (z + 1 < maxZoom) {
  9499. this._retainChildren(i, j, z + 1, maxZoom);
  9500. }
  9501. }
  9502. }
  9503. },
  9504. _resetView: function (e) {
  9505. var animating = e && (e.pinch || e.flyTo);
  9506. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  9507. },
  9508. _animateZoom: function (e) {
  9509. this._setView(e.center, e.zoom, true, e.noUpdate);
  9510. },
  9511. _clampZoom: function (zoom) {
  9512. var options = this.options;
  9513. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  9514. return options.minNativeZoom;
  9515. }
  9516. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  9517. return options.maxNativeZoom;
  9518. }
  9519. return zoom;
  9520. },
  9521. _setView: function (center, zoom, noPrune, noUpdate) {
  9522. var tileZoom = Math.round(zoom);
  9523. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  9524. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  9525. tileZoom = undefined;
  9526. } else {
  9527. tileZoom = this._clampZoom(tileZoom);
  9528. }
  9529. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  9530. if (!noUpdate || tileZoomChanged) {
  9531. this._tileZoom = tileZoom;
  9532. if (this._abortLoading) {
  9533. this._abortLoading();
  9534. }
  9535. this._updateLevels();
  9536. this._resetGrid();
  9537. if (tileZoom !== undefined) {
  9538. this._update(center);
  9539. }
  9540. if (!noPrune) {
  9541. this._pruneTiles();
  9542. }
  9543. // Flag to prevent _updateOpacity from pruning tiles during
  9544. // a zoom anim or a pinch gesture
  9545. this._noPrune = !!noPrune;
  9546. }
  9547. this._setZoomTransforms(center, zoom);
  9548. },
  9549. _setZoomTransforms: function (center, zoom) {
  9550. for (var i in this._levels) {
  9551. this._setZoomTransform(this._levels[i], center, zoom);
  9552. }
  9553. },
  9554. _setZoomTransform: function (level, center, zoom) {
  9555. var scale = this._map.getZoomScale(zoom, level.zoom),
  9556. translate = level.origin.multiplyBy(scale)
  9557. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  9558. if (Browser.any3d) {
  9559. setTransform(level.el, translate, scale);
  9560. } else {
  9561. setPosition(level.el, translate);
  9562. }
  9563. },
  9564. _resetGrid: function () {
  9565. var map = this._map,
  9566. crs = map.options.crs,
  9567. tileSize = this._tileSize = this.getTileSize(),
  9568. tileZoom = this._tileZoom;
  9569. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  9570. if (bounds) {
  9571. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  9572. }
  9573. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  9574. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  9575. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  9576. ];
  9577. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  9578. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  9579. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  9580. ];
  9581. },
  9582. _onMoveEnd: function () {
  9583. if (!this._map || this._map._animatingZoom) { return; }
  9584. this._update();
  9585. },
  9586. _getTiledPixelBounds: function (center) {
  9587. var map = this._map,
  9588. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9589. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9590. pixelCenter = map.project(center, this._tileZoom).floor(),
  9591. halfSize = map.getSize().divideBy(scale * 2);
  9592. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9593. },
  9594. // Private method to load tiles in the grid's active zoom level according to map bounds
  9595. _update: function (center) {
  9596. var map = this._map;
  9597. if (!map) { return; }
  9598. var zoom = this._clampZoom(map.getZoom());
  9599. if (center === undefined) { center = map.getCenter(); }
  9600. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  9601. var pixelBounds = this._getTiledPixelBounds(center),
  9602. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9603. tileCenter = tileRange.getCenter(),
  9604. queue = [],
  9605. margin = this.options.keepBuffer,
  9606. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9607. tileRange.getTopRight().add([margin, -margin]));
  9608. // Sanity check: panic if the tile range contains Infinity somewhere.
  9609. if (!(isFinite(tileRange.min.x) &&
  9610. isFinite(tileRange.min.y) &&
  9611. isFinite(tileRange.max.x) &&
  9612. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  9613. for (var key in this._tiles) {
  9614. var c = this._tiles[key].coords;
  9615. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9616. this._tiles[key].current = false;
  9617. }
  9618. }
  9619. // _update just loads more tiles. If the tile zoom level differs too much
  9620. // from the map's, let _setView reset levels and prune old tiles.
  9621. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  9622. // create a queue of coordinates to load tiles from
  9623. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9624. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9625. var coords = new Point(i, j);
  9626. coords.z = this._tileZoom;
  9627. if (!this._isValidTile(coords)) { continue; }
  9628. var tile = this._tiles[this._tileCoordsToKey(coords)];
  9629. if (tile) {
  9630. tile.current = true;
  9631. } else {
  9632. queue.push(coords);
  9633. }
  9634. }
  9635. }
  9636. // sort tile queue to load tiles in order of their distance to center
  9637. queue.sort(function (a, b) {
  9638. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9639. });
  9640. if (queue.length !== 0) {
  9641. // if it's the first batch of tiles to load
  9642. if (!this._loading) {
  9643. this._loading = true;
  9644. // @event loading: Event
  9645. // Fired when the grid layer starts loading tiles.
  9646. this.fire('loading');
  9647. }
  9648. // create DOM fragment to append tiles in one batch
  9649. var fragment = document.createDocumentFragment();
  9650. for (i = 0; i < queue.length; i++) {
  9651. this._addTile(queue[i], fragment);
  9652. }
  9653. this._level.el.appendChild(fragment);
  9654. }
  9655. },
  9656. _isValidTile: function (coords) {
  9657. var crs = this._map.options.crs;
  9658. if (!crs.infinite) {
  9659. // don't load tile if it's out of bounds and not wrapped
  9660. var bounds = this._globalTileRange;
  9661. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9662. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  9663. }
  9664. if (!this.options.bounds) { return true; }
  9665. // don't load tile if it doesn't intersect the bounds in options
  9666. var tileBounds = this._tileCoordsToBounds(coords);
  9667. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9668. },
  9669. _keyToBounds: function (key) {
  9670. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9671. },
  9672. _tileCoordsToNwSe: function (coords) {
  9673. var map = this._map,
  9674. tileSize = this.getTileSize(),
  9675. nwPoint = coords.scaleBy(tileSize),
  9676. sePoint = nwPoint.add(tileSize),
  9677. nw = map.unproject(nwPoint, coords.z),
  9678. se = map.unproject(sePoint, coords.z);
  9679. return [nw, se];
  9680. },
  9681. // converts tile coordinates to its geographical bounds
  9682. _tileCoordsToBounds: function (coords) {
  9683. var bp = this._tileCoordsToNwSe(coords),
  9684. bounds = new LatLngBounds(bp[0], bp[1]);
  9685. if (!this.options.noWrap) {
  9686. bounds = this._map.wrapLatLngBounds(bounds);
  9687. }
  9688. return bounds;
  9689. },
  9690. // converts tile coordinates to key for the tile cache
  9691. _tileCoordsToKey: function (coords) {
  9692. return coords.x + ':' + coords.y + ':' + coords.z;
  9693. },
  9694. // converts tile cache key to coordinates
  9695. _keyToTileCoords: function (key) {
  9696. var k = key.split(':'),
  9697. coords = new Point(+k[0], +k[1]);
  9698. coords.z = +k[2];
  9699. return coords;
  9700. },
  9701. _removeTile: function (key) {
  9702. var tile = this._tiles[key];
  9703. if (!tile) { return; }
  9704. remove(tile.el);
  9705. delete this._tiles[key];
  9706. // @event tileunload: TileEvent
  9707. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9708. this.fire('tileunload', {
  9709. tile: tile.el,
  9710. coords: this._keyToTileCoords(key)
  9711. });
  9712. },
  9713. _initTile: function (tile) {
  9714. addClass(tile, 'leaflet-tile');
  9715. var tileSize = this.getTileSize();
  9716. tile.style.width = tileSize.x + 'px';
  9717. tile.style.height = tileSize.y + 'px';
  9718. tile.onselectstart = falseFn;
  9719. tile.onmousemove = falseFn;
  9720. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9721. if (Browser.ielt9 && this.options.opacity < 1) {
  9722. setOpacity(tile, this.options.opacity);
  9723. }
  9724. },
  9725. _addTile: function (coords, container) {
  9726. var tilePos = this._getTilePos(coords),
  9727. key = this._tileCoordsToKey(coords);
  9728. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9729. this._initTile(tile);
  9730. // if createTile is defined with a second argument ("done" callback),
  9731. // we know that tile is async and will be ready later; otherwise
  9732. if (this.createTile.length < 2) {
  9733. // mark tile as ready, but delay one frame for opacity animation to happen
  9734. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9735. }
  9736. setPosition(tile, tilePos);
  9737. // save tile in cache
  9738. this._tiles[key] = {
  9739. el: tile,
  9740. coords: coords,
  9741. current: true
  9742. };
  9743. container.appendChild(tile);
  9744. // @event tileloadstart: TileEvent
  9745. // Fired when a tile is requested and starts loading.
  9746. this.fire('tileloadstart', {
  9747. tile: tile,
  9748. coords: coords
  9749. });
  9750. },
  9751. _tileReady: function (coords, err, tile) {
  9752. if (err) {
  9753. // @event tileerror: TileErrorEvent
  9754. // Fired when there is an error loading a tile.
  9755. this.fire('tileerror', {
  9756. error: err,
  9757. tile: tile,
  9758. coords: coords
  9759. });
  9760. }
  9761. var key = this._tileCoordsToKey(coords);
  9762. tile = this._tiles[key];
  9763. if (!tile) { return; }
  9764. tile.loaded = +new Date();
  9765. if (this._map._fadeAnimated) {
  9766. setOpacity(tile.el, 0);
  9767. cancelAnimFrame(this._fadeFrame);
  9768. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9769. } else {
  9770. tile.active = true;
  9771. this._pruneTiles();
  9772. }
  9773. if (!err) {
  9774. addClass(tile.el, 'leaflet-tile-loaded');
  9775. // @event tileload: TileEvent
  9776. // Fired when a tile loads.
  9777. this.fire('tileload', {
  9778. tile: tile.el,
  9779. coords: coords
  9780. });
  9781. }
  9782. if (this._noTilesToLoad()) {
  9783. this._loading = false;
  9784. // @event load: Event
  9785. // Fired when the grid layer loaded all visible tiles.
  9786. this.fire('load');
  9787. if (Browser.ielt9 || !this._map._fadeAnimated) {
  9788. requestAnimFrame(this._pruneTiles, this);
  9789. } else {
  9790. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9791. // to trigger a pruning.
  9792. setTimeout(bind(this._pruneTiles, this), 250);
  9793. }
  9794. }
  9795. },
  9796. _getTilePos: function (coords) {
  9797. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9798. },
  9799. _wrapCoords: function (coords) {
  9800. var newCoords = new Point(
  9801. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9802. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9803. newCoords.z = coords.z;
  9804. return newCoords;
  9805. },
  9806. _pxBoundsToTileRange: function (bounds) {
  9807. var tileSize = this.getTileSize();
  9808. return new Bounds(
  9809. bounds.min.unscaleBy(tileSize).floor(),
  9810. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9811. },
  9812. _noTilesToLoad: function () {
  9813. for (var key in this._tiles) {
  9814. if (!this._tiles[key].loaded) { return false; }
  9815. }
  9816. return true;
  9817. }
  9818. });
  9819. // @factory L.gridLayer(options?: GridLayer options)
  9820. // Creates a new instance of GridLayer with the supplied options.
  9821. function gridLayer(options) {
  9822. return new GridLayer(options);
  9823. }
  9824. /*
  9825. * @class TileLayer
  9826. * @inherits GridLayer
  9827. * @aka L.TileLayer
  9828. * Used to load and display tile layers on the map. Note that most tile servers require attribution, which you can set under `Layer`. Extends `GridLayer`.
  9829. *
  9830. * @example
  9831. *
  9832. * ```js
  9833. * L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);
  9834. * ```
  9835. *
  9836. * @section URL template
  9837. * @example
  9838. *
  9839. * A string of the following form:
  9840. *
  9841. * ```
  9842. * 'https://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9843. * ```
  9844. *
  9845. * `{s}` means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; `a`, `b` or `c` by default, can be omitted), `{z}` — zoom level, `{x}` and `{y}` — tile coordinates. `{r}` can be used to add "&commat;2x" to the URL to load retina tiles.
  9846. *
  9847. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9848. *
  9849. * ```
  9850. * L.tileLayer('https://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9851. * ```
  9852. */
  9853. var TileLayer = GridLayer.extend({
  9854. // @section
  9855. // @aka TileLayer options
  9856. options: {
  9857. // @option minZoom: Number = 0
  9858. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9859. minZoom: 0,
  9860. // @option maxZoom: Number = 18
  9861. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9862. maxZoom: 18,
  9863. // @option subdomains: String|String[] = 'abc'
  9864. // 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.
  9865. subdomains: 'abc',
  9866. // @option errorTileUrl: String = ''
  9867. // URL to the tile image to show in place of the tile that failed to load.
  9868. errorTileUrl: '',
  9869. // @option zoomOffset: Number = 0
  9870. // The zoom number used in tile URLs will be offset with this value.
  9871. zoomOffset: 0,
  9872. // @option tms: Boolean = false
  9873. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9874. tms: false,
  9875. // @option zoomReverse: Boolean = false
  9876. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9877. zoomReverse: false,
  9878. // @option detectRetina: Boolean = false
  9879. // 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.
  9880. detectRetina: false,
  9881. // @option crossOrigin: Boolean|String = false
  9882. // Whether the crossOrigin attribute will be added to the tiles.
  9883. // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
  9884. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  9885. crossOrigin: false,
  9886. // @option referrerPolicy: Boolean|String = false
  9887. // Whether the referrerPolicy attribute will be added to the tiles.
  9888. // If a String is provided, all tiles will have their referrerPolicy attribute set to the String provided.
  9889. // This may be needed if your map's rendering context has a strict default but your tile provider expects a valid referrer
  9890. // (e.g. to validate an API token).
  9891. // Refer to [HTMLImageElement.referrerPolicy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/referrerPolicy) for valid String values.
  9892. referrerPolicy: false
  9893. },
  9894. initialize: function (url, options) {
  9895. this._url = url;
  9896. options = setOptions(this, options);
  9897. // detecting retina displays, adjusting tileSize and zoom levels
  9898. if (options.detectRetina && Browser.retina && options.maxZoom > 0) {
  9899. options.tileSize = Math.floor(options.tileSize / 2);
  9900. if (!options.zoomReverse) {
  9901. options.zoomOffset++;
  9902. options.maxZoom = Math.max(options.minZoom, options.maxZoom - 1);
  9903. } else {
  9904. options.zoomOffset--;
  9905. options.minZoom = Math.min(options.maxZoom, options.minZoom + 1);
  9906. }
  9907. options.minZoom = Math.max(0, options.minZoom);
  9908. } else if (!options.zoomReverse) {
  9909. // make sure maxZoom is gte minZoom
  9910. options.maxZoom = Math.max(options.minZoom, options.maxZoom);
  9911. } else {
  9912. // make sure minZoom is lte maxZoom
  9913. options.minZoom = Math.min(options.maxZoom, options.minZoom);
  9914. }
  9915. if (typeof options.subdomains === 'string') {
  9916. options.subdomains = options.subdomains.split('');
  9917. }
  9918. this.on('tileunload', this._onTileRemove);
  9919. },
  9920. // @method setUrl(url: String, noRedraw?: Boolean): this
  9921. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9922. // If the URL does not change, the layer will not be redrawn unless
  9923. // the noRedraw parameter is set to false.
  9924. setUrl: function (url, noRedraw) {
  9925. if (this._url === url && noRedraw === undefined) {
  9926. noRedraw = true;
  9927. }
  9928. this._url = url;
  9929. if (!noRedraw) {
  9930. this.redraw();
  9931. }
  9932. return this;
  9933. },
  9934. // @method createTile(coords: Object, done?: Function): HTMLElement
  9935. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9936. // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
  9937. // callback is called when the tile has been loaded.
  9938. createTile: function (coords, done) {
  9939. var tile = document.createElement('img');
  9940. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9941. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9942. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  9943. tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  9944. }
  9945. // for this new option we follow the documented behavior
  9946. // more closely by only setting the property when string
  9947. if (typeof this.options.referrerPolicy === 'string') {
  9948. tile.referrerPolicy = this.options.referrerPolicy;
  9949. }
  9950. // The alt attribute is set to the empty string,
  9951. // allowing screen readers to ignore the decorative image tiles.
  9952. // https://www.w3.org/WAI/tutorials/images/decorative/
  9953. // https://www.w3.org/TR/html-aria/#el-img-empty-alt
  9954. tile.alt = '';
  9955. tile.src = this.getTileUrl(coords);
  9956. return tile;
  9957. },
  9958. // @section Extension methods
  9959. // @uninheritable
  9960. // Layers extending `TileLayer` might reimplement the following method.
  9961. // @method getTileUrl(coords: Object): String
  9962. // Called only internally, returns the URL for a tile given its coordinates.
  9963. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9964. getTileUrl: function (coords) {
  9965. var data = {
  9966. r: Browser.retina ? '@2x' : '',
  9967. s: this._getSubdomain(coords),
  9968. x: coords.x,
  9969. y: coords.y,
  9970. z: this._getZoomForUrl()
  9971. };
  9972. if (this._map && !this._map.options.crs.infinite) {
  9973. var invertedY = this._globalTileRange.max.y - coords.y;
  9974. if (this.options.tms) {
  9975. data['y'] = invertedY;
  9976. }
  9977. data['-y'] = invertedY;
  9978. }
  9979. return template(this._url, extend(data, this.options));
  9980. },
  9981. _tileOnLoad: function (done, tile) {
  9982. // For https://github.com/Leaflet/Leaflet/issues/3332
  9983. if (Browser.ielt9) {
  9984. setTimeout(bind(done, this, null, tile), 0);
  9985. } else {
  9986. done(null, tile);
  9987. }
  9988. },
  9989. _tileOnError: function (done, tile, e) {
  9990. var errorUrl = this.options.errorTileUrl;
  9991. if (errorUrl && tile.getAttribute('src') !== errorUrl) {
  9992. tile.src = errorUrl;
  9993. }
  9994. done(e, tile);
  9995. },
  9996. _onTileRemove: function (e) {
  9997. e.tile.onload = null;
  9998. },
  9999. _getZoomForUrl: function () {
  10000. var zoom = this._tileZoom,
  10001. maxZoom = this.options.maxZoom,
  10002. zoomReverse = this.options.zoomReverse,
  10003. zoomOffset = this.options.zoomOffset;
  10004. if (zoomReverse) {
  10005. zoom = maxZoom - zoom;
  10006. }
  10007. return zoom + zoomOffset;
  10008. },
  10009. _getSubdomain: function (tilePoint) {
  10010. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  10011. return this.options.subdomains[index];
  10012. },
  10013. // stops loading all tiles in the background layer
  10014. _abortLoading: function () {
  10015. var i, tile;
  10016. for (i in this._tiles) {
  10017. if (this._tiles[i].coords.z !== this._tileZoom) {
  10018. tile = this._tiles[i].el;
  10019. tile.onload = falseFn;
  10020. tile.onerror = falseFn;
  10021. if (!tile.complete) {
  10022. tile.src = emptyImageUrl;
  10023. var coords = this._tiles[i].coords;
  10024. remove(tile);
  10025. delete this._tiles[i];
  10026. // @event tileabort: TileEvent
  10027. // Fired when a tile was loading but is now not wanted.
  10028. this.fire('tileabort', {
  10029. tile: tile,
  10030. coords: coords
  10031. });
  10032. }
  10033. }
  10034. }
  10035. },
  10036. _removeTile: function (key) {
  10037. var tile = this._tiles[key];
  10038. if (!tile) { return; }
  10039. // Cancels any pending http requests associated with the tile
  10040. tile.el.setAttribute('src', emptyImageUrl);
  10041. return GridLayer.prototype._removeTile.call(this, key);
  10042. },
  10043. _tileReady: function (coords, err, tile) {
  10044. if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) {
  10045. return;
  10046. }
  10047. return GridLayer.prototype._tileReady.call(this, coords, err, tile);
  10048. }
  10049. });
  10050. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  10051. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  10052. function tileLayer(url, options) {
  10053. return new TileLayer(url, options);
  10054. }
  10055. /*
  10056. * @class TileLayer.WMS
  10057. * @inherits TileLayer
  10058. * @aka L.TileLayer.WMS
  10059. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  10060. *
  10061. * @example
  10062. *
  10063. * ```js
  10064. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  10065. * layers: 'nexrad-n0r-900913',
  10066. * format: 'image/png',
  10067. * transparent: true,
  10068. * attribution: "Weather data © 2012 IEM Nexrad"
  10069. * });
  10070. * ```
  10071. */
  10072. var TileLayerWMS = TileLayer.extend({
  10073. // @section
  10074. // @aka TileLayer.WMS options
  10075. // If any custom options not documented here are used, they will be sent to the
  10076. // WMS server as extra parameters in each request URL. This can be useful for
  10077. // [non-standard vendor WMS parameters](https://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  10078. defaultWmsParams: {
  10079. service: 'WMS',
  10080. request: 'GetMap',
  10081. // @option layers: String = ''
  10082. // **(required)** Comma-separated list of WMS layers to show.
  10083. layers: '',
  10084. // @option styles: String = ''
  10085. // Comma-separated list of WMS styles.
  10086. styles: '',
  10087. // @option format: String = 'image/jpeg'
  10088. // WMS image format (use `'image/png'` for layers with transparency).
  10089. format: 'image/jpeg',
  10090. // @option transparent: Boolean = false
  10091. // If `true`, the WMS service will return images with transparency.
  10092. transparent: false,
  10093. // @option version: String = '1.1.1'
  10094. // Version of the WMS service to use
  10095. version: '1.1.1'
  10096. },
  10097. options: {
  10098. // @option crs: CRS = null
  10099. // Coordinate Reference System to use for the WMS requests, defaults to
  10100. // map CRS. Don't change this if you're not sure what it means.
  10101. crs: null,
  10102. // @option uppercase: Boolean = false
  10103. // If `true`, WMS request parameter keys will be uppercase.
  10104. uppercase: false
  10105. },
  10106. initialize: function (url, options) {
  10107. this._url = url;
  10108. var wmsParams = extend({}, this.defaultWmsParams);
  10109. // all keys that are not TileLayer options go to WMS params
  10110. for (var i in options) {
  10111. if (!(i in this.options)) {
  10112. wmsParams[i] = options[i];
  10113. }
  10114. }
  10115. options = setOptions(this, options);
  10116. var realRetina = options.detectRetina && Browser.retina ? 2 : 1;
  10117. var tileSize = this.getTileSize();
  10118. wmsParams.width = tileSize.x * realRetina;
  10119. wmsParams.height = tileSize.y * realRetina;
  10120. this.wmsParams = wmsParams;
  10121. },
  10122. onAdd: function (map) {
  10123. this._crs = this.options.crs || map.options.crs;
  10124. this._wmsVersion = parseFloat(this.wmsParams.version);
  10125. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  10126. this.wmsParams[projectionKey] = this._crs.code;
  10127. TileLayer.prototype.onAdd.call(this, map);
  10128. },
  10129. getTileUrl: function (coords) {
  10130. var tileBounds = this._tileCoordsToNwSe(coords),
  10131. crs = this._crs,
  10132. bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
  10133. min = bounds.min,
  10134. max = bounds.max,
  10135. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  10136. [min.y, min.x, max.y, max.x] :
  10137. [min.x, min.y, max.x, max.y]).join(','),
  10138. url = TileLayer.prototype.getTileUrl.call(this, coords);
  10139. return url +
  10140. getParamString(this.wmsParams, url, this.options.uppercase) +
  10141. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  10142. },
  10143. // @method setParams(params: Object, noRedraw?: Boolean): this
  10144. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  10145. setParams: function (params, noRedraw) {
  10146. extend(this.wmsParams, params);
  10147. if (!noRedraw) {
  10148. this.redraw();
  10149. }
  10150. return this;
  10151. }
  10152. });
  10153. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  10154. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  10155. function tileLayerWMS(url, options) {
  10156. return new TileLayerWMS(url, options);
  10157. }
  10158. TileLayer.WMS = TileLayerWMS;
  10159. tileLayer.wms = tileLayerWMS;
  10160. /*
  10161. * @class Renderer
  10162. * @inherits Layer
  10163. * @aka L.Renderer
  10164. *
  10165. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  10166. * DOM container of the renderer, its bounds, and its zoom animation.
  10167. *
  10168. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  10169. * itself can be added or removed to the map. All paths use a renderer, which can
  10170. * be implicit (the map will decide the type of renderer and use it automatically)
  10171. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  10172. *
  10173. * Do not use this class directly, use `SVG` and `Canvas` instead.
  10174. *
  10175. * @event update: Event
  10176. * Fired when the renderer updates its bounds, center and zoom, for example when
  10177. * its map has moved
  10178. */
  10179. var Renderer = Layer.extend({
  10180. // @section
  10181. // @aka Renderer options
  10182. options: {
  10183. // @option padding: Number = 0.1
  10184. // How much to extend the clip area around the map view (relative to its size)
  10185. // e.g. 0.1 would be 10% of map view in each direction
  10186. padding: 0.1
  10187. },
  10188. initialize: function (options) {
  10189. setOptions(this, options);
  10190. stamp(this);
  10191. this._layers = this._layers || {};
  10192. },
  10193. onAdd: function () {
  10194. if (!this._container) {
  10195. this._initContainer(); // defined by renderer implementations
  10196. if (this._zoomAnimated) {
  10197. addClass(this._container, 'leaflet-zoom-animated');
  10198. }
  10199. }
  10200. this.getPane().appendChild(this._container);
  10201. this._update();
  10202. this.on('update', this._updatePaths, this);
  10203. },
  10204. onRemove: function () {
  10205. this.off('update', this._updatePaths, this);
  10206. this._destroyContainer();
  10207. },
  10208. getEvents: function () {
  10209. var events = {
  10210. viewreset: this._reset,
  10211. zoom: this._onZoom,
  10212. moveend: this._update,
  10213. zoomend: this._onZoomEnd
  10214. };
  10215. if (this._zoomAnimated) {
  10216. events.zoomanim = this._onAnimZoom;
  10217. }
  10218. return events;
  10219. },
  10220. _onAnimZoom: function (ev) {
  10221. this._updateTransform(ev.center, ev.zoom);
  10222. },
  10223. _onZoom: function () {
  10224. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  10225. },
  10226. _updateTransform: function (center, zoom) {
  10227. var scale = this._map.getZoomScale(zoom, this._zoom),
  10228. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  10229. currentCenterPoint = this._map.project(this._center, zoom),
  10230. topLeftOffset = viewHalf.multiplyBy(-scale).add(currentCenterPoint)
  10231. .subtract(this._map._getNewPixelOrigin(center, zoom));
  10232. if (Browser.any3d) {
  10233. setTransform(this._container, topLeftOffset, scale);
  10234. } else {
  10235. setPosition(this._container, topLeftOffset);
  10236. }
  10237. },
  10238. _reset: function () {
  10239. this._update();
  10240. this._updateTransform(this._center, this._zoom);
  10241. for (var id in this._layers) {
  10242. this._layers[id]._reset();
  10243. }
  10244. },
  10245. _onZoomEnd: function () {
  10246. for (var id in this._layers) {
  10247. this._layers[id]._project();
  10248. }
  10249. },
  10250. _updatePaths: function () {
  10251. for (var id in this._layers) {
  10252. this._layers[id]._update();
  10253. }
  10254. },
  10255. _update: function () {
  10256. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  10257. // Subclasses are responsible of firing the 'update' event.
  10258. var p = this.options.padding,
  10259. size = this._map.getSize(),
  10260. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  10261. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  10262. this._center = this._map.getCenter();
  10263. this._zoom = this._map.getZoom();
  10264. }
  10265. });
  10266. /*
  10267. * @class Canvas
  10268. * @inherits Renderer
  10269. * @aka L.Canvas
  10270. *
  10271. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  10272. * Inherits `Renderer`.
  10273. *
  10274. * Due to [technical limitations](https://caniuse.com/canvas), Canvas is not
  10275. * available in all web browsers, notably IE8, and overlapping geometries might
  10276. * not display properly in some edge cases.
  10277. *
  10278. * @example
  10279. *
  10280. * Use Canvas by default for all paths in the map:
  10281. *
  10282. * ```js
  10283. * var map = L.map('map', {
  10284. * renderer: L.canvas()
  10285. * });
  10286. * ```
  10287. *
  10288. * Use a Canvas renderer with extra padding for specific vector geometries:
  10289. *
  10290. * ```js
  10291. * var map = L.map('map');
  10292. * var myRenderer = L.canvas({ padding: 0.5 });
  10293. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10294. * var circle = L.circle( center, { renderer: myRenderer } );
  10295. * ```
  10296. */
  10297. var Canvas = Renderer.extend({
  10298. // @section
  10299. // @aka Canvas options
  10300. options: {
  10301. // @option tolerance: Number = 0
  10302. // How much to extend the click tolerance around a path/object on the map.
  10303. tolerance: 0
  10304. },
  10305. getEvents: function () {
  10306. var events = Renderer.prototype.getEvents.call(this);
  10307. events.viewprereset = this._onViewPreReset;
  10308. return events;
  10309. },
  10310. _onViewPreReset: function () {
  10311. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  10312. this._postponeUpdatePaths = true;
  10313. },
  10314. onAdd: function () {
  10315. Renderer.prototype.onAdd.call(this);
  10316. // Redraw vectors since canvas is cleared upon removal,
  10317. // in case of removing the renderer itself from the map.
  10318. this._draw();
  10319. },
  10320. _initContainer: function () {
  10321. var container = this._container = document.createElement('canvas');
  10322. on(container, 'mousemove', this._onMouseMove, this);
  10323. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  10324. on(container, 'mouseout', this._handleMouseOut, this);
  10325. container['_leaflet_disable_events'] = true;
  10326. this._ctx = container.getContext('2d');
  10327. },
  10328. _destroyContainer: function () {
  10329. cancelAnimFrame(this._redrawRequest);
  10330. delete this._ctx;
  10331. remove(this._container);
  10332. off(this._container);
  10333. delete this._container;
  10334. },
  10335. _updatePaths: function () {
  10336. if (this._postponeUpdatePaths) { return; }
  10337. var layer;
  10338. this._redrawBounds = null;
  10339. for (var id in this._layers) {
  10340. layer = this._layers[id];
  10341. layer._update();
  10342. }
  10343. this._redraw();
  10344. },
  10345. _update: function () {
  10346. if (this._map._animatingZoom && this._bounds) { return; }
  10347. Renderer.prototype._update.call(this);
  10348. var b = this._bounds,
  10349. container = this._container,
  10350. size = b.getSize(),
  10351. m = Browser.retina ? 2 : 1;
  10352. setPosition(container, b.min);
  10353. // set canvas size (also clearing it); use double size on retina
  10354. container.width = m * size.x;
  10355. container.height = m * size.y;
  10356. container.style.width = size.x + 'px';
  10357. container.style.height = size.y + 'px';
  10358. if (Browser.retina) {
  10359. this._ctx.scale(2, 2);
  10360. }
  10361. // translate so we use the same path coordinates after canvas element moves
  10362. this._ctx.translate(-b.min.x, -b.min.y);
  10363. // Tell paths to redraw themselves
  10364. this.fire('update');
  10365. },
  10366. _reset: function () {
  10367. Renderer.prototype._reset.call(this);
  10368. if (this._postponeUpdatePaths) {
  10369. this._postponeUpdatePaths = false;
  10370. this._updatePaths();
  10371. }
  10372. },
  10373. _initPath: function (layer) {
  10374. this._updateDashArray(layer);
  10375. this._layers[stamp(layer)] = layer;
  10376. var order = layer._order = {
  10377. layer: layer,
  10378. prev: this._drawLast,
  10379. next: null
  10380. };
  10381. if (this._drawLast) { this._drawLast.next = order; }
  10382. this._drawLast = order;
  10383. this._drawFirst = this._drawFirst || this._drawLast;
  10384. },
  10385. _addPath: function (layer) {
  10386. this._requestRedraw(layer);
  10387. },
  10388. _removePath: function (layer) {
  10389. var order = layer._order;
  10390. var next = order.next;
  10391. var prev = order.prev;
  10392. if (next) {
  10393. next.prev = prev;
  10394. } else {
  10395. this._drawLast = prev;
  10396. }
  10397. if (prev) {
  10398. prev.next = next;
  10399. } else {
  10400. this._drawFirst = next;
  10401. }
  10402. delete layer._order;
  10403. delete this._layers[stamp(layer)];
  10404. this._requestRedraw(layer);
  10405. },
  10406. _updatePath: function (layer) {
  10407. // Redraw the union of the layer's old pixel
  10408. // bounds and the new pixel bounds.
  10409. this._extendRedrawBounds(layer);
  10410. layer._project();
  10411. layer._update();
  10412. // The redraw will extend the redraw bounds
  10413. // with the new pixel bounds.
  10414. this._requestRedraw(layer);
  10415. },
  10416. _updateStyle: function (layer) {
  10417. this._updateDashArray(layer);
  10418. this._requestRedraw(layer);
  10419. },
  10420. _updateDashArray: function (layer) {
  10421. if (typeof layer.options.dashArray === 'string') {
  10422. var parts = layer.options.dashArray.split(/[, ]+/),
  10423. dashArray = [],
  10424. dashValue,
  10425. i;
  10426. for (i = 0; i < parts.length; i++) {
  10427. dashValue = Number(parts[i]);
  10428. // Ignore dash array containing invalid lengths
  10429. if (isNaN(dashValue)) { return; }
  10430. dashArray.push(dashValue);
  10431. }
  10432. layer.options._dashArray = dashArray;
  10433. } else {
  10434. layer.options._dashArray = layer.options.dashArray;
  10435. }
  10436. },
  10437. _requestRedraw: function (layer) {
  10438. if (!this._map) { return; }
  10439. this._extendRedrawBounds(layer);
  10440. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  10441. },
  10442. _extendRedrawBounds: function (layer) {
  10443. if (layer._pxBounds) {
  10444. var padding = (layer.options.weight || 0) + 1;
  10445. this._redrawBounds = this._redrawBounds || new Bounds();
  10446. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  10447. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  10448. }
  10449. },
  10450. _redraw: function () {
  10451. this._redrawRequest = null;
  10452. if (this._redrawBounds) {
  10453. this._redrawBounds.min._floor();
  10454. this._redrawBounds.max._ceil();
  10455. }
  10456. this._clear(); // clear layers in redraw bounds
  10457. this._draw(); // draw layers
  10458. this._redrawBounds = null;
  10459. },
  10460. _clear: function () {
  10461. var bounds = this._redrawBounds;
  10462. if (bounds) {
  10463. var size = bounds.getSize();
  10464. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  10465. } else {
  10466. this._ctx.save();
  10467. this._ctx.setTransform(1, 0, 0, 1, 0, 0);
  10468. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  10469. this._ctx.restore();
  10470. }
  10471. },
  10472. _draw: function () {
  10473. var layer, bounds = this._redrawBounds;
  10474. this._ctx.save();
  10475. if (bounds) {
  10476. var size = bounds.getSize();
  10477. this._ctx.beginPath();
  10478. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  10479. this._ctx.clip();
  10480. }
  10481. this._drawing = true;
  10482. for (var order = this._drawFirst; order; order = order.next) {
  10483. layer = order.layer;
  10484. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  10485. layer._updatePath();
  10486. }
  10487. }
  10488. this._drawing = false;
  10489. this._ctx.restore(); // Restore state before clipping.
  10490. },
  10491. _updatePoly: function (layer, closed) {
  10492. if (!this._drawing) { return; }
  10493. var i, j, len2, p,
  10494. parts = layer._parts,
  10495. len = parts.length,
  10496. ctx = this._ctx;
  10497. if (!len) { return; }
  10498. ctx.beginPath();
  10499. for (i = 0; i < len; i++) {
  10500. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  10501. p = parts[i][j];
  10502. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  10503. }
  10504. if (closed) {
  10505. ctx.closePath();
  10506. }
  10507. }
  10508. this._fillStroke(ctx, layer);
  10509. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  10510. },
  10511. _updateCircle: function (layer) {
  10512. if (!this._drawing || layer._empty()) { return; }
  10513. var p = layer._point,
  10514. ctx = this._ctx,
  10515. r = Math.max(Math.round(layer._radius), 1),
  10516. s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
  10517. if (s !== 1) {
  10518. ctx.save();
  10519. ctx.scale(1, s);
  10520. }
  10521. ctx.beginPath();
  10522. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  10523. if (s !== 1) {
  10524. ctx.restore();
  10525. }
  10526. this._fillStroke(ctx, layer);
  10527. },
  10528. _fillStroke: function (ctx, layer) {
  10529. var options = layer.options;
  10530. if (options.fill) {
  10531. ctx.globalAlpha = options.fillOpacity;
  10532. ctx.fillStyle = options.fillColor || options.color;
  10533. ctx.fill(options.fillRule || 'evenodd');
  10534. }
  10535. if (options.stroke && options.weight !== 0) {
  10536. if (ctx.setLineDash) {
  10537. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  10538. }
  10539. ctx.globalAlpha = options.opacity;
  10540. ctx.lineWidth = options.weight;
  10541. ctx.strokeStyle = options.color;
  10542. ctx.lineCap = options.lineCap;
  10543. ctx.lineJoin = options.lineJoin;
  10544. ctx.stroke();
  10545. }
  10546. },
  10547. // Canvas obviously doesn't have mouse events for individual drawn objects,
  10548. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  10549. _onClick: function (e) {
  10550. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  10551. for (var order = this._drawFirst; order; order = order.next) {
  10552. layer = order.layer;
  10553. if (layer.options.interactive && layer._containsPoint(point)) {
  10554. if (!(e.type === 'click' || e.type === 'preclick') || !this._map._draggableMoved(layer)) {
  10555. clickedLayer = layer;
  10556. }
  10557. }
  10558. }
  10559. this._fireEvent(clickedLayer ? [clickedLayer] : false, e);
  10560. },
  10561. _onMouseMove: function (e) {
  10562. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  10563. var point = this._map.mouseEventToLayerPoint(e);
  10564. this._handleMouseHover(e, point);
  10565. },
  10566. _handleMouseOut: function (e) {
  10567. var layer = this._hoveredLayer;
  10568. if (layer) {
  10569. // if we're leaving the layer, fire mouseout
  10570. removeClass(this._container, 'leaflet-interactive');
  10571. this._fireEvent([layer], e, 'mouseout');
  10572. this._hoveredLayer = null;
  10573. this._mouseHoverThrottled = false;
  10574. }
  10575. },
  10576. _handleMouseHover: function (e, point) {
  10577. if (this._mouseHoverThrottled) {
  10578. return;
  10579. }
  10580. var layer, candidateHoveredLayer;
  10581. for (var order = this._drawFirst; order; order = order.next) {
  10582. layer = order.layer;
  10583. if (layer.options.interactive && layer._containsPoint(point)) {
  10584. candidateHoveredLayer = layer;
  10585. }
  10586. }
  10587. if (candidateHoveredLayer !== this._hoveredLayer) {
  10588. this._handleMouseOut(e);
  10589. if (candidateHoveredLayer) {
  10590. addClass(this._container, 'leaflet-interactive'); // change cursor
  10591. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  10592. this._hoveredLayer = candidateHoveredLayer;
  10593. }
  10594. }
  10595. this._fireEvent(this._hoveredLayer ? [this._hoveredLayer] : false, e);
  10596. this._mouseHoverThrottled = true;
  10597. setTimeout(bind(function () {
  10598. this._mouseHoverThrottled = false;
  10599. }, this), 32);
  10600. },
  10601. _fireEvent: function (layers, e, type) {
  10602. this._map._fireDOMEvent(e, type || e.type, layers);
  10603. },
  10604. _bringToFront: function (layer) {
  10605. var order = layer._order;
  10606. if (!order) { return; }
  10607. var next = order.next;
  10608. var prev = order.prev;
  10609. if (next) {
  10610. next.prev = prev;
  10611. } else {
  10612. // Already last
  10613. return;
  10614. }
  10615. if (prev) {
  10616. prev.next = next;
  10617. } else if (next) {
  10618. // Update first entry unless this is the
  10619. // single entry
  10620. this._drawFirst = next;
  10621. }
  10622. order.prev = this._drawLast;
  10623. this._drawLast.next = order;
  10624. order.next = null;
  10625. this._drawLast = order;
  10626. this._requestRedraw(layer);
  10627. },
  10628. _bringToBack: function (layer) {
  10629. var order = layer._order;
  10630. if (!order) { return; }
  10631. var next = order.next;
  10632. var prev = order.prev;
  10633. if (prev) {
  10634. prev.next = next;
  10635. } else {
  10636. // Already first
  10637. return;
  10638. }
  10639. if (next) {
  10640. next.prev = prev;
  10641. } else if (prev) {
  10642. // Update last entry unless this is the
  10643. // single entry
  10644. this._drawLast = prev;
  10645. }
  10646. order.prev = null;
  10647. order.next = this._drawFirst;
  10648. this._drawFirst.prev = order;
  10649. this._drawFirst = order;
  10650. this._requestRedraw(layer);
  10651. }
  10652. });
  10653. // @factory L.canvas(options?: Renderer options)
  10654. // Creates a Canvas renderer with the given options.
  10655. function canvas(options) {
  10656. return Browser.canvas ? new Canvas(options) : null;
  10657. }
  10658. /*
  10659. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10660. */
  10661. var vmlCreate = (function () {
  10662. try {
  10663. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10664. return function (name) {
  10665. return document.createElement('<lvml:' + name + ' class="lvml">');
  10666. };
  10667. } catch (e) {
  10668. // Do not return fn from catch block so `e` can be garbage collected
  10669. // See https://github.com/Leaflet/Leaflet/pull/7279
  10670. }
  10671. return function (name) {
  10672. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10673. };
  10674. })();
  10675. /*
  10676. * @class SVG
  10677. *
  10678. *
  10679. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10680. * with old versions of Internet Explorer.
  10681. */
  10682. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10683. var vmlMixin = {
  10684. _initContainer: function () {
  10685. this._container = create$1('div', 'leaflet-vml-container');
  10686. },
  10687. _update: function () {
  10688. if (this._map._animatingZoom) { return; }
  10689. Renderer.prototype._update.call(this);
  10690. this.fire('update');
  10691. },
  10692. _initPath: function (layer) {
  10693. var container = layer._container = vmlCreate('shape');
  10694. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10695. container.coordsize = '1 1';
  10696. layer._path = vmlCreate('path');
  10697. container.appendChild(layer._path);
  10698. this._updateStyle(layer);
  10699. this._layers[stamp(layer)] = layer;
  10700. },
  10701. _addPath: function (layer) {
  10702. var container = layer._container;
  10703. this._container.appendChild(container);
  10704. if (layer.options.interactive) {
  10705. layer.addInteractiveTarget(container);
  10706. }
  10707. },
  10708. _removePath: function (layer) {
  10709. var container = layer._container;
  10710. remove(container);
  10711. layer.removeInteractiveTarget(container);
  10712. delete this._layers[stamp(layer)];
  10713. },
  10714. _updateStyle: function (layer) {
  10715. var stroke = layer._stroke,
  10716. fill = layer._fill,
  10717. options = layer.options,
  10718. container = layer._container;
  10719. container.stroked = !!options.stroke;
  10720. container.filled = !!options.fill;
  10721. if (options.stroke) {
  10722. if (!stroke) {
  10723. stroke = layer._stroke = vmlCreate('stroke');
  10724. }
  10725. container.appendChild(stroke);
  10726. stroke.weight = options.weight + 'px';
  10727. stroke.color = options.color;
  10728. stroke.opacity = options.opacity;
  10729. if (options.dashArray) {
  10730. stroke.dashStyle = isArray(options.dashArray) ?
  10731. options.dashArray.join(' ') :
  10732. options.dashArray.replace(/( *, *)/g, ' ');
  10733. } else {
  10734. stroke.dashStyle = '';
  10735. }
  10736. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10737. stroke.joinstyle = options.lineJoin;
  10738. } else if (stroke) {
  10739. container.removeChild(stroke);
  10740. layer._stroke = null;
  10741. }
  10742. if (options.fill) {
  10743. if (!fill) {
  10744. fill = layer._fill = vmlCreate('fill');
  10745. }
  10746. container.appendChild(fill);
  10747. fill.color = options.fillColor || options.color;
  10748. fill.opacity = options.fillOpacity;
  10749. } else if (fill) {
  10750. container.removeChild(fill);
  10751. layer._fill = null;
  10752. }
  10753. },
  10754. _updateCircle: function (layer) {
  10755. var p = layer._point.round(),
  10756. r = Math.round(layer._radius),
  10757. r2 = Math.round(layer._radiusY || r);
  10758. this._setPath(layer, layer._empty() ? 'M0 0' :
  10759. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10760. },
  10761. _setPath: function (layer, path) {
  10762. layer._path.v = path;
  10763. },
  10764. _bringToFront: function (layer) {
  10765. toFront(layer._container);
  10766. },
  10767. _bringToBack: function (layer) {
  10768. toBack(layer._container);
  10769. }
  10770. };
  10771. var create = Browser.vml ? vmlCreate : svgCreate;
  10772. /*
  10773. * @class SVG
  10774. * @inherits Renderer
  10775. * @aka L.SVG
  10776. *
  10777. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10778. * Inherits `Renderer`.
  10779. *
  10780. * Due to [technical limitations](https://caniuse.com/svg), SVG is not
  10781. * available in all web browsers, notably Android 2.x and 3.x.
  10782. *
  10783. * Although SVG is not available on IE7 and IE8, these browsers support
  10784. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10785. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10786. * this case.
  10787. *
  10788. * @example
  10789. *
  10790. * Use SVG by default for all paths in the map:
  10791. *
  10792. * ```js
  10793. * var map = L.map('map', {
  10794. * renderer: L.svg()
  10795. * });
  10796. * ```
  10797. *
  10798. * Use a SVG renderer with extra padding for specific vector geometries:
  10799. *
  10800. * ```js
  10801. * var map = L.map('map');
  10802. * var myRenderer = L.svg({ padding: 0.5 });
  10803. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10804. * var circle = L.circle( center, { renderer: myRenderer } );
  10805. * ```
  10806. */
  10807. var SVG = Renderer.extend({
  10808. _initContainer: function () {
  10809. this._container = create('svg');
  10810. // makes it possible to click through svg root; we'll reset it back in individual paths
  10811. this._container.setAttribute('pointer-events', 'none');
  10812. this._rootGroup = create('g');
  10813. this._container.appendChild(this._rootGroup);
  10814. },
  10815. _destroyContainer: function () {
  10816. remove(this._container);
  10817. off(this._container);
  10818. delete this._container;
  10819. delete this._rootGroup;
  10820. delete this._svgSize;
  10821. },
  10822. _update: function () {
  10823. if (this._map._animatingZoom && this._bounds) { return; }
  10824. Renderer.prototype._update.call(this);
  10825. var b = this._bounds,
  10826. size = b.getSize(),
  10827. container = this._container;
  10828. // set size of svg-container if changed
  10829. if (!this._svgSize || !this._svgSize.equals(size)) {
  10830. this._svgSize = size;
  10831. container.setAttribute('width', size.x);
  10832. container.setAttribute('height', size.y);
  10833. }
  10834. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10835. setPosition(container, b.min);
  10836. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10837. this.fire('update');
  10838. },
  10839. // methods below are called by vector layers implementations
  10840. _initPath: function (layer) {
  10841. var path = layer._path = create('path');
  10842. // @namespace Path
  10843. // @option className: String = null
  10844. // Custom class name set on an element. Only for SVG renderer.
  10845. if (layer.options.className) {
  10846. addClass(path, layer.options.className);
  10847. }
  10848. if (layer.options.interactive) {
  10849. addClass(path, 'leaflet-interactive');
  10850. }
  10851. this._updateStyle(layer);
  10852. this._layers[stamp(layer)] = layer;
  10853. },
  10854. _addPath: function (layer) {
  10855. if (!this._rootGroup) { this._initContainer(); }
  10856. this._rootGroup.appendChild(layer._path);
  10857. layer.addInteractiveTarget(layer._path);
  10858. },
  10859. _removePath: function (layer) {
  10860. remove(layer._path);
  10861. layer.removeInteractiveTarget(layer._path);
  10862. delete this._layers[stamp(layer)];
  10863. },
  10864. _updatePath: function (layer) {
  10865. layer._project();
  10866. layer._update();
  10867. },
  10868. _updateStyle: function (layer) {
  10869. var path = layer._path,
  10870. options = layer.options;
  10871. if (!path) { return; }
  10872. if (options.stroke) {
  10873. path.setAttribute('stroke', options.color);
  10874. path.setAttribute('stroke-opacity', options.opacity);
  10875. path.setAttribute('stroke-width', options.weight);
  10876. path.setAttribute('stroke-linecap', options.lineCap);
  10877. path.setAttribute('stroke-linejoin', options.lineJoin);
  10878. if (options.dashArray) {
  10879. path.setAttribute('stroke-dasharray', options.dashArray);
  10880. } else {
  10881. path.removeAttribute('stroke-dasharray');
  10882. }
  10883. if (options.dashOffset) {
  10884. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10885. } else {
  10886. path.removeAttribute('stroke-dashoffset');
  10887. }
  10888. } else {
  10889. path.setAttribute('stroke', 'none');
  10890. }
  10891. if (options.fill) {
  10892. path.setAttribute('fill', options.fillColor || options.color);
  10893. path.setAttribute('fill-opacity', options.fillOpacity);
  10894. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10895. } else {
  10896. path.setAttribute('fill', 'none');
  10897. }
  10898. },
  10899. _updatePoly: function (layer, closed) {
  10900. this._setPath(layer, pointsToPath(layer._parts, closed));
  10901. },
  10902. _updateCircle: function (layer) {
  10903. var p = layer._point,
  10904. r = Math.max(Math.round(layer._radius), 1),
  10905. r2 = Math.max(Math.round(layer._radiusY), 1) || r,
  10906. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10907. // drawing a circle with two half-arcs
  10908. var d = layer._empty() ? 'M0 0' :
  10909. 'M' + (p.x - r) + ',' + p.y +
  10910. arc + (r * 2) + ',0 ' +
  10911. arc + (-r * 2) + ',0 ';
  10912. this._setPath(layer, d);
  10913. },
  10914. _setPath: function (layer, path) {
  10915. layer._path.setAttribute('d', path);
  10916. },
  10917. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10918. _bringToFront: function (layer) {
  10919. toFront(layer._path);
  10920. },
  10921. _bringToBack: function (layer) {
  10922. toBack(layer._path);
  10923. }
  10924. });
  10925. if (Browser.vml) {
  10926. SVG.include(vmlMixin);
  10927. }
  10928. // @namespace SVG
  10929. // @factory L.svg(options?: Renderer options)
  10930. // Creates a SVG renderer with the given options.
  10931. function svg(options) {
  10932. return Browser.svg || Browser.vml ? new SVG(options) : null;
  10933. }
  10934. Map.include({
  10935. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10936. // Returns the instance of `Renderer` that should be used to render the given
  10937. // `Path`. It will ensure that the `renderer` options of the map and paths
  10938. // are respected, and that the renderers do exist on the map.
  10939. getRenderer: function (layer) {
  10940. // @namespace Path; @option renderer: Renderer
  10941. // Use this specific instance of `Renderer` for this path. Takes
  10942. // precedence over the map's [default renderer](#map-renderer).
  10943. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10944. if (!renderer) {
  10945. renderer = this._renderer = this._createRenderer();
  10946. }
  10947. if (!this.hasLayer(renderer)) {
  10948. this.addLayer(renderer);
  10949. }
  10950. return renderer;
  10951. },
  10952. _getPaneRenderer: function (name) {
  10953. if (name === 'overlayPane' || name === undefined) {
  10954. return false;
  10955. }
  10956. var renderer = this._paneRenderers[name];
  10957. if (renderer === undefined) {
  10958. renderer = this._createRenderer({pane: name});
  10959. this._paneRenderers[name] = renderer;
  10960. }
  10961. return renderer;
  10962. },
  10963. _createRenderer: function (options) {
  10964. // @namespace Map; @option preferCanvas: Boolean = false
  10965. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10966. // By default, all `Path`s are rendered in a `SVG` renderer.
  10967. return (this.options.preferCanvas && canvas(options)) || svg(options);
  10968. }
  10969. });
  10970. /*
  10971. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10972. */
  10973. /*
  10974. * @class Rectangle
  10975. * @aka L.Rectangle
  10976. * @inherits Polygon
  10977. *
  10978. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10979. *
  10980. * @example
  10981. *
  10982. * ```js
  10983. * // define rectangle geographical bounds
  10984. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10985. *
  10986. * // create an orange rectangle
  10987. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10988. *
  10989. * // zoom the map to the rectangle bounds
  10990. * map.fitBounds(bounds);
  10991. * ```
  10992. *
  10993. */
  10994. var Rectangle = Polygon.extend({
  10995. initialize: function (latLngBounds, options) {
  10996. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10997. },
  10998. // @method setBounds(latLngBounds: LatLngBounds): this
  10999. // Redraws the rectangle with the passed bounds.
  11000. setBounds: function (latLngBounds) {
  11001. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  11002. },
  11003. _boundsToLatLngs: function (latLngBounds) {
  11004. latLngBounds = toLatLngBounds(latLngBounds);
  11005. return [
  11006. latLngBounds.getSouthWest(),
  11007. latLngBounds.getNorthWest(),
  11008. latLngBounds.getNorthEast(),
  11009. latLngBounds.getSouthEast()
  11010. ];
  11011. }
  11012. });
  11013. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  11014. function rectangle(latLngBounds, options) {
  11015. return new Rectangle(latLngBounds, options);
  11016. }
  11017. SVG.create = create;
  11018. SVG.pointsToPath = pointsToPath;
  11019. GeoJSON.geometryToLayer = geometryToLayer;
  11020. GeoJSON.coordsToLatLng = coordsToLatLng;
  11021. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  11022. GeoJSON.latLngToCoords = latLngToCoords;
  11023. GeoJSON.latLngsToCoords = latLngsToCoords;
  11024. GeoJSON.getFeature = getFeature;
  11025. GeoJSON.asFeature = asFeature;
  11026. /*
  11027. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  11028. * (zoom to a selected bounding box), enabled by default.
  11029. */
  11030. // @namespace Map
  11031. // @section Interaction Options
  11032. Map.mergeOptions({
  11033. // @option boxZoom: Boolean = true
  11034. // Whether the map can be zoomed to a rectangular area specified by
  11035. // dragging the mouse while pressing the shift key.
  11036. boxZoom: true
  11037. });
  11038. var BoxZoom = Handler.extend({
  11039. initialize: function (map) {
  11040. this._map = map;
  11041. this._container = map._container;
  11042. this._pane = map._panes.overlayPane;
  11043. this._resetStateTimeout = 0;
  11044. map.on('unload', this._destroy, this);
  11045. },
  11046. addHooks: function () {
  11047. on(this._container, 'mousedown', this._onMouseDown, this);
  11048. },
  11049. removeHooks: function () {
  11050. off(this._container, 'mousedown', this._onMouseDown, this);
  11051. },
  11052. moved: function () {
  11053. return this._moved;
  11054. },
  11055. _destroy: function () {
  11056. remove(this._pane);
  11057. delete this._pane;
  11058. },
  11059. _resetState: function () {
  11060. this._resetStateTimeout = 0;
  11061. this._moved = false;
  11062. },
  11063. _clearDeferredResetState: function () {
  11064. if (this._resetStateTimeout !== 0) {
  11065. clearTimeout(this._resetStateTimeout);
  11066. this._resetStateTimeout = 0;
  11067. }
  11068. },
  11069. _onMouseDown: function (e) {
  11070. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  11071. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  11072. // will interrupt the interaction and orphan a box element in the container.
  11073. this._clearDeferredResetState();
  11074. this._resetState();
  11075. disableTextSelection();
  11076. disableImageDrag();
  11077. this._startPoint = this._map.mouseEventToContainerPoint(e);
  11078. on(document, {
  11079. contextmenu: stop,
  11080. mousemove: this._onMouseMove,
  11081. mouseup: this._onMouseUp,
  11082. keydown: this._onKeyDown
  11083. }, this);
  11084. },
  11085. _onMouseMove: function (e) {
  11086. if (!this._moved) {
  11087. this._moved = true;
  11088. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  11089. addClass(this._container, 'leaflet-crosshair');
  11090. this._map.fire('boxzoomstart');
  11091. }
  11092. this._point = this._map.mouseEventToContainerPoint(e);
  11093. var bounds = new Bounds(this._point, this._startPoint),
  11094. size = bounds.getSize();
  11095. setPosition(this._box, bounds.min);
  11096. this._box.style.width = size.x + 'px';
  11097. this._box.style.height = size.y + 'px';
  11098. },
  11099. _finish: function () {
  11100. if (this._moved) {
  11101. remove(this._box);
  11102. removeClass(this._container, 'leaflet-crosshair');
  11103. }
  11104. enableTextSelection();
  11105. enableImageDrag();
  11106. off(document, {
  11107. contextmenu: stop,
  11108. mousemove: this._onMouseMove,
  11109. mouseup: this._onMouseUp,
  11110. keydown: this._onKeyDown
  11111. }, this);
  11112. },
  11113. _onMouseUp: function (e) {
  11114. if ((e.which !== 1) && (e.button !== 1)) { return; }
  11115. this._finish();
  11116. if (!this._moved) { return; }
  11117. // Postpone to next JS tick so internal click event handling
  11118. // still see it as "moved".
  11119. this._clearDeferredResetState();
  11120. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  11121. var bounds = new LatLngBounds(
  11122. this._map.containerPointToLatLng(this._startPoint),
  11123. this._map.containerPointToLatLng(this._point));
  11124. this._map
  11125. .fitBounds(bounds)
  11126. .fire('boxzoomend', {boxZoomBounds: bounds});
  11127. },
  11128. _onKeyDown: function (e) {
  11129. if (e.keyCode === 27) {
  11130. this._finish();
  11131. this._clearDeferredResetState();
  11132. this._resetState();
  11133. }
  11134. }
  11135. });
  11136. // @section Handlers
  11137. // @property boxZoom: Handler
  11138. // Box (shift-drag with mouse) zoom handler.
  11139. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  11140. /*
  11141. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  11142. */
  11143. // @namespace Map
  11144. // @section Interaction Options
  11145. Map.mergeOptions({
  11146. // @option doubleClickZoom: Boolean|String = true
  11147. // Whether the map can be zoomed in by double clicking on it and
  11148. // zoomed out by double clicking while holding shift. If passed
  11149. // `'center'`, double-click zoom will zoom to the center of the
  11150. // view regardless of where the mouse was.
  11151. doubleClickZoom: true
  11152. });
  11153. var DoubleClickZoom = Handler.extend({
  11154. addHooks: function () {
  11155. this._map.on('dblclick', this._onDoubleClick, this);
  11156. },
  11157. removeHooks: function () {
  11158. this._map.off('dblclick', this._onDoubleClick, this);
  11159. },
  11160. _onDoubleClick: function (e) {
  11161. var map = this._map,
  11162. oldZoom = map.getZoom(),
  11163. delta = map.options.zoomDelta,
  11164. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  11165. if (map.options.doubleClickZoom === 'center') {
  11166. map.setZoom(zoom);
  11167. } else {
  11168. map.setZoomAround(e.containerPoint, zoom);
  11169. }
  11170. }
  11171. });
  11172. // @section Handlers
  11173. //
  11174. // Map properties include interaction handlers that allow you to control
  11175. // interaction behavior in runtime, enabling or disabling certain features such
  11176. // as dragging or touch zoom (see `Handler` methods). For example:
  11177. //
  11178. // ```js
  11179. // map.doubleClickZoom.disable();
  11180. // ```
  11181. //
  11182. // @property doubleClickZoom: Handler
  11183. // Double click zoom handler.
  11184. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  11185. /*
  11186. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  11187. */
  11188. // @namespace Map
  11189. // @section Interaction Options
  11190. Map.mergeOptions({
  11191. // @option dragging: Boolean = true
  11192. // Whether the map is draggable with mouse/touch or not.
  11193. dragging: true,
  11194. // @section Panning Inertia Options
  11195. // @option inertia: Boolean = *
  11196. // If enabled, panning of the map will have an inertia effect where
  11197. // the map builds momentum while dragging and continues moving in
  11198. // the same direction for some time. Feels especially nice on touch
  11199. // devices. Enabled by default.
  11200. inertia: true,
  11201. // @option inertiaDeceleration: Number = 3000
  11202. // The rate with which the inertial movement slows down, in pixels/second².
  11203. inertiaDeceleration: 3400, // px/s^2
  11204. // @option inertiaMaxSpeed: Number = Infinity
  11205. // Max speed of the inertial movement, in pixels/second.
  11206. inertiaMaxSpeed: Infinity, // px/s
  11207. // @option easeLinearity: Number = 0.2
  11208. easeLinearity: 0.2,
  11209. // TODO refactor, move to CRS
  11210. // @option worldCopyJump: Boolean = false
  11211. // With this option enabled, the map tracks when you pan to another "copy"
  11212. // of the world and seamlessly jumps to the original one so that all overlays
  11213. // like markers and vector layers are still visible.
  11214. worldCopyJump: false,
  11215. // @option maxBoundsViscosity: Number = 0.0
  11216. // If `maxBounds` is set, this option will control how solid the bounds
  11217. // are when dragging the map around. The default value of `0.0` allows the
  11218. // user to drag outside the bounds at normal speed, higher values will
  11219. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  11220. // solid, preventing the user from dragging outside the bounds.
  11221. maxBoundsViscosity: 0.0
  11222. });
  11223. var Drag = Handler.extend({
  11224. addHooks: function () {
  11225. if (!this._draggable) {
  11226. var map = this._map;
  11227. this._draggable = new Draggable(map._mapPane, map._container);
  11228. this._draggable.on({
  11229. dragstart: this._onDragStart,
  11230. drag: this._onDrag,
  11231. dragend: this._onDragEnd
  11232. }, this);
  11233. this._draggable.on('predrag', this._onPreDragLimit, this);
  11234. if (map.options.worldCopyJump) {
  11235. this._draggable.on('predrag', this._onPreDragWrap, this);
  11236. map.on('zoomend', this._onZoomEnd, this);
  11237. map.whenReady(this._onZoomEnd, this);
  11238. }
  11239. }
  11240. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  11241. this._draggable.enable();
  11242. this._positions = [];
  11243. this._times = [];
  11244. },
  11245. removeHooks: function () {
  11246. removeClass(this._map._container, 'leaflet-grab');
  11247. removeClass(this._map._container, 'leaflet-touch-drag');
  11248. this._draggable.disable();
  11249. },
  11250. moved: function () {
  11251. return this._draggable && this._draggable._moved;
  11252. },
  11253. moving: function () {
  11254. return this._draggable && this._draggable._moving;
  11255. },
  11256. _onDragStart: function () {
  11257. var map = this._map;
  11258. map._stop();
  11259. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  11260. var bounds = toLatLngBounds(this._map.options.maxBounds);
  11261. this._offsetLimit = toBounds(
  11262. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  11263. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  11264. .add(this._map.getSize()));
  11265. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  11266. } else {
  11267. this._offsetLimit = null;
  11268. }
  11269. map
  11270. .fire('movestart')
  11271. .fire('dragstart');
  11272. if (map.options.inertia) {
  11273. this._positions = [];
  11274. this._times = [];
  11275. }
  11276. },
  11277. _onDrag: function (e) {
  11278. if (this._map.options.inertia) {
  11279. var time = this._lastTime = +new Date(),
  11280. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  11281. this._positions.push(pos);
  11282. this._times.push(time);
  11283. this._prunePositions(time);
  11284. }
  11285. this._map
  11286. .fire('move', e)
  11287. .fire('drag', e);
  11288. },
  11289. _prunePositions: function (time) {
  11290. while (this._positions.length > 1 && time - this._times[0] > 50) {
  11291. this._positions.shift();
  11292. this._times.shift();
  11293. }
  11294. },
  11295. _onZoomEnd: function () {
  11296. var pxCenter = this._map.getSize().divideBy(2),
  11297. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  11298. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  11299. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  11300. },
  11301. _viscousLimit: function (value, threshold) {
  11302. return value - (value - threshold) * this._viscosity;
  11303. },
  11304. _onPreDragLimit: function () {
  11305. if (!this._viscosity || !this._offsetLimit) { return; }
  11306. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  11307. var limit = this._offsetLimit;
  11308. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  11309. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  11310. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  11311. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  11312. this._draggable._newPos = this._draggable._startPos.add(offset);
  11313. },
  11314. _onPreDragWrap: function () {
  11315. // TODO refactor to be able to adjust map pane position after zoom
  11316. var worldWidth = this._worldWidth,
  11317. halfWidth = Math.round(worldWidth / 2),
  11318. dx = this._initialWorldOffset,
  11319. x = this._draggable._newPos.x,
  11320. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  11321. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  11322. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  11323. this._draggable._absPos = this._draggable._newPos.clone();
  11324. this._draggable._newPos.x = newX;
  11325. },
  11326. _onDragEnd: function (e) {
  11327. var map = this._map,
  11328. options = map.options,
  11329. noInertia = !options.inertia || e.noInertia || this._times.length < 2;
  11330. map.fire('dragend', e);
  11331. if (noInertia) {
  11332. map.fire('moveend');
  11333. } else {
  11334. this._prunePositions(+new Date());
  11335. var direction = this._lastPos.subtract(this._positions[0]),
  11336. duration = (this._lastTime - this._times[0]) / 1000,
  11337. ease = options.easeLinearity,
  11338. speedVector = direction.multiplyBy(ease / duration),
  11339. speed = speedVector.distanceTo([0, 0]),
  11340. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  11341. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  11342. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  11343. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  11344. if (!offset.x && !offset.y) {
  11345. map.fire('moveend');
  11346. } else {
  11347. offset = map._limitOffset(offset, map.options.maxBounds);
  11348. requestAnimFrame(function () {
  11349. map.panBy(offset, {
  11350. duration: decelerationDuration,
  11351. easeLinearity: ease,
  11352. noMoveStart: true,
  11353. animate: true
  11354. });
  11355. });
  11356. }
  11357. }
  11358. }
  11359. });
  11360. // @section Handlers
  11361. // @property dragging: Handler
  11362. // Map dragging handler (by both mouse and touch).
  11363. Map.addInitHook('addHandler', 'dragging', Drag);
  11364. /*
  11365. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  11366. */
  11367. // @namespace Map
  11368. // @section Keyboard Navigation Options
  11369. Map.mergeOptions({
  11370. // @option keyboard: Boolean = true
  11371. // Makes the map focusable and allows users to navigate the map with keyboard
  11372. // arrows and `+`/`-` keys.
  11373. keyboard: true,
  11374. // @option keyboardPanDelta: Number = 80
  11375. // Amount of pixels to pan when pressing an arrow key.
  11376. keyboardPanDelta: 80
  11377. });
  11378. var Keyboard = Handler.extend({
  11379. keyCodes: {
  11380. left: [37],
  11381. right: [39],
  11382. down: [40],
  11383. up: [38],
  11384. zoomIn: [187, 107, 61, 171],
  11385. zoomOut: [189, 109, 54, 173]
  11386. },
  11387. initialize: function (map) {
  11388. this._map = map;
  11389. this._setPanDelta(map.options.keyboardPanDelta);
  11390. this._setZoomDelta(map.options.zoomDelta);
  11391. },
  11392. addHooks: function () {
  11393. var container = this._map._container;
  11394. // make the container focusable by tabbing
  11395. if (container.tabIndex <= 0) {
  11396. container.tabIndex = '0';
  11397. }
  11398. on(container, {
  11399. focus: this._onFocus,
  11400. blur: this._onBlur,
  11401. mousedown: this._onMouseDown
  11402. }, this);
  11403. this._map.on({
  11404. focus: this._addHooks,
  11405. blur: this._removeHooks
  11406. }, this);
  11407. },
  11408. removeHooks: function () {
  11409. this._removeHooks();
  11410. off(this._map._container, {
  11411. focus: this._onFocus,
  11412. blur: this._onBlur,
  11413. mousedown: this._onMouseDown
  11414. }, this);
  11415. this._map.off({
  11416. focus: this._addHooks,
  11417. blur: this._removeHooks
  11418. }, this);
  11419. },
  11420. _onMouseDown: function () {
  11421. if (this._focused) { return; }
  11422. var body = document.body,
  11423. docEl = document.documentElement,
  11424. top = body.scrollTop || docEl.scrollTop,
  11425. left = body.scrollLeft || docEl.scrollLeft;
  11426. this._map._container.focus();
  11427. window.scrollTo(left, top);
  11428. },
  11429. _onFocus: function () {
  11430. this._focused = true;
  11431. this._map.fire('focus');
  11432. },
  11433. _onBlur: function () {
  11434. this._focused = false;
  11435. this._map.fire('blur');
  11436. },
  11437. _setPanDelta: function (panDelta) {
  11438. var keys = this._panKeys = {},
  11439. codes = this.keyCodes,
  11440. i, len;
  11441. for (i = 0, len = codes.left.length; i < len; i++) {
  11442. keys[codes.left[i]] = [-1 * panDelta, 0];
  11443. }
  11444. for (i = 0, len = codes.right.length; i < len; i++) {
  11445. keys[codes.right[i]] = [panDelta, 0];
  11446. }
  11447. for (i = 0, len = codes.down.length; i < len; i++) {
  11448. keys[codes.down[i]] = [0, panDelta];
  11449. }
  11450. for (i = 0, len = codes.up.length; i < len; i++) {
  11451. keys[codes.up[i]] = [0, -1 * panDelta];
  11452. }
  11453. },
  11454. _setZoomDelta: function (zoomDelta) {
  11455. var keys = this._zoomKeys = {},
  11456. codes = this.keyCodes,
  11457. i, len;
  11458. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  11459. keys[codes.zoomIn[i]] = zoomDelta;
  11460. }
  11461. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  11462. keys[codes.zoomOut[i]] = -zoomDelta;
  11463. }
  11464. },
  11465. _addHooks: function () {
  11466. on(document, 'keydown', this._onKeyDown, this);
  11467. },
  11468. _removeHooks: function () {
  11469. off(document, 'keydown', this._onKeyDown, this);
  11470. },
  11471. _onKeyDown: function (e) {
  11472. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  11473. var key = e.keyCode,
  11474. map = this._map,
  11475. offset;
  11476. if (key in this._panKeys) {
  11477. if (!map._panAnim || !map._panAnim._inProgress) {
  11478. offset = this._panKeys[key];
  11479. if (e.shiftKey) {
  11480. offset = toPoint(offset).multiplyBy(3);
  11481. }
  11482. if (map.options.maxBounds) {
  11483. offset = map._limitOffset(toPoint(offset), map.options.maxBounds);
  11484. }
  11485. if (map.options.worldCopyJump) {
  11486. var newLatLng = map.wrapLatLng(map.unproject(map.project(map.getCenter()).add(offset)));
  11487. map.panTo(newLatLng);
  11488. } else {
  11489. map.panBy(offset);
  11490. }
  11491. }
  11492. } else if (key in this._zoomKeys) {
  11493. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  11494. } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
  11495. map.closePopup();
  11496. } else {
  11497. return;
  11498. }
  11499. stop(e);
  11500. }
  11501. });
  11502. // @section Handlers
  11503. // @section Handlers
  11504. // @property keyboard: Handler
  11505. // Keyboard navigation handler.
  11506. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  11507. /*
  11508. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  11509. */
  11510. // @namespace Map
  11511. // @section Interaction Options
  11512. Map.mergeOptions({
  11513. // @section Mouse wheel options
  11514. // @option scrollWheelZoom: Boolean|String = true
  11515. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  11516. // it will zoom to the center of the view regardless of where the mouse was.
  11517. scrollWheelZoom: true,
  11518. // @option wheelDebounceTime: Number = 40
  11519. // Limits the rate at which a wheel can fire (in milliseconds). By default
  11520. // user can't zoom via wheel more often than once per 40 ms.
  11521. wheelDebounceTime: 40,
  11522. // @option wheelPxPerZoomLevel: Number = 60
  11523. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  11524. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  11525. // faster (and vice versa).
  11526. wheelPxPerZoomLevel: 60
  11527. });
  11528. var ScrollWheelZoom = Handler.extend({
  11529. addHooks: function () {
  11530. on(this._map._container, 'wheel', this._onWheelScroll, this);
  11531. this._delta = 0;
  11532. },
  11533. removeHooks: function () {
  11534. off(this._map._container, 'wheel', this._onWheelScroll, this);
  11535. },
  11536. _onWheelScroll: function (e) {
  11537. var delta = getWheelDelta(e);
  11538. var debounce = this._map.options.wheelDebounceTime;
  11539. this._delta += delta;
  11540. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  11541. if (!this._startTime) {
  11542. this._startTime = +new Date();
  11543. }
  11544. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  11545. clearTimeout(this._timer);
  11546. this._timer = setTimeout(bind(this._performZoom, this), left);
  11547. stop(e);
  11548. },
  11549. _performZoom: function () {
  11550. var map = this._map,
  11551. zoom = map.getZoom(),
  11552. snap = this._map.options.zoomSnap || 0;
  11553. map._stop(); // stop panning and fly animations if any
  11554. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  11555. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  11556. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  11557. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  11558. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  11559. this._delta = 0;
  11560. this._startTime = null;
  11561. if (!delta) { return; }
  11562. if (map.options.scrollWheelZoom === 'center') {
  11563. map.setZoom(zoom + delta);
  11564. } else {
  11565. map.setZoomAround(this._lastMousePos, zoom + delta);
  11566. }
  11567. }
  11568. });
  11569. // @section Handlers
  11570. // @property scrollWheelZoom: Handler
  11571. // Scroll wheel zoom handler.
  11572. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  11573. /*
  11574. * L.Map.TapHold is used to simulate `contextmenu` event on long hold,
  11575. * which otherwise is not fired by mobile Safari.
  11576. */
  11577. var tapHoldDelay = 600;
  11578. // @namespace Map
  11579. // @section Interaction Options
  11580. Map.mergeOptions({
  11581. // @section Touch interaction options
  11582. // @option tapHold: Boolean
  11583. // Enables simulation of `contextmenu` event, default is `true` for mobile Safari.
  11584. tapHold: Browser.touchNative && Browser.safari && Browser.mobile,
  11585. // @option tapTolerance: Number = 15
  11586. // The max number of pixels a user can shift his finger during touch
  11587. // for it to be considered a valid tap.
  11588. tapTolerance: 15
  11589. });
  11590. var TapHold = Handler.extend({
  11591. addHooks: function () {
  11592. on(this._map._container, 'touchstart', this._onDown, this);
  11593. },
  11594. removeHooks: function () {
  11595. off(this._map._container, 'touchstart', this._onDown, this);
  11596. },
  11597. _onDown: function (e) {
  11598. clearTimeout(this._holdTimeout);
  11599. if (e.touches.length !== 1) { return; }
  11600. var first = e.touches[0];
  11601. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  11602. this._holdTimeout = setTimeout(bind(function () {
  11603. this._cancel();
  11604. if (!this._isTapValid()) { return; }
  11605. // prevent simulated mouse events https://w3c.github.io/touch-events/#mouse-events
  11606. on(document, 'touchend', preventDefault);
  11607. on(document, 'touchend touchcancel', this._cancelClickPrevent);
  11608. this._simulateEvent('contextmenu', first);
  11609. }, this), tapHoldDelay);
  11610. on(document, 'touchend touchcancel contextmenu', this._cancel, this);
  11611. on(document, 'touchmove', this._onMove, this);
  11612. },
  11613. _cancelClickPrevent: function cancelClickPrevent() {
  11614. off(document, 'touchend', preventDefault);
  11615. off(document, 'touchend touchcancel', cancelClickPrevent);
  11616. },
  11617. _cancel: function () {
  11618. clearTimeout(this._holdTimeout);
  11619. off(document, 'touchend touchcancel contextmenu', this._cancel, this);
  11620. off(document, 'touchmove', this._onMove, this);
  11621. },
  11622. _onMove: function (e) {
  11623. var first = e.touches[0];
  11624. this._newPos = new Point(first.clientX, first.clientY);
  11625. },
  11626. _isTapValid: function () {
  11627. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11628. },
  11629. _simulateEvent: function (type, e) {
  11630. var simulatedEvent = new MouseEvent(type, {
  11631. bubbles: true,
  11632. cancelable: true,
  11633. view: window,
  11634. // detail: 1,
  11635. screenX: e.screenX,
  11636. screenY: e.screenY,
  11637. clientX: e.clientX,
  11638. clientY: e.clientY,
  11639. // button: 2,
  11640. // buttons: 2
  11641. });
  11642. simulatedEvent._simulated = true;
  11643. e.target.dispatchEvent(simulatedEvent);
  11644. }
  11645. });
  11646. // @section Handlers
  11647. // @property tapHold: Handler
  11648. // Long tap handler to simulate `contextmenu` event (useful in mobile Safari).
  11649. Map.addInitHook('addHandler', 'tapHold', TapHold);
  11650. /*
  11651. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11652. */
  11653. // @namespace Map
  11654. // @section Interaction Options
  11655. Map.mergeOptions({
  11656. // @section Touch interaction options
  11657. // @option touchZoom: Boolean|String = *
  11658. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11659. // passed `'center'`, it will zoom to the center of the view regardless of
  11660. // where the touch events (fingers) were. Enabled for touch-capable web
  11661. // browsers.
  11662. touchZoom: Browser.touch,
  11663. // @option bounceAtZoomLimits: Boolean = true
  11664. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11665. // and then bounce back when pinch-zooming.
  11666. bounceAtZoomLimits: true
  11667. });
  11668. var TouchZoom = Handler.extend({
  11669. addHooks: function () {
  11670. addClass(this._map._container, 'leaflet-touch-zoom');
  11671. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11672. },
  11673. removeHooks: function () {
  11674. removeClass(this._map._container, 'leaflet-touch-zoom');
  11675. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11676. },
  11677. _onTouchStart: function (e) {
  11678. var map = this._map;
  11679. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  11680. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11681. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11682. this._centerPoint = map.getSize()._divideBy(2);
  11683. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11684. if (map.options.touchZoom !== 'center') {
  11685. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11686. }
  11687. this._startDist = p1.distanceTo(p2);
  11688. this._startZoom = map.getZoom();
  11689. this._moved = false;
  11690. this._zooming = true;
  11691. map._stop();
  11692. on(document, 'touchmove', this._onTouchMove, this);
  11693. on(document, 'touchend touchcancel', this._onTouchEnd, this);
  11694. preventDefault(e);
  11695. },
  11696. _onTouchMove: function (e) {
  11697. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  11698. var map = this._map,
  11699. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11700. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11701. scale = p1.distanceTo(p2) / this._startDist;
  11702. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11703. if (!map.options.bounceAtZoomLimits && (
  11704. (this._zoom < map.getMinZoom() && scale < 1) ||
  11705. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11706. this._zoom = map._limitZoom(this._zoom);
  11707. }
  11708. if (map.options.touchZoom === 'center') {
  11709. this._center = this._startLatLng;
  11710. if (scale === 1) { return; }
  11711. } else {
  11712. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11713. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11714. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  11715. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11716. }
  11717. if (!this._moved) {
  11718. map._moveStart(true, false);
  11719. this._moved = true;
  11720. }
  11721. cancelAnimFrame(this._animRequest);
  11722. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false}, undefined);
  11723. this._animRequest = requestAnimFrame(moveFn, this, true);
  11724. preventDefault(e);
  11725. },
  11726. _onTouchEnd: function () {
  11727. if (!this._moved || !this._zooming) {
  11728. this._zooming = false;
  11729. return;
  11730. }
  11731. this._zooming = false;
  11732. cancelAnimFrame(this._animRequest);
  11733. off(document, 'touchmove', this._onTouchMove, this);
  11734. off(document, 'touchend touchcancel', this._onTouchEnd, this);
  11735. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11736. if (this._map.options.zoomAnimation) {
  11737. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11738. } else {
  11739. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11740. }
  11741. }
  11742. });
  11743. // @section Handlers
  11744. // @property touchZoom: Handler
  11745. // Touch zoom handler.
  11746. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11747. Map.BoxZoom = BoxZoom;
  11748. Map.DoubleClickZoom = DoubleClickZoom;
  11749. Map.Drag = Drag;
  11750. Map.Keyboard = Keyboard;
  11751. Map.ScrollWheelZoom = ScrollWheelZoom;
  11752. Map.TapHold = TapHold;
  11753. Map.TouchZoom = TouchZoom;
  11754. export { Bounds, Browser, CRS, Canvas, Circle, CircleMarker, Class, Control, DivIcon, DivOverlay, DomEvent, DomUtil, Draggable, Evented, FeatureGroup, GeoJSON, GridLayer, Handler, Icon, ImageOverlay, LatLng, LatLngBounds, Layer, LayerGroup, LineUtil, Map, Marker, Mixin, Path, Point, PolyUtil, Polygon, Polyline, Popup, PosAnimation, index as Projection, Rectangle, Renderer, SVG, SVGOverlay, TileLayer, Tooltip, Transformation, Util, VideoOverlay, bind, toBounds as bounds, canvas, circle, circleMarker, control, divIcon, extend, featureGroup, geoJSON, geoJson, gridLayer, icon, imageOverlay, toLatLng as latLng, toLatLngBounds as latLngBounds, layerGroup, createMap as map, marker, toPoint as point, polygon, polyline, popup, rectangle, setOptions, stamp, svg, svgOverlay, tileLayer, tooltip, toTransformation as transformation, version, videoOverlay };
  11755. //# sourceMappingURL=leaflet-src.esm.js.map