leaflet-src.js 413 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062
  1. /* @preserve
  2. * Leaflet 1.7.1, a JS library for interactive maps. http://leafletjs.com
  3. * (c) 2010-2019 Vladimir Agafonkin, (c) 2010-2011 CloudMade
  4. */
  5. (function (global, factory) {
  6. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  7. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  8. (factory((global.L = {})));
  9. }(this, (function (exports) { 'use strict';
  10. var version = "1.7.1";
  11. /*
  12. * @namespace Util
  13. *
  14. * Various utility functions, used by Leaflet internally.
  15. */
  16. // @function extend(dest: Object, src?: Object): Object
  17. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  18. function extend(dest) {
  19. var i, j, len, src;
  20. for (j = 1, len = arguments.length; j < len; j++) {
  21. src = arguments[j];
  22. for (i in src) {
  23. dest[i] = src[i];
  24. }
  25. }
  26. return dest;
  27. }
  28. // @function create(proto: Object, properties?: Object): Object
  29. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  30. var create = Object.create || (function () {
  31. function F() {}
  32. return function (proto) {
  33. F.prototype = proto;
  34. return new F();
  35. };
  36. })();
  37. // @function bind(fn: Function, …): Function
  38. // Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
  39. // Has a `L.bind()` shortcut.
  40. function bind(fn, obj) {
  41. var slice = Array.prototype.slice;
  42. if (fn.bind) {
  43. return fn.bind.apply(fn, slice.call(arguments, 1));
  44. }
  45. var args = slice.call(arguments, 2);
  46. return function () {
  47. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  48. };
  49. }
  50. // @property lastId: Number
  51. // Last unique ID used by [`stamp()`](#util-stamp)
  52. var lastId = 0;
  53. // @function stamp(obj: Object): Number
  54. // Returns the unique ID of an object, assigning it one if it doesn't have it.
  55. function stamp(obj) {
  56. /*eslint-disable */
  57. obj._leaflet_id = obj._leaflet_id || ++lastId;
  58. return obj._leaflet_id;
  59. /* eslint-enable */
  60. }
  61. // @function throttle(fn: Function, time: Number, context: Object): Function
  62. // Returns a function which executes function `fn` with the given scope `context`
  63. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  64. // `fn` will be called no more than one time per given amount of `time`. The arguments
  65. // received by the bound function will be any arguments passed when binding the
  66. // function, followed by any arguments passed when invoking the bound function.
  67. // Has an `L.throttle` shortcut.
  68. function throttle(fn, time, context) {
  69. var lock, args, wrapperFn, later;
  70. later = function () {
  71. // reset lock and call if queued
  72. lock = false;
  73. if (args) {
  74. wrapperFn.apply(context, args);
  75. args = false;
  76. }
  77. };
  78. wrapperFn = function () {
  79. if (lock) {
  80. // called too soon, queue to call later
  81. args = arguments;
  82. } else {
  83. // call and lock until later
  84. fn.apply(context, arguments);
  85. setTimeout(later, time);
  86. lock = true;
  87. }
  88. };
  89. return wrapperFn;
  90. }
  91. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  92. // Returns the number `num` modulo `range` in such a way so it lies within
  93. // `range[0]` and `range[1]`. The returned value will be always smaller than
  94. // `range[1]` unless `includeMax` is set to `true`.
  95. function wrapNum(x, range, includeMax) {
  96. var max = range[1],
  97. min = range[0],
  98. d = max - min;
  99. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  100. }
  101. // @function falseFn(): Function
  102. // Returns a function which always returns `false`.
  103. function falseFn() { return false; }
  104. // @function formatNum(num: Number, digits?: Number): Number
  105. // Returns the number `num` rounded to `digits` decimals, or to 6 decimals by default.
  106. function formatNum(num, digits) {
  107. var pow = Math.pow(10, (digits === undefined ? 6 : digits));
  108. return Math.round(num * pow) / pow;
  109. }
  110. // @function trim(str: String): String
  111. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  112. function trim(str) {
  113. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  114. }
  115. // @function splitWords(str: String): String[]
  116. // Trims and splits the string on whitespace and returns the array of parts.
  117. function splitWords(str) {
  118. return trim(str).split(/\s+/);
  119. }
  120. // @function setOptions(obj: Object, options: Object): Object
  121. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  122. function setOptions(obj, options) {
  123. if (!Object.prototype.hasOwnProperty.call(obj, 'options')) {
  124. obj.options = obj.options ? create(obj.options) : {};
  125. }
  126. for (var i in options) {
  127. obj.options[i] = options[i];
  128. }
  129. return obj.options;
  130. }
  131. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  132. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  133. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  134. // be appended at the end. If `uppercase` is `true`, the parameter names will
  135. // be uppercased (e.g. `'?A=foo&B=bar'`)
  136. function getParamString(obj, existingUrl, uppercase) {
  137. var params = [];
  138. for (var i in obj) {
  139. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  140. }
  141. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  142. }
  143. var templateRe = /\{ *([\w_-]+) *\}/g;
  144. // @function template(str: String, data: Object): String
  145. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  146. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  147. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  148. // data values — they will be evaluated passing `data` as an argument.
  149. function template(str, data) {
  150. return str.replace(templateRe, function (str, key) {
  151. var value = data[key];
  152. if (value === undefined) {
  153. throw new Error('No value provided for variable ' + str);
  154. } else if (typeof value === 'function') {
  155. value = value(data);
  156. }
  157. return value;
  158. });
  159. }
  160. // @function isArray(obj): Boolean
  161. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  162. var isArray = Array.isArray || function (obj) {
  163. return (Object.prototype.toString.call(obj) === '[object Array]');
  164. };
  165. // @function indexOf(array: Array, el: Object): Number
  166. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  167. function indexOf(array, el) {
  168. for (var i = 0; i < array.length; i++) {
  169. if (array[i] === el) { return i; }
  170. }
  171. return -1;
  172. }
  173. // @property emptyImageUrl: String
  174. // Data URI string containing a base64-encoded empty GIF image.
  175. // Used as a hack to free memory from unused images on WebKit-powered
  176. // mobile devices (by setting image `src` to this string).
  177. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  178. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  179. function getPrefixed(name) {
  180. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  181. }
  182. var lastTime = 0;
  183. // fallback for IE 7-8
  184. function timeoutDefer(fn) {
  185. var time = +new Date(),
  186. timeToCall = Math.max(0, 16 - (time - lastTime));
  187. lastTime = time + timeToCall;
  188. return window.setTimeout(fn, timeToCall);
  189. }
  190. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  191. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  192. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  193. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  194. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  195. // `context` if given. When `immediate` is set, `fn` is called immediately if
  196. // the browser doesn't have native support for
  197. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  198. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  199. function requestAnimFrame(fn, context, immediate) {
  200. if (immediate && requestFn === timeoutDefer) {
  201. fn.call(context);
  202. } else {
  203. return requestFn.call(window, bind(fn, context));
  204. }
  205. }
  206. // @function cancelAnimFrame(id: Number): undefined
  207. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  208. function cancelAnimFrame(id) {
  209. if (id) {
  210. cancelFn.call(window, id);
  211. }
  212. }
  213. var Util = ({
  214. extend: extend,
  215. create: create,
  216. bind: bind,
  217. lastId: lastId,
  218. stamp: stamp,
  219. throttle: throttle,
  220. wrapNum: wrapNum,
  221. falseFn: falseFn,
  222. formatNum: formatNum,
  223. trim: trim,
  224. splitWords: splitWords,
  225. setOptions: setOptions,
  226. getParamString: getParamString,
  227. template: template,
  228. isArray: isArray,
  229. indexOf: indexOf,
  230. emptyImageUrl: emptyImageUrl,
  231. requestFn: requestFn,
  232. cancelFn: cancelFn,
  233. requestAnimFrame: requestAnimFrame,
  234. cancelAnimFrame: cancelAnimFrame
  235. });
  236. // @class Class
  237. // @aka L.Class
  238. // @section
  239. // @uninheritable
  240. // Thanks to John Resig and Dean Edwards for inspiration!
  241. function Class() {}
  242. Class.extend = function (props) {
  243. // @function extend(props: Object): Function
  244. // [Extends the current class](#class-inheritance) given the properties to be included.
  245. // Returns a Javascript function that is a class constructor (to be called with `new`).
  246. var NewClass = function () {
  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(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. delete props.statics;
  268. }
  269. // mix includes into the prototype
  270. if (props.includes) {
  271. checkDeprecatedMixinEvents(props.includes);
  272. extend.apply(null, [proto].concat(props.includes));
  273. delete props.includes;
  274. }
  275. // merge options
  276. if (proto.options) {
  277. props.options = extend(create(proto.options), props.options);
  278. }
  279. // mix given properties into the prototype
  280. extend(proto, props);
  281. proto._initHooks = [];
  282. // add method for calling all hooks
  283. proto.callInitHooks = function () {
  284. if (this._initHooksCalled) { return; }
  285. if (parentProto.callInitHooks) {
  286. parentProto.callInitHooks.call(this);
  287. }
  288. this._initHooksCalled = true;
  289. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  290. proto._initHooks[i].call(this);
  291. }
  292. };
  293. return NewClass;
  294. };
  295. // @function include(properties: Object): this
  296. // [Includes a mixin](#class-includes) into the current class.
  297. Class.include = function (props) {
  298. extend(this.prototype, props);
  299. return this;
  300. };
  301. // @function mergeOptions(options: Object): this
  302. // [Merges `options`](#class-options) into the defaults of the class.
  303. Class.mergeOptions = function (options) {
  304. extend(this.prototype.options, options);
  305. return this;
  306. };
  307. // @function addInitHook(fn: Function): this
  308. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  309. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  310. var args = Array.prototype.slice.call(arguments, 1);
  311. var init = typeof fn === 'function' ? fn : function () {
  312. this[fn].apply(this, args);
  313. };
  314. this.prototype._initHooks = this.prototype._initHooks || [];
  315. this.prototype._initHooks.push(init);
  316. return this;
  317. };
  318. function checkDeprecatedMixinEvents(includes) {
  319. if (typeof L === 'undefined' || !L || !L.Mixin) { return; }
  320. includes = isArray(includes) ? includes : [includes];
  321. for (var i = 0; i < includes.length; i++) {
  322. if (includes[i] === L.Mixin.Events) {
  323. console.warn('Deprecated include of L.Mixin.Events: ' +
  324. 'this property will be removed in future releases, ' +
  325. 'please inherit from L.Evented instead.', new Error().stack);
  326. }
  327. }
  328. }
  329. /*
  330. * @class Evented
  331. * @aka L.Evented
  332. * @inherits Class
  333. *
  334. * 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).
  335. *
  336. * @example
  337. *
  338. * ```js
  339. * map.on('click', function(e) {
  340. * alert(e.latlng);
  341. * } );
  342. * ```
  343. *
  344. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  345. *
  346. * ```js
  347. * function onClick(e) { ... }
  348. *
  349. * map.on('click', onClick);
  350. * map.off('click', onClick);
  351. * ```
  352. */
  353. var Events = {
  354. /* @method on(type: String, fn: Function, context?: Object): this
  355. * 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'`).
  356. *
  357. * @alternative
  358. * @method on(eventMap: Object): this
  359. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  360. */
  361. on: function (types, fn, context) {
  362. // types can be a map of types/handlers
  363. if (typeof types === 'object') {
  364. for (var type in types) {
  365. // we don't process space-separated events here for performance;
  366. // it's a hot path since Layer uses the on(obj) syntax
  367. this._on(type, types[type], fn);
  368. }
  369. } else {
  370. // types can be a string of space-separated words
  371. types = splitWords(types);
  372. for (var i = 0, len = types.length; i < len; i++) {
  373. this._on(types[i], fn, context);
  374. }
  375. }
  376. return this;
  377. },
  378. /* @method off(type: String, fn?: Function, context?: Object): this
  379. * 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.
  380. *
  381. * @alternative
  382. * @method off(eventMap: Object): this
  383. * Removes a set of type/listener pairs.
  384. *
  385. * @alternative
  386. * @method off: this
  387. * Removes all listeners to all events on the object. This includes implicitly attached events.
  388. */
  389. off: function (types, fn, context) {
  390. if (!types) {
  391. // clear all listeners if called without arguments
  392. delete this._events;
  393. } else if (typeof types === 'object') {
  394. for (var type in types) {
  395. this._off(type, types[type], fn);
  396. }
  397. } else {
  398. types = splitWords(types);
  399. for (var i = 0, len = types.length; i < len; i++) {
  400. this._off(types[i], fn, context);
  401. }
  402. }
  403. return this;
  404. },
  405. // attach listener (without syntactic sugar now)
  406. _on: function (type, fn, context) {
  407. this._events = this._events || {};
  408. /* get/init listeners for type */
  409. var typeListeners = this._events[type];
  410. if (!typeListeners) {
  411. typeListeners = [];
  412. this._events[type] = typeListeners;
  413. }
  414. if (context === this) {
  415. // Less memory footprint.
  416. context = undefined;
  417. }
  418. var newListener = {fn: fn, ctx: context},
  419. listeners = typeListeners;
  420. // check if fn already there
  421. for (var i = 0, len = listeners.length; i < len; i++) {
  422. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  423. return;
  424. }
  425. }
  426. listeners.push(newListener);
  427. },
  428. _off: function (type, fn, context) {
  429. var listeners,
  430. i,
  431. len;
  432. if (!this._events) { return; }
  433. listeners = this._events[type];
  434. if (!listeners) {
  435. return;
  436. }
  437. if (!fn) {
  438. // Set all removed listeners to noop so they are not called if remove happens in fire
  439. for (i = 0, len = listeners.length; i < len; i++) {
  440. listeners[i].fn = falseFn;
  441. }
  442. // clear all listeners for a type if function isn't specified
  443. delete this._events[type];
  444. return;
  445. }
  446. if (context === this) {
  447. context = undefined;
  448. }
  449. if (listeners) {
  450. // find fn and remove it
  451. for (i = 0, len = listeners.length; i < len; i++) {
  452. var l = listeners[i];
  453. if (l.ctx !== context) { continue; }
  454. if (l.fn === fn) {
  455. // set the removed listener to noop so that's not called if remove happens in fire
  456. l.fn = falseFn;
  457. if (this._firingCount) {
  458. /* copy array in case events are being fired */
  459. this._events[type] = listeners = listeners.slice();
  460. }
  461. listeners.splice(i, 1);
  462. return;
  463. }
  464. }
  465. }
  466. },
  467. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  468. // Fires an event of the specified type. You can optionally provide an data
  469. // object — the first argument of the listener function will contain its
  470. // properties. The event can optionally be propagated to event parents.
  471. fire: function (type, data, propagate) {
  472. if (!this.listens(type, propagate)) { return this; }
  473. var event = extend({}, data, {
  474. type: type,
  475. target: this,
  476. sourceTarget: data && data.sourceTarget || this
  477. });
  478. if (this._events) {
  479. var listeners = this._events[type];
  480. if (listeners) {
  481. this._firingCount = (this._firingCount + 1) || 1;
  482. for (var i = 0, len = listeners.length; i < len; i++) {
  483. var l = listeners[i];
  484. l.fn.call(l.ctx || this, event);
  485. }
  486. this._firingCount--;
  487. }
  488. }
  489. if (propagate) {
  490. // propagate the event to parents (set with addEventParent)
  491. this._propagateEvent(event);
  492. }
  493. return this;
  494. },
  495. // @method listens(type: String): Boolean
  496. // Returns `true` if a particular event type has any listeners attached to it.
  497. listens: function (type, propagate) {
  498. var listeners = this._events && this._events[type];
  499. if (listeners && listeners.length) { return true; }
  500. if (propagate) {
  501. // also check parents for listeners if event propagates
  502. for (var id in this._eventParents) {
  503. if (this._eventParents[id].listens(type, propagate)) { return true; }
  504. }
  505. }
  506. return false;
  507. },
  508. // @method once(…): this
  509. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  510. once: function (types, fn, context) {
  511. if (typeof types === 'object') {
  512. for (var type in types) {
  513. this.once(type, types[type], fn);
  514. }
  515. return this;
  516. }
  517. var handler = bind(function () {
  518. this
  519. .off(types, fn, context)
  520. .off(types, handler, context);
  521. }, this);
  522. // add a listener that's executed once and removed after that
  523. return this
  524. .on(types, fn, context)
  525. .on(types, handler, context);
  526. },
  527. // @method addEventParent(obj: Evented): this
  528. // Adds an event parent - an `Evented` that will receive propagated events
  529. addEventParent: function (obj) {
  530. this._eventParents = this._eventParents || {};
  531. this._eventParents[stamp(obj)] = obj;
  532. return this;
  533. },
  534. // @method removeEventParent(obj: Evented): this
  535. // Removes an event parent, so it will stop receiving propagated events
  536. removeEventParent: function (obj) {
  537. if (this._eventParents) {
  538. delete this._eventParents[stamp(obj)];
  539. }
  540. return this;
  541. },
  542. _propagateEvent: function (e) {
  543. for (var id in this._eventParents) {
  544. this._eventParents[id].fire(e.type, extend({
  545. layer: e.target,
  546. propagatedFrom: e.target
  547. }, e), true);
  548. }
  549. }
  550. };
  551. // aliases; we should ditch those eventually
  552. // @method addEventListener(…): this
  553. // Alias to [`on(…)`](#evented-on)
  554. Events.addEventListener = Events.on;
  555. // @method removeEventListener(…): this
  556. // Alias to [`off(…)`](#evented-off)
  557. // @method clearAllEventListeners(…): this
  558. // Alias to [`off()`](#evented-off)
  559. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  560. // @method addOneTimeEventListener(…): this
  561. // Alias to [`once(…)`](#evented-once)
  562. Events.addOneTimeEventListener = Events.once;
  563. // @method fireEvent(…): this
  564. // Alias to [`fire(…)`](#evented-fire)
  565. Events.fireEvent = Events.fire;
  566. // @method hasEventListeners(…): Boolean
  567. // Alias to [`listens(…)`](#evented-listens)
  568. Events.hasEventListeners = Events.listens;
  569. var Evented = Class.extend(Events);
  570. /*
  571. * @class Point
  572. * @aka L.Point
  573. *
  574. * Represents a point with `x` and `y` coordinates in pixels.
  575. *
  576. * @example
  577. *
  578. * ```js
  579. * var point = L.point(200, 300);
  580. * ```
  581. *
  582. * 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:
  583. *
  584. * ```js
  585. * map.panBy([200, 300]);
  586. * map.panBy(L.point(200, 300));
  587. * ```
  588. *
  589. * Note that `Point` does not inherit from Leaflet's `Class` object,
  590. * which means new classes can't inherit from it, and new methods
  591. * can't be added to it with the `include` function.
  592. */
  593. function Point(x, y, round) {
  594. // @property x: Number; The `x` coordinate of the point
  595. this.x = (round ? Math.round(x) : x);
  596. // @property y: Number; The `y` coordinate of the point
  597. this.y = (round ? Math.round(y) : y);
  598. }
  599. var trunc = Math.trunc || function (v) {
  600. return v > 0 ? Math.floor(v) : Math.ceil(v);
  601. };
  602. Point.prototype = {
  603. // @method clone(): Point
  604. // Returns a copy of the current point.
  605. clone: function () {
  606. return new Point(this.x, this.y);
  607. },
  608. // @method add(otherPoint: Point): Point
  609. // Returns the result of addition of the current and the given points.
  610. add: function (point) {
  611. // non-destructive, returns a new point
  612. return this.clone()._add(toPoint(point));
  613. },
  614. _add: function (point) {
  615. // destructive, used directly for performance in situations where it's safe to modify existing point
  616. this.x += point.x;
  617. this.y += point.y;
  618. return this;
  619. },
  620. // @method subtract(otherPoint: Point): Point
  621. // Returns the result of subtraction of the given point from the current.
  622. subtract: function (point) {
  623. return this.clone()._subtract(toPoint(point));
  624. },
  625. _subtract: function (point) {
  626. this.x -= point.x;
  627. this.y -= point.y;
  628. return this;
  629. },
  630. // @method divideBy(num: Number): Point
  631. // Returns the result of division of the current point by the given number.
  632. divideBy: function (num) {
  633. return this.clone()._divideBy(num);
  634. },
  635. _divideBy: function (num) {
  636. this.x /= num;
  637. this.y /= num;
  638. return this;
  639. },
  640. // @method multiplyBy(num: Number): Point
  641. // Returns the result of multiplication of the current point by the given number.
  642. multiplyBy: function (num) {
  643. return this.clone()._multiplyBy(num);
  644. },
  645. _multiplyBy: function (num) {
  646. this.x *= num;
  647. this.y *= num;
  648. return this;
  649. },
  650. // @method scaleBy(scale: Point): Point
  651. // Multiply each coordinate of the current point by each coordinate of
  652. // `scale`. In linear algebra terms, multiply the point by the
  653. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  654. // defined by `scale`.
  655. scaleBy: function (point) {
  656. return new Point(this.x * point.x, this.y * point.y);
  657. },
  658. // @method unscaleBy(scale: Point): Point
  659. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  660. // each coordinate of `scale`.
  661. unscaleBy: function (point) {
  662. return new Point(this.x / point.x, this.y / point.y);
  663. },
  664. // @method round(): Point
  665. // Returns a copy of the current point with rounded coordinates.
  666. round: function () {
  667. return this.clone()._round();
  668. },
  669. _round: function () {
  670. this.x = Math.round(this.x);
  671. this.y = Math.round(this.y);
  672. return this;
  673. },
  674. // @method floor(): Point
  675. // Returns a copy of the current point with floored coordinates (rounded down).
  676. floor: function () {
  677. return this.clone()._floor();
  678. },
  679. _floor: function () {
  680. this.x = Math.floor(this.x);
  681. this.y = Math.floor(this.y);
  682. return this;
  683. },
  684. // @method ceil(): Point
  685. // Returns a copy of the current point with ceiled coordinates (rounded up).
  686. ceil: function () {
  687. return this.clone()._ceil();
  688. },
  689. _ceil: function () {
  690. this.x = Math.ceil(this.x);
  691. this.y = Math.ceil(this.y);
  692. return this;
  693. },
  694. // @method trunc(): Point
  695. // Returns a copy of the current point with truncated coordinates (rounded towards zero).
  696. trunc: function () {
  697. return this.clone()._trunc();
  698. },
  699. _trunc: function () {
  700. this.x = trunc(this.x);
  701. this.y = trunc(this.y);
  702. return this;
  703. },
  704. // @method distanceTo(otherPoint: Point): Number
  705. // Returns the cartesian distance between the current and the given points.
  706. distanceTo: function (point) {
  707. point = toPoint(point);
  708. var x = point.x - this.x,
  709. y = point.y - this.y;
  710. return Math.sqrt(x * x + y * y);
  711. },
  712. // @method equals(otherPoint: Point): Boolean
  713. // Returns `true` if the given point has the same coordinates.
  714. equals: function (point) {
  715. point = toPoint(point);
  716. return point.x === this.x &&
  717. point.y === this.y;
  718. },
  719. // @method contains(otherPoint: Point): Boolean
  720. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  721. contains: function (point) {
  722. point = toPoint(point);
  723. return Math.abs(point.x) <= Math.abs(this.x) &&
  724. Math.abs(point.y) <= Math.abs(this.y);
  725. },
  726. // @method toString(): String
  727. // Returns a string representation of the point for debugging purposes.
  728. toString: function () {
  729. return 'Point(' +
  730. formatNum(this.x) + ', ' +
  731. formatNum(this.y) + ')';
  732. }
  733. };
  734. // @factory L.point(x: Number, y: Number, round?: Boolean)
  735. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  736. // @alternative
  737. // @factory L.point(coords: Number[])
  738. // Expects an array of the form `[x, y]` instead.
  739. // @alternative
  740. // @factory L.point(coords: Object)
  741. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  742. function toPoint(x, y, round) {
  743. if (x instanceof Point) {
  744. return x;
  745. }
  746. if (isArray(x)) {
  747. return new Point(x[0], x[1]);
  748. }
  749. if (x === undefined || x === null) {
  750. return x;
  751. }
  752. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  753. return new Point(x.x, x.y);
  754. }
  755. return new Point(x, y, round);
  756. }
  757. /*
  758. * @class Bounds
  759. * @aka L.Bounds
  760. *
  761. * Represents a rectangular area in pixel coordinates.
  762. *
  763. * @example
  764. *
  765. * ```js
  766. * var p1 = L.point(10, 10),
  767. * p2 = L.point(40, 60),
  768. * bounds = L.bounds(p1, p2);
  769. * ```
  770. *
  771. * 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:
  772. *
  773. * ```js
  774. * otherBounds.intersects([[10, 10], [40, 60]]);
  775. * ```
  776. *
  777. * Note that `Bounds` does not inherit from Leaflet's `Class` object,
  778. * which means new classes can't inherit from it, and new methods
  779. * can't be added to it with the `include` function.
  780. */
  781. function Bounds(a, b) {
  782. if (!a) { return; }
  783. var points = b ? [a, b] : a;
  784. for (var i = 0, len = points.length; i < len; i++) {
  785. this.extend(points[i]);
  786. }
  787. }
  788. Bounds.prototype = {
  789. // @method extend(point: Point): this
  790. // Extends the bounds to contain the given point.
  791. extend: function (point) { // (Point)
  792. point = toPoint(point);
  793. // @property min: Point
  794. // The top left corner of the rectangle.
  795. // @property max: Point
  796. // The bottom right corner of the rectangle.
  797. if (!this.min && !this.max) {
  798. this.min = point.clone();
  799. this.max = point.clone();
  800. } else {
  801. this.min.x = Math.min(point.x, this.min.x);
  802. this.max.x = Math.max(point.x, this.max.x);
  803. this.min.y = Math.min(point.y, this.min.y);
  804. this.max.y = Math.max(point.y, this.max.y);
  805. }
  806. return this;
  807. },
  808. // @method getCenter(round?: Boolean): Point
  809. // Returns the center point of the bounds.
  810. getCenter: function (round) {
  811. return new Point(
  812. (this.min.x + this.max.x) / 2,
  813. (this.min.y + this.max.y) / 2, round);
  814. },
  815. // @method getBottomLeft(): Point
  816. // Returns the bottom-left point of the bounds.
  817. getBottomLeft: function () {
  818. return new Point(this.min.x, this.max.y);
  819. },
  820. // @method getTopRight(): Point
  821. // Returns the top-right point of the bounds.
  822. getTopRight: function () { // -> Point
  823. return new Point(this.max.x, this.min.y);
  824. },
  825. // @method getTopLeft(): Point
  826. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  827. getTopLeft: function () {
  828. return this.min; // left, top
  829. },
  830. // @method getBottomRight(): Point
  831. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  832. getBottomRight: function () {
  833. return this.max; // right, bottom
  834. },
  835. // @method getSize(): Point
  836. // Returns the size of the given bounds
  837. getSize: function () {
  838. return this.max.subtract(this.min);
  839. },
  840. // @method contains(otherBounds: Bounds): Boolean
  841. // Returns `true` if the rectangle contains the given one.
  842. // @alternative
  843. // @method contains(point: Point): Boolean
  844. // Returns `true` if the rectangle contains the given point.
  845. contains: function (obj) {
  846. var min, max;
  847. if (typeof obj[0] === 'number' || obj instanceof Point) {
  848. obj = toPoint(obj);
  849. } else {
  850. obj = toBounds(obj);
  851. }
  852. if (obj instanceof Bounds) {
  853. min = obj.min;
  854. max = obj.max;
  855. } else {
  856. min = max = obj;
  857. }
  858. return (min.x >= this.min.x) &&
  859. (max.x <= this.max.x) &&
  860. (min.y >= this.min.y) &&
  861. (max.y <= this.max.y);
  862. },
  863. // @method intersects(otherBounds: Bounds): Boolean
  864. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  865. // intersect if they have at least one point in common.
  866. intersects: function (bounds) { // (Bounds) -> Boolean
  867. bounds = toBounds(bounds);
  868. var min = this.min,
  869. max = this.max,
  870. min2 = bounds.min,
  871. max2 = bounds.max,
  872. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  873. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  874. return xIntersects && yIntersects;
  875. },
  876. // @method overlaps(otherBounds: Bounds): Boolean
  877. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  878. // overlap if their intersection is an area.
  879. overlaps: function (bounds) { // (Bounds) -> Boolean
  880. bounds = toBounds(bounds);
  881. var min = this.min,
  882. max = this.max,
  883. min2 = bounds.min,
  884. max2 = bounds.max,
  885. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  886. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  887. return xOverlaps && yOverlaps;
  888. },
  889. isValid: function () {
  890. return !!(this.min && this.max);
  891. }
  892. };
  893. // @factory L.bounds(corner1: Point, corner2: Point)
  894. // Creates a Bounds object from two corners coordinate pairs.
  895. // @alternative
  896. // @factory L.bounds(points: Point[])
  897. // Creates a Bounds object from the given array of points.
  898. function toBounds(a, b) {
  899. if (!a || a instanceof Bounds) {
  900. return a;
  901. }
  902. return new Bounds(a, b);
  903. }
  904. /*
  905. * @class LatLngBounds
  906. * @aka L.LatLngBounds
  907. *
  908. * Represents a rectangular geographical area on a map.
  909. *
  910. * @example
  911. *
  912. * ```js
  913. * var corner1 = L.latLng(40.712, -74.227),
  914. * corner2 = L.latLng(40.774, -74.125),
  915. * bounds = L.latLngBounds(corner1, corner2);
  916. * ```
  917. *
  918. * 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:
  919. *
  920. * ```js
  921. * map.fitBounds([
  922. * [40.712, -74.227],
  923. * [40.774, -74.125]
  924. * ]);
  925. * ```
  926. *
  927. * 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.
  928. *
  929. * Note that `LatLngBounds` does not inherit from Leaflet's `Class` object,
  930. * which means new classes can't inherit from it, and new methods
  931. * can't be added to it with the `include` function.
  932. */
  933. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  934. if (!corner1) { return; }
  935. var latlngs = corner2 ? [corner1, corner2] : corner1;
  936. for (var i = 0, len = latlngs.length; i < len; i++) {
  937. this.extend(latlngs[i]);
  938. }
  939. }
  940. LatLngBounds.prototype = {
  941. // @method extend(latlng: LatLng): this
  942. // Extend the bounds to contain the given point
  943. // @alternative
  944. // @method extend(otherBounds: LatLngBounds): this
  945. // Extend the bounds to contain the given bounds
  946. extend: function (obj) {
  947. var sw = this._southWest,
  948. ne = this._northEast,
  949. sw2, ne2;
  950. if (obj instanceof LatLng) {
  951. sw2 = obj;
  952. ne2 = obj;
  953. } else if (obj instanceof LatLngBounds) {
  954. sw2 = obj._southWest;
  955. ne2 = obj._northEast;
  956. if (!sw2 || !ne2) { return this; }
  957. } else {
  958. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  959. }
  960. if (!sw && !ne) {
  961. this._southWest = new LatLng(sw2.lat, sw2.lng);
  962. this._northEast = new LatLng(ne2.lat, ne2.lng);
  963. } else {
  964. sw.lat = Math.min(sw2.lat, sw.lat);
  965. sw.lng = Math.min(sw2.lng, sw.lng);
  966. ne.lat = Math.max(ne2.lat, ne.lat);
  967. ne.lng = Math.max(ne2.lng, ne.lng);
  968. }
  969. return this;
  970. },
  971. // @method pad(bufferRatio: Number): LatLngBounds
  972. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  973. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  974. // Negative values will retract the bounds.
  975. pad: function (bufferRatio) {
  976. var sw = this._southWest,
  977. ne = this._northEast,
  978. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  979. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  980. return new LatLngBounds(
  981. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  982. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  983. },
  984. // @method getCenter(): LatLng
  985. // Returns the center point of the bounds.
  986. getCenter: function () {
  987. return new LatLng(
  988. (this._southWest.lat + this._northEast.lat) / 2,
  989. (this._southWest.lng + this._northEast.lng) / 2);
  990. },
  991. // @method getSouthWest(): LatLng
  992. // Returns the south-west point of the bounds.
  993. getSouthWest: function () {
  994. return this._southWest;
  995. },
  996. // @method getNorthEast(): LatLng
  997. // Returns the north-east point of the bounds.
  998. getNorthEast: function () {
  999. return this._northEast;
  1000. },
  1001. // @method getNorthWest(): LatLng
  1002. // Returns the north-west point of the bounds.
  1003. getNorthWest: function () {
  1004. return new LatLng(this.getNorth(), this.getWest());
  1005. },
  1006. // @method getSouthEast(): LatLng
  1007. // Returns the south-east point of the bounds.
  1008. getSouthEast: function () {
  1009. return new LatLng(this.getSouth(), this.getEast());
  1010. },
  1011. // @method getWest(): Number
  1012. // Returns the west longitude of the bounds
  1013. getWest: function () {
  1014. return this._southWest.lng;
  1015. },
  1016. // @method getSouth(): Number
  1017. // Returns the south latitude of the bounds
  1018. getSouth: function () {
  1019. return this._southWest.lat;
  1020. },
  1021. // @method getEast(): Number
  1022. // Returns the east longitude of the bounds
  1023. getEast: function () {
  1024. return this._northEast.lng;
  1025. },
  1026. // @method getNorth(): Number
  1027. // Returns the north latitude of the bounds
  1028. getNorth: function () {
  1029. return this._northEast.lat;
  1030. },
  1031. // @method contains(otherBounds: LatLngBounds): Boolean
  1032. // Returns `true` if the rectangle contains the given one.
  1033. // @alternative
  1034. // @method contains (latlng: LatLng): Boolean
  1035. // Returns `true` if the rectangle contains the given point.
  1036. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1037. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1038. obj = toLatLng(obj);
  1039. } else {
  1040. obj = toLatLngBounds(obj);
  1041. }
  1042. var sw = this._southWest,
  1043. ne = this._northEast,
  1044. sw2, ne2;
  1045. if (obj instanceof LatLngBounds) {
  1046. sw2 = obj.getSouthWest();
  1047. ne2 = obj.getNorthEast();
  1048. } else {
  1049. sw2 = ne2 = obj;
  1050. }
  1051. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1052. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1053. },
  1054. // @method intersects(otherBounds: LatLngBounds): Boolean
  1055. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1056. intersects: function (bounds) {
  1057. bounds = toLatLngBounds(bounds);
  1058. var sw = this._southWest,
  1059. ne = this._northEast,
  1060. sw2 = bounds.getSouthWest(),
  1061. ne2 = bounds.getNorthEast(),
  1062. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1063. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1064. return latIntersects && lngIntersects;
  1065. },
  1066. // @method overlaps(otherBounds: LatLngBounds): Boolean
  1067. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1068. overlaps: function (bounds) {
  1069. bounds = toLatLngBounds(bounds);
  1070. var sw = this._southWest,
  1071. ne = this._northEast,
  1072. sw2 = bounds.getSouthWest(),
  1073. ne2 = bounds.getNorthEast(),
  1074. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1075. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1076. return latOverlaps && lngOverlaps;
  1077. },
  1078. // @method toBBoxString(): String
  1079. // Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.
  1080. toBBoxString: function () {
  1081. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1082. },
  1083. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1084. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.
  1085. equals: function (bounds, maxMargin) {
  1086. if (!bounds) { return false; }
  1087. bounds = toLatLngBounds(bounds);
  1088. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1089. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1090. },
  1091. // @method isValid(): Boolean
  1092. // Returns `true` if the bounds are properly initialized.
  1093. isValid: function () {
  1094. return !!(this._southWest && this._northEast);
  1095. }
  1096. };
  1097. // TODO International date line?
  1098. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1099. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1100. // @alternative
  1101. // @factory L.latLngBounds(latlngs: LatLng[])
  1102. // 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).
  1103. function toLatLngBounds(a, b) {
  1104. if (a instanceof LatLngBounds) {
  1105. return a;
  1106. }
  1107. return new LatLngBounds(a, b);
  1108. }
  1109. /* @class LatLng
  1110. * @aka L.LatLng
  1111. *
  1112. * Represents a geographical point with a certain latitude and longitude.
  1113. *
  1114. * @example
  1115. *
  1116. * ```
  1117. * var latlng = L.latLng(50.5, 30.5);
  1118. * ```
  1119. *
  1120. * 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:
  1121. *
  1122. * ```
  1123. * map.panTo([50, 30]);
  1124. * map.panTo({lon: 30, lat: 50});
  1125. * map.panTo({lat: 50, lng: 30});
  1126. * map.panTo(L.latLng(50, 30));
  1127. * ```
  1128. *
  1129. * Note that `LatLng` does not inherit from Leaflet's `Class` object,
  1130. * which means new classes can't inherit from it, and new methods
  1131. * can't be added to it with the `include` function.
  1132. */
  1133. function LatLng(lat, lng, alt) {
  1134. if (isNaN(lat) || isNaN(lng)) {
  1135. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1136. }
  1137. // @property lat: Number
  1138. // Latitude in degrees
  1139. this.lat = +lat;
  1140. // @property lng: Number
  1141. // Longitude in degrees
  1142. this.lng = +lng;
  1143. // @property alt: Number
  1144. // Altitude in meters (optional)
  1145. if (alt !== undefined) {
  1146. this.alt = +alt;
  1147. }
  1148. }
  1149. LatLng.prototype = {
  1150. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1151. // 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.
  1152. equals: function (obj, maxMargin) {
  1153. if (!obj) { return false; }
  1154. obj = toLatLng(obj);
  1155. var margin = Math.max(
  1156. Math.abs(this.lat - obj.lat),
  1157. Math.abs(this.lng - obj.lng));
  1158. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1159. },
  1160. // @method toString(): String
  1161. // Returns a string representation of the point (for debugging purposes).
  1162. toString: function (precision) {
  1163. return 'LatLng(' +
  1164. formatNum(this.lat, precision) + ', ' +
  1165. formatNum(this.lng, precision) + ')';
  1166. },
  1167. // @method distanceTo(otherLatLng: LatLng): Number
  1168. // Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).
  1169. distanceTo: function (other) {
  1170. return Earth.distance(this, toLatLng(other));
  1171. },
  1172. // @method wrap(): LatLng
  1173. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1174. wrap: function () {
  1175. return Earth.wrapLatLng(this);
  1176. },
  1177. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1178. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1179. toBounds: function (sizeInMeters) {
  1180. var latAccuracy = 180 * sizeInMeters / 40075017,
  1181. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1182. return toLatLngBounds(
  1183. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1184. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1185. },
  1186. clone: function () {
  1187. return new LatLng(this.lat, this.lng, this.alt);
  1188. }
  1189. };
  1190. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1191. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1192. // @alternative
  1193. // @factory L.latLng(coords: Array): LatLng
  1194. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1195. // @alternative
  1196. // @factory L.latLng(coords: Object): LatLng
  1197. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1198. function toLatLng(a, b, c) {
  1199. if (a instanceof LatLng) {
  1200. return a;
  1201. }
  1202. if (isArray(a) && typeof a[0] !== 'object') {
  1203. if (a.length === 3) {
  1204. return new LatLng(a[0], a[1], a[2]);
  1205. }
  1206. if (a.length === 2) {
  1207. return new LatLng(a[0], a[1]);
  1208. }
  1209. return null;
  1210. }
  1211. if (a === undefined || a === null) {
  1212. return a;
  1213. }
  1214. if (typeof a === 'object' && 'lat' in a) {
  1215. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1216. }
  1217. if (b === undefined) {
  1218. return null;
  1219. }
  1220. return new LatLng(a, b, c);
  1221. }
  1222. /*
  1223. * @namespace CRS
  1224. * @crs L.CRS.Base
  1225. * Object that defines coordinate reference systems for projecting
  1226. * geographical points into pixel (screen) coordinates and back (and to
  1227. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1228. * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
  1229. *
  1230. * Leaflet defines the most usual CRSs by default. If you want to use a
  1231. * CRS not defined by default, take a look at the
  1232. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1233. *
  1234. * Note that the CRS instances do not inherit from Leaflet's `Class` object,
  1235. * and can't be instantiated. Also, new classes can't inherit from them,
  1236. * and methods can't be added to them with the `include` function.
  1237. */
  1238. var CRS = {
  1239. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1240. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1241. latLngToPoint: function (latlng, zoom) {
  1242. var projectedPoint = this.projection.project(latlng),
  1243. scale = this.scale(zoom);
  1244. return this.transformation._transform(projectedPoint, scale);
  1245. },
  1246. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1247. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1248. // zoom into geographical coordinates.
  1249. pointToLatLng: function (point, zoom) {
  1250. var scale = this.scale(zoom),
  1251. untransformedPoint = this.transformation.untransform(point, scale);
  1252. return this.projection.unproject(untransformedPoint);
  1253. },
  1254. // @method project(latlng: LatLng): Point
  1255. // Projects geographical coordinates into coordinates in units accepted for
  1256. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1257. project: function (latlng) {
  1258. return this.projection.project(latlng);
  1259. },
  1260. // @method unproject(point: Point): LatLng
  1261. // Given a projected coordinate returns the corresponding LatLng.
  1262. // The inverse of `project`.
  1263. unproject: function (point) {
  1264. return this.projection.unproject(point);
  1265. },
  1266. // @method scale(zoom: Number): Number
  1267. // Returns the scale used when transforming projected coordinates into
  1268. // pixel coordinates for a particular zoom. For example, it returns
  1269. // `256 * 2^zoom` for Mercator-based CRS.
  1270. scale: function (zoom) {
  1271. return 256 * Math.pow(2, zoom);
  1272. },
  1273. // @method zoom(scale: Number): Number
  1274. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1275. // factor of `scale`.
  1276. zoom: function (scale) {
  1277. return Math.log(scale / 256) / Math.LN2;
  1278. },
  1279. // @method getProjectedBounds(zoom: Number): Bounds
  1280. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1281. getProjectedBounds: function (zoom) {
  1282. if (this.infinite) { return null; }
  1283. var b = this.projection.bounds,
  1284. s = this.scale(zoom),
  1285. min = this.transformation.transform(b.min, s),
  1286. max = this.transformation.transform(b.max, s);
  1287. return new Bounds(min, max);
  1288. },
  1289. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1290. // Returns the distance between two geographical coordinates.
  1291. // @property code: String
  1292. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1293. //
  1294. // @property wrapLng: Number[]
  1295. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1296. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1297. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1298. //
  1299. // @property wrapLat: Number[]
  1300. // Like `wrapLng`, but for the latitude (vertical) axis.
  1301. // wrapLng: [min, max],
  1302. // wrapLat: [min, max],
  1303. // @property infinite: Boolean
  1304. // If true, the coordinate space will be unbounded (infinite in both axes)
  1305. infinite: false,
  1306. // @method wrapLatLng(latlng: LatLng): LatLng
  1307. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1308. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1309. wrapLatLng: function (latlng) {
  1310. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1311. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1312. alt = latlng.alt;
  1313. return new LatLng(lat, lng, alt);
  1314. },
  1315. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1316. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1317. // that its center is within the CRS's bounds.
  1318. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1319. wrapLatLngBounds: function (bounds) {
  1320. var center = bounds.getCenter(),
  1321. newCenter = this.wrapLatLng(center),
  1322. latShift = center.lat - newCenter.lat,
  1323. lngShift = center.lng - newCenter.lng;
  1324. if (latShift === 0 && lngShift === 0) {
  1325. return bounds;
  1326. }
  1327. var sw = bounds.getSouthWest(),
  1328. ne = bounds.getNorthEast(),
  1329. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1330. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1331. return new LatLngBounds(newSw, newNe);
  1332. }
  1333. };
  1334. /*
  1335. * @namespace CRS
  1336. * @crs L.CRS.Earth
  1337. *
  1338. * Serves as the base for CRS that are global such that they cover the earth.
  1339. * Can only be used as the base for other CRS and cannot be used directly,
  1340. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1341. * meters.
  1342. */
  1343. var Earth = extend({}, CRS, {
  1344. wrapLng: [-180, 180],
  1345. // Mean Earth Radius, as recommended for use by
  1346. // the International Union of Geodesy and Geophysics,
  1347. // see http://rosettacode.org/wiki/Haversine_formula
  1348. R: 6371000,
  1349. // distance between two geographical points using spherical law of cosines approximation
  1350. distance: function (latlng1, latlng2) {
  1351. var rad = Math.PI / 180,
  1352. lat1 = latlng1.lat * rad,
  1353. lat2 = latlng2.lat * rad,
  1354. sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
  1355. sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
  1356. a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
  1357. c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1358. return this.R * c;
  1359. }
  1360. });
  1361. /*
  1362. * @namespace Projection
  1363. * @projection L.Projection.SphericalMercator
  1364. *
  1365. * Spherical Mercator projection — the most common projection for online maps,
  1366. * used by almost all free and commercial tile providers. Assumes that Earth is
  1367. * a sphere. Used by the `EPSG:3857` CRS.
  1368. */
  1369. var earthRadius = 6378137;
  1370. var SphericalMercator = {
  1371. R: earthRadius,
  1372. MAX_LATITUDE: 85.0511287798,
  1373. project: function (latlng) {
  1374. var d = Math.PI / 180,
  1375. max = this.MAX_LATITUDE,
  1376. lat = Math.max(Math.min(max, latlng.lat), -max),
  1377. sin = Math.sin(lat * d);
  1378. return new Point(
  1379. this.R * latlng.lng * d,
  1380. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1381. },
  1382. unproject: function (point) {
  1383. var d = 180 / Math.PI;
  1384. return new LatLng(
  1385. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1386. point.x * d / this.R);
  1387. },
  1388. bounds: (function () {
  1389. var d = earthRadius * Math.PI;
  1390. return new Bounds([-d, -d], [d, d]);
  1391. })()
  1392. };
  1393. /*
  1394. * @class Transformation
  1395. * @aka L.Transformation
  1396. *
  1397. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1398. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1399. * the reverse. Used by Leaflet in its projections code.
  1400. *
  1401. * @example
  1402. *
  1403. * ```js
  1404. * var transformation = L.transformation(2, 5, -1, 10),
  1405. * p = L.point(1, 2),
  1406. * p2 = transformation.transform(p), // L.point(7, 8)
  1407. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1408. * ```
  1409. */
  1410. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1411. // Creates a `Transformation` object with the given coefficients.
  1412. function Transformation(a, b, c, d) {
  1413. if (isArray(a)) {
  1414. // use array properties
  1415. this._a = a[0];
  1416. this._b = a[1];
  1417. this._c = a[2];
  1418. this._d = a[3];
  1419. return;
  1420. }
  1421. this._a = a;
  1422. this._b = b;
  1423. this._c = c;
  1424. this._d = d;
  1425. }
  1426. Transformation.prototype = {
  1427. // @method transform(point: Point, scale?: Number): Point
  1428. // Returns a transformed point, optionally multiplied by the given scale.
  1429. // Only accepts actual `L.Point` instances, not arrays.
  1430. transform: function (point, scale) { // (Point, Number) -> Point
  1431. return this._transform(point.clone(), scale);
  1432. },
  1433. // destructive transform (faster)
  1434. _transform: function (point, scale) {
  1435. scale = scale || 1;
  1436. point.x = scale * (this._a * point.x + this._b);
  1437. point.y = scale * (this._c * point.y + this._d);
  1438. return point;
  1439. },
  1440. // @method untransform(point: Point, scale?: Number): Point
  1441. // Returns the reverse transformation of the given point, optionally divided
  1442. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1443. untransform: function (point, scale) {
  1444. scale = scale || 1;
  1445. return new Point(
  1446. (point.x / scale - this._b) / this._a,
  1447. (point.y / scale - this._d) / this._c);
  1448. }
  1449. };
  1450. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1451. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1452. // Instantiates a Transformation object with the given coefficients.
  1453. // @alternative
  1454. // @factory L.transformation(coefficients: Array): Transformation
  1455. // Expects an coefficients array of the form
  1456. // `[a: Number, b: Number, c: Number, d: Number]`.
  1457. function toTransformation(a, b, c, d) {
  1458. return new Transformation(a, b, c, d);
  1459. }
  1460. /*
  1461. * @namespace CRS
  1462. * @crs L.CRS.EPSG3857
  1463. *
  1464. * The most common CRS for online maps, used by almost all free and commercial
  1465. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1466. * Map's `crs` option.
  1467. */
  1468. var EPSG3857 = extend({}, Earth, {
  1469. code: 'EPSG:3857',
  1470. projection: SphericalMercator,
  1471. transformation: (function () {
  1472. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1473. return toTransformation(scale, 0.5, -scale, 0.5);
  1474. }())
  1475. });
  1476. var EPSG900913 = extend({}, EPSG3857, {
  1477. code: 'EPSG:900913'
  1478. });
  1479. // @namespace SVG; @section
  1480. // There are several static functions which can be called without instantiating L.SVG:
  1481. // @function create(name: String): SVGElement
  1482. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1483. // corresponding to the class name passed. For example, using 'line' will return
  1484. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1485. function svgCreate(name) {
  1486. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1487. }
  1488. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1489. // Generates a SVG path string for multiple rings, with each ring turning
  1490. // into "M..L..L.." instructions
  1491. function pointsToPath(rings, closed) {
  1492. var str = '',
  1493. i, j, len, len2, points, p;
  1494. for (i = 0, len = rings.length; i < len; i++) {
  1495. points = rings[i];
  1496. for (j = 0, len2 = points.length; j < len2; j++) {
  1497. p = points[j];
  1498. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1499. }
  1500. // closes the ring for polygons; "x" is VML syntax
  1501. str += closed ? (svg ? 'z' : 'x') : '';
  1502. }
  1503. // SVG complains about empty path strings
  1504. return str || 'M0 0';
  1505. }
  1506. /*
  1507. * @namespace Browser
  1508. * @aka L.Browser
  1509. *
  1510. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1511. *
  1512. * @example
  1513. *
  1514. * ```js
  1515. * if (L.Browser.ielt9) {
  1516. * alert('Upgrade your browser, dude!');
  1517. * }
  1518. * ```
  1519. */
  1520. var style$1 = document.documentElement.style;
  1521. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1522. var ie = 'ActiveXObject' in window;
  1523. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1524. var ielt9 = ie && !document.addEventListener;
  1525. // @property edge: Boolean; `true` for the Edge web browser.
  1526. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1527. // @property webkit: Boolean;
  1528. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1529. var webkit = userAgentContains('webkit');
  1530. // @property android: Boolean
  1531. // `true` for any browser running on an Android platform.
  1532. var android = userAgentContains('android');
  1533. // @property android23: Boolean; `true` for browsers running on Android 2 or Android 3.
  1534. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1535. /* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */
  1536. var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit
  1537. // @property androidStock: Boolean; `true` for the Android stock browser (i.e. not Chrome)
  1538. var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);
  1539. // @property opera: Boolean; `true` for the Opera browser
  1540. var opera = !!window.opera;
  1541. // @property chrome: Boolean; `true` for the Chrome browser.
  1542. var chrome = !edge && userAgentContains('chrome');
  1543. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1544. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1545. // @property safari: Boolean; `true` for the Safari browser.
  1546. var safari = !chrome && userAgentContains('safari');
  1547. var phantom = userAgentContains('phantom');
  1548. // @property opera12: Boolean
  1549. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1550. var opera12 = 'OTransition' in style$1;
  1551. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1552. var win = navigator.platform.indexOf('Win') === 0;
  1553. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1554. var ie3d = ie && ('transition' in style$1);
  1555. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1556. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1557. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1558. var gecko3d = 'MozPerspective' in style$1;
  1559. // @property any3d: Boolean
  1560. // `true` for all browsers supporting CSS transforms.
  1561. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1562. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1563. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1564. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1565. var mobileWebkit = mobile && webkit;
  1566. // @property mobileWebkit3d: Boolean
  1567. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1568. var mobileWebkit3d = mobile && webkit3d;
  1569. // @property msPointer: Boolean
  1570. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1571. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1572. // @property pointer: Boolean
  1573. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1574. var pointer = !!(window.PointerEvent || msPointer);
  1575. // @property touch: Boolean
  1576. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1577. // This does not necessarily mean that the browser is running in a computer with
  1578. // a touchscreen, it only means that the browser is capable of understanding
  1579. // touch events.
  1580. var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
  1581. (window.DocumentTouch && document instanceof window.DocumentTouch));
  1582. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1583. var mobileOpera = mobile && opera;
  1584. // @property mobileGecko: Boolean
  1585. // `true` for gecko-based browsers running in a mobile device.
  1586. var mobileGecko = mobile && gecko;
  1587. // @property retina: Boolean
  1588. // `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%.
  1589. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1590. // @property passiveEvents: Boolean
  1591. // `true` for browsers that support passive events.
  1592. var passiveEvents = (function () {
  1593. var supportsPassiveOption = false;
  1594. try {
  1595. var opts = Object.defineProperty({}, 'passive', {
  1596. get: function () { // eslint-disable-line getter-return
  1597. supportsPassiveOption = true;
  1598. }
  1599. });
  1600. window.addEventListener('testPassiveEventSupport', falseFn, opts);
  1601. window.removeEventListener('testPassiveEventSupport', falseFn, opts);
  1602. } catch (e) {
  1603. // Errors can safely be ignored since this is only a browser support test.
  1604. }
  1605. return supportsPassiveOption;
  1606. }());
  1607. // @property canvas: Boolean
  1608. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1609. var canvas = (function () {
  1610. return !!document.createElement('canvas').getContext;
  1611. }());
  1612. // @property svg: Boolean
  1613. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1614. var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1615. // @property vml: Boolean
  1616. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1617. var vml = !svg && (function () {
  1618. try {
  1619. var div = document.createElement('div');
  1620. div.innerHTML = '<v:shape adj="1"/>';
  1621. var shape = div.firstChild;
  1622. shape.style.behavior = 'url(#default#VML)';
  1623. return shape && (typeof shape.adj === 'object');
  1624. } catch (e) {
  1625. return false;
  1626. }
  1627. }());
  1628. function userAgentContains(str) {
  1629. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1630. }
  1631. var Browser = ({
  1632. ie: ie,
  1633. ielt9: ielt9,
  1634. edge: edge,
  1635. webkit: webkit,
  1636. android: android,
  1637. android23: android23,
  1638. androidStock: androidStock,
  1639. opera: opera,
  1640. chrome: chrome,
  1641. gecko: gecko,
  1642. safari: safari,
  1643. phantom: phantom,
  1644. opera12: opera12,
  1645. win: win,
  1646. ie3d: ie3d,
  1647. webkit3d: webkit3d,
  1648. gecko3d: gecko3d,
  1649. any3d: any3d,
  1650. mobile: mobile,
  1651. mobileWebkit: mobileWebkit,
  1652. mobileWebkit3d: mobileWebkit3d,
  1653. msPointer: msPointer,
  1654. pointer: pointer,
  1655. touch: touch,
  1656. mobileOpera: mobileOpera,
  1657. mobileGecko: mobileGecko,
  1658. retina: retina,
  1659. passiveEvents: passiveEvents,
  1660. canvas: canvas,
  1661. svg: svg,
  1662. vml: vml
  1663. });
  1664. /*
  1665. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1666. */
  1667. var POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';
  1668. var POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';
  1669. var POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';
  1670. var POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';
  1671. var _pointers = {};
  1672. var _pointerDocListener = false;
  1673. // Provides a touch events wrapper for (ms)pointer events.
  1674. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1675. function addPointerListener(obj, type, handler, id) {
  1676. if (type === 'touchstart') {
  1677. _addPointerStart(obj, handler, id);
  1678. } else if (type === 'touchmove') {
  1679. _addPointerMove(obj, handler, id);
  1680. } else if (type === 'touchend') {
  1681. _addPointerEnd(obj, handler, id);
  1682. }
  1683. return this;
  1684. }
  1685. function removePointerListener(obj, type, id) {
  1686. var handler = obj['_leaflet_' + type + id];
  1687. if (type === 'touchstart') {
  1688. obj.removeEventListener(POINTER_DOWN, handler, false);
  1689. } else if (type === 'touchmove') {
  1690. obj.removeEventListener(POINTER_MOVE, handler, false);
  1691. } else if (type === 'touchend') {
  1692. obj.removeEventListener(POINTER_UP, handler, false);
  1693. obj.removeEventListener(POINTER_CANCEL, handler, false);
  1694. }
  1695. return this;
  1696. }
  1697. function _addPointerStart(obj, handler, id) {
  1698. var onDown = bind(function (e) {
  1699. // IE10 specific: MsTouch needs preventDefault. See #2000
  1700. if (e.MSPOINTER_TYPE_TOUCH && e.pointerType === e.MSPOINTER_TYPE_TOUCH) {
  1701. preventDefault(e);
  1702. }
  1703. _handlePointer(e, handler);
  1704. });
  1705. obj['_leaflet_touchstart' + id] = onDown;
  1706. obj.addEventListener(POINTER_DOWN, onDown, false);
  1707. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1708. if (!_pointerDocListener) {
  1709. // we listen document as any drags that end by moving the touch off the screen get fired there
  1710. document.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1711. document.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1712. document.addEventListener(POINTER_UP, _globalPointerUp, true);
  1713. document.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1714. _pointerDocListener = true;
  1715. }
  1716. }
  1717. function _globalPointerDown(e) {
  1718. _pointers[e.pointerId] = e;
  1719. }
  1720. function _globalPointerMove(e) {
  1721. if (_pointers[e.pointerId]) {
  1722. _pointers[e.pointerId] = e;
  1723. }
  1724. }
  1725. function _globalPointerUp(e) {
  1726. delete _pointers[e.pointerId];
  1727. }
  1728. function _handlePointer(e, handler) {
  1729. e.touches = [];
  1730. for (var i in _pointers) {
  1731. e.touches.push(_pointers[i]);
  1732. }
  1733. e.changedTouches = [e];
  1734. handler(e);
  1735. }
  1736. function _addPointerMove(obj, handler, id) {
  1737. var onMove = function (e) {
  1738. // don't fire touch moves when mouse isn't down
  1739. if ((e.pointerType === (e.MSPOINTER_TYPE_MOUSE || 'mouse')) && e.buttons === 0) {
  1740. return;
  1741. }
  1742. _handlePointer(e, handler);
  1743. };
  1744. obj['_leaflet_touchmove' + id] = onMove;
  1745. obj.addEventListener(POINTER_MOVE, onMove, false);
  1746. }
  1747. function _addPointerEnd(obj, handler, id) {
  1748. var onUp = function (e) {
  1749. _handlePointer(e, handler);
  1750. };
  1751. obj['_leaflet_touchend' + id] = onUp;
  1752. obj.addEventListener(POINTER_UP, onUp, false);
  1753. obj.addEventListener(POINTER_CANCEL, onUp, false);
  1754. }
  1755. /*
  1756. * Extends the event handling code with double tap support for mobile browsers.
  1757. */
  1758. var _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';
  1759. var _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';
  1760. var _pre = '_leaflet_';
  1761. // inspired by Zepto touch code by Thomas Fuchs
  1762. function addDoubleTapListener(obj, handler, id) {
  1763. var last, touch$$1,
  1764. doubleTap = false,
  1765. delay = 250;
  1766. function onTouchStart(e) {
  1767. if (pointer) {
  1768. if (!e.isPrimary) { return; }
  1769. if (e.pointerType === 'mouse') { return; } // mouse fires native dblclick
  1770. } else if (e.touches.length > 1) {
  1771. return;
  1772. }
  1773. var now = Date.now(),
  1774. delta = now - (last || now);
  1775. touch$$1 = e.touches ? e.touches[0] : e;
  1776. doubleTap = (delta > 0 && delta <= delay);
  1777. last = now;
  1778. }
  1779. function onTouchEnd(e) {
  1780. if (doubleTap && !touch$$1.cancelBubble) {
  1781. if (pointer) {
  1782. if (e.pointerType === 'mouse') { return; }
  1783. // work around .type being readonly with MSPointer* events
  1784. var newTouch = {},
  1785. prop, i;
  1786. for (i in touch$$1) {
  1787. prop = touch$$1[i];
  1788. newTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;
  1789. }
  1790. touch$$1 = newTouch;
  1791. }
  1792. touch$$1.type = 'dblclick';
  1793. touch$$1.button = 0;
  1794. handler(touch$$1);
  1795. last = null;
  1796. }
  1797. }
  1798. obj[_pre + _touchstart + id] = onTouchStart;
  1799. obj[_pre + _touchend + id] = onTouchEnd;
  1800. obj[_pre + 'dblclick' + id] = handler;
  1801. obj.addEventListener(_touchstart, onTouchStart, passiveEvents ? {passive: false} : false);
  1802. obj.addEventListener(_touchend, onTouchEnd, passiveEvents ? {passive: false} : false);
  1803. // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
  1804. // the browser doesn't fire touchend/pointerup events but does fire
  1805. // native dblclicks. See #4127.
  1806. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
  1807. obj.addEventListener('dblclick', handler, false);
  1808. return this;
  1809. }
  1810. function removeDoubleTapListener(obj, id) {
  1811. var touchstart = obj[_pre + _touchstart + id],
  1812. touchend = obj[_pre + _touchend + id],
  1813. dblclick = obj[_pre + 'dblclick' + id];
  1814. obj.removeEventListener(_touchstart, touchstart, passiveEvents ? {passive: false} : false);
  1815. obj.removeEventListener(_touchend, touchend, passiveEvents ? {passive: false} : false);
  1816. obj.removeEventListener('dblclick', dblclick, false);
  1817. return this;
  1818. }
  1819. /*
  1820. * @namespace DomUtil
  1821. *
  1822. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1823. * tree, used by Leaflet internally.
  1824. *
  1825. * Most functions expecting or returning a `HTMLElement` also work for
  1826. * SVG elements. The only difference is that classes refer to CSS classes
  1827. * in HTML and SVG classes in SVG.
  1828. */
  1829. // @property TRANSFORM: String
  1830. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  1831. var TRANSFORM = testProp(
  1832. ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1833. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1834. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1835. // @property TRANSITION: String
  1836. // Vendor-prefixed transition style name.
  1837. var TRANSITION = testProp(
  1838. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1839. // @property TRANSITION_END: String
  1840. // Vendor-prefixed transitionend event name.
  1841. var TRANSITION_END =
  1842. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  1843. // @function get(id: String|HTMLElement): HTMLElement
  1844. // Returns an element given its DOM id, or returns the element itself
  1845. // if it was passed directly.
  1846. function get(id) {
  1847. return typeof id === 'string' ? document.getElementById(id) : id;
  1848. }
  1849. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1850. // Returns the value for a certain style attribute on an element,
  1851. // including computed values or values set through CSS.
  1852. function getStyle(el, style) {
  1853. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1854. if ((!value || value === 'auto') && document.defaultView) {
  1855. var css = document.defaultView.getComputedStyle(el, null);
  1856. value = css ? css[style] : null;
  1857. }
  1858. return value === 'auto' ? null : value;
  1859. }
  1860. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1861. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1862. function create$1(tagName, className, container) {
  1863. var el = document.createElement(tagName);
  1864. el.className = className || '';
  1865. if (container) {
  1866. container.appendChild(el);
  1867. }
  1868. return el;
  1869. }
  1870. // @function remove(el: HTMLElement)
  1871. // Removes `el` from its parent element
  1872. function remove(el) {
  1873. var parent = el.parentNode;
  1874. if (parent) {
  1875. parent.removeChild(el);
  1876. }
  1877. }
  1878. // @function empty(el: HTMLElement)
  1879. // Removes all of `el`'s children elements from `el`
  1880. function empty(el) {
  1881. while (el.firstChild) {
  1882. el.removeChild(el.firstChild);
  1883. }
  1884. }
  1885. // @function toFront(el: HTMLElement)
  1886. // Makes `el` the last child of its parent, so it renders in front of the other children.
  1887. function toFront(el) {
  1888. var parent = el.parentNode;
  1889. if (parent && parent.lastChild !== el) {
  1890. parent.appendChild(el);
  1891. }
  1892. }
  1893. // @function toBack(el: HTMLElement)
  1894. // Makes `el` the first child of its parent, so it renders behind the other children.
  1895. function toBack(el) {
  1896. var parent = el.parentNode;
  1897. if (parent && parent.firstChild !== el) {
  1898. parent.insertBefore(el, parent.firstChild);
  1899. }
  1900. }
  1901. // @function hasClass(el: HTMLElement, name: String): Boolean
  1902. // Returns `true` if the element's class attribute contains `name`.
  1903. function hasClass(el, name) {
  1904. if (el.classList !== undefined) {
  1905. return el.classList.contains(name);
  1906. }
  1907. var className = getClass(el);
  1908. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  1909. }
  1910. // @function addClass(el: HTMLElement, name: String)
  1911. // Adds `name` to the element's class attribute.
  1912. function addClass(el, name) {
  1913. if (el.classList !== undefined) {
  1914. var classes = splitWords(name);
  1915. for (var i = 0, len = classes.length; i < len; i++) {
  1916. el.classList.add(classes[i]);
  1917. }
  1918. } else if (!hasClass(el, name)) {
  1919. var className = getClass(el);
  1920. setClass(el, (className ? className + ' ' : '') + name);
  1921. }
  1922. }
  1923. // @function removeClass(el: HTMLElement, name: String)
  1924. // Removes `name` from the element's class attribute.
  1925. function removeClass(el, name) {
  1926. if (el.classList !== undefined) {
  1927. el.classList.remove(name);
  1928. } else {
  1929. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  1930. }
  1931. }
  1932. // @function setClass(el: HTMLElement, name: String)
  1933. // Sets the element's class.
  1934. function setClass(el, name) {
  1935. if (el.className.baseVal === undefined) {
  1936. el.className = name;
  1937. } else {
  1938. // in case of SVG element
  1939. el.className.baseVal = name;
  1940. }
  1941. }
  1942. // @function getClass(el: HTMLElement): String
  1943. // Returns the element's class.
  1944. function getClass(el) {
  1945. // Check if the element is an SVGElementInstance and use the correspondingElement instead
  1946. // (Required for linked SVG elements in IE11.)
  1947. if (el.correspondingElement) {
  1948. el = el.correspondingElement;
  1949. }
  1950. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  1951. }
  1952. // @function setOpacity(el: HTMLElement, opacity: Number)
  1953. // Set the opacity of an element (including old IE support).
  1954. // `opacity` must be a number from `0` to `1`.
  1955. function setOpacity(el, value) {
  1956. if ('opacity' in el.style) {
  1957. el.style.opacity = value;
  1958. } else if ('filter' in el.style) {
  1959. _setOpacityIE(el, value);
  1960. }
  1961. }
  1962. function _setOpacityIE(el, value) {
  1963. var filter = false,
  1964. filterName = 'DXImageTransform.Microsoft.Alpha';
  1965. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  1966. try {
  1967. filter = el.filters.item(filterName);
  1968. } catch (e) {
  1969. // don't set opacity to 1 if we haven't already set an opacity,
  1970. // it isn't needed and breaks transparent pngs.
  1971. if (value === 1) { return; }
  1972. }
  1973. value = Math.round(value * 100);
  1974. if (filter) {
  1975. filter.Enabled = (value !== 100);
  1976. filter.Opacity = value;
  1977. } else {
  1978. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  1979. }
  1980. }
  1981. // @function testProp(props: String[]): String|false
  1982. // Goes through the array of style names and returns the first name
  1983. // that is a valid style name for an element. If no such name is found,
  1984. // it returns false. Useful for vendor-prefixed styles like `transform`.
  1985. function testProp(props) {
  1986. var style = document.documentElement.style;
  1987. for (var i = 0; i < props.length; i++) {
  1988. if (props[i] in style) {
  1989. return props[i];
  1990. }
  1991. }
  1992. return false;
  1993. }
  1994. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  1995. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  1996. // and optionally scaled by `scale`. Does not have an effect if the
  1997. // browser doesn't support 3D CSS transforms.
  1998. function setTransform(el, offset, scale) {
  1999. var pos = offset || new Point(0, 0);
  2000. el.style[TRANSFORM] =
  2001. (ie3d ?
  2002. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2003. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2004. (scale ? ' scale(' + scale + ')' : '');
  2005. }
  2006. // @function setPosition(el: HTMLElement, position: Point)
  2007. // Sets the position of `el` to coordinates specified by `position`,
  2008. // using CSS translate or top/left positioning depending on the browser
  2009. // (used by Leaflet internally to position its layers).
  2010. function setPosition(el, point) {
  2011. /*eslint-disable */
  2012. el._leaflet_pos = point;
  2013. /* eslint-enable */
  2014. if (any3d) {
  2015. setTransform(el, point);
  2016. } else {
  2017. el.style.left = point.x + 'px';
  2018. el.style.top = point.y + 'px';
  2019. }
  2020. }
  2021. // @function getPosition(el: HTMLElement): Point
  2022. // Returns the coordinates of an element previously positioned with setPosition.
  2023. function getPosition(el) {
  2024. // this method is only used for elements previously positioned using setPosition,
  2025. // so it's safe to cache the position for performance
  2026. return el._leaflet_pos || new Point(0, 0);
  2027. }
  2028. // @function disableTextSelection()
  2029. // Prevents the user from generating `selectstart` DOM events, usually generated
  2030. // when the user drags the mouse through a page with text. Used internally
  2031. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2032. // the map. Affects drag interactions on the whole document.
  2033. // @function enableTextSelection()
  2034. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2035. var disableTextSelection;
  2036. var enableTextSelection;
  2037. var _userSelect;
  2038. if ('onselectstart' in document) {
  2039. disableTextSelection = function () {
  2040. on(window, 'selectstart', preventDefault);
  2041. };
  2042. enableTextSelection = function () {
  2043. off(window, 'selectstart', preventDefault);
  2044. };
  2045. } else {
  2046. var userSelectProperty = testProp(
  2047. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2048. disableTextSelection = function () {
  2049. if (userSelectProperty) {
  2050. var style = document.documentElement.style;
  2051. _userSelect = style[userSelectProperty];
  2052. style[userSelectProperty] = 'none';
  2053. }
  2054. };
  2055. enableTextSelection = function () {
  2056. if (userSelectProperty) {
  2057. document.documentElement.style[userSelectProperty] = _userSelect;
  2058. _userSelect = undefined;
  2059. }
  2060. };
  2061. }
  2062. // @function disableImageDrag()
  2063. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2064. // for `dragstart` DOM events, usually generated when the user drags an image.
  2065. function disableImageDrag() {
  2066. on(window, 'dragstart', preventDefault);
  2067. }
  2068. // @function enableImageDrag()
  2069. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2070. function enableImageDrag() {
  2071. off(window, 'dragstart', preventDefault);
  2072. }
  2073. var _outlineElement, _outlineStyle;
  2074. // @function preventOutline(el: HTMLElement)
  2075. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2076. // of the element `el` invisible. Used internally by Leaflet to prevent
  2077. // focusable elements from displaying an outline when the user performs a
  2078. // drag interaction on them.
  2079. function preventOutline(element) {
  2080. while (element.tabIndex === -1) {
  2081. element = element.parentNode;
  2082. }
  2083. if (!element.style) { return; }
  2084. restoreOutline();
  2085. _outlineElement = element;
  2086. _outlineStyle = element.style.outline;
  2087. element.style.outline = 'none';
  2088. on(window, 'keydown', restoreOutline);
  2089. }
  2090. // @function restoreOutline()
  2091. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2092. function restoreOutline() {
  2093. if (!_outlineElement) { return; }
  2094. _outlineElement.style.outline = _outlineStyle;
  2095. _outlineElement = undefined;
  2096. _outlineStyle = undefined;
  2097. off(window, 'keydown', restoreOutline);
  2098. }
  2099. // @function getSizedParentNode(el: HTMLElement): HTMLElement
  2100. // Finds the closest parent node which size (width and height) is not null.
  2101. function getSizedParentNode(element) {
  2102. do {
  2103. element = element.parentNode;
  2104. } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);
  2105. return element;
  2106. }
  2107. // @function getScale(el: HTMLElement): Object
  2108. // Computes the CSS scale currently applied on the element.
  2109. // Returns an object with `x` and `y` members as horizontal and vertical scales respectively,
  2110. // and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2111. function getScale(element) {
  2112. var rect = element.getBoundingClientRect(); // Read-only in old browsers.
  2113. return {
  2114. x: rect.width / element.offsetWidth || 1,
  2115. y: rect.height / element.offsetHeight || 1,
  2116. boundingClientRect: rect
  2117. };
  2118. }
  2119. var DomUtil = ({
  2120. TRANSFORM: TRANSFORM,
  2121. TRANSITION: TRANSITION,
  2122. TRANSITION_END: TRANSITION_END,
  2123. get: get,
  2124. getStyle: getStyle,
  2125. create: create$1,
  2126. remove: remove,
  2127. empty: empty,
  2128. toFront: toFront,
  2129. toBack: toBack,
  2130. hasClass: hasClass,
  2131. addClass: addClass,
  2132. removeClass: removeClass,
  2133. setClass: setClass,
  2134. getClass: getClass,
  2135. setOpacity: setOpacity,
  2136. testProp: testProp,
  2137. setTransform: setTransform,
  2138. setPosition: setPosition,
  2139. getPosition: getPosition,
  2140. disableTextSelection: disableTextSelection,
  2141. enableTextSelection: enableTextSelection,
  2142. disableImageDrag: disableImageDrag,
  2143. enableImageDrag: enableImageDrag,
  2144. preventOutline: preventOutline,
  2145. restoreOutline: restoreOutline,
  2146. getSizedParentNode: getSizedParentNode,
  2147. getScale: getScale
  2148. });
  2149. /*
  2150. * @namespace DomEvent
  2151. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  2152. */
  2153. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  2154. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2155. // Adds a listener function (`fn`) to a particular DOM event type of the
  2156. // element `el`. You can optionally specify the context of the listener
  2157. // (object the `this` keyword will point to). You can also pass several
  2158. // space-separated types (e.g. `'click dblclick'`).
  2159. // @alternative
  2160. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  2161. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2162. function on(obj, types, fn, context) {
  2163. if (typeof types === 'object') {
  2164. for (var type in types) {
  2165. addOne(obj, type, types[type], fn);
  2166. }
  2167. } else {
  2168. types = splitWords(types);
  2169. for (var i = 0, len = types.length; i < len; i++) {
  2170. addOne(obj, types[i], fn, context);
  2171. }
  2172. }
  2173. return this;
  2174. }
  2175. var eventsKey = '_leaflet_events';
  2176. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2177. // Removes a previously added listener function.
  2178. // Note that if you passed a custom context to on, you must pass the same
  2179. // context to `off` in order to remove the listener.
  2180. // @alternative
  2181. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  2182. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2183. function off(obj, types, fn, context) {
  2184. if (typeof types === 'object') {
  2185. for (var type in types) {
  2186. removeOne(obj, type, types[type], fn);
  2187. }
  2188. } else if (types) {
  2189. types = splitWords(types);
  2190. for (var i = 0, len = types.length; i < len; i++) {
  2191. removeOne(obj, types[i], fn, context);
  2192. }
  2193. } else {
  2194. for (var j in obj[eventsKey]) {
  2195. removeOne(obj, j, obj[eventsKey][j]);
  2196. }
  2197. delete obj[eventsKey];
  2198. }
  2199. return this;
  2200. }
  2201. function browserFiresNativeDblClick() {
  2202. // See https://github.com/w3c/pointerevents/issues/171
  2203. if (pointer) {
  2204. return !(edge || safari);
  2205. }
  2206. }
  2207. var mouseSubst = {
  2208. mouseenter: 'mouseover',
  2209. mouseleave: 'mouseout',
  2210. wheel: !('onwheel' in window) && 'mousewheel'
  2211. };
  2212. function addOne(obj, type, fn, context) {
  2213. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2214. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  2215. var handler = function (e) {
  2216. return fn.call(context || obj, e || window.event);
  2217. };
  2218. var originalHandler = handler;
  2219. if (pointer && type.indexOf('touch') === 0) {
  2220. // Needs DomEvent.Pointer.js
  2221. addPointerListener(obj, type, handler, id);
  2222. } else if (touch && (type === 'dblclick') && !browserFiresNativeDblClick()) {
  2223. addDoubleTapListener(obj, handler, id);
  2224. } else if ('addEventListener' in obj) {
  2225. if (type === 'touchstart' || type === 'touchmove' || type === 'wheel' || type === 'mousewheel') {
  2226. obj.addEventListener(mouseSubst[type] || type, handler, passiveEvents ? {passive: false} : false);
  2227. } else if (type === 'mouseenter' || type === 'mouseleave') {
  2228. handler = function (e) {
  2229. e = e || window.event;
  2230. if (isExternalTarget(obj, e)) {
  2231. originalHandler(e);
  2232. }
  2233. };
  2234. obj.addEventListener(mouseSubst[type], handler, false);
  2235. } else {
  2236. obj.addEventListener(type, originalHandler, false);
  2237. }
  2238. } else if ('attachEvent' in obj) {
  2239. obj.attachEvent('on' + type, handler);
  2240. }
  2241. obj[eventsKey] = obj[eventsKey] || {};
  2242. obj[eventsKey][id] = handler;
  2243. }
  2244. function removeOne(obj, type, fn, context) {
  2245. var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),
  2246. handler = obj[eventsKey] && obj[eventsKey][id];
  2247. if (!handler) { return this; }
  2248. if (pointer && type.indexOf('touch') === 0) {
  2249. removePointerListener(obj, type, id);
  2250. } else if (touch && (type === 'dblclick') && !browserFiresNativeDblClick()) {
  2251. removeDoubleTapListener(obj, id);
  2252. } else if ('removeEventListener' in obj) {
  2253. obj.removeEventListener(mouseSubst[type] || type, handler, false);
  2254. } else if ('detachEvent' in obj) {
  2255. obj.detachEvent('on' + type, handler);
  2256. }
  2257. obj[eventsKey][id] = null;
  2258. }
  2259. // @function stopPropagation(ev: DOMEvent): this
  2260. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  2261. // ```js
  2262. // L.DomEvent.on(div, 'click', function (ev) {
  2263. // L.DomEvent.stopPropagation(ev);
  2264. // });
  2265. // ```
  2266. function stopPropagation(e) {
  2267. if (e.stopPropagation) {
  2268. e.stopPropagation();
  2269. } else if (e.originalEvent) { // In case of Leaflet event.
  2270. e.originalEvent._stopped = true;
  2271. } else {
  2272. e.cancelBubble = true;
  2273. }
  2274. skipped(e);
  2275. return this;
  2276. }
  2277. // @function disableScrollPropagation(el: HTMLElement): this
  2278. // Adds `stopPropagation` to the element's `'wheel'` events (plus browser variants).
  2279. function disableScrollPropagation(el) {
  2280. addOne(el, 'wheel', stopPropagation);
  2281. return this;
  2282. }
  2283. // @function disableClickPropagation(el: HTMLElement): this
  2284. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  2285. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  2286. function disableClickPropagation(el) {
  2287. on(el, 'mousedown touchstart dblclick', stopPropagation);
  2288. addOne(el, 'click', fakeStop);
  2289. return this;
  2290. }
  2291. // @function preventDefault(ev: DOMEvent): this
  2292. // Prevents the default action of the DOM Event `ev` from happening (such as
  2293. // following a link in the href of the a element, or doing a POST request
  2294. // with page reload when a `<form>` is submitted).
  2295. // Use it inside listener functions.
  2296. function preventDefault(e) {
  2297. if (e.preventDefault) {
  2298. e.preventDefault();
  2299. } else {
  2300. e.returnValue = false;
  2301. }
  2302. return this;
  2303. }
  2304. // @function stop(ev: DOMEvent): this
  2305. // Does `stopPropagation` and `preventDefault` at the same time.
  2306. function stop(e) {
  2307. preventDefault(e);
  2308. stopPropagation(e);
  2309. return this;
  2310. }
  2311. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  2312. // Gets normalized mouse position from a DOM event relative to the
  2313. // `container` (border excluded) or to the whole page if not specified.
  2314. function getMousePosition(e, container) {
  2315. if (!container) {
  2316. return new Point(e.clientX, e.clientY);
  2317. }
  2318. var scale = getScale(container),
  2319. offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)
  2320. return new Point(
  2321. // offset.left/top values are in page scale (like clientX/Y),
  2322. // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
  2323. (e.clientX - offset.left) / scale.x - container.clientLeft,
  2324. (e.clientY - offset.top) / scale.y - container.clientTop
  2325. );
  2326. }
  2327. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  2328. // and Firefox scrolls device pixels, not CSS pixels
  2329. var wheelPxFactor =
  2330. (win && chrome) ? 2 * window.devicePixelRatio :
  2331. gecko ? window.devicePixelRatio : 1;
  2332. // @function getWheelDelta(ev: DOMEvent): Number
  2333. // Gets normalized wheel delta from a wheel DOM event, in vertical
  2334. // pixels scrolled (negative if scrolling down).
  2335. // Events from pointing devices without precise scrolling are mapped to
  2336. // a best guess of 60 pixels.
  2337. function getWheelDelta(e) {
  2338. return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2339. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2340. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2341. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2342. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2343. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2344. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2345. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2346. 0;
  2347. }
  2348. var skipEvents = {};
  2349. function fakeStop(e) {
  2350. // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)
  2351. skipEvents[e.type] = true;
  2352. }
  2353. function skipped(e) {
  2354. var events = skipEvents[e.type];
  2355. // reset when checking, as it's only used in map container and propagates outside of the map
  2356. skipEvents[e.type] = false;
  2357. return events;
  2358. }
  2359. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2360. function isExternalTarget(el, e) {
  2361. var related = e.relatedTarget;
  2362. if (!related) { return true; }
  2363. try {
  2364. while (related && (related !== el)) {
  2365. related = related.parentNode;
  2366. }
  2367. } catch (err) {
  2368. return false;
  2369. }
  2370. return (related !== el);
  2371. }
  2372. var DomEvent = ({
  2373. on: on,
  2374. off: off,
  2375. stopPropagation: stopPropagation,
  2376. disableScrollPropagation: disableScrollPropagation,
  2377. disableClickPropagation: disableClickPropagation,
  2378. preventDefault: preventDefault,
  2379. stop: stop,
  2380. getMousePosition: getMousePosition,
  2381. getWheelDelta: getWheelDelta,
  2382. fakeStop: fakeStop,
  2383. skipped: skipped,
  2384. isExternalTarget: isExternalTarget,
  2385. addListener: on,
  2386. removeListener: off
  2387. });
  2388. /*
  2389. * @class PosAnimation
  2390. * @aka L.PosAnimation
  2391. * @inherits Evented
  2392. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2393. *
  2394. * @example
  2395. * ```js
  2396. * var fx = new L.PosAnimation();
  2397. * fx.run(el, [300, 500], 0.5);
  2398. * ```
  2399. *
  2400. * @constructor L.PosAnimation()
  2401. * Creates a `PosAnimation` object.
  2402. *
  2403. */
  2404. var PosAnimation = Evented.extend({
  2405. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2406. // Run an animation of a given element to a new position, optionally setting
  2407. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2408. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  2409. // `0.5` by default).
  2410. run: function (el, newPos, duration, easeLinearity) {
  2411. this.stop();
  2412. this._el = el;
  2413. this._inProgress = true;
  2414. this._duration = duration || 0.25;
  2415. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2416. this._startPos = getPosition(el);
  2417. this._offset = newPos.subtract(this._startPos);
  2418. this._startTime = +new Date();
  2419. // @event start: Event
  2420. // Fired when the animation starts
  2421. this.fire('start');
  2422. this._animate();
  2423. },
  2424. // @method stop()
  2425. // Stops the animation (if currently running).
  2426. stop: function () {
  2427. if (!this._inProgress) { return; }
  2428. this._step(true);
  2429. this._complete();
  2430. },
  2431. _animate: function () {
  2432. // animation loop
  2433. this._animId = requestAnimFrame(this._animate, this);
  2434. this._step();
  2435. },
  2436. _step: function (round) {
  2437. var elapsed = (+new Date()) - this._startTime,
  2438. duration = this._duration * 1000;
  2439. if (elapsed < duration) {
  2440. this._runFrame(this._easeOut(elapsed / duration), round);
  2441. } else {
  2442. this._runFrame(1);
  2443. this._complete();
  2444. }
  2445. },
  2446. _runFrame: function (progress, round) {
  2447. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2448. if (round) {
  2449. pos._round();
  2450. }
  2451. setPosition(this._el, pos);
  2452. // @event step: Event
  2453. // Fired continuously during the animation.
  2454. this.fire('step');
  2455. },
  2456. _complete: function () {
  2457. cancelAnimFrame(this._animId);
  2458. this._inProgress = false;
  2459. // @event end: Event
  2460. // Fired when the animation ends.
  2461. this.fire('end');
  2462. },
  2463. _easeOut: function (t) {
  2464. return 1 - Math.pow(1 - t, this._easeOutPower);
  2465. }
  2466. });
  2467. /*
  2468. * @class Map
  2469. * @aka L.Map
  2470. * @inherits Evented
  2471. *
  2472. * The central class of the API — it is used to create a map on a page and manipulate it.
  2473. *
  2474. * @example
  2475. *
  2476. * ```js
  2477. * // initialize the map on the "map" div with a given center and zoom
  2478. * var map = L.map('map', {
  2479. * center: [51.505, -0.09],
  2480. * zoom: 13
  2481. * });
  2482. * ```
  2483. *
  2484. */
  2485. var Map = Evented.extend({
  2486. options: {
  2487. // @section Map State Options
  2488. // @option crs: CRS = L.CRS.EPSG3857
  2489. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2490. // sure what it means.
  2491. crs: EPSG3857,
  2492. // @option center: LatLng = undefined
  2493. // Initial geographic center of the map
  2494. center: undefined,
  2495. // @option zoom: Number = undefined
  2496. // Initial map zoom level
  2497. zoom: undefined,
  2498. // @option minZoom: Number = *
  2499. // Minimum zoom level of the map.
  2500. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2501. // the lowest of their `minZoom` options will be used instead.
  2502. minZoom: undefined,
  2503. // @option maxZoom: Number = *
  2504. // Maximum zoom level of the map.
  2505. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2506. // the highest of their `maxZoom` options will be used instead.
  2507. maxZoom: undefined,
  2508. // @option layers: Layer[] = []
  2509. // Array of layers that will be added to the map initially
  2510. layers: [],
  2511. // @option maxBounds: LatLngBounds = null
  2512. // When this option is set, the map restricts the view to the given
  2513. // geographical bounds, bouncing the user back if the user tries to pan
  2514. // outside the view. To set the restriction dynamically, use
  2515. // [`setMaxBounds`](#map-setmaxbounds) method.
  2516. maxBounds: undefined,
  2517. // @option renderer: Renderer = *
  2518. // The default method for drawing vector layers on the map. `L.SVG`
  2519. // or `L.Canvas` by default depending on browser support.
  2520. renderer: undefined,
  2521. // @section Animation Options
  2522. // @option zoomAnimation: Boolean = true
  2523. // Whether the map zoom animation is enabled. By default it's enabled
  2524. // in all browsers that support CSS3 Transitions except Android.
  2525. zoomAnimation: true,
  2526. // @option zoomAnimationThreshold: Number = 4
  2527. // Won't animate zoom if the zoom difference exceeds this value.
  2528. zoomAnimationThreshold: 4,
  2529. // @option fadeAnimation: Boolean = true
  2530. // Whether the tile fade animation is enabled. By default it's enabled
  2531. // in all browsers that support CSS3 Transitions except Android.
  2532. fadeAnimation: true,
  2533. // @option markerZoomAnimation: Boolean = true
  2534. // Whether markers animate their zoom with the zoom animation, if disabled
  2535. // they will disappear for the length of the animation. By default it's
  2536. // enabled in all browsers that support CSS3 Transitions except Android.
  2537. markerZoomAnimation: true,
  2538. // @option transform3DLimit: Number = 2^23
  2539. // Defines the maximum size of a CSS translation transform. The default
  2540. // value should not be changed unless a web browser positions layers in
  2541. // the wrong place after doing a large `panBy`.
  2542. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2543. // @section Interaction Options
  2544. // @option zoomSnap: Number = 1
  2545. // Forces the map's zoom level to always be a multiple of this, particularly
  2546. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2547. // By default, the zoom level snaps to the nearest integer; lower values
  2548. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2549. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2550. zoomSnap: 1,
  2551. // @option zoomDelta: Number = 1
  2552. // Controls how much the map's zoom level will change after a
  2553. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2554. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2555. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2556. zoomDelta: 1,
  2557. // @option trackResize: Boolean = true
  2558. // Whether the map automatically handles browser window resize to update itself.
  2559. trackResize: true
  2560. },
  2561. initialize: function (id, options) { // (HTMLElement or String, Object)
  2562. options = setOptions(this, options);
  2563. // Make sure to assign internal flags at the beginning,
  2564. // to avoid inconsistent state in some edge cases.
  2565. this._handlers = [];
  2566. this._layers = {};
  2567. this._zoomBoundLayers = {};
  2568. this._sizeChanged = true;
  2569. this._initContainer(id);
  2570. this._initLayout();
  2571. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2572. this._onResize = bind(this._onResize, this);
  2573. this._initEvents();
  2574. if (options.maxBounds) {
  2575. this.setMaxBounds(options.maxBounds);
  2576. }
  2577. if (options.zoom !== undefined) {
  2578. this._zoom = this._limitZoom(options.zoom);
  2579. }
  2580. if (options.center && options.zoom !== undefined) {
  2581. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2582. }
  2583. this.callInitHooks();
  2584. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2585. this._zoomAnimated = TRANSITION && any3d && !mobileOpera &&
  2586. this.options.zoomAnimation;
  2587. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2588. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2589. if (this._zoomAnimated) {
  2590. this._createAnimProxy();
  2591. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2592. }
  2593. this._addLayers(this.options.layers);
  2594. },
  2595. // @section Methods for modifying map state
  2596. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2597. // Sets the view of the map (geographical center and zoom) with the given
  2598. // animation options.
  2599. setView: function (center, zoom, options) {
  2600. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2601. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2602. options = options || {};
  2603. this._stop();
  2604. if (this._loaded && !options.reset && options !== true) {
  2605. if (options.animate !== undefined) {
  2606. options.zoom = extend({animate: options.animate}, options.zoom);
  2607. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2608. }
  2609. // try animating pan or zoom
  2610. var moved = (this._zoom !== zoom) ?
  2611. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2612. this._tryAnimatedPan(center, options.pan);
  2613. if (moved) {
  2614. // prevent resize handler call, the view will refresh after animation anyway
  2615. clearTimeout(this._sizeTimer);
  2616. return this;
  2617. }
  2618. }
  2619. // animation didn't start, just reset the map view
  2620. this._resetView(center, zoom);
  2621. return this;
  2622. },
  2623. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2624. // Sets the zoom of the map.
  2625. setZoom: function (zoom, options) {
  2626. if (!this._loaded) {
  2627. this._zoom = zoom;
  2628. return this;
  2629. }
  2630. return this.setView(this.getCenter(), zoom, {zoom: options});
  2631. },
  2632. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2633. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2634. zoomIn: function (delta, options) {
  2635. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2636. return this.setZoom(this._zoom + delta, options);
  2637. },
  2638. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2639. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2640. zoomOut: function (delta, options) {
  2641. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2642. return this.setZoom(this._zoom - delta, options);
  2643. },
  2644. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2645. // Zooms the map while keeping a specified geographical point on the map
  2646. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2647. // @alternative
  2648. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2649. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2650. setZoomAround: function (latlng, zoom, options) {
  2651. var scale = this.getZoomScale(zoom),
  2652. viewHalf = this.getSize().divideBy(2),
  2653. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2654. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2655. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2656. return this.setView(newCenter, zoom, {zoom: options});
  2657. },
  2658. _getBoundsCenterZoom: function (bounds, options) {
  2659. options = options || {};
  2660. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2661. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2662. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2663. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2664. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2665. if (zoom === Infinity) {
  2666. return {
  2667. center: bounds.getCenter(),
  2668. zoom: zoom
  2669. };
  2670. }
  2671. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2672. swPoint = this.project(bounds.getSouthWest(), zoom),
  2673. nePoint = this.project(bounds.getNorthEast(), zoom),
  2674. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2675. return {
  2676. center: center,
  2677. zoom: zoom
  2678. };
  2679. },
  2680. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2681. // Sets a map view that contains the given geographical bounds with the
  2682. // maximum zoom level possible.
  2683. fitBounds: function (bounds, options) {
  2684. bounds = toLatLngBounds(bounds);
  2685. if (!bounds.isValid()) {
  2686. throw new Error('Bounds are not valid.');
  2687. }
  2688. var target = this._getBoundsCenterZoom(bounds, options);
  2689. return this.setView(target.center, target.zoom, options);
  2690. },
  2691. // @method fitWorld(options?: fitBounds options): this
  2692. // Sets a map view that mostly contains the whole world with the maximum
  2693. // zoom level possible.
  2694. fitWorld: function (options) {
  2695. return this.fitBounds([[-90, -180], [90, 180]], options);
  2696. },
  2697. // @method panTo(latlng: LatLng, options?: Pan options): this
  2698. // Pans the map to a given center.
  2699. panTo: function (center, options) { // (LatLng)
  2700. return this.setView(center, this._zoom, {pan: options});
  2701. },
  2702. // @method panBy(offset: Point, options?: Pan options): this
  2703. // Pans the map by a given number of pixels (animated).
  2704. panBy: function (offset, options) {
  2705. offset = toPoint(offset).round();
  2706. options = options || {};
  2707. if (!offset.x && !offset.y) {
  2708. return this.fire('moveend');
  2709. }
  2710. // If we pan too far, Chrome gets issues with tiles
  2711. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2712. if (options.animate !== true && !this.getSize().contains(offset)) {
  2713. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2714. return this;
  2715. }
  2716. if (!this._panAnim) {
  2717. this._panAnim = new PosAnimation();
  2718. this._panAnim.on({
  2719. 'step': this._onPanTransitionStep,
  2720. 'end': this._onPanTransitionEnd
  2721. }, this);
  2722. }
  2723. // don't fire movestart if animating inertia
  2724. if (!options.noMoveStart) {
  2725. this.fire('movestart');
  2726. }
  2727. // animate pan unless animate: false specified
  2728. if (options.animate !== false) {
  2729. addClass(this._mapPane, 'leaflet-pan-anim');
  2730. var newPos = this._getMapPanePos().subtract(offset).round();
  2731. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2732. } else {
  2733. this._rawPanBy(offset);
  2734. this.fire('move').fire('moveend');
  2735. }
  2736. return this;
  2737. },
  2738. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2739. // Sets the view of the map (geographical center and zoom) performing a smooth
  2740. // pan-zoom animation.
  2741. flyTo: function (targetCenter, targetZoom, options) {
  2742. options = options || {};
  2743. if (options.animate === false || !any3d) {
  2744. return this.setView(targetCenter, targetZoom, options);
  2745. }
  2746. this._stop();
  2747. var from = this.project(this.getCenter()),
  2748. to = this.project(targetCenter),
  2749. size = this.getSize(),
  2750. startZoom = this._zoom;
  2751. targetCenter = toLatLng(targetCenter);
  2752. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2753. var w0 = Math.max(size.x, size.y),
  2754. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2755. u1 = (to.distanceTo(from)) || 1,
  2756. rho = 1.42,
  2757. rho2 = rho * rho;
  2758. function r(i) {
  2759. var s1 = i ? -1 : 1,
  2760. s2 = i ? w1 : w0,
  2761. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2762. b1 = 2 * s2 * rho2 * u1,
  2763. b = t1 / b1,
  2764. sq = Math.sqrt(b * b + 1) - b;
  2765. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2766. // thus triggering an infinite loop in flyTo
  2767. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2768. return log;
  2769. }
  2770. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2771. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2772. function tanh(n) { return sinh(n) / cosh(n); }
  2773. var r0 = r(0);
  2774. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2775. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2776. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2777. var start = Date.now(),
  2778. S = (r(1) - r0) / rho,
  2779. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2780. function frame() {
  2781. var t = (Date.now() - start) / duration,
  2782. s = easeOut(t) * S;
  2783. if (t <= 1) {
  2784. this._flyToFrame = requestAnimFrame(frame, this);
  2785. this._move(
  2786. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2787. this.getScaleZoom(w0 / w(s), startZoom),
  2788. {flyTo: true});
  2789. } else {
  2790. this
  2791. ._move(targetCenter, targetZoom)
  2792. ._moveEnd(true);
  2793. }
  2794. }
  2795. this._moveStart(true, options.noMoveStart);
  2796. frame.call(this);
  2797. return this;
  2798. },
  2799. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2800. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2801. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2802. flyToBounds: function (bounds, options) {
  2803. var target = this._getBoundsCenterZoom(bounds, options);
  2804. return this.flyTo(target.center, target.zoom, options);
  2805. },
  2806. // @method setMaxBounds(bounds: LatLngBounds): this
  2807. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2808. setMaxBounds: function (bounds) {
  2809. bounds = toLatLngBounds(bounds);
  2810. if (!bounds.isValid()) {
  2811. this.options.maxBounds = null;
  2812. return this.off('moveend', this._panInsideMaxBounds);
  2813. } else if (this.options.maxBounds) {
  2814. this.off('moveend', this._panInsideMaxBounds);
  2815. }
  2816. this.options.maxBounds = bounds;
  2817. if (this._loaded) {
  2818. this._panInsideMaxBounds();
  2819. }
  2820. return this.on('moveend', this._panInsideMaxBounds);
  2821. },
  2822. // @method setMinZoom(zoom: Number): this
  2823. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2824. setMinZoom: function (zoom) {
  2825. var oldZoom = this.options.minZoom;
  2826. this.options.minZoom = zoom;
  2827. if (this._loaded && oldZoom !== zoom) {
  2828. this.fire('zoomlevelschange');
  2829. if (this.getZoom() < this.options.minZoom) {
  2830. return this.setZoom(zoom);
  2831. }
  2832. }
  2833. return this;
  2834. },
  2835. // @method setMaxZoom(zoom: Number): this
  2836. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2837. setMaxZoom: function (zoom) {
  2838. var oldZoom = this.options.maxZoom;
  2839. this.options.maxZoom = zoom;
  2840. if (this._loaded && oldZoom !== zoom) {
  2841. this.fire('zoomlevelschange');
  2842. if (this.getZoom() > this.options.maxZoom) {
  2843. return this.setZoom(zoom);
  2844. }
  2845. }
  2846. return this;
  2847. },
  2848. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2849. // 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.
  2850. panInsideBounds: function (bounds, options) {
  2851. this._enforcingBounds = true;
  2852. var center = this.getCenter(),
  2853. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2854. if (!center.equals(newCenter)) {
  2855. this.panTo(newCenter, options);
  2856. }
  2857. this._enforcingBounds = false;
  2858. return this;
  2859. },
  2860. // @method panInside(latlng: LatLng, options?: options): this
  2861. // Pans the map the minimum amount to make the `latlng` visible. Use
  2862. // `padding`, `paddingTopLeft` and `paddingTopRight` options to fit
  2863. // the display to more restricted bounds, like [`fitBounds`](#map-fitbounds).
  2864. // If `latlng` is already within the (optionally padded) display bounds,
  2865. // the map will not be panned.
  2866. panInside: function (latlng, options) {
  2867. options = options || {};
  2868. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2869. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2870. center = this.getCenter(),
  2871. pixelCenter = this.project(center),
  2872. pixelPoint = this.project(latlng),
  2873. pixelBounds = this.getPixelBounds(),
  2874. halfPixelBounds = pixelBounds.getSize().divideBy(2),
  2875. paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]);
  2876. if (!paddedBounds.contains(pixelPoint)) {
  2877. this._enforcingBounds = true;
  2878. var diff = pixelCenter.subtract(pixelPoint),
  2879. newCenter = toPoint(pixelPoint.x + diff.x, pixelPoint.y + diff.y);
  2880. if (pixelPoint.x < paddedBounds.min.x || pixelPoint.x > paddedBounds.max.x) {
  2881. newCenter.x = pixelCenter.x - diff.x;
  2882. if (diff.x > 0) {
  2883. newCenter.x += halfPixelBounds.x - paddingTL.x;
  2884. } else {
  2885. newCenter.x -= halfPixelBounds.x - paddingBR.x;
  2886. }
  2887. }
  2888. if (pixelPoint.y < paddedBounds.min.y || pixelPoint.y > paddedBounds.max.y) {
  2889. newCenter.y = pixelCenter.y - diff.y;
  2890. if (diff.y > 0) {
  2891. newCenter.y += halfPixelBounds.y - paddingTL.y;
  2892. } else {
  2893. newCenter.y -= halfPixelBounds.y - paddingBR.y;
  2894. }
  2895. }
  2896. this.panTo(this.unproject(newCenter), options);
  2897. this._enforcingBounds = false;
  2898. }
  2899. return this;
  2900. },
  2901. // @method invalidateSize(options: Zoom/pan options): this
  2902. // Checks if the map container size changed and updates the map if so —
  2903. // call it after you've changed the map size dynamically, also animating
  2904. // pan by default. If `options.pan` is `false`, panning will not occur.
  2905. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2906. // that it doesn't happen often even if the method is called many
  2907. // times in a row.
  2908. // @alternative
  2909. // @method invalidateSize(animate: Boolean): this
  2910. // Checks if the map container size changed and updates the map if so —
  2911. // call it after you've changed the map size dynamically, also animating
  2912. // pan by default.
  2913. invalidateSize: function (options) {
  2914. if (!this._loaded) { return this; }
  2915. options = extend({
  2916. animate: false,
  2917. pan: true
  2918. }, options === true ? {animate: true} : options);
  2919. var oldSize = this.getSize();
  2920. this._sizeChanged = true;
  2921. this._lastCenter = null;
  2922. var newSize = this.getSize(),
  2923. oldCenter = oldSize.divideBy(2).round(),
  2924. newCenter = newSize.divideBy(2).round(),
  2925. offset = oldCenter.subtract(newCenter);
  2926. if (!offset.x && !offset.y) { return this; }
  2927. if (options.animate && options.pan) {
  2928. this.panBy(offset);
  2929. } else {
  2930. if (options.pan) {
  2931. this._rawPanBy(offset);
  2932. }
  2933. this.fire('move');
  2934. if (options.debounceMoveend) {
  2935. clearTimeout(this._sizeTimer);
  2936. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  2937. } else {
  2938. this.fire('moveend');
  2939. }
  2940. }
  2941. // @section Map state change events
  2942. // @event resize: ResizeEvent
  2943. // Fired when the map is resized.
  2944. return this.fire('resize', {
  2945. oldSize: oldSize,
  2946. newSize: newSize
  2947. });
  2948. },
  2949. // @section Methods for modifying map state
  2950. // @method stop(): this
  2951. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2952. stop: function () {
  2953. this.setZoom(this._limitZoom(this._zoom));
  2954. if (!this.options.zoomSnap) {
  2955. this.fire('viewreset');
  2956. }
  2957. return this._stop();
  2958. },
  2959. // @section Geolocation methods
  2960. // @method locate(options?: Locate options): this
  2961. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  2962. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  2963. // and optionally sets the map view to the user's location with respect to
  2964. // detection accuracy (or to the world view if geolocation failed).
  2965. // Note that, if your page doesn't use HTTPS, this method will fail in
  2966. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  2967. // See `Locate options` for more details.
  2968. locate: function (options) {
  2969. options = this._locateOptions = extend({
  2970. timeout: 10000,
  2971. watch: false
  2972. // setView: false
  2973. // maxZoom: <Number>
  2974. // maximumAge: 0
  2975. // enableHighAccuracy: false
  2976. }, options);
  2977. if (!('geolocation' in navigator)) {
  2978. this._handleGeolocationError({
  2979. code: 0,
  2980. message: 'Geolocation not supported.'
  2981. });
  2982. return this;
  2983. }
  2984. var onResponse = bind(this._handleGeolocationResponse, this),
  2985. onError = bind(this._handleGeolocationError, this);
  2986. if (options.watch) {
  2987. this._locationWatchId =
  2988. navigator.geolocation.watchPosition(onResponse, onError, options);
  2989. } else {
  2990. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  2991. }
  2992. return this;
  2993. },
  2994. // @method stopLocate(): this
  2995. // Stops watching location previously initiated by `map.locate({watch: true})`
  2996. // and aborts resetting the map view if map.locate was called with
  2997. // `{setView: true}`.
  2998. stopLocate: function () {
  2999. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  3000. navigator.geolocation.clearWatch(this._locationWatchId);
  3001. }
  3002. if (this._locateOptions) {
  3003. this._locateOptions.setView = false;
  3004. }
  3005. return this;
  3006. },
  3007. _handleGeolocationError: function (error) {
  3008. var c = error.code,
  3009. message = error.message ||
  3010. (c === 1 ? 'permission denied' :
  3011. (c === 2 ? 'position unavailable' : 'timeout'));
  3012. if (this._locateOptions.setView && !this._loaded) {
  3013. this.fitWorld();
  3014. }
  3015. // @section Location events
  3016. // @event locationerror: ErrorEvent
  3017. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  3018. this.fire('locationerror', {
  3019. code: c,
  3020. message: 'Geolocation error: ' + message + '.'
  3021. });
  3022. },
  3023. _handleGeolocationResponse: function (pos) {
  3024. var lat = pos.coords.latitude,
  3025. lng = pos.coords.longitude,
  3026. latlng = new LatLng(lat, lng),
  3027. bounds = latlng.toBounds(pos.coords.accuracy * 2),
  3028. options = this._locateOptions;
  3029. if (options.setView) {
  3030. var zoom = this.getBoundsZoom(bounds);
  3031. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  3032. }
  3033. var data = {
  3034. latlng: latlng,
  3035. bounds: bounds,
  3036. timestamp: pos.timestamp
  3037. };
  3038. for (var i in pos.coords) {
  3039. if (typeof pos.coords[i] === 'number') {
  3040. data[i] = pos.coords[i];
  3041. }
  3042. }
  3043. // @event locationfound: LocationEvent
  3044. // Fired when geolocation (using the [`locate`](#map-locate) method)
  3045. // went successfully.
  3046. this.fire('locationfound', data);
  3047. },
  3048. // TODO Appropriate docs section?
  3049. // @section Other Methods
  3050. // @method addHandler(name: String, HandlerClass: Function): this
  3051. // Adds a new `Handler` to the map, given its name and constructor function.
  3052. addHandler: function (name, HandlerClass) {
  3053. if (!HandlerClass) { return this; }
  3054. var handler = this[name] = new HandlerClass(this);
  3055. this._handlers.push(handler);
  3056. if (this.options[name]) {
  3057. handler.enable();
  3058. }
  3059. return this;
  3060. },
  3061. // @method remove(): this
  3062. // Destroys the map and clears all related event listeners.
  3063. remove: function () {
  3064. this._initEvents(true);
  3065. this.off('moveend', this._panInsideMaxBounds);
  3066. if (this._containerId !== this._container._leaflet_id) {
  3067. throw new Error('Map container is being reused by another instance');
  3068. }
  3069. try {
  3070. // throws error in IE6-8
  3071. delete this._container._leaflet_id;
  3072. delete this._containerId;
  3073. } catch (e) {
  3074. /*eslint-disable */
  3075. this._container._leaflet_id = undefined;
  3076. /* eslint-enable */
  3077. this._containerId = undefined;
  3078. }
  3079. if (this._locationWatchId !== undefined) {
  3080. this.stopLocate();
  3081. }
  3082. this._stop();
  3083. remove(this._mapPane);
  3084. if (this._clearControlPos) {
  3085. this._clearControlPos();
  3086. }
  3087. if (this._resizeRequest) {
  3088. cancelAnimFrame(this._resizeRequest);
  3089. this._resizeRequest = null;
  3090. }
  3091. this._clearHandlers();
  3092. if (this._loaded) {
  3093. // @section Map state change events
  3094. // @event unload: Event
  3095. // Fired when the map is destroyed with [remove](#map-remove) method.
  3096. this.fire('unload');
  3097. }
  3098. var i;
  3099. for (i in this._layers) {
  3100. this._layers[i].remove();
  3101. }
  3102. for (i in this._panes) {
  3103. remove(this._panes[i]);
  3104. }
  3105. this._layers = [];
  3106. this._panes = [];
  3107. delete this._mapPane;
  3108. delete this._renderer;
  3109. return this;
  3110. },
  3111. // @section Other Methods
  3112. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3113. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3114. // then returns it. The pane is created as a child of `container`, or
  3115. // as a child of the main map pane if not set.
  3116. createPane: function (name, container) {
  3117. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3118. pane = create$1('div', className, container || this._mapPane);
  3119. if (name) {
  3120. this._panes[name] = pane;
  3121. }
  3122. return pane;
  3123. },
  3124. // @section Methods for Getting Map State
  3125. // @method getCenter(): LatLng
  3126. // Returns the geographical center of the map view
  3127. getCenter: function () {
  3128. this._checkIfLoaded();
  3129. if (this._lastCenter && !this._moved()) {
  3130. return this._lastCenter;
  3131. }
  3132. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3133. },
  3134. // @method getZoom(): Number
  3135. // Returns the current zoom level of the map view
  3136. getZoom: function () {
  3137. return this._zoom;
  3138. },
  3139. // @method getBounds(): LatLngBounds
  3140. // Returns the geographical bounds visible in the current map view
  3141. getBounds: function () {
  3142. var bounds = this.getPixelBounds(),
  3143. sw = this.unproject(bounds.getBottomLeft()),
  3144. ne = this.unproject(bounds.getTopRight());
  3145. return new LatLngBounds(sw, ne);
  3146. },
  3147. // @method getMinZoom(): Number
  3148. // 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.
  3149. getMinZoom: function () {
  3150. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3151. },
  3152. // @method getMaxZoom(): Number
  3153. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3154. getMaxZoom: function () {
  3155. return this.options.maxZoom === undefined ?
  3156. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3157. this.options.maxZoom;
  3158. },
  3159. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
  3160. // Returns the maximum zoom level on which the given bounds fit to the map
  3161. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3162. // instead returns the minimum zoom level on which the map view fits into
  3163. // the given bounds in its entirety.
  3164. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3165. bounds = toLatLngBounds(bounds);
  3166. padding = toPoint(padding || [0, 0]);
  3167. var zoom = this.getZoom() || 0,
  3168. min = this.getMinZoom(),
  3169. max = this.getMaxZoom(),
  3170. nw = bounds.getNorthWest(),
  3171. se = bounds.getSouthEast(),
  3172. size = this.getSize().subtract(padding),
  3173. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3174. snap = any3d ? this.options.zoomSnap : 1,
  3175. scalex = size.x / boundsSize.x,
  3176. scaley = size.y / boundsSize.y,
  3177. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3178. zoom = this.getScaleZoom(scale, zoom);
  3179. if (snap) {
  3180. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3181. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3182. }
  3183. return Math.max(min, Math.min(max, zoom));
  3184. },
  3185. // @method getSize(): Point
  3186. // Returns the current size of the map container (in pixels).
  3187. getSize: function () {
  3188. if (!this._size || this._sizeChanged) {
  3189. this._size = new Point(
  3190. this._container.clientWidth || 0,
  3191. this._container.clientHeight || 0);
  3192. this._sizeChanged = false;
  3193. }
  3194. return this._size.clone();
  3195. },
  3196. // @method getPixelBounds(): Bounds
  3197. // Returns the bounds of the current map view in projected pixel
  3198. // coordinates (sometimes useful in layer and overlay implementations).
  3199. getPixelBounds: function (center, zoom) {
  3200. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3201. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3202. },
  3203. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3204. // the map pane? "left point of the map layer" can be confusing, specially
  3205. // since there can be negative offsets.
  3206. // @method getPixelOrigin(): Point
  3207. // Returns the projected pixel coordinates of the top left point of
  3208. // the map layer (useful in custom layer and overlay implementations).
  3209. getPixelOrigin: function () {
  3210. this._checkIfLoaded();
  3211. return this._pixelOrigin;
  3212. },
  3213. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3214. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3215. // If `zoom` is omitted, the map's current zoom level is used.
  3216. getPixelWorldBounds: function (zoom) {
  3217. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3218. },
  3219. // @section Other Methods
  3220. // @method getPane(pane: String|HTMLElement): HTMLElement
  3221. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3222. getPane: function (pane) {
  3223. return typeof pane === 'string' ? this._panes[pane] : pane;
  3224. },
  3225. // @method getPanes(): Object
  3226. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3227. // the panes as values.
  3228. getPanes: function () {
  3229. return this._panes;
  3230. },
  3231. // @method getContainer: HTMLElement
  3232. // Returns the HTML element that contains the map.
  3233. getContainer: function () {
  3234. return this._container;
  3235. },
  3236. // @section Conversion Methods
  3237. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3238. // Returns the scale factor to be applied to a map transition from zoom level
  3239. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3240. getZoomScale: function (toZoom, fromZoom) {
  3241. // TODO replace with universal implementation after refactoring projections
  3242. var crs = this.options.crs;
  3243. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3244. return crs.scale(toZoom) / crs.scale(fromZoom);
  3245. },
  3246. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3247. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3248. // level and everything is scaled by a factor of `scale`. Inverse of
  3249. // [`getZoomScale`](#map-getZoomScale).
  3250. getScaleZoom: function (scale, fromZoom) {
  3251. var crs = this.options.crs;
  3252. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3253. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3254. return isNaN(zoom) ? Infinity : zoom;
  3255. },
  3256. // @method project(latlng: LatLng, zoom: Number): Point
  3257. // Projects a geographical coordinate `LatLng` according to the projection
  3258. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3259. // `Transformation`. The result is pixel coordinate relative to
  3260. // the CRS origin.
  3261. project: function (latlng, zoom) {
  3262. zoom = zoom === undefined ? this._zoom : zoom;
  3263. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3264. },
  3265. // @method unproject(point: Point, zoom: Number): LatLng
  3266. // Inverse of [`project`](#map-project).
  3267. unproject: function (point, zoom) {
  3268. zoom = zoom === undefined ? this._zoom : zoom;
  3269. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3270. },
  3271. // @method layerPointToLatLng(point: Point): LatLng
  3272. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3273. // returns the corresponding geographical coordinate (for the current zoom level).
  3274. layerPointToLatLng: function (point) {
  3275. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3276. return this.unproject(projectedPoint);
  3277. },
  3278. // @method latLngToLayerPoint(latlng: LatLng): Point
  3279. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3280. // relative to the [origin pixel](#map-getpixelorigin).
  3281. latLngToLayerPoint: function (latlng) {
  3282. var projectedPoint = this.project(toLatLng(latlng))._round();
  3283. return projectedPoint._subtract(this.getPixelOrigin());
  3284. },
  3285. // @method wrapLatLng(latlng: LatLng): LatLng
  3286. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3287. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3288. // CRS's bounds.
  3289. // By default this means longitude is wrapped around the dateline so its
  3290. // value is between -180 and +180 degrees.
  3291. wrapLatLng: function (latlng) {
  3292. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3293. },
  3294. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3295. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3296. // its center is within the CRS's bounds.
  3297. // By default this means the center longitude is wrapped around the dateline so its
  3298. // value is between -180 and +180 degrees, and the majority of the bounds
  3299. // overlaps the CRS's bounds.
  3300. wrapLatLngBounds: function (latlng) {
  3301. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3302. },
  3303. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3304. // Returns the distance between two geographical coordinates according to
  3305. // the map's CRS. By default this measures distance in meters.
  3306. distance: function (latlng1, latlng2) {
  3307. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3308. },
  3309. // @method containerPointToLayerPoint(point: Point): Point
  3310. // Given a pixel coordinate relative to the map container, returns the corresponding
  3311. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3312. containerPointToLayerPoint: function (point) { // (Point)
  3313. return toPoint(point).subtract(this._getMapPanePos());
  3314. },
  3315. // @method layerPointToContainerPoint(point: Point): Point
  3316. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3317. // returns the corresponding pixel coordinate relative to the map container.
  3318. layerPointToContainerPoint: function (point) { // (Point)
  3319. return toPoint(point).add(this._getMapPanePos());
  3320. },
  3321. // @method containerPointToLatLng(point: Point): LatLng
  3322. // Given a pixel coordinate relative to the map container, returns
  3323. // the corresponding geographical coordinate (for the current zoom level).
  3324. containerPointToLatLng: function (point) {
  3325. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3326. return this.layerPointToLatLng(layerPoint);
  3327. },
  3328. // @method latLngToContainerPoint(latlng: LatLng): Point
  3329. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3330. // relative to the map container.
  3331. latLngToContainerPoint: function (latlng) {
  3332. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3333. },
  3334. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3335. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3336. // map container where the event took place.
  3337. mouseEventToContainerPoint: function (e) {
  3338. return getMousePosition(e, this._container);
  3339. },
  3340. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3341. // Given a MouseEvent object, returns the pixel coordinate relative to
  3342. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3343. mouseEventToLayerPoint: function (e) {
  3344. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3345. },
  3346. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3347. // Given a MouseEvent object, returns geographical coordinate where the
  3348. // event took place.
  3349. mouseEventToLatLng: function (e) { // (MouseEvent)
  3350. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3351. },
  3352. // map initialization methods
  3353. _initContainer: function (id) {
  3354. var container = this._container = get(id);
  3355. if (!container) {
  3356. throw new Error('Map container not found.');
  3357. } else if (container._leaflet_id) {
  3358. throw new Error('Map container is already initialized.');
  3359. }
  3360. on(container, 'scroll', this._onScroll, this);
  3361. this._containerId = stamp(container);
  3362. },
  3363. _initLayout: function () {
  3364. var container = this._container;
  3365. this._fadeAnimated = this.options.fadeAnimation && any3d;
  3366. addClass(container, 'leaflet-container' +
  3367. (touch ? ' leaflet-touch' : '') +
  3368. (retina ? ' leaflet-retina' : '') +
  3369. (ielt9 ? ' leaflet-oldie' : '') +
  3370. (safari ? ' leaflet-safari' : '') +
  3371. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3372. var position = getStyle(container, 'position');
  3373. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  3374. container.style.position = 'relative';
  3375. }
  3376. this._initPanes();
  3377. if (this._initControlPos) {
  3378. this._initControlPos();
  3379. }
  3380. },
  3381. _initPanes: function () {
  3382. var panes = this._panes = {};
  3383. this._paneRenderers = {};
  3384. // @section
  3385. //
  3386. // Panes are DOM elements used to control the ordering of layers on the map. You
  3387. // can access panes with [`map.getPane`](#map-getpane) or
  3388. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3389. // [`map.createPane`](#map-createpane) method.
  3390. //
  3391. // Every map has the following default panes that differ only in zIndex.
  3392. //
  3393. // @pane mapPane: HTMLElement = 'auto'
  3394. // Pane that contains all other map panes
  3395. this._mapPane = this.createPane('mapPane', this._container);
  3396. setPosition(this._mapPane, new Point(0, 0));
  3397. // @pane tilePane: HTMLElement = 200
  3398. // Pane for `GridLayer`s and `TileLayer`s
  3399. this.createPane('tilePane');
  3400. // @pane overlayPane: HTMLElement = 400
  3401. // Pane for overlay shadows (e.g. `Marker` shadows)
  3402. this.createPane('shadowPane');
  3403. // @pane shadowPane: HTMLElement = 500
  3404. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  3405. this.createPane('overlayPane');
  3406. // @pane markerPane: HTMLElement = 600
  3407. // Pane for `Icon`s of `Marker`s
  3408. this.createPane('markerPane');
  3409. // @pane tooltipPane: HTMLElement = 650
  3410. // Pane for `Tooltip`s.
  3411. this.createPane('tooltipPane');
  3412. // @pane popupPane: HTMLElement = 700
  3413. // Pane for `Popup`s.
  3414. this.createPane('popupPane');
  3415. if (!this.options.markerZoomAnimation) {
  3416. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3417. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3418. }
  3419. },
  3420. // private methods that modify map state
  3421. // @section Map state change events
  3422. _resetView: function (center, zoom) {
  3423. setPosition(this._mapPane, new Point(0, 0));
  3424. var loading = !this._loaded;
  3425. this._loaded = true;
  3426. zoom = this._limitZoom(zoom);
  3427. this.fire('viewprereset');
  3428. var zoomChanged = this._zoom !== zoom;
  3429. this
  3430. ._moveStart(zoomChanged, false)
  3431. ._move(center, zoom)
  3432. ._moveEnd(zoomChanged);
  3433. // @event viewreset: Event
  3434. // Fired when the map needs to redraw its content (this usually happens
  3435. // on map zoom or load). Very useful for creating custom overlays.
  3436. this.fire('viewreset');
  3437. // @event load: Event
  3438. // Fired when the map is initialized (when its center and zoom are set
  3439. // for the first time).
  3440. if (loading) {
  3441. this.fire('load');
  3442. }
  3443. },
  3444. _moveStart: function (zoomChanged, noMoveStart) {
  3445. // @event zoomstart: Event
  3446. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3447. // @event movestart: Event
  3448. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3449. if (zoomChanged) {
  3450. this.fire('zoomstart');
  3451. }
  3452. if (!noMoveStart) {
  3453. this.fire('movestart');
  3454. }
  3455. return this;
  3456. },
  3457. _move: function (center, zoom, data) {
  3458. if (zoom === undefined) {
  3459. zoom = this._zoom;
  3460. }
  3461. var zoomChanged = this._zoom !== zoom;
  3462. this._zoom = zoom;
  3463. this._lastCenter = center;
  3464. this._pixelOrigin = this._getNewPixelOrigin(center);
  3465. // @event zoom: Event
  3466. // Fired repeatedly during any change in zoom level, including zoom
  3467. // and fly animations.
  3468. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3469. this.fire('zoom', data);
  3470. }
  3471. // @event move: Event
  3472. // Fired repeatedly during any movement of the map, including pan and
  3473. // fly animations.
  3474. return this.fire('move', data);
  3475. },
  3476. _moveEnd: function (zoomChanged) {
  3477. // @event zoomend: Event
  3478. // Fired when the map has changed, after any animations.
  3479. if (zoomChanged) {
  3480. this.fire('zoomend');
  3481. }
  3482. // @event moveend: Event
  3483. // Fired when the center of the map stops changing (e.g. user stopped
  3484. // dragging the map).
  3485. return this.fire('moveend');
  3486. },
  3487. _stop: function () {
  3488. cancelAnimFrame(this._flyToFrame);
  3489. if (this._panAnim) {
  3490. this._panAnim.stop();
  3491. }
  3492. return this;
  3493. },
  3494. _rawPanBy: function (offset) {
  3495. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3496. },
  3497. _getZoomSpan: function () {
  3498. return this.getMaxZoom() - this.getMinZoom();
  3499. },
  3500. _panInsideMaxBounds: function () {
  3501. if (!this._enforcingBounds) {
  3502. this.panInsideBounds(this.options.maxBounds);
  3503. }
  3504. },
  3505. _checkIfLoaded: function () {
  3506. if (!this._loaded) {
  3507. throw new Error('Set map center and zoom first.');
  3508. }
  3509. },
  3510. // DOM event handling
  3511. // @section Interaction events
  3512. _initEvents: function (remove$$1) {
  3513. this._targets = {};
  3514. this._targets[stamp(this._container)] = this;
  3515. var onOff = remove$$1 ? off : on;
  3516. // @event click: MouseEvent
  3517. // Fired when the user clicks (or taps) the map.
  3518. // @event dblclick: MouseEvent
  3519. // Fired when the user double-clicks (or double-taps) the map.
  3520. // @event mousedown: MouseEvent
  3521. // Fired when the user pushes the mouse button on the map.
  3522. // @event mouseup: MouseEvent
  3523. // Fired when the user releases the mouse button on the map.
  3524. // @event mouseover: MouseEvent
  3525. // Fired when the mouse enters the map.
  3526. // @event mouseout: MouseEvent
  3527. // Fired when the mouse leaves the map.
  3528. // @event mousemove: MouseEvent
  3529. // Fired while the mouse moves over the map.
  3530. // @event contextmenu: MouseEvent
  3531. // Fired when the user pushes the right mouse button on the map, prevents
  3532. // default browser context menu from showing if there are listeners on
  3533. // this event. Also fired on mobile when the user holds a single touch
  3534. // for a second (also called long press).
  3535. // @event keypress: KeyboardEvent
  3536. // Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
  3537. // @event keydown: KeyboardEvent
  3538. // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
  3539. // the `keydown` event is fired for keys that produce a character value and for keys
  3540. // that do not produce a character value.
  3541. // @event keyup: KeyboardEvent
  3542. // Fired when the user releases a key from the keyboard while the map is focused.
  3543. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3544. 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
  3545. if (this.options.trackResize) {
  3546. onOff(window, 'resize', this._onResize, this);
  3547. }
  3548. if (any3d && this.options.transform3DLimit) {
  3549. (remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3550. }
  3551. },
  3552. _onResize: function () {
  3553. cancelAnimFrame(this._resizeRequest);
  3554. this._resizeRequest = requestAnimFrame(
  3555. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3556. },
  3557. _onScroll: function () {
  3558. this._container.scrollTop = 0;
  3559. this._container.scrollLeft = 0;
  3560. },
  3561. _onMoveEnd: function () {
  3562. var pos = this._getMapPanePos();
  3563. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3564. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3565. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  3566. this._resetView(this.getCenter(), this.getZoom());
  3567. }
  3568. },
  3569. _findEventTargets: function (e, type) {
  3570. var targets = [],
  3571. target,
  3572. isHover = type === 'mouseout' || type === 'mouseover',
  3573. src = e.target || e.srcElement,
  3574. dragging = false;
  3575. while (src) {
  3576. target = this._targets[stamp(src)];
  3577. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  3578. // Prevent firing click after you just dragged an object.
  3579. dragging = true;
  3580. break;
  3581. }
  3582. if (target && target.listens(type, true)) {
  3583. if (isHover && !isExternalTarget(src, e)) { break; }
  3584. targets.push(target);
  3585. if (isHover) { break; }
  3586. }
  3587. if (src === this._container) { break; }
  3588. src = src.parentNode;
  3589. }
  3590. if (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {
  3591. targets = [this];
  3592. }
  3593. return targets;
  3594. },
  3595. _handleDOMEvent: function (e) {
  3596. if (!this._loaded || skipped(e)) { return; }
  3597. var type = e.type;
  3598. if (type === 'mousedown' || type === 'keypress' || type === 'keyup' || type === 'keydown') {
  3599. // prevents outline when clicking on keyboard-focusable element
  3600. preventOutline(e.target || e.srcElement);
  3601. }
  3602. this._fireDOMEvent(e, type);
  3603. },
  3604. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3605. _fireDOMEvent: function (e, type, targets) {
  3606. if (e.type === 'click') {
  3607. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3608. // @event preclick: MouseEvent
  3609. // Fired before mouse click on the map (sometimes useful when you
  3610. // want something to happen on click before any existing click
  3611. // handlers start running).
  3612. var synth = extend({}, e);
  3613. synth.type = 'preclick';
  3614. this._fireDOMEvent(synth, synth.type, targets);
  3615. }
  3616. if (e._stopped) { return; }
  3617. // Find the layer the event is propagating from and its parents.
  3618. targets = (targets || []).concat(this._findEventTargets(e, type));
  3619. if (!targets.length) { return; }
  3620. var target = targets[0];
  3621. if (type === 'contextmenu' && target.listens(type, true)) {
  3622. preventDefault(e);
  3623. }
  3624. var data = {
  3625. originalEvent: e
  3626. };
  3627. if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
  3628. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  3629. data.containerPoint = isMarker ?
  3630. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3631. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3632. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3633. }
  3634. for (var i = 0; i < targets.length; i++) {
  3635. targets[i].fire(type, data, true);
  3636. if (data.originalEvent._stopped ||
  3637. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3638. }
  3639. },
  3640. _draggableMoved: function (obj) {
  3641. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3642. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3643. },
  3644. _clearHandlers: function () {
  3645. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3646. this._handlers[i].disable();
  3647. }
  3648. },
  3649. // @section Other Methods
  3650. // @method whenReady(fn: Function, context?: Object): this
  3651. // Runs the given function `fn` when the map gets initialized with
  3652. // a view (center and zoom) and at least one layer, or immediately
  3653. // if it's already initialized, optionally passing a function context.
  3654. whenReady: function (callback, context) {
  3655. if (this._loaded) {
  3656. callback.call(context || this, {target: this});
  3657. } else {
  3658. this.on('load', callback, context);
  3659. }
  3660. return this;
  3661. },
  3662. // private methods for getting map state
  3663. _getMapPanePos: function () {
  3664. return getPosition(this._mapPane) || new Point(0, 0);
  3665. },
  3666. _moved: function () {
  3667. var pos = this._getMapPanePos();
  3668. return pos && !pos.equals([0, 0]);
  3669. },
  3670. _getTopLeftPoint: function (center, zoom) {
  3671. var pixelOrigin = center && zoom !== undefined ?
  3672. this._getNewPixelOrigin(center, zoom) :
  3673. this.getPixelOrigin();
  3674. return pixelOrigin.subtract(this._getMapPanePos());
  3675. },
  3676. _getNewPixelOrigin: function (center, zoom) {
  3677. var viewHalf = this.getSize()._divideBy(2);
  3678. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3679. },
  3680. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3681. var topLeft = this._getNewPixelOrigin(center, zoom);
  3682. return this.project(latlng, zoom)._subtract(topLeft);
  3683. },
  3684. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3685. var topLeft = this._getNewPixelOrigin(center, zoom);
  3686. return toBounds([
  3687. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3688. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3689. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3690. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3691. ]);
  3692. },
  3693. // layer point of the current center
  3694. _getCenterLayerPoint: function () {
  3695. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3696. },
  3697. // offset of the specified place to the current center in pixels
  3698. _getCenterOffset: function (latlng) {
  3699. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3700. },
  3701. // adjust center for view to get inside bounds
  3702. _limitCenter: function (center, zoom, bounds) {
  3703. if (!bounds) { return center; }
  3704. var centerPoint = this.project(center, zoom),
  3705. viewHalf = this.getSize().divideBy(2),
  3706. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3707. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3708. // If offset is less than a pixel, ignore.
  3709. // This prevents unstable projections from getting into
  3710. // an infinite loop of tiny offsets.
  3711. if (offset.round().equals([0, 0])) {
  3712. return center;
  3713. }
  3714. return this.unproject(centerPoint.add(offset), zoom);
  3715. },
  3716. // adjust offset for view to get inside bounds
  3717. _limitOffset: function (offset, bounds) {
  3718. if (!bounds) { return offset; }
  3719. var viewBounds = this.getPixelBounds(),
  3720. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3721. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3722. },
  3723. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3724. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3725. var projectedMaxBounds = toBounds(
  3726. this.project(maxBounds.getNorthEast(), zoom),
  3727. this.project(maxBounds.getSouthWest(), zoom)
  3728. ),
  3729. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3730. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3731. dx = this._rebound(minOffset.x, -maxOffset.x),
  3732. dy = this._rebound(minOffset.y, -maxOffset.y);
  3733. return new Point(dx, dy);
  3734. },
  3735. _rebound: function (left, right) {
  3736. return left + right > 0 ?
  3737. Math.round(left - right) / 2 :
  3738. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3739. },
  3740. _limitZoom: function (zoom) {
  3741. var min = this.getMinZoom(),
  3742. max = this.getMaxZoom(),
  3743. snap = any3d ? this.options.zoomSnap : 1;
  3744. if (snap) {
  3745. zoom = Math.round(zoom / snap) * snap;
  3746. }
  3747. return Math.max(min, Math.min(max, zoom));
  3748. },
  3749. _onPanTransitionStep: function () {
  3750. this.fire('move');
  3751. },
  3752. _onPanTransitionEnd: function () {
  3753. removeClass(this._mapPane, 'leaflet-pan-anim');
  3754. this.fire('moveend');
  3755. },
  3756. _tryAnimatedPan: function (center, options) {
  3757. // difference between the new and current centers in pixels
  3758. var offset = this._getCenterOffset(center)._trunc();
  3759. // don't animate too far unless animate: true specified in options
  3760. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3761. this.panBy(offset, options);
  3762. return true;
  3763. },
  3764. _createAnimProxy: function () {
  3765. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3766. this._panes.mapPane.appendChild(proxy);
  3767. this.on('zoomanim', function (e) {
  3768. var prop = TRANSFORM,
  3769. transform = this._proxy.style[prop];
  3770. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3771. // workaround for case when transform is the same and so transitionend event is not fired
  3772. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3773. this._onZoomTransitionEnd();
  3774. }
  3775. }, this);
  3776. this.on('load moveend', this._animMoveEnd, this);
  3777. this._on('unload', this._destroyAnimProxy, this);
  3778. },
  3779. _destroyAnimProxy: function () {
  3780. remove(this._proxy);
  3781. this.off('load moveend', this._animMoveEnd, this);
  3782. delete this._proxy;
  3783. },
  3784. _animMoveEnd: function () {
  3785. var c = this.getCenter(),
  3786. z = this.getZoom();
  3787. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3788. },
  3789. _catchTransitionEnd: function (e) {
  3790. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3791. this._onZoomTransitionEnd();
  3792. }
  3793. },
  3794. _nothingToAnimate: function () {
  3795. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3796. },
  3797. _tryAnimatedZoom: function (center, zoom, options) {
  3798. if (this._animatingZoom) { return true; }
  3799. options = options || {};
  3800. // don't animate if disabled, not supported or zoom difference is too large
  3801. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3802. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3803. // offset is the pixel coords of the zoom origin relative to the current center
  3804. var scale = this.getZoomScale(zoom),
  3805. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3806. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3807. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3808. requestAnimFrame(function () {
  3809. this
  3810. ._moveStart(true, false)
  3811. ._animateZoom(center, zoom, true);
  3812. }, this);
  3813. return true;
  3814. },
  3815. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3816. if (!this._mapPane) { return; }
  3817. if (startAnim) {
  3818. this._animatingZoom = true;
  3819. // remember what center/zoom to set after animation
  3820. this._animateToCenter = center;
  3821. this._animateToZoom = zoom;
  3822. addClass(this._mapPane, 'leaflet-zoom-anim');
  3823. }
  3824. // @section Other Events
  3825. // @event zoomanim: ZoomAnimEvent
  3826. // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
  3827. this.fire('zoomanim', {
  3828. center: center,
  3829. zoom: zoom,
  3830. noUpdate: noUpdate
  3831. });
  3832. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3833. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3834. },
  3835. _onZoomTransitionEnd: function () {
  3836. if (!this._animatingZoom) { return; }
  3837. if (this._mapPane) {
  3838. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3839. }
  3840. this._animatingZoom = false;
  3841. this._move(this._animateToCenter, this._animateToZoom);
  3842. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  3843. requestAnimFrame(function () {
  3844. this._moveEnd(true);
  3845. }, this);
  3846. }
  3847. });
  3848. // @section
  3849. // @factory L.map(id: String, options?: Map options)
  3850. // Instantiates a map object given the DOM ID of a `<div>` element
  3851. // and optionally an object literal with `Map options`.
  3852. //
  3853. // @alternative
  3854. // @factory L.map(el: HTMLElement, options?: Map options)
  3855. // Instantiates a map object given an instance of a `<div>` HTML element
  3856. // and optionally an object literal with `Map options`.
  3857. function createMap(id, options) {
  3858. return new Map(id, options);
  3859. }
  3860. /*
  3861. * @class Control
  3862. * @aka L.Control
  3863. * @inherits Class
  3864. *
  3865. * L.Control is a base class for implementing map controls. Handles positioning.
  3866. * All other controls extend from this class.
  3867. */
  3868. var Control = Class.extend({
  3869. // @section
  3870. // @aka Control options
  3871. options: {
  3872. // @option position: String = 'topright'
  3873. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  3874. // `'topright'`, `'bottomleft'` or `'bottomright'`
  3875. position: 'topright'
  3876. },
  3877. initialize: function (options) {
  3878. setOptions(this, options);
  3879. },
  3880. /* @section
  3881. * Classes extending L.Control will inherit the following methods:
  3882. *
  3883. * @method getPosition: string
  3884. * Returns the position of the control.
  3885. */
  3886. getPosition: function () {
  3887. return this.options.position;
  3888. },
  3889. // @method setPosition(position: string): this
  3890. // Sets the position of the control.
  3891. setPosition: function (position) {
  3892. var map = this._map;
  3893. if (map) {
  3894. map.removeControl(this);
  3895. }
  3896. this.options.position = position;
  3897. if (map) {
  3898. map.addControl(this);
  3899. }
  3900. return this;
  3901. },
  3902. // @method getContainer: HTMLElement
  3903. // Returns the HTMLElement that contains the control.
  3904. getContainer: function () {
  3905. return this._container;
  3906. },
  3907. // @method addTo(map: Map): this
  3908. // Adds the control to the given map.
  3909. addTo: function (map) {
  3910. this.remove();
  3911. this._map = map;
  3912. var container = this._container = this.onAdd(map),
  3913. pos = this.getPosition(),
  3914. corner = map._controlCorners[pos];
  3915. addClass(container, 'leaflet-control');
  3916. if (pos.indexOf('bottom') !== -1) {
  3917. corner.insertBefore(container, corner.firstChild);
  3918. } else {
  3919. corner.appendChild(container);
  3920. }
  3921. this._map.on('unload', this.remove, this);
  3922. return this;
  3923. },
  3924. // @method remove: this
  3925. // Removes the control from the map it is currently active on.
  3926. remove: function () {
  3927. if (!this._map) {
  3928. return this;
  3929. }
  3930. remove(this._container);
  3931. if (this.onRemove) {
  3932. this.onRemove(this._map);
  3933. }
  3934. this._map.off('unload', this.remove, this);
  3935. this._map = null;
  3936. return this;
  3937. },
  3938. _refocusOnMap: function (e) {
  3939. // if map exists and event is not a keyboard event
  3940. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  3941. this._map.getContainer().focus();
  3942. }
  3943. }
  3944. });
  3945. var control = function (options) {
  3946. return new Control(options);
  3947. };
  3948. /* @section Extension methods
  3949. * @uninheritable
  3950. *
  3951. * Every control should extend from `L.Control` and (re-)implement the following methods.
  3952. *
  3953. * @method onAdd(map: Map): HTMLElement
  3954. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  3955. *
  3956. * @method onRemove(map: Map)
  3957. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  3958. */
  3959. /* @namespace Map
  3960. * @section Methods for Layers and Controls
  3961. */
  3962. Map.include({
  3963. // @method addControl(control: Control): this
  3964. // Adds the given control to the map
  3965. addControl: function (control) {
  3966. control.addTo(this);
  3967. return this;
  3968. },
  3969. // @method removeControl(control: Control): this
  3970. // Removes the given control from the map
  3971. removeControl: function (control) {
  3972. control.remove();
  3973. return this;
  3974. },
  3975. _initControlPos: function () {
  3976. var corners = this._controlCorners = {},
  3977. l = 'leaflet-',
  3978. container = this._controlContainer =
  3979. create$1('div', l + 'control-container', this._container);
  3980. function createCorner(vSide, hSide) {
  3981. var className = l + vSide + ' ' + l + hSide;
  3982. corners[vSide + hSide] = create$1('div', className, container);
  3983. }
  3984. createCorner('top', 'left');
  3985. createCorner('top', 'right');
  3986. createCorner('bottom', 'left');
  3987. createCorner('bottom', 'right');
  3988. },
  3989. _clearControlPos: function () {
  3990. for (var i in this._controlCorners) {
  3991. remove(this._controlCorners[i]);
  3992. }
  3993. remove(this._controlContainer);
  3994. delete this._controlCorners;
  3995. delete this._controlContainer;
  3996. }
  3997. });
  3998. /*
  3999. * @class Control.Layers
  4000. * @aka L.Control.Layers
  4001. * @inherits Control
  4002. *
  4003. * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control/)). Extends `Control`.
  4004. *
  4005. * @example
  4006. *
  4007. * ```js
  4008. * var baseLayers = {
  4009. * "Mapbox": mapbox,
  4010. * "OpenStreetMap": osm
  4011. * };
  4012. *
  4013. * var overlays = {
  4014. * "Marker": marker,
  4015. * "Roads": roadsLayer
  4016. * };
  4017. *
  4018. * L.control.layers(baseLayers, overlays).addTo(map);
  4019. * ```
  4020. *
  4021. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  4022. *
  4023. * ```js
  4024. * {
  4025. * "<someName1>": layer1,
  4026. * "<someName2>": layer2
  4027. * }
  4028. * ```
  4029. *
  4030. * The layer names can contain HTML, which allows you to add additional styling to the items:
  4031. *
  4032. * ```js
  4033. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  4034. * ```
  4035. */
  4036. var Layers = Control.extend({
  4037. // @section
  4038. // @aka Control.Layers options
  4039. options: {
  4040. // @option collapsed: Boolean = true
  4041. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  4042. collapsed: true,
  4043. position: 'topright',
  4044. // @option autoZIndex: Boolean = true
  4045. // 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.
  4046. autoZIndex: true,
  4047. // @option hideSingleBase: Boolean = false
  4048. // If `true`, the base layers in the control will be hidden when there is only one.
  4049. hideSingleBase: false,
  4050. // @option sortLayers: Boolean = false
  4051. // Whether to sort the layers. When `false`, layers will keep the order
  4052. // in which they were added to the control.
  4053. sortLayers: false,
  4054. // @option sortFunction: Function = *
  4055. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  4056. // that will be used for sorting the layers, when `sortLayers` is `true`.
  4057. // The function receives both the `L.Layer` instances and their names, as in
  4058. // `sortFunction(layerA, layerB, nameA, nameB)`.
  4059. // By default, it sorts layers alphabetically by their name.
  4060. sortFunction: function (layerA, layerB, nameA, nameB) {
  4061. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  4062. }
  4063. },
  4064. initialize: function (baseLayers, overlays, options) {
  4065. setOptions(this, options);
  4066. this._layerControlInputs = [];
  4067. this._layers = [];
  4068. this._lastZIndex = 0;
  4069. this._handlingClick = false;
  4070. for (var i in baseLayers) {
  4071. this._addLayer(baseLayers[i], i);
  4072. }
  4073. for (i in overlays) {
  4074. this._addLayer(overlays[i], i, true);
  4075. }
  4076. },
  4077. onAdd: function (map) {
  4078. this._initLayout();
  4079. this._update();
  4080. this._map = map;
  4081. map.on('zoomend', this._checkDisabledLayers, this);
  4082. for (var i = 0; i < this._layers.length; i++) {
  4083. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4084. }
  4085. return this._container;
  4086. },
  4087. addTo: function (map) {
  4088. Control.prototype.addTo.call(this, map);
  4089. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4090. return this._expandIfNotCollapsed();
  4091. },
  4092. onRemove: function () {
  4093. this._map.off('zoomend', this._checkDisabledLayers, this);
  4094. for (var i = 0; i < this._layers.length; i++) {
  4095. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4096. }
  4097. },
  4098. // @method addBaseLayer(layer: Layer, name: String): this
  4099. // Adds a base layer (radio button entry) with the given name to the control.
  4100. addBaseLayer: function (layer, name) {
  4101. this._addLayer(layer, name);
  4102. return (this._map) ? this._update() : this;
  4103. },
  4104. // @method addOverlay(layer: Layer, name: String): this
  4105. // Adds an overlay (checkbox entry) with the given name to the control.
  4106. addOverlay: function (layer, name) {
  4107. this._addLayer(layer, name, true);
  4108. return (this._map) ? this._update() : this;
  4109. },
  4110. // @method removeLayer(layer: Layer): this
  4111. // Remove the given layer from the control.
  4112. removeLayer: function (layer) {
  4113. layer.off('add remove', this._onLayerChange, this);
  4114. var obj = this._getLayer(stamp(layer));
  4115. if (obj) {
  4116. this._layers.splice(this._layers.indexOf(obj), 1);
  4117. }
  4118. return (this._map) ? this._update() : this;
  4119. },
  4120. // @method expand(): this
  4121. // Expand the control container if collapsed.
  4122. expand: function () {
  4123. addClass(this._container, 'leaflet-control-layers-expanded');
  4124. this._section.style.height = null;
  4125. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4126. if (acceptableHeight < this._section.clientHeight) {
  4127. addClass(this._section, 'leaflet-control-layers-scrollbar');
  4128. this._section.style.height = acceptableHeight + 'px';
  4129. } else {
  4130. removeClass(this._section, 'leaflet-control-layers-scrollbar');
  4131. }
  4132. this._checkDisabledLayers();
  4133. return this;
  4134. },
  4135. // @method collapse(): this
  4136. // Collapse the control container if expanded.
  4137. collapse: function () {
  4138. removeClass(this._container, 'leaflet-control-layers-expanded');
  4139. return this;
  4140. },
  4141. _initLayout: function () {
  4142. var className = 'leaflet-control-layers',
  4143. container = this._container = create$1('div', className),
  4144. collapsed = this.options.collapsed;
  4145. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4146. container.setAttribute('aria-haspopup', true);
  4147. disableClickPropagation(container);
  4148. disableScrollPropagation(container);
  4149. var section = this._section = create$1('section', className + '-list');
  4150. if (collapsed) {
  4151. this._map.on('click', this.collapse, this);
  4152. if (!android) {
  4153. on(container, {
  4154. mouseenter: this.expand,
  4155. mouseleave: this.collapse
  4156. }, this);
  4157. }
  4158. }
  4159. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4160. link.href = '#';
  4161. link.title = 'Layers';
  4162. if (touch) {
  4163. on(link, 'click', stop);
  4164. on(link, 'click', this.expand, this);
  4165. } else {
  4166. on(link, 'focus', this.expand, this);
  4167. }
  4168. if (!collapsed) {
  4169. this.expand();
  4170. }
  4171. this._baseLayersList = create$1('div', className + '-base', section);
  4172. this._separator = create$1('div', className + '-separator', section);
  4173. this._overlaysList = create$1('div', className + '-overlays', section);
  4174. container.appendChild(section);
  4175. },
  4176. _getLayer: function (id) {
  4177. for (var i = 0; i < this._layers.length; i++) {
  4178. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4179. return this._layers[i];
  4180. }
  4181. }
  4182. },
  4183. _addLayer: function (layer, name, overlay) {
  4184. if (this._map) {
  4185. layer.on('add remove', this._onLayerChange, this);
  4186. }
  4187. this._layers.push({
  4188. layer: layer,
  4189. name: name,
  4190. overlay: overlay
  4191. });
  4192. if (this.options.sortLayers) {
  4193. this._layers.sort(bind(function (a, b) {
  4194. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4195. }, this));
  4196. }
  4197. if (this.options.autoZIndex && layer.setZIndex) {
  4198. this._lastZIndex++;
  4199. layer.setZIndex(this._lastZIndex);
  4200. }
  4201. this._expandIfNotCollapsed();
  4202. },
  4203. _update: function () {
  4204. if (!this._container) { return this; }
  4205. empty(this._baseLayersList);
  4206. empty(this._overlaysList);
  4207. this._layerControlInputs = [];
  4208. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4209. for (i = 0; i < this._layers.length; i++) {
  4210. obj = this._layers[i];
  4211. this._addItem(obj);
  4212. overlaysPresent = overlaysPresent || obj.overlay;
  4213. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4214. baseLayersCount += !obj.overlay ? 1 : 0;
  4215. }
  4216. // Hide base layers section if there's only one layer.
  4217. if (this.options.hideSingleBase) {
  4218. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4219. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4220. }
  4221. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4222. return this;
  4223. },
  4224. _onLayerChange: function (e) {
  4225. if (!this._handlingClick) {
  4226. this._update();
  4227. }
  4228. var obj = this._getLayer(stamp(e.target));
  4229. // @namespace Map
  4230. // @section Layer events
  4231. // @event baselayerchange: LayersControlEvent
  4232. // Fired when the base layer is changed through the [layers control](#control-layers).
  4233. // @event overlayadd: LayersControlEvent
  4234. // Fired when an overlay is selected through the [layers control](#control-layers).
  4235. // @event overlayremove: LayersControlEvent
  4236. // Fired when an overlay is deselected through the [layers control](#control-layers).
  4237. // @namespace Control.Layers
  4238. var type = obj.overlay ?
  4239. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4240. (e.type === 'add' ? 'baselayerchange' : null);
  4241. if (type) {
  4242. this._map.fire(type, obj);
  4243. }
  4244. },
  4245. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  4246. _createRadioElement: function (name, checked) {
  4247. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4248. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4249. var radioFragment = document.createElement('div');
  4250. radioFragment.innerHTML = radioHtml;
  4251. return radioFragment.firstChild;
  4252. },
  4253. _addItem: function (obj) {
  4254. var label = document.createElement('label'),
  4255. checked = this._map.hasLayer(obj.layer),
  4256. input;
  4257. if (obj.overlay) {
  4258. input = document.createElement('input');
  4259. input.type = 'checkbox';
  4260. input.className = 'leaflet-control-layers-selector';
  4261. input.defaultChecked = checked;
  4262. } else {
  4263. input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);
  4264. }
  4265. this._layerControlInputs.push(input);
  4266. input.layerId = stamp(obj.layer);
  4267. on(input, 'click', this._onInputClick, this);
  4268. var name = document.createElement('span');
  4269. name.innerHTML = ' ' + obj.name;
  4270. // Helps from preventing layer control flicker when checkboxes are disabled
  4271. // https://github.com/Leaflet/Leaflet/issues/2771
  4272. var holder = document.createElement('div');
  4273. label.appendChild(holder);
  4274. holder.appendChild(input);
  4275. holder.appendChild(name);
  4276. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4277. container.appendChild(label);
  4278. this._checkDisabledLayers();
  4279. return label;
  4280. },
  4281. _onInputClick: function () {
  4282. var inputs = this._layerControlInputs,
  4283. input, layer;
  4284. var addedLayers = [],
  4285. removedLayers = [];
  4286. this._handlingClick = true;
  4287. for (var i = inputs.length - 1; i >= 0; i--) {
  4288. input = inputs[i];
  4289. layer = this._getLayer(input.layerId).layer;
  4290. if (input.checked) {
  4291. addedLayers.push(layer);
  4292. } else if (!input.checked) {
  4293. removedLayers.push(layer);
  4294. }
  4295. }
  4296. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4297. for (i = 0; i < removedLayers.length; i++) {
  4298. if (this._map.hasLayer(removedLayers[i])) {
  4299. this._map.removeLayer(removedLayers[i]);
  4300. }
  4301. }
  4302. for (i = 0; i < addedLayers.length; i++) {
  4303. if (!this._map.hasLayer(addedLayers[i])) {
  4304. this._map.addLayer(addedLayers[i]);
  4305. }
  4306. }
  4307. this._handlingClick = false;
  4308. this._refocusOnMap();
  4309. },
  4310. _checkDisabledLayers: function () {
  4311. var inputs = this._layerControlInputs,
  4312. input,
  4313. layer,
  4314. zoom = this._map.getZoom();
  4315. for (var i = inputs.length - 1; i >= 0; i--) {
  4316. input = inputs[i];
  4317. layer = this._getLayer(input.layerId).layer;
  4318. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4319. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4320. }
  4321. },
  4322. _expandIfNotCollapsed: function () {
  4323. if (this._map && !this.options.collapsed) {
  4324. this.expand();
  4325. }
  4326. return this;
  4327. },
  4328. _expand: function () {
  4329. // Backward compatibility, remove me in 1.1.
  4330. return this.expand();
  4331. },
  4332. _collapse: function () {
  4333. // Backward compatibility, remove me in 1.1.
  4334. return this.collapse();
  4335. }
  4336. });
  4337. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4338. // 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.
  4339. var layers = function (baseLayers, overlays, options) {
  4340. return new Layers(baseLayers, overlays, options);
  4341. };
  4342. /*
  4343. * @class Control.Zoom
  4344. * @aka L.Control.Zoom
  4345. * @inherits Control
  4346. *
  4347. * 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`.
  4348. */
  4349. var Zoom = Control.extend({
  4350. // @section
  4351. // @aka Control.Zoom options
  4352. options: {
  4353. position: 'topleft',
  4354. // @option zoomInText: String = '+'
  4355. // The text set on the 'zoom in' button.
  4356. zoomInText: '+',
  4357. // @option zoomInTitle: String = 'Zoom in'
  4358. // The title set on the 'zoom in' button.
  4359. zoomInTitle: 'Zoom in',
  4360. // @option zoomOutText: String = '&#x2212;'
  4361. // The text set on the 'zoom out' button.
  4362. zoomOutText: '&#x2212;',
  4363. // @option zoomOutTitle: String = 'Zoom out'
  4364. // The title set on the 'zoom out' button.
  4365. zoomOutTitle: 'Zoom out'
  4366. },
  4367. onAdd: function (map) {
  4368. var zoomName = 'leaflet-control-zoom',
  4369. container = create$1('div', zoomName + ' leaflet-bar'),
  4370. options = this.options;
  4371. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4372. zoomName + '-in', container, this._zoomIn);
  4373. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4374. zoomName + '-out', container, this._zoomOut);
  4375. this._updateDisabled();
  4376. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4377. return container;
  4378. },
  4379. onRemove: function (map) {
  4380. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4381. },
  4382. disable: function () {
  4383. this._disabled = true;
  4384. this._updateDisabled();
  4385. return this;
  4386. },
  4387. enable: function () {
  4388. this._disabled = false;
  4389. this._updateDisabled();
  4390. return this;
  4391. },
  4392. _zoomIn: function (e) {
  4393. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4394. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4395. }
  4396. },
  4397. _zoomOut: function (e) {
  4398. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4399. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4400. }
  4401. },
  4402. _createButton: function (html, title, className, container, fn) {
  4403. var link = create$1('a', className, container);
  4404. link.innerHTML = html;
  4405. link.href = '#';
  4406. link.title = title;
  4407. /*
  4408. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4409. */
  4410. link.setAttribute('role', 'button');
  4411. link.setAttribute('aria-label', title);
  4412. disableClickPropagation(link);
  4413. on(link, 'click', stop);
  4414. on(link, 'click', fn, this);
  4415. on(link, 'click', this._refocusOnMap, this);
  4416. return link;
  4417. },
  4418. _updateDisabled: function () {
  4419. var map = this._map,
  4420. className = 'leaflet-disabled';
  4421. removeClass(this._zoomInButton, className);
  4422. removeClass(this._zoomOutButton, className);
  4423. if (this._disabled || map._zoom === map.getMinZoom()) {
  4424. addClass(this._zoomOutButton, className);
  4425. }
  4426. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4427. addClass(this._zoomInButton, className);
  4428. }
  4429. }
  4430. });
  4431. // @namespace Map
  4432. // @section Control options
  4433. // @option zoomControl: Boolean = true
  4434. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4435. Map.mergeOptions({
  4436. zoomControl: true
  4437. });
  4438. Map.addInitHook(function () {
  4439. if (this.options.zoomControl) {
  4440. // @section Controls
  4441. // @property zoomControl: Control.Zoom
  4442. // The default zoom control (only available if the
  4443. // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
  4444. this.zoomControl = new Zoom();
  4445. this.addControl(this.zoomControl);
  4446. }
  4447. });
  4448. // @namespace Control.Zoom
  4449. // @factory L.control.zoom(options: Control.Zoom options)
  4450. // Creates a zoom control
  4451. var zoom = function (options) {
  4452. return new Zoom(options);
  4453. };
  4454. /*
  4455. * @class Control.Scale
  4456. * @aka L.Control.Scale
  4457. * @inherits Control
  4458. *
  4459. * 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`.
  4460. *
  4461. * @example
  4462. *
  4463. * ```js
  4464. * L.control.scale().addTo(map);
  4465. * ```
  4466. */
  4467. var Scale = Control.extend({
  4468. // @section
  4469. // @aka Control.Scale options
  4470. options: {
  4471. position: 'bottomleft',
  4472. // @option maxWidth: Number = 100
  4473. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4474. maxWidth: 100,
  4475. // @option metric: Boolean = True
  4476. // Whether to show the metric scale line (m/km).
  4477. metric: true,
  4478. // @option imperial: Boolean = True
  4479. // Whether to show the imperial scale line (mi/ft).
  4480. imperial: true
  4481. // @option updateWhenIdle: Boolean = false
  4482. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4483. },
  4484. onAdd: function (map) {
  4485. var className = 'leaflet-control-scale',
  4486. container = create$1('div', className),
  4487. options = this.options;
  4488. this._addScales(options, className + '-line', container);
  4489. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4490. map.whenReady(this._update, this);
  4491. return container;
  4492. },
  4493. onRemove: function (map) {
  4494. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4495. },
  4496. _addScales: function (options, className, container) {
  4497. if (options.metric) {
  4498. this._mScale = create$1('div', className, container);
  4499. }
  4500. if (options.imperial) {
  4501. this._iScale = create$1('div', className, container);
  4502. }
  4503. },
  4504. _update: function () {
  4505. var map = this._map,
  4506. y = map.getSize().y / 2;
  4507. var maxMeters = map.distance(
  4508. map.containerPointToLatLng([0, y]),
  4509. map.containerPointToLatLng([this.options.maxWidth, y]));
  4510. this._updateScales(maxMeters);
  4511. },
  4512. _updateScales: function (maxMeters) {
  4513. if (this.options.metric && maxMeters) {
  4514. this._updateMetric(maxMeters);
  4515. }
  4516. if (this.options.imperial && maxMeters) {
  4517. this._updateImperial(maxMeters);
  4518. }
  4519. },
  4520. _updateMetric: function (maxMeters) {
  4521. var meters = this._getRoundNum(maxMeters),
  4522. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4523. this._updateScale(this._mScale, label, meters / maxMeters);
  4524. },
  4525. _updateImperial: function (maxMeters) {
  4526. var maxFeet = maxMeters * 3.2808399,
  4527. maxMiles, miles, feet;
  4528. if (maxFeet > 5280) {
  4529. maxMiles = maxFeet / 5280;
  4530. miles = this._getRoundNum(maxMiles);
  4531. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4532. } else {
  4533. feet = this._getRoundNum(maxFeet);
  4534. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4535. }
  4536. },
  4537. _updateScale: function (scale, text, ratio) {
  4538. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4539. scale.innerHTML = text;
  4540. },
  4541. _getRoundNum: function (num) {
  4542. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4543. d = num / pow10;
  4544. d = d >= 10 ? 10 :
  4545. d >= 5 ? 5 :
  4546. d >= 3 ? 3 :
  4547. d >= 2 ? 2 : 1;
  4548. return pow10 * d;
  4549. }
  4550. });
  4551. // @factory L.control.scale(options?: Control.Scale options)
  4552. // Creates an scale control with the given options.
  4553. var scale = function (options) {
  4554. return new Scale(options);
  4555. };
  4556. /*
  4557. * @class Control.Attribution
  4558. * @aka L.Control.Attribution
  4559. * @inherits Control
  4560. *
  4561. * 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.
  4562. */
  4563. var Attribution = Control.extend({
  4564. // @section
  4565. // @aka Control.Attribution options
  4566. options: {
  4567. position: 'bottomright',
  4568. // @option prefix: String = 'Leaflet'
  4569. // The HTML text shown before the attributions. Pass `false` to disable.
  4570. prefix: '<a href="https://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  4571. },
  4572. initialize: function (options) {
  4573. setOptions(this, options);
  4574. this._attributions = {};
  4575. },
  4576. onAdd: function (map) {
  4577. map.attributionControl = this;
  4578. this._container = create$1('div', 'leaflet-control-attribution');
  4579. disableClickPropagation(this._container);
  4580. // TODO ugly, refactor
  4581. for (var i in map._layers) {
  4582. if (map._layers[i].getAttribution) {
  4583. this.addAttribution(map._layers[i].getAttribution());
  4584. }
  4585. }
  4586. this._update();
  4587. return this._container;
  4588. },
  4589. // @method setPrefix(prefix: String): this
  4590. // Sets the text before the attributions.
  4591. setPrefix: function (prefix) {
  4592. this.options.prefix = prefix;
  4593. this._update();
  4594. return this;
  4595. },
  4596. // @method addAttribution(text: String): this
  4597. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  4598. addAttribution: function (text) {
  4599. if (!text) { return this; }
  4600. if (!this._attributions[text]) {
  4601. this._attributions[text] = 0;
  4602. }
  4603. this._attributions[text]++;
  4604. this._update();
  4605. return this;
  4606. },
  4607. // @method removeAttribution(text: String): this
  4608. // Removes an attribution text.
  4609. removeAttribution: function (text) {
  4610. if (!text) { return this; }
  4611. if (this._attributions[text]) {
  4612. this._attributions[text]--;
  4613. this._update();
  4614. }
  4615. return this;
  4616. },
  4617. _update: function () {
  4618. if (!this._map) { return; }
  4619. var attribs = [];
  4620. for (var i in this._attributions) {
  4621. if (this._attributions[i]) {
  4622. attribs.push(i);
  4623. }
  4624. }
  4625. var prefixAndAttribs = [];
  4626. if (this.options.prefix) {
  4627. prefixAndAttribs.push(this.options.prefix);
  4628. }
  4629. if (attribs.length) {
  4630. prefixAndAttribs.push(attribs.join(', '));
  4631. }
  4632. this._container.innerHTML = prefixAndAttribs.join(' | ');
  4633. }
  4634. });
  4635. // @namespace Map
  4636. // @section Control options
  4637. // @option attributionControl: Boolean = true
  4638. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4639. Map.mergeOptions({
  4640. attributionControl: true
  4641. });
  4642. Map.addInitHook(function () {
  4643. if (this.options.attributionControl) {
  4644. new Attribution().addTo(this);
  4645. }
  4646. });
  4647. // @namespace Control.Attribution
  4648. // @factory L.control.attribution(options: Control.Attribution options)
  4649. // Creates an attribution control.
  4650. var attribution = function (options) {
  4651. return new Attribution(options);
  4652. };
  4653. Control.Layers = Layers;
  4654. Control.Zoom = Zoom;
  4655. Control.Scale = Scale;
  4656. Control.Attribution = Attribution;
  4657. control.layers = layers;
  4658. control.zoom = zoom;
  4659. control.scale = scale;
  4660. control.attribution = attribution;
  4661. /*
  4662. L.Handler is a base class for handler classes that are used internally to inject
  4663. interaction features like dragging to classes like Map and Marker.
  4664. */
  4665. // @class Handler
  4666. // @aka L.Handler
  4667. // Abstract class for map interaction handlers
  4668. var Handler = Class.extend({
  4669. initialize: function (map) {
  4670. this._map = map;
  4671. },
  4672. // @method enable(): this
  4673. // Enables the handler
  4674. enable: function () {
  4675. if (this._enabled) { return this; }
  4676. this._enabled = true;
  4677. this.addHooks();
  4678. return this;
  4679. },
  4680. // @method disable(): this
  4681. // Disables the handler
  4682. disable: function () {
  4683. if (!this._enabled) { return this; }
  4684. this._enabled = false;
  4685. this.removeHooks();
  4686. return this;
  4687. },
  4688. // @method enabled(): Boolean
  4689. // Returns `true` if the handler is enabled
  4690. enabled: function () {
  4691. return !!this._enabled;
  4692. }
  4693. // @section Extension methods
  4694. // Classes inheriting from `Handler` must implement the two following methods:
  4695. // @method addHooks()
  4696. // Called when the handler is enabled, should add event hooks.
  4697. // @method removeHooks()
  4698. // Called when the handler is disabled, should remove the event hooks added previously.
  4699. });
  4700. // @section There is static function which can be called without instantiating L.Handler:
  4701. // @function addTo(map: Map, name: String): this
  4702. // Adds a new Handler to the given map with the given name.
  4703. Handler.addTo = function (map, name) {
  4704. map.addHandler(name, this);
  4705. return this;
  4706. };
  4707. var Mixin = {Events: Events};
  4708. /*
  4709. * @class Draggable
  4710. * @aka L.Draggable
  4711. * @inherits Evented
  4712. *
  4713. * A class for making DOM elements draggable (including touch support).
  4714. * Used internally for map and marker dragging. Only works for elements
  4715. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4716. *
  4717. * @example
  4718. * ```js
  4719. * var draggable = new L.Draggable(elementToDrag);
  4720. * draggable.enable();
  4721. * ```
  4722. */
  4723. var START = touch ? 'touchstart mousedown' : 'mousedown';
  4724. var END = {
  4725. mousedown: 'mouseup',
  4726. touchstart: 'touchend',
  4727. pointerdown: 'touchend',
  4728. MSPointerDown: 'touchend'
  4729. };
  4730. var MOVE = {
  4731. mousedown: 'mousemove',
  4732. touchstart: 'touchmove',
  4733. pointerdown: 'touchmove',
  4734. MSPointerDown: 'touchmove'
  4735. };
  4736. var Draggable = Evented.extend({
  4737. options: {
  4738. // @section
  4739. // @aka Draggable options
  4740. // @option clickTolerance: Number = 3
  4741. // The max number of pixels a user can shift the mouse pointer during a click
  4742. // for it to be considered a valid click (as opposed to a mouse drag).
  4743. clickTolerance: 3
  4744. },
  4745. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4746. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4747. initialize: function (element, dragStartTarget, preventOutline$$1, options) {
  4748. setOptions(this, options);
  4749. this._element = element;
  4750. this._dragStartTarget = dragStartTarget || element;
  4751. this._preventOutline = preventOutline$$1;
  4752. },
  4753. // @method enable()
  4754. // Enables the dragging ability
  4755. enable: function () {
  4756. if (this._enabled) { return; }
  4757. on(this._dragStartTarget, START, this._onDown, this);
  4758. this._enabled = true;
  4759. },
  4760. // @method disable()
  4761. // Disables the dragging ability
  4762. disable: function () {
  4763. if (!this._enabled) { return; }
  4764. // If we're currently dragging this draggable,
  4765. // disabling it counts as first ending the drag.
  4766. if (Draggable._dragging === this) {
  4767. this.finishDrag();
  4768. }
  4769. off(this._dragStartTarget, START, this._onDown, this);
  4770. this._enabled = false;
  4771. this._moved = false;
  4772. },
  4773. _onDown: function (e) {
  4774. // Ignore simulated events, since we handle both touch and
  4775. // mouse explicitly; otherwise we risk getting duplicates of
  4776. // touch events, see #4315.
  4777. // Also ignore the event if disabled; this happens in IE11
  4778. // under some circumstances, see #3666.
  4779. if (e._simulated || !this._enabled) { return; }
  4780. this._moved = false;
  4781. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4782. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4783. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4784. if (this._preventOutline) {
  4785. preventOutline(this._element);
  4786. }
  4787. disableImageDrag();
  4788. disableTextSelection();
  4789. if (this._moving) { return; }
  4790. // @event down: Event
  4791. // Fired when a drag is about to start.
  4792. this.fire('down');
  4793. var first = e.touches ? e.touches[0] : e,
  4794. sizedParent = getSizedParentNode(this._element);
  4795. this._startPoint = new Point(first.clientX, first.clientY);
  4796. // Cache the scale, so that we can continuously compensate for it during drag (_onMove).
  4797. this._parentScale = getScale(sizedParent);
  4798. on(document, MOVE[e.type], this._onMove, this);
  4799. on(document, END[e.type], this._onUp, this);
  4800. },
  4801. _onMove: function (e) {
  4802. // Ignore simulated events, since we handle both touch and
  4803. // mouse explicitly; otherwise we risk getting duplicates of
  4804. // touch events, see #4315.
  4805. // Also ignore the event if disabled; this happens in IE11
  4806. // under some circumstances, see #3666.
  4807. if (e._simulated || !this._enabled) { return; }
  4808. if (e.touches && e.touches.length > 1) {
  4809. this._moved = true;
  4810. return;
  4811. }
  4812. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4813. offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);
  4814. if (!offset.x && !offset.y) { return; }
  4815. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4816. // We assume that the parent container's position, border and scale do not change for the duration of the drag.
  4817. // Therefore there is no need to account for the position and border (they are eliminated by the subtraction)
  4818. // and we can use the cached value for the scale.
  4819. offset.x /= this._parentScale.x;
  4820. offset.y /= this._parentScale.y;
  4821. preventDefault(e);
  4822. if (!this._moved) {
  4823. // @event dragstart: Event
  4824. // Fired when a drag starts
  4825. this.fire('dragstart');
  4826. this._moved = true;
  4827. this._startPos = getPosition(this._element).subtract(offset);
  4828. addClass(document.body, 'leaflet-dragging');
  4829. this._lastTarget = e.target || e.srcElement;
  4830. // IE and Edge do not give the <use> element, so fetch it
  4831. // if necessary
  4832. if (window.SVGElementInstance && this._lastTarget instanceof window.SVGElementInstance) {
  4833. this._lastTarget = this._lastTarget.correspondingUseElement;
  4834. }
  4835. addClass(this._lastTarget, 'leaflet-drag-target');
  4836. }
  4837. this._newPos = this._startPos.add(offset);
  4838. this._moving = true;
  4839. cancelAnimFrame(this._animRequest);
  4840. this._lastEvent = e;
  4841. this._animRequest = requestAnimFrame(this._updatePosition, this, true);
  4842. },
  4843. _updatePosition: function () {
  4844. var e = {originalEvent: this._lastEvent};
  4845. // @event predrag: Event
  4846. // Fired continuously during dragging *before* each corresponding
  4847. // update of the element's position.
  4848. this.fire('predrag', e);
  4849. setPosition(this._element, this._newPos);
  4850. // @event drag: Event
  4851. // Fired continuously during dragging.
  4852. this.fire('drag', e);
  4853. },
  4854. _onUp: function (e) {
  4855. // Ignore simulated events, since we handle both touch and
  4856. // mouse explicitly; otherwise we risk getting duplicates of
  4857. // touch events, see #4315.
  4858. // Also ignore the event if disabled; this happens in IE11
  4859. // under some circumstances, see #3666.
  4860. if (e._simulated || !this._enabled) { return; }
  4861. this.finishDrag();
  4862. },
  4863. finishDrag: function () {
  4864. removeClass(document.body, 'leaflet-dragging');
  4865. if (this._lastTarget) {
  4866. removeClass(this._lastTarget, 'leaflet-drag-target');
  4867. this._lastTarget = null;
  4868. }
  4869. for (var i in MOVE) {
  4870. off(document, MOVE[i], this._onMove, this);
  4871. off(document, END[i], this._onUp, this);
  4872. }
  4873. enableImageDrag();
  4874. enableTextSelection();
  4875. if (this._moved && this._moving) {
  4876. // ensure drag is not fired after dragend
  4877. cancelAnimFrame(this._animRequest);
  4878. // @event dragend: DragEndEvent
  4879. // Fired when the drag ends.
  4880. this.fire('dragend', {
  4881. distance: this._newPos.distanceTo(this._startPos)
  4882. });
  4883. }
  4884. this._moving = false;
  4885. Draggable._dragging = false;
  4886. }
  4887. });
  4888. /*
  4889. * @namespace LineUtil
  4890. *
  4891. * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
  4892. */
  4893. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  4894. // Improves rendering performance dramatically by lessening the number of points to draw.
  4895. // @function simplify(points: Point[], tolerance: Number): Point[]
  4896. // Dramatically reduces the number of points in a polyline while retaining
  4897. // its shape and returns a new array of simplified points, using the
  4898. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  4899. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  4900. // each zoom level and also reducing visual noise. tolerance affects the amount of
  4901. // simplification (lesser value means higher quality but slower and with more points).
  4902. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  4903. function simplify(points, tolerance) {
  4904. if (!tolerance || !points.length) {
  4905. return points.slice();
  4906. }
  4907. var sqTolerance = tolerance * tolerance;
  4908. // stage 1: vertex reduction
  4909. points = _reducePoints(points, sqTolerance);
  4910. // stage 2: Douglas-Peucker simplification
  4911. points = _simplifyDP(points, sqTolerance);
  4912. return points;
  4913. }
  4914. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  4915. // Returns the distance between point `p` and segment `p1` to `p2`.
  4916. function pointToSegmentDistance(p, p1, p2) {
  4917. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  4918. }
  4919. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  4920. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  4921. function closestPointOnSegment(p, p1, p2) {
  4922. return _sqClosestPointOnSegment(p, p1, p2);
  4923. }
  4924. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  4925. function _simplifyDP(points, sqTolerance) {
  4926. var len = points.length,
  4927. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  4928. markers = new ArrayConstructor(len);
  4929. markers[0] = markers[len - 1] = 1;
  4930. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  4931. var i,
  4932. newPoints = [];
  4933. for (i = 0; i < len; i++) {
  4934. if (markers[i]) {
  4935. newPoints.push(points[i]);
  4936. }
  4937. }
  4938. return newPoints;
  4939. }
  4940. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  4941. var maxSqDist = 0,
  4942. index, i, sqDist;
  4943. for (i = first + 1; i <= last - 1; i++) {
  4944. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  4945. if (sqDist > maxSqDist) {
  4946. index = i;
  4947. maxSqDist = sqDist;
  4948. }
  4949. }
  4950. if (maxSqDist > sqTolerance) {
  4951. markers[index] = 1;
  4952. _simplifyDPStep(points, markers, sqTolerance, first, index);
  4953. _simplifyDPStep(points, markers, sqTolerance, index, last);
  4954. }
  4955. }
  4956. // reduce points that are too close to each other to a single point
  4957. function _reducePoints(points, sqTolerance) {
  4958. var reducedPoints = [points[0]];
  4959. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  4960. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  4961. reducedPoints.push(points[i]);
  4962. prev = i;
  4963. }
  4964. }
  4965. if (prev < len - 1) {
  4966. reducedPoints.push(points[len - 1]);
  4967. }
  4968. return reducedPoints;
  4969. }
  4970. var _lastCode;
  4971. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  4972. // Clips the segment a to b by rectangular bounds with the
  4973. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  4974. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  4975. // points that are on the screen or near, increasing performance.
  4976. function clipSegment(a, b, bounds, useLastCode, round) {
  4977. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  4978. codeB = _getBitCode(b, bounds),
  4979. codeOut, p, newCode;
  4980. // save 2nd code to avoid calculating it on the next segment
  4981. _lastCode = codeB;
  4982. while (true) {
  4983. // if a,b is inside the clip window (trivial accept)
  4984. if (!(codeA | codeB)) {
  4985. return [a, b];
  4986. }
  4987. // if a,b is outside the clip window (trivial reject)
  4988. if (codeA & codeB) {
  4989. return false;
  4990. }
  4991. // other cases
  4992. codeOut = codeA || codeB;
  4993. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  4994. newCode = _getBitCode(p, bounds);
  4995. if (codeOut === codeA) {
  4996. a = p;
  4997. codeA = newCode;
  4998. } else {
  4999. b = p;
  5000. codeB = newCode;
  5001. }
  5002. }
  5003. }
  5004. function _getEdgeIntersection(a, b, code, bounds, round) {
  5005. var dx = b.x - a.x,
  5006. dy = b.y - a.y,
  5007. min = bounds.min,
  5008. max = bounds.max,
  5009. x, y;
  5010. if (code & 8) { // top
  5011. x = a.x + dx * (max.y - a.y) / dy;
  5012. y = max.y;
  5013. } else if (code & 4) { // bottom
  5014. x = a.x + dx * (min.y - a.y) / dy;
  5015. y = min.y;
  5016. } else if (code & 2) { // right
  5017. x = max.x;
  5018. y = a.y + dy * (max.x - a.x) / dx;
  5019. } else if (code & 1) { // left
  5020. x = min.x;
  5021. y = a.y + dy * (min.x - a.x) / dx;
  5022. }
  5023. return new Point(x, y, round);
  5024. }
  5025. function _getBitCode(p, bounds) {
  5026. var code = 0;
  5027. if (p.x < bounds.min.x) { // left
  5028. code |= 1;
  5029. } else if (p.x > bounds.max.x) { // right
  5030. code |= 2;
  5031. }
  5032. if (p.y < bounds.min.y) { // bottom
  5033. code |= 4;
  5034. } else if (p.y > bounds.max.y) { // top
  5035. code |= 8;
  5036. }
  5037. return code;
  5038. }
  5039. // square distance (to avoid unnecessary Math.sqrt calls)
  5040. function _sqDist(p1, p2) {
  5041. var dx = p2.x - p1.x,
  5042. dy = p2.y - p1.y;
  5043. return dx * dx + dy * dy;
  5044. }
  5045. // return closest point on segment or distance to that point
  5046. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  5047. var x = p1.x,
  5048. y = p1.y,
  5049. dx = p2.x - x,
  5050. dy = p2.y - y,
  5051. dot = dx * dx + dy * dy,
  5052. t;
  5053. if (dot > 0) {
  5054. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  5055. if (t > 1) {
  5056. x = p2.x;
  5057. y = p2.y;
  5058. } else if (t > 0) {
  5059. x += dx * t;
  5060. y += dy * t;
  5061. }
  5062. }
  5063. dx = p.x - x;
  5064. dy = p.y - y;
  5065. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  5066. }
  5067. // @function isFlat(latlngs: LatLng[]): Boolean
  5068. // Returns true if `latlngs` is a flat array, false is nested.
  5069. function isFlat(latlngs) {
  5070. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  5071. }
  5072. function _flat(latlngs) {
  5073. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  5074. return isFlat(latlngs);
  5075. }
  5076. var LineUtil = ({
  5077. simplify: simplify,
  5078. pointToSegmentDistance: pointToSegmentDistance,
  5079. closestPointOnSegment: closestPointOnSegment,
  5080. clipSegment: clipSegment,
  5081. _getEdgeIntersection: _getEdgeIntersection,
  5082. _getBitCode: _getBitCode,
  5083. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5084. isFlat: isFlat,
  5085. _flat: _flat
  5086. });
  5087. /*
  5088. * @namespace PolyUtil
  5089. * Various utility functions for polygon geometries.
  5090. */
  5091. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5092. * 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)).
  5093. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5094. * performance. Note that polygon points needs different algorithm for clipping
  5095. * than polyline, so there's a separate method for it.
  5096. */
  5097. function clipPolygon(points, bounds, round) {
  5098. var clippedPoints,
  5099. edges = [1, 4, 2, 8],
  5100. i, j, k,
  5101. a, b,
  5102. len, edge, p;
  5103. for (i = 0, len = points.length; i < len; i++) {
  5104. points[i]._code = _getBitCode(points[i], bounds);
  5105. }
  5106. // for each edge (left, bottom, right, top)
  5107. for (k = 0; k < 4; k++) {
  5108. edge = edges[k];
  5109. clippedPoints = [];
  5110. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5111. a = points[i];
  5112. b = points[j];
  5113. // if a is inside the clip window
  5114. if (!(a._code & edge)) {
  5115. // if b is outside the clip window (a->b goes out of screen)
  5116. if (b._code & edge) {
  5117. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5118. p._code = _getBitCode(p, bounds);
  5119. clippedPoints.push(p);
  5120. }
  5121. clippedPoints.push(a);
  5122. // else if b is inside the clip window (a->b enters the screen)
  5123. } else if (!(b._code & edge)) {
  5124. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5125. p._code = _getBitCode(p, bounds);
  5126. clippedPoints.push(p);
  5127. }
  5128. }
  5129. points = clippedPoints;
  5130. }
  5131. return points;
  5132. }
  5133. var PolyUtil = ({
  5134. clipPolygon: clipPolygon
  5135. });
  5136. /*
  5137. * @namespace Projection
  5138. * @section
  5139. * Leaflet comes with a set of already defined Projections out of the box:
  5140. *
  5141. * @projection L.Projection.LonLat
  5142. *
  5143. * Equirectangular, or Plate Carree projection — the most simple projection,
  5144. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5145. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5146. * `EPSG:4326` and `Simple` CRS.
  5147. */
  5148. var LonLat = {
  5149. project: function (latlng) {
  5150. return new Point(latlng.lng, latlng.lat);
  5151. },
  5152. unproject: function (point) {
  5153. return new LatLng(point.y, point.x);
  5154. },
  5155. bounds: new Bounds([-180, -90], [180, 90])
  5156. };
  5157. /*
  5158. * @namespace Projection
  5159. * @projection L.Projection.Mercator
  5160. *
  5161. * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.
  5162. */
  5163. var Mercator = {
  5164. R: 6378137,
  5165. R_MINOR: 6356752.314245179,
  5166. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5167. project: function (latlng) {
  5168. var d = Math.PI / 180,
  5169. r = this.R,
  5170. y = latlng.lat * d,
  5171. tmp = this.R_MINOR / r,
  5172. e = Math.sqrt(1 - tmp * tmp),
  5173. con = e * Math.sin(y);
  5174. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5175. y = -r * Math.log(Math.max(ts, 1E-10));
  5176. return new Point(latlng.lng * d * r, y);
  5177. },
  5178. unproject: function (point) {
  5179. var d = 180 / Math.PI,
  5180. r = this.R,
  5181. tmp = this.R_MINOR / r,
  5182. e = Math.sqrt(1 - tmp * tmp),
  5183. ts = Math.exp(-point.y / r),
  5184. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5185. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5186. con = e * Math.sin(phi);
  5187. con = Math.pow((1 - con) / (1 + con), e / 2);
  5188. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5189. phi += dphi;
  5190. }
  5191. return new LatLng(phi * d, point.x * d / r);
  5192. }
  5193. };
  5194. /*
  5195. * @class Projection
  5196. * An object with methods for projecting geographical coordinates of the world onto
  5197. * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).
  5198. * @property bounds: Bounds
  5199. * The bounds (specified in CRS units) where the projection is valid
  5200. * @method project(latlng: LatLng): Point
  5201. * Projects geographical coordinates into a 2D point.
  5202. * Only accepts actual `L.LatLng` instances, not arrays.
  5203. * @method unproject(point: Point): LatLng
  5204. * The inverse of `project`. Projects a 2D point into a geographical location.
  5205. * Only accepts actual `L.Point` instances, not arrays.
  5206. * Note that the projection instances do not inherit from Leaflet's `Class` object,
  5207. * and can't be instantiated. Also, new classes can't inherit from them,
  5208. * and methods can't be added to them with the `include` function.
  5209. */
  5210. var index = ({
  5211. LonLat: LonLat,
  5212. Mercator: Mercator,
  5213. SphericalMercator: SphericalMercator
  5214. });
  5215. /*
  5216. * @namespace CRS
  5217. * @crs L.CRS.EPSG3395
  5218. *
  5219. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5220. */
  5221. var EPSG3395 = extend({}, Earth, {
  5222. code: 'EPSG:3395',
  5223. projection: Mercator,
  5224. transformation: (function () {
  5225. var scale = 0.5 / (Math.PI * Mercator.R);
  5226. return toTransformation(scale, 0.5, -scale, 0.5);
  5227. }())
  5228. });
  5229. /*
  5230. * @namespace CRS
  5231. * @crs L.CRS.EPSG4326
  5232. *
  5233. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5234. *
  5235. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5236. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5237. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5238. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5239. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5240. */
  5241. var EPSG4326 = extend({}, Earth, {
  5242. code: 'EPSG:4326',
  5243. projection: LonLat,
  5244. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5245. });
  5246. /*
  5247. * @namespace CRS
  5248. * @crs L.CRS.Simple
  5249. *
  5250. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5251. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5252. * axis should still be inverted (going from bottom to top). `distance()` returns
  5253. * simple euclidean distance.
  5254. */
  5255. var Simple = extend({}, CRS, {
  5256. projection: LonLat,
  5257. transformation: toTransformation(1, 0, -1, 0),
  5258. scale: function (zoom) {
  5259. return Math.pow(2, zoom);
  5260. },
  5261. zoom: function (scale) {
  5262. return Math.log(scale) / Math.LN2;
  5263. },
  5264. distance: function (latlng1, latlng2) {
  5265. var dx = latlng2.lng - latlng1.lng,
  5266. dy = latlng2.lat - latlng1.lat;
  5267. return Math.sqrt(dx * dx + dy * dy);
  5268. },
  5269. infinite: true
  5270. });
  5271. CRS.Earth = Earth;
  5272. CRS.EPSG3395 = EPSG3395;
  5273. CRS.EPSG3857 = EPSG3857;
  5274. CRS.EPSG900913 = EPSG900913;
  5275. CRS.EPSG4326 = EPSG4326;
  5276. CRS.Simple = Simple;
  5277. /*
  5278. * @class Layer
  5279. * @inherits Evented
  5280. * @aka L.Layer
  5281. * @aka ILayer
  5282. *
  5283. * A set of methods from the Layer base class that all Leaflet layers use.
  5284. * Inherits all methods, options and events from `L.Evented`.
  5285. *
  5286. * @example
  5287. *
  5288. * ```js
  5289. * var layer = L.marker(latlng).addTo(map);
  5290. * layer.addTo(map);
  5291. * layer.remove();
  5292. * ```
  5293. *
  5294. * @event add: Event
  5295. * Fired after the layer is added to a map
  5296. *
  5297. * @event remove: Event
  5298. * Fired after the layer is removed from a map
  5299. */
  5300. var Layer = Evented.extend({
  5301. // Classes extending `L.Layer` will inherit the following options:
  5302. options: {
  5303. // @option pane: String = 'overlayPane'
  5304. // 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.
  5305. pane: 'overlayPane',
  5306. // @option attribution: String = null
  5307. // 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.
  5308. attribution: null,
  5309. bubblingMouseEvents: true
  5310. },
  5311. /* @section
  5312. * Classes extending `L.Layer` will inherit the following methods:
  5313. *
  5314. * @method addTo(map: Map|LayerGroup): this
  5315. * Adds the layer to the given map or layer group.
  5316. */
  5317. addTo: function (map) {
  5318. map.addLayer(this);
  5319. return this;
  5320. },
  5321. // @method remove: this
  5322. // Removes the layer from the map it is currently active on.
  5323. remove: function () {
  5324. return this.removeFrom(this._map || this._mapToAdd);
  5325. },
  5326. // @method removeFrom(map: Map): this
  5327. // Removes the layer from the given map
  5328. //
  5329. // @alternative
  5330. // @method removeFrom(group: LayerGroup): this
  5331. // Removes the layer from the given `LayerGroup`
  5332. removeFrom: function (obj) {
  5333. if (obj) {
  5334. obj.removeLayer(this);
  5335. }
  5336. return this;
  5337. },
  5338. // @method getPane(name? : String): HTMLElement
  5339. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5340. getPane: function (name) {
  5341. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5342. },
  5343. addInteractiveTarget: function (targetEl) {
  5344. this._map._targets[stamp(targetEl)] = this;
  5345. return this;
  5346. },
  5347. removeInteractiveTarget: function (targetEl) {
  5348. delete this._map._targets[stamp(targetEl)];
  5349. return this;
  5350. },
  5351. // @method getAttribution: String
  5352. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5353. getAttribution: function () {
  5354. return this.options.attribution;
  5355. },
  5356. _layerAdd: function (e) {
  5357. var map = e.target;
  5358. // check in case layer gets added and then removed before the map is ready
  5359. if (!map.hasLayer(this)) { return; }
  5360. this._map = map;
  5361. this._zoomAnimated = map._zoomAnimated;
  5362. if (this.getEvents) {
  5363. var events = this.getEvents();
  5364. map.on(events, this);
  5365. this.once('remove', function () {
  5366. map.off(events, this);
  5367. }, this);
  5368. }
  5369. this.onAdd(map);
  5370. if (this.getAttribution && map.attributionControl) {
  5371. map.attributionControl.addAttribution(this.getAttribution());
  5372. }
  5373. this.fire('add');
  5374. map.fire('layeradd', {layer: this});
  5375. }
  5376. });
  5377. /* @section Extension methods
  5378. * @uninheritable
  5379. *
  5380. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5381. *
  5382. * @method onAdd(map: Map): this
  5383. * 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).
  5384. *
  5385. * @method onRemove(map: Map): this
  5386. * 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).
  5387. *
  5388. * @method getEvents(): Object
  5389. * 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.
  5390. *
  5391. * @method getAttribution(): String
  5392. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5393. *
  5394. * @method beforeAdd(map: Map): this
  5395. * 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.
  5396. */
  5397. /* @namespace Map
  5398. * @section Layer events
  5399. *
  5400. * @event layeradd: LayerEvent
  5401. * Fired when a new layer is added to the map.
  5402. *
  5403. * @event layerremove: LayerEvent
  5404. * Fired when some layer is removed from the map
  5405. *
  5406. * @section Methods for Layers and Controls
  5407. */
  5408. Map.include({
  5409. // @method addLayer(layer: Layer): this
  5410. // Adds the given layer to the map
  5411. addLayer: function (layer) {
  5412. if (!layer._layerAdd) {
  5413. throw new Error('The provided object is not a Layer.');
  5414. }
  5415. var id = stamp(layer);
  5416. if (this._layers[id]) { return this; }
  5417. this._layers[id] = layer;
  5418. layer._mapToAdd = this;
  5419. if (layer.beforeAdd) {
  5420. layer.beforeAdd(this);
  5421. }
  5422. this.whenReady(layer._layerAdd, layer);
  5423. return this;
  5424. },
  5425. // @method removeLayer(layer: Layer): this
  5426. // Removes the given layer from the map.
  5427. removeLayer: function (layer) {
  5428. var id = stamp(layer);
  5429. if (!this._layers[id]) { return this; }
  5430. if (this._loaded) {
  5431. layer.onRemove(this);
  5432. }
  5433. if (layer.getAttribution && this.attributionControl) {
  5434. this.attributionControl.removeAttribution(layer.getAttribution());
  5435. }
  5436. delete this._layers[id];
  5437. if (this._loaded) {
  5438. this.fire('layerremove', {layer: layer});
  5439. layer.fire('remove');
  5440. }
  5441. layer._map = layer._mapToAdd = null;
  5442. return this;
  5443. },
  5444. // @method hasLayer(layer: Layer): Boolean
  5445. // Returns `true` if the given layer is currently added to the map
  5446. hasLayer: function (layer) {
  5447. return !!layer && (stamp(layer) in this._layers);
  5448. },
  5449. /* @method eachLayer(fn: Function, context?: Object): this
  5450. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5451. * ```
  5452. * map.eachLayer(function(layer){
  5453. * layer.bindPopup('Hello');
  5454. * });
  5455. * ```
  5456. */
  5457. eachLayer: function (method, context) {
  5458. for (var i in this._layers) {
  5459. method.call(context, this._layers[i]);
  5460. }
  5461. return this;
  5462. },
  5463. _addLayers: function (layers) {
  5464. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5465. for (var i = 0, len = layers.length; i < len; i++) {
  5466. this.addLayer(layers[i]);
  5467. }
  5468. },
  5469. _addZoomLimit: function (layer) {
  5470. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5471. this._zoomBoundLayers[stamp(layer)] = layer;
  5472. this._updateZoomLevels();
  5473. }
  5474. },
  5475. _removeZoomLimit: function (layer) {
  5476. var id = stamp(layer);
  5477. if (this._zoomBoundLayers[id]) {
  5478. delete this._zoomBoundLayers[id];
  5479. this._updateZoomLevels();
  5480. }
  5481. },
  5482. _updateZoomLevels: function () {
  5483. var minZoom = Infinity,
  5484. maxZoom = -Infinity,
  5485. oldZoomSpan = this._getZoomSpan();
  5486. for (var i in this._zoomBoundLayers) {
  5487. var options = this._zoomBoundLayers[i].options;
  5488. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5489. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5490. }
  5491. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5492. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5493. // @section Map state change events
  5494. // @event zoomlevelschange: Event
  5495. // Fired when the number of zoomlevels on the map is changed due
  5496. // to adding or removing a layer.
  5497. if (oldZoomSpan !== this._getZoomSpan()) {
  5498. this.fire('zoomlevelschange');
  5499. }
  5500. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5501. this.setZoom(this._layersMaxZoom);
  5502. }
  5503. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5504. this.setZoom(this._layersMinZoom);
  5505. }
  5506. }
  5507. });
  5508. /*
  5509. * @class LayerGroup
  5510. * @aka L.LayerGroup
  5511. * @inherits Layer
  5512. *
  5513. * Used to group several layers and handle them as one. If you add it to the map,
  5514. * any layers added or removed from the group will be added/removed on the map as
  5515. * well. Extends `Layer`.
  5516. *
  5517. * @example
  5518. *
  5519. * ```js
  5520. * L.layerGroup([marker1, marker2])
  5521. * .addLayer(polyline)
  5522. * .addTo(map);
  5523. * ```
  5524. */
  5525. var LayerGroup = Layer.extend({
  5526. initialize: function (layers, options) {
  5527. setOptions(this, options);
  5528. this._layers = {};
  5529. var i, len;
  5530. if (layers) {
  5531. for (i = 0, len = layers.length; i < len; i++) {
  5532. this.addLayer(layers[i]);
  5533. }
  5534. }
  5535. },
  5536. // @method addLayer(layer: Layer): this
  5537. // Adds the given layer to the group.
  5538. addLayer: function (layer) {
  5539. var id = this.getLayerId(layer);
  5540. this._layers[id] = layer;
  5541. if (this._map) {
  5542. this._map.addLayer(layer);
  5543. }
  5544. return this;
  5545. },
  5546. // @method removeLayer(layer: Layer): this
  5547. // Removes the given layer from the group.
  5548. // @alternative
  5549. // @method removeLayer(id: Number): this
  5550. // Removes the layer with the given internal ID from the group.
  5551. removeLayer: function (layer) {
  5552. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5553. if (this._map && this._layers[id]) {
  5554. this._map.removeLayer(this._layers[id]);
  5555. }
  5556. delete this._layers[id];
  5557. return this;
  5558. },
  5559. // @method hasLayer(layer: Layer): Boolean
  5560. // Returns `true` if the given layer is currently added to the group.
  5561. // @alternative
  5562. // @method hasLayer(id: Number): Boolean
  5563. // Returns `true` if the given internal ID is currently added to the group.
  5564. hasLayer: function (layer) {
  5565. if (!layer) { return false; }
  5566. var layerId = typeof layer === 'number' ? layer : this.getLayerId(layer);
  5567. return layerId in this._layers;
  5568. },
  5569. // @method clearLayers(): this
  5570. // Removes all the layers from the group.
  5571. clearLayers: function () {
  5572. return this.eachLayer(this.removeLayer, this);
  5573. },
  5574. // @method invoke(methodName: String, …): this
  5575. // Calls `methodName` on every layer contained in this group, passing any
  5576. // additional parameters. Has no effect if the layers contained do not
  5577. // implement `methodName`.
  5578. invoke: function (methodName) {
  5579. var args = Array.prototype.slice.call(arguments, 1),
  5580. i, layer;
  5581. for (i in this._layers) {
  5582. layer = this._layers[i];
  5583. if (layer[methodName]) {
  5584. layer[methodName].apply(layer, args);
  5585. }
  5586. }
  5587. return this;
  5588. },
  5589. onAdd: function (map) {
  5590. this.eachLayer(map.addLayer, map);
  5591. },
  5592. onRemove: function (map) {
  5593. this.eachLayer(map.removeLayer, map);
  5594. },
  5595. // @method eachLayer(fn: Function, context?: Object): this
  5596. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5597. // ```js
  5598. // group.eachLayer(function (layer) {
  5599. // layer.bindPopup('Hello');
  5600. // });
  5601. // ```
  5602. eachLayer: function (method, context) {
  5603. for (var i in this._layers) {
  5604. method.call(context, this._layers[i]);
  5605. }
  5606. return this;
  5607. },
  5608. // @method getLayer(id: Number): Layer
  5609. // Returns the layer with the given internal ID.
  5610. getLayer: function (id) {
  5611. return this._layers[id];
  5612. },
  5613. // @method getLayers(): Layer[]
  5614. // Returns an array of all the layers added to the group.
  5615. getLayers: function () {
  5616. var layers = [];
  5617. this.eachLayer(layers.push, layers);
  5618. return layers;
  5619. },
  5620. // @method setZIndex(zIndex: Number): this
  5621. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5622. setZIndex: function (zIndex) {
  5623. return this.invoke('setZIndex', zIndex);
  5624. },
  5625. // @method getLayerId(layer: Layer): Number
  5626. // Returns the internal ID for a layer
  5627. getLayerId: function (layer) {
  5628. return stamp(layer);
  5629. }
  5630. });
  5631. // @factory L.layerGroup(layers?: Layer[], options?: Object)
  5632. // Create a layer group, optionally given an initial set of layers and an `options` object.
  5633. var layerGroup = function (layers, options) {
  5634. return new LayerGroup(layers, options);
  5635. };
  5636. /*
  5637. * @class FeatureGroup
  5638. * @aka L.FeatureGroup
  5639. * @inherits LayerGroup
  5640. *
  5641. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5642. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5643. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5644. * handler, it will handle events from any of the layers. This includes mouse events
  5645. * and custom events.
  5646. * * Has `layeradd` and `layerremove` events
  5647. *
  5648. * @example
  5649. *
  5650. * ```js
  5651. * L.featureGroup([marker1, marker2, polyline])
  5652. * .bindPopup('Hello world!')
  5653. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5654. * .addTo(map);
  5655. * ```
  5656. */
  5657. var FeatureGroup = LayerGroup.extend({
  5658. addLayer: function (layer) {
  5659. if (this.hasLayer(layer)) {
  5660. return this;
  5661. }
  5662. layer.addEventParent(this);
  5663. LayerGroup.prototype.addLayer.call(this, layer);
  5664. // @event layeradd: LayerEvent
  5665. // Fired when a layer is added to this `FeatureGroup`
  5666. return this.fire('layeradd', {layer: layer});
  5667. },
  5668. removeLayer: function (layer) {
  5669. if (!this.hasLayer(layer)) {
  5670. return this;
  5671. }
  5672. if (layer in this._layers) {
  5673. layer = this._layers[layer];
  5674. }
  5675. layer.removeEventParent(this);
  5676. LayerGroup.prototype.removeLayer.call(this, layer);
  5677. // @event layerremove: LayerEvent
  5678. // Fired when a layer is removed from this `FeatureGroup`
  5679. return this.fire('layerremove', {layer: layer});
  5680. },
  5681. // @method setStyle(style: Path options): this
  5682. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5683. setStyle: function (style) {
  5684. return this.invoke('setStyle', style);
  5685. },
  5686. // @method bringToFront(): this
  5687. // Brings the layer group to the top of all other layers
  5688. bringToFront: function () {
  5689. return this.invoke('bringToFront');
  5690. },
  5691. // @method bringToBack(): this
  5692. // Brings the layer group to the back of all other layers
  5693. bringToBack: function () {
  5694. return this.invoke('bringToBack');
  5695. },
  5696. // @method getBounds(): LatLngBounds
  5697. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5698. getBounds: function () {
  5699. var bounds = new LatLngBounds();
  5700. for (var id in this._layers) {
  5701. var layer = this._layers[id];
  5702. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5703. }
  5704. return bounds;
  5705. }
  5706. });
  5707. // @factory L.featureGroup(layers?: Layer[], options?: Object)
  5708. // Create a feature group, optionally given an initial set of layers and an `options` object.
  5709. var featureGroup = function (layers, options) {
  5710. return new FeatureGroup(layers, options);
  5711. };
  5712. /*
  5713. * @class Icon
  5714. * @aka L.Icon
  5715. *
  5716. * Represents an icon to provide when creating a marker.
  5717. *
  5718. * @example
  5719. *
  5720. * ```js
  5721. * var myIcon = L.icon({
  5722. * iconUrl: 'my-icon.png',
  5723. * iconRetinaUrl: 'my-icon@2x.png',
  5724. * iconSize: [38, 95],
  5725. * iconAnchor: [22, 94],
  5726. * popupAnchor: [-3, -76],
  5727. * shadowUrl: 'my-icon-shadow.png',
  5728. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5729. * shadowSize: [68, 95],
  5730. * shadowAnchor: [22, 94]
  5731. * });
  5732. *
  5733. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5734. * ```
  5735. *
  5736. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5737. *
  5738. */
  5739. var Icon = Class.extend({
  5740. /* @section
  5741. * @aka Icon options
  5742. *
  5743. * @option iconUrl: String = null
  5744. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5745. *
  5746. * @option iconRetinaUrl: String = null
  5747. * The URL to a retina sized version of the icon image (absolute or relative to your
  5748. * script path). Used for Retina screen devices.
  5749. *
  5750. * @option iconSize: Point = null
  5751. * Size of the icon image in pixels.
  5752. *
  5753. * @option iconAnchor: Point = null
  5754. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5755. * will be aligned so that this point is at the marker's geographical location. Centered
  5756. * by default if size is specified, also can be set in CSS with negative margins.
  5757. *
  5758. * @option popupAnchor: Point = [0, 0]
  5759. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5760. *
  5761. * @option tooltipAnchor: Point = [0, 0]
  5762. * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
  5763. *
  5764. * @option shadowUrl: String = null
  5765. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  5766. *
  5767. * @option shadowRetinaUrl: String = null
  5768. *
  5769. * @option shadowSize: Point = null
  5770. * Size of the shadow image in pixels.
  5771. *
  5772. * @option shadowAnchor: Point = null
  5773. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  5774. * as iconAnchor if not specified).
  5775. *
  5776. * @option className: String = ''
  5777. * A custom class name to assign to both icon and shadow images. Empty by default.
  5778. */
  5779. options: {
  5780. popupAnchor: [0, 0],
  5781. tooltipAnchor: [0, 0]
  5782. },
  5783. initialize: function (options) {
  5784. setOptions(this, options);
  5785. },
  5786. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  5787. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  5788. // styled according to the options.
  5789. createIcon: function (oldIcon) {
  5790. return this._createIcon('icon', oldIcon);
  5791. },
  5792. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  5793. // As `createIcon`, but for the shadow beneath it.
  5794. createShadow: function (oldIcon) {
  5795. return this._createIcon('shadow', oldIcon);
  5796. },
  5797. _createIcon: function (name, oldIcon) {
  5798. var src = this._getIconUrl(name);
  5799. if (!src) {
  5800. if (name === 'icon') {
  5801. throw new Error('iconUrl not set in Icon options (see the docs).');
  5802. }
  5803. return null;
  5804. }
  5805. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  5806. this._setIconStyles(img, name);
  5807. return img;
  5808. },
  5809. _setIconStyles: function (img, name) {
  5810. var options = this.options;
  5811. var sizeOption = options[name + 'Size'];
  5812. if (typeof sizeOption === 'number') {
  5813. sizeOption = [sizeOption, sizeOption];
  5814. }
  5815. var size = toPoint(sizeOption),
  5816. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  5817. size && size.divideBy(2, true));
  5818. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  5819. if (anchor) {
  5820. img.style.marginLeft = (-anchor.x) + 'px';
  5821. img.style.marginTop = (-anchor.y) + 'px';
  5822. }
  5823. if (size) {
  5824. img.style.width = size.x + 'px';
  5825. img.style.height = size.y + 'px';
  5826. }
  5827. },
  5828. _createImg: function (src, el) {
  5829. el = el || document.createElement('img');
  5830. el.src = src;
  5831. return el;
  5832. },
  5833. _getIconUrl: function (name) {
  5834. return retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  5835. }
  5836. });
  5837. // @factory L.icon(options: Icon options)
  5838. // Creates an icon instance with the given options.
  5839. function icon(options) {
  5840. return new Icon(options);
  5841. }
  5842. /*
  5843. * @miniclass Icon.Default (Icon)
  5844. * @aka L.Icon.Default
  5845. * @section
  5846. *
  5847. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  5848. * no icon is specified. Points to the blue marker image distributed with Leaflet
  5849. * releases.
  5850. *
  5851. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  5852. * (which is a set of `Icon options`).
  5853. *
  5854. * If you want to _completely_ replace the default icon, override the
  5855. * `L.Marker.prototype.options.icon` with your own icon instead.
  5856. */
  5857. var IconDefault = Icon.extend({
  5858. options: {
  5859. iconUrl: 'marker-icon.png',
  5860. iconRetinaUrl: 'marker-icon-2x.png',
  5861. shadowUrl: 'marker-shadow.png',
  5862. iconSize: [25, 41],
  5863. iconAnchor: [12, 41],
  5864. popupAnchor: [1, -34],
  5865. tooltipAnchor: [16, -28],
  5866. shadowSize: [41, 41]
  5867. },
  5868. _getIconUrl: function (name) {
  5869. if (!IconDefault.imagePath) { // Deprecated, backwards-compatibility only
  5870. IconDefault.imagePath = this._detectIconPath();
  5871. }
  5872. // @option imagePath: String
  5873. // `Icon.Default` will try to auto-detect the location of the
  5874. // blue icon images. If you are placing these images in a non-standard
  5875. // way, set this option to point to the right path.
  5876. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  5877. },
  5878. _detectIconPath: function () {
  5879. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  5880. var path = getStyle(el, 'background-image') ||
  5881. getStyle(el, 'backgroundImage'); // IE8
  5882. document.body.removeChild(el);
  5883. if (path === null || path.indexOf('url') !== 0) {
  5884. path = '';
  5885. } else {
  5886. path = path.replace(/^url\(["']?/, '').replace(/marker-icon\.png["']?\)$/, '');
  5887. }
  5888. return path;
  5889. }
  5890. });
  5891. /*
  5892. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  5893. */
  5894. /* @namespace Marker
  5895. * @section Interaction handlers
  5896. *
  5897. * 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:
  5898. *
  5899. * ```js
  5900. * marker.dragging.disable();
  5901. * ```
  5902. *
  5903. * @property dragging: Handler
  5904. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  5905. */
  5906. var MarkerDrag = Handler.extend({
  5907. initialize: function (marker) {
  5908. this._marker = marker;
  5909. },
  5910. addHooks: function () {
  5911. var icon = this._marker._icon;
  5912. if (!this._draggable) {
  5913. this._draggable = new Draggable(icon, icon, true);
  5914. }
  5915. this._draggable.on({
  5916. dragstart: this._onDragStart,
  5917. predrag: this._onPreDrag,
  5918. drag: this._onDrag,
  5919. dragend: this._onDragEnd
  5920. }, this).enable();
  5921. addClass(icon, 'leaflet-marker-draggable');
  5922. },
  5923. removeHooks: function () {
  5924. this._draggable.off({
  5925. dragstart: this._onDragStart,
  5926. predrag: this._onPreDrag,
  5927. drag: this._onDrag,
  5928. dragend: this._onDragEnd
  5929. }, this).disable();
  5930. if (this._marker._icon) {
  5931. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  5932. }
  5933. },
  5934. moved: function () {
  5935. return this._draggable && this._draggable._moved;
  5936. },
  5937. _adjustPan: function (e) {
  5938. var marker = this._marker,
  5939. map = marker._map,
  5940. speed = this._marker.options.autoPanSpeed,
  5941. padding = this._marker.options.autoPanPadding,
  5942. iconPos = getPosition(marker._icon),
  5943. bounds = map.getPixelBounds(),
  5944. origin = map.getPixelOrigin();
  5945. var panBounds = toBounds(
  5946. bounds.min._subtract(origin).add(padding),
  5947. bounds.max._subtract(origin).subtract(padding)
  5948. );
  5949. if (!panBounds.contains(iconPos)) {
  5950. // Compute incremental movement
  5951. var movement = toPoint(
  5952. (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
  5953. (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
  5954. (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
  5955. (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
  5956. ).multiplyBy(speed);
  5957. map.panBy(movement, {animate: false});
  5958. this._draggable._newPos._add(movement);
  5959. this._draggable._startPos._add(movement);
  5960. setPosition(marker._icon, this._draggable._newPos);
  5961. this._onDrag(e);
  5962. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  5963. }
  5964. },
  5965. _onDragStart: function () {
  5966. // @section Dragging events
  5967. // @event dragstart: Event
  5968. // Fired when the user starts dragging the marker.
  5969. // @event movestart: Event
  5970. // Fired when the marker starts moving (because of dragging).
  5971. this._oldLatLng = this._marker.getLatLng();
  5972. // When using ES6 imports it could not be set when `Popup` was not imported as well
  5973. this._marker.closePopup && this._marker.closePopup();
  5974. this._marker
  5975. .fire('movestart')
  5976. .fire('dragstart');
  5977. },
  5978. _onPreDrag: function (e) {
  5979. if (this._marker.options.autoPan) {
  5980. cancelAnimFrame(this._panRequest);
  5981. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  5982. }
  5983. },
  5984. _onDrag: function (e) {
  5985. var marker = this._marker,
  5986. shadow = marker._shadow,
  5987. iconPos = getPosition(marker._icon),
  5988. latlng = marker._map.layerPointToLatLng(iconPos);
  5989. // update shadow position
  5990. if (shadow) {
  5991. setPosition(shadow, iconPos);
  5992. }
  5993. marker._latlng = latlng;
  5994. e.latlng = latlng;
  5995. e.oldLatLng = this._oldLatLng;
  5996. // @event drag: Event
  5997. // Fired repeatedly while the user drags the marker.
  5998. marker
  5999. .fire('move', e)
  6000. .fire('drag', e);
  6001. },
  6002. _onDragEnd: function (e) {
  6003. // @event dragend: DragEndEvent
  6004. // Fired when the user stops dragging the marker.
  6005. cancelAnimFrame(this._panRequest);
  6006. // @event moveend: Event
  6007. // Fired when the marker stops moving (because of dragging).
  6008. delete this._oldLatLng;
  6009. this._marker
  6010. .fire('moveend')
  6011. .fire('dragend', e);
  6012. }
  6013. });
  6014. /*
  6015. * @class Marker
  6016. * @inherits Interactive layer
  6017. * @aka L.Marker
  6018. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  6019. *
  6020. * @example
  6021. *
  6022. * ```js
  6023. * L.marker([50.5, 30.5]).addTo(map);
  6024. * ```
  6025. */
  6026. var Marker = Layer.extend({
  6027. // @section
  6028. // @aka Marker options
  6029. options: {
  6030. // @option icon: Icon = *
  6031. // Icon instance to use for rendering the marker.
  6032. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  6033. // If not specified, a common instance of `L.Icon.Default` is used.
  6034. icon: new IconDefault(),
  6035. // Option inherited from "Interactive layer" abstract class
  6036. interactive: true,
  6037. // @option keyboard: Boolean = true
  6038. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  6039. keyboard: true,
  6040. // @option title: String = ''
  6041. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  6042. title: '',
  6043. // @option alt: String = ''
  6044. // Text for the `alt` attribute of the icon image (useful for accessibility).
  6045. alt: '',
  6046. // @option zIndexOffset: Number = 0
  6047. // 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).
  6048. zIndexOffset: 0,
  6049. // @option opacity: Number = 1.0
  6050. // The opacity of the marker.
  6051. opacity: 1,
  6052. // @option riseOnHover: Boolean = false
  6053. // If `true`, the marker will get on top of others when you hover the mouse over it.
  6054. riseOnHover: false,
  6055. // @option riseOffset: Number = 250
  6056. // The z-index offset used for the `riseOnHover` feature.
  6057. riseOffset: 250,
  6058. // @option pane: String = 'markerPane'
  6059. // `Map pane` where the markers icon will be added.
  6060. pane: 'markerPane',
  6061. // @option shadowPane: String = 'shadowPane'
  6062. // `Map pane` where the markers shadow will be added.
  6063. shadowPane: 'shadowPane',
  6064. // @option bubblingMouseEvents: Boolean = false
  6065. // When `true`, a mouse event on this marker will trigger the same event on the map
  6066. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6067. bubblingMouseEvents: false,
  6068. // @section Draggable marker options
  6069. // @option draggable: Boolean = false
  6070. // Whether the marker is draggable with mouse/touch or not.
  6071. draggable: false,
  6072. // @option autoPan: Boolean = false
  6073. // Whether to pan the map when dragging this marker near its edge or not.
  6074. autoPan: false,
  6075. // @option autoPanPadding: Point = Point(50, 50)
  6076. // Distance (in pixels to the left/right and to the top/bottom) of the
  6077. // map edge to start panning the map.
  6078. autoPanPadding: [50, 50],
  6079. // @option autoPanSpeed: Number = 10
  6080. // Number of pixels the map should pan by.
  6081. autoPanSpeed: 10
  6082. },
  6083. /* @section
  6084. *
  6085. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  6086. */
  6087. initialize: function (latlng, options) {
  6088. setOptions(this, options);
  6089. this._latlng = toLatLng(latlng);
  6090. },
  6091. onAdd: function (map) {
  6092. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  6093. if (this._zoomAnimated) {
  6094. map.on('zoomanim', this._animateZoom, this);
  6095. }
  6096. this._initIcon();
  6097. this.update();
  6098. },
  6099. onRemove: function (map) {
  6100. if (this.dragging && this.dragging.enabled()) {
  6101. this.options.draggable = true;
  6102. this.dragging.removeHooks();
  6103. }
  6104. delete this.dragging;
  6105. if (this._zoomAnimated) {
  6106. map.off('zoomanim', this._animateZoom, this);
  6107. }
  6108. this._removeIcon();
  6109. this._removeShadow();
  6110. },
  6111. getEvents: function () {
  6112. return {
  6113. zoom: this.update,
  6114. viewreset: this.update
  6115. };
  6116. },
  6117. // @method getLatLng: LatLng
  6118. // Returns the current geographical position of the marker.
  6119. getLatLng: function () {
  6120. return this._latlng;
  6121. },
  6122. // @method setLatLng(latlng: LatLng): this
  6123. // Changes the marker position to the given point.
  6124. setLatLng: function (latlng) {
  6125. var oldLatLng = this._latlng;
  6126. this._latlng = toLatLng(latlng);
  6127. this.update();
  6128. // @event move: Event
  6129. // 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`.
  6130. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6131. },
  6132. // @method setZIndexOffset(offset: Number): this
  6133. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6134. setZIndexOffset: function (offset) {
  6135. this.options.zIndexOffset = offset;
  6136. return this.update();
  6137. },
  6138. // @method getIcon: Icon
  6139. // Returns the current icon used by the marker
  6140. getIcon: function () {
  6141. return this.options.icon;
  6142. },
  6143. // @method setIcon(icon: Icon): this
  6144. // Changes the marker icon.
  6145. setIcon: function (icon) {
  6146. this.options.icon = icon;
  6147. if (this._map) {
  6148. this._initIcon();
  6149. this.update();
  6150. }
  6151. if (this._popup) {
  6152. this.bindPopup(this._popup, this._popup.options);
  6153. }
  6154. return this;
  6155. },
  6156. getElement: function () {
  6157. return this._icon;
  6158. },
  6159. update: function () {
  6160. if (this._icon && this._map) {
  6161. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6162. this._setPos(pos);
  6163. }
  6164. return this;
  6165. },
  6166. _initIcon: function () {
  6167. var options = this.options,
  6168. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6169. var icon = options.icon.createIcon(this._icon),
  6170. addIcon = false;
  6171. // if we're not reusing the icon, remove the old one and init new one
  6172. if (icon !== this._icon) {
  6173. if (this._icon) {
  6174. this._removeIcon();
  6175. }
  6176. addIcon = true;
  6177. if (options.title) {
  6178. icon.title = options.title;
  6179. }
  6180. if (icon.tagName === 'IMG') {
  6181. icon.alt = options.alt || '';
  6182. }
  6183. }
  6184. addClass(icon, classToAdd);
  6185. if (options.keyboard) {
  6186. icon.tabIndex = '0';
  6187. }
  6188. this._icon = icon;
  6189. if (options.riseOnHover) {
  6190. this.on({
  6191. mouseover: this._bringToFront,
  6192. mouseout: this._resetZIndex
  6193. });
  6194. }
  6195. var newShadow = options.icon.createShadow(this._shadow),
  6196. addShadow = false;
  6197. if (newShadow !== this._shadow) {
  6198. this._removeShadow();
  6199. addShadow = true;
  6200. }
  6201. if (newShadow) {
  6202. addClass(newShadow, classToAdd);
  6203. newShadow.alt = '';
  6204. }
  6205. this._shadow = newShadow;
  6206. if (options.opacity < 1) {
  6207. this._updateOpacity();
  6208. }
  6209. if (addIcon) {
  6210. this.getPane().appendChild(this._icon);
  6211. }
  6212. this._initInteraction();
  6213. if (newShadow && addShadow) {
  6214. this.getPane(options.shadowPane).appendChild(this._shadow);
  6215. }
  6216. },
  6217. _removeIcon: function () {
  6218. if (this.options.riseOnHover) {
  6219. this.off({
  6220. mouseover: this._bringToFront,
  6221. mouseout: this._resetZIndex
  6222. });
  6223. }
  6224. remove(this._icon);
  6225. this.removeInteractiveTarget(this._icon);
  6226. this._icon = null;
  6227. },
  6228. _removeShadow: function () {
  6229. if (this._shadow) {
  6230. remove(this._shadow);
  6231. }
  6232. this._shadow = null;
  6233. },
  6234. _setPos: function (pos) {
  6235. if (this._icon) {
  6236. setPosition(this._icon, pos);
  6237. }
  6238. if (this._shadow) {
  6239. setPosition(this._shadow, pos);
  6240. }
  6241. this._zIndex = pos.y + this.options.zIndexOffset;
  6242. this._resetZIndex();
  6243. },
  6244. _updateZIndex: function (offset) {
  6245. if (this._icon) {
  6246. this._icon.style.zIndex = this._zIndex + offset;
  6247. }
  6248. },
  6249. _animateZoom: function (opt) {
  6250. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6251. this._setPos(pos);
  6252. },
  6253. _initInteraction: function () {
  6254. if (!this.options.interactive) { return; }
  6255. addClass(this._icon, 'leaflet-interactive');
  6256. this.addInteractiveTarget(this._icon);
  6257. if (MarkerDrag) {
  6258. var draggable = this.options.draggable;
  6259. if (this.dragging) {
  6260. draggable = this.dragging.enabled();
  6261. this.dragging.disable();
  6262. }
  6263. this.dragging = new MarkerDrag(this);
  6264. if (draggable) {
  6265. this.dragging.enable();
  6266. }
  6267. }
  6268. },
  6269. // @method setOpacity(opacity: Number): this
  6270. // Changes the opacity of the marker.
  6271. setOpacity: function (opacity) {
  6272. this.options.opacity = opacity;
  6273. if (this._map) {
  6274. this._updateOpacity();
  6275. }
  6276. return this;
  6277. },
  6278. _updateOpacity: function () {
  6279. var opacity = this.options.opacity;
  6280. if (this._icon) {
  6281. setOpacity(this._icon, opacity);
  6282. }
  6283. if (this._shadow) {
  6284. setOpacity(this._shadow, opacity);
  6285. }
  6286. },
  6287. _bringToFront: function () {
  6288. this._updateZIndex(this.options.riseOffset);
  6289. },
  6290. _resetZIndex: function () {
  6291. this._updateZIndex(0);
  6292. },
  6293. _getPopupAnchor: function () {
  6294. return this.options.icon.options.popupAnchor;
  6295. },
  6296. _getTooltipAnchor: function () {
  6297. return this.options.icon.options.tooltipAnchor;
  6298. }
  6299. });
  6300. // factory L.marker(latlng: LatLng, options? : Marker options)
  6301. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6302. // Instantiates a Marker object given a geographical point and optionally an options object.
  6303. function marker(latlng, options) {
  6304. return new Marker(latlng, options);
  6305. }
  6306. /*
  6307. * @class Path
  6308. * @aka L.Path
  6309. * @inherits Interactive layer
  6310. *
  6311. * An abstract class that contains options and constants shared between vector
  6312. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6313. */
  6314. var Path = Layer.extend({
  6315. // @section
  6316. // @aka Path options
  6317. options: {
  6318. // @option stroke: Boolean = true
  6319. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6320. stroke: true,
  6321. // @option color: String = '#3388ff'
  6322. // Stroke color
  6323. color: '#3388ff',
  6324. // @option weight: Number = 3
  6325. // Stroke width in pixels
  6326. weight: 3,
  6327. // @option opacity: Number = 1.0
  6328. // Stroke opacity
  6329. opacity: 1,
  6330. // @option lineCap: String= 'round'
  6331. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6332. lineCap: 'round',
  6333. // @option lineJoin: String = 'round'
  6334. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6335. lineJoin: 'round',
  6336. // @option dashArray: String = null
  6337. // 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).
  6338. dashArray: null,
  6339. // @option dashOffset: String = null
  6340. // 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).
  6341. dashOffset: null,
  6342. // @option fill: Boolean = depends
  6343. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6344. fill: false,
  6345. // @option fillColor: String = *
  6346. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6347. fillColor: null,
  6348. // @option fillOpacity: Number = 0.2
  6349. // Fill opacity.
  6350. fillOpacity: 0.2,
  6351. // @option fillRule: String = 'evenodd'
  6352. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6353. fillRule: 'evenodd',
  6354. // className: '',
  6355. // Option inherited from "Interactive layer" abstract class
  6356. interactive: true,
  6357. // @option bubblingMouseEvents: Boolean = true
  6358. // When `true`, a mouse event on this path will trigger the same event on the map
  6359. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6360. bubblingMouseEvents: true
  6361. },
  6362. beforeAdd: function (map) {
  6363. // Renderer is set here because we need to call renderer.getEvents
  6364. // before this.getEvents.
  6365. this._renderer = map.getRenderer(this);
  6366. },
  6367. onAdd: function () {
  6368. this._renderer._initPath(this);
  6369. this._reset();
  6370. this._renderer._addPath(this);
  6371. },
  6372. onRemove: function () {
  6373. this._renderer._removePath(this);
  6374. },
  6375. // @method redraw(): this
  6376. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6377. redraw: function () {
  6378. if (this._map) {
  6379. this._renderer._updatePath(this);
  6380. }
  6381. return this;
  6382. },
  6383. // @method setStyle(style: Path options): this
  6384. // Changes the appearance of a Path based on the options in the `Path options` object.
  6385. setStyle: function (style) {
  6386. setOptions(this, style);
  6387. if (this._renderer) {
  6388. this._renderer._updateStyle(this);
  6389. if (this.options.stroke && style && Object.prototype.hasOwnProperty.call(style, 'weight')) {
  6390. this._updateBounds();
  6391. }
  6392. }
  6393. return this;
  6394. },
  6395. // @method bringToFront(): this
  6396. // Brings the layer to the top of all path layers.
  6397. bringToFront: function () {
  6398. if (this._renderer) {
  6399. this._renderer._bringToFront(this);
  6400. }
  6401. return this;
  6402. },
  6403. // @method bringToBack(): this
  6404. // Brings the layer to the bottom of all path layers.
  6405. bringToBack: function () {
  6406. if (this._renderer) {
  6407. this._renderer._bringToBack(this);
  6408. }
  6409. return this;
  6410. },
  6411. getElement: function () {
  6412. return this._path;
  6413. },
  6414. _reset: function () {
  6415. // defined in child classes
  6416. this._project();
  6417. this._update();
  6418. },
  6419. _clickTolerance: function () {
  6420. // used when doing hit detection for Canvas layers
  6421. return (this.options.stroke ? this.options.weight / 2 : 0) + this._renderer.options.tolerance;
  6422. }
  6423. });
  6424. /*
  6425. * @class CircleMarker
  6426. * @aka L.CircleMarker
  6427. * @inherits Path
  6428. *
  6429. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6430. */
  6431. var CircleMarker = Path.extend({
  6432. // @section
  6433. // @aka CircleMarker options
  6434. options: {
  6435. fill: true,
  6436. // @option radius: Number = 10
  6437. // Radius of the circle marker, in pixels
  6438. radius: 10
  6439. },
  6440. initialize: function (latlng, options) {
  6441. setOptions(this, options);
  6442. this._latlng = toLatLng(latlng);
  6443. this._radius = this.options.radius;
  6444. },
  6445. // @method setLatLng(latLng: LatLng): this
  6446. // Sets the position of a circle marker to a new location.
  6447. setLatLng: function (latlng) {
  6448. var oldLatLng = this._latlng;
  6449. this._latlng = toLatLng(latlng);
  6450. this.redraw();
  6451. // @event move: Event
  6452. // Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
  6453. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6454. },
  6455. // @method getLatLng(): LatLng
  6456. // Returns the current geographical position of the circle marker
  6457. getLatLng: function () {
  6458. return this._latlng;
  6459. },
  6460. // @method setRadius(radius: Number): this
  6461. // Sets the radius of a circle marker. Units are in pixels.
  6462. setRadius: function (radius) {
  6463. this.options.radius = this._radius = radius;
  6464. return this.redraw();
  6465. },
  6466. // @method getRadius(): Number
  6467. // Returns the current radius of the circle
  6468. getRadius: function () {
  6469. return this._radius;
  6470. },
  6471. setStyle : function (options) {
  6472. var radius = options && options.radius || this._radius;
  6473. Path.prototype.setStyle.call(this, options);
  6474. this.setRadius(radius);
  6475. return this;
  6476. },
  6477. _project: function () {
  6478. this._point = this._map.latLngToLayerPoint(this._latlng);
  6479. this._updateBounds();
  6480. },
  6481. _updateBounds: function () {
  6482. var r = this._radius,
  6483. r2 = this._radiusY || r,
  6484. w = this._clickTolerance(),
  6485. p = [r + w, r2 + w];
  6486. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6487. },
  6488. _update: function () {
  6489. if (this._map) {
  6490. this._updatePath();
  6491. }
  6492. },
  6493. _updatePath: function () {
  6494. this._renderer._updateCircle(this);
  6495. },
  6496. _empty: function () {
  6497. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6498. },
  6499. // Needed by the `Canvas` renderer for interactivity
  6500. _containsPoint: function (p) {
  6501. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6502. }
  6503. });
  6504. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6505. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6506. function circleMarker(latlng, options) {
  6507. return new CircleMarker(latlng, options);
  6508. }
  6509. /*
  6510. * @class Circle
  6511. * @aka L.Circle
  6512. * @inherits CircleMarker
  6513. *
  6514. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6515. *
  6516. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6517. *
  6518. * @example
  6519. *
  6520. * ```js
  6521. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6522. * ```
  6523. */
  6524. var Circle = CircleMarker.extend({
  6525. initialize: function (latlng, options, legacyOptions) {
  6526. if (typeof options === 'number') {
  6527. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6528. options = extend({}, legacyOptions, {radius: options});
  6529. }
  6530. setOptions(this, options);
  6531. this._latlng = toLatLng(latlng);
  6532. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6533. // @section
  6534. // @aka Circle options
  6535. // @option radius: Number; Radius of the circle, in meters.
  6536. this._mRadius = this.options.radius;
  6537. },
  6538. // @method setRadius(radius: Number): this
  6539. // Sets the radius of a circle. Units are in meters.
  6540. setRadius: function (radius) {
  6541. this._mRadius = radius;
  6542. return this.redraw();
  6543. },
  6544. // @method getRadius(): Number
  6545. // Returns the current radius of a circle. Units are in meters.
  6546. getRadius: function () {
  6547. return this._mRadius;
  6548. },
  6549. // @method getBounds(): LatLngBounds
  6550. // Returns the `LatLngBounds` of the path.
  6551. getBounds: function () {
  6552. var half = [this._radius, this._radiusY || this._radius];
  6553. return new LatLngBounds(
  6554. this._map.layerPointToLatLng(this._point.subtract(half)),
  6555. this._map.layerPointToLatLng(this._point.add(half)));
  6556. },
  6557. setStyle: Path.prototype.setStyle,
  6558. _project: function () {
  6559. var lng = this._latlng.lng,
  6560. lat = this._latlng.lat,
  6561. map = this._map,
  6562. crs = map.options.crs;
  6563. if (crs.distance === Earth.distance) {
  6564. var d = Math.PI / 180,
  6565. latR = (this._mRadius / Earth.R) / d,
  6566. top = map.project([lat + latR, lng]),
  6567. bottom = map.project([lat - latR, lng]),
  6568. p = top.add(bottom).divideBy(2),
  6569. lat2 = map.unproject(p).lat,
  6570. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6571. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6572. if (isNaN(lngR) || lngR === 0) {
  6573. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6574. }
  6575. this._point = p.subtract(map.getPixelOrigin());
  6576. this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
  6577. this._radiusY = p.y - top.y;
  6578. } else {
  6579. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6580. this._point = map.latLngToLayerPoint(this._latlng);
  6581. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6582. }
  6583. this._updateBounds();
  6584. }
  6585. });
  6586. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6587. // Instantiates a circle object given a geographical point, and an options object
  6588. // which contains the circle radius.
  6589. // @alternative
  6590. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6591. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6592. // Do not use in new applications or plugins.
  6593. function circle(latlng, options, legacyOptions) {
  6594. return new Circle(latlng, options, legacyOptions);
  6595. }
  6596. /*
  6597. * @class Polyline
  6598. * @aka L.Polyline
  6599. * @inherits Path
  6600. *
  6601. * A class for drawing polyline overlays on a map. Extends `Path`.
  6602. *
  6603. * @example
  6604. *
  6605. * ```js
  6606. * // create a red polyline from an array of LatLng points
  6607. * var latlngs = [
  6608. * [45.51, -122.68],
  6609. * [37.77, -122.43],
  6610. * [34.04, -118.2]
  6611. * ];
  6612. *
  6613. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6614. *
  6615. * // zoom the map to the polyline
  6616. * map.fitBounds(polyline.getBounds());
  6617. * ```
  6618. *
  6619. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6620. *
  6621. * ```js
  6622. * // create a red polyline from an array of arrays of LatLng points
  6623. * var latlngs = [
  6624. * [[45.51, -122.68],
  6625. * [37.77, -122.43],
  6626. * [34.04, -118.2]],
  6627. * [[40.78, -73.91],
  6628. * [41.83, -87.62],
  6629. * [32.76, -96.72]]
  6630. * ];
  6631. * ```
  6632. */
  6633. var Polyline = Path.extend({
  6634. // @section
  6635. // @aka Polyline options
  6636. options: {
  6637. // @option smoothFactor: Number = 1.0
  6638. // How much to simplify the polyline on each zoom level. More means
  6639. // better performance and smoother look, and less means more accurate representation.
  6640. smoothFactor: 1.0,
  6641. // @option noClip: Boolean = false
  6642. // Disable polyline clipping.
  6643. noClip: false
  6644. },
  6645. initialize: function (latlngs, options) {
  6646. setOptions(this, options);
  6647. this._setLatLngs(latlngs);
  6648. },
  6649. // @method getLatLngs(): LatLng[]
  6650. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6651. getLatLngs: function () {
  6652. return this._latlngs;
  6653. },
  6654. // @method setLatLngs(latlngs: LatLng[]): this
  6655. // Replaces all the points in the polyline with the given array of geographical points.
  6656. setLatLngs: function (latlngs) {
  6657. this._setLatLngs(latlngs);
  6658. return this.redraw();
  6659. },
  6660. // @method isEmpty(): Boolean
  6661. // Returns `true` if the Polyline has no LatLngs.
  6662. isEmpty: function () {
  6663. return !this._latlngs.length;
  6664. },
  6665. // @method closestLayerPoint(p: Point): Point
  6666. // Returns the point closest to `p` on the Polyline.
  6667. closestLayerPoint: function (p) {
  6668. var minDistance = Infinity,
  6669. minPoint = null,
  6670. closest = _sqClosestPointOnSegment,
  6671. p1, p2;
  6672. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6673. var points = this._parts[j];
  6674. for (var i = 1, len = points.length; i < len; i++) {
  6675. p1 = points[i - 1];
  6676. p2 = points[i];
  6677. var sqDist = closest(p, p1, p2, true);
  6678. if (sqDist < minDistance) {
  6679. minDistance = sqDist;
  6680. minPoint = closest(p, p1, p2);
  6681. }
  6682. }
  6683. }
  6684. if (minPoint) {
  6685. minPoint.distance = Math.sqrt(minDistance);
  6686. }
  6687. return minPoint;
  6688. },
  6689. // @method getCenter(): LatLng
  6690. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6691. getCenter: function () {
  6692. // throws error when not yet added to map as this center calculation requires projected coordinates
  6693. if (!this._map) {
  6694. throw new Error('Must add layer to map before using getCenter()');
  6695. }
  6696. var i, halfDist, segDist, dist, p1, p2, ratio,
  6697. points = this._rings[0],
  6698. len = points.length;
  6699. if (!len) { return null; }
  6700. // polyline centroid algorithm; only uses the first ring if there are multiple
  6701. for (i = 0, halfDist = 0; i < len - 1; i++) {
  6702. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  6703. }
  6704. // The line is so small in the current view that all points are on the same pixel.
  6705. if (halfDist === 0) {
  6706. return this._map.layerPointToLatLng(points[0]);
  6707. }
  6708. for (i = 0, dist = 0; i < len - 1; i++) {
  6709. p1 = points[i];
  6710. p2 = points[i + 1];
  6711. segDist = p1.distanceTo(p2);
  6712. dist += segDist;
  6713. if (dist > halfDist) {
  6714. ratio = (dist - halfDist) / segDist;
  6715. return this._map.layerPointToLatLng([
  6716. p2.x - ratio * (p2.x - p1.x),
  6717. p2.y - ratio * (p2.y - p1.y)
  6718. ]);
  6719. }
  6720. }
  6721. },
  6722. // @method getBounds(): LatLngBounds
  6723. // Returns the `LatLngBounds` of the path.
  6724. getBounds: function () {
  6725. return this._bounds;
  6726. },
  6727. // @method addLatLng(latlng: LatLng, latlngs?: LatLng[]): this
  6728. // Adds a given point to the polyline. By default, adds to the first ring of
  6729. // the polyline in case of a multi-polyline, but can be overridden by passing
  6730. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6731. addLatLng: function (latlng, latlngs) {
  6732. latlngs = latlngs || this._defaultShape();
  6733. latlng = toLatLng(latlng);
  6734. latlngs.push(latlng);
  6735. this._bounds.extend(latlng);
  6736. return this.redraw();
  6737. },
  6738. _setLatLngs: function (latlngs) {
  6739. this._bounds = new LatLngBounds();
  6740. this._latlngs = this._convertLatLngs(latlngs);
  6741. },
  6742. _defaultShape: function () {
  6743. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6744. },
  6745. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6746. _convertLatLngs: function (latlngs) {
  6747. var result = [],
  6748. flat = isFlat(latlngs);
  6749. for (var i = 0, len = latlngs.length; i < len; i++) {
  6750. if (flat) {
  6751. result[i] = toLatLng(latlngs[i]);
  6752. this._bounds.extend(result[i]);
  6753. } else {
  6754. result[i] = this._convertLatLngs(latlngs[i]);
  6755. }
  6756. }
  6757. return result;
  6758. },
  6759. _project: function () {
  6760. var pxBounds = new Bounds();
  6761. this._rings = [];
  6762. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  6763. if (this._bounds.isValid() && pxBounds.isValid()) {
  6764. this._rawPxBounds = pxBounds;
  6765. this._updateBounds();
  6766. }
  6767. },
  6768. _updateBounds: function () {
  6769. var w = this._clickTolerance(),
  6770. p = new Point(w, w);
  6771. this._pxBounds = new Bounds([
  6772. this._rawPxBounds.min.subtract(p),
  6773. this._rawPxBounds.max.add(p)
  6774. ]);
  6775. },
  6776. // recursively turns latlngs into a set of rings with projected coordinates
  6777. _projectLatlngs: function (latlngs, result, projectedBounds) {
  6778. var flat = latlngs[0] instanceof LatLng,
  6779. len = latlngs.length,
  6780. i, ring;
  6781. if (flat) {
  6782. ring = [];
  6783. for (i = 0; i < len; i++) {
  6784. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  6785. projectedBounds.extend(ring[i]);
  6786. }
  6787. result.push(ring);
  6788. } else {
  6789. for (i = 0; i < len; i++) {
  6790. this._projectLatlngs(latlngs[i], result, projectedBounds);
  6791. }
  6792. }
  6793. },
  6794. // clip polyline by renderer bounds so that we have less to render for performance
  6795. _clipPoints: function () {
  6796. var bounds = this._renderer._bounds;
  6797. this._parts = [];
  6798. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6799. return;
  6800. }
  6801. if (this.options.noClip) {
  6802. this._parts = this._rings;
  6803. return;
  6804. }
  6805. var parts = this._parts,
  6806. i, j, k, len, len2, segment, points;
  6807. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  6808. points = this._rings[i];
  6809. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  6810. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  6811. if (!segment) { continue; }
  6812. parts[k] = parts[k] || [];
  6813. parts[k].push(segment[0]);
  6814. // if segment goes out of screen, or it's the last one, it's the end of the line part
  6815. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  6816. parts[k].push(segment[1]);
  6817. k++;
  6818. }
  6819. }
  6820. }
  6821. },
  6822. // simplify each clipped part of the polyline for performance
  6823. _simplifyPoints: function () {
  6824. var parts = this._parts,
  6825. tolerance = this.options.smoothFactor;
  6826. for (var i = 0, len = parts.length; i < len; i++) {
  6827. parts[i] = simplify(parts[i], tolerance);
  6828. }
  6829. },
  6830. _update: function () {
  6831. if (!this._map) { return; }
  6832. this._clipPoints();
  6833. this._simplifyPoints();
  6834. this._updatePath();
  6835. },
  6836. _updatePath: function () {
  6837. this._renderer._updatePoly(this);
  6838. },
  6839. // Needed by the `Canvas` renderer for interactivity
  6840. _containsPoint: function (p, closed) {
  6841. var i, j, k, len, len2, part,
  6842. w = this._clickTolerance();
  6843. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  6844. // hit detection for polylines
  6845. for (i = 0, len = this._parts.length; i < len; i++) {
  6846. part = this._parts[i];
  6847. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6848. if (!closed && (j === 0)) { continue; }
  6849. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  6850. return true;
  6851. }
  6852. }
  6853. }
  6854. return false;
  6855. }
  6856. });
  6857. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  6858. // Instantiates a polyline object given an array of geographical points and
  6859. // optionally an options object. You can create a `Polyline` object with
  6860. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  6861. // of geographic points.
  6862. function polyline(latlngs, options) {
  6863. return new Polyline(latlngs, options);
  6864. }
  6865. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  6866. Polyline._flat = _flat;
  6867. /*
  6868. * @class Polygon
  6869. * @aka L.Polygon
  6870. * @inherits Polyline
  6871. *
  6872. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  6873. *
  6874. * 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.
  6875. *
  6876. *
  6877. * @example
  6878. *
  6879. * ```js
  6880. * // create a red polygon from an array of LatLng points
  6881. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  6882. *
  6883. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  6884. *
  6885. * // zoom the map to the polygon
  6886. * map.fitBounds(polygon.getBounds());
  6887. * ```
  6888. *
  6889. * 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:
  6890. *
  6891. * ```js
  6892. * var latlngs = [
  6893. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6894. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6895. * ];
  6896. * ```
  6897. *
  6898. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  6899. *
  6900. * ```js
  6901. * var latlngs = [
  6902. * [ // first polygon
  6903. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6904. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6905. * ],
  6906. * [ // second polygon
  6907. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  6908. * ]
  6909. * ];
  6910. * ```
  6911. */
  6912. var Polygon = Polyline.extend({
  6913. options: {
  6914. fill: true
  6915. },
  6916. isEmpty: function () {
  6917. return !this._latlngs.length || !this._latlngs[0].length;
  6918. },
  6919. getCenter: function () {
  6920. // throws error when not yet added to map as this center calculation requires projected coordinates
  6921. if (!this._map) {
  6922. throw new Error('Must add layer to map before using getCenter()');
  6923. }
  6924. var i, j, p1, p2, f, area, x, y, center,
  6925. points = this._rings[0],
  6926. len = points.length;
  6927. if (!len) { return null; }
  6928. // polygon centroid algorithm; only uses the first ring if there are multiple
  6929. area = x = y = 0;
  6930. for (i = 0, j = len - 1; i < len; j = i++) {
  6931. p1 = points[i];
  6932. p2 = points[j];
  6933. f = p1.y * p2.x - p2.y * p1.x;
  6934. x += (p1.x + p2.x) * f;
  6935. y += (p1.y + p2.y) * f;
  6936. area += f * 3;
  6937. }
  6938. if (area === 0) {
  6939. // Polygon is so small that all points are on same pixel.
  6940. center = points[0];
  6941. } else {
  6942. center = [x / area, y / area];
  6943. }
  6944. return this._map.layerPointToLatLng(center);
  6945. },
  6946. _convertLatLngs: function (latlngs) {
  6947. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  6948. len = result.length;
  6949. // remove last point if it equals first one
  6950. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  6951. result.pop();
  6952. }
  6953. return result;
  6954. },
  6955. _setLatLngs: function (latlngs) {
  6956. Polyline.prototype._setLatLngs.call(this, latlngs);
  6957. if (isFlat(this._latlngs)) {
  6958. this._latlngs = [this._latlngs];
  6959. }
  6960. },
  6961. _defaultShape: function () {
  6962. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  6963. },
  6964. _clipPoints: function () {
  6965. // polygons need a different clipping algorithm so we redefine that
  6966. var bounds = this._renderer._bounds,
  6967. w = this.options.weight,
  6968. p = new Point(w, w);
  6969. // increase clip padding by stroke width to avoid stroke on clip edges
  6970. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  6971. this._parts = [];
  6972. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6973. return;
  6974. }
  6975. if (this.options.noClip) {
  6976. this._parts = this._rings;
  6977. return;
  6978. }
  6979. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  6980. clipped = clipPolygon(this._rings[i], bounds, true);
  6981. if (clipped.length) {
  6982. this._parts.push(clipped);
  6983. }
  6984. }
  6985. },
  6986. _updatePath: function () {
  6987. this._renderer._updatePoly(this, true);
  6988. },
  6989. // Needed by the `Canvas` renderer for interactivity
  6990. _containsPoint: function (p) {
  6991. var inside = false,
  6992. part, p1, p2, i, j, k, len, len2;
  6993. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  6994. // ray casting algorithm for detecting if point is in polygon
  6995. for (i = 0, len = this._parts.length; i < len; i++) {
  6996. part = this._parts[i];
  6997. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6998. p1 = part[j];
  6999. p2 = part[k];
  7000. 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)) {
  7001. inside = !inside;
  7002. }
  7003. }
  7004. }
  7005. // also check if it's on polygon stroke
  7006. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  7007. }
  7008. });
  7009. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  7010. function polygon(latlngs, options) {
  7011. return new Polygon(latlngs, options);
  7012. }
  7013. /*
  7014. * @class GeoJSON
  7015. * @aka L.GeoJSON
  7016. * @inherits FeatureGroup
  7017. *
  7018. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  7019. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  7020. *
  7021. * @example
  7022. *
  7023. * ```js
  7024. * L.geoJSON(data, {
  7025. * style: function (feature) {
  7026. * return {color: feature.properties.color};
  7027. * }
  7028. * }).bindPopup(function (layer) {
  7029. * return layer.feature.properties.description;
  7030. * }).addTo(map);
  7031. * ```
  7032. */
  7033. var GeoJSON = FeatureGroup.extend({
  7034. /* @section
  7035. * @aka GeoJSON options
  7036. *
  7037. * @option pointToLayer: Function = *
  7038. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  7039. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  7040. * The default is to spawn a default `Marker`:
  7041. * ```js
  7042. * function(geoJsonPoint, latlng) {
  7043. * return L.marker(latlng);
  7044. * }
  7045. * ```
  7046. *
  7047. * @option style: Function = *
  7048. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  7049. * called internally when data is added.
  7050. * The default value is to not override any defaults:
  7051. * ```js
  7052. * function (geoJsonFeature) {
  7053. * return {}
  7054. * }
  7055. * ```
  7056. *
  7057. * @option onEachFeature: Function = *
  7058. * A `Function` that will be called once for each created `Feature`, after it has
  7059. * been created and styled. Useful for attaching events and popups to features.
  7060. * The default is to do nothing with the newly created layers:
  7061. * ```js
  7062. * function (feature, layer) {}
  7063. * ```
  7064. *
  7065. * @option filter: Function = *
  7066. * A `Function` that will be used to decide whether to include a feature or not.
  7067. * The default is to include all features:
  7068. * ```js
  7069. * function (geoJsonFeature) {
  7070. * return true;
  7071. * }
  7072. * ```
  7073. * Note: dynamically changing the `filter` option will have effect only on newly
  7074. * added data. It will _not_ re-evaluate already included features.
  7075. *
  7076. * @option coordsToLatLng: Function = *
  7077. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  7078. * The default is the `coordsToLatLng` static method.
  7079. *
  7080. * @option markersInheritOptions: Boolean = false
  7081. * Whether default Markers for "Point" type Features inherit from group options.
  7082. */
  7083. initialize: function (geojson, options) {
  7084. setOptions(this, options);
  7085. this._layers = {};
  7086. if (geojson) {
  7087. this.addData(geojson);
  7088. }
  7089. },
  7090. // @method addData( <GeoJSON> data ): this
  7091. // Adds a GeoJSON object to the layer.
  7092. addData: function (geojson) {
  7093. var features = isArray(geojson) ? geojson : geojson.features,
  7094. i, len, feature;
  7095. if (features) {
  7096. for (i = 0, len = features.length; i < len; i++) {
  7097. // only add this if geometry or geometries are set and not null
  7098. feature = features[i];
  7099. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  7100. this.addData(feature);
  7101. }
  7102. }
  7103. return this;
  7104. }
  7105. var options = this.options;
  7106. if (options.filter && !options.filter(geojson)) { return this; }
  7107. var layer = geometryToLayer(geojson, options);
  7108. if (!layer) {
  7109. return this;
  7110. }
  7111. layer.feature = asFeature(geojson);
  7112. layer.defaultOptions = layer.options;
  7113. this.resetStyle(layer);
  7114. if (options.onEachFeature) {
  7115. options.onEachFeature(geojson, layer);
  7116. }
  7117. return this.addLayer(layer);
  7118. },
  7119. // @method resetStyle( <Path> layer? ): this
  7120. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7121. // If `layer` is omitted, the style of all features in the current layer is reset.
  7122. resetStyle: function (layer) {
  7123. if (layer === undefined) {
  7124. return this.eachLayer(this.resetStyle, this);
  7125. }
  7126. // reset any custom styles
  7127. layer.options = extend({}, layer.defaultOptions);
  7128. this._setLayerStyle(layer, this.options.style);
  7129. return this;
  7130. },
  7131. // @method setStyle( <Function> style ): this
  7132. // Changes styles of GeoJSON vector layers with the given style function.
  7133. setStyle: function (style) {
  7134. return this.eachLayer(function (layer) {
  7135. this._setLayerStyle(layer, style);
  7136. }, this);
  7137. },
  7138. _setLayerStyle: function (layer, style) {
  7139. if (layer.setStyle) {
  7140. if (typeof style === 'function') {
  7141. style = style(layer.feature);
  7142. }
  7143. layer.setStyle(style);
  7144. }
  7145. }
  7146. });
  7147. // @section
  7148. // There are several static functions which can be called without instantiating L.GeoJSON:
  7149. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7150. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7151. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7152. // functions if provided as options.
  7153. function geometryToLayer(geojson, options) {
  7154. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7155. coords = geometry ? geometry.coordinates : null,
  7156. layers = [],
  7157. pointToLayer = options && options.pointToLayer,
  7158. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7159. latlng, latlngs, i, len;
  7160. if (!coords && !geometry) {
  7161. return null;
  7162. }
  7163. switch (geometry.type) {
  7164. case 'Point':
  7165. latlng = _coordsToLatLng(coords);
  7166. return _pointToLayer(pointToLayer, geojson, latlng, options);
  7167. case 'MultiPoint':
  7168. for (i = 0, len = coords.length; i < len; i++) {
  7169. latlng = _coordsToLatLng(coords[i]);
  7170. layers.push(_pointToLayer(pointToLayer, geojson, latlng, options));
  7171. }
  7172. return new FeatureGroup(layers);
  7173. case 'LineString':
  7174. case 'MultiLineString':
  7175. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7176. return new Polyline(latlngs, options);
  7177. case 'Polygon':
  7178. case 'MultiPolygon':
  7179. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7180. return new Polygon(latlngs, options);
  7181. case 'GeometryCollection':
  7182. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7183. var layer = geometryToLayer({
  7184. geometry: geometry.geometries[i],
  7185. type: 'Feature',
  7186. properties: geojson.properties
  7187. }, options);
  7188. if (layer) {
  7189. layers.push(layer);
  7190. }
  7191. }
  7192. return new FeatureGroup(layers);
  7193. default:
  7194. throw new Error('Invalid GeoJSON object.');
  7195. }
  7196. }
  7197. function _pointToLayer(pointToLayerFn, geojson, latlng, options) {
  7198. return pointToLayerFn ?
  7199. pointToLayerFn(geojson, latlng) :
  7200. new Marker(latlng, options && options.markersInheritOptions && options);
  7201. }
  7202. // @function coordsToLatLng(coords: Array): LatLng
  7203. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7204. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7205. function coordsToLatLng(coords) {
  7206. return new LatLng(coords[1], coords[0], coords[2]);
  7207. }
  7208. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7209. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7210. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7211. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7212. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7213. var latlngs = [];
  7214. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7215. latlng = levelsDeep ?
  7216. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7217. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7218. latlngs.push(latlng);
  7219. }
  7220. return latlngs;
  7221. }
  7222. // @function latLngToCoords(latlng: LatLng, precision?: Number): Array
  7223. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7224. function latLngToCoords(latlng, precision) {
  7225. precision = typeof precision === 'number' ? precision : 6;
  7226. return latlng.alt !== undefined ?
  7227. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7228. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7229. }
  7230. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  7231. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7232. // `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.
  7233. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7234. var coords = [];
  7235. for (var i = 0, len = latlngs.length; i < len; i++) {
  7236. coords.push(levelsDeep ?
  7237. latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :
  7238. latLngToCoords(latlngs[i], precision));
  7239. }
  7240. if (!levelsDeep && closed) {
  7241. coords.push(coords[0]);
  7242. }
  7243. return coords;
  7244. }
  7245. function getFeature(layer, newGeometry) {
  7246. return layer.feature ?
  7247. extend({}, layer.feature, {geometry: newGeometry}) :
  7248. asFeature(newGeometry);
  7249. }
  7250. // @function asFeature(geojson: Object): Object
  7251. // Normalize GeoJSON geometries/features into GeoJSON features.
  7252. function asFeature(geojson) {
  7253. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7254. return geojson;
  7255. }
  7256. return {
  7257. type: 'Feature',
  7258. properties: {},
  7259. geometry: geojson
  7260. };
  7261. }
  7262. var PointToGeoJSON = {
  7263. toGeoJSON: function (precision) {
  7264. return getFeature(this, {
  7265. type: 'Point',
  7266. coordinates: latLngToCoords(this.getLatLng(), precision)
  7267. });
  7268. }
  7269. };
  7270. // @namespace Marker
  7271. // @section Other methods
  7272. // @method toGeoJSON(precision?: Number): Object
  7273. // `precision` is the number of decimal places for coordinates.
  7274. // The default value is 6 places.
  7275. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7276. Marker.include(PointToGeoJSON);
  7277. // @namespace CircleMarker
  7278. // @method toGeoJSON(precision?: Number): Object
  7279. // `precision` is the number of decimal places for coordinates.
  7280. // The default value is 6 places.
  7281. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7282. Circle.include(PointToGeoJSON);
  7283. CircleMarker.include(PointToGeoJSON);
  7284. // @namespace Polyline
  7285. // @method toGeoJSON(precision?: Number): Object
  7286. // `precision` is the number of decimal places for coordinates.
  7287. // The default value is 6 places.
  7288. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7289. Polyline.include({
  7290. toGeoJSON: function (precision) {
  7291. var multi = !isFlat(this._latlngs);
  7292. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7293. return getFeature(this, {
  7294. type: (multi ? 'Multi' : '') + 'LineString',
  7295. coordinates: coords
  7296. });
  7297. }
  7298. });
  7299. // @namespace Polygon
  7300. // @method toGeoJSON(precision?: Number): Object
  7301. // `precision` is the number of decimal places for coordinates.
  7302. // The default value is 6 places.
  7303. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7304. Polygon.include({
  7305. toGeoJSON: function (precision) {
  7306. var holes = !isFlat(this._latlngs),
  7307. multi = holes && !isFlat(this._latlngs[0]);
  7308. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7309. if (!holes) {
  7310. coords = [coords];
  7311. }
  7312. return getFeature(this, {
  7313. type: (multi ? 'Multi' : '') + 'Polygon',
  7314. coordinates: coords
  7315. });
  7316. }
  7317. });
  7318. // @namespace LayerGroup
  7319. LayerGroup.include({
  7320. toMultiPoint: function (precision) {
  7321. var coords = [];
  7322. this.eachLayer(function (layer) {
  7323. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7324. });
  7325. return getFeature(this, {
  7326. type: 'MultiPoint',
  7327. coordinates: coords
  7328. });
  7329. },
  7330. // @method toGeoJSON(precision?: Number): Object
  7331. // `precision` is the number of decimal places for coordinates.
  7332. // The default value is 6 places.
  7333. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7334. toGeoJSON: function (precision) {
  7335. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7336. if (type === 'MultiPoint') {
  7337. return this.toMultiPoint(precision);
  7338. }
  7339. var isGeometryCollection = type === 'GeometryCollection',
  7340. jsons = [];
  7341. this.eachLayer(function (layer) {
  7342. if (layer.toGeoJSON) {
  7343. var json = layer.toGeoJSON(precision);
  7344. if (isGeometryCollection) {
  7345. jsons.push(json.geometry);
  7346. } else {
  7347. var feature = asFeature(json);
  7348. // Squash nested feature collections
  7349. if (feature.type === 'FeatureCollection') {
  7350. jsons.push.apply(jsons, feature.features);
  7351. } else {
  7352. jsons.push(feature);
  7353. }
  7354. }
  7355. }
  7356. });
  7357. if (isGeometryCollection) {
  7358. return getFeature(this, {
  7359. geometries: jsons,
  7360. type: 'GeometryCollection'
  7361. });
  7362. }
  7363. return {
  7364. type: 'FeatureCollection',
  7365. features: jsons
  7366. };
  7367. }
  7368. });
  7369. // @namespace GeoJSON
  7370. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7371. // Creates a GeoJSON layer. Optionally accepts an object in
  7372. // [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map
  7373. // (you can alternatively add it later with `addData` method) and an `options` object.
  7374. function geoJSON(geojson, options) {
  7375. return new GeoJSON(geojson, options);
  7376. }
  7377. // Backward compatibility.
  7378. var geoJson = geoJSON;
  7379. /*
  7380. * @class ImageOverlay
  7381. * @aka L.ImageOverlay
  7382. * @inherits Interactive layer
  7383. *
  7384. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7385. *
  7386. * @example
  7387. *
  7388. * ```js
  7389. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7390. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7391. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7392. * ```
  7393. */
  7394. var ImageOverlay = Layer.extend({
  7395. // @section
  7396. // @aka ImageOverlay options
  7397. options: {
  7398. // @option opacity: Number = 1.0
  7399. // The opacity of the image overlay.
  7400. opacity: 1,
  7401. // @option alt: String = ''
  7402. // Text for the `alt` attribute of the image (useful for accessibility).
  7403. alt: '',
  7404. // @option interactive: Boolean = false
  7405. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7406. interactive: false,
  7407. // @option crossOrigin: Boolean|String = false
  7408. // Whether the crossOrigin attribute will be added to the image.
  7409. // 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.
  7410. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  7411. crossOrigin: false,
  7412. // @option errorOverlayUrl: String = ''
  7413. // URL to the overlay image to show in place of the overlay that failed to load.
  7414. errorOverlayUrl: '',
  7415. // @option zIndex: Number = 1
  7416. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
  7417. zIndex: 1,
  7418. // @option className: String = ''
  7419. // A custom class name to assign to the image. Empty by default.
  7420. className: ''
  7421. },
  7422. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7423. this._url = url;
  7424. this._bounds = toLatLngBounds(bounds);
  7425. setOptions(this, options);
  7426. },
  7427. onAdd: function () {
  7428. if (!this._image) {
  7429. this._initImage();
  7430. if (this.options.opacity < 1) {
  7431. this._updateOpacity();
  7432. }
  7433. }
  7434. if (this.options.interactive) {
  7435. addClass(this._image, 'leaflet-interactive');
  7436. this.addInteractiveTarget(this._image);
  7437. }
  7438. this.getPane().appendChild(this._image);
  7439. this._reset();
  7440. },
  7441. onRemove: function () {
  7442. remove(this._image);
  7443. if (this.options.interactive) {
  7444. this.removeInteractiveTarget(this._image);
  7445. }
  7446. },
  7447. // @method setOpacity(opacity: Number): this
  7448. // Sets the opacity of the overlay.
  7449. setOpacity: function (opacity) {
  7450. this.options.opacity = opacity;
  7451. if (this._image) {
  7452. this._updateOpacity();
  7453. }
  7454. return this;
  7455. },
  7456. setStyle: function (styleOpts) {
  7457. if (styleOpts.opacity) {
  7458. this.setOpacity(styleOpts.opacity);
  7459. }
  7460. return this;
  7461. },
  7462. // @method bringToFront(): this
  7463. // Brings the layer to the top of all overlays.
  7464. bringToFront: function () {
  7465. if (this._map) {
  7466. toFront(this._image);
  7467. }
  7468. return this;
  7469. },
  7470. // @method bringToBack(): this
  7471. // Brings the layer to the bottom of all overlays.
  7472. bringToBack: function () {
  7473. if (this._map) {
  7474. toBack(this._image);
  7475. }
  7476. return this;
  7477. },
  7478. // @method setUrl(url: String): this
  7479. // Changes the URL of the image.
  7480. setUrl: function (url) {
  7481. this._url = url;
  7482. if (this._image) {
  7483. this._image.src = url;
  7484. }
  7485. return this;
  7486. },
  7487. // @method setBounds(bounds: LatLngBounds): this
  7488. // Update the bounds that this ImageOverlay covers
  7489. setBounds: function (bounds) {
  7490. this._bounds = toLatLngBounds(bounds);
  7491. if (this._map) {
  7492. this._reset();
  7493. }
  7494. return this;
  7495. },
  7496. getEvents: function () {
  7497. var events = {
  7498. zoom: this._reset,
  7499. viewreset: this._reset
  7500. };
  7501. if (this._zoomAnimated) {
  7502. events.zoomanim = this._animateZoom;
  7503. }
  7504. return events;
  7505. },
  7506. // @method setZIndex(value: Number): this
  7507. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7508. setZIndex: function (value) {
  7509. this.options.zIndex = value;
  7510. this._updateZIndex();
  7511. return this;
  7512. },
  7513. // @method getBounds(): LatLngBounds
  7514. // Get the bounds that this ImageOverlay covers
  7515. getBounds: function () {
  7516. return this._bounds;
  7517. },
  7518. // @method getElement(): HTMLElement
  7519. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7520. // used by this overlay.
  7521. getElement: function () {
  7522. return this._image;
  7523. },
  7524. _initImage: function () {
  7525. var wasElementSupplied = this._url.tagName === 'IMG';
  7526. var img = this._image = wasElementSupplied ? this._url : create$1('img');
  7527. addClass(img, 'leaflet-image-layer');
  7528. if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
  7529. if (this.options.className) { addClass(img, this.options.className); }
  7530. img.onselectstart = falseFn;
  7531. img.onmousemove = falseFn;
  7532. // @event load: Event
  7533. // Fired when the ImageOverlay layer has loaded its image
  7534. img.onload = bind(this.fire, this, 'load');
  7535. img.onerror = bind(this._overlayOnError, this, 'error');
  7536. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  7537. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  7538. }
  7539. if (this.options.zIndex) {
  7540. this._updateZIndex();
  7541. }
  7542. if (wasElementSupplied) {
  7543. this._url = img.src;
  7544. return;
  7545. }
  7546. img.src = this._url;
  7547. img.alt = this.options.alt;
  7548. },
  7549. _animateZoom: function (e) {
  7550. var scale = this._map.getZoomScale(e.zoom),
  7551. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7552. setTransform(this._image, offset, scale);
  7553. },
  7554. _reset: function () {
  7555. var image = this._image,
  7556. bounds = new Bounds(
  7557. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7558. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7559. size = bounds.getSize();
  7560. setPosition(image, bounds.min);
  7561. image.style.width = size.x + 'px';
  7562. image.style.height = size.y + 'px';
  7563. },
  7564. _updateOpacity: function () {
  7565. setOpacity(this._image, this.options.opacity);
  7566. },
  7567. _updateZIndex: function () {
  7568. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7569. this._image.style.zIndex = this.options.zIndex;
  7570. }
  7571. },
  7572. _overlayOnError: function () {
  7573. // @event error: Event
  7574. // Fired when the ImageOverlay layer fails to load its image
  7575. this.fire('error');
  7576. var errorUrl = this.options.errorOverlayUrl;
  7577. if (errorUrl && this._url !== errorUrl) {
  7578. this._url = errorUrl;
  7579. this._image.src = errorUrl;
  7580. }
  7581. }
  7582. });
  7583. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7584. // Instantiates an image overlay object given the URL of the image and the
  7585. // geographical bounds it is tied to.
  7586. var imageOverlay = function (url, bounds, options) {
  7587. return new ImageOverlay(url, bounds, options);
  7588. };
  7589. /*
  7590. * @class VideoOverlay
  7591. * @aka L.VideoOverlay
  7592. * @inherits ImageOverlay
  7593. *
  7594. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7595. *
  7596. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7597. * HTML5 element.
  7598. *
  7599. * @example
  7600. *
  7601. * ```js
  7602. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7603. * videoBounds = [[ 32, -130], [ 13, -100]];
  7604. * L.videoOverlay(videoUrl, videoBounds ).addTo(map);
  7605. * ```
  7606. */
  7607. var VideoOverlay = ImageOverlay.extend({
  7608. // @section
  7609. // @aka VideoOverlay options
  7610. options: {
  7611. // @option autoplay: Boolean = true
  7612. // Whether the video starts playing automatically when loaded.
  7613. autoplay: true,
  7614. // @option loop: Boolean = true
  7615. // Whether the video will loop back to the beginning when played.
  7616. loop: true,
  7617. // @option keepAspectRatio: Boolean = true
  7618. // Whether the video will save aspect ratio after the projection.
  7619. // Relevant for supported browsers. Browser compatibility- https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
  7620. keepAspectRatio: true,
  7621. // @option muted: Boolean = false
  7622. // Whether the video starts on mute when loaded.
  7623. muted: false
  7624. },
  7625. _initImage: function () {
  7626. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7627. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7628. addClass(vid, 'leaflet-image-layer');
  7629. if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
  7630. if (this.options.className) { addClass(vid, this.options.className); }
  7631. vid.onselectstart = falseFn;
  7632. vid.onmousemove = falseFn;
  7633. // @event load: Event
  7634. // Fired when the video has finished loading the first frame
  7635. vid.onloadeddata = bind(this.fire, this, 'load');
  7636. if (wasElementSupplied) {
  7637. var sourceElements = vid.getElementsByTagName('source');
  7638. var sources = [];
  7639. for (var j = 0; j < sourceElements.length; j++) {
  7640. sources.push(sourceElements[j].src);
  7641. }
  7642. this._url = (sourceElements.length > 0) ? sources : [vid.src];
  7643. return;
  7644. }
  7645. if (!isArray(this._url)) { this._url = [this._url]; }
  7646. if (!this.options.keepAspectRatio && Object.prototype.hasOwnProperty.call(vid.style, 'objectFit')) {
  7647. vid.style['objectFit'] = 'fill';
  7648. }
  7649. vid.autoplay = !!this.options.autoplay;
  7650. vid.loop = !!this.options.loop;
  7651. vid.muted = !!this.options.muted;
  7652. for (var i = 0; i < this._url.length; i++) {
  7653. var source = create$1('source');
  7654. source.src = this._url[i];
  7655. vid.appendChild(source);
  7656. }
  7657. }
  7658. // @method getElement(): HTMLVideoElement
  7659. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7660. // used by this overlay.
  7661. });
  7662. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7663. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7664. // geographical bounds it is tied to.
  7665. function videoOverlay(video, bounds, options) {
  7666. return new VideoOverlay(video, bounds, options);
  7667. }
  7668. /*
  7669. * @class SVGOverlay
  7670. * @aka L.SVGOverlay
  7671. * @inherits ImageOverlay
  7672. *
  7673. * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.
  7674. *
  7675. * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.
  7676. *
  7677. * @example
  7678. *
  7679. * ```js
  7680. * var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  7681. * svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
  7682. * svgElement.setAttribute('viewBox', "0 0 200 200");
  7683. * 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"/>';
  7684. * var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
  7685. * L.svgOverlay(svgElement, svgElementBounds).addTo(map);
  7686. * ```
  7687. */
  7688. var SVGOverlay = ImageOverlay.extend({
  7689. _initImage: function () {
  7690. var el = this._image = this._url;
  7691. addClass(el, 'leaflet-image-layer');
  7692. if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); }
  7693. if (this.options.className) { addClass(el, this.options.className); }
  7694. el.onselectstart = falseFn;
  7695. el.onmousemove = falseFn;
  7696. }
  7697. // @method getElement(): SVGElement
  7698. // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
  7699. // used by this overlay.
  7700. });
  7701. // @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)
  7702. // Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.
  7703. // A viewBox attribute is required on the SVG element to zoom in and out properly.
  7704. function svgOverlay(el, bounds, options) {
  7705. return new SVGOverlay(el, bounds, options);
  7706. }
  7707. /*
  7708. * @class DivOverlay
  7709. * @inherits Layer
  7710. * @aka L.DivOverlay
  7711. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  7712. */
  7713. // @namespace DivOverlay
  7714. var DivOverlay = Layer.extend({
  7715. // @section
  7716. // @aka DivOverlay options
  7717. options: {
  7718. // @option offset: Point = Point(0, 7)
  7719. // The offset of the popup position. Useful to control the anchor
  7720. // of the popup when opening it on some overlays.
  7721. offset: [0, 7],
  7722. // @option className: String = ''
  7723. // A custom CSS class name to assign to the popup.
  7724. className: '',
  7725. // @option pane: String = 'popupPane'
  7726. // `Map pane` where the popup will be added.
  7727. pane: 'popupPane'
  7728. },
  7729. initialize: function (options, source) {
  7730. setOptions(this, options);
  7731. this._source = source;
  7732. },
  7733. onAdd: function (map) {
  7734. this._zoomAnimated = map._zoomAnimated;
  7735. if (!this._container) {
  7736. this._initLayout();
  7737. }
  7738. if (map._fadeAnimated) {
  7739. setOpacity(this._container, 0);
  7740. }
  7741. clearTimeout(this._removeTimeout);
  7742. this.getPane().appendChild(this._container);
  7743. this.update();
  7744. if (map._fadeAnimated) {
  7745. setOpacity(this._container, 1);
  7746. }
  7747. this.bringToFront();
  7748. },
  7749. onRemove: function (map) {
  7750. if (map._fadeAnimated) {
  7751. setOpacity(this._container, 0);
  7752. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  7753. } else {
  7754. remove(this._container);
  7755. }
  7756. },
  7757. // @namespace Popup
  7758. // @method getLatLng: LatLng
  7759. // Returns the geographical point of popup.
  7760. getLatLng: function () {
  7761. return this._latlng;
  7762. },
  7763. // @method setLatLng(latlng: LatLng): this
  7764. // Sets the geographical point where the popup will open.
  7765. setLatLng: function (latlng) {
  7766. this._latlng = toLatLng(latlng);
  7767. if (this._map) {
  7768. this._updatePosition();
  7769. this._adjustPan();
  7770. }
  7771. return this;
  7772. },
  7773. // @method getContent: String|HTMLElement
  7774. // Returns the content of the popup.
  7775. getContent: function () {
  7776. return this._content;
  7777. },
  7778. // @method setContent(htmlContent: String|HTMLElement|Function): this
  7779. // Sets the HTML content of the popup. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the popup.
  7780. setContent: function (content) {
  7781. this._content = content;
  7782. this.update();
  7783. return this;
  7784. },
  7785. // @method getElement: String|HTMLElement
  7786. // Returns the HTML container of the popup.
  7787. getElement: function () {
  7788. return this._container;
  7789. },
  7790. // @method update: null
  7791. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  7792. update: function () {
  7793. if (!this._map) { return; }
  7794. this._container.style.visibility = 'hidden';
  7795. this._updateContent();
  7796. this._updateLayout();
  7797. this._updatePosition();
  7798. this._container.style.visibility = '';
  7799. this._adjustPan();
  7800. },
  7801. getEvents: function () {
  7802. var events = {
  7803. zoom: this._updatePosition,
  7804. viewreset: this._updatePosition
  7805. };
  7806. if (this._zoomAnimated) {
  7807. events.zoomanim = this._animateZoom;
  7808. }
  7809. return events;
  7810. },
  7811. // @method isOpen: Boolean
  7812. // Returns `true` when the popup is visible on the map.
  7813. isOpen: function () {
  7814. return !!this._map && this._map.hasLayer(this);
  7815. },
  7816. // @method bringToFront: this
  7817. // Brings this popup in front of other popups (in the same map pane).
  7818. bringToFront: function () {
  7819. if (this._map) {
  7820. toFront(this._container);
  7821. }
  7822. return this;
  7823. },
  7824. // @method bringToBack: this
  7825. // Brings this popup to the back of other popups (in the same map pane).
  7826. bringToBack: function () {
  7827. if (this._map) {
  7828. toBack(this._container);
  7829. }
  7830. return this;
  7831. },
  7832. _prepareOpen: function (parent, layer, latlng) {
  7833. if (!(layer instanceof Layer)) {
  7834. latlng = layer;
  7835. layer = parent;
  7836. }
  7837. if (layer instanceof FeatureGroup) {
  7838. for (var id in parent._layers) {
  7839. layer = parent._layers[id];
  7840. break;
  7841. }
  7842. }
  7843. if (!latlng) {
  7844. if (layer.getCenter) {
  7845. latlng = layer.getCenter();
  7846. } else if (layer.getLatLng) {
  7847. latlng = layer.getLatLng();
  7848. } else {
  7849. throw new Error('Unable to get source layer LatLng.');
  7850. }
  7851. }
  7852. // set overlay source to this layer
  7853. this._source = layer;
  7854. // update the overlay (content, layout, ect...)
  7855. this.update();
  7856. return latlng;
  7857. },
  7858. _updateContent: function () {
  7859. if (!this._content) { return; }
  7860. var node = this._contentNode;
  7861. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  7862. if (typeof content === 'string') {
  7863. node.innerHTML = content;
  7864. } else {
  7865. while (node.hasChildNodes()) {
  7866. node.removeChild(node.firstChild);
  7867. }
  7868. node.appendChild(content);
  7869. }
  7870. this.fire('contentupdate');
  7871. },
  7872. _updatePosition: function () {
  7873. if (!this._map) { return; }
  7874. var pos = this._map.latLngToLayerPoint(this._latlng),
  7875. offset = toPoint(this.options.offset),
  7876. anchor = this._getAnchor();
  7877. if (this._zoomAnimated) {
  7878. setPosition(this._container, pos.add(anchor));
  7879. } else {
  7880. offset = offset.add(pos).add(anchor);
  7881. }
  7882. var bottom = this._containerBottom = -offset.y,
  7883. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  7884. // bottom position the popup in case the height of the popup changes (images loading etc)
  7885. this._container.style.bottom = bottom + 'px';
  7886. this._container.style.left = left + 'px';
  7887. },
  7888. _getAnchor: function () {
  7889. return [0, 0];
  7890. }
  7891. });
  7892. /*
  7893. * @class Popup
  7894. * @inherits DivOverlay
  7895. * @aka L.Popup
  7896. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  7897. * open popups while making sure that only one popup is open at one time
  7898. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  7899. *
  7900. * @example
  7901. *
  7902. * If you want to just bind a popup to marker click and then open it, it's really easy:
  7903. *
  7904. * ```js
  7905. * marker.bindPopup(popupContent).openPopup();
  7906. * ```
  7907. * Path overlays like polylines also have a `bindPopup` method.
  7908. * Here's a more complicated way to open a popup on a map:
  7909. *
  7910. * ```js
  7911. * var popup = L.popup()
  7912. * .setLatLng(latlng)
  7913. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  7914. * .openOn(map);
  7915. * ```
  7916. */
  7917. // @namespace Popup
  7918. var Popup = DivOverlay.extend({
  7919. // @section
  7920. // @aka Popup options
  7921. options: {
  7922. // @option maxWidth: Number = 300
  7923. // Max width of the popup, in pixels.
  7924. maxWidth: 300,
  7925. // @option minWidth: Number = 50
  7926. // Min width of the popup, in pixels.
  7927. minWidth: 50,
  7928. // @option maxHeight: Number = null
  7929. // If set, creates a scrollable container of the given height
  7930. // inside a popup if its content exceeds it.
  7931. maxHeight: null,
  7932. // @option autoPan: Boolean = true
  7933. // Set it to `false` if you don't want the map to do panning animation
  7934. // to fit the opened popup.
  7935. autoPan: true,
  7936. // @option autoPanPaddingTopLeft: Point = null
  7937. // The margin between the popup and the top left corner of the map
  7938. // view after autopanning was performed.
  7939. autoPanPaddingTopLeft: null,
  7940. // @option autoPanPaddingBottomRight: Point = null
  7941. // The margin between the popup and the bottom right corner of the map
  7942. // view after autopanning was performed.
  7943. autoPanPaddingBottomRight: null,
  7944. // @option autoPanPadding: Point = Point(5, 5)
  7945. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  7946. autoPanPadding: [5, 5],
  7947. // @option keepInView: Boolean = false
  7948. // Set it to `true` if you want to prevent users from panning the popup
  7949. // off of the screen while it is open.
  7950. keepInView: false,
  7951. // @option closeButton: Boolean = true
  7952. // Controls the presence of a close button in the popup.
  7953. closeButton: true,
  7954. // @option autoClose: Boolean = true
  7955. // Set it to `false` if you want to override the default behavior of
  7956. // the popup closing when another popup is opened.
  7957. autoClose: true,
  7958. // @option closeOnEscapeKey: Boolean = true
  7959. // Set it to `false` if you want to override the default behavior of
  7960. // the ESC key for closing of the popup.
  7961. closeOnEscapeKey: true,
  7962. // @option closeOnClick: Boolean = *
  7963. // Set it if you want to override the default behavior of the popup closing when user clicks
  7964. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  7965. // @option className: String = ''
  7966. // A custom CSS class name to assign to the popup.
  7967. className: ''
  7968. },
  7969. // @namespace Popup
  7970. // @method openOn(map: Map): this
  7971. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  7972. openOn: function (map) {
  7973. map.openPopup(this);
  7974. return this;
  7975. },
  7976. onAdd: function (map) {
  7977. DivOverlay.prototype.onAdd.call(this, map);
  7978. // @namespace Map
  7979. // @section Popup events
  7980. // @event popupopen: PopupEvent
  7981. // Fired when a popup is opened in the map
  7982. map.fire('popupopen', {popup: this});
  7983. if (this._source) {
  7984. // @namespace Layer
  7985. // @section Popup events
  7986. // @event popupopen: PopupEvent
  7987. // Fired when a popup bound to this layer is opened
  7988. this._source.fire('popupopen', {popup: this}, true);
  7989. // For non-path layers, we toggle the popup when clicking
  7990. // again the layer, so prevent the map to reopen it.
  7991. if (!(this._source instanceof Path)) {
  7992. this._source.on('preclick', stopPropagation);
  7993. }
  7994. }
  7995. },
  7996. onRemove: function (map) {
  7997. DivOverlay.prototype.onRemove.call(this, map);
  7998. // @namespace Map
  7999. // @section Popup events
  8000. // @event popupclose: PopupEvent
  8001. // Fired when a popup in the map is closed
  8002. map.fire('popupclose', {popup: this});
  8003. if (this._source) {
  8004. // @namespace Layer
  8005. // @section Popup events
  8006. // @event popupclose: PopupEvent
  8007. // Fired when a popup bound to this layer is closed
  8008. this._source.fire('popupclose', {popup: this}, true);
  8009. if (!(this._source instanceof Path)) {
  8010. this._source.off('preclick', stopPropagation);
  8011. }
  8012. }
  8013. },
  8014. getEvents: function () {
  8015. var events = DivOverlay.prototype.getEvents.call(this);
  8016. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  8017. events.preclick = this._close;
  8018. }
  8019. if (this.options.keepInView) {
  8020. events.moveend = this._adjustPan;
  8021. }
  8022. return events;
  8023. },
  8024. _close: function () {
  8025. if (this._map) {
  8026. this._map.closePopup(this);
  8027. }
  8028. },
  8029. _initLayout: function () {
  8030. var prefix = 'leaflet-popup',
  8031. container = this._container = create$1('div',
  8032. prefix + ' ' + (this.options.className || '') +
  8033. ' leaflet-zoom-animated');
  8034. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  8035. this._contentNode = create$1('div', prefix + '-content', wrapper);
  8036. disableClickPropagation(container);
  8037. disableScrollPropagation(this._contentNode);
  8038. on(container, 'contextmenu', stopPropagation);
  8039. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  8040. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  8041. if (this.options.closeButton) {
  8042. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  8043. closeButton.href = '#close';
  8044. closeButton.innerHTML = '&#215;';
  8045. on(closeButton, 'click', this._onCloseButtonClick, this);
  8046. }
  8047. },
  8048. _updateLayout: function () {
  8049. var container = this._contentNode,
  8050. style = container.style;
  8051. style.width = '';
  8052. style.whiteSpace = 'nowrap';
  8053. var width = container.offsetWidth;
  8054. width = Math.min(width, this.options.maxWidth);
  8055. width = Math.max(width, this.options.minWidth);
  8056. style.width = (width + 1) + 'px';
  8057. style.whiteSpace = '';
  8058. style.height = '';
  8059. var height = container.offsetHeight,
  8060. maxHeight = this.options.maxHeight,
  8061. scrolledClass = 'leaflet-popup-scrolled';
  8062. if (maxHeight && height > maxHeight) {
  8063. style.height = maxHeight + 'px';
  8064. addClass(container, scrolledClass);
  8065. } else {
  8066. removeClass(container, scrolledClass);
  8067. }
  8068. this._containerWidth = this._container.offsetWidth;
  8069. },
  8070. _animateZoom: function (e) {
  8071. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  8072. anchor = this._getAnchor();
  8073. setPosition(this._container, pos.add(anchor));
  8074. },
  8075. _adjustPan: function () {
  8076. if (!this.options.autoPan) { return; }
  8077. if (this._map._panAnim) { this._map._panAnim.stop(); }
  8078. var map = this._map,
  8079. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  8080. containerHeight = this._container.offsetHeight + marginBottom,
  8081. containerWidth = this._containerWidth,
  8082. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  8083. layerPos._add(getPosition(this._container));
  8084. var containerPos = map.layerPointToContainerPoint(layerPos),
  8085. padding = toPoint(this.options.autoPanPadding),
  8086. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  8087. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  8088. size = map.getSize(),
  8089. dx = 0,
  8090. dy = 0;
  8091. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  8092. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  8093. }
  8094. if (containerPos.x - dx - paddingTL.x < 0) { // left
  8095. dx = containerPos.x - paddingTL.x;
  8096. }
  8097. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  8098. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  8099. }
  8100. if (containerPos.y - dy - paddingTL.y < 0) { // top
  8101. dy = containerPos.y - paddingTL.y;
  8102. }
  8103. // @namespace Map
  8104. // @section Popup events
  8105. // @event autopanstart: Event
  8106. // Fired when the map starts autopanning when opening a popup.
  8107. if (dx || dy) {
  8108. map
  8109. .fire('autopanstart')
  8110. .panBy([dx, dy]);
  8111. }
  8112. },
  8113. _onCloseButtonClick: function (e) {
  8114. this._close();
  8115. stop(e);
  8116. },
  8117. _getAnchor: function () {
  8118. // Where should we anchor the popup on the source layer?
  8119. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  8120. }
  8121. });
  8122. // @namespace Popup
  8123. // @factory L.popup(options?: Popup options, source?: Layer)
  8124. // 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.
  8125. var popup = function (options, source) {
  8126. return new Popup(options, source);
  8127. };
  8128. /* @namespace Map
  8129. * @section Interaction Options
  8130. * @option closePopupOnClick: Boolean = true
  8131. * Set it to `false` if you don't want popups to close when user clicks the map.
  8132. */
  8133. Map.mergeOptions({
  8134. closePopupOnClick: true
  8135. });
  8136. // @namespace Map
  8137. // @section Methods for Layers and Controls
  8138. Map.include({
  8139. // @method openPopup(popup: Popup): this
  8140. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  8141. // @alternative
  8142. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  8143. // Creates a popup with the specified content and options and opens it in the given point on a map.
  8144. openPopup: function (popup, latlng, options) {
  8145. if (!(popup instanceof Popup)) {
  8146. popup = new Popup(options).setContent(popup);
  8147. }
  8148. if (latlng) {
  8149. popup.setLatLng(latlng);
  8150. }
  8151. if (this.hasLayer(popup)) {
  8152. return this;
  8153. }
  8154. if (this._popup && this._popup.options.autoClose) {
  8155. this.closePopup();
  8156. }
  8157. this._popup = popup;
  8158. return this.addLayer(popup);
  8159. },
  8160. // @method closePopup(popup?: Popup): this
  8161. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  8162. closePopup: function (popup) {
  8163. if (!popup || popup === this._popup) {
  8164. popup = this._popup;
  8165. this._popup = null;
  8166. }
  8167. if (popup) {
  8168. this.removeLayer(popup);
  8169. }
  8170. return this;
  8171. }
  8172. });
  8173. /*
  8174. * @namespace Layer
  8175. * @section Popup methods example
  8176. *
  8177. * All layers share a set of methods convenient for binding popups to it.
  8178. *
  8179. * ```js
  8180. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  8181. * layer.openPopup();
  8182. * layer.closePopup();
  8183. * ```
  8184. *
  8185. * 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.
  8186. */
  8187. // @section Popup methods
  8188. Layer.include({
  8189. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  8190. // Binds a popup to the layer with the passed `content` and sets up the
  8191. // necessary event listeners. If a `Function` is passed it will receive
  8192. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8193. bindPopup: function (content, options) {
  8194. if (content instanceof Popup) {
  8195. setOptions(content, options);
  8196. this._popup = content;
  8197. content._source = this;
  8198. } else {
  8199. if (!this._popup || options) {
  8200. this._popup = new Popup(options, this);
  8201. }
  8202. this._popup.setContent(content);
  8203. }
  8204. if (!this._popupHandlersAdded) {
  8205. this.on({
  8206. click: this._openPopup,
  8207. keypress: this._onKeyPress,
  8208. remove: this.closePopup,
  8209. move: this._movePopup
  8210. });
  8211. this._popupHandlersAdded = true;
  8212. }
  8213. return this;
  8214. },
  8215. // @method unbindPopup(): this
  8216. // Removes the popup previously bound with `bindPopup`.
  8217. unbindPopup: function () {
  8218. if (this._popup) {
  8219. this.off({
  8220. click: this._openPopup,
  8221. keypress: this._onKeyPress,
  8222. remove: this.closePopup,
  8223. move: this._movePopup
  8224. });
  8225. this._popupHandlersAdded = false;
  8226. this._popup = null;
  8227. }
  8228. return this;
  8229. },
  8230. // @method openPopup(latlng?: LatLng): this
  8231. // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
  8232. openPopup: function (layer, latlng) {
  8233. if (this._popup && this._map) {
  8234. latlng = this._popup._prepareOpen(this, layer, latlng);
  8235. // open the popup on the map
  8236. this._map.openPopup(this._popup, latlng);
  8237. }
  8238. return this;
  8239. },
  8240. // @method closePopup(): this
  8241. // Closes the popup bound to this layer if it is open.
  8242. closePopup: function () {
  8243. if (this._popup) {
  8244. this._popup._close();
  8245. }
  8246. return this;
  8247. },
  8248. // @method togglePopup(): this
  8249. // Opens or closes the popup bound to this layer depending on its current state.
  8250. togglePopup: function (target) {
  8251. if (this._popup) {
  8252. if (this._popup._map) {
  8253. this.closePopup();
  8254. } else {
  8255. this.openPopup(target);
  8256. }
  8257. }
  8258. return this;
  8259. },
  8260. // @method isPopupOpen(): boolean
  8261. // Returns `true` if the popup bound to this layer is currently open.
  8262. isPopupOpen: function () {
  8263. return (this._popup ? this._popup.isOpen() : false);
  8264. },
  8265. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8266. // Sets the content of the popup bound to this layer.
  8267. setPopupContent: function (content) {
  8268. if (this._popup) {
  8269. this._popup.setContent(content);
  8270. }
  8271. return this;
  8272. },
  8273. // @method getPopup(): Popup
  8274. // Returns the popup bound to this layer.
  8275. getPopup: function () {
  8276. return this._popup;
  8277. },
  8278. _openPopup: function (e) {
  8279. var layer = e.layer || e.target;
  8280. if (!this._popup) {
  8281. return;
  8282. }
  8283. if (!this._map) {
  8284. return;
  8285. }
  8286. // prevent map click
  8287. stop(e);
  8288. // if this inherits from Path its a vector and we can just
  8289. // open the popup at the new location
  8290. if (layer instanceof Path) {
  8291. this.openPopup(e.layer || e.target, e.latlng);
  8292. return;
  8293. }
  8294. // otherwise treat it like a marker and figure out
  8295. // if we should toggle it open/closed
  8296. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  8297. this.closePopup();
  8298. } else {
  8299. this.openPopup(layer, e.latlng);
  8300. }
  8301. },
  8302. _movePopup: function (e) {
  8303. this._popup.setLatLng(e.latlng);
  8304. },
  8305. _onKeyPress: function (e) {
  8306. if (e.originalEvent.keyCode === 13) {
  8307. this._openPopup(e);
  8308. }
  8309. }
  8310. });
  8311. /*
  8312. * @class Tooltip
  8313. * @inherits DivOverlay
  8314. * @aka L.Tooltip
  8315. * Used to display small texts on top of map layers.
  8316. *
  8317. * @example
  8318. *
  8319. * ```js
  8320. * marker.bindTooltip("my tooltip text").openTooltip();
  8321. * ```
  8322. * Note about tooltip offset. Leaflet takes two options in consideration
  8323. * for computing tooltip offsetting:
  8324. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8325. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8326. * move it to the bottom. Negatives will move to the left and top.
  8327. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8328. * should adapt this value if you use a custom icon.
  8329. */
  8330. // @namespace Tooltip
  8331. var Tooltip = DivOverlay.extend({
  8332. // @section
  8333. // @aka Tooltip options
  8334. options: {
  8335. // @option pane: String = 'tooltipPane'
  8336. // `Map pane` where the tooltip will be added.
  8337. pane: 'tooltipPane',
  8338. // @option offset: Point = Point(0, 0)
  8339. // Optional offset of the tooltip position.
  8340. offset: [0, 0],
  8341. // @option direction: String = 'auto'
  8342. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8343. // `top`, `bottom`, `center`, `auto`.
  8344. // `auto` will dynamically switch between `right` and `left` according to the tooltip
  8345. // position on the map.
  8346. direction: 'auto',
  8347. // @option permanent: Boolean = false
  8348. // Whether to open the tooltip permanently or only on mouseover.
  8349. permanent: false,
  8350. // @option sticky: Boolean = false
  8351. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8352. sticky: false,
  8353. // @option interactive: Boolean = false
  8354. // If true, the tooltip will listen to the feature events.
  8355. interactive: false,
  8356. // @option opacity: Number = 0.9
  8357. // Tooltip container opacity.
  8358. opacity: 0.9
  8359. },
  8360. onAdd: function (map) {
  8361. DivOverlay.prototype.onAdd.call(this, map);
  8362. this.setOpacity(this.options.opacity);
  8363. // @namespace Map
  8364. // @section Tooltip events
  8365. // @event tooltipopen: TooltipEvent
  8366. // Fired when a tooltip is opened in the map.
  8367. map.fire('tooltipopen', {tooltip: this});
  8368. if (this._source) {
  8369. // @namespace Layer
  8370. // @section Tooltip events
  8371. // @event tooltipopen: TooltipEvent
  8372. // Fired when a tooltip bound to this layer is opened.
  8373. this._source.fire('tooltipopen', {tooltip: this}, true);
  8374. }
  8375. },
  8376. onRemove: function (map) {
  8377. DivOverlay.prototype.onRemove.call(this, map);
  8378. // @namespace Map
  8379. // @section Tooltip events
  8380. // @event tooltipclose: TooltipEvent
  8381. // Fired when a tooltip in the map is closed.
  8382. map.fire('tooltipclose', {tooltip: this});
  8383. if (this._source) {
  8384. // @namespace Layer
  8385. // @section Tooltip events
  8386. // @event tooltipclose: TooltipEvent
  8387. // Fired when a tooltip bound to this layer is closed.
  8388. this._source.fire('tooltipclose', {tooltip: this}, true);
  8389. }
  8390. },
  8391. getEvents: function () {
  8392. var events = DivOverlay.prototype.getEvents.call(this);
  8393. if (touch && !this.options.permanent) {
  8394. events.preclick = this._close;
  8395. }
  8396. return events;
  8397. },
  8398. _close: function () {
  8399. if (this._map) {
  8400. this._map.closeTooltip(this);
  8401. }
  8402. },
  8403. _initLayout: function () {
  8404. var prefix = 'leaflet-tooltip',
  8405. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8406. this._contentNode = this._container = create$1('div', className);
  8407. },
  8408. _updateLayout: function () {},
  8409. _adjustPan: function () {},
  8410. _setPosition: function (pos) {
  8411. var subX, subY,
  8412. map = this._map,
  8413. container = this._container,
  8414. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8415. tooltipPoint = map.layerPointToContainerPoint(pos),
  8416. direction = this.options.direction,
  8417. tooltipWidth = container.offsetWidth,
  8418. tooltipHeight = container.offsetHeight,
  8419. offset = toPoint(this.options.offset),
  8420. anchor = this._getAnchor();
  8421. if (direction === 'top') {
  8422. subX = tooltipWidth / 2;
  8423. subY = tooltipHeight;
  8424. } else if (direction === 'bottom') {
  8425. subX = tooltipWidth / 2;
  8426. subY = 0;
  8427. } else if (direction === 'center') {
  8428. subX = tooltipWidth / 2;
  8429. subY = tooltipHeight / 2;
  8430. } else if (direction === 'right') {
  8431. subX = 0;
  8432. subY = tooltipHeight / 2;
  8433. } else if (direction === 'left') {
  8434. subX = tooltipWidth;
  8435. subY = tooltipHeight / 2;
  8436. } else if (tooltipPoint.x < centerPoint.x) {
  8437. direction = 'right';
  8438. subX = 0;
  8439. subY = tooltipHeight / 2;
  8440. } else {
  8441. direction = 'left';
  8442. subX = tooltipWidth + (offset.x + anchor.x) * 2;
  8443. subY = tooltipHeight / 2;
  8444. }
  8445. pos = pos.subtract(toPoint(subX, subY, true)).add(offset).add(anchor);
  8446. removeClass(container, 'leaflet-tooltip-right');
  8447. removeClass(container, 'leaflet-tooltip-left');
  8448. removeClass(container, 'leaflet-tooltip-top');
  8449. removeClass(container, 'leaflet-tooltip-bottom');
  8450. addClass(container, 'leaflet-tooltip-' + direction);
  8451. setPosition(container, pos);
  8452. },
  8453. _updatePosition: function () {
  8454. var pos = this._map.latLngToLayerPoint(this._latlng);
  8455. this._setPosition(pos);
  8456. },
  8457. setOpacity: function (opacity) {
  8458. this.options.opacity = opacity;
  8459. if (this._container) {
  8460. setOpacity(this._container, opacity);
  8461. }
  8462. },
  8463. _animateZoom: function (e) {
  8464. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8465. this._setPosition(pos);
  8466. },
  8467. _getAnchor: function () {
  8468. // Where should we anchor the tooltip on the source layer?
  8469. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8470. }
  8471. });
  8472. // @namespace Tooltip
  8473. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8474. // 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.
  8475. var tooltip = function (options, source) {
  8476. return new Tooltip(options, source);
  8477. };
  8478. // @namespace Map
  8479. // @section Methods for Layers and Controls
  8480. Map.include({
  8481. // @method openTooltip(tooltip: Tooltip): this
  8482. // Opens the specified tooltip.
  8483. // @alternative
  8484. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8485. // Creates a tooltip with the specified content and options and open it.
  8486. openTooltip: function (tooltip, latlng, options) {
  8487. if (!(tooltip instanceof Tooltip)) {
  8488. tooltip = new Tooltip(options).setContent(tooltip);
  8489. }
  8490. if (latlng) {
  8491. tooltip.setLatLng(latlng);
  8492. }
  8493. if (this.hasLayer(tooltip)) {
  8494. return this;
  8495. }
  8496. return this.addLayer(tooltip);
  8497. },
  8498. // @method closeTooltip(tooltip?: Tooltip): this
  8499. // Closes the tooltip given as parameter.
  8500. closeTooltip: function (tooltip) {
  8501. if (tooltip) {
  8502. this.removeLayer(tooltip);
  8503. }
  8504. return this;
  8505. }
  8506. });
  8507. /*
  8508. * @namespace Layer
  8509. * @section Tooltip methods example
  8510. *
  8511. * All layers share a set of methods convenient for binding tooltips to it.
  8512. *
  8513. * ```js
  8514. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8515. * layer.openTooltip();
  8516. * layer.closeTooltip();
  8517. * ```
  8518. */
  8519. // @section Tooltip methods
  8520. Layer.include({
  8521. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8522. // Binds a tooltip to the layer with the passed `content` and sets up the
  8523. // necessary event listeners. If a `Function` is passed it will receive
  8524. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8525. bindTooltip: function (content, options) {
  8526. if (content instanceof Tooltip) {
  8527. setOptions(content, options);
  8528. this._tooltip = content;
  8529. content._source = this;
  8530. } else {
  8531. if (!this._tooltip || options) {
  8532. this._tooltip = new Tooltip(options, this);
  8533. }
  8534. this._tooltip.setContent(content);
  8535. }
  8536. this._initTooltipInteractions();
  8537. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8538. this.openTooltip();
  8539. }
  8540. return this;
  8541. },
  8542. // @method unbindTooltip(): this
  8543. // Removes the tooltip previously bound with `bindTooltip`.
  8544. unbindTooltip: function () {
  8545. if (this._tooltip) {
  8546. this._initTooltipInteractions(true);
  8547. this.closeTooltip();
  8548. this._tooltip = null;
  8549. }
  8550. return this;
  8551. },
  8552. _initTooltipInteractions: function (remove$$1) {
  8553. if (!remove$$1 && this._tooltipHandlersAdded) { return; }
  8554. var onOff = remove$$1 ? 'off' : 'on',
  8555. events = {
  8556. remove: this.closeTooltip,
  8557. move: this._moveTooltip
  8558. };
  8559. if (!this._tooltip.options.permanent) {
  8560. events.mouseover = this._openTooltip;
  8561. events.mouseout = this.closeTooltip;
  8562. if (this._tooltip.options.sticky) {
  8563. events.mousemove = this._moveTooltip;
  8564. }
  8565. if (touch) {
  8566. events.click = this._openTooltip;
  8567. }
  8568. } else {
  8569. events.add = this._openTooltip;
  8570. }
  8571. this[onOff](events);
  8572. this._tooltipHandlersAdded = !remove$$1;
  8573. },
  8574. // @method openTooltip(latlng?: LatLng): this
  8575. // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8576. openTooltip: function (layer, latlng) {
  8577. if (this._tooltip && this._map) {
  8578. latlng = this._tooltip._prepareOpen(this, layer, latlng);
  8579. // open the tooltip on the map
  8580. this._map.openTooltip(this._tooltip, latlng);
  8581. // Tooltip container may not be defined if not permanent and never
  8582. // opened.
  8583. if (this._tooltip.options.interactive && this._tooltip._container) {
  8584. addClass(this._tooltip._container, 'leaflet-clickable');
  8585. this.addInteractiveTarget(this._tooltip._container);
  8586. }
  8587. }
  8588. return this;
  8589. },
  8590. // @method closeTooltip(): this
  8591. // Closes the tooltip bound to this layer if it is open.
  8592. closeTooltip: function () {
  8593. if (this._tooltip) {
  8594. this._tooltip._close();
  8595. if (this._tooltip.options.interactive && this._tooltip._container) {
  8596. removeClass(this._tooltip._container, 'leaflet-clickable');
  8597. this.removeInteractiveTarget(this._tooltip._container);
  8598. }
  8599. }
  8600. return this;
  8601. },
  8602. // @method toggleTooltip(): this
  8603. // Opens or closes the tooltip bound to this layer depending on its current state.
  8604. toggleTooltip: function (target) {
  8605. if (this._tooltip) {
  8606. if (this._tooltip._map) {
  8607. this.closeTooltip();
  8608. } else {
  8609. this.openTooltip(target);
  8610. }
  8611. }
  8612. return this;
  8613. },
  8614. // @method isTooltipOpen(): boolean
  8615. // Returns `true` if the tooltip bound to this layer is currently open.
  8616. isTooltipOpen: function () {
  8617. return this._tooltip.isOpen();
  8618. },
  8619. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8620. // Sets the content of the tooltip bound to this layer.
  8621. setTooltipContent: function (content) {
  8622. if (this._tooltip) {
  8623. this._tooltip.setContent(content);
  8624. }
  8625. return this;
  8626. },
  8627. // @method getTooltip(): Tooltip
  8628. // Returns the tooltip bound to this layer.
  8629. getTooltip: function () {
  8630. return this._tooltip;
  8631. },
  8632. _openTooltip: function (e) {
  8633. var layer = e.layer || e.target;
  8634. if (!this._tooltip || !this._map) {
  8635. return;
  8636. }
  8637. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  8638. },
  8639. _moveTooltip: function (e) {
  8640. var latlng = e.latlng, containerPoint, layerPoint;
  8641. if (this._tooltip.options.sticky && e.originalEvent) {
  8642. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  8643. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  8644. latlng = this._map.layerPointToLatLng(layerPoint);
  8645. }
  8646. this._tooltip.setLatLng(latlng);
  8647. }
  8648. });
  8649. /*
  8650. * @class DivIcon
  8651. * @aka L.DivIcon
  8652. * @inherits Icon
  8653. *
  8654. * Represents a lightweight icon for markers that uses a simple `<div>`
  8655. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  8656. *
  8657. * @example
  8658. * ```js
  8659. * var myIcon = L.divIcon({className: 'my-div-icon'});
  8660. * // you can set .my-div-icon styles in CSS
  8661. *
  8662. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  8663. * ```
  8664. *
  8665. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  8666. */
  8667. var DivIcon = Icon.extend({
  8668. options: {
  8669. // @section
  8670. // @aka DivIcon options
  8671. iconSize: [12, 12], // also can be set through CSS
  8672. // iconAnchor: (Point),
  8673. // popupAnchor: (Point),
  8674. // @option html: String|HTMLElement = ''
  8675. // Custom HTML code to put inside the div element, empty by default. Alternatively,
  8676. // an instance of `HTMLElement`.
  8677. html: false,
  8678. // @option bgPos: Point = [0, 0]
  8679. // Optional relative position of the background, in pixels
  8680. bgPos: null,
  8681. className: 'leaflet-div-icon'
  8682. },
  8683. createIcon: function (oldIcon) {
  8684. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  8685. options = this.options;
  8686. if (options.html instanceof Element) {
  8687. empty(div);
  8688. div.appendChild(options.html);
  8689. } else {
  8690. div.innerHTML = options.html !== false ? options.html : '';
  8691. }
  8692. if (options.bgPos) {
  8693. var bgPos = toPoint(options.bgPos);
  8694. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  8695. }
  8696. this._setIconStyles(div, 'icon');
  8697. return div;
  8698. },
  8699. createShadow: function () {
  8700. return null;
  8701. }
  8702. });
  8703. // @factory L.divIcon(options: DivIcon options)
  8704. // Creates a `DivIcon` instance with the given options.
  8705. function divIcon(options) {
  8706. return new DivIcon(options);
  8707. }
  8708. Icon.Default = IconDefault;
  8709. /*
  8710. * @class GridLayer
  8711. * @inherits Layer
  8712. * @aka L.GridLayer
  8713. *
  8714. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  8715. * 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.
  8716. *
  8717. *
  8718. * @section Synchronous usage
  8719. * @example
  8720. *
  8721. * 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.
  8722. *
  8723. * ```js
  8724. * var CanvasLayer = L.GridLayer.extend({
  8725. * createTile: function(coords){
  8726. * // create a <canvas> element for drawing
  8727. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8728. *
  8729. * // setup tile width and height according to the options
  8730. * var size = this.getTileSize();
  8731. * tile.width = size.x;
  8732. * tile.height = size.y;
  8733. *
  8734. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  8735. * var ctx = tile.getContext('2d');
  8736. *
  8737. * // return the tile so it can be rendered on screen
  8738. * return tile;
  8739. * }
  8740. * });
  8741. * ```
  8742. *
  8743. * @section Asynchronous usage
  8744. * @example
  8745. *
  8746. * 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.
  8747. *
  8748. * ```js
  8749. * var CanvasLayer = L.GridLayer.extend({
  8750. * createTile: function(coords, done){
  8751. * var error;
  8752. *
  8753. * // create a <canvas> element for drawing
  8754. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8755. *
  8756. * // setup tile width and height according to the options
  8757. * var size = this.getTileSize();
  8758. * tile.width = size.x;
  8759. * tile.height = size.y;
  8760. *
  8761. * // draw something asynchronously and pass the tile to the done() callback
  8762. * setTimeout(function() {
  8763. * done(error, tile);
  8764. * }, 1000);
  8765. *
  8766. * return tile;
  8767. * }
  8768. * });
  8769. * ```
  8770. *
  8771. * @section
  8772. */
  8773. var GridLayer = Layer.extend({
  8774. // @section
  8775. // @aka GridLayer options
  8776. options: {
  8777. // @option tileSize: Number|Point = 256
  8778. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  8779. tileSize: 256,
  8780. // @option opacity: Number = 1.0
  8781. // Opacity of the tiles. Can be used in the `createTile()` function.
  8782. opacity: 1,
  8783. // @option updateWhenIdle: Boolean = (depends)
  8784. // Load new tiles only when panning ends.
  8785. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  8786. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  8787. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  8788. updateWhenIdle: mobile,
  8789. // @option updateWhenZooming: Boolean = true
  8790. // 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.
  8791. updateWhenZooming: true,
  8792. // @option updateInterval: Number = 200
  8793. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  8794. updateInterval: 200,
  8795. // @option zIndex: Number = 1
  8796. // The explicit zIndex of the tile layer.
  8797. zIndex: 1,
  8798. // @option bounds: LatLngBounds = undefined
  8799. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  8800. bounds: null,
  8801. // @option minZoom: Number = 0
  8802. // The minimum zoom level down to which this layer will be displayed (inclusive).
  8803. minZoom: 0,
  8804. // @option maxZoom: Number = undefined
  8805. // The maximum zoom level up to which this layer will be displayed (inclusive).
  8806. maxZoom: undefined,
  8807. // @option maxNativeZoom: Number = undefined
  8808. // Maximum zoom number the tile source has available. If it is specified,
  8809. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  8810. // from `maxNativeZoom` level and auto-scaled.
  8811. maxNativeZoom: undefined,
  8812. // @option minNativeZoom: Number = undefined
  8813. // Minimum zoom number the tile source has available. If it is specified,
  8814. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  8815. // from `minNativeZoom` level and auto-scaled.
  8816. minNativeZoom: undefined,
  8817. // @option noWrap: Boolean = false
  8818. // Whether the layer is wrapped around the antimeridian. If `true`, the
  8819. // GridLayer will only be displayed once at low zoom levels. Has no
  8820. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  8821. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  8822. // tiles outside the CRS limits.
  8823. noWrap: false,
  8824. // @option pane: String = 'tilePane'
  8825. // `Map pane` where the grid layer will be added.
  8826. pane: 'tilePane',
  8827. // @option className: String = ''
  8828. // A custom class name to assign to the tile layer. Empty by default.
  8829. className: '',
  8830. // @option keepBuffer: Number = 2
  8831. // When panning the map, keep this many rows and columns of tiles before unloading them.
  8832. keepBuffer: 2
  8833. },
  8834. initialize: function (options) {
  8835. setOptions(this, options);
  8836. },
  8837. onAdd: function () {
  8838. this._initContainer();
  8839. this._levels = {};
  8840. this._tiles = {};
  8841. this._resetView();
  8842. this._update();
  8843. },
  8844. beforeAdd: function (map) {
  8845. map._addZoomLimit(this);
  8846. },
  8847. onRemove: function (map) {
  8848. this._removeAllTiles();
  8849. remove(this._container);
  8850. map._removeZoomLimit(this);
  8851. this._container = null;
  8852. this._tileZoom = undefined;
  8853. },
  8854. // @method bringToFront: this
  8855. // Brings the tile layer to the top of all tile layers.
  8856. bringToFront: function () {
  8857. if (this._map) {
  8858. toFront(this._container);
  8859. this._setAutoZIndex(Math.max);
  8860. }
  8861. return this;
  8862. },
  8863. // @method bringToBack: this
  8864. // Brings the tile layer to the bottom of all tile layers.
  8865. bringToBack: function () {
  8866. if (this._map) {
  8867. toBack(this._container);
  8868. this._setAutoZIndex(Math.min);
  8869. }
  8870. return this;
  8871. },
  8872. // @method getContainer: HTMLElement
  8873. // Returns the HTML element that contains the tiles for this layer.
  8874. getContainer: function () {
  8875. return this._container;
  8876. },
  8877. // @method setOpacity(opacity: Number): this
  8878. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  8879. setOpacity: function (opacity) {
  8880. this.options.opacity = opacity;
  8881. this._updateOpacity();
  8882. return this;
  8883. },
  8884. // @method setZIndex(zIndex: Number): this
  8885. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  8886. setZIndex: function (zIndex) {
  8887. this.options.zIndex = zIndex;
  8888. this._updateZIndex();
  8889. return this;
  8890. },
  8891. // @method isLoading: Boolean
  8892. // Returns `true` if any tile in the grid layer has not finished loading.
  8893. isLoading: function () {
  8894. return this._loading;
  8895. },
  8896. // @method redraw: this
  8897. // Causes the layer to clear all the tiles and request them again.
  8898. redraw: function () {
  8899. if (this._map) {
  8900. this._removeAllTiles();
  8901. this._update();
  8902. }
  8903. return this;
  8904. },
  8905. getEvents: function () {
  8906. var events = {
  8907. viewprereset: this._invalidateAll,
  8908. viewreset: this._resetView,
  8909. zoom: this._resetView,
  8910. moveend: this._onMoveEnd
  8911. };
  8912. if (!this.options.updateWhenIdle) {
  8913. // update tiles on move, but not more often than once per given interval
  8914. if (!this._onMove) {
  8915. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  8916. }
  8917. events.move = this._onMove;
  8918. }
  8919. if (this._zoomAnimated) {
  8920. events.zoomanim = this._animateZoom;
  8921. }
  8922. return events;
  8923. },
  8924. // @section Extension methods
  8925. // Layers extending `GridLayer` shall reimplement the following method.
  8926. // @method createTile(coords: Object, done?: Function): HTMLElement
  8927. // Called only internally, must be overridden by classes extending `GridLayer`.
  8928. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  8929. // is specified, it must be called when the tile has finished loading and drawing.
  8930. createTile: function () {
  8931. return document.createElement('div');
  8932. },
  8933. // @section
  8934. // @method getTileSize: Point
  8935. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  8936. getTileSize: function () {
  8937. var s = this.options.tileSize;
  8938. return s instanceof Point ? s : new Point(s, s);
  8939. },
  8940. _updateZIndex: function () {
  8941. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  8942. this._container.style.zIndex = this.options.zIndex;
  8943. }
  8944. },
  8945. _setAutoZIndex: function (compare) {
  8946. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  8947. var layers = this.getPane().children,
  8948. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  8949. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  8950. zIndex = layers[i].style.zIndex;
  8951. if (layers[i] !== this._container && zIndex) {
  8952. edgeZIndex = compare(edgeZIndex, +zIndex);
  8953. }
  8954. }
  8955. if (isFinite(edgeZIndex)) {
  8956. this.options.zIndex = edgeZIndex + compare(-1, 1);
  8957. this._updateZIndex();
  8958. }
  8959. },
  8960. _updateOpacity: function () {
  8961. if (!this._map) { return; }
  8962. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  8963. if (ielt9) { return; }
  8964. setOpacity(this._container, this.options.opacity);
  8965. var now = +new Date(),
  8966. nextFrame = false,
  8967. willPrune = false;
  8968. for (var key in this._tiles) {
  8969. var tile = this._tiles[key];
  8970. if (!tile.current || !tile.loaded) { continue; }
  8971. var fade = Math.min(1, (now - tile.loaded) / 200);
  8972. setOpacity(tile.el, fade);
  8973. if (fade < 1) {
  8974. nextFrame = true;
  8975. } else {
  8976. if (tile.active) {
  8977. willPrune = true;
  8978. } else {
  8979. this._onOpaqueTile(tile);
  8980. }
  8981. tile.active = true;
  8982. }
  8983. }
  8984. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  8985. if (nextFrame) {
  8986. cancelAnimFrame(this._fadeFrame);
  8987. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  8988. }
  8989. },
  8990. _onOpaqueTile: falseFn,
  8991. _initContainer: function () {
  8992. if (this._container) { return; }
  8993. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  8994. this._updateZIndex();
  8995. if (this.options.opacity < 1) {
  8996. this._updateOpacity();
  8997. }
  8998. this.getPane().appendChild(this._container);
  8999. },
  9000. _updateLevels: function () {
  9001. var zoom = this._tileZoom,
  9002. maxZoom = this.options.maxZoom;
  9003. if (zoom === undefined) { return undefined; }
  9004. for (var z in this._levels) {
  9005. z = Number(z);
  9006. if (this._levels[z].el.children.length || z === zoom) {
  9007. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  9008. this._onUpdateLevel(z);
  9009. } else {
  9010. remove(this._levels[z].el);
  9011. this._removeTilesAtZoom(z);
  9012. this._onRemoveLevel(z);
  9013. delete this._levels[z];
  9014. }
  9015. }
  9016. var level = this._levels[zoom],
  9017. map = this._map;
  9018. if (!level) {
  9019. level = this._levels[zoom] = {};
  9020. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  9021. level.el.style.zIndex = maxZoom;
  9022. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  9023. level.zoom = zoom;
  9024. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  9025. // force the browser to consider the newly added element for transition
  9026. falseFn(level.el.offsetWidth);
  9027. this._onCreateLevel(level);
  9028. }
  9029. this._level = level;
  9030. return level;
  9031. },
  9032. _onUpdateLevel: falseFn,
  9033. _onRemoveLevel: falseFn,
  9034. _onCreateLevel: falseFn,
  9035. _pruneTiles: function () {
  9036. if (!this._map) {
  9037. return;
  9038. }
  9039. var key, tile;
  9040. var zoom = this._map.getZoom();
  9041. if (zoom > this.options.maxZoom ||
  9042. zoom < this.options.minZoom) {
  9043. this._removeAllTiles();
  9044. return;
  9045. }
  9046. for (key in this._tiles) {
  9047. tile = this._tiles[key];
  9048. tile.retain = tile.current;
  9049. }
  9050. for (key in this._tiles) {
  9051. tile = this._tiles[key];
  9052. if (tile.current && !tile.active) {
  9053. var coords = tile.coords;
  9054. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  9055. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  9056. }
  9057. }
  9058. }
  9059. for (key in this._tiles) {
  9060. if (!this._tiles[key].retain) {
  9061. this._removeTile(key);
  9062. }
  9063. }
  9064. },
  9065. _removeTilesAtZoom: function (zoom) {
  9066. for (var key in this._tiles) {
  9067. if (this._tiles[key].coords.z !== zoom) {
  9068. continue;
  9069. }
  9070. this._removeTile(key);
  9071. }
  9072. },
  9073. _removeAllTiles: function () {
  9074. for (var key in this._tiles) {
  9075. this._removeTile(key);
  9076. }
  9077. },
  9078. _invalidateAll: function () {
  9079. for (var z in this._levels) {
  9080. remove(this._levels[z].el);
  9081. this._onRemoveLevel(Number(z));
  9082. delete this._levels[z];
  9083. }
  9084. this._removeAllTiles();
  9085. this._tileZoom = undefined;
  9086. },
  9087. _retainParent: function (x, y, z, minZoom) {
  9088. var x2 = Math.floor(x / 2),
  9089. y2 = Math.floor(y / 2),
  9090. z2 = z - 1,
  9091. coords2 = new Point(+x2, +y2);
  9092. coords2.z = +z2;
  9093. var key = this._tileCoordsToKey(coords2),
  9094. tile = this._tiles[key];
  9095. if (tile && tile.active) {
  9096. tile.retain = true;
  9097. return true;
  9098. } else if (tile && tile.loaded) {
  9099. tile.retain = true;
  9100. }
  9101. if (z2 > minZoom) {
  9102. return this._retainParent(x2, y2, z2, minZoom);
  9103. }
  9104. return false;
  9105. },
  9106. _retainChildren: function (x, y, z, maxZoom) {
  9107. for (var i = 2 * x; i < 2 * x + 2; i++) {
  9108. for (var j = 2 * y; j < 2 * y + 2; j++) {
  9109. var coords = new Point(i, j);
  9110. coords.z = z + 1;
  9111. var key = this._tileCoordsToKey(coords),
  9112. tile = this._tiles[key];
  9113. if (tile && tile.active) {
  9114. tile.retain = true;
  9115. continue;
  9116. } else if (tile && tile.loaded) {
  9117. tile.retain = true;
  9118. }
  9119. if (z + 1 < maxZoom) {
  9120. this._retainChildren(i, j, z + 1, maxZoom);
  9121. }
  9122. }
  9123. }
  9124. },
  9125. _resetView: function (e) {
  9126. var animating = e && (e.pinch || e.flyTo);
  9127. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  9128. },
  9129. _animateZoom: function (e) {
  9130. this._setView(e.center, e.zoom, true, e.noUpdate);
  9131. },
  9132. _clampZoom: function (zoom) {
  9133. var options = this.options;
  9134. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  9135. return options.minNativeZoom;
  9136. }
  9137. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  9138. return options.maxNativeZoom;
  9139. }
  9140. return zoom;
  9141. },
  9142. _setView: function (center, zoom, noPrune, noUpdate) {
  9143. var tileZoom = Math.round(zoom);
  9144. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  9145. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  9146. tileZoom = undefined;
  9147. } else {
  9148. tileZoom = this._clampZoom(tileZoom);
  9149. }
  9150. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  9151. if (!noUpdate || tileZoomChanged) {
  9152. this._tileZoom = tileZoom;
  9153. if (this._abortLoading) {
  9154. this._abortLoading();
  9155. }
  9156. this._updateLevels();
  9157. this._resetGrid();
  9158. if (tileZoom !== undefined) {
  9159. this._update(center);
  9160. }
  9161. if (!noPrune) {
  9162. this._pruneTiles();
  9163. }
  9164. // Flag to prevent _updateOpacity from pruning tiles during
  9165. // a zoom anim or a pinch gesture
  9166. this._noPrune = !!noPrune;
  9167. }
  9168. this._setZoomTransforms(center, zoom);
  9169. },
  9170. _setZoomTransforms: function (center, zoom) {
  9171. for (var i in this._levels) {
  9172. this._setZoomTransform(this._levels[i], center, zoom);
  9173. }
  9174. },
  9175. _setZoomTransform: function (level, center, zoom) {
  9176. var scale = this._map.getZoomScale(zoom, level.zoom),
  9177. translate = level.origin.multiplyBy(scale)
  9178. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  9179. if (any3d) {
  9180. setTransform(level.el, translate, scale);
  9181. } else {
  9182. setPosition(level.el, translate);
  9183. }
  9184. },
  9185. _resetGrid: function () {
  9186. var map = this._map,
  9187. crs = map.options.crs,
  9188. tileSize = this._tileSize = this.getTileSize(),
  9189. tileZoom = this._tileZoom;
  9190. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  9191. if (bounds) {
  9192. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  9193. }
  9194. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  9195. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  9196. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  9197. ];
  9198. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  9199. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  9200. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  9201. ];
  9202. },
  9203. _onMoveEnd: function () {
  9204. if (!this._map || this._map._animatingZoom) { return; }
  9205. this._update();
  9206. },
  9207. _getTiledPixelBounds: function (center) {
  9208. var map = this._map,
  9209. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9210. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9211. pixelCenter = map.project(center, this._tileZoom).floor(),
  9212. halfSize = map.getSize().divideBy(scale * 2);
  9213. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9214. },
  9215. // Private method to load tiles in the grid's active zoom level according to map bounds
  9216. _update: function (center) {
  9217. var map = this._map;
  9218. if (!map) { return; }
  9219. var zoom = this._clampZoom(map.getZoom());
  9220. if (center === undefined) { center = map.getCenter(); }
  9221. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  9222. var pixelBounds = this._getTiledPixelBounds(center),
  9223. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9224. tileCenter = tileRange.getCenter(),
  9225. queue = [],
  9226. margin = this.options.keepBuffer,
  9227. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9228. tileRange.getTopRight().add([margin, -margin]));
  9229. // Sanity check: panic if the tile range contains Infinity somewhere.
  9230. if (!(isFinite(tileRange.min.x) &&
  9231. isFinite(tileRange.min.y) &&
  9232. isFinite(tileRange.max.x) &&
  9233. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  9234. for (var key in this._tiles) {
  9235. var c = this._tiles[key].coords;
  9236. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9237. this._tiles[key].current = false;
  9238. }
  9239. }
  9240. // _update just loads more tiles. If the tile zoom level differs too much
  9241. // from the map's, let _setView reset levels and prune old tiles.
  9242. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  9243. // create a queue of coordinates to load tiles from
  9244. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9245. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9246. var coords = new Point(i, j);
  9247. coords.z = this._tileZoom;
  9248. if (!this._isValidTile(coords)) { continue; }
  9249. var tile = this._tiles[this._tileCoordsToKey(coords)];
  9250. if (tile) {
  9251. tile.current = true;
  9252. } else {
  9253. queue.push(coords);
  9254. }
  9255. }
  9256. }
  9257. // sort tile queue to load tiles in order of their distance to center
  9258. queue.sort(function (a, b) {
  9259. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9260. });
  9261. if (queue.length !== 0) {
  9262. // if it's the first batch of tiles to load
  9263. if (!this._loading) {
  9264. this._loading = true;
  9265. // @event loading: Event
  9266. // Fired when the grid layer starts loading tiles.
  9267. this.fire('loading');
  9268. }
  9269. // create DOM fragment to append tiles in one batch
  9270. var fragment = document.createDocumentFragment();
  9271. for (i = 0; i < queue.length; i++) {
  9272. this._addTile(queue[i], fragment);
  9273. }
  9274. this._level.el.appendChild(fragment);
  9275. }
  9276. },
  9277. _isValidTile: function (coords) {
  9278. var crs = this._map.options.crs;
  9279. if (!crs.infinite) {
  9280. // don't load tile if it's out of bounds and not wrapped
  9281. var bounds = this._globalTileRange;
  9282. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9283. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  9284. }
  9285. if (!this.options.bounds) { return true; }
  9286. // don't load tile if it doesn't intersect the bounds in options
  9287. var tileBounds = this._tileCoordsToBounds(coords);
  9288. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9289. },
  9290. _keyToBounds: function (key) {
  9291. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9292. },
  9293. _tileCoordsToNwSe: function (coords) {
  9294. var map = this._map,
  9295. tileSize = this.getTileSize(),
  9296. nwPoint = coords.scaleBy(tileSize),
  9297. sePoint = nwPoint.add(tileSize),
  9298. nw = map.unproject(nwPoint, coords.z),
  9299. se = map.unproject(sePoint, coords.z);
  9300. return [nw, se];
  9301. },
  9302. // converts tile coordinates to its geographical bounds
  9303. _tileCoordsToBounds: function (coords) {
  9304. var bp = this._tileCoordsToNwSe(coords),
  9305. bounds = new LatLngBounds(bp[0], bp[1]);
  9306. if (!this.options.noWrap) {
  9307. bounds = this._map.wrapLatLngBounds(bounds);
  9308. }
  9309. return bounds;
  9310. },
  9311. // converts tile coordinates to key for the tile cache
  9312. _tileCoordsToKey: function (coords) {
  9313. return coords.x + ':' + coords.y + ':' + coords.z;
  9314. },
  9315. // converts tile cache key to coordinates
  9316. _keyToTileCoords: function (key) {
  9317. var k = key.split(':'),
  9318. coords = new Point(+k[0], +k[1]);
  9319. coords.z = +k[2];
  9320. return coords;
  9321. },
  9322. _removeTile: function (key) {
  9323. var tile = this._tiles[key];
  9324. if (!tile) { return; }
  9325. remove(tile.el);
  9326. delete this._tiles[key];
  9327. // @event tileunload: TileEvent
  9328. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9329. this.fire('tileunload', {
  9330. tile: tile.el,
  9331. coords: this._keyToTileCoords(key)
  9332. });
  9333. },
  9334. _initTile: function (tile) {
  9335. addClass(tile, 'leaflet-tile');
  9336. var tileSize = this.getTileSize();
  9337. tile.style.width = tileSize.x + 'px';
  9338. tile.style.height = tileSize.y + 'px';
  9339. tile.onselectstart = falseFn;
  9340. tile.onmousemove = falseFn;
  9341. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9342. if (ielt9 && this.options.opacity < 1) {
  9343. setOpacity(tile, this.options.opacity);
  9344. }
  9345. // without this hack, tiles disappear after zoom on Chrome for Android
  9346. // https://github.com/Leaflet/Leaflet/issues/2078
  9347. if (android && !android23) {
  9348. tile.style.WebkitBackfaceVisibility = 'hidden';
  9349. }
  9350. },
  9351. _addTile: function (coords, container) {
  9352. var tilePos = this._getTilePos(coords),
  9353. key = this._tileCoordsToKey(coords);
  9354. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9355. this._initTile(tile);
  9356. // if createTile is defined with a second argument ("done" callback),
  9357. // we know that tile is async and will be ready later; otherwise
  9358. if (this.createTile.length < 2) {
  9359. // mark tile as ready, but delay one frame for opacity animation to happen
  9360. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9361. }
  9362. setPosition(tile, tilePos);
  9363. // save tile in cache
  9364. this._tiles[key] = {
  9365. el: tile,
  9366. coords: coords,
  9367. current: true
  9368. };
  9369. container.appendChild(tile);
  9370. // @event tileloadstart: TileEvent
  9371. // Fired when a tile is requested and starts loading.
  9372. this.fire('tileloadstart', {
  9373. tile: tile,
  9374. coords: coords
  9375. });
  9376. },
  9377. _tileReady: function (coords, err, tile) {
  9378. if (err) {
  9379. // @event tileerror: TileErrorEvent
  9380. // Fired when there is an error loading a tile.
  9381. this.fire('tileerror', {
  9382. error: err,
  9383. tile: tile,
  9384. coords: coords
  9385. });
  9386. }
  9387. var key = this._tileCoordsToKey(coords);
  9388. tile = this._tiles[key];
  9389. if (!tile) { return; }
  9390. tile.loaded = +new Date();
  9391. if (this._map._fadeAnimated) {
  9392. setOpacity(tile.el, 0);
  9393. cancelAnimFrame(this._fadeFrame);
  9394. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9395. } else {
  9396. tile.active = true;
  9397. this._pruneTiles();
  9398. }
  9399. if (!err) {
  9400. addClass(tile.el, 'leaflet-tile-loaded');
  9401. // @event tileload: TileEvent
  9402. // Fired when a tile loads.
  9403. this.fire('tileload', {
  9404. tile: tile.el,
  9405. coords: coords
  9406. });
  9407. }
  9408. if (this._noTilesToLoad()) {
  9409. this._loading = false;
  9410. // @event load: Event
  9411. // Fired when the grid layer loaded all visible tiles.
  9412. this.fire('load');
  9413. if (ielt9 || !this._map._fadeAnimated) {
  9414. requestAnimFrame(this._pruneTiles, this);
  9415. } else {
  9416. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9417. // to trigger a pruning.
  9418. setTimeout(bind(this._pruneTiles, this), 250);
  9419. }
  9420. }
  9421. },
  9422. _getTilePos: function (coords) {
  9423. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9424. },
  9425. _wrapCoords: function (coords) {
  9426. var newCoords = new Point(
  9427. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9428. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9429. newCoords.z = coords.z;
  9430. return newCoords;
  9431. },
  9432. _pxBoundsToTileRange: function (bounds) {
  9433. var tileSize = this.getTileSize();
  9434. return new Bounds(
  9435. bounds.min.unscaleBy(tileSize).floor(),
  9436. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9437. },
  9438. _noTilesToLoad: function () {
  9439. for (var key in this._tiles) {
  9440. if (!this._tiles[key].loaded) { return false; }
  9441. }
  9442. return true;
  9443. }
  9444. });
  9445. // @factory L.gridLayer(options?: GridLayer options)
  9446. // Creates a new instance of GridLayer with the supplied options.
  9447. function gridLayer(options) {
  9448. return new GridLayer(options);
  9449. }
  9450. /*
  9451. * @class TileLayer
  9452. * @inherits GridLayer
  9453. * @aka L.TileLayer
  9454. * 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`.
  9455. *
  9456. * @example
  9457. *
  9458. * ```js
  9459. * L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'}).addTo(map);
  9460. * ```
  9461. *
  9462. * @section URL template
  9463. * @example
  9464. *
  9465. * A string of the following form:
  9466. *
  9467. * ```
  9468. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9469. * ```
  9470. *
  9471. * `{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.
  9472. *
  9473. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9474. *
  9475. * ```
  9476. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9477. * ```
  9478. */
  9479. var TileLayer = GridLayer.extend({
  9480. // @section
  9481. // @aka TileLayer options
  9482. options: {
  9483. // @option minZoom: Number = 0
  9484. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9485. minZoom: 0,
  9486. // @option maxZoom: Number = 18
  9487. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9488. maxZoom: 18,
  9489. // @option subdomains: String|String[] = 'abc'
  9490. // 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.
  9491. subdomains: 'abc',
  9492. // @option errorTileUrl: String = ''
  9493. // URL to the tile image to show in place of the tile that failed to load.
  9494. errorTileUrl: '',
  9495. // @option zoomOffset: Number = 0
  9496. // The zoom number used in tile URLs will be offset with this value.
  9497. zoomOffset: 0,
  9498. // @option tms: Boolean = false
  9499. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9500. tms: false,
  9501. // @option zoomReverse: Boolean = false
  9502. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9503. zoomReverse: false,
  9504. // @option detectRetina: Boolean = false
  9505. // 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.
  9506. detectRetina: false,
  9507. // @option crossOrigin: Boolean|String = false
  9508. // Whether the crossOrigin attribute will be added to the tiles.
  9509. // 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.
  9510. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  9511. crossOrigin: false
  9512. },
  9513. initialize: function (url, options) {
  9514. this._url = url;
  9515. options = setOptions(this, options);
  9516. // detecting retina displays, adjusting tileSize and zoom levels
  9517. if (options.detectRetina && retina && options.maxZoom > 0) {
  9518. options.tileSize = Math.floor(options.tileSize / 2);
  9519. if (!options.zoomReverse) {
  9520. options.zoomOffset++;
  9521. options.maxZoom--;
  9522. } else {
  9523. options.zoomOffset--;
  9524. options.minZoom++;
  9525. }
  9526. options.minZoom = Math.max(0, options.minZoom);
  9527. }
  9528. if (typeof options.subdomains === 'string') {
  9529. options.subdomains = options.subdomains.split('');
  9530. }
  9531. // for https://github.com/Leaflet/Leaflet/issues/137
  9532. if (!android) {
  9533. this.on('tileunload', this._onTileRemove);
  9534. }
  9535. },
  9536. // @method setUrl(url: String, noRedraw?: Boolean): this
  9537. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9538. // If the URL does not change, the layer will not be redrawn unless
  9539. // the noRedraw parameter is set to false.
  9540. setUrl: function (url, noRedraw) {
  9541. if (this._url === url && noRedraw === undefined) {
  9542. noRedraw = true;
  9543. }
  9544. this._url = url;
  9545. if (!noRedraw) {
  9546. this.redraw();
  9547. }
  9548. return this;
  9549. },
  9550. // @method createTile(coords: Object, done?: Function): HTMLElement
  9551. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9552. // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
  9553. // callback is called when the tile has been loaded.
  9554. createTile: function (coords, done) {
  9555. var tile = document.createElement('img');
  9556. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9557. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9558. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  9559. tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  9560. }
  9561. /*
  9562. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  9563. http://www.w3.org/TR/WCAG20-TECHS/H67
  9564. */
  9565. tile.alt = '';
  9566. /*
  9567. Set role="presentation" to force screen readers to ignore this
  9568. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  9569. */
  9570. tile.setAttribute('role', 'presentation');
  9571. tile.src = this.getTileUrl(coords);
  9572. return tile;
  9573. },
  9574. // @section Extension methods
  9575. // @uninheritable
  9576. // Layers extending `TileLayer` might reimplement the following method.
  9577. // @method getTileUrl(coords: Object): String
  9578. // Called only internally, returns the URL for a tile given its coordinates.
  9579. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9580. getTileUrl: function (coords) {
  9581. var data = {
  9582. r: retina ? '@2x' : '',
  9583. s: this._getSubdomain(coords),
  9584. x: coords.x,
  9585. y: coords.y,
  9586. z: this._getZoomForUrl()
  9587. };
  9588. if (this._map && !this._map.options.crs.infinite) {
  9589. var invertedY = this._globalTileRange.max.y - coords.y;
  9590. if (this.options.tms) {
  9591. data['y'] = invertedY;
  9592. }
  9593. data['-y'] = invertedY;
  9594. }
  9595. return template(this._url, extend(data, this.options));
  9596. },
  9597. _tileOnLoad: function (done, tile) {
  9598. // For https://github.com/Leaflet/Leaflet/issues/3332
  9599. if (ielt9) {
  9600. setTimeout(bind(done, this, null, tile), 0);
  9601. } else {
  9602. done(null, tile);
  9603. }
  9604. },
  9605. _tileOnError: function (done, tile, e) {
  9606. var errorUrl = this.options.errorTileUrl;
  9607. if (errorUrl && tile.getAttribute('src') !== errorUrl) {
  9608. tile.src = errorUrl;
  9609. }
  9610. done(e, tile);
  9611. },
  9612. _onTileRemove: function (e) {
  9613. e.tile.onload = null;
  9614. },
  9615. _getZoomForUrl: function () {
  9616. var zoom = this._tileZoom,
  9617. maxZoom = this.options.maxZoom,
  9618. zoomReverse = this.options.zoomReverse,
  9619. zoomOffset = this.options.zoomOffset;
  9620. if (zoomReverse) {
  9621. zoom = maxZoom - zoom;
  9622. }
  9623. return zoom + zoomOffset;
  9624. },
  9625. _getSubdomain: function (tilePoint) {
  9626. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  9627. return this.options.subdomains[index];
  9628. },
  9629. // stops loading all tiles in the background layer
  9630. _abortLoading: function () {
  9631. var i, tile;
  9632. for (i in this._tiles) {
  9633. if (this._tiles[i].coords.z !== this._tileZoom) {
  9634. tile = this._tiles[i].el;
  9635. tile.onload = falseFn;
  9636. tile.onerror = falseFn;
  9637. if (!tile.complete) {
  9638. tile.src = emptyImageUrl;
  9639. remove(tile);
  9640. delete this._tiles[i];
  9641. }
  9642. }
  9643. }
  9644. },
  9645. _removeTile: function (key) {
  9646. var tile = this._tiles[key];
  9647. if (!tile) { return; }
  9648. // Cancels any pending http requests associated with the tile
  9649. // unless we're on Android's stock browser,
  9650. // see https://github.com/Leaflet/Leaflet/issues/137
  9651. if (!androidStock) {
  9652. tile.el.setAttribute('src', emptyImageUrl);
  9653. }
  9654. return GridLayer.prototype._removeTile.call(this, key);
  9655. },
  9656. _tileReady: function (coords, err, tile) {
  9657. if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) {
  9658. return;
  9659. }
  9660. return GridLayer.prototype._tileReady.call(this, coords, err, tile);
  9661. }
  9662. });
  9663. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  9664. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  9665. function tileLayer(url, options) {
  9666. return new TileLayer(url, options);
  9667. }
  9668. /*
  9669. * @class TileLayer.WMS
  9670. * @inherits TileLayer
  9671. * @aka L.TileLayer.WMS
  9672. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  9673. *
  9674. * @example
  9675. *
  9676. * ```js
  9677. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  9678. * layers: 'nexrad-n0r-900913',
  9679. * format: 'image/png',
  9680. * transparent: true,
  9681. * attribution: "Weather data © 2012 IEM Nexrad"
  9682. * });
  9683. * ```
  9684. */
  9685. var TileLayerWMS = TileLayer.extend({
  9686. // @section
  9687. // @aka TileLayer.WMS options
  9688. // If any custom options not documented here are used, they will be sent to the
  9689. // WMS server as extra parameters in each request URL. This can be useful for
  9690. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  9691. defaultWmsParams: {
  9692. service: 'WMS',
  9693. request: 'GetMap',
  9694. // @option layers: String = ''
  9695. // **(required)** Comma-separated list of WMS layers to show.
  9696. layers: '',
  9697. // @option styles: String = ''
  9698. // Comma-separated list of WMS styles.
  9699. styles: '',
  9700. // @option format: String = 'image/jpeg'
  9701. // WMS image format (use `'image/png'` for layers with transparency).
  9702. format: 'image/jpeg',
  9703. // @option transparent: Boolean = false
  9704. // If `true`, the WMS service will return images with transparency.
  9705. transparent: false,
  9706. // @option version: String = '1.1.1'
  9707. // Version of the WMS service to use
  9708. version: '1.1.1'
  9709. },
  9710. options: {
  9711. // @option crs: CRS = null
  9712. // Coordinate Reference System to use for the WMS requests, defaults to
  9713. // map CRS. Don't change this if you're not sure what it means.
  9714. crs: null,
  9715. // @option uppercase: Boolean = false
  9716. // If `true`, WMS request parameter keys will be uppercase.
  9717. uppercase: false
  9718. },
  9719. initialize: function (url, options) {
  9720. this._url = url;
  9721. var wmsParams = extend({}, this.defaultWmsParams);
  9722. // all keys that are not TileLayer options go to WMS params
  9723. for (var i in options) {
  9724. if (!(i in this.options)) {
  9725. wmsParams[i] = options[i];
  9726. }
  9727. }
  9728. options = setOptions(this, options);
  9729. var realRetina = options.detectRetina && retina ? 2 : 1;
  9730. var tileSize = this.getTileSize();
  9731. wmsParams.width = tileSize.x * realRetina;
  9732. wmsParams.height = tileSize.y * realRetina;
  9733. this.wmsParams = wmsParams;
  9734. },
  9735. onAdd: function (map) {
  9736. this._crs = this.options.crs || map.options.crs;
  9737. this._wmsVersion = parseFloat(this.wmsParams.version);
  9738. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  9739. this.wmsParams[projectionKey] = this._crs.code;
  9740. TileLayer.prototype.onAdd.call(this, map);
  9741. },
  9742. getTileUrl: function (coords) {
  9743. var tileBounds = this._tileCoordsToNwSe(coords),
  9744. crs = this._crs,
  9745. bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
  9746. min = bounds.min,
  9747. max = bounds.max,
  9748. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  9749. [min.y, min.x, max.y, max.x] :
  9750. [min.x, min.y, max.x, max.y]).join(','),
  9751. url = TileLayer.prototype.getTileUrl.call(this, coords);
  9752. return url +
  9753. getParamString(this.wmsParams, url, this.options.uppercase) +
  9754. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  9755. },
  9756. // @method setParams(params: Object, noRedraw?: Boolean): this
  9757. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  9758. setParams: function (params, noRedraw) {
  9759. extend(this.wmsParams, params);
  9760. if (!noRedraw) {
  9761. this.redraw();
  9762. }
  9763. return this;
  9764. }
  9765. });
  9766. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  9767. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  9768. function tileLayerWMS(url, options) {
  9769. return new TileLayerWMS(url, options);
  9770. }
  9771. TileLayer.WMS = TileLayerWMS;
  9772. tileLayer.wms = tileLayerWMS;
  9773. /*
  9774. * @class Renderer
  9775. * @inherits Layer
  9776. * @aka L.Renderer
  9777. *
  9778. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  9779. * DOM container of the renderer, its bounds, and its zoom animation.
  9780. *
  9781. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  9782. * itself can be added or removed to the map. All paths use a renderer, which can
  9783. * be implicit (the map will decide the type of renderer and use it automatically)
  9784. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  9785. *
  9786. * Do not use this class directly, use `SVG` and `Canvas` instead.
  9787. *
  9788. * @event update: Event
  9789. * Fired when the renderer updates its bounds, center and zoom, for example when
  9790. * its map has moved
  9791. */
  9792. var Renderer = Layer.extend({
  9793. // @section
  9794. // @aka Renderer options
  9795. options: {
  9796. // @option padding: Number = 0.1
  9797. // How much to extend the clip area around the map view (relative to its size)
  9798. // e.g. 0.1 would be 10% of map view in each direction
  9799. padding: 0.1,
  9800. // @option tolerance: Number = 0
  9801. // How much to extend click tolerance round a path/object on the map
  9802. tolerance : 0
  9803. },
  9804. initialize: function (options) {
  9805. setOptions(this, options);
  9806. stamp(this);
  9807. this._layers = this._layers || {};
  9808. },
  9809. onAdd: function () {
  9810. if (!this._container) {
  9811. this._initContainer(); // defined by renderer implementations
  9812. if (this._zoomAnimated) {
  9813. addClass(this._container, 'leaflet-zoom-animated');
  9814. }
  9815. }
  9816. this.getPane().appendChild(this._container);
  9817. this._update();
  9818. this.on('update', this._updatePaths, this);
  9819. },
  9820. onRemove: function () {
  9821. this.off('update', this._updatePaths, this);
  9822. this._destroyContainer();
  9823. },
  9824. getEvents: function () {
  9825. var events = {
  9826. viewreset: this._reset,
  9827. zoom: this._onZoom,
  9828. moveend: this._update,
  9829. zoomend: this._onZoomEnd
  9830. };
  9831. if (this._zoomAnimated) {
  9832. events.zoomanim = this._onAnimZoom;
  9833. }
  9834. return events;
  9835. },
  9836. _onAnimZoom: function (ev) {
  9837. this._updateTransform(ev.center, ev.zoom);
  9838. },
  9839. _onZoom: function () {
  9840. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  9841. },
  9842. _updateTransform: function (center, zoom) {
  9843. var scale = this._map.getZoomScale(zoom, this._zoom),
  9844. position = getPosition(this._container),
  9845. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  9846. currentCenterPoint = this._map.project(this._center, zoom),
  9847. destCenterPoint = this._map.project(center, zoom),
  9848. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  9849. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  9850. if (any3d) {
  9851. setTransform(this._container, topLeftOffset, scale);
  9852. } else {
  9853. setPosition(this._container, topLeftOffset);
  9854. }
  9855. },
  9856. _reset: function () {
  9857. this._update();
  9858. this._updateTransform(this._center, this._zoom);
  9859. for (var id in this._layers) {
  9860. this._layers[id]._reset();
  9861. }
  9862. },
  9863. _onZoomEnd: function () {
  9864. for (var id in this._layers) {
  9865. this._layers[id]._project();
  9866. }
  9867. },
  9868. _updatePaths: function () {
  9869. for (var id in this._layers) {
  9870. this._layers[id]._update();
  9871. }
  9872. },
  9873. _update: function () {
  9874. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  9875. // Subclasses are responsible of firing the 'update' event.
  9876. var p = this.options.padding,
  9877. size = this._map.getSize(),
  9878. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  9879. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  9880. this._center = this._map.getCenter();
  9881. this._zoom = this._map.getZoom();
  9882. }
  9883. });
  9884. /*
  9885. * @class Canvas
  9886. * @inherits Renderer
  9887. * @aka L.Canvas
  9888. *
  9889. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  9890. * Inherits `Renderer`.
  9891. *
  9892. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  9893. * available in all web browsers, notably IE8, and overlapping geometries might
  9894. * not display properly in some edge cases.
  9895. *
  9896. * @example
  9897. *
  9898. * Use Canvas by default for all paths in the map:
  9899. *
  9900. * ```js
  9901. * var map = L.map('map', {
  9902. * renderer: L.canvas()
  9903. * });
  9904. * ```
  9905. *
  9906. * Use a Canvas renderer with extra padding for specific vector geometries:
  9907. *
  9908. * ```js
  9909. * var map = L.map('map');
  9910. * var myRenderer = L.canvas({ padding: 0.5 });
  9911. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  9912. * var circle = L.circle( center, { renderer: myRenderer } );
  9913. * ```
  9914. */
  9915. var Canvas = Renderer.extend({
  9916. getEvents: function () {
  9917. var events = Renderer.prototype.getEvents.call(this);
  9918. events.viewprereset = this._onViewPreReset;
  9919. return events;
  9920. },
  9921. _onViewPreReset: function () {
  9922. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  9923. this._postponeUpdatePaths = true;
  9924. },
  9925. onAdd: function () {
  9926. Renderer.prototype.onAdd.call(this);
  9927. // Redraw vectors since canvas is cleared upon removal,
  9928. // in case of removing the renderer itself from the map.
  9929. this._draw();
  9930. },
  9931. _initContainer: function () {
  9932. var container = this._container = document.createElement('canvas');
  9933. on(container, 'mousemove', this._onMouseMove, this);
  9934. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  9935. on(container, 'mouseout', this._handleMouseOut, this);
  9936. this._ctx = container.getContext('2d');
  9937. },
  9938. _destroyContainer: function () {
  9939. cancelAnimFrame(this._redrawRequest);
  9940. delete this._ctx;
  9941. remove(this._container);
  9942. off(this._container);
  9943. delete this._container;
  9944. },
  9945. _updatePaths: function () {
  9946. if (this._postponeUpdatePaths) { return; }
  9947. var layer;
  9948. this._redrawBounds = null;
  9949. for (var id in this._layers) {
  9950. layer = this._layers[id];
  9951. layer._update();
  9952. }
  9953. this._redraw();
  9954. },
  9955. _update: function () {
  9956. if (this._map._animatingZoom && this._bounds) { return; }
  9957. Renderer.prototype._update.call(this);
  9958. var b = this._bounds,
  9959. container = this._container,
  9960. size = b.getSize(),
  9961. m = retina ? 2 : 1;
  9962. setPosition(container, b.min);
  9963. // set canvas size (also clearing it); use double size on retina
  9964. container.width = m * size.x;
  9965. container.height = m * size.y;
  9966. container.style.width = size.x + 'px';
  9967. container.style.height = size.y + 'px';
  9968. if (retina) {
  9969. this._ctx.scale(2, 2);
  9970. }
  9971. // translate so we use the same path coordinates after canvas element moves
  9972. this._ctx.translate(-b.min.x, -b.min.y);
  9973. // Tell paths to redraw themselves
  9974. this.fire('update');
  9975. },
  9976. _reset: function () {
  9977. Renderer.prototype._reset.call(this);
  9978. if (this._postponeUpdatePaths) {
  9979. this._postponeUpdatePaths = false;
  9980. this._updatePaths();
  9981. }
  9982. },
  9983. _initPath: function (layer) {
  9984. this._updateDashArray(layer);
  9985. this._layers[stamp(layer)] = layer;
  9986. var order = layer._order = {
  9987. layer: layer,
  9988. prev: this._drawLast,
  9989. next: null
  9990. };
  9991. if (this._drawLast) { this._drawLast.next = order; }
  9992. this._drawLast = order;
  9993. this._drawFirst = this._drawFirst || this._drawLast;
  9994. },
  9995. _addPath: function (layer) {
  9996. this._requestRedraw(layer);
  9997. },
  9998. _removePath: function (layer) {
  9999. var order = layer._order;
  10000. var next = order.next;
  10001. var prev = order.prev;
  10002. if (next) {
  10003. next.prev = prev;
  10004. } else {
  10005. this._drawLast = prev;
  10006. }
  10007. if (prev) {
  10008. prev.next = next;
  10009. } else {
  10010. this._drawFirst = next;
  10011. }
  10012. delete layer._order;
  10013. delete this._layers[stamp(layer)];
  10014. this._requestRedraw(layer);
  10015. },
  10016. _updatePath: function (layer) {
  10017. // Redraw the union of the layer's old pixel
  10018. // bounds and the new pixel bounds.
  10019. this._extendRedrawBounds(layer);
  10020. layer._project();
  10021. layer._update();
  10022. // The redraw will extend the redraw bounds
  10023. // with the new pixel bounds.
  10024. this._requestRedraw(layer);
  10025. },
  10026. _updateStyle: function (layer) {
  10027. this._updateDashArray(layer);
  10028. this._requestRedraw(layer);
  10029. },
  10030. _updateDashArray: function (layer) {
  10031. if (typeof layer.options.dashArray === 'string') {
  10032. var parts = layer.options.dashArray.split(/[, ]+/),
  10033. dashArray = [],
  10034. dashValue,
  10035. i;
  10036. for (i = 0; i < parts.length; i++) {
  10037. dashValue = Number(parts[i]);
  10038. // Ignore dash array containing invalid lengths
  10039. if (isNaN(dashValue)) { return; }
  10040. dashArray.push(dashValue);
  10041. }
  10042. layer.options._dashArray = dashArray;
  10043. } else {
  10044. layer.options._dashArray = layer.options.dashArray;
  10045. }
  10046. },
  10047. _requestRedraw: function (layer) {
  10048. if (!this._map) { return; }
  10049. this._extendRedrawBounds(layer);
  10050. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  10051. },
  10052. _extendRedrawBounds: function (layer) {
  10053. if (layer._pxBounds) {
  10054. var padding = (layer.options.weight || 0) + 1;
  10055. this._redrawBounds = this._redrawBounds || new Bounds();
  10056. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  10057. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  10058. }
  10059. },
  10060. _redraw: function () {
  10061. this._redrawRequest = null;
  10062. if (this._redrawBounds) {
  10063. this._redrawBounds.min._floor();
  10064. this._redrawBounds.max._ceil();
  10065. }
  10066. this._clear(); // clear layers in redraw bounds
  10067. this._draw(); // draw layers
  10068. this._redrawBounds = null;
  10069. },
  10070. _clear: function () {
  10071. var bounds = this._redrawBounds;
  10072. if (bounds) {
  10073. var size = bounds.getSize();
  10074. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  10075. } else {
  10076. this._ctx.save();
  10077. this._ctx.setTransform(1, 0, 0, 1, 0, 0);
  10078. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  10079. this._ctx.restore();
  10080. }
  10081. },
  10082. _draw: function () {
  10083. var layer, bounds = this._redrawBounds;
  10084. this._ctx.save();
  10085. if (bounds) {
  10086. var size = bounds.getSize();
  10087. this._ctx.beginPath();
  10088. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  10089. this._ctx.clip();
  10090. }
  10091. this._drawing = true;
  10092. for (var order = this._drawFirst; order; order = order.next) {
  10093. layer = order.layer;
  10094. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  10095. layer._updatePath();
  10096. }
  10097. }
  10098. this._drawing = false;
  10099. this._ctx.restore(); // Restore state before clipping.
  10100. },
  10101. _updatePoly: function (layer, closed) {
  10102. if (!this._drawing) { return; }
  10103. var i, j, len2, p,
  10104. parts = layer._parts,
  10105. len = parts.length,
  10106. ctx = this._ctx;
  10107. if (!len) { return; }
  10108. ctx.beginPath();
  10109. for (i = 0; i < len; i++) {
  10110. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  10111. p = parts[i][j];
  10112. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  10113. }
  10114. if (closed) {
  10115. ctx.closePath();
  10116. }
  10117. }
  10118. this._fillStroke(ctx, layer);
  10119. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  10120. },
  10121. _updateCircle: function (layer) {
  10122. if (!this._drawing || layer._empty()) { return; }
  10123. var p = layer._point,
  10124. ctx = this._ctx,
  10125. r = Math.max(Math.round(layer._radius), 1),
  10126. s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
  10127. if (s !== 1) {
  10128. ctx.save();
  10129. ctx.scale(1, s);
  10130. }
  10131. ctx.beginPath();
  10132. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  10133. if (s !== 1) {
  10134. ctx.restore();
  10135. }
  10136. this._fillStroke(ctx, layer);
  10137. },
  10138. _fillStroke: function (ctx, layer) {
  10139. var options = layer.options;
  10140. if (options.fill) {
  10141. ctx.globalAlpha = options.fillOpacity;
  10142. ctx.fillStyle = options.fillColor || options.color;
  10143. ctx.fill(options.fillRule || 'evenodd');
  10144. }
  10145. if (options.stroke && options.weight !== 0) {
  10146. if (ctx.setLineDash) {
  10147. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  10148. }
  10149. ctx.globalAlpha = options.opacity;
  10150. ctx.lineWidth = options.weight;
  10151. ctx.strokeStyle = options.color;
  10152. ctx.lineCap = options.lineCap;
  10153. ctx.lineJoin = options.lineJoin;
  10154. ctx.stroke();
  10155. }
  10156. },
  10157. // Canvas obviously doesn't have mouse events for individual drawn objects,
  10158. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  10159. _onClick: function (e) {
  10160. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  10161. for (var order = this._drawFirst; order; order = order.next) {
  10162. layer = order.layer;
  10163. if (layer.options.interactive && layer._containsPoint(point)) {
  10164. if (!(e.type === 'click' || e.type !== 'preclick') || !this._map._draggableMoved(layer)) {
  10165. clickedLayer = layer;
  10166. }
  10167. }
  10168. }
  10169. if (clickedLayer) {
  10170. fakeStop(e);
  10171. this._fireEvent([clickedLayer], e);
  10172. }
  10173. },
  10174. _onMouseMove: function (e) {
  10175. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  10176. var point = this._map.mouseEventToLayerPoint(e);
  10177. this._handleMouseHover(e, point);
  10178. },
  10179. _handleMouseOut: function (e) {
  10180. var layer = this._hoveredLayer;
  10181. if (layer) {
  10182. // if we're leaving the layer, fire mouseout
  10183. removeClass(this._container, 'leaflet-interactive');
  10184. this._fireEvent([layer], e, 'mouseout');
  10185. this._hoveredLayer = null;
  10186. this._mouseHoverThrottled = false;
  10187. }
  10188. },
  10189. _handleMouseHover: function (e, point) {
  10190. if (this._mouseHoverThrottled) {
  10191. return;
  10192. }
  10193. var layer, candidateHoveredLayer;
  10194. for (var order = this._drawFirst; order; order = order.next) {
  10195. layer = order.layer;
  10196. if (layer.options.interactive && layer._containsPoint(point)) {
  10197. candidateHoveredLayer = layer;
  10198. }
  10199. }
  10200. if (candidateHoveredLayer !== this._hoveredLayer) {
  10201. this._handleMouseOut(e);
  10202. if (candidateHoveredLayer) {
  10203. addClass(this._container, 'leaflet-interactive'); // change cursor
  10204. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  10205. this._hoveredLayer = candidateHoveredLayer;
  10206. }
  10207. }
  10208. if (this._hoveredLayer) {
  10209. this._fireEvent([this._hoveredLayer], e);
  10210. }
  10211. this._mouseHoverThrottled = true;
  10212. setTimeout(bind(function () {
  10213. this._mouseHoverThrottled = false;
  10214. }, this), 32);
  10215. },
  10216. _fireEvent: function (layers, e, type) {
  10217. this._map._fireDOMEvent(e, type || e.type, layers);
  10218. },
  10219. _bringToFront: function (layer) {
  10220. var order = layer._order;
  10221. if (!order) { return; }
  10222. var next = order.next;
  10223. var prev = order.prev;
  10224. if (next) {
  10225. next.prev = prev;
  10226. } else {
  10227. // Already last
  10228. return;
  10229. }
  10230. if (prev) {
  10231. prev.next = next;
  10232. } else if (next) {
  10233. // Update first entry unless this is the
  10234. // single entry
  10235. this._drawFirst = next;
  10236. }
  10237. order.prev = this._drawLast;
  10238. this._drawLast.next = order;
  10239. order.next = null;
  10240. this._drawLast = order;
  10241. this._requestRedraw(layer);
  10242. },
  10243. _bringToBack: function (layer) {
  10244. var order = layer._order;
  10245. if (!order) { return; }
  10246. var next = order.next;
  10247. var prev = order.prev;
  10248. if (prev) {
  10249. prev.next = next;
  10250. } else {
  10251. // Already first
  10252. return;
  10253. }
  10254. if (next) {
  10255. next.prev = prev;
  10256. } else if (prev) {
  10257. // Update last entry unless this is the
  10258. // single entry
  10259. this._drawLast = prev;
  10260. }
  10261. order.prev = null;
  10262. order.next = this._drawFirst;
  10263. this._drawFirst.prev = order;
  10264. this._drawFirst = order;
  10265. this._requestRedraw(layer);
  10266. }
  10267. });
  10268. // @factory L.canvas(options?: Renderer options)
  10269. // Creates a Canvas renderer with the given options.
  10270. function canvas$1(options) {
  10271. return canvas ? new Canvas(options) : null;
  10272. }
  10273. /*
  10274. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10275. */
  10276. var vmlCreate = (function () {
  10277. try {
  10278. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10279. return function (name) {
  10280. return document.createElement('<lvml:' + name + ' class="lvml">');
  10281. };
  10282. } catch (e) {
  10283. return function (name) {
  10284. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10285. };
  10286. }
  10287. })();
  10288. /*
  10289. * @class SVG
  10290. *
  10291. *
  10292. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10293. * with old versions of Internet Explorer.
  10294. */
  10295. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10296. var vmlMixin = {
  10297. _initContainer: function () {
  10298. this._container = create$1('div', 'leaflet-vml-container');
  10299. },
  10300. _update: function () {
  10301. if (this._map._animatingZoom) { return; }
  10302. Renderer.prototype._update.call(this);
  10303. this.fire('update');
  10304. },
  10305. _initPath: function (layer) {
  10306. var container = layer._container = vmlCreate('shape');
  10307. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10308. container.coordsize = '1 1';
  10309. layer._path = vmlCreate('path');
  10310. container.appendChild(layer._path);
  10311. this._updateStyle(layer);
  10312. this._layers[stamp(layer)] = layer;
  10313. },
  10314. _addPath: function (layer) {
  10315. var container = layer._container;
  10316. this._container.appendChild(container);
  10317. if (layer.options.interactive) {
  10318. layer.addInteractiveTarget(container);
  10319. }
  10320. },
  10321. _removePath: function (layer) {
  10322. var container = layer._container;
  10323. remove(container);
  10324. layer.removeInteractiveTarget(container);
  10325. delete this._layers[stamp(layer)];
  10326. },
  10327. _updateStyle: function (layer) {
  10328. var stroke = layer._stroke,
  10329. fill = layer._fill,
  10330. options = layer.options,
  10331. container = layer._container;
  10332. container.stroked = !!options.stroke;
  10333. container.filled = !!options.fill;
  10334. if (options.stroke) {
  10335. if (!stroke) {
  10336. stroke = layer._stroke = vmlCreate('stroke');
  10337. }
  10338. container.appendChild(stroke);
  10339. stroke.weight = options.weight + 'px';
  10340. stroke.color = options.color;
  10341. stroke.opacity = options.opacity;
  10342. if (options.dashArray) {
  10343. stroke.dashStyle = isArray(options.dashArray) ?
  10344. options.dashArray.join(' ') :
  10345. options.dashArray.replace(/( *, *)/g, ' ');
  10346. } else {
  10347. stroke.dashStyle = '';
  10348. }
  10349. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10350. stroke.joinstyle = options.lineJoin;
  10351. } else if (stroke) {
  10352. container.removeChild(stroke);
  10353. layer._stroke = null;
  10354. }
  10355. if (options.fill) {
  10356. if (!fill) {
  10357. fill = layer._fill = vmlCreate('fill');
  10358. }
  10359. container.appendChild(fill);
  10360. fill.color = options.fillColor || options.color;
  10361. fill.opacity = options.fillOpacity;
  10362. } else if (fill) {
  10363. container.removeChild(fill);
  10364. layer._fill = null;
  10365. }
  10366. },
  10367. _updateCircle: function (layer) {
  10368. var p = layer._point.round(),
  10369. r = Math.round(layer._radius),
  10370. r2 = Math.round(layer._radiusY || r);
  10371. this._setPath(layer, layer._empty() ? 'M0 0' :
  10372. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10373. },
  10374. _setPath: function (layer, path) {
  10375. layer._path.v = path;
  10376. },
  10377. _bringToFront: function (layer) {
  10378. toFront(layer._container);
  10379. },
  10380. _bringToBack: function (layer) {
  10381. toBack(layer._container);
  10382. }
  10383. };
  10384. var create$2 = vml ? vmlCreate : svgCreate;
  10385. /*
  10386. * @class SVG
  10387. * @inherits Renderer
  10388. * @aka L.SVG
  10389. *
  10390. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10391. * Inherits `Renderer`.
  10392. *
  10393. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  10394. * available in all web browsers, notably Android 2.x and 3.x.
  10395. *
  10396. * Although SVG is not available on IE7 and IE8, these browsers support
  10397. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10398. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10399. * this case.
  10400. *
  10401. * @example
  10402. *
  10403. * Use SVG by default for all paths in the map:
  10404. *
  10405. * ```js
  10406. * var map = L.map('map', {
  10407. * renderer: L.svg()
  10408. * });
  10409. * ```
  10410. *
  10411. * Use a SVG renderer with extra padding for specific vector geometries:
  10412. *
  10413. * ```js
  10414. * var map = L.map('map');
  10415. * var myRenderer = L.svg({ padding: 0.5 });
  10416. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10417. * var circle = L.circle( center, { renderer: myRenderer } );
  10418. * ```
  10419. */
  10420. var SVG = Renderer.extend({
  10421. getEvents: function () {
  10422. var events = Renderer.prototype.getEvents.call(this);
  10423. events.zoomstart = this._onZoomStart;
  10424. return events;
  10425. },
  10426. _initContainer: function () {
  10427. this._container = create$2('svg');
  10428. // makes it possible to click through svg root; we'll reset it back in individual paths
  10429. this._container.setAttribute('pointer-events', 'none');
  10430. this._rootGroup = create$2('g');
  10431. this._container.appendChild(this._rootGroup);
  10432. },
  10433. _destroyContainer: function () {
  10434. remove(this._container);
  10435. off(this._container);
  10436. delete this._container;
  10437. delete this._rootGroup;
  10438. delete this._svgSize;
  10439. },
  10440. _onZoomStart: function () {
  10441. // Drag-then-pinch interactions might mess up the center and zoom.
  10442. // In this case, the easiest way to prevent this is re-do the renderer
  10443. // bounds and padding when the zooming starts.
  10444. this._update();
  10445. },
  10446. _update: function () {
  10447. if (this._map._animatingZoom && this._bounds) { return; }
  10448. Renderer.prototype._update.call(this);
  10449. var b = this._bounds,
  10450. size = b.getSize(),
  10451. container = this._container;
  10452. // set size of svg-container if changed
  10453. if (!this._svgSize || !this._svgSize.equals(size)) {
  10454. this._svgSize = size;
  10455. container.setAttribute('width', size.x);
  10456. container.setAttribute('height', size.y);
  10457. }
  10458. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10459. setPosition(container, b.min);
  10460. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10461. this.fire('update');
  10462. },
  10463. // methods below are called by vector layers implementations
  10464. _initPath: function (layer) {
  10465. var path = layer._path = create$2('path');
  10466. // @namespace Path
  10467. // @option className: String = null
  10468. // Custom class name set on an element. Only for SVG renderer.
  10469. if (layer.options.className) {
  10470. addClass(path, layer.options.className);
  10471. }
  10472. if (layer.options.interactive) {
  10473. addClass(path, 'leaflet-interactive');
  10474. }
  10475. this._updateStyle(layer);
  10476. this._layers[stamp(layer)] = layer;
  10477. },
  10478. _addPath: function (layer) {
  10479. if (!this._rootGroup) { this._initContainer(); }
  10480. this._rootGroup.appendChild(layer._path);
  10481. layer.addInteractiveTarget(layer._path);
  10482. },
  10483. _removePath: function (layer) {
  10484. remove(layer._path);
  10485. layer.removeInteractiveTarget(layer._path);
  10486. delete this._layers[stamp(layer)];
  10487. },
  10488. _updatePath: function (layer) {
  10489. layer._project();
  10490. layer._update();
  10491. },
  10492. _updateStyle: function (layer) {
  10493. var path = layer._path,
  10494. options = layer.options;
  10495. if (!path) { return; }
  10496. if (options.stroke) {
  10497. path.setAttribute('stroke', options.color);
  10498. path.setAttribute('stroke-opacity', options.opacity);
  10499. path.setAttribute('stroke-width', options.weight);
  10500. path.setAttribute('stroke-linecap', options.lineCap);
  10501. path.setAttribute('stroke-linejoin', options.lineJoin);
  10502. if (options.dashArray) {
  10503. path.setAttribute('stroke-dasharray', options.dashArray);
  10504. } else {
  10505. path.removeAttribute('stroke-dasharray');
  10506. }
  10507. if (options.dashOffset) {
  10508. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10509. } else {
  10510. path.removeAttribute('stroke-dashoffset');
  10511. }
  10512. } else {
  10513. path.setAttribute('stroke', 'none');
  10514. }
  10515. if (options.fill) {
  10516. path.setAttribute('fill', options.fillColor || options.color);
  10517. path.setAttribute('fill-opacity', options.fillOpacity);
  10518. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10519. } else {
  10520. path.setAttribute('fill', 'none');
  10521. }
  10522. },
  10523. _updatePoly: function (layer, closed) {
  10524. this._setPath(layer, pointsToPath(layer._parts, closed));
  10525. },
  10526. _updateCircle: function (layer) {
  10527. var p = layer._point,
  10528. r = Math.max(Math.round(layer._radius), 1),
  10529. r2 = Math.max(Math.round(layer._radiusY), 1) || r,
  10530. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10531. // drawing a circle with two half-arcs
  10532. var d = layer._empty() ? 'M0 0' :
  10533. 'M' + (p.x - r) + ',' + p.y +
  10534. arc + (r * 2) + ',0 ' +
  10535. arc + (-r * 2) + ',0 ';
  10536. this._setPath(layer, d);
  10537. },
  10538. _setPath: function (layer, path) {
  10539. layer._path.setAttribute('d', path);
  10540. },
  10541. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10542. _bringToFront: function (layer) {
  10543. toFront(layer._path);
  10544. },
  10545. _bringToBack: function (layer) {
  10546. toBack(layer._path);
  10547. }
  10548. });
  10549. if (vml) {
  10550. SVG.include(vmlMixin);
  10551. }
  10552. // @namespace SVG
  10553. // @factory L.svg(options?: Renderer options)
  10554. // Creates a SVG renderer with the given options.
  10555. function svg$1(options) {
  10556. return svg || vml ? new SVG(options) : null;
  10557. }
  10558. Map.include({
  10559. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10560. // Returns the instance of `Renderer` that should be used to render the given
  10561. // `Path`. It will ensure that the `renderer` options of the map and paths
  10562. // are respected, and that the renderers do exist on the map.
  10563. getRenderer: function (layer) {
  10564. // @namespace Path; @option renderer: Renderer
  10565. // Use this specific instance of `Renderer` for this path. Takes
  10566. // precedence over the map's [default renderer](#map-renderer).
  10567. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10568. if (!renderer) {
  10569. renderer = this._renderer = this._createRenderer();
  10570. }
  10571. if (!this.hasLayer(renderer)) {
  10572. this.addLayer(renderer);
  10573. }
  10574. return renderer;
  10575. },
  10576. _getPaneRenderer: function (name) {
  10577. if (name === 'overlayPane' || name === undefined) {
  10578. return false;
  10579. }
  10580. var renderer = this._paneRenderers[name];
  10581. if (renderer === undefined) {
  10582. renderer = this._createRenderer({pane: name});
  10583. this._paneRenderers[name] = renderer;
  10584. }
  10585. return renderer;
  10586. },
  10587. _createRenderer: function (options) {
  10588. // @namespace Map; @option preferCanvas: Boolean = false
  10589. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10590. // By default, all `Path`s are rendered in a `SVG` renderer.
  10591. return (this.options.preferCanvas && canvas$1(options)) || svg$1(options);
  10592. }
  10593. });
  10594. /*
  10595. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10596. */
  10597. /*
  10598. * @class Rectangle
  10599. * @aka L.Rectangle
  10600. * @inherits Polygon
  10601. *
  10602. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10603. *
  10604. * @example
  10605. *
  10606. * ```js
  10607. * // define rectangle geographical bounds
  10608. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10609. *
  10610. * // create an orange rectangle
  10611. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10612. *
  10613. * // zoom the map to the rectangle bounds
  10614. * map.fitBounds(bounds);
  10615. * ```
  10616. *
  10617. */
  10618. var Rectangle = Polygon.extend({
  10619. initialize: function (latLngBounds, options) {
  10620. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10621. },
  10622. // @method setBounds(latLngBounds: LatLngBounds): this
  10623. // Redraws the rectangle with the passed bounds.
  10624. setBounds: function (latLngBounds) {
  10625. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  10626. },
  10627. _boundsToLatLngs: function (latLngBounds) {
  10628. latLngBounds = toLatLngBounds(latLngBounds);
  10629. return [
  10630. latLngBounds.getSouthWest(),
  10631. latLngBounds.getNorthWest(),
  10632. latLngBounds.getNorthEast(),
  10633. latLngBounds.getSouthEast()
  10634. ];
  10635. }
  10636. });
  10637. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  10638. function rectangle(latLngBounds, options) {
  10639. return new Rectangle(latLngBounds, options);
  10640. }
  10641. SVG.create = create$2;
  10642. SVG.pointsToPath = pointsToPath;
  10643. GeoJSON.geometryToLayer = geometryToLayer;
  10644. GeoJSON.coordsToLatLng = coordsToLatLng;
  10645. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  10646. GeoJSON.latLngToCoords = latLngToCoords;
  10647. GeoJSON.latLngsToCoords = latLngsToCoords;
  10648. GeoJSON.getFeature = getFeature;
  10649. GeoJSON.asFeature = asFeature;
  10650. /*
  10651. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  10652. * (zoom to a selected bounding box), enabled by default.
  10653. */
  10654. // @namespace Map
  10655. // @section Interaction Options
  10656. Map.mergeOptions({
  10657. // @option boxZoom: Boolean = true
  10658. // Whether the map can be zoomed to a rectangular area specified by
  10659. // dragging the mouse while pressing the shift key.
  10660. boxZoom: true
  10661. });
  10662. var BoxZoom = Handler.extend({
  10663. initialize: function (map) {
  10664. this._map = map;
  10665. this._container = map._container;
  10666. this._pane = map._panes.overlayPane;
  10667. this._resetStateTimeout = 0;
  10668. map.on('unload', this._destroy, this);
  10669. },
  10670. addHooks: function () {
  10671. on(this._container, 'mousedown', this._onMouseDown, this);
  10672. },
  10673. removeHooks: function () {
  10674. off(this._container, 'mousedown', this._onMouseDown, this);
  10675. },
  10676. moved: function () {
  10677. return this._moved;
  10678. },
  10679. _destroy: function () {
  10680. remove(this._pane);
  10681. delete this._pane;
  10682. },
  10683. _resetState: function () {
  10684. this._resetStateTimeout = 0;
  10685. this._moved = false;
  10686. },
  10687. _clearDeferredResetState: function () {
  10688. if (this._resetStateTimeout !== 0) {
  10689. clearTimeout(this._resetStateTimeout);
  10690. this._resetStateTimeout = 0;
  10691. }
  10692. },
  10693. _onMouseDown: function (e) {
  10694. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  10695. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  10696. // will interrupt the interaction and orphan a box element in the container.
  10697. this._clearDeferredResetState();
  10698. this._resetState();
  10699. disableTextSelection();
  10700. disableImageDrag();
  10701. this._startPoint = this._map.mouseEventToContainerPoint(e);
  10702. on(document, {
  10703. contextmenu: stop,
  10704. mousemove: this._onMouseMove,
  10705. mouseup: this._onMouseUp,
  10706. keydown: this._onKeyDown
  10707. }, this);
  10708. },
  10709. _onMouseMove: function (e) {
  10710. if (!this._moved) {
  10711. this._moved = true;
  10712. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  10713. addClass(this._container, 'leaflet-crosshair');
  10714. this._map.fire('boxzoomstart');
  10715. }
  10716. this._point = this._map.mouseEventToContainerPoint(e);
  10717. var bounds = new Bounds(this._point, this._startPoint),
  10718. size = bounds.getSize();
  10719. setPosition(this._box, bounds.min);
  10720. this._box.style.width = size.x + 'px';
  10721. this._box.style.height = size.y + 'px';
  10722. },
  10723. _finish: function () {
  10724. if (this._moved) {
  10725. remove(this._box);
  10726. removeClass(this._container, 'leaflet-crosshair');
  10727. }
  10728. enableTextSelection();
  10729. enableImageDrag();
  10730. off(document, {
  10731. contextmenu: stop,
  10732. mousemove: this._onMouseMove,
  10733. mouseup: this._onMouseUp,
  10734. keydown: this._onKeyDown
  10735. }, this);
  10736. },
  10737. _onMouseUp: function (e) {
  10738. if ((e.which !== 1) && (e.button !== 1)) { return; }
  10739. this._finish();
  10740. if (!this._moved) { return; }
  10741. // Postpone to next JS tick so internal click event handling
  10742. // still see it as "moved".
  10743. this._clearDeferredResetState();
  10744. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  10745. var bounds = new LatLngBounds(
  10746. this._map.containerPointToLatLng(this._startPoint),
  10747. this._map.containerPointToLatLng(this._point));
  10748. this._map
  10749. .fitBounds(bounds)
  10750. .fire('boxzoomend', {boxZoomBounds: bounds});
  10751. },
  10752. _onKeyDown: function (e) {
  10753. if (e.keyCode === 27) {
  10754. this._finish();
  10755. }
  10756. }
  10757. });
  10758. // @section Handlers
  10759. // @property boxZoom: Handler
  10760. // Box (shift-drag with mouse) zoom handler.
  10761. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  10762. /*
  10763. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  10764. */
  10765. // @namespace Map
  10766. // @section Interaction Options
  10767. Map.mergeOptions({
  10768. // @option doubleClickZoom: Boolean|String = true
  10769. // Whether the map can be zoomed in by double clicking on it and
  10770. // zoomed out by double clicking while holding shift. If passed
  10771. // `'center'`, double-click zoom will zoom to the center of the
  10772. // view regardless of where the mouse was.
  10773. doubleClickZoom: true
  10774. });
  10775. var DoubleClickZoom = Handler.extend({
  10776. addHooks: function () {
  10777. this._map.on('dblclick', this._onDoubleClick, this);
  10778. },
  10779. removeHooks: function () {
  10780. this._map.off('dblclick', this._onDoubleClick, this);
  10781. },
  10782. _onDoubleClick: function (e) {
  10783. var map = this._map,
  10784. oldZoom = map.getZoom(),
  10785. delta = map.options.zoomDelta,
  10786. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  10787. if (map.options.doubleClickZoom === 'center') {
  10788. map.setZoom(zoom);
  10789. } else {
  10790. map.setZoomAround(e.containerPoint, zoom);
  10791. }
  10792. }
  10793. });
  10794. // @section Handlers
  10795. //
  10796. // Map properties include interaction handlers that allow you to control
  10797. // interaction behavior in runtime, enabling or disabling certain features such
  10798. // as dragging or touch zoom (see `Handler` methods). For example:
  10799. //
  10800. // ```js
  10801. // map.doubleClickZoom.disable();
  10802. // ```
  10803. //
  10804. // @property doubleClickZoom: Handler
  10805. // Double click zoom handler.
  10806. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  10807. /*
  10808. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  10809. */
  10810. // @namespace Map
  10811. // @section Interaction Options
  10812. Map.mergeOptions({
  10813. // @option dragging: Boolean = true
  10814. // Whether the map be draggable with mouse/touch or not.
  10815. dragging: true,
  10816. // @section Panning Inertia Options
  10817. // @option inertia: Boolean = *
  10818. // If enabled, panning of the map will have an inertia effect where
  10819. // the map builds momentum while dragging and continues moving in
  10820. // the same direction for some time. Feels especially nice on touch
  10821. // devices. Enabled by default unless running on old Android devices.
  10822. inertia: !android23,
  10823. // @option inertiaDeceleration: Number = 3000
  10824. // The rate with which the inertial movement slows down, in pixels/second².
  10825. inertiaDeceleration: 3400, // px/s^2
  10826. // @option inertiaMaxSpeed: Number = Infinity
  10827. // Max speed of the inertial movement, in pixels/second.
  10828. inertiaMaxSpeed: Infinity, // px/s
  10829. // @option easeLinearity: Number = 0.2
  10830. easeLinearity: 0.2,
  10831. // TODO refactor, move to CRS
  10832. // @option worldCopyJump: Boolean = false
  10833. // With this option enabled, the map tracks when you pan to another "copy"
  10834. // of the world and seamlessly jumps to the original one so that all overlays
  10835. // like markers and vector layers are still visible.
  10836. worldCopyJump: false,
  10837. // @option maxBoundsViscosity: Number = 0.0
  10838. // If `maxBounds` is set, this option will control how solid the bounds
  10839. // are when dragging the map around. The default value of `0.0` allows the
  10840. // user to drag outside the bounds at normal speed, higher values will
  10841. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  10842. // solid, preventing the user from dragging outside the bounds.
  10843. maxBoundsViscosity: 0.0
  10844. });
  10845. var Drag = Handler.extend({
  10846. addHooks: function () {
  10847. if (!this._draggable) {
  10848. var map = this._map;
  10849. this._draggable = new Draggable(map._mapPane, map._container);
  10850. this._draggable.on({
  10851. dragstart: this._onDragStart,
  10852. drag: this._onDrag,
  10853. dragend: this._onDragEnd
  10854. }, this);
  10855. this._draggable.on('predrag', this._onPreDragLimit, this);
  10856. if (map.options.worldCopyJump) {
  10857. this._draggable.on('predrag', this._onPreDragWrap, this);
  10858. map.on('zoomend', this._onZoomEnd, this);
  10859. map.whenReady(this._onZoomEnd, this);
  10860. }
  10861. }
  10862. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  10863. this._draggable.enable();
  10864. this._positions = [];
  10865. this._times = [];
  10866. },
  10867. removeHooks: function () {
  10868. removeClass(this._map._container, 'leaflet-grab');
  10869. removeClass(this._map._container, 'leaflet-touch-drag');
  10870. this._draggable.disable();
  10871. },
  10872. moved: function () {
  10873. return this._draggable && this._draggable._moved;
  10874. },
  10875. moving: function () {
  10876. return this._draggable && this._draggable._moving;
  10877. },
  10878. _onDragStart: function () {
  10879. var map = this._map;
  10880. map._stop();
  10881. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  10882. var bounds = toLatLngBounds(this._map.options.maxBounds);
  10883. this._offsetLimit = toBounds(
  10884. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  10885. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  10886. .add(this._map.getSize()));
  10887. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  10888. } else {
  10889. this._offsetLimit = null;
  10890. }
  10891. map
  10892. .fire('movestart')
  10893. .fire('dragstart');
  10894. if (map.options.inertia) {
  10895. this._positions = [];
  10896. this._times = [];
  10897. }
  10898. },
  10899. _onDrag: function (e) {
  10900. if (this._map.options.inertia) {
  10901. var time = this._lastTime = +new Date(),
  10902. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  10903. this._positions.push(pos);
  10904. this._times.push(time);
  10905. this._prunePositions(time);
  10906. }
  10907. this._map
  10908. .fire('move', e)
  10909. .fire('drag', e);
  10910. },
  10911. _prunePositions: function (time) {
  10912. while (this._positions.length > 1 && time - this._times[0] > 50) {
  10913. this._positions.shift();
  10914. this._times.shift();
  10915. }
  10916. },
  10917. _onZoomEnd: function () {
  10918. var pxCenter = this._map.getSize().divideBy(2),
  10919. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  10920. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  10921. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  10922. },
  10923. _viscousLimit: function (value, threshold) {
  10924. return value - (value - threshold) * this._viscosity;
  10925. },
  10926. _onPreDragLimit: function () {
  10927. if (!this._viscosity || !this._offsetLimit) { return; }
  10928. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  10929. var limit = this._offsetLimit;
  10930. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  10931. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  10932. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  10933. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  10934. this._draggable._newPos = this._draggable._startPos.add(offset);
  10935. },
  10936. _onPreDragWrap: function () {
  10937. // TODO refactor to be able to adjust map pane position after zoom
  10938. var worldWidth = this._worldWidth,
  10939. halfWidth = Math.round(worldWidth / 2),
  10940. dx = this._initialWorldOffset,
  10941. x = this._draggable._newPos.x,
  10942. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  10943. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  10944. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  10945. this._draggable._absPos = this._draggable._newPos.clone();
  10946. this._draggable._newPos.x = newX;
  10947. },
  10948. _onDragEnd: function (e) {
  10949. var map = this._map,
  10950. options = map.options,
  10951. noInertia = !options.inertia || this._times.length < 2;
  10952. map.fire('dragend', e);
  10953. if (noInertia) {
  10954. map.fire('moveend');
  10955. } else {
  10956. this._prunePositions(+new Date());
  10957. var direction = this._lastPos.subtract(this._positions[0]),
  10958. duration = (this._lastTime - this._times[0]) / 1000,
  10959. ease = options.easeLinearity,
  10960. speedVector = direction.multiplyBy(ease / duration),
  10961. speed = speedVector.distanceTo([0, 0]),
  10962. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  10963. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  10964. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  10965. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  10966. if (!offset.x && !offset.y) {
  10967. map.fire('moveend');
  10968. } else {
  10969. offset = map._limitOffset(offset, map.options.maxBounds);
  10970. requestAnimFrame(function () {
  10971. map.panBy(offset, {
  10972. duration: decelerationDuration,
  10973. easeLinearity: ease,
  10974. noMoveStart: true,
  10975. animate: true
  10976. });
  10977. });
  10978. }
  10979. }
  10980. }
  10981. });
  10982. // @section Handlers
  10983. // @property dragging: Handler
  10984. // Map dragging handler (by both mouse and touch).
  10985. Map.addInitHook('addHandler', 'dragging', Drag);
  10986. /*
  10987. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  10988. */
  10989. // @namespace Map
  10990. // @section Keyboard Navigation Options
  10991. Map.mergeOptions({
  10992. // @option keyboard: Boolean = true
  10993. // Makes the map focusable and allows users to navigate the map with keyboard
  10994. // arrows and `+`/`-` keys.
  10995. keyboard: true,
  10996. // @option keyboardPanDelta: Number = 80
  10997. // Amount of pixels to pan when pressing an arrow key.
  10998. keyboardPanDelta: 80
  10999. });
  11000. var Keyboard = Handler.extend({
  11001. keyCodes: {
  11002. left: [37],
  11003. right: [39],
  11004. down: [40],
  11005. up: [38],
  11006. zoomIn: [187, 107, 61, 171],
  11007. zoomOut: [189, 109, 54, 173]
  11008. },
  11009. initialize: function (map) {
  11010. this._map = map;
  11011. this._setPanDelta(map.options.keyboardPanDelta);
  11012. this._setZoomDelta(map.options.zoomDelta);
  11013. },
  11014. addHooks: function () {
  11015. var container = this._map._container;
  11016. // make the container focusable by tabbing
  11017. if (container.tabIndex <= 0) {
  11018. container.tabIndex = '0';
  11019. }
  11020. on(container, {
  11021. focus: this._onFocus,
  11022. blur: this._onBlur,
  11023. mousedown: this._onMouseDown
  11024. }, this);
  11025. this._map.on({
  11026. focus: this._addHooks,
  11027. blur: this._removeHooks
  11028. }, this);
  11029. },
  11030. removeHooks: function () {
  11031. this._removeHooks();
  11032. off(this._map._container, {
  11033. focus: this._onFocus,
  11034. blur: this._onBlur,
  11035. mousedown: this._onMouseDown
  11036. }, this);
  11037. this._map.off({
  11038. focus: this._addHooks,
  11039. blur: this._removeHooks
  11040. }, this);
  11041. },
  11042. _onMouseDown: function () {
  11043. if (this._focused) { return; }
  11044. var body = document.body,
  11045. docEl = document.documentElement,
  11046. top = body.scrollTop || docEl.scrollTop,
  11047. left = body.scrollLeft || docEl.scrollLeft;
  11048. this._map._container.focus();
  11049. window.scrollTo(left, top);
  11050. },
  11051. _onFocus: function () {
  11052. this._focused = true;
  11053. this._map.fire('focus');
  11054. },
  11055. _onBlur: function () {
  11056. this._focused = false;
  11057. this._map.fire('blur');
  11058. },
  11059. _setPanDelta: function (panDelta) {
  11060. var keys = this._panKeys = {},
  11061. codes = this.keyCodes,
  11062. i, len;
  11063. for (i = 0, len = codes.left.length; i < len; i++) {
  11064. keys[codes.left[i]] = [-1 * panDelta, 0];
  11065. }
  11066. for (i = 0, len = codes.right.length; i < len; i++) {
  11067. keys[codes.right[i]] = [panDelta, 0];
  11068. }
  11069. for (i = 0, len = codes.down.length; i < len; i++) {
  11070. keys[codes.down[i]] = [0, panDelta];
  11071. }
  11072. for (i = 0, len = codes.up.length; i < len; i++) {
  11073. keys[codes.up[i]] = [0, -1 * panDelta];
  11074. }
  11075. },
  11076. _setZoomDelta: function (zoomDelta) {
  11077. var keys = this._zoomKeys = {},
  11078. codes = this.keyCodes,
  11079. i, len;
  11080. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  11081. keys[codes.zoomIn[i]] = zoomDelta;
  11082. }
  11083. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  11084. keys[codes.zoomOut[i]] = -zoomDelta;
  11085. }
  11086. },
  11087. _addHooks: function () {
  11088. on(document, 'keydown', this._onKeyDown, this);
  11089. },
  11090. _removeHooks: function () {
  11091. off(document, 'keydown', this._onKeyDown, this);
  11092. },
  11093. _onKeyDown: function (e) {
  11094. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  11095. var key = e.keyCode,
  11096. map = this._map,
  11097. offset;
  11098. if (key in this._panKeys) {
  11099. if (!map._panAnim || !map._panAnim._inProgress) {
  11100. offset = this._panKeys[key];
  11101. if (e.shiftKey) {
  11102. offset = toPoint(offset).multiplyBy(3);
  11103. }
  11104. map.panBy(offset);
  11105. if (map.options.maxBounds) {
  11106. map.panInsideBounds(map.options.maxBounds);
  11107. }
  11108. }
  11109. } else if (key in this._zoomKeys) {
  11110. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  11111. } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
  11112. map.closePopup();
  11113. } else {
  11114. return;
  11115. }
  11116. stop(e);
  11117. }
  11118. });
  11119. // @section Handlers
  11120. // @section Handlers
  11121. // @property keyboard: Handler
  11122. // Keyboard navigation handler.
  11123. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  11124. /*
  11125. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  11126. */
  11127. // @namespace Map
  11128. // @section Interaction Options
  11129. Map.mergeOptions({
  11130. // @section Mouse wheel options
  11131. // @option scrollWheelZoom: Boolean|String = true
  11132. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  11133. // it will zoom to the center of the view regardless of where the mouse was.
  11134. scrollWheelZoom: true,
  11135. // @option wheelDebounceTime: Number = 40
  11136. // Limits the rate at which a wheel can fire (in milliseconds). By default
  11137. // user can't zoom via wheel more often than once per 40 ms.
  11138. wheelDebounceTime: 40,
  11139. // @option wheelPxPerZoomLevel: Number = 60
  11140. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  11141. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  11142. // faster (and vice versa).
  11143. wheelPxPerZoomLevel: 60
  11144. });
  11145. var ScrollWheelZoom = Handler.extend({
  11146. addHooks: function () {
  11147. on(this._map._container, 'wheel', this._onWheelScroll, this);
  11148. this._delta = 0;
  11149. },
  11150. removeHooks: function () {
  11151. off(this._map._container, 'wheel', this._onWheelScroll, this);
  11152. },
  11153. _onWheelScroll: function (e) {
  11154. var delta = getWheelDelta(e);
  11155. var debounce = this._map.options.wheelDebounceTime;
  11156. this._delta += delta;
  11157. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  11158. if (!this._startTime) {
  11159. this._startTime = +new Date();
  11160. }
  11161. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  11162. clearTimeout(this._timer);
  11163. this._timer = setTimeout(bind(this._performZoom, this), left);
  11164. stop(e);
  11165. },
  11166. _performZoom: function () {
  11167. var map = this._map,
  11168. zoom = map.getZoom(),
  11169. snap = this._map.options.zoomSnap || 0;
  11170. map._stop(); // stop panning and fly animations if any
  11171. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  11172. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  11173. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  11174. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  11175. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  11176. this._delta = 0;
  11177. this._startTime = null;
  11178. if (!delta) { return; }
  11179. if (map.options.scrollWheelZoom === 'center') {
  11180. map.setZoom(zoom + delta);
  11181. } else {
  11182. map.setZoomAround(this._lastMousePos, zoom + delta);
  11183. }
  11184. }
  11185. });
  11186. // @section Handlers
  11187. // @property scrollWheelZoom: Handler
  11188. // Scroll wheel zoom handler.
  11189. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  11190. /*
  11191. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  11192. */
  11193. // @namespace Map
  11194. // @section Interaction Options
  11195. Map.mergeOptions({
  11196. // @section Touch interaction options
  11197. // @option tap: Boolean = true
  11198. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  11199. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  11200. tap: true,
  11201. // @option tapTolerance: Number = 15
  11202. // The max number of pixels a user can shift his finger during touch
  11203. // for it to be considered a valid tap.
  11204. tapTolerance: 15
  11205. });
  11206. var Tap = Handler.extend({
  11207. addHooks: function () {
  11208. on(this._map._container, 'touchstart', this._onDown, this);
  11209. },
  11210. removeHooks: function () {
  11211. off(this._map._container, 'touchstart', this._onDown, this);
  11212. },
  11213. _onDown: function (e) {
  11214. if (!e.touches) { return; }
  11215. preventDefault(e);
  11216. this._fireClick = true;
  11217. // don't simulate click or track longpress if more than 1 touch
  11218. if (e.touches.length > 1) {
  11219. this._fireClick = false;
  11220. clearTimeout(this._holdTimeout);
  11221. return;
  11222. }
  11223. var first = e.touches[0],
  11224. el = first.target;
  11225. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  11226. // if touching a link, highlight it
  11227. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  11228. addClass(el, 'leaflet-active');
  11229. }
  11230. // simulate long hold but setting a timeout
  11231. this._holdTimeout = setTimeout(bind(function () {
  11232. if (this._isTapValid()) {
  11233. this._fireClick = false;
  11234. this._onUp();
  11235. this._simulateEvent('contextmenu', first);
  11236. }
  11237. }, this), 1000);
  11238. this._simulateEvent('mousedown', first);
  11239. on(document, {
  11240. touchmove: this._onMove,
  11241. touchend: this._onUp
  11242. }, this);
  11243. },
  11244. _onUp: function (e) {
  11245. clearTimeout(this._holdTimeout);
  11246. off(document, {
  11247. touchmove: this._onMove,
  11248. touchend: this._onUp
  11249. }, this);
  11250. if (this._fireClick && e && e.changedTouches) {
  11251. var first = e.changedTouches[0],
  11252. el = first.target;
  11253. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  11254. removeClass(el, 'leaflet-active');
  11255. }
  11256. this._simulateEvent('mouseup', first);
  11257. // simulate click if the touch didn't move too much
  11258. if (this._isTapValid()) {
  11259. this._simulateEvent('click', first);
  11260. }
  11261. }
  11262. },
  11263. _isTapValid: function () {
  11264. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11265. },
  11266. _onMove: function (e) {
  11267. var first = e.touches[0];
  11268. this._newPos = new Point(first.clientX, first.clientY);
  11269. this._simulateEvent('mousemove', first);
  11270. },
  11271. _simulateEvent: function (type, e) {
  11272. var simulatedEvent = document.createEvent('MouseEvents');
  11273. simulatedEvent._simulated = true;
  11274. e.target._simulatedClick = true;
  11275. simulatedEvent.initMouseEvent(
  11276. type, true, true, window, 1,
  11277. e.screenX, e.screenY,
  11278. e.clientX, e.clientY,
  11279. false, false, false, false, 0, null);
  11280. e.target.dispatchEvent(simulatedEvent);
  11281. }
  11282. });
  11283. // @section Handlers
  11284. // @property tap: Handler
  11285. // Mobile touch hacks (quick tap and touch hold) handler.
  11286. if (touch && (!pointer || safari)) {
  11287. Map.addInitHook('addHandler', 'tap', Tap);
  11288. }
  11289. /*
  11290. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11291. */
  11292. // @namespace Map
  11293. // @section Interaction Options
  11294. Map.mergeOptions({
  11295. // @section Touch interaction options
  11296. // @option touchZoom: Boolean|String = *
  11297. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11298. // passed `'center'`, it will zoom to the center of the view regardless of
  11299. // where the touch events (fingers) were. Enabled for touch-capable web
  11300. // browsers except for old Androids.
  11301. touchZoom: touch && !android23,
  11302. // @option bounceAtZoomLimits: Boolean = true
  11303. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11304. // and then bounce back when pinch-zooming.
  11305. bounceAtZoomLimits: true
  11306. });
  11307. var TouchZoom = Handler.extend({
  11308. addHooks: function () {
  11309. addClass(this._map._container, 'leaflet-touch-zoom');
  11310. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11311. },
  11312. removeHooks: function () {
  11313. removeClass(this._map._container, 'leaflet-touch-zoom');
  11314. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11315. },
  11316. _onTouchStart: function (e) {
  11317. var map = this._map;
  11318. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  11319. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11320. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11321. this._centerPoint = map.getSize()._divideBy(2);
  11322. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11323. if (map.options.touchZoom !== 'center') {
  11324. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11325. }
  11326. this._startDist = p1.distanceTo(p2);
  11327. this._startZoom = map.getZoom();
  11328. this._moved = false;
  11329. this._zooming = true;
  11330. map._stop();
  11331. on(document, 'touchmove', this._onTouchMove, this);
  11332. on(document, 'touchend', this._onTouchEnd, this);
  11333. preventDefault(e);
  11334. },
  11335. _onTouchMove: function (e) {
  11336. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  11337. var map = this._map,
  11338. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11339. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11340. scale = p1.distanceTo(p2) / this._startDist;
  11341. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11342. if (!map.options.bounceAtZoomLimits && (
  11343. (this._zoom < map.getMinZoom() && scale < 1) ||
  11344. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11345. this._zoom = map._limitZoom(this._zoom);
  11346. }
  11347. if (map.options.touchZoom === 'center') {
  11348. this._center = this._startLatLng;
  11349. if (scale === 1) { return; }
  11350. } else {
  11351. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11352. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11353. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  11354. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11355. }
  11356. if (!this._moved) {
  11357. map._moveStart(true, false);
  11358. this._moved = true;
  11359. }
  11360. cancelAnimFrame(this._animRequest);
  11361. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  11362. this._animRequest = requestAnimFrame(moveFn, this, true);
  11363. preventDefault(e);
  11364. },
  11365. _onTouchEnd: function () {
  11366. if (!this._moved || !this._zooming) {
  11367. this._zooming = false;
  11368. return;
  11369. }
  11370. this._zooming = false;
  11371. cancelAnimFrame(this._animRequest);
  11372. off(document, 'touchmove', this._onTouchMove, this);
  11373. off(document, 'touchend', this._onTouchEnd, this);
  11374. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11375. if (this._map.options.zoomAnimation) {
  11376. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11377. } else {
  11378. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11379. }
  11380. }
  11381. });
  11382. // @section Handlers
  11383. // @property touchZoom: Handler
  11384. // Touch zoom handler.
  11385. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11386. Map.BoxZoom = BoxZoom;
  11387. Map.DoubleClickZoom = DoubleClickZoom;
  11388. Map.Drag = Drag;
  11389. Map.Keyboard = Keyboard;
  11390. Map.ScrollWheelZoom = ScrollWheelZoom;
  11391. Map.Tap = Tap;
  11392. Map.TouchZoom = TouchZoom;
  11393. exports.version = version;
  11394. exports.Control = Control;
  11395. exports.control = control;
  11396. exports.Browser = Browser;
  11397. exports.Evented = Evented;
  11398. exports.Mixin = Mixin;
  11399. exports.Util = Util;
  11400. exports.Class = Class;
  11401. exports.Handler = Handler;
  11402. exports.extend = extend;
  11403. exports.bind = bind;
  11404. exports.stamp = stamp;
  11405. exports.setOptions = setOptions;
  11406. exports.DomEvent = DomEvent;
  11407. exports.DomUtil = DomUtil;
  11408. exports.PosAnimation = PosAnimation;
  11409. exports.Draggable = Draggable;
  11410. exports.LineUtil = LineUtil;
  11411. exports.PolyUtil = PolyUtil;
  11412. exports.Point = Point;
  11413. exports.point = toPoint;
  11414. exports.Bounds = Bounds;
  11415. exports.bounds = toBounds;
  11416. exports.Transformation = Transformation;
  11417. exports.transformation = toTransformation;
  11418. exports.Projection = index;
  11419. exports.LatLng = LatLng;
  11420. exports.latLng = toLatLng;
  11421. exports.LatLngBounds = LatLngBounds;
  11422. exports.latLngBounds = toLatLngBounds;
  11423. exports.CRS = CRS;
  11424. exports.GeoJSON = GeoJSON;
  11425. exports.geoJSON = geoJSON;
  11426. exports.geoJson = geoJson;
  11427. exports.Layer = Layer;
  11428. exports.LayerGroup = LayerGroup;
  11429. exports.layerGroup = layerGroup;
  11430. exports.FeatureGroup = FeatureGroup;
  11431. exports.featureGroup = featureGroup;
  11432. exports.ImageOverlay = ImageOverlay;
  11433. exports.imageOverlay = imageOverlay;
  11434. exports.VideoOverlay = VideoOverlay;
  11435. exports.videoOverlay = videoOverlay;
  11436. exports.SVGOverlay = SVGOverlay;
  11437. exports.svgOverlay = svgOverlay;
  11438. exports.DivOverlay = DivOverlay;
  11439. exports.Popup = Popup;
  11440. exports.popup = popup;
  11441. exports.Tooltip = Tooltip;
  11442. exports.tooltip = tooltip;
  11443. exports.Icon = Icon;
  11444. exports.icon = icon;
  11445. exports.DivIcon = DivIcon;
  11446. exports.divIcon = divIcon;
  11447. exports.Marker = Marker;
  11448. exports.marker = marker;
  11449. exports.TileLayer = TileLayer;
  11450. exports.tileLayer = tileLayer;
  11451. exports.GridLayer = GridLayer;
  11452. exports.gridLayer = gridLayer;
  11453. exports.SVG = SVG;
  11454. exports.svg = svg$1;
  11455. exports.Renderer = Renderer;
  11456. exports.Canvas = Canvas;
  11457. exports.canvas = canvas$1;
  11458. exports.Path = Path;
  11459. exports.CircleMarker = CircleMarker;
  11460. exports.circleMarker = circleMarker;
  11461. exports.Circle = Circle;
  11462. exports.circle = circle;
  11463. exports.Polyline = Polyline;
  11464. exports.polyline = polyline;
  11465. exports.Polygon = Polygon;
  11466. exports.polygon = polygon;
  11467. exports.Rectangle = Rectangle;
  11468. exports.rectangle = rectangle;
  11469. exports.Map = Map;
  11470. exports.map = createMap;
  11471. var oldL = window.L;
  11472. exports.noConflict = function() {
  11473. window.L = oldL;
  11474. return this;
  11475. }
  11476. // Always export us to window global (see #2364)
  11477. window.L = exports;
  11478. })));
  11479. //# sourceMappingURL=leaflet-src.js.map