leaflet-src.js 391 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080
  1. /* @preserve
  2. * Leaflet 1.6.0, 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.6.0";
  11. /*
  12. * @namespace Util
  13. *
  14. * Various utility functions, used by Leaflet internally.
  15. */
  16. var freeze = Object.freeze;
  17. Object.freeze = function (obj) { return obj; };
  18. // @function extend(dest: Object, src?: Object): Object
  19. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  20. function extend(dest) {
  21. var i, j, len, src;
  22. for (j = 1, len = arguments.length; j < len; j++) {
  23. src = arguments[j];
  24. for (i in src) {
  25. dest[i] = src[i];
  26. }
  27. }
  28. return dest;
  29. }
  30. // @function create(proto: Object, properties?: Object): Object
  31. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  32. var create = Object.create || (function () {
  33. function F() {}
  34. return function (proto) {
  35. F.prototype = proto;
  36. return new F();
  37. };
  38. })();
  39. // @function bind(fn: Function, …): Function
  40. // 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).
  41. // Has a `L.bind()` shortcut.
  42. function bind(fn, obj) {
  43. var slice = Array.prototype.slice;
  44. if (fn.bind) {
  45. return fn.bind.apply(fn, slice.call(arguments, 1));
  46. }
  47. var args = slice.call(arguments, 2);
  48. return function () {
  49. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  50. };
  51. }
  52. // @property lastId: Number
  53. // Last unique ID used by [`stamp()`](#util-stamp)
  54. var lastId = 0;
  55. // @function stamp(obj: Object): Number
  56. // Returns the unique ID of an object, assigning it one if it doesn't have it.
  57. function stamp(obj) {
  58. /*eslint-disable */
  59. obj._leaflet_id = obj._leaflet_id || ++lastId;
  60. return obj._leaflet_id;
  61. /* eslint-enable */
  62. }
  63. // @function throttle(fn: Function, time: Number, context: Object): Function
  64. // Returns a function which executes function `fn` with the given scope `context`
  65. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  66. // `fn` will be called no more than one time per given amount of `time`. The arguments
  67. // received by the bound function will be any arguments passed when binding the
  68. // function, followed by any arguments passed when invoking the bound function.
  69. // Has an `L.throttle` shortcut.
  70. function throttle(fn, time, context) {
  71. var lock, args, wrapperFn, later;
  72. later = function () {
  73. // reset lock and call if queued
  74. lock = false;
  75. if (args) {
  76. wrapperFn.apply(context, args);
  77. args = false;
  78. }
  79. };
  80. wrapperFn = function () {
  81. if (lock) {
  82. // called too soon, queue to call later
  83. args = arguments;
  84. } else {
  85. // call and lock until later
  86. fn.apply(context, arguments);
  87. setTimeout(later, time);
  88. lock = true;
  89. }
  90. };
  91. return wrapperFn;
  92. }
  93. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  94. // Returns the number `num` modulo `range` in such a way so it lies within
  95. // `range[0]` and `range[1]`. The returned value will be always smaller than
  96. // `range[1]` unless `includeMax` is set to `true`.
  97. function wrapNum(x, range, includeMax) {
  98. var max = range[1],
  99. min = range[0],
  100. d = max - min;
  101. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  102. }
  103. // @function falseFn(): Function
  104. // Returns a function which always returns `false`.
  105. function falseFn() { return false; }
  106. // @function formatNum(num: Number, digits?: Number): Number
  107. // Returns the number `num` rounded to `digits` decimals, or to 6 decimals by default.
  108. function formatNum(num, digits) {
  109. var pow = Math.pow(10, (digits === undefined ? 6 : digits));
  110. return Math.round(num * pow) / pow;
  111. }
  112. // @function trim(str: String): String
  113. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  114. function trim(str) {
  115. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  116. }
  117. // @function splitWords(str: String): String[]
  118. // Trims and splits the string on whitespace and returns the array of parts.
  119. function splitWords(str) {
  120. return trim(str).split(/\s+/);
  121. }
  122. // @function setOptions(obj: Object, options: Object): Object
  123. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  124. function setOptions(obj, options) {
  125. if (!obj.hasOwnProperty('options')) {
  126. obj.options = obj.options ? create(obj.options) : {};
  127. }
  128. for (var i in options) {
  129. obj.options[i] = options[i];
  130. }
  131. return obj.options;
  132. }
  133. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  134. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  135. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  136. // be appended at the end. If `uppercase` is `true`, the parameter names will
  137. // be uppercased (e.g. `'?A=foo&B=bar'`)
  138. function getParamString(obj, existingUrl, uppercase) {
  139. var params = [];
  140. for (var i in obj) {
  141. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  142. }
  143. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  144. }
  145. var templateRe = /\{ *([\w_-]+) *\}/g;
  146. // @function template(str: String, data: Object): String
  147. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  148. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  149. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  150. // data values — they will be evaluated passing `data` as an argument.
  151. function template(str, data) {
  152. return str.replace(templateRe, function (str, key) {
  153. var value = data[key];
  154. if (value === undefined) {
  155. throw new Error('No value provided for variable ' + str);
  156. } else if (typeof value === 'function') {
  157. value = value(data);
  158. }
  159. return value;
  160. });
  161. }
  162. // @function isArray(obj): Boolean
  163. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  164. var isArray = Array.isArray || function (obj) {
  165. return (Object.prototype.toString.call(obj) === '[object Array]');
  166. };
  167. // @function indexOf(array: Array, el: Object): Number
  168. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  169. function indexOf(array, el) {
  170. for (var i = 0; i < array.length; i++) {
  171. if (array[i] === el) { return i; }
  172. }
  173. return -1;
  174. }
  175. // @property emptyImageUrl: String
  176. // Data URI string containing a base64-encoded empty GIF image.
  177. // Used as a hack to free memory from unused images on WebKit-powered
  178. // mobile devices (by setting image `src` to this string).
  179. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  180. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  181. function getPrefixed(name) {
  182. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  183. }
  184. var lastTime = 0;
  185. // fallback for IE 7-8
  186. function timeoutDefer(fn) {
  187. var time = +new Date(),
  188. timeToCall = Math.max(0, 16 - (time - lastTime));
  189. lastTime = time + timeToCall;
  190. return window.setTimeout(fn, timeToCall);
  191. }
  192. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  193. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  194. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  195. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  196. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  197. // `context` if given. When `immediate` is set, `fn` is called immediately if
  198. // the browser doesn't have native support for
  199. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  200. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  201. function requestAnimFrame(fn, context, immediate) {
  202. if (immediate && requestFn === timeoutDefer) {
  203. fn.call(context);
  204. } else {
  205. return requestFn.call(window, bind(fn, context));
  206. }
  207. }
  208. // @function cancelAnimFrame(id: Number): undefined
  209. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  210. function cancelAnimFrame(id) {
  211. if (id) {
  212. cancelFn.call(window, id);
  213. }
  214. }
  215. var Util = (Object.freeze || Object)({
  216. freeze: freeze,
  217. extend: extend,
  218. create: create,
  219. bind: bind,
  220. lastId: lastId,
  221. stamp: stamp,
  222. throttle: throttle,
  223. wrapNum: wrapNum,
  224. falseFn: falseFn,
  225. formatNum: formatNum,
  226. trim: trim,
  227. splitWords: splitWords,
  228. setOptions: setOptions,
  229. getParamString: getParamString,
  230. template: template,
  231. isArray: isArray,
  232. indexOf: indexOf,
  233. emptyImageUrl: emptyImageUrl,
  234. requestFn: requestFn,
  235. cancelFn: cancelFn,
  236. requestAnimFrame: requestAnimFrame,
  237. cancelAnimFrame: cancelAnimFrame
  238. });
  239. // @class Class
  240. // @aka L.Class
  241. // @section
  242. // @uninheritable
  243. // Thanks to John Resig and Dean Edwards for inspiration!
  244. function Class() {}
  245. Class.extend = function (props) {
  246. // @function extend(props: Object): Function
  247. // [Extends the current class](#class-inheritance) given the properties to be included.
  248. // Returns a Javascript function that is a class constructor (to be called with `new`).
  249. var NewClass = function () {
  250. // call the constructor
  251. if (this.initialize) {
  252. this.initialize.apply(this, arguments);
  253. }
  254. // call all constructor hooks
  255. this.callInitHooks();
  256. };
  257. var parentProto = NewClass.__super__ = this.prototype;
  258. var proto = create(parentProto);
  259. proto.constructor = NewClass;
  260. NewClass.prototype = proto;
  261. // inherit parent's statics
  262. for (var i in this) {
  263. if (this.hasOwnProperty(i) && i !== 'prototype' && i !== '__super__') {
  264. NewClass[i] = this[i];
  265. }
  266. }
  267. // mix static properties into the class
  268. if (props.statics) {
  269. extend(NewClass, props.statics);
  270. delete props.statics;
  271. }
  272. // mix includes into the prototype
  273. if (props.includes) {
  274. checkDeprecatedMixinEvents(props.includes);
  275. extend.apply(null, [proto].concat(props.includes));
  276. delete props.includes;
  277. }
  278. // merge options
  279. if (proto.options) {
  280. props.options = extend(create(proto.options), props.options);
  281. }
  282. // mix given properties into the prototype
  283. extend(proto, props);
  284. proto._initHooks = [];
  285. // add method for calling all hooks
  286. proto.callInitHooks = function () {
  287. if (this._initHooksCalled) { return; }
  288. if (parentProto.callInitHooks) {
  289. parentProto.callInitHooks.call(this);
  290. }
  291. this._initHooksCalled = true;
  292. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  293. proto._initHooks[i].call(this);
  294. }
  295. };
  296. return NewClass;
  297. };
  298. // @function include(properties: Object): this
  299. // [Includes a mixin](#class-includes) into the current class.
  300. Class.include = function (props) {
  301. extend(this.prototype, props);
  302. return this;
  303. };
  304. // @function mergeOptions(options: Object): this
  305. // [Merges `options`](#class-options) into the defaults of the class.
  306. Class.mergeOptions = function (options) {
  307. extend(this.prototype.options, options);
  308. return this;
  309. };
  310. // @function addInitHook(fn: Function): this
  311. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  312. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  313. var args = Array.prototype.slice.call(arguments, 1);
  314. var init = typeof fn === 'function' ? fn : function () {
  315. this[fn].apply(this, args);
  316. };
  317. this.prototype._initHooks = this.prototype._initHooks || [];
  318. this.prototype._initHooks.push(init);
  319. return this;
  320. };
  321. function checkDeprecatedMixinEvents(includes) {
  322. if (typeof L === 'undefined' || !L || !L.Mixin) { return; }
  323. includes = isArray(includes) ? includes : [includes];
  324. for (var i = 0; i < includes.length; i++) {
  325. if (includes[i] === L.Mixin.Events) {
  326. console.warn('Deprecated include of L.Mixin.Events: ' +
  327. 'this property will be removed in future releases, ' +
  328. 'please inherit from L.Evented instead.', new Error().stack);
  329. }
  330. }
  331. }
  332. /*
  333. * @class Evented
  334. * @aka L.Evented
  335. * @inherits Class
  336. *
  337. * 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).
  338. *
  339. * @example
  340. *
  341. * ```js
  342. * map.on('click', function(e) {
  343. * alert(e.latlng);
  344. * } );
  345. * ```
  346. *
  347. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  348. *
  349. * ```js
  350. * function onClick(e) { ... }
  351. *
  352. * map.on('click', onClick);
  353. * map.off('click', onClick);
  354. * ```
  355. */
  356. var Events = {
  357. /* @method on(type: String, fn: Function, context?: Object): this
  358. * 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'`).
  359. *
  360. * @alternative
  361. * @method on(eventMap: Object): this
  362. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  363. */
  364. on: function (types, fn, context) {
  365. // types can be a map of types/handlers
  366. if (typeof types === 'object') {
  367. for (var type in types) {
  368. // we don't process space-separated events here for performance;
  369. // it's a hot path since Layer uses the on(obj) syntax
  370. this._on(type, types[type], fn);
  371. }
  372. } else {
  373. // types can be a string of space-separated words
  374. types = splitWords(types);
  375. for (var i = 0, len = types.length; i < len; i++) {
  376. this._on(types[i], fn, context);
  377. }
  378. }
  379. return this;
  380. },
  381. /* @method off(type: String, fn?: Function, context?: Object): this
  382. * 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.
  383. *
  384. * @alternative
  385. * @method off(eventMap: Object): this
  386. * Removes a set of type/listener pairs.
  387. *
  388. * @alternative
  389. * @method off: this
  390. * Removes all listeners to all events on the object. This includes implicitly attached events.
  391. */
  392. off: function (types, fn, context) {
  393. if (!types) {
  394. // clear all listeners if called without arguments
  395. delete this._events;
  396. } else if (typeof types === 'object') {
  397. for (var type in types) {
  398. this._off(type, types[type], fn);
  399. }
  400. } else {
  401. types = splitWords(types);
  402. for (var i = 0, len = types.length; i < len; i++) {
  403. this._off(types[i], fn, context);
  404. }
  405. }
  406. return this;
  407. },
  408. // attach listener (without syntactic sugar now)
  409. _on: function (type, fn, context) {
  410. this._events = this._events || {};
  411. /* get/init listeners for type */
  412. var typeListeners = this._events[type];
  413. if (!typeListeners) {
  414. typeListeners = [];
  415. this._events[type] = typeListeners;
  416. }
  417. if (context === this) {
  418. // Less memory footprint.
  419. context = undefined;
  420. }
  421. var newListener = {fn: fn, ctx: context},
  422. listeners = typeListeners;
  423. // check if fn already there
  424. for (var i = 0, len = listeners.length; i < len; i++) {
  425. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  426. return;
  427. }
  428. }
  429. listeners.push(newListener);
  430. },
  431. _off: function (type, fn, context) {
  432. var listeners,
  433. i,
  434. len;
  435. if (!this._events) { return; }
  436. listeners = this._events[type];
  437. if (!listeners) {
  438. return;
  439. }
  440. if (!fn) {
  441. // Set all removed listeners to noop so they are not called if remove happens in fire
  442. for (i = 0, len = listeners.length; i < len; i++) {
  443. listeners[i].fn = falseFn;
  444. }
  445. // clear all listeners for a type if function isn't specified
  446. delete this._events[type];
  447. return;
  448. }
  449. if (context === this) {
  450. context = undefined;
  451. }
  452. if (listeners) {
  453. // find fn and remove it
  454. for (i = 0, len = listeners.length; i < len; i++) {
  455. var l = listeners[i];
  456. if (l.ctx !== context) { continue; }
  457. if (l.fn === fn) {
  458. // set the removed listener to noop so that's not called if remove happens in fire
  459. l.fn = falseFn;
  460. if (this._firingCount) {
  461. /* copy array in case events are being fired */
  462. this._events[type] = listeners = listeners.slice();
  463. }
  464. listeners.splice(i, 1);
  465. return;
  466. }
  467. }
  468. }
  469. },
  470. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  471. // Fires an event of the specified type. You can optionally provide an data
  472. // object — the first argument of the listener function will contain its
  473. // properties. The event can optionally be propagated to event parents.
  474. fire: function (type, data, propagate) {
  475. if (!this.listens(type, propagate)) { return this; }
  476. var event = extend({}, data, {
  477. type: type,
  478. target: this,
  479. sourceTarget: data && data.sourceTarget || this
  480. });
  481. if (this._events) {
  482. var listeners = this._events[type];
  483. if (listeners) {
  484. this._firingCount = (this._firingCount + 1) || 1;
  485. for (var i = 0, len = listeners.length; i < len; i++) {
  486. var l = listeners[i];
  487. l.fn.call(l.ctx || this, event);
  488. }
  489. this._firingCount--;
  490. }
  491. }
  492. if (propagate) {
  493. // propagate the event to parents (set with addEventParent)
  494. this._propagateEvent(event);
  495. }
  496. return this;
  497. },
  498. // @method listens(type: String): Boolean
  499. // Returns `true` if a particular event type has any listeners attached to it.
  500. listens: function (type, propagate) {
  501. var listeners = this._events && this._events[type];
  502. if (listeners && listeners.length) { return true; }
  503. if (propagate) {
  504. // also check parents for listeners if event propagates
  505. for (var id in this._eventParents) {
  506. if (this._eventParents[id].listens(type, propagate)) { return true; }
  507. }
  508. }
  509. return false;
  510. },
  511. // @method once(…): this
  512. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  513. once: function (types, fn, context) {
  514. if (typeof types === 'object') {
  515. for (var type in types) {
  516. this.once(type, types[type], fn);
  517. }
  518. return this;
  519. }
  520. var handler = bind(function () {
  521. this
  522. .off(types, fn, context)
  523. .off(types, handler, context);
  524. }, this);
  525. // add a listener that's executed once and removed after that
  526. return this
  527. .on(types, fn, context)
  528. .on(types, handler, context);
  529. },
  530. // @method addEventParent(obj: Evented): this
  531. // Adds an event parent - an `Evented` that will receive propagated events
  532. addEventParent: function (obj) {
  533. this._eventParents = this._eventParents || {};
  534. this._eventParents[stamp(obj)] = obj;
  535. return this;
  536. },
  537. // @method removeEventParent(obj: Evented): this
  538. // Removes an event parent, so it will stop receiving propagated events
  539. removeEventParent: function (obj) {
  540. if (this._eventParents) {
  541. delete this._eventParents[stamp(obj)];
  542. }
  543. return this;
  544. },
  545. _propagateEvent: function (e) {
  546. for (var id in this._eventParents) {
  547. this._eventParents[id].fire(e.type, extend({
  548. layer: e.target,
  549. propagatedFrom: e.target
  550. }, e), true);
  551. }
  552. }
  553. };
  554. // aliases; we should ditch those eventually
  555. // @method addEventListener(…): this
  556. // Alias to [`on(…)`](#evented-on)
  557. Events.addEventListener = Events.on;
  558. // @method removeEventListener(…): this
  559. // Alias to [`off(…)`](#evented-off)
  560. // @method clearAllEventListeners(…): this
  561. // Alias to [`off()`](#evented-off)
  562. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  563. // @method addOneTimeEventListener(…): this
  564. // Alias to [`once(…)`](#evented-once)
  565. Events.addOneTimeEventListener = Events.once;
  566. // @method fireEvent(…): this
  567. // Alias to [`fire(…)`](#evented-fire)
  568. Events.fireEvent = Events.fire;
  569. // @method hasEventListeners(…): Boolean
  570. // Alias to [`listens(…)`](#evented-listens)
  571. Events.hasEventListeners = Events.listens;
  572. var Evented = Class.extend(Events);
  573. /*
  574. * @class Point
  575. * @aka L.Point
  576. *
  577. * Represents a point with `x` and `y` coordinates in pixels.
  578. *
  579. * @example
  580. *
  581. * ```js
  582. * var point = L.point(200, 300);
  583. * ```
  584. *
  585. * 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:
  586. *
  587. * ```js
  588. * map.panBy([200, 300]);
  589. * map.panBy(L.point(200, 300));
  590. * ```
  591. *
  592. * Note that `Point` does not inherit from Leafet's `Class` object,
  593. * which means new classes can't inherit from it, and new methods
  594. * can't be added to it with the `include` function.
  595. */
  596. function Point(x, y, round) {
  597. // @property x: Number; The `x` coordinate of the point
  598. this.x = (round ? Math.round(x) : x);
  599. // @property y: Number; The `y` coordinate of the point
  600. this.y = (round ? Math.round(y) : y);
  601. }
  602. var trunc = Math.trunc || function (v) {
  603. return v > 0 ? Math.floor(v) : Math.ceil(v);
  604. };
  605. Point.prototype = {
  606. // @method clone(): Point
  607. // Returns a copy of the current point.
  608. clone: function () {
  609. return new Point(this.x, this.y);
  610. },
  611. // @method add(otherPoint: Point): Point
  612. // Returns the result of addition of the current and the given points.
  613. add: function (point) {
  614. // non-destructive, returns a new point
  615. return this.clone()._add(toPoint(point));
  616. },
  617. _add: function (point) {
  618. // destructive, used directly for performance in situations where it's safe to modify existing point
  619. this.x += point.x;
  620. this.y += point.y;
  621. return this;
  622. },
  623. // @method subtract(otherPoint: Point): Point
  624. // Returns the result of subtraction of the given point from the current.
  625. subtract: function (point) {
  626. return this.clone()._subtract(toPoint(point));
  627. },
  628. _subtract: function (point) {
  629. this.x -= point.x;
  630. this.y -= point.y;
  631. return this;
  632. },
  633. // @method divideBy(num: Number): Point
  634. // Returns the result of division of the current point by the given number.
  635. divideBy: function (num) {
  636. return this.clone()._divideBy(num);
  637. },
  638. _divideBy: function (num) {
  639. this.x /= num;
  640. this.y /= num;
  641. return this;
  642. },
  643. // @method multiplyBy(num: Number): Point
  644. // Returns the result of multiplication of the current point by the given number.
  645. multiplyBy: function (num) {
  646. return this.clone()._multiplyBy(num);
  647. },
  648. _multiplyBy: function (num) {
  649. this.x *= num;
  650. this.y *= num;
  651. return this;
  652. },
  653. // @method scaleBy(scale: Point): Point
  654. // Multiply each coordinate of the current point by each coordinate of
  655. // `scale`. In linear algebra terms, multiply the point by the
  656. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  657. // defined by `scale`.
  658. scaleBy: function (point) {
  659. return new Point(this.x * point.x, this.y * point.y);
  660. },
  661. // @method unscaleBy(scale: Point): Point
  662. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  663. // each coordinate of `scale`.
  664. unscaleBy: function (point) {
  665. return new Point(this.x / point.x, this.y / point.y);
  666. },
  667. // @method round(): Point
  668. // Returns a copy of the current point with rounded coordinates.
  669. round: function () {
  670. return this.clone()._round();
  671. },
  672. _round: function () {
  673. this.x = Math.round(this.x);
  674. this.y = Math.round(this.y);
  675. return this;
  676. },
  677. // @method floor(): Point
  678. // Returns a copy of the current point with floored coordinates (rounded down).
  679. floor: function () {
  680. return this.clone()._floor();
  681. },
  682. _floor: function () {
  683. this.x = Math.floor(this.x);
  684. this.y = Math.floor(this.y);
  685. return this;
  686. },
  687. // @method ceil(): Point
  688. // Returns a copy of the current point with ceiled coordinates (rounded up).
  689. ceil: function () {
  690. return this.clone()._ceil();
  691. },
  692. _ceil: function () {
  693. this.x = Math.ceil(this.x);
  694. this.y = Math.ceil(this.y);
  695. return this;
  696. },
  697. // @method trunc(): Point
  698. // Returns a copy of the current point with truncated coordinates (rounded towards zero).
  699. trunc: function () {
  700. return this.clone()._trunc();
  701. },
  702. _trunc: function () {
  703. this.x = trunc(this.x);
  704. this.y = trunc(this.y);
  705. return this;
  706. },
  707. // @method distanceTo(otherPoint: Point): Number
  708. // Returns the cartesian distance between the current and the given points.
  709. distanceTo: function (point) {
  710. point = toPoint(point);
  711. var x = point.x - this.x,
  712. y = point.y - this.y;
  713. return Math.sqrt(x * x + y * y);
  714. },
  715. // @method equals(otherPoint: Point): Boolean
  716. // Returns `true` if the given point has the same coordinates.
  717. equals: function (point) {
  718. point = toPoint(point);
  719. return point.x === this.x &&
  720. point.y === this.y;
  721. },
  722. // @method contains(otherPoint: Point): Boolean
  723. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  724. contains: function (point) {
  725. point = toPoint(point);
  726. return Math.abs(point.x) <= Math.abs(this.x) &&
  727. Math.abs(point.y) <= Math.abs(this.y);
  728. },
  729. // @method toString(): String
  730. // Returns a string representation of the point for debugging purposes.
  731. toString: function () {
  732. return 'Point(' +
  733. formatNum(this.x) + ', ' +
  734. formatNum(this.y) + ')';
  735. }
  736. };
  737. // @factory L.point(x: Number, y: Number, round?: Boolean)
  738. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  739. // @alternative
  740. // @factory L.point(coords: Number[])
  741. // Expects an array of the form `[x, y]` instead.
  742. // @alternative
  743. // @factory L.point(coords: Object)
  744. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  745. function toPoint(x, y, round) {
  746. if (x instanceof Point) {
  747. return x;
  748. }
  749. if (isArray(x)) {
  750. return new Point(x[0], x[1]);
  751. }
  752. if (x === undefined || x === null) {
  753. return x;
  754. }
  755. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  756. return new Point(x.x, x.y);
  757. }
  758. return new Point(x, y, round);
  759. }
  760. /*
  761. * @class Bounds
  762. * @aka L.Bounds
  763. *
  764. * Represents a rectangular area in pixel coordinates.
  765. *
  766. * @example
  767. *
  768. * ```js
  769. * var p1 = L.point(10, 10),
  770. * p2 = L.point(40, 60),
  771. * bounds = L.bounds(p1, p2);
  772. * ```
  773. *
  774. * 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:
  775. *
  776. * ```js
  777. * otherBounds.intersects([[10, 10], [40, 60]]);
  778. * ```
  779. *
  780. * Note that `Bounds` does not inherit from Leafet's `Class` object,
  781. * which means new classes can't inherit from it, and new methods
  782. * can't be added to it with the `include` function.
  783. */
  784. function Bounds(a, b) {
  785. if (!a) { return; }
  786. var points = b ? [a, b] : a;
  787. for (var i = 0, len = points.length; i < len; i++) {
  788. this.extend(points[i]);
  789. }
  790. }
  791. Bounds.prototype = {
  792. // @method extend(point: Point): this
  793. // Extends the bounds to contain the given point.
  794. extend: function (point) { // (Point)
  795. point = toPoint(point);
  796. // @property min: Point
  797. // The top left corner of the rectangle.
  798. // @property max: Point
  799. // The bottom right corner of the rectangle.
  800. if (!this.min && !this.max) {
  801. this.min = point.clone();
  802. this.max = point.clone();
  803. } else {
  804. this.min.x = Math.min(point.x, this.min.x);
  805. this.max.x = Math.max(point.x, this.max.x);
  806. this.min.y = Math.min(point.y, this.min.y);
  807. this.max.y = Math.max(point.y, this.max.y);
  808. }
  809. return this;
  810. },
  811. // @method getCenter(round?: Boolean): Point
  812. // Returns the center point of the bounds.
  813. getCenter: function (round) {
  814. return new Point(
  815. (this.min.x + this.max.x) / 2,
  816. (this.min.y + this.max.y) / 2, round);
  817. },
  818. // @method getBottomLeft(): Point
  819. // Returns the bottom-left point of the bounds.
  820. getBottomLeft: function () {
  821. return new Point(this.min.x, this.max.y);
  822. },
  823. // @method getTopRight(): Point
  824. // Returns the top-right point of the bounds.
  825. getTopRight: function () { // -> Point
  826. return new Point(this.max.x, this.min.y);
  827. },
  828. // @method getTopLeft(): Point
  829. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  830. getTopLeft: function () {
  831. return this.min; // left, top
  832. },
  833. // @method getBottomRight(): Point
  834. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  835. getBottomRight: function () {
  836. return this.max; // right, bottom
  837. },
  838. // @method getSize(): Point
  839. // Returns the size of the given bounds
  840. getSize: function () {
  841. return this.max.subtract(this.min);
  842. },
  843. // @method contains(otherBounds: Bounds): Boolean
  844. // Returns `true` if the rectangle contains the given one.
  845. // @alternative
  846. // @method contains(point: Point): Boolean
  847. // Returns `true` if the rectangle contains the given point.
  848. contains: function (obj) {
  849. var min, max;
  850. if (typeof obj[0] === 'number' || obj instanceof Point) {
  851. obj = toPoint(obj);
  852. } else {
  853. obj = toBounds(obj);
  854. }
  855. if (obj instanceof Bounds) {
  856. min = obj.min;
  857. max = obj.max;
  858. } else {
  859. min = max = obj;
  860. }
  861. return (min.x >= this.min.x) &&
  862. (max.x <= this.max.x) &&
  863. (min.y >= this.min.y) &&
  864. (max.y <= this.max.y);
  865. },
  866. // @method intersects(otherBounds: Bounds): Boolean
  867. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  868. // intersect if they have at least one point in common.
  869. intersects: function (bounds) { // (Bounds) -> Boolean
  870. bounds = toBounds(bounds);
  871. var min = this.min,
  872. max = this.max,
  873. min2 = bounds.min,
  874. max2 = bounds.max,
  875. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  876. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  877. return xIntersects && yIntersects;
  878. },
  879. // @method overlaps(otherBounds: Bounds): Boolean
  880. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  881. // overlap if their intersection is an area.
  882. overlaps: function (bounds) { // (Bounds) -> Boolean
  883. bounds = toBounds(bounds);
  884. var min = this.min,
  885. max = this.max,
  886. min2 = bounds.min,
  887. max2 = bounds.max,
  888. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  889. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  890. return xOverlaps && yOverlaps;
  891. },
  892. isValid: function () {
  893. return !!(this.min && this.max);
  894. }
  895. };
  896. // @factory L.bounds(corner1: Point, corner2: Point)
  897. // Creates a Bounds object from two corners coordinate pairs.
  898. // @alternative
  899. // @factory L.bounds(points: Point[])
  900. // Creates a Bounds object from the given array of points.
  901. function toBounds(a, b) {
  902. if (!a || a instanceof Bounds) {
  903. return a;
  904. }
  905. return new Bounds(a, b);
  906. }
  907. /*
  908. * @class LatLngBounds
  909. * @aka L.LatLngBounds
  910. *
  911. * Represents a rectangular geographical area on a map.
  912. *
  913. * @example
  914. *
  915. * ```js
  916. * var corner1 = L.latLng(40.712, -74.227),
  917. * corner2 = L.latLng(40.774, -74.125),
  918. * bounds = L.latLngBounds(corner1, corner2);
  919. * ```
  920. *
  921. * 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:
  922. *
  923. * ```js
  924. * map.fitBounds([
  925. * [40.712, -74.227],
  926. * [40.774, -74.125]
  927. * ]);
  928. * ```
  929. *
  930. * 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.
  931. *
  932. * Note that `LatLngBounds` does not inherit from Leafet's `Class` object,
  933. * which means new classes can't inherit from it, and new methods
  934. * can't be added to it with the `include` function.
  935. */
  936. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  937. if (!corner1) { return; }
  938. var latlngs = corner2 ? [corner1, corner2] : corner1;
  939. for (var i = 0, len = latlngs.length; i < len; i++) {
  940. this.extend(latlngs[i]);
  941. }
  942. }
  943. LatLngBounds.prototype = {
  944. // @method extend(latlng: LatLng): this
  945. // Extend the bounds to contain the given point
  946. // @alternative
  947. // @method extend(otherBounds: LatLngBounds): this
  948. // Extend the bounds to contain the given bounds
  949. extend: function (obj) {
  950. var sw = this._southWest,
  951. ne = this._northEast,
  952. sw2, ne2;
  953. if (obj instanceof LatLng) {
  954. sw2 = obj;
  955. ne2 = obj;
  956. } else if (obj instanceof LatLngBounds) {
  957. sw2 = obj._southWest;
  958. ne2 = obj._northEast;
  959. if (!sw2 || !ne2) { return this; }
  960. } else {
  961. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  962. }
  963. if (!sw && !ne) {
  964. this._southWest = new LatLng(sw2.lat, sw2.lng);
  965. this._northEast = new LatLng(ne2.lat, ne2.lng);
  966. } else {
  967. sw.lat = Math.min(sw2.lat, sw.lat);
  968. sw.lng = Math.min(sw2.lng, sw.lng);
  969. ne.lat = Math.max(ne2.lat, ne.lat);
  970. ne.lng = Math.max(ne2.lng, ne.lng);
  971. }
  972. return this;
  973. },
  974. // @method pad(bufferRatio: Number): LatLngBounds
  975. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  976. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  977. // Negative values will retract the bounds.
  978. pad: function (bufferRatio) {
  979. var sw = this._southWest,
  980. ne = this._northEast,
  981. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  982. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  983. return new LatLngBounds(
  984. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  985. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  986. },
  987. // @method getCenter(): LatLng
  988. // Returns the center point of the bounds.
  989. getCenter: function () {
  990. return new LatLng(
  991. (this._southWest.lat + this._northEast.lat) / 2,
  992. (this._southWest.lng + this._northEast.lng) / 2);
  993. },
  994. // @method getSouthWest(): LatLng
  995. // Returns the south-west point of the bounds.
  996. getSouthWest: function () {
  997. return this._southWest;
  998. },
  999. // @method getNorthEast(): LatLng
  1000. // Returns the north-east point of the bounds.
  1001. getNorthEast: function () {
  1002. return this._northEast;
  1003. },
  1004. // @method getNorthWest(): LatLng
  1005. // Returns the north-west point of the bounds.
  1006. getNorthWest: function () {
  1007. return new LatLng(this.getNorth(), this.getWest());
  1008. },
  1009. // @method getSouthEast(): LatLng
  1010. // Returns the south-east point of the bounds.
  1011. getSouthEast: function () {
  1012. return new LatLng(this.getSouth(), this.getEast());
  1013. },
  1014. // @method getWest(): Number
  1015. // Returns the west longitude of the bounds
  1016. getWest: function () {
  1017. return this._southWest.lng;
  1018. },
  1019. // @method getSouth(): Number
  1020. // Returns the south latitude of the bounds
  1021. getSouth: function () {
  1022. return this._southWest.lat;
  1023. },
  1024. // @method getEast(): Number
  1025. // Returns the east longitude of the bounds
  1026. getEast: function () {
  1027. return this._northEast.lng;
  1028. },
  1029. // @method getNorth(): Number
  1030. // Returns the north latitude of the bounds
  1031. getNorth: function () {
  1032. return this._northEast.lat;
  1033. },
  1034. // @method contains(otherBounds: LatLngBounds): Boolean
  1035. // Returns `true` if the rectangle contains the given one.
  1036. // @alternative
  1037. // @method contains (latlng: LatLng): Boolean
  1038. // Returns `true` if the rectangle contains the given point.
  1039. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1040. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1041. obj = toLatLng(obj);
  1042. } else {
  1043. obj = toLatLngBounds(obj);
  1044. }
  1045. var sw = this._southWest,
  1046. ne = this._northEast,
  1047. sw2, ne2;
  1048. if (obj instanceof LatLngBounds) {
  1049. sw2 = obj.getSouthWest();
  1050. ne2 = obj.getNorthEast();
  1051. } else {
  1052. sw2 = ne2 = obj;
  1053. }
  1054. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1055. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1056. },
  1057. // @method intersects(otherBounds: LatLngBounds): Boolean
  1058. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1059. intersects: function (bounds) {
  1060. bounds = toLatLngBounds(bounds);
  1061. var sw = this._southWest,
  1062. ne = this._northEast,
  1063. sw2 = bounds.getSouthWest(),
  1064. ne2 = bounds.getNorthEast(),
  1065. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1066. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1067. return latIntersects && lngIntersects;
  1068. },
  1069. // @method overlaps(otherBounds: Bounds): Boolean
  1070. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1071. overlaps: function (bounds) {
  1072. bounds = toLatLngBounds(bounds);
  1073. var sw = this._southWest,
  1074. ne = this._northEast,
  1075. sw2 = bounds.getSouthWest(),
  1076. ne2 = bounds.getNorthEast(),
  1077. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1078. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1079. return latOverlaps && lngOverlaps;
  1080. },
  1081. // @method toBBoxString(): String
  1082. // 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.
  1083. toBBoxString: function () {
  1084. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1085. },
  1086. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1087. // 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.
  1088. equals: function (bounds, maxMargin) {
  1089. if (!bounds) { return false; }
  1090. bounds = toLatLngBounds(bounds);
  1091. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1092. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1093. },
  1094. // @method isValid(): Boolean
  1095. // Returns `true` if the bounds are properly initialized.
  1096. isValid: function () {
  1097. return !!(this._southWest && this._northEast);
  1098. }
  1099. };
  1100. // TODO International date line?
  1101. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1102. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1103. // @alternative
  1104. // @factory L.latLngBounds(latlngs: LatLng[])
  1105. // 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).
  1106. function toLatLngBounds(a, b) {
  1107. if (a instanceof LatLngBounds) {
  1108. return a;
  1109. }
  1110. return new LatLngBounds(a, b);
  1111. }
  1112. /* @class LatLng
  1113. * @aka L.LatLng
  1114. *
  1115. * Represents a geographical point with a certain latitude and longitude.
  1116. *
  1117. * @example
  1118. *
  1119. * ```
  1120. * var latlng = L.latLng(50.5, 30.5);
  1121. * ```
  1122. *
  1123. * 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:
  1124. *
  1125. * ```
  1126. * map.panTo([50, 30]);
  1127. * map.panTo({lon: 30, lat: 50});
  1128. * map.panTo({lat: 50, lng: 30});
  1129. * map.panTo(L.latLng(50, 30));
  1130. * ```
  1131. *
  1132. * Note that `LatLng` does not inherit from Leaflet's `Class` object,
  1133. * which means new classes can't inherit from it, and new methods
  1134. * can't be added to it with the `include` function.
  1135. */
  1136. function LatLng(lat, lng, alt) {
  1137. if (isNaN(lat) || isNaN(lng)) {
  1138. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1139. }
  1140. // @property lat: Number
  1141. // Latitude in degrees
  1142. this.lat = +lat;
  1143. // @property lng: Number
  1144. // Longitude in degrees
  1145. this.lng = +lng;
  1146. // @property alt: Number
  1147. // Altitude in meters (optional)
  1148. if (alt !== undefined) {
  1149. this.alt = +alt;
  1150. }
  1151. }
  1152. LatLng.prototype = {
  1153. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1154. // 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.
  1155. equals: function (obj, maxMargin) {
  1156. if (!obj) { return false; }
  1157. obj = toLatLng(obj);
  1158. var margin = Math.max(
  1159. Math.abs(this.lat - obj.lat),
  1160. Math.abs(this.lng - obj.lng));
  1161. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1162. },
  1163. // @method toString(): String
  1164. // Returns a string representation of the point (for debugging purposes).
  1165. toString: function (precision) {
  1166. return 'LatLng(' +
  1167. formatNum(this.lat, precision) + ', ' +
  1168. formatNum(this.lng, precision) + ')';
  1169. },
  1170. // @method distanceTo(otherLatLng: LatLng): Number
  1171. // 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).
  1172. distanceTo: function (other) {
  1173. return Earth.distance(this, toLatLng(other));
  1174. },
  1175. // @method wrap(): LatLng
  1176. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1177. wrap: function () {
  1178. return Earth.wrapLatLng(this);
  1179. },
  1180. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1181. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1182. toBounds: function (sizeInMeters) {
  1183. var latAccuracy = 180 * sizeInMeters / 40075017,
  1184. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1185. return toLatLngBounds(
  1186. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1187. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1188. },
  1189. clone: function () {
  1190. return new LatLng(this.lat, this.lng, this.alt);
  1191. }
  1192. };
  1193. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1194. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1195. // @alternative
  1196. // @factory L.latLng(coords: Array): LatLng
  1197. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1198. // @alternative
  1199. // @factory L.latLng(coords: Object): LatLng
  1200. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1201. function toLatLng(a, b, c) {
  1202. if (a instanceof LatLng) {
  1203. return a;
  1204. }
  1205. if (isArray(a) && typeof a[0] !== 'object') {
  1206. if (a.length === 3) {
  1207. return new LatLng(a[0], a[1], a[2]);
  1208. }
  1209. if (a.length === 2) {
  1210. return new LatLng(a[0], a[1]);
  1211. }
  1212. return null;
  1213. }
  1214. if (a === undefined || a === null) {
  1215. return a;
  1216. }
  1217. if (typeof a === 'object' && 'lat' in a) {
  1218. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1219. }
  1220. if (b === undefined) {
  1221. return null;
  1222. }
  1223. return new LatLng(a, b, c);
  1224. }
  1225. /*
  1226. * @namespace CRS
  1227. * @crs L.CRS.Base
  1228. * Object that defines coordinate reference systems for projecting
  1229. * geographical points into pixel (screen) coordinates and back (and to
  1230. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1231. * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
  1232. *
  1233. * Leaflet defines the most usual CRSs by default. If you want to use a
  1234. * CRS not defined by default, take a look at the
  1235. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1236. *
  1237. * Note that the CRS instances do not inherit from Leafet's `Class` object,
  1238. * and can't be instantiated. Also, new classes can't inherit from them,
  1239. * and methods can't be added to them with the `include` function.
  1240. */
  1241. var CRS = {
  1242. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1243. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1244. latLngToPoint: function (latlng, zoom) {
  1245. var projectedPoint = this.projection.project(latlng),
  1246. scale = this.scale(zoom);
  1247. return this.transformation._transform(projectedPoint, scale);
  1248. },
  1249. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1250. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1251. // zoom into geographical coordinates.
  1252. pointToLatLng: function (point, zoom) {
  1253. var scale = this.scale(zoom),
  1254. untransformedPoint = this.transformation.untransform(point, scale);
  1255. return this.projection.unproject(untransformedPoint);
  1256. },
  1257. // @method project(latlng: LatLng): Point
  1258. // Projects geographical coordinates into coordinates in units accepted for
  1259. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1260. project: function (latlng) {
  1261. return this.projection.project(latlng);
  1262. },
  1263. // @method unproject(point: Point): LatLng
  1264. // Given a projected coordinate returns the corresponding LatLng.
  1265. // The inverse of `project`.
  1266. unproject: function (point) {
  1267. return this.projection.unproject(point);
  1268. },
  1269. // @method scale(zoom: Number): Number
  1270. // Returns the scale used when transforming projected coordinates into
  1271. // pixel coordinates for a particular zoom. For example, it returns
  1272. // `256 * 2^zoom` for Mercator-based CRS.
  1273. scale: function (zoom) {
  1274. return 256 * Math.pow(2, zoom);
  1275. },
  1276. // @method zoom(scale: Number): Number
  1277. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1278. // factor of `scale`.
  1279. zoom: function (scale) {
  1280. return Math.log(scale / 256) / Math.LN2;
  1281. },
  1282. // @method getProjectedBounds(zoom: Number): Bounds
  1283. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1284. getProjectedBounds: function (zoom) {
  1285. if (this.infinite) { return null; }
  1286. var b = this.projection.bounds,
  1287. s = this.scale(zoom),
  1288. min = this.transformation.transform(b.min, s),
  1289. max = this.transformation.transform(b.max, s);
  1290. return new Bounds(min, max);
  1291. },
  1292. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1293. // Returns the distance between two geographical coordinates.
  1294. // @property code: String
  1295. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1296. //
  1297. // @property wrapLng: Number[]
  1298. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1299. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1300. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1301. //
  1302. // @property wrapLat: Number[]
  1303. // Like `wrapLng`, but for the latitude (vertical) axis.
  1304. // wrapLng: [min, max],
  1305. // wrapLat: [min, max],
  1306. // @property infinite: Boolean
  1307. // If true, the coordinate space will be unbounded (infinite in both axes)
  1308. infinite: false,
  1309. // @method wrapLatLng(latlng: LatLng): LatLng
  1310. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1311. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1312. wrapLatLng: function (latlng) {
  1313. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1314. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1315. alt = latlng.alt;
  1316. return new LatLng(lat, lng, alt);
  1317. },
  1318. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1319. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1320. // that its center is within the CRS's bounds.
  1321. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1322. wrapLatLngBounds: function (bounds) {
  1323. var center = bounds.getCenter(),
  1324. newCenter = this.wrapLatLng(center),
  1325. latShift = center.lat - newCenter.lat,
  1326. lngShift = center.lng - newCenter.lng;
  1327. if (latShift === 0 && lngShift === 0) {
  1328. return bounds;
  1329. }
  1330. var sw = bounds.getSouthWest(),
  1331. ne = bounds.getNorthEast(),
  1332. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1333. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1334. return new LatLngBounds(newSw, newNe);
  1335. }
  1336. };
  1337. /*
  1338. * @namespace CRS
  1339. * @crs L.CRS.Earth
  1340. *
  1341. * Serves as the base for CRS that are global such that they cover the earth.
  1342. * Can only be used as the base for other CRS and cannot be used directly,
  1343. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1344. * meters.
  1345. */
  1346. var Earth = extend({}, CRS, {
  1347. wrapLng: [-180, 180],
  1348. // Mean Earth Radius, as recommended for use by
  1349. // the International Union of Geodesy and Geophysics,
  1350. // see http://rosettacode.org/wiki/Haversine_formula
  1351. R: 6371000,
  1352. // distance between two geographical points using spherical law of cosines approximation
  1353. distance: function (latlng1, latlng2) {
  1354. var rad = Math.PI / 180,
  1355. lat1 = latlng1.lat * rad,
  1356. lat2 = latlng2.lat * rad,
  1357. sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
  1358. sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
  1359. a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
  1360. c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1361. return this.R * c;
  1362. }
  1363. });
  1364. /*
  1365. * @namespace Projection
  1366. * @projection L.Projection.SphericalMercator
  1367. *
  1368. * Spherical Mercator projection — the most common projection for online maps,
  1369. * used by almost all free and commercial tile providers. Assumes that Earth is
  1370. * a sphere. Used by the `EPSG:3857` CRS.
  1371. */
  1372. var earthRadius = 6378137;
  1373. var SphericalMercator = {
  1374. R: earthRadius,
  1375. MAX_LATITUDE: 85.0511287798,
  1376. project: function (latlng) {
  1377. var d = Math.PI / 180,
  1378. max = this.MAX_LATITUDE,
  1379. lat = Math.max(Math.min(max, latlng.lat), -max),
  1380. sin = Math.sin(lat * d);
  1381. return new Point(
  1382. this.R * latlng.lng * d,
  1383. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1384. },
  1385. unproject: function (point) {
  1386. var d = 180 / Math.PI;
  1387. return new LatLng(
  1388. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1389. point.x * d / this.R);
  1390. },
  1391. bounds: (function () {
  1392. var d = earthRadius * Math.PI;
  1393. return new Bounds([-d, -d], [d, d]);
  1394. })()
  1395. };
  1396. /*
  1397. * @class Transformation
  1398. * @aka L.Transformation
  1399. *
  1400. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1401. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1402. * the reverse. Used by Leaflet in its projections code.
  1403. *
  1404. * @example
  1405. *
  1406. * ```js
  1407. * var transformation = L.transformation(2, 5, -1, 10),
  1408. * p = L.point(1, 2),
  1409. * p2 = transformation.transform(p), // L.point(7, 8)
  1410. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1411. * ```
  1412. */
  1413. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1414. // Creates a `Transformation` object with the given coefficients.
  1415. function Transformation(a, b, c, d) {
  1416. if (isArray(a)) {
  1417. // use array properties
  1418. this._a = a[0];
  1419. this._b = a[1];
  1420. this._c = a[2];
  1421. this._d = a[3];
  1422. return;
  1423. }
  1424. this._a = a;
  1425. this._b = b;
  1426. this._c = c;
  1427. this._d = d;
  1428. }
  1429. Transformation.prototype = {
  1430. // @method transform(point: Point, scale?: Number): Point
  1431. // Returns a transformed point, optionally multiplied by the given scale.
  1432. // Only accepts actual `L.Point` instances, not arrays.
  1433. transform: function (point, scale) { // (Point, Number) -> Point
  1434. return this._transform(point.clone(), scale);
  1435. },
  1436. // destructive transform (faster)
  1437. _transform: function (point, scale) {
  1438. scale = scale || 1;
  1439. point.x = scale * (this._a * point.x + this._b);
  1440. point.y = scale * (this._c * point.y + this._d);
  1441. return point;
  1442. },
  1443. // @method untransform(point: Point, scale?: Number): Point
  1444. // Returns the reverse transformation of the given point, optionally divided
  1445. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1446. untransform: function (point, scale) {
  1447. scale = scale || 1;
  1448. return new Point(
  1449. (point.x / scale - this._b) / this._a,
  1450. (point.y / scale - this._d) / this._c);
  1451. }
  1452. };
  1453. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1454. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1455. // Instantiates a Transformation object with the given coefficients.
  1456. // @alternative
  1457. // @factory L.transformation(coefficients: Array): Transformation
  1458. // Expects an coefficients array of the form
  1459. // `[a: Number, b: Number, c: Number, d: Number]`.
  1460. function toTransformation(a, b, c, d) {
  1461. return new Transformation(a, b, c, d);
  1462. }
  1463. /*
  1464. * @namespace CRS
  1465. * @crs L.CRS.EPSG3857
  1466. *
  1467. * The most common CRS for online maps, used by almost all free and commercial
  1468. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1469. * Map's `crs` option.
  1470. */
  1471. var EPSG3857 = extend({}, Earth, {
  1472. code: 'EPSG:3857',
  1473. projection: SphericalMercator,
  1474. transformation: (function () {
  1475. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1476. return toTransformation(scale, 0.5, -scale, 0.5);
  1477. }())
  1478. });
  1479. var EPSG900913 = extend({}, EPSG3857, {
  1480. code: 'EPSG:900913'
  1481. });
  1482. // @namespace SVG; @section
  1483. // There are several static functions which can be called without instantiating L.SVG:
  1484. // @function create(name: String): SVGElement
  1485. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1486. // corresponding to the class name passed. For example, using 'line' will return
  1487. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1488. function svgCreate(name) {
  1489. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1490. }
  1491. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1492. // Generates a SVG path string for multiple rings, with each ring turning
  1493. // into "M..L..L.." instructions
  1494. function pointsToPath(rings, closed) {
  1495. var str = '',
  1496. i, j, len, len2, points, p;
  1497. for (i = 0, len = rings.length; i < len; i++) {
  1498. points = rings[i];
  1499. for (j = 0, len2 = points.length; j < len2; j++) {
  1500. p = points[j];
  1501. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1502. }
  1503. // closes the ring for polygons; "x" is VML syntax
  1504. str += closed ? (svg ? 'z' : 'x') : '';
  1505. }
  1506. // SVG complains about empty path strings
  1507. return str || 'M0 0';
  1508. }
  1509. /*
  1510. * @namespace Browser
  1511. * @aka L.Browser
  1512. *
  1513. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1514. *
  1515. * @example
  1516. *
  1517. * ```js
  1518. * if (L.Browser.ielt9) {
  1519. * alert('Upgrade your browser, dude!');
  1520. * }
  1521. * ```
  1522. */
  1523. var style$1 = document.documentElement.style;
  1524. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1525. var ie = 'ActiveXObject' in window;
  1526. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1527. var ielt9 = ie && !document.addEventListener;
  1528. // @property edge: Boolean; `true` for the Edge web browser.
  1529. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1530. // @property webkit: Boolean;
  1531. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1532. var webkit = userAgentContains('webkit');
  1533. // @property android: Boolean
  1534. // `true` for any browser running on an Android platform.
  1535. var android = userAgentContains('android');
  1536. // @property android23: Boolean; `true` for browsers running on Android 2 or Android 3.
  1537. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1538. /* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */
  1539. var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit
  1540. // @property androidStock: Boolean; `true` for the Android stock browser (i.e. not Chrome)
  1541. var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);
  1542. // @property opera: Boolean; `true` for the Opera browser
  1543. var opera = !!window.opera;
  1544. // @property chrome: Boolean; `true` for the Chrome browser.
  1545. var chrome = userAgentContains('chrome');
  1546. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1547. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1548. // @property safari: Boolean; `true` for the Safari browser.
  1549. var safari = !chrome && userAgentContains('safari');
  1550. var phantom = userAgentContains('phantom');
  1551. // @property opera12: Boolean
  1552. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1553. var opera12 = 'OTransition' in style$1;
  1554. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1555. var win = navigator.platform.indexOf('Win') === 0;
  1556. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1557. var ie3d = ie && ('transition' in style$1);
  1558. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1559. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1560. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1561. var gecko3d = 'MozPerspective' in style$1;
  1562. // @property any3d: Boolean
  1563. // `true` for all browsers supporting CSS transforms.
  1564. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1565. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1566. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1567. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1568. var mobileWebkit = mobile && webkit;
  1569. // @property mobileWebkit3d: Boolean
  1570. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1571. var mobileWebkit3d = mobile && webkit3d;
  1572. // @property msPointer: Boolean
  1573. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1574. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1575. // @property pointer: Boolean
  1576. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1577. var pointer = !webkit && !!(window.PointerEvent || msPointer);
  1578. // @property touch: Boolean
  1579. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1580. // This does not necessarily mean that the browser is running in a computer with
  1581. // a touchscreen, it only means that the browser is capable of understanding
  1582. // touch events.
  1583. var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
  1584. (window.DocumentTouch && document instanceof window.DocumentTouch));
  1585. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1586. var mobileOpera = mobile && opera;
  1587. // @property mobileGecko: Boolean
  1588. // `true` for gecko-based browsers running in a mobile device.
  1589. var mobileGecko = mobile && gecko;
  1590. // @property retina: Boolean
  1591. // `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%.
  1592. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1593. // @property passiveEvents: Boolean
  1594. // `true` for browsers that support passive events.
  1595. var passiveEvents = (function () {
  1596. var supportsPassiveOption = false;
  1597. try {
  1598. var opts = Object.defineProperty({}, 'passive', {
  1599. get: function () {
  1600. supportsPassiveOption = true;
  1601. }
  1602. });
  1603. window.addEventListener('testPassiveEventSupport', falseFn, opts);
  1604. window.removeEventListener('testPassiveEventSupport', falseFn, opts);
  1605. } catch (e) {
  1606. // Errors can safely be ignored since this is only a browser support test.
  1607. }
  1608. return supportsPassiveOption;
  1609. });
  1610. // @property canvas: Boolean
  1611. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1612. var canvas = (function () {
  1613. return !!document.createElement('canvas').getContext;
  1614. }());
  1615. // @property svg: Boolean
  1616. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1617. var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1618. // @property vml: Boolean
  1619. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1620. var vml = !svg && (function () {
  1621. try {
  1622. var div = document.createElement('div');
  1623. div.innerHTML = '<v:shape adj="1"/>';
  1624. var shape = div.firstChild;
  1625. shape.style.behavior = 'url(#default#VML)';
  1626. return shape && (typeof shape.adj === 'object');
  1627. } catch (e) {
  1628. return false;
  1629. }
  1630. }());
  1631. function userAgentContains(str) {
  1632. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1633. }
  1634. var Browser = (Object.freeze || Object)({
  1635. ie: ie,
  1636. ielt9: ielt9,
  1637. edge: edge,
  1638. webkit: webkit,
  1639. android: android,
  1640. android23: android23,
  1641. androidStock: androidStock,
  1642. opera: opera,
  1643. chrome: chrome,
  1644. gecko: gecko,
  1645. safari: safari,
  1646. phantom: phantom,
  1647. opera12: opera12,
  1648. win: win,
  1649. ie3d: ie3d,
  1650. webkit3d: webkit3d,
  1651. gecko3d: gecko3d,
  1652. any3d: any3d,
  1653. mobile: mobile,
  1654. mobileWebkit: mobileWebkit,
  1655. mobileWebkit3d: mobileWebkit3d,
  1656. msPointer: msPointer,
  1657. pointer: pointer,
  1658. touch: touch,
  1659. mobileOpera: mobileOpera,
  1660. mobileGecko: mobileGecko,
  1661. retina: retina,
  1662. passiveEvents: passiveEvents,
  1663. canvas: canvas,
  1664. svg: svg,
  1665. vml: vml
  1666. });
  1667. /*
  1668. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1669. */
  1670. var POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';
  1671. var POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';
  1672. var POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';
  1673. var POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';
  1674. var TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION'];
  1675. var _pointers = {};
  1676. var _pointerDocListener = false;
  1677. // DomEvent.DoubleTap needs to know about this
  1678. var _pointersCount = 0;
  1679. // Provides a touch events wrapper for (ms)pointer events.
  1680. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1681. function addPointerListener(obj, type, handler, id) {
  1682. if (type === 'touchstart') {
  1683. _addPointerStart(obj, handler, id);
  1684. } else if (type === 'touchmove') {
  1685. _addPointerMove(obj, handler, id);
  1686. } else if (type === 'touchend') {
  1687. _addPointerEnd(obj, handler, id);
  1688. }
  1689. return this;
  1690. }
  1691. function removePointerListener(obj, type, id) {
  1692. var handler = obj['_leaflet_' + type + id];
  1693. if (type === 'touchstart') {
  1694. obj.removeEventListener(POINTER_DOWN, handler, false);
  1695. } else if (type === 'touchmove') {
  1696. obj.removeEventListener(POINTER_MOVE, handler, false);
  1697. } else if (type === 'touchend') {
  1698. obj.removeEventListener(POINTER_UP, handler, false);
  1699. obj.removeEventListener(POINTER_CANCEL, handler, false);
  1700. }
  1701. return this;
  1702. }
  1703. function _addPointerStart(obj, handler, id) {
  1704. var onDown = bind(function (e) {
  1705. if (e.pointerType !== 'mouse' && e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
  1706. // In IE11, some touch events needs to fire for form controls, or
  1707. // the controls will stop working. We keep a whitelist of tag names that
  1708. // need these events. For other target tags, we prevent default on the event.
  1709. if (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
  1710. preventDefault(e);
  1711. } else {
  1712. return;
  1713. }
  1714. }
  1715. _handlePointer(e, handler);
  1716. });
  1717. obj['_leaflet_touchstart' + id] = onDown;
  1718. obj.addEventListener(POINTER_DOWN, onDown, false);
  1719. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1720. if (!_pointerDocListener) {
  1721. // we listen documentElement as any drags that end by moving the touch off the screen get fired there
  1722. document.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1723. document.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1724. document.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true);
  1725. document.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1726. _pointerDocListener = true;
  1727. }
  1728. }
  1729. function _globalPointerDown(e) {
  1730. _pointers[e.pointerId] = e;
  1731. _pointersCount++;
  1732. }
  1733. function _globalPointerMove(e) {
  1734. if (_pointers[e.pointerId]) {
  1735. _pointers[e.pointerId] = e;
  1736. }
  1737. }
  1738. function _globalPointerUp(e) {
  1739. delete _pointers[e.pointerId];
  1740. _pointersCount--;
  1741. }
  1742. function _handlePointer(e, handler) {
  1743. e.touches = [];
  1744. for (var i in _pointers) {
  1745. e.touches.push(_pointers[i]);
  1746. }
  1747. e.changedTouches = [e];
  1748. handler(e);
  1749. }
  1750. function _addPointerMove(obj, handler, id) {
  1751. var onMove = function (e) {
  1752. // don't fire touch moves when mouse isn't down
  1753. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
  1754. _handlePointer(e, handler);
  1755. };
  1756. obj['_leaflet_touchmove' + id] = onMove;
  1757. obj.addEventListener(POINTER_MOVE, onMove, false);
  1758. }
  1759. function _addPointerEnd(obj, handler, id) {
  1760. var onUp = function (e) {
  1761. _handlePointer(e, handler);
  1762. };
  1763. obj['_leaflet_touchend' + id] = onUp;
  1764. obj.addEventListener(POINTER_UP, onUp, false);
  1765. obj.addEventListener(POINTER_CANCEL, onUp, false);
  1766. }
  1767. /*
  1768. * Extends the event handling code with double tap support for mobile browsers.
  1769. */
  1770. var _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';
  1771. var _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';
  1772. var _pre = '_leaflet_';
  1773. // inspired by Zepto touch code by Thomas Fuchs
  1774. function addDoubleTapListener(obj, handler, id) {
  1775. var last, touch$$1,
  1776. doubleTap = false,
  1777. delay = 250;
  1778. function onTouchStart(e) {
  1779. var count;
  1780. if (pointer) {
  1781. if ((!edge) || e.pointerType === 'mouse') { return; }
  1782. count = _pointersCount;
  1783. } else {
  1784. count = e.touches.length;
  1785. }
  1786. if (count > 1) { return; }
  1787. var now = Date.now(),
  1788. delta = now - (last || now);
  1789. touch$$1 = e.touches ? e.touches[0] : e;
  1790. doubleTap = (delta > 0 && delta <= delay);
  1791. last = now;
  1792. }
  1793. function onTouchEnd(e) {
  1794. if (doubleTap && !touch$$1.cancelBubble) {
  1795. if (pointer) {
  1796. if ((!edge) || e.pointerType === 'mouse') { return; }
  1797. // work around .type being readonly with MSPointer* events
  1798. var newTouch = {},
  1799. prop, i;
  1800. for (i in touch$$1) {
  1801. prop = touch$$1[i];
  1802. newTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;
  1803. }
  1804. touch$$1 = newTouch;
  1805. }
  1806. touch$$1.type = 'dblclick';
  1807. touch$$1.button = 0;
  1808. handler(touch$$1);
  1809. last = null;
  1810. }
  1811. }
  1812. obj[_pre + _touchstart + id] = onTouchStart;
  1813. obj[_pre + _touchend + id] = onTouchEnd;
  1814. obj[_pre + 'dblclick' + id] = handler;
  1815. obj.addEventListener(_touchstart, onTouchStart, passiveEvents ? {passive: false} : false);
  1816. obj.addEventListener(_touchend, onTouchEnd, passiveEvents ? {passive: false} : false);
  1817. // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
  1818. // the browser doesn't fire touchend/pointerup events but does fire
  1819. // native dblclicks. See #4127.
  1820. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
  1821. obj.addEventListener('dblclick', handler, false);
  1822. return this;
  1823. }
  1824. function removeDoubleTapListener(obj, id) {
  1825. var touchstart = obj[_pre + _touchstart + id],
  1826. touchend = obj[_pre + _touchend + id],
  1827. dblclick = obj[_pre + 'dblclick' + id];
  1828. obj.removeEventListener(_touchstart, touchstart, passiveEvents ? {passive: false} : false);
  1829. obj.removeEventListener(_touchend, touchend, passiveEvents ? {passive: false} : false);
  1830. if (!edge) {
  1831. obj.removeEventListener('dblclick', dblclick, false);
  1832. }
  1833. return this;
  1834. }
  1835. /*
  1836. * @namespace DomUtil
  1837. *
  1838. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1839. * tree, used by Leaflet internally.
  1840. *
  1841. * Most functions expecting or returning a `HTMLElement` also work for
  1842. * SVG elements. The only difference is that classes refer to CSS classes
  1843. * in HTML and SVG classes in SVG.
  1844. */
  1845. // @property TRANSFORM: String
  1846. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  1847. var TRANSFORM = testProp(
  1848. ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1849. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1850. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1851. // @property TRANSITION: String
  1852. // Vendor-prefixed transition style name.
  1853. var TRANSITION = testProp(
  1854. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1855. // @property TRANSITION_END: String
  1856. // Vendor-prefixed transitionend event name.
  1857. var TRANSITION_END =
  1858. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  1859. // @function get(id: String|HTMLElement): HTMLElement
  1860. // Returns an element given its DOM id, or returns the element itself
  1861. // if it was passed directly.
  1862. function get(id) {
  1863. return typeof id === 'string' ? document.getElementById(id) : id;
  1864. }
  1865. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1866. // Returns the value for a certain style attribute on an element,
  1867. // including computed values or values set through CSS.
  1868. function getStyle(el, style) {
  1869. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1870. if ((!value || value === 'auto') && document.defaultView) {
  1871. var css = document.defaultView.getComputedStyle(el, null);
  1872. value = css ? css[style] : null;
  1873. }
  1874. return value === 'auto' ? null : value;
  1875. }
  1876. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1877. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1878. function create$1(tagName, className, container) {
  1879. var el = document.createElement(tagName);
  1880. el.className = className || '';
  1881. if (container) {
  1882. container.appendChild(el);
  1883. }
  1884. return el;
  1885. }
  1886. // @function remove(el: HTMLElement)
  1887. // Removes `el` from its parent element
  1888. function remove(el) {
  1889. var parent = el.parentNode;
  1890. if (parent) {
  1891. parent.removeChild(el);
  1892. }
  1893. }
  1894. // @function empty(el: HTMLElement)
  1895. // Removes all of `el`'s children elements from `el`
  1896. function empty(el) {
  1897. while (el.firstChild) {
  1898. el.removeChild(el.firstChild);
  1899. }
  1900. }
  1901. // @function toFront(el: HTMLElement)
  1902. // Makes `el` the last child of its parent, so it renders in front of the other children.
  1903. function toFront(el) {
  1904. var parent = el.parentNode;
  1905. if (parent && parent.lastChild !== el) {
  1906. parent.appendChild(el);
  1907. }
  1908. }
  1909. // @function toBack(el: HTMLElement)
  1910. // Makes `el` the first child of its parent, so it renders behind the other children.
  1911. function toBack(el) {
  1912. var parent = el.parentNode;
  1913. if (parent && parent.firstChild !== el) {
  1914. parent.insertBefore(el, parent.firstChild);
  1915. }
  1916. }
  1917. // @function hasClass(el: HTMLElement, name: String): Boolean
  1918. // Returns `true` if the element's class attribute contains `name`.
  1919. function hasClass(el, name) {
  1920. if (el.classList !== undefined) {
  1921. return el.classList.contains(name);
  1922. }
  1923. var className = getClass(el);
  1924. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  1925. }
  1926. // @function addClass(el: HTMLElement, name: String)
  1927. // Adds `name` to the element's class attribute.
  1928. function addClass(el, name) {
  1929. if (el.classList !== undefined) {
  1930. var classes = splitWords(name);
  1931. for (var i = 0, len = classes.length; i < len; i++) {
  1932. el.classList.add(classes[i]);
  1933. }
  1934. } else if (!hasClass(el, name)) {
  1935. var className = getClass(el);
  1936. setClass(el, (className ? className + ' ' : '') + name);
  1937. }
  1938. }
  1939. // @function removeClass(el: HTMLElement, name: String)
  1940. // Removes `name` from the element's class attribute.
  1941. function removeClass(el, name) {
  1942. if (el.classList !== undefined) {
  1943. el.classList.remove(name);
  1944. } else {
  1945. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  1946. }
  1947. }
  1948. // @function setClass(el: HTMLElement, name: String)
  1949. // Sets the element's class.
  1950. function setClass(el, name) {
  1951. if (el.className.baseVal === undefined) {
  1952. el.className = name;
  1953. } else {
  1954. // in case of SVG element
  1955. el.className.baseVal = name;
  1956. }
  1957. }
  1958. // @function getClass(el: HTMLElement): String
  1959. // Returns the element's class.
  1960. function getClass(el) {
  1961. // Check if the element is an SVGElementInstance and use the correspondingElement instead
  1962. // (Required for linked SVG elements in IE11.)
  1963. if (el.correspondingElement) {
  1964. el = el.correspondingElement;
  1965. }
  1966. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  1967. }
  1968. // @function setOpacity(el: HTMLElement, opacity: Number)
  1969. // Set the opacity of an element (including old IE support).
  1970. // `opacity` must be a number from `0` to `1`.
  1971. function setOpacity(el, value) {
  1972. if ('opacity' in el.style) {
  1973. el.style.opacity = value;
  1974. } else if ('filter' in el.style) {
  1975. _setOpacityIE(el, value);
  1976. }
  1977. }
  1978. function _setOpacityIE(el, value) {
  1979. var filter = false,
  1980. filterName = 'DXImageTransform.Microsoft.Alpha';
  1981. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  1982. try {
  1983. filter = el.filters.item(filterName);
  1984. } catch (e) {
  1985. // don't set opacity to 1 if we haven't already set an opacity,
  1986. // it isn't needed and breaks transparent pngs.
  1987. if (value === 1) { return; }
  1988. }
  1989. value = Math.round(value * 100);
  1990. if (filter) {
  1991. filter.Enabled = (value !== 100);
  1992. filter.Opacity = value;
  1993. } else {
  1994. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  1995. }
  1996. }
  1997. // @function testProp(props: String[]): String|false
  1998. // Goes through the array of style names and returns the first name
  1999. // that is a valid style name for an element. If no such name is found,
  2000. // it returns false. Useful for vendor-prefixed styles like `transform`.
  2001. function testProp(props) {
  2002. var style = document.documentElement.style;
  2003. for (var i = 0; i < props.length; i++) {
  2004. if (props[i] in style) {
  2005. return props[i];
  2006. }
  2007. }
  2008. return false;
  2009. }
  2010. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  2011. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  2012. // and optionally scaled by `scale`. Does not have an effect if the
  2013. // browser doesn't support 3D CSS transforms.
  2014. function setTransform(el, offset, scale) {
  2015. var pos = offset || new Point(0, 0);
  2016. el.style[TRANSFORM] =
  2017. (ie3d ?
  2018. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2019. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2020. (scale ? ' scale(' + scale + ')' : '');
  2021. }
  2022. // @function setPosition(el: HTMLElement, position: Point)
  2023. // Sets the position of `el` to coordinates specified by `position`,
  2024. // using CSS translate or top/left positioning depending on the browser
  2025. // (used by Leaflet internally to position its layers).
  2026. function setPosition(el, point) {
  2027. /*eslint-disable */
  2028. el._leaflet_pos = point;
  2029. /* eslint-enable */
  2030. if (any3d) {
  2031. setTransform(el, point);
  2032. } else {
  2033. el.style.left = point.x + 'px';
  2034. el.style.top = point.y + 'px';
  2035. }
  2036. }
  2037. // @function getPosition(el: HTMLElement): Point
  2038. // Returns the coordinates of an element previously positioned with setPosition.
  2039. function getPosition(el) {
  2040. // this method is only used for elements previously positioned using setPosition,
  2041. // so it's safe to cache the position for performance
  2042. return el._leaflet_pos || new Point(0, 0);
  2043. }
  2044. // @function disableTextSelection()
  2045. // Prevents the user from generating `selectstart` DOM events, usually generated
  2046. // when the user drags the mouse through a page with text. Used internally
  2047. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2048. // the map. Affects drag interactions on the whole document.
  2049. // @function enableTextSelection()
  2050. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2051. var disableTextSelection;
  2052. var enableTextSelection;
  2053. var _userSelect;
  2054. if ('onselectstart' in document) {
  2055. disableTextSelection = function () {
  2056. on(window, 'selectstart', preventDefault);
  2057. };
  2058. enableTextSelection = function () {
  2059. off(window, 'selectstart', preventDefault);
  2060. };
  2061. } else {
  2062. var userSelectProperty = testProp(
  2063. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2064. disableTextSelection = function () {
  2065. if (userSelectProperty) {
  2066. var style = document.documentElement.style;
  2067. _userSelect = style[userSelectProperty];
  2068. style[userSelectProperty] = 'none';
  2069. }
  2070. };
  2071. enableTextSelection = function () {
  2072. if (userSelectProperty) {
  2073. document.documentElement.style[userSelectProperty] = _userSelect;
  2074. _userSelect = undefined;
  2075. }
  2076. };
  2077. }
  2078. // @function disableImageDrag()
  2079. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2080. // for `dragstart` DOM events, usually generated when the user drags an image.
  2081. function disableImageDrag() {
  2082. on(window, 'dragstart', preventDefault);
  2083. }
  2084. // @function enableImageDrag()
  2085. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2086. function enableImageDrag() {
  2087. off(window, 'dragstart', preventDefault);
  2088. }
  2089. var _outlineElement;
  2090. var _outlineStyle;
  2091. // @function preventOutline(el: HTMLElement)
  2092. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2093. // of the element `el` invisible. Used internally by Leaflet to prevent
  2094. // focusable elements from displaying an outline when the user performs a
  2095. // drag interaction on them.
  2096. function preventOutline(element) {
  2097. while (element.tabIndex === -1) {
  2098. element = element.parentNode;
  2099. }
  2100. if (!element.style) { return; }
  2101. restoreOutline();
  2102. _outlineElement = element;
  2103. _outlineStyle = element.style.outline;
  2104. element.style.outline = 'none';
  2105. on(window, 'keydown', restoreOutline);
  2106. }
  2107. // @function restoreOutline()
  2108. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2109. function restoreOutline() {
  2110. if (!_outlineElement) { return; }
  2111. _outlineElement.style.outline = _outlineStyle;
  2112. _outlineElement = undefined;
  2113. _outlineStyle = undefined;
  2114. off(window, 'keydown', restoreOutline);
  2115. }
  2116. // @function getSizedParentNode(el: HTMLElement): HTMLElement
  2117. // Finds the closest parent node which size (width and height) is not null.
  2118. function getSizedParentNode(element) {
  2119. do {
  2120. element = element.parentNode;
  2121. } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);
  2122. return element;
  2123. }
  2124. // @function getScale(el: HTMLElement): Object
  2125. // Computes the CSS scale currently applied on the element.
  2126. // Returns an object with `x` and `y` members as horizontal and vertical scales respectively,
  2127. // and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2128. function getScale(element) {
  2129. var rect = element.getBoundingClientRect(); // Read-only in old browsers.
  2130. return {
  2131. x: rect.width / element.offsetWidth || 1,
  2132. y: rect.height / element.offsetHeight || 1,
  2133. boundingClientRect: rect
  2134. };
  2135. }
  2136. var DomUtil = (Object.freeze || Object)({
  2137. TRANSFORM: TRANSFORM,
  2138. TRANSITION: TRANSITION,
  2139. TRANSITION_END: TRANSITION_END,
  2140. get: get,
  2141. getStyle: getStyle,
  2142. create: create$1,
  2143. remove: remove,
  2144. empty: empty,
  2145. toFront: toFront,
  2146. toBack: toBack,
  2147. hasClass: hasClass,
  2148. addClass: addClass,
  2149. removeClass: removeClass,
  2150. setClass: setClass,
  2151. getClass: getClass,
  2152. setOpacity: setOpacity,
  2153. testProp: testProp,
  2154. setTransform: setTransform,
  2155. setPosition: setPosition,
  2156. getPosition: getPosition,
  2157. disableTextSelection: disableTextSelection,
  2158. enableTextSelection: enableTextSelection,
  2159. disableImageDrag: disableImageDrag,
  2160. enableImageDrag: enableImageDrag,
  2161. preventOutline: preventOutline,
  2162. restoreOutline: restoreOutline,
  2163. getSizedParentNode: getSizedParentNode,
  2164. getScale: getScale
  2165. });
  2166. /*
  2167. * @namespace DomEvent
  2168. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  2169. */
  2170. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  2171. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2172. // Adds a listener function (`fn`) to a particular DOM event type of the
  2173. // element `el`. You can optionally specify the context of the listener
  2174. // (object the `this` keyword will point to). You can also pass several
  2175. // space-separated types (e.g. `'click dblclick'`).
  2176. // @alternative
  2177. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  2178. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2179. function on(obj, types, fn, context) {
  2180. if (typeof types === 'object') {
  2181. for (var type in types) {
  2182. addOne(obj, type, types[type], fn);
  2183. }
  2184. } else {
  2185. types = splitWords(types);
  2186. for (var i = 0, len = types.length; i < len; i++) {
  2187. addOne(obj, types[i], fn, context);
  2188. }
  2189. }
  2190. return this;
  2191. }
  2192. var eventsKey = '_leaflet_events';
  2193. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2194. // Removes a previously added listener function.
  2195. // Note that if you passed a custom context to on, you must pass the same
  2196. // context to `off` in order to remove the listener.
  2197. // @alternative
  2198. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  2199. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2200. function off(obj, types, fn, context) {
  2201. if (typeof types === 'object') {
  2202. for (var type in types) {
  2203. removeOne(obj, type, types[type], fn);
  2204. }
  2205. } else if (types) {
  2206. types = splitWords(types);
  2207. for (var i = 0, len = types.length; i < len; i++) {
  2208. removeOne(obj, types[i], fn, context);
  2209. }
  2210. } else {
  2211. for (var j in obj[eventsKey]) {
  2212. removeOne(obj, j, obj[eventsKey][j]);
  2213. }
  2214. delete obj[eventsKey];
  2215. }
  2216. return this;
  2217. }
  2218. function addOne(obj, type, fn, context) {
  2219. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2220. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  2221. var handler = function (e) {
  2222. return fn.call(context || obj, e || window.event);
  2223. };
  2224. var originalHandler = handler;
  2225. if (pointer && type.indexOf('touch') === 0) {
  2226. // Needs DomEvent.Pointer.js
  2227. addPointerListener(obj, type, handler, id);
  2228. } else if (touch && (type === 'dblclick') && addDoubleTapListener &&
  2229. !(pointer && chrome)) {
  2230. // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener
  2231. // See #5180
  2232. addDoubleTapListener(obj, handler, id);
  2233. } else if ('addEventListener' in obj) {
  2234. if (type === 'mousewheel') {
  2235. obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, passiveEvents ? {passive: false} : false);
  2236. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  2237. handler = function (e) {
  2238. e = e || window.event;
  2239. if (isExternalTarget(obj, e)) {
  2240. originalHandler(e);
  2241. }
  2242. };
  2243. obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
  2244. } else {
  2245. if (type === 'click' && android) {
  2246. handler = function (e) {
  2247. filterClick(e, originalHandler);
  2248. };
  2249. }
  2250. obj.addEventListener(type, handler, false);
  2251. }
  2252. } else if ('attachEvent' in obj) {
  2253. obj.attachEvent('on' + type, handler);
  2254. }
  2255. obj[eventsKey] = obj[eventsKey] || {};
  2256. obj[eventsKey][id] = handler;
  2257. }
  2258. function removeOne(obj, type, fn, context) {
  2259. var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),
  2260. handler = obj[eventsKey] && obj[eventsKey][id];
  2261. if (!handler) { return this; }
  2262. if (pointer && type.indexOf('touch') === 0) {
  2263. removePointerListener(obj, type, id);
  2264. } else if (touch && (type === 'dblclick') && removeDoubleTapListener &&
  2265. !(pointer && chrome)) {
  2266. removeDoubleTapListener(obj, id);
  2267. } else if ('removeEventListener' in obj) {
  2268. if (type === 'mousewheel') {
  2269. obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, passiveEvents ? {passive: false} : false);
  2270. } else {
  2271. obj.removeEventListener(
  2272. type === 'mouseenter' ? 'mouseover' :
  2273. type === 'mouseleave' ? 'mouseout' : type, handler, false);
  2274. }
  2275. } else if ('detachEvent' in obj) {
  2276. obj.detachEvent('on' + type, handler);
  2277. }
  2278. obj[eventsKey][id] = null;
  2279. }
  2280. // @function stopPropagation(ev: DOMEvent): this
  2281. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  2282. // ```js
  2283. // L.DomEvent.on(div, 'click', function (ev) {
  2284. // L.DomEvent.stopPropagation(ev);
  2285. // });
  2286. // ```
  2287. function stopPropagation(e) {
  2288. if (e.stopPropagation) {
  2289. e.stopPropagation();
  2290. } else if (e.originalEvent) { // In case of Leaflet event.
  2291. e.originalEvent._stopped = true;
  2292. } else {
  2293. e.cancelBubble = true;
  2294. }
  2295. skipped(e);
  2296. return this;
  2297. }
  2298. // @function disableScrollPropagation(el: HTMLElement): this
  2299. // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
  2300. function disableScrollPropagation(el) {
  2301. addOne(el, 'mousewheel', stopPropagation);
  2302. return this;
  2303. }
  2304. // @function disableClickPropagation(el: HTMLElement): this
  2305. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  2306. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  2307. function disableClickPropagation(el) {
  2308. on(el, 'mousedown touchstart dblclick', stopPropagation);
  2309. addOne(el, 'click', fakeStop);
  2310. return this;
  2311. }
  2312. // @function preventDefault(ev: DOMEvent): this
  2313. // Prevents the default action of the DOM Event `ev` from happening (such as
  2314. // following a link in the href of the a element, or doing a POST request
  2315. // with page reload when a `<form>` is submitted).
  2316. // Use it inside listener functions.
  2317. function preventDefault(e) {
  2318. if (e.preventDefault) {
  2319. e.preventDefault();
  2320. } else {
  2321. e.returnValue = false;
  2322. }
  2323. return this;
  2324. }
  2325. // @function stop(ev: DOMEvent): this
  2326. // Does `stopPropagation` and `preventDefault` at the same time.
  2327. function stop(e) {
  2328. preventDefault(e);
  2329. stopPropagation(e);
  2330. return this;
  2331. }
  2332. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  2333. // Gets normalized mouse position from a DOM event relative to the
  2334. // `container` (border excluded) or to the whole page if not specified.
  2335. function getMousePosition(e, container) {
  2336. if (!container) {
  2337. return new Point(e.clientX, e.clientY);
  2338. }
  2339. var scale = getScale(container),
  2340. offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)
  2341. return new Point(
  2342. // offset.left/top values are in page scale (like clientX/Y),
  2343. // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
  2344. (e.clientX - offset.left) / scale.x - container.clientLeft,
  2345. (e.clientY - offset.top) / scale.y - container.clientTop
  2346. );
  2347. }
  2348. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  2349. // and Firefox scrolls device pixels, not CSS pixels
  2350. var wheelPxFactor =
  2351. (win && chrome) ? 2 * window.devicePixelRatio :
  2352. gecko ? window.devicePixelRatio : 1;
  2353. // @function getWheelDelta(ev: DOMEvent): Number
  2354. // Gets normalized wheel delta from a mousewheel DOM event, in vertical
  2355. // pixels scrolled (negative if scrolling down).
  2356. // Events from pointing devices without precise scrolling are mapped to
  2357. // a best guess of 60 pixels.
  2358. function getWheelDelta(e) {
  2359. return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2360. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2361. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2362. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2363. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2364. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2365. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2366. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2367. 0;
  2368. }
  2369. var skipEvents = {};
  2370. function fakeStop(e) {
  2371. // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)
  2372. skipEvents[e.type] = true;
  2373. }
  2374. function skipped(e) {
  2375. var events = skipEvents[e.type];
  2376. // reset when checking, as it's only used in map container and propagates outside of the map
  2377. skipEvents[e.type] = false;
  2378. return events;
  2379. }
  2380. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2381. function isExternalTarget(el, e) {
  2382. var related = e.relatedTarget;
  2383. if (!related) { return true; }
  2384. try {
  2385. while (related && (related !== el)) {
  2386. related = related.parentNode;
  2387. }
  2388. } catch (err) {
  2389. return false;
  2390. }
  2391. return (related !== el);
  2392. }
  2393. var lastClick;
  2394. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  2395. function filterClick(e, handler) {
  2396. var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
  2397. elapsed = lastClick && (timeStamp - lastClick);
  2398. // are they closer together than 500ms yet more than 100ms?
  2399. // Android typically triggers them ~300ms apart while multiple listeners
  2400. // on the same event should be triggered far faster;
  2401. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  2402. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  2403. stop(e);
  2404. return;
  2405. }
  2406. lastClick = timeStamp;
  2407. handler(e);
  2408. }
  2409. var DomEvent = (Object.freeze || Object)({
  2410. on: on,
  2411. off: off,
  2412. stopPropagation: stopPropagation,
  2413. disableScrollPropagation: disableScrollPropagation,
  2414. disableClickPropagation: disableClickPropagation,
  2415. preventDefault: preventDefault,
  2416. stop: stop,
  2417. getMousePosition: getMousePosition,
  2418. getWheelDelta: getWheelDelta,
  2419. fakeStop: fakeStop,
  2420. skipped: skipped,
  2421. isExternalTarget: isExternalTarget,
  2422. addListener: on,
  2423. removeListener: off
  2424. });
  2425. /*
  2426. * @class PosAnimation
  2427. * @aka L.PosAnimation
  2428. * @inherits Evented
  2429. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2430. *
  2431. * @example
  2432. * ```js
  2433. * var fx = new L.PosAnimation();
  2434. * fx.run(el, [300, 500], 0.5);
  2435. * ```
  2436. *
  2437. * @constructor L.PosAnimation()
  2438. * Creates a `PosAnimation` object.
  2439. *
  2440. */
  2441. var PosAnimation = Evented.extend({
  2442. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2443. // Run an animation of a given element to a new position, optionally setting
  2444. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2445. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  2446. // `0.5` by default).
  2447. run: function (el, newPos, duration, easeLinearity) {
  2448. this.stop();
  2449. this._el = el;
  2450. this._inProgress = true;
  2451. this._duration = duration || 0.25;
  2452. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2453. this._startPos = getPosition(el);
  2454. this._offset = newPos.subtract(this._startPos);
  2455. this._startTime = +new Date();
  2456. // @event start: Event
  2457. // Fired when the animation starts
  2458. this.fire('start');
  2459. this._animate();
  2460. },
  2461. // @method stop()
  2462. // Stops the animation (if currently running).
  2463. stop: function () {
  2464. if (!this._inProgress) { return; }
  2465. this._step(true);
  2466. this._complete();
  2467. },
  2468. _animate: function () {
  2469. // animation loop
  2470. this._animId = requestAnimFrame(this._animate, this);
  2471. this._step();
  2472. },
  2473. _step: function (round) {
  2474. var elapsed = (+new Date()) - this._startTime,
  2475. duration = this._duration * 1000;
  2476. if (elapsed < duration) {
  2477. this._runFrame(this._easeOut(elapsed / duration), round);
  2478. } else {
  2479. this._runFrame(1);
  2480. this._complete();
  2481. }
  2482. },
  2483. _runFrame: function (progress, round) {
  2484. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2485. if (round) {
  2486. pos._round();
  2487. }
  2488. setPosition(this._el, pos);
  2489. // @event step: Event
  2490. // Fired continuously during the animation.
  2491. this.fire('step');
  2492. },
  2493. _complete: function () {
  2494. cancelAnimFrame(this._animId);
  2495. this._inProgress = false;
  2496. // @event end: Event
  2497. // Fired when the animation ends.
  2498. this.fire('end');
  2499. },
  2500. _easeOut: function (t) {
  2501. return 1 - Math.pow(1 - t, this._easeOutPower);
  2502. }
  2503. });
  2504. /*
  2505. * @class Map
  2506. * @aka L.Map
  2507. * @inherits Evented
  2508. *
  2509. * The central class of the API — it is used to create a map on a page and manipulate it.
  2510. *
  2511. * @example
  2512. *
  2513. * ```js
  2514. * // initialize the map on the "map" div with a given center and zoom
  2515. * var map = L.map('map', {
  2516. * center: [51.505, -0.09],
  2517. * zoom: 13
  2518. * });
  2519. * ```
  2520. *
  2521. */
  2522. var Map = Evented.extend({
  2523. options: {
  2524. // @section Map State Options
  2525. // @option crs: CRS = L.CRS.EPSG3857
  2526. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2527. // sure what it means.
  2528. crs: EPSG3857,
  2529. // @option center: LatLng = undefined
  2530. // Initial geographic center of the map
  2531. center: undefined,
  2532. // @option zoom: Number = undefined
  2533. // Initial map zoom level
  2534. zoom: undefined,
  2535. // @option minZoom: Number = *
  2536. // Minimum zoom level of the map.
  2537. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2538. // the lowest of their `minZoom` options will be used instead.
  2539. minZoom: undefined,
  2540. // @option maxZoom: Number = *
  2541. // Maximum zoom level of the map.
  2542. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2543. // the highest of their `maxZoom` options will be used instead.
  2544. maxZoom: undefined,
  2545. // @option layers: Layer[] = []
  2546. // Array of layers that will be added to the map initially
  2547. layers: [],
  2548. // @option maxBounds: LatLngBounds = null
  2549. // When this option is set, the map restricts the view to the given
  2550. // geographical bounds, bouncing the user back if the user tries to pan
  2551. // outside the view. To set the restriction dynamically, use
  2552. // [`setMaxBounds`](#map-setmaxbounds) method.
  2553. maxBounds: undefined,
  2554. // @option renderer: Renderer = *
  2555. // The default method for drawing vector layers on the map. `L.SVG`
  2556. // or `L.Canvas` by default depending on browser support.
  2557. renderer: undefined,
  2558. // @section Animation Options
  2559. // @option zoomAnimation: Boolean = true
  2560. // Whether the map zoom animation is enabled. By default it's enabled
  2561. // in all browsers that support CSS3 Transitions except Android.
  2562. zoomAnimation: true,
  2563. // @option zoomAnimationThreshold: Number = 4
  2564. // Won't animate zoom if the zoom difference exceeds this value.
  2565. zoomAnimationThreshold: 4,
  2566. // @option fadeAnimation: Boolean = true
  2567. // Whether the tile fade animation is enabled. By default it's enabled
  2568. // in all browsers that support CSS3 Transitions except Android.
  2569. fadeAnimation: true,
  2570. // @option markerZoomAnimation: Boolean = true
  2571. // Whether markers animate their zoom with the zoom animation, if disabled
  2572. // they will disappear for the length of the animation. By default it's
  2573. // enabled in all browsers that support CSS3 Transitions except Android.
  2574. markerZoomAnimation: true,
  2575. // @option transform3DLimit: Number = 2^23
  2576. // Defines the maximum size of a CSS translation transform. The default
  2577. // value should not be changed unless a web browser positions layers in
  2578. // the wrong place after doing a large `panBy`.
  2579. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2580. // @section Interaction Options
  2581. // @option zoomSnap: Number = 1
  2582. // Forces the map's zoom level to always be a multiple of this, particularly
  2583. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2584. // By default, the zoom level snaps to the nearest integer; lower values
  2585. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2586. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2587. zoomSnap: 1,
  2588. // @option zoomDelta: Number = 1
  2589. // Controls how much the map's zoom level will change after a
  2590. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2591. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2592. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2593. zoomDelta: 1,
  2594. // @option trackResize: Boolean = true
  2595. // Whether the map automatically handles browser window resize to update itself.
  2596. trackResize: true
  2597. },
  2598. initialize: function (id, options) { // (HTMLElement or String, Object)
  2599. options = setOptions(this, options);
  2600. // Make sure to assign internal flags at the beginning,
  2601. // to avoid inconsistent state in some edge cases.
  2602. this._handlers = [];
  2603. this._layers = {};
  2604. this._zoomBoundLayers = {};
  2605. this._sizeChanged = true;
  2606. this._initContainer(id);
  2607. this._initLayout();
  2608. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2609. this._onResize = bind(this._onResize, this);
  2610. this._initEvents();
  2611. if (options.maxBounds) {
  2612. this.setMaxBounds(options.maxBounds);
  2613. }
  2614. if (options.zoom !== undefined) {
  2615. this._zoom = this._limitZoom(options.zoom);
  2616. }
  2617. if (options.center && options.zoom !== undefined) {
  2618. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2619. }
  2620. this.callInitHooks();
  2621. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2622. this._zoomAnimated = TRANSITION && any3d && !mobileOpera &&
  2623. this.options.zoomAnimation;
  2624. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2625. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2626. if (this._zoomAnimated) {
  2627. this._createAnimProxy();
  2628. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2629. }
  2630. this._addLayers(this.options.layers);
  2631. },
  2632. // @section Methods for modifying map state
  2633. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2634. // Sets the view of the map (geographical center and zoom) with the given
  2635. // animation options.
  2636. setView: function (center, zoom, options) {
  2637. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2638. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2639. options = options || {};
  2640. this._stop();
  2641. if (this._loaded && !options.reset && options !== true) {
  2642. if (options.animate !== undefined) {
  2643. options.zoom = extend({animate: options.animate}, options.zoom);
  2644. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2645. }
  2646. // try animating pan or zoom
  2647. var moved = (this._zoom !== zoom) ?
  2648. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2649. this._tryAnimatedPan(center, options.pan);
  2650. if (moved) {
  2651. // prevent resize handler call, the view will refresh after animation anyway
  2652. clearTimeout(this._sizeTimer);
  2653. return this;
  2654. }
  2655. }
  2656. // animation didn't start, just reset the map view
  2657. this._resetView(center, zoom);
  2658. return this;
  2659. },
  2660. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2661. // Sets the zoom of the map.
  2662. setZoom: function (zoom, options) {
  2663. if (!this._loaded) {
  2664. this._zoom = zoom;
  2665. return this;
  2666. }
  2667. return this.setView(this.getCenter(), zoom, {zoom: options});
  2668. },
  2669. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2670. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2671. zoomIn: function (delta, options) {
  2672. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2673. return this.setZoom(this._zoom + delta, options);
  2674. },
  2675. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2676. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2677. zoomOut: function (delta, options) {
  2678. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2679. return this.setZoom(this._zoom - delta, options);
  2680. },
  2681. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2682. // Zooms the map while keeping a specified geographical point on the map
  2683. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2684. // @alternative
  2685. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2686. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2687. setZoomAround: function (latlng, zoom, options) {
  2688. var scale = this.getZoomScale(zoom),
  2689. viewHalf = this.getSize().divideBy(2),
  2690. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2691. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2692. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2693. return this.setView(newCenter, zoom, {zoom: options});
  2694. },
  2695. _getBoundsCenterZoom: function (bounds, options) {
  2696. options = options || {};
  2697. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2698. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2699. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2700. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2701. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2702. if (zoom === Infinity) {
  2703. return {
  2704. center: bounds.getCenter(),
  2705. zoom: zoom
  2706. };
  2707. }
  2708. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2709. swPoint = this.project(bounds.getSouthWest(), zoom),
  2710. nePoint = this.project(bounds.getNorthEast(), zoom),
  2711. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2712. return {
  2713. center: center,
  2714. zoom: zoom
  2715. };
  2716. },
  2717. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2718. // Sets a map view that contains the given geographical bounds with the
  2719. // maximum zoom level possible.
  2720. fitBounds: function (bounds, options) {
  2721. bounds = toLatLngBounds(bounds);
  2722. if (!bounds.isValid()) {
  2723. throw new Error('Bounds are not valid.');
  2724. }
  2725. var target = this._getBoundsCenterZoom(bounds, options);
  2726. return this.setView(target.center, target.zoom, options);
  2727. },
  2728. // @method fitWorld(options?: fitBounds options): this
  2729. // Sets a map view that mostly contains the whole world with the maximum
  2730. // zoom level possible.
  2731. fitWorld: function (options) {
  2732. return this.fitBounds([[-90, -180], [90, 180]], options);
  2733. },
  2734. // @method panTo(latlng: LatLng, options?: Pan options): this
  2735. // Pans the map to a given center.
  2736. panTo: function (center, options) { // (LatLng)
  2737. return this.setView(center, this._zoom, {pan: options});
  2738. },
  2739. // @method panBy(offset: Point, options?: Pan options): this
  2740. // Pans the map by a given number of pixels (animated).
  2741. panBy: function (offset, options) {
  2742. offset = toPoint(offset).round();
  2743. options = options || {};
  2744. if (!offset.x && !offset.y) {
  2745. return this.fire('moveend');
  2746. }
  2747. // If we pan too far, Chrome gets issues with tiles
  2748. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2749. if (options.animate !== true && !this.getSize().contains(offset)) {
  2750. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2751. return this;
  2752. }
  2753. if (!this._panAnim) {
  2754. this._panAnim = new PosAnimation();
  2755. this._panAnim.on({
  2756. 'step': this._onPanTransitionStep,
  2757. 'end': this._onPanTransitionEnd
  2758. }, this);
  2759. }
  2760. // don't fire movestart if animating inertia
  2761. if (!options.noMoveStart) {
  2762. this.fire('movestart');
  2763. }
  2764. // animate pan unless animate: false specified
  2765. if (options.animate !== false) {
  2766. addClass(this._mapPane, 'leaflet-pan-anim');
  2767. var newPos = this._getMapPanePos().subtract(offset).round();
  2768. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2769. } else {
  2770. this._rawPanBy(offset);
  2771. this.fire('move').fire('moveend');
  2772. }
  2773. return this;
  2774. },
  2775. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2776. // Sets the view of the map (geographical center and zoom) performing a smooth
  2777. // pan-zoom animation.
  2778. flyTo: function (targetCenter, targetZoom, options) {
  2779. options = options || {};
  2780. if (options.animate === false || !any3d) {
  2781. return this.setView(targetCenter, targetZoom, options);
  2782. }
  2783. this._stop();
  2784. var from = this.project(this.getCenter()),
  2785. to = this.project(targetCenter),
  2786. size = this.getSize(),
  2787. startZoom = this._zoom;
  2788. targetCenter = toLatLng(targetCenter);
  2789. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2790. var w0 = Math.max(size.x, size.y),
  2791. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2792. u1 = (to.distanceTo(from)) || 1,
  2793. rho = 1.42,
  2794. rho2 = rho * rho;
  2795. function r(i) {
  2796. var s1 = i ? -1 : 1,
  2797. s2 = i ? w1 : w0,
  2798. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2799. b1 = 2 * s2 * rho2 * u1,
  2800. b = t1 / b1,
  2801. sq = Math.sqrt(b * b + 1) - b;
  2802. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2803. // thus triggering an infinite loop in flyTo
  2804. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2805. return log;
  2806. }
  2807. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2808. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2809. function tanh(n) { return sinh(n) / cosh(n); }
  2810. var r0 = r(0);
  2811. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2812. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2813. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2814. var start = Date.now(),
  2815. S = (r(1) - r0) / rho,
  2816. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2817. function frame() {
  2818. var t = (Date.now() - start) / duration,
  2819. s = easeOut(t) * S;
  2820. if (t <= 1) {
  2821. this._flyToFrame = requestAnimFrame(frame, this);
  2822. this._move(
  2823. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2824. this.getScaleZoom(w0 / w(s), startZoom),
  2825. {flyTo: true});
  2826. } else {
  2827. this
  2828. ._move(targetCenter, targetZoom)
  2829. ._moveEnd(true);
  2830. }
  2831. }
  2832. this._moveStart(true, options.noMoveStart);
  2833. frame.call(this);
  2834. return this;
  2835. },
  2836. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2837. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2838. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2839. flyToBounds: function (bounds, options) {
  2840. var target = this._getBoundsCenterZoom(bounds, options);
  2841. return this.flyTo(target.center, target.zoom, options);
  2842. },
  2843. // @method setMaxBounds(bounds: Bounds): this
  2844. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2845. setMaxBounds: function (bounds) {
  2846. bounds = toLatLngBounds(bounds);
  2847. if (!bounds.isValid()) {
  2848. this.options.maxBounds = null;
  2849. return this.off('moveend', this._panInsideMaxBounds);
  2850. } else if (this.options.maxBounds) {
  2851. this.off('moveend', this._panInsideMaxBounds);
  2852. }
  2853. this.options.maxBounds = bounds;
  2854. if (this._loaded) {
  2855. this._panInsideMaxBounds();
  2856. }
  2857. return this.on('moveend', this._panInsideMaxBounds);
  2858. },
  2859. // @method setMinZoom(zoom: Number): this
  2860. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2861. setMinZoom: function (zoom) {
  2862. var oldZoom = this.options.minZoom;
  2863. this.options.minZoom = zoom;
  2864. if (this._loaded && oldZoom !== zoom) {
  2865. this.fire('zoomlevelschange');
  2866. if (this.getZoom() < this.options.minZoom) {
  2867. return this.setZoom(zoom);
  2868. }
  2869. }
  2870. return this;
  2871. },
  2872. // @method setMaxZoom(zoom: Number): this
  2873. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2874. setMaxZoom: function (zoom) {
  2875. var oldZoom = this.options.maxZoom;
  2876. this.options.maxZoom = zoom;
  2877. if (this._loaded && oldZoom !== zoom) {
  2878. this.fire('zoomlevelschange');
  2879. if (this.getZoom() > this.options.maxZoom) {
  2880. return this.setZoom(zoom);
  2881. }
  2882. }
  2883. return this;
  2884. },
  2885. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2886. // 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.
  2887. panInsideBounds: function (bounds, options) {
  2888. this._enforcingBounds = true;
  2889. var center = this.getCenter(),
  2890. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2891. if (!center.equals(newCenter)) {
  2892. this.panTo(newCenter, options);
  2893. }
  2894. this._enforcingBounds = false;
  2895. return this;
  2896. },
  2897. // @method panInside(latlng: LatLng, options?: options): this
  2898. // Pans the map the minimum amount to make the `latlng` visible. Use
  2899. // `padding`, `paddingTopLeft` and `paddingTopRight` options to fit
  2900. // the display to more restricted bounds, like [`fitBounds`](#map-fitbounds).
  2901. // If `latlng` is already within the (optionally padded) display bounds,
  2902. // the map will not be panned.
  2903. panInside: function (latlng, options) {
  2904. options = options || {};
  2905. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2906. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2907. center = this.getCenter(),
  2908. pixelCenter = this.project(center),
  2909. pixelPoint = this.project(latlng),
  2910. pixelBounds = this.getPixelBounds(),
  2911. halfPixelBounds = pixelBounds.getSize().divideBy(2),
  2912. paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]);
  2913. if (!paddedBounds.contains(pixelPoint)) {
  2914. this._enforcingBounds = true;
  2915. var diff = pixelCenter.subtract(pixelPoint),
  2916. newCenter = toPoint(pixelPoint.x + diff.x, pixelPoint.y + diff.y);
  2917. if (pixelPoint.x < paddedBounds.min.x || pixelPoint.x > paddedBounds.max.x) {
  2918. newCenter.x = pixelCenter.x - diff.x;
  2919. if (diff.x > 0) {
  2920. newCenter.x += halfPixelBounds.x - paddingTL.x;
  2921. } else {
  2922. newCenter.x -= halfPixelBounds.x - paddingBR.x;
  2923. }
  2924. }
  2925. if (pixelPoint.y < paddedBounds.min.y || pixelPoint.y > paddedBounds.max.y) {
  2926. newCenter.y = pixelCenter.y - diff.y;
  2927. if (diff.y > 0) {
  2928. newCenter.y += halfPixelBounds.y - paddingTL.y;
  2929. } else {
  2930. newCenter.y -= halfPixelBounds.y - paddingBR.y;
  2931. }
  2932. }
  2933. this.panTo(this.unproject(newCenter), options);
  2934. this._enforcingBounds = false;
  2935. }
  2936. return this;
  2937. },
  2938. // @method invalidateSize(options: Zoom/pan options): this
  2939. // Checks if the map container size changed and updates the map if so —
  2940. // call it after you've changed the map size dynamically, also animating
  2941. // pan by default. If `options.pan` is `false`, panning will not occur.
  2942. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2943. // that it doesn't happen often even if the method is called many
  2944. // times in a row.
  2945. // @alternative
  2946. // @method invalidateSize(animate: Boolean): this
  2947. // Checks if the map container size changed and updates the map if so —
  2948. // call it after you've changed the map size dynamically, also animating
  2949. // pan by default.
  2950. invalidateSize: function (options) {
  2951. if (!this._loaded) { return this; }
  2952. options = extend({
  2953. animate: false,
  2954. pan: true
  2955. }, options === true ? {animate: true} : options);
  2956. var oldSize = this.getSize();
  2957. this._sizeChanged = true;
  2958. this._lastCenter = null;
  2959. var newSize = this.getSize(),
  2960. oldCenter = oldSize.divideBy(2).round(),
  2961. newCenter = newSize.divideBy(2).round(),
  2962. offset = oldCenter.subtract(newCenter);
  2963. if (!offset.x && !offset.y) { return this; }
  2964. if (options.animate && options.pan) {
  2965. this.panBy(offset);
  2966. } else {
  2967. if (options.pan) {
  2968. this._rawPanBy(offset);
  2969. }
  2970. this.fire('move');
  2971. if (options.debounceMoveend) {
  2972. clearTimeout(this._sizeTimer);
  2973. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  2974. } else {
  2975. this.fire('moveend');
  2976. }
  2977. }
  2978. // @section Map state change events
  2979. // @event resize: ResizeEvent
  2980. // Fired when the map is resized.
  2981. return this.fire('resize', {
  2982. oldSize: oldSize,
  2983. newSize: newSize
  2984. });
  2985. },
  2986. // @section Methods for modifying map state
  2987. // @method stop(): this
  2988. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2989. stop: function () {
  2990. this.setZoom(this._limitZoom(this._zoom));
  2991. if (!this.options.zoomSnap) {
  2992. this.fire('viewreset');
  2993. }
  2994. return this._stop();
  2995. },
  2996. // @section Geolocation methods
  2997. // @method locate(options?: Locate options): this
  2998. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  2999. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  3000. // and optionally sets the map view to the user's location with respect to
  3001. // detection accuracy (or to the world view if geolocation failed).
  3002. // Note that, if your page doesn't use HTTPS, this method will fail in
  3003. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  3004. // See `Locate options` for more details.
  3005. locate: function (options) {
  3006. options = this._locateOptions = extend({
  3007. timeout: 10000,
  3008. watch: false
  3009. // setView: false
  3010. // maxZoom: <Number>
  3011. // maximumAge: 0
  3012. // enableHighAccuracy: false
  3013. }, options);
  3014. if (!('geolocation' in navigator)) {
  3015. this._handleGeolocationError({
  3016. code: 0,
  3017. message: 'Geolocation not supported.'
  3018. });
  3019. return this;
  3020. }
  3021. var onResponse = bind(this._handleGeolocationResponse, this),
  3022. onError = bind(this._handleGeolocationError, this);
  3023. if (options.watch) {
  3024. this._locationWatchId =
  3025. navigator.geolocation.watchPosition(onResponse, onError, options);
  3026. } else {
  3027. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  3028. }
  3029. return this;
  3030. },
  3031. // @method stopLocate(): this
  3032. // Stops watching location previously initiated by `map.locate({watch: true})`
  3033. // and aborts resetting the map view if map.locate was called with
  3034. // `{setView: true}`.
  3035. stopLocate: function () {
  3036. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  3037. navigator.geolocation.clearWatch(this._locationWatchId);
  3038. }
  3039. if (this._locateOptions) {
  3040. this._locateOptions.setView = false;
  3041. }
  3042. return this;
  3043. },
  3044. _handleGeolocationError: function (error) {
  3045. var c = error.code,
  3046. message = error.message ||
  3047. (c === 1 ? 'permission denied' :
  3048. (c === 2 ? 'position unavailable' : 'timeout'));
  3049. if (this._locateOptions.setView && !this._loaded) {
  3050. this.fitWorld();
  3051. }
  3052. // @section Location events
  3053. // @event locationerror: ErrorEvent
  3054. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  3055. this.fire('locationerror', {
  3056. code: c,
  3057. message: 'Geolocation error: ' + message + '.'
  3058. });
  3059. },
  3060. _handleGeolocationResponse: function (pos) {
  3061. var lat = pos.coords.latitude,
  3062. lng = pos.coords.longitude,
  3063. latlng = new LatLng(lat, lng),
  3064. bounds = latlng.toBounds(pos.coords.accuracy * 2),
  3065. options = this._locateOptions;
  3066. if (options.setView) {
  3067. var zoom = this.getBoundsZoom(bounds);
  3068. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  3069. }
  3070. var data = {
  3071. latlng: latlng,
  3072. bounds: bounds,
  3073. timestamp: pos.timestamp
  3074. };
  3075. for (var i in pos.coords) {
  3076. if (typeof pos.coords[i] === 'number') {
  3077. data[i] = pos.coords[i];
  3078. }
  3079. }
  3080. // @event locationfound: LocationEvent
  3081. // Fired when geolocation (using the [`locate`](#map-locate) method)
  3082. // went successfully.
  3083. this.fire('locationfound', data);
  3084. },
  3085. // TODO Appropriate docs section?
  3086. // @section Other Methods
  3087. // @method addHandler(name: String, HandlerClass: Function): this
  3088. // Adds a new `Handler` to the map, given its name and constructor function.
  3089. addHandler: function (name, HandlerClass) {
  3090. if (!HandlerClass) { return this; }
  3091. var handler = this[name] = new HandlerClass(this);
  3092. this._handlers.push(handler);
  3093. if (this.options[name]) {
  3094. handler.enable();
  3095. }
  3096. return this;
  3097. },
  3098. // @method remove(): this
  3099. // Destroys the map and clears all related event listeners.
  3100. remove: function () {
  3101. this._initEvents(true);
  3102. if (this._containerId !== this._container._leaflet_id) {
  3103. throw new Error('Map container is being reused by another instance');
  3104. }
  3105. try {
  3106. // throws error in IE6-8
  3107. delete this._container._leaflet_id;
  3108. delete this._containerId;
  3109. } catch (e) {
  3110. /*eslint-disable */
  3111. this._container._leaflet_id = undefined;
  3112. /* eslint-enable */
  3113. this._containerId = undefined;
  3114. }
  3115. if (this._locationWatchId !== undefined) {
  3116. this.stopLocate();
  3117. }
  3118. this._stop();
  3119. remove(this._mapPane);
  3120. if (this._clearControlPos) {
  3121. this._clearControlPos();
  3122. }
  3123. if (this._resizeRequest) {
  3124. cancelAnimFrame(this._resizeRequest);
  3125. this._resizeRequest = null;
  3126. }
  3127. this._clearHandlers();
  3128. if (this._loaded) {
  3129. // @section Map state change events
  3130. // @event unload: Event
  3131. // Fired when the map is destroyed with [remove](#map-remove) method.
  3132. this.fire('unload');
  3133. }
  3134. var i;
  3135. for (i in this._layers) {
  3136. this._layers[i].remove();
  3137. }
  3138. for (i in this._panes) {
  3139. remove(this._panes[i]);
  3140. }
  3141. this._layers = [];
  3142. this._panes = [];
  3143. delete this._mapPane;
  3144. delete this._renderer;
  3145. return this;
  3146. },
  3147. // @section Other Methods
  3148. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3149. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3150. // then returns it. The pane is created as a child of `container`, or
  3151. // as a child of the main map pane if not set.
  3152. createPane: function (name, container) {
  3153. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3154. pane = create$1('div', className, container || this._mapPane);
  3155. if (name) {
  3156. this._panes[name] = pane;
  3157. }
  3158. return pane;
  3159. },
  3160. // @section Methods for Getting Map State
  3161. // @method getCenter(): LatLng
  3162. // Returns the geographical center of the map view
  3163. getCenter: function () {
  3164. this._checkIfLoaded();
  3165. if (this._lastCenter && !this._moved()) {
  3166. return this._lastCenter;
  3167. }
  3168. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3169. },
  3170. // @method getZoom(): Number
  3171. // Returns the current zoom level of the map view
  3172. getZoom: function () {
  3173. return this._zoom;
  3174. },
  3175. // @method getBounds(): LatLngBounds
  3176. // Returns the geographical bounds visible in the current map view
  3177. getBounds: function () {
  3178. var bounds = this.getPixelBounds(),
  3179. sw = this.unproject(bounds.getBottomLeft()),
  3180. ne = this.unproject(bounds.getTopRight());
  3181. return new LatLngBounds(sw, ne);
  3182. },
  3183. // @method getMinZoom(): Number
  3184. // 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.
  3185. getMinZoom: function () {
  3186. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3187. },
  3188. // @method getMaxZoom(): Number
  3189. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3190. getMaxZoom: function () {
  3191. return this.options.maxZoom === undefined ?
  3192. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3193. this.options.maxZoom;
  3194. },
  3195. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
  3196. // Returns the maximum zoom level on which the given bounds fit to the map
  3197. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3198. // instead returns the minimum zoom level on which the map view fits into
  3199. // the given bounds in its entirety.
  3200. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3201. bounds = toLatLngBounds(bounds);
  3202. padding = toPoint(padding || [0, 0]);
  3203. var zoom = this.getZoom() || 0,
  3204. min = this.getMinZoom(),
  3205. max = this.getMaxZoom(),
  3206. nw = bounds.getNorthWest(),
  3207. se = bounds.getSouthEast(),
  3208. size = this.getSize().subtract(padding),
  3209. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3210. snap = any3d ? this.options.zoomSnap : 1,
  3211. scalex = size.x / boundsSize.x,
  3212. scaley = size.y / boundsSize.y,
  3213. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3214. zoom = this.getScaleZoom(scale, zoom);
  3215. if (snap) {
  3216. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3217. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3218. }
  3219. return Math.max(min, Math.min(max, zoom));
  3220. },
  3221. // @method getSize(): Point
  3222. // Returns the current size of the map container (in pixels).
  3223. getSize: function () {
  3224. if (!this._size || this._sizeChanged) {
  3225. this._size = new Point(
  3226. this._container.clientWidth || 0,
  3227. this._container.clientHeight || 0);
  3228. this._sizeChanged = false;
  3229. }
  3230. return this._size.clone();
  3231. },
  3232. // @method getPixelBounds(): Bounds
  3233. // Returns the bounds of the current map view in projected pixel
  3234. // coordinates (sometimes useful in layer and overlay implementations).
  3235. getPixelBounds: function (center, zoom) {
  3236. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3237. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3238. },
  3239. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3240. // the map pane? "left point of the map layer" can be confusing, specially
  3241. // since there can be negative offsets.
  3242. // @method getPixelOrigin(): Point
  3243. // Returns the projected pixel coordinates of the top left point of
  3244. // the map layer (useful in custom layer and overlay implementations).
  3245. getPixelOrigin: function () {
  3246. this._checkIfLoaded();
  3247. return this._pixelOrigin;
  3248. },
  3249. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3250. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3251. // If `zoom` is omitted, the map's current zoom level is used.
  3252. getPixelWorldBounds: function (zoom) {
  3253. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3254. },
  3255. // @section Other Methods
  3256. // @method getPane(pane: String|HTMLElement): HTMLElement
  3257. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3258. getPane: function (pane) {
  3259. return typeof pane === 'string' ? this._panes[pane] : pane;
  3260. },
  3261. // @method getPanes(): Object
  3262. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3263. // the panes as values.
  3264. getPanes: function () {
  3265. return this._panes;
  3266. },
  3267. // @method getContainer: HTMLElement
  3268. // Returns the HTML element that contains the map.
  3269. getContainer: function () {
  3270. return this._container;
  3271. },
  3272. // @section Conversion Methods
  3273. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3274. // Returns the scale factor to be applied to a map transition from zoom level
  3275. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3276. getZoomScale: function (toZoom, fromZoom) {
  3277. // TODO replace with universal implementation after refactoring projections
  3278. var crs = this.options.crs;
  3279. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3280. return crs.scale(toZoom) / crs.scale(fromZoom);
  3281. },
  3282. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3283. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3284. // level and everything is scaled by a factor of `scale`. Inverse of
  3285. // [`getZoomScale`](#map-getZoomScale).
  3286. getScaleZoom: function (scale, fromZoom) {
  3287. var crs = this.options.crs;
  3288. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3289. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3290. return isNaN(zoom) ? Infinity : zoom;
  3291. },
  3292. // @method project(latlng: LatLng, zoom: Number): Point
  3293. // Projects a geographical coordinate `LatLng` according to the projection
  3294. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3295. // `Transformation`. The result is pixel coordinate relative to
  3296. // the CRS origin.
  3297. project: function (latlng, zoom) {
  3298. zoom = zoom === undefined ? this._zoom : zoom;
  3299. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3300. },
  3301. // @method unproject(point: Point, zoom: Number): LatLng
  3302. // Inverse of [`project`](#map-project).
  3303. unproject: function (point, zoom) {
  3304. zoom = zoom === undefined ? this._zoom : zoom;
  3305. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3306. },
  3307. // @method layerPointToLatLng(point: Point): LatLng
  3308. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3309. // returns the corresponding geographical coordinate (for the current zoom level).
  3310. layerPointToLatLng: function (point) {
  3311. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3312. return this.unproject(projectedPoint);
  3313. },
  3314. // @method latLngToLayerPoint(latlng: LatLng): Point
  3315. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3316. // relative to the [origin pixel](#map-getpixelorigin).
  3317. latLngToLayerPoint: function (latlng) {
  3318. var projectedPoint = this.project(toLatLng(latlng))._round();
  3319. return projectedPoint._subtract(this.getPixelOrigin());
  3320. },
  3321. // @method wrapLatLng(latlng: LatLng): LatLng
  3322. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3323. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3324. // CRS's bounds.
  3325. // By default this means longitude is wrapped around the dateline so its
  3326. // value is between -180 and +180 degrees.
  3327. wrapLatLng: function (latlng) {
  3328. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3329. },
  3330. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3331. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3332. // its center is within the CRS's bounds.
  3333. // By default this means the center longitude is wrapped around the dateline so its
  3334. // value is between -180 and +180 degrees, and the majority of the bounds
  3335. // overlaps the CRS's bounds.
  3336. wrapLatLngBounds: function (latlng) {
  3337. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3338. },
  3339. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3340. // Returns the distance between two geographical coordinates according to
  3341. // the map's CRS. By default this measures distance in meters.
  3342. distance: function (latlng1, latlng2) {
  3343. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3344. },
  3345. // @method containerPointToLayerPoint(point: Point): Point
  3346. // Given a pixel coordinate relative to the map container, returns the corresponding
  3347. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3348. containerPointToLayerPoint: function (point) { // (Point)
  3349. return toPoint(point).subtract(this._getMapPanePos());
  3350. },
  3351. // @method layerPointToContainerPoint(point: Point): Point
  3352. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3353. // returns the corresponding pixel coordinate relative to the map container.
  3354. layerPointToContainerPoint: function (point) { // (Point)
  3355. return toPoint(point).add(this._getMapPanePos());
  3356. },
  3357. // @method containerPointToLatLng(point: Point): LatLng
  3358. // Given a pixel coordinate relative to the map container, returns
  3359. // the corresponding geographical coordinate (for the current zoom level).
  3360. containerPointToLatLng: function (point) {
  3361. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3362. return this.layerPointToLatLng(layerPoint);
  3363. },
  3364. // @method latLngToContainerPoint(latlng: LatLng): Point
  3365. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3366. // relative to the map container.
  3367. latLngToContainerPoint: function (latlng) {
  3368. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3369. },
  3370. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3371. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3372. // map container where the event took place.
  3373. mouseEventToContainerPoint: function (e) {
  3374. return getMousePosition(e, this._container);
  3375. },
  3376. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3377. // Given a MouseEvent object, returns the pixel coordinate relative to
  3378. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3379. mouseEventToLayerPoint: function (e) {
  3380. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3381. },
  3382. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3383. // Given a MouseEvent object, returns geographical coordinate where the
  3384. // event took place.
  3385. mouseEventToLatLng: function (e) { // (MouseEvent)
  3386. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3387. },
  3388. // map initialization methods
  3389. _initContainer: function (id) {
  3390. var container = this._container = get(id);
  3391. if (!container) {
  3392. throw new Error('Map container not found.');
  3393. } else if (container._leaflet_id) {
  3394. throw new Error('Map container is already initialized.');
  3395. }
  3396. on(container, 'scroll', this._onScroll, this);
  3397. this._containerId = stamp(container);
  3398. },
  3399. _initLayout: function () {
  3400. var container = this._container;
  3401. this._fadeAnimated = this.options.fadeAnimation && any3d;
  3402. addClass(container, 'leaflet-container' +
  3403. (touch ? ' leaflet-touch' : '') +
  3404. (retina ? ' leaflet-retina' : '') +
  3405. (ielt9 ? ' leaflet-oldie' : '') +
  3406. (safari ? ' leaflet-safari' : '') +
  3407. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3408. var position = getStyle(container, 'position');
  3409. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  3410. container.style.position = 'relative';
  3411. }
  3412. this._initPanes();
  3413. if (this._initControlPos) {
  3414. this._initControlPos();
  3415. }
  3416. },
  3417. _initPanes: function () {
  3418. var panes = this._panes = {};
  3419. this._paneRenderers = {};
  3420. // @section
  3421. //
  3422. // Panes are DOM elements used to control the ordering of layers on the map. You
  3423. // can access panes with [`map.getPane`](#map-getpane) or
  3424. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3425. // [`map.createPane`](#map-createpane) method.
  3426. //
  3427. // Every map has the following default panes that differ only in zIndex.
  3428. //
  3429. // @pane mapPane: HTMLElement = 'auto'
  3430. // Pane that contains all other map panes
  3431. this._mapPane = this.createPane('mapPane', this._container);
  3432. setPosition(this._mapPane, new Point(0, 0));
  3433. // @pane tilePane: HTMLElement = 200
  3434. // Pane for `GridLayer`s and `TileLayer`s
  3435. this.createPane('tilePane');
  3436. // @pane overlayPane: HTMLElement = 400
  3437. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  3438. this.createPane('shadowPane');
  3439. // @pane shadowPane: HTMLElement = 500
  3440. // Pane for overlay shadows (e.g. `Marker` shadows)
  3441. this.createPane('overlayPane');
  3442. // @pane markerPane: HTMLElement = 600
  3443. // Pane for `Icon`s of `Marker`s
  3444. this.createPane('markerPane');
  3445. // @pane tooltipPane: HTMLElement = 650
  3446. // Pane for `Tooltip`s.
  3447. this.createPane('tooltipPane');
  3448. // @pane popupPane: HTMLElement = 700
  3449. // Pane for `Popup`s.
  3450. this.createPane('popupPane');
  3451. if (!this.options.markerZoomAnimation) {
  3452. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3453. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3454. }
  3455. },
  3456. // private methods that modify map state
  3457. // @section Map state change events
  3458. _resetView: function (center, zoom) {
  3459. setPosition(this._mapPane, new Point(0, 0));
  3460. var loading = !this._loaded;
  3461. this._loaded = true;
  3462. zoom = this._limitZoom(zoom);
  3463. this.fire('viewprereset');
  3464. var zoomChanged = this._zoom !== zoom;
  3465. this
  3466. ._moveStart(zoomChanged, false)
  3467. ._move(center, zoom)
  3468. ._moveEnd(zoomChanged);
  3469. // @event viewreset: Event
  3470. // Fired when the map needs to redraw its content (this usually happens
  3471. // on map zoom or load). Very useful for creating custom overlays.
  3472. this.fire('viewreset');
  3473. // @event load: Event
  3474. // Fired when the map is initialized (when its center and zoom are set
  3475. // for the first time).
  3476. if (loading) {
  3477. this.fire('load');
  3478. }
  3479. },
  3480. _moveStart: function (zoomChanged, noMoveStart) {
  3481. // @event zoomstart: Event
  3482. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3483. // @event movestart: Event
  3484. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3485. if (zoomChanged) {
  3486. this.fire('zoomstart');
  3487. }
  3488. if (!noMoveStart) {
  3489. this.fire('movestart');
  3490. }
  3491. return this;
  3492. },
  3493. _move: function (center, zoom, data) {
  3494. if (zoom === undefined) {
  3495. zoom = this._zoom;
  3496. }
  3497. var zoomChanged = this._zoom !== zoom;
  3498. this._zoom = zoom;
  3499. this._lastCenter = center;
  3500. this._pixelOrigin = this._getNewPixelOrigin(center);
  3501. // @event zoom: Event
  3502. // Fired repeatedly during any change in zoom level, including zoom
  3503. // and fly animations.
  3504. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3505. this.fire('zoom', data);
  3506. }
  3507. // @event move: Event
  3508. // Fired repeatedly during any movement of the map, including pan and
  3509. // fly animations.
  3510. return this.fire('move', data);
  3511. },
  3512. _moveEnd: function (zoomChanged) {
  3513. // @event zoomend: Event
  3514. // Fired when the map has changed, after any animations.
  3515. if (zoomChanged) {
  3516. this.fire('zoomend');
  3517. }
  3518. // @event moveend: Event
  3519. // Fired when the center of the map stops changing (e.g. user stopped
  3520. // dragging the map).
  3521. return this.fire('moveend');
  3522. },
  3523. _stop: function () {
  3524. cancelAnimFrame(this._flyToFrame);
  3525. if (this._panAnim) {
  3526. this._panAnim.stop();
  3527. }
  3528. return this;
  3529. },
  3530. _rawPanBy: function (offset) {
  3531. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3532. },
  3533. _getZoomSpan: function () {
  3534. return this.getMaxZoom() - this.getMinZoom();
  3535. },
  3536. _panInsideMaxBounds: function () {
  3537. if (!this._enforcingBounds) {
  3538. this.panInsideBounds(this.options.maxBounds);
  3539. }
  3540. },
  3541. _checkIfLoaded: function () {
  3542. if (!this._loaded) {
  3543. throw new Error('Set map center and zoom first.');
  3544. }
  3545. },
  3546. // DOM event handling
  3547. // @section Interaction events
  3548. _initEvents: function (remove$$1) {
  3549. this._targets = {};
  3550. this._targets[stamp(this._container)] = this;
  3551. var onOff = remove$$1 ? off : on;
  3552. // @event click: MouseEvent
  3553. // Fired when the user clicks (or taps) the map.
  3554. // @event dblclick: MouseEvent
  3555. // Fired when the user double-clicks (or double-taps) the map.
  3556. // @event mousedown: MouseEvent
  3557. // Fired when the user pushes the mouse button on the map.
  3558. // @event mouseup: MouseEvent
  3559. // Fired when the user releases the mouse button on the map.
  3560. // @event mouseover: MouseEvent
  3561. // Fired when the mouse enters the map.
  3562. // @event mouseout: MouseEvent
  3563. // Fired when the mouse leaves the map.
  3564. // @event mousemove: MouseEvent
  3565. // Fired while the mouse moves over the map.
  3566. // @event contextmenu: MouseEvent
  3567. // Fired when the user pushes the right mouse button on the map, prevents
  3568. // default browser context menu from showing if there are listeners on
  3569. // this event. Also fired on mobile when the user holds a single touch
  3570. // for a second (also called long press).
  3571. // @event keypress: KeyboardEvent
  3572. // Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
  3573. // @event keydown: KeyboardEvent
  3574. // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
  3575. // the `keydown` event is fired for keys that produce a character value and for keys
  3576. // that do not produce a character value.
  3577. // @event keyup: KeyboardEvent
  3578. // Fired when the user releases a key from the keyboard while the map is focused.
  3579. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3580. 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
  3581. if (this.options.trackResize) {
  3582. onOff(window, 'resize', this._onResize, this);
  3583. }
  3584. if (any3d && this.options.transform3DLimit) {
  3585. (remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3586. }
  3587. },
  3588. _onResize: function () {
  3589. cancelAnimFrame(this._resizeRequest);
  3590. this._resizeRequest = requestAnimFrame(
  3591. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3592. },
  3593. _onScroll: function () {
  3594. this._container.scrollTop = 0;
  3595. this._container.scrollLeft = 0;
  3596. },
  3597. _onMoveEnd: function () {
  3598. var pos = this._getMapPanePos();
  3599. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3600. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3601. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  3602. this._resetView(this.getCenter(), this.getZoom());
  3603. }
  3604. },
  3605. _findEventTargets: function (e, type) {
  3606. var targets = [],
  3607. target,
  3608. isHover = type === 'mouseout' || type === 'mouseover',
  3609. src = e.target || e.srcElement,
  3610. dragging = false;
  3611. while (src) {
  3612. target = this._targets[stamp(src)];
  3613. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  3614. // Prevent firing click after you just dragged an object.
  3615. dragging = true;
  3616. break;
  3617. }
  3618. if (target && target.listens(type, true)) {
  3619. if (isHover && !isExternalTarget(src, e)) { break; }
  3620. targets.push(target);
  3621. if (isHover) { break; }
  3622. }
  3623. if (src === this._container) { break; }
  3624. src = src.parentNode;
  3625. }
  3626. if (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {
  3627. targets = [this];
  3628. }
  3629. return targets;
  3630. },
  3631. _handleDOMEvent: function (e) {
  3632. if (!this._loaded || skipped(e)) { return; }
  3633. var type = e.type;
  3634. if (type === 'mousedown' || type === 'keypress' || type === 'keyup' || type === 'keydown') {
  3635. // prevents outline when clicking on keyboard-focusable element
  3636. preventOutline(e.target || e.srcElement);
  3637. }
  3638. this._fireDOMEvent(e, type);
  3639. },
  3640. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3641. _fireDOMEvent: function (e, type, targets) {
  3642. if (e.type === 'click') {
  3643. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3644. // @event preclick: MouseEvent
  3645. // Fired before mouse click on the map (sometimes useful when you
  3646. // want something to happen on click before any existing click
  3647. // handlers start running).
  3648. var synth = extend({}, e);
  3649. synth.type = 'preclick';
  3650. this._fireDOMEvent(synth, synth.type, targets);
  3651. }
  3652. if (e._stopped) { return; }
  3653. // Find the layer the event is propagating from and its parents.
  3654. targets = (targets || []).concat(this._findEventTargets(e, type));
  3655. if (!targets.length) { return; }
  3656. var target = targets[0];
  3657. if (type === 'contextmenu' && target.listens(type, true)) {
  3658. preventDefault(e);
  3659. }
  3660. var data = {
  3661. originalEvent: e
  3662. };
  3663. if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
  3664. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  3665. data.containerPoint = isMarker ?
  3666. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3667. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3668. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3669. }
  3670. for (var i = 0; i < targets.length; i++) {
  3671. targets[i].fire(type, data, true);
  3672. if (data.originalEvent._stopped ||
  3673. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3674. }
  3675. },
  3676. _draggableMoved: function (obj) {
  3677. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3678. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3679. },
  3680. _clearHandlers: function () {
  3681. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3682. this._handlers[i].disable();
  3683. }
  3684. },
  3685. // @section Other Methods
  3686. // @method whenReady(fn: Function, context?: Object): this
  3687. // Runs the given function `fn` when the map gets initialized with
  3688. // a view (center and zoom) and at least one layer, or immediately
  3689. // if it's already initialized, optionally passing a function context.
  3690. whenReady: function (callback, context) {
  3691. if (this._loaded) {
  3692. callback.call(context || this, {target: this});
  3693. } else {
  3694. this.on('load', callback, context);
  3695. }
  3696. return this;
  3697. },
  3698. // private methods for getting map state
  3699. _getMapPanePos: function () {
  3700. return getPosition(this._mapPane) || new Point(0, 0);
  3701. },
  3702. _moved: function () {
  3703. var pos = this._getMapPanePos();
  3704. return pos && !pos.equals([0, 0]);
  3705. },
  3706. _getTopLeftPoint: function (center, zoom) {
  3707. var pixelOrigin = center && zoom !== undefined ?
  3708. this._getNewPixelOrigin(center, zoom) :
  3709. this.getPixelOrigin();
  3710. return pixelOrigin.subtract(this._getMapPanePos());
  3711. },
  3712. _getNewPixelOrigin: function (center, zoom) {
  3713. var viewHalf = this.getSize()._divideBy(2);
  3714. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3715. },
  3716. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3717. var topLeft = this._getNewPixelOrigin(center, zoom);
  3718. return this.project(latlng, zoom)._subtract(topLeft);
  3719. },
  3720. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3721. var topLeft = this._getNewPixelOrigin(center, zoom);
  3722. return toBounds([
  3723. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3724. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3725. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3726. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3727. ]);
  3728. },
  3729. // layer point of the current center
  3730. _getCenterLayerPoint: function () {
  3731. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3732. },
  3733. // offset of the specified place to the current center in pixels
  3734. _getCenterOffset: function (latlng) {
  3735. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3736. },
  3737. // adjust center for view to get inside bounds
  3738. _limitCenter: function (center, zoom, bounds) {
  3739. if (!bounds) { return center; }
  3740. var centerPoint = this.project(center, zoom),
  3741. viewHalf = this.getSize().divideBy(2),
  3742. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3743. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3744. // If offset is less than a pixel, ignore.
  3745. // This prevents unstable projections from getting into
  3746. // an infinite loop of tiny offsets.
  3747. if (offset.round().equals([0, 0])) {
  3748. return center;
  3749. }
  3750. return this.unproject(centerPoint.add(offset), zoom);
  3751. },
  3752. // adjust offset for view to get inside bounds
  3753. _limitOffset: function (offset, bounds) {
  3754. if (!bounds) { return offset; }
  3755. var viewBounds = this.getPixelBounds(),
  3756. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3757. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3758. },
  3759. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3760. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3761. var projectedMaxBounds = toBounds(
  3762. this.project(maxBounds.getNorthEast(), zoom),
  3763. this.project(maxBounds.getSouthWest(), zoom)
  3764. ),
  3765. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3766. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3767. dx = this._rebound(minOffset.x, -maxOffset.x),
  3768. dy = this._rebound(minOffset.y, -maxOffset.y);
  3769. return new Point(dx, dy);
  3770. },
  3771. _rebound: function (left, right) {
  3772. return left + right > 0 ?
  3773. Math.round(left - right) / 2 :
  3774. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3775. },
  3776. _limitZoom: function (zoom) {
  3777. var min = this.getMinZoom(),
  3778. max = this.getMaxZoom(),
  3779. snap = any3d ? this.options.zoomSnap : 1;
  3780. if (snap) {
  3781. zoom = Math.round(zoom / snap) * snap;
  3782. }
  3783. return Math.max(min, Math.min(max, zoom));
  3784. },
  3785. _onPanTransitionStep: function () {
  3786. this.fire('move');
  3787. },
  3788. _onPanTransitionEnd: function () {
  3789. removeClass(this._mapPane, 'leaflet-pan-anim');
  3790. this.fire('moveend');
  3791. },
  3792. _tryAnimatedPan: function (center, options) {
  3793. // difference between the new and current centers in pixels
  3794. var offset = this._getCenterOffset(center)._trunc();
  3795. // don't animate too far unless animate: true specified in options
  3796. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3797. this.panBy(offset, options);
  3798. return true;
  3799. },
  3800. _createAnimProxy: function () {
  3801. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3802. this._panes.mapPane.appendChild(proxy);
  3803. this.on('zoomanim', function (e) {
  3804. var prop = TRANSFORM,
  3805. transform = this._proxy.style[prop];
  3806. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3807. // workaround for case when transform is the same and so transitionend event is not fired
  3808. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3809. this._onZoomTransitionEnd();
  3810. }
  3811. }, this);
  3812. this.on('load moveend', this._animMoveEnd, this);
  3813. this._on('unload', this._destroyAnimProxy, this);
  3814. },
  3815. _destroyAnimProxy: function () {
  3816. remove(this._proxy);
  3817. this.off('load moveend', this._animMoveEnd, this);
  3818. delete this._proxy;
  3819. },
  3820. _animMoveEnd: function () {
  3821. var c = this.getCenter(),
  3822. z = this.getZoom();
  3823. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3824. },
  3825. _catchTransitionEnd: function (e) {
  3826. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3827. this._onZoomTransitionEnd();
  3828. }
  3829. },
  3830. _nothingToAnimate: function () {
  3831. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3832. },
  3833. _tryAnimatedZoom: function (center, zoom, options) {
  3834. if (this._animatingZoom) { return true; }
  3835. options = options || {};
  3836. // don't animate if disabled, not supported or zoom difference is too large
  3837. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3838. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3839. // offset is the pixel coords of the zoom origin relative to the current center
  3840. var scale = this.getZoomScale(zoom),
  3841. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3842. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3843. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3844. requestAnimFrame(function () {
  3845. this
  3846. ._moveStart(true, false)
  3847. ._animateZoom(center, zoom, true);
  3848. }, this);
  3849. return true;
  3850. },
  3851. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3852. if (!this._mapPane) { return; }
  3853. if (startAnim) {
  3854. this._animatingZoom = true;
  3855. // remember what center/zoom to set after animation
  3856. this._animateToCenter = center;
  3857. this._animateToZoom = zoom;
  3858. addClass(this._mapPane, 'leaflet-zoom-anim');
  3859. }
  3860. // @section Other Events
  3861. // @event zoomanim: ZoomAnimEvent
  3862. // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
  3863. this.fire('zoomanim', {
  3864. center: center,
  3865. zoom: zoom,
  3866. noUpdate: noUpdate
  3867. });
  3868. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3869. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3870. },
  3871. _onZoomTransitionEnd: function () {
  3872. if (!this._animatingZoom) { return; }
  3873. if (this._mapPane) {
  3874. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3875. }
  3876. this._animatingZoom = false;
  3877. this._move(this._animateToCenter, this._animateToZoom);
  3878. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  3879. requestAnimFrame(function () {
  3880. this._moveEnd(true);
  3881. }, this);
  3882. }
  3883. });
  3884. // @section
  3885. // @factory L.map(id: String, options?: Map options)
  3886. // Instantiates a map object given the DOM ID of a `<div>` element
  3887. // and optionally an object literal with `Map options`.
  3888. //
  3889. // @alternative
  3890. // @factory L.map(el: HTMLElement, options?: Map options)
  3891. // Instantiates a map object given an instance of a `<div>` HTML element
  3892. // and optionally an object literal with `Map options`.
  3893. function createMap(id, options) {
  3894. return new Map(id, options);
  3895. }
  3896. /*
  3897. * @class Control
  3898. * @aka L.Control
  3899. * @inherits Class
  3900. *
  3901. * L.Control is a base class for implementing map controls. Handles positioning.
  3902. * All other controls extend from this class.
  3903. */
  3904. var Control = Class.extend({
  3905. // @section
  3906. // @aka Control options
  3907. options: {
  3908. // @option position: String = 'topright'
  3909. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  3910. // `'topright'`, `'bottomleft'` or `'bottomright'`
  3911. position: 'topright'
  3912. },
  3913. initialize: function (options) {
  3914. setOptions(this, options);
  3915. },
  3916. /* @section
  3917. * Classes extending L.Control will inherit the following methods:
  3918. *
  3919. * @method getPosition: string
  3920. * Returns the position of the control.
  3921. */
  3922. getPosition: function () {
  3923. return this.options.position;
  3924. },
  3925. // @method setPosition(position: string): this
  3926. // Sets the position of the control.
  3927. setPosition: function (position) {
  3928. var map = this._map;
  3929. if (map) {
  3930. map.removeControl(this);
  3931. }
  3932. this.options.position = position;
  3933. if (map) {
  3934. map.addControl(this);
  3935. }
  3936. return this;
  3937. },
  3938. // @method getContainer: HTMLElement
  3939. // Returns the HTMLElement that contains the control.
  3940. getContainer: function () {
  3941. return this._container;
  3942. },
  3943. // @method addTo(map: Map): this
  3944. // Adds the control to the given map.
  3945. addTo: function (map) {
  3946. this.remove();
  3947. this._map = map;
  3948. var container = this._container = this.onAdd(map),
  3949. pos = this.getPosition(),
  3950. corner = map._controlCorners[pos];
  3951. addClass(container, 'leaflet-control');
  3952. if (pos.indexOf('bottom') !== -1) {
  3953. corner.insertBefore(container, corner.firstChild);
  3954. } else {
  3955. corner.appendChild(container);
  3956. }
  3957. this._map.on('unload', this.remove, this);
  3958. return this;
  3959. },
  3960. // @method remove: this
  3961. // Removes the control from the map it is currently active on.
  3962. remove: function () {
  3963. if (!this._map) {
  3964. return this;
  3965. }
  3966. remove(this._container);
  3967. if (this.onRemove) {
  3968. this.onRemove(this._map);
  3969. }
  3970. this._map.off('unload', this.remove, this);
  3971. this._map = null;
  3972. return this;
  3973. },
  3974. _refocusOnMap: function (e) {
  3975. // if map exists and event is not a keyboard event
  3976. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  3977. this._map.getContainer().focus();
  3978. }
  3979. }
  3980. });
  3981. var control = function (options) {
  3982. return new Control(options);
  3983. };
  3984. /* @section Extension methods
  3985. * @uninheritable
  3986. *
  3987. * Every control should extend from `L.Control` and (re-)implement the following methods.
  3988. *
  3989. * @method onAdd(map: Map): HTMLElement
  3990. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  3991. *
  3992. * @method onRemove(map: Map)
  3993. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  3994. */
  3995. /* @namespace Map
  3996. * @section Methods for Layers and Controls
  3997. */
  3998. Map.include({
  3999. // @method addControl(control: Control): this
  4000. // Adds the given control to the map
  4001. addControl: function (control) {
  4002. control.addTo(this);
  4003. return this;
  4004. },
  4005. // @method removeControl(control: Control): this
  4006. // Removes the given control from the map
  4007. removeControl: function (control) {
  4008. control.remove();
  4009. return this;
  4010. },
  4011. _initControlPos: function () {
  4012. var corners = this._controlCorners = {},
  4013. l = 'leaflet-',
  4014. container = this._controlContainer =
  4015. create$1('div', l + 'control-container', this._container);
  4016. function createCorner(vSide, hSide) {
  4017. var className = l + vSide + ' ' + l + hSide;
  4018. corners[vSide + hSide] = create$1('div', className, container);
  4019. }
  4020. createCorner('top', 'left');
  4021. createCorner('top', 'right');
  4022. createCorner('bottom', 'left');
  4023. createCorner('bottom', 'right');
  4024. },
  4025. _clearControlPos: function () {
  4026. for (var i in this._controlCorners) {
  4027. remove(this._controlCorners[i]);
  4028. }
  4029. remove(this._controlContainer);
  4030. delete this._controlCorners;
  4031. delete this._controlContainer;
  4032. }
  4033. });
  4034. /*
  4035. * @class Control.Layers
  4036. * @aka L.Control.Layers
  4037. * @inherits Control
  4038. *
  4039. * 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`.
  4040. *
  4041. * @example
  4042. *
  4043. * ```js
  4044. * var baseLayers = {
  4045. * "Mapbox": mapbox,
  4046. * "OpenStreetMap": osm
  4047. * };
  4048. *
  4049. * var overlays = {
  4050. * "Marker": marker,
  4051. * "Roads": roadsLayer
  4052. * };
  4053. *
  4054. * L.control.layers(baseLayers, overlays).addTo(map);
  4055. * ```
  4056. *
  4057. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  4058. *
  4059. * ```js
  4060. * {
  4061. * "<someName1>": layer1,
  4062. * "<someName2>": layer2
  4063. * }
  4064. * ```
  4065. *
  4066. * The layer names can contain HTML, which allows you to add additional styling to the items:
  4067. *
  4068. * ```js
  4069. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  4070. * ```
  4071. */
  4072. var Layers = Control.extend({
  4073. // @section
  4074. // @aka Control.Layers options
  4075. options: {
  4076. // @option collapsed: Boolean = true
  4077. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  4078. collapsed: true,
  4079. position: 'topright',
  4080. // @option autoZIndex: Boolean = true
  4081. // 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.
  4082. autoZIndex: true,
  4083. // @option hideSingleBase: Boolean = false
  4084. // If `true`, the base layers in the control will be hidden when there is only one.
  4085. hideSingleBase: false,
  4086. // @option sortLayers: Boolean = false
  4087. // Whether to sort the layers. When `false`, layers will keep the order
  4088. // in which they were added to the control.
  4089. sortLayers: false,
  4090. // @option sortFunction: Function = *
  4091. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  4092. // that will be used for sorting the layers, when `sortLayers` is `true`.
  4093. // The function receives both the `L.Layer` instances and their names, as in
  4094. // `sortFunction(layerA, layerB, nameA, nameB)`.
  4095. // By default, it sorts layers alphabetically by their name.
  4096. sortFunction: function (layerA, layerB, nameA, nameB) {
  4097. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  4098. }
  4099. },
  4100. initialize: function (baseLayers, overlays, options) {
  4101. setOptions(this, options);
  4102. this._layerControlInputs = [];
  4103. this._layers = [];
  4104. this._lastZIndex = 0;
  4105. this._handlingClick = false;
  4106. for (var i in baseLayers) {
  4107. this._addLayer(baseLayers[i], i);
  4108. }
  4109. for (i in overlays) {
  4110. this._addLayer(overlays[i], i, true);
  4111. }
  4112. },
  4113. onAdd: function (map) {
  4114. this._initLayout();
  4115. this._update();
  4116. this._map = map;
  4117. map.on('zoomend', this._checkDisabledLayers, this);
  4118. for (var i = 0; i < this._layers.length; i++) {
  4119. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4120. }
  4121. return this._container;
  4122. },
  4123. addTo: function (map) {
  4124. Control.prototype.addTo.call(this, map);
  4125. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4126. return this._expandIfNotCollapsed();
  4127. },
  4128. onRemove: function () {
  4129. this._map.off('zoomend', this._checkDisabledLayers, this);
  4130. for (var i = 0; i < this._layers.length; i++) {
  4131. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4132. }
  4133. },
  4134. // @method addBaseLayer(layer: Layer, name: String): this
  4135. // Adds a base layer (radio button entry) with the given name to the control.
  4136. addBaseLayer: function (layer, name) {
  4137. this._addLayer(layer, name);
  4138. return (this._map) ? this._update() : this;
  4139. },
  4140. // @method addOverlay(layer: Layer, name: String): this
  4141. // Adds an overlay (checkbox entry) with the given name to the control.
  4142. addOverlay: function (layer, name) {
  4143. this._addLayer(layer, name, true);
  4144. return (this._map) ? this._update() : this;
  4145. },
  4146. // @method removeLayer(layer: Layer): this
  4147. // Remove the given layer from the control.
  4148. removeLayer: function (layer) {
  4149. layer.off('add remove', this._onLayerChange, this);
  4150. var obj = this._getLayer(stamp(layer));
  4151. if (obj) {
  4152. this._layers.splice(this._layers.indexOf(obj), 1);
  4153. }
  4154. return (this._map) ? this._update() : this;
  4155. },
  4156. // @method expand(): this
  4157. // Expand the control container if collapsed.
  4158. expand: function () {
  4159. addClass(this._container, 'leaflet-control-layers-expanded');
  4160. this._section.style.height = null;
  4161. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4162. if (acceptableHeight < this._section.clientHeight) {
  4163. addClass(this._section, 'leaflet-control-layers-scrollbar');
  4164. this._section.style.height = acceptableHeight + 'px';
  4165. } else {
  4166. removeClass(this._section, 'leaflet-control-layers-scrollbar');
  4167. }
  4168. this._checkDisabledLayers();
  4169. return this;
  4170. },
  4171. // @method collapse(): this
  4172. // Collapse the control container if expanded.
  4173. collapse: function () {
  4174. removeClass(this._container, 'leaflet-control-layers-expanded');
  4175. return this;
  4176. },
  4177. _initLayout: function () {
  4178. var className = 'leaflet-control-layers',
  4179. container = this._container = create$1('div', className),
  4180. collapsed = this.options.collapsed;
  4181. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4182. container.setAttribute('aria-haspopup', true);
  4183. disableClickPropagation(container);
  4184. disableScrollPropagation(container);
  4185. var section = this._section = create$1('section', className + '-list');
  4186. if (collapsed) {
  4187. this._map.on('click', this.collapse, this);
  4188. if (!android) {
  4189. on(container, {
  4190. mouseenter: this.expand,
  4191. mouseleave: this.collapse
  4192. }, this);
  4193. }
  4194. }
  4195. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4196. link.href = '#';
  4197. link.title = 'Layers';
  4198. if (touch) {
  4199. on(link, 'click', stop);
  4200. on(link, 'click', this.expand, this);
  4201. } else {
  4202. on(link, 'focus', this.expand, this);
  4203. }
  4204. if (!collapsed) {
  4205. this.expand();
  4206. }
  4207. this._baseLayersList = create$1('div', className + '-base', section);
  4208. this._separator = create$1('div', className + '-separator', section);
  4209. this._overlaysList = create$1('div', className + '-overlays', section);
  4210. container.appendChild(section);
  4211. },
  4212. _getLayer: function (id) {
  4213. for (var i = 0; i < this._layers.length; i++) {
  4214. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4215. return this._layers[i];
  4216. }
  4217. }
  4218. },
  4219. _addLayer: function (layer, name, overlay) {
  4220. if (this._map) {
  4221. layer.on('add remove', this._onLayerChange, this);
  4222. }
  4223. this._layers.push({
  4224. layer: layer,
  4225. name: name,
  4226. overlay: overlay
  4227. });
  4228. if (this.options.sortLayers) {
  4229. this._layers.sort(bind(function (a, b) {
  4230. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4231. }, this));
  4232. }
  4233. if (this.options.autoZIndex && layer.setZIndex) {
  4234. this._lastZIndex++;
  4235. layer.setZIndex(this._lastZIndex);
  4236. }
  4237. this._expandIfNotCollapsed();
  4238. },
  4239. _update: function () {
  4240. if (!this._container) { return this; }
  4241. empty(this._baseLayersList);
  4242. empty(this._overlaysList);
  4243. this._layerControlInputs = [];
  4244. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4245. for (i = 0; i < this._layers.length; i++) {
  4246. obj = this._layers[i];
  4247. this._addItem(obj);
  4248. overlaysPresent = overlaysPresent || obj.overlay;
  4249. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4250. baseLayersCount += !obj.overlay ? 1 : 0;
  4251. }
  4252. // Hide base layers section if there's only one layer.
  4253. if (this.options.hideSingleBase) {
  4254. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4255. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4256. }
  4257. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4258. return this;
  4259. },
  4260. _onLayerChange: function (e) {
  4261. if (!this._handlingClick) {
  4262. this._update();
  4263. }
  4264. var obj = this._getLayer(stamp(e.target));
  4265. // @namespace Map
  4266. // @section Layer events
  4267. // @event baselayerchange: LayersControlEvent
  4268. // Fired when the base layer is changed through the [layer control](#control-layers).
  4269. // @event overlayadd: LayersControlEvent
  4270. // Fired when an overlay is selected through the [layer control](#control-layers).
  4271. // @event overlayremove: LayersControlEvent
  4272. // Fired when an overlay is deselected through the [layer control](#control-layers).
  4273. // @namespace Control.Layers
  4274. var type = obj.overlay ?
  4275. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4276. (e.type === 'add' ? 'baselayerchange' : null);
  4277. if (type) {
  4278. this._map.fire(type, obj);
  4279. }
  4280. },
  4281. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  4282. _createRadioElement: function (name, checked) {
  4283. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4284. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4285. var radioFragment = document.createElement('div');
  4286. radioFragment.innerHTML = radioHtml;
  4287. return radioFragment.firstChild;
  4288. },
  4289. _addItem: function (obj) {
  4290. var label = document.createElement('label'),
  4291. checked = this._map.hasLayer(obj.layer),
  4292. input;
  4293. if (obj.overlay) {
  4294. input = document.createElement('input');
  4295. input.type = 'checkbox';
  4296. input.className = 'leaflet-control-layers-selector';
  4297. input.defaultChecked = checked;
  4298. } else {
  4299. input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);
  4300. }
  4301. this._layerControlInputs.push(input);
  4302. input.layerId = stamp(obj.layer);
  4303. on(input, 'click', this._onInputClick, this);
  4304. var name = document.createElement('span');
  4305. name.innerHTML = ' ' + obj.name;
  4306. // Helps from preventing layer control flicker when checkboxes are disabled
  4307. // https://github.com/Leaflet/Leaflet/issues/2771
  4308. var holder = document.createElement('div');
  4309. label.appendChild(holder);
  4310. holder.appendChild(input);
  4311. holder.appendChild(name);
  4312. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4313. container.appendChild(label);
  4314. this._checkDisabledLayers();
  4315. return label;
  4316. },
  4317. _onInputClick: function () {
  4318. var inputs = this._layerControlInputs,
  4319. input, layer;
  4320. var addedLayers = [],
  4321. removedLayers = [];
  4322. this._handlingClick = true;
  4323. for (var i = inputs.length - 1; i >= 0; i--) {
  4324. input = inputs[i];
  4325. layer = this._getLayer(input.layerId).layer;
  4326. if (input.checked) {
  4327. addedLayers.push(layer);
  4328. } else if (!input.checked) {
  4329. removedLayers.push(layer);
  4330. }
  4331. }
  4332. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4333. for (i = 0; i < removedLayers.length; i++) {
  4334. if (this._map.hasLayer(removedLayers[i])) {
  4335. this._map.removeLayer(removedLayers[i]);
  4336. }
  4337. }
  4338. for (i = 0; i < addedLayers.length; i++) {
  4339. if (!this._map.hasLayer(addedLayers[i])) {
  4340. this._map.addLayer(addedLayers[i]);
  4341. }
  4342. }
  4343. this._handlingClick = false;
  4344. this._refocusOnMap();
  4345. },
  4346. _checkDisabledLayers: function () {
  4347. var inputs = this._layerControlInputs,
  4348. input,
  4349. layer,
  4350. zoom = this._map.getZoom();
  4351. for (var i = inputs.length - 1; i >= 0; i--) {
  4352. input = inputs[i];
  4353. layer = this._getLayer(input.layerId).layer;
  4354. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4355. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4356. }
  4357. },
  4358. _expandIfNotCollapsed: function () {
  4359. if (this._map && !this.options.collapsed) {
  4360. this.expand();
  4361. }
  4362. return this;
  4363. },
  4364. _expand: function () {
  4365. // Backward compatibility, remove me in 1.1.
  4366. return this.expand();
  4367. },
  4368. _collapse: function () {
  4369. // Backward compatibility, remove me in 1.1.
  4370. return this.collapse();
  4371. }
  4372. });
  4373. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4374. // 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.
  4375. var layers = function (baseLayers, overlays, options) {
  4376. return new Layers(baseLayers, overlays, options);
  4377. };
  4378. /*
  4379. * @class Control.Zoom
  4380. * @aka L.Control.Zoom
  4381. * @inherits Control
  4382. *
  4383. * 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`.
  4384. */
  4385. var Zoom = Control.extend({
  4386. // @section
  4387. // @aka Control.Zoom options
  4388. options: {
  4389. position: 'topleft',
  4390. // @option zoomInText: String = '+'
  4391. // The text set on the 'zoom in' button.
  4392. zoomInText: '+',
  4393. // @option zoomInTitle: String = 'Zoom in'
  4394. // The title set on the 'zoom in' button.
  4395. zoomInTitle: 'Zoom in',
  4396. // @option zoomOutText: String = '&#x2212;'
  4397. // The text set on the 'zoom out' button.
  4398. zoomOutText: '&#x2212;',
  4399. // @option zoomOutTitle: String = 'Zoom out'
  4400. // The title set on the 'zoom out' button.
  4401. zoomOutTitle: 'Zoom out'
  4402. },
  4403. onAdd: function (map) {
  4404. var zoomName = 'leaflet-control-zoom',
  4405. container = create$1('div', zoomName + ' leaflet-bar'),
  4406. options = this.options;
  4407. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4408. zoomName + '-in', container, this._zoomIn);
  4409. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4410. zoomName + '-out', container, this._zoomOut);
  4411. this._updateDisabled();
  4412. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4413. return container;
  4414. },
  4415. onRemove: function (map) {
  4416. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4417. },
  4418. disable: function () {
  4419. this._disabled = true;
  4420. this._updateDisabled();
  4421. return this;
  4422. },
  4423. enable: function () {
  4424. this._disabled = false;
  4425. this._updateDisabled();
  4426. return this;
  4427. },
  4428. _zoomIn: function (e) {
  4429. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4430. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4431. }
  4432. },
  4433. _zoomOut: function (e) {
  4434. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4435. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4436. }
  4437. },
  4438. _createButton: function (html, title, className, container, fn) {
  4439. var link = create$1('a', className, container);
  4440. link.innerHTML = html;
  4441. link.href = '#';
  4442. link.title = title;
  4443. /*
  4444. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4445. */
  4446. link.setAttribute('role', 'button');
  4447. link.setAttribute('aria-label', title);
  4448. disableClickPropagation(link);
  4449. on(link, 'click', stop);
  4450. on(link, 'click', fn, this);
  4451. on(link, 'click', this._refocusOnMap, this);
  4452. return link;
  4453. },
  4454. _updateDisabled: function () {
  4455. var map = this._map,
  4456. className = 'leaflet-disabled';
  4457. removeClass(this._zoomInButton, className);
  4458. removeClass(this._zoomOutButton, className);
  4459. if (this._disabled || map._zoom === map.getMinZoom()) {
  4460. addClass(this._zoomOutButton, className);
  4461. }
  4462. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4463. addClass(this._zoomInButton, className);
  4464. }
  4465. }
  4466. });
  4467. // @namespace Map
  4468. // @section Control options
  4469. // @option zoomControl: Boolean = true
  4470. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4471. Map.mergeOptions({
  4472. zoomControl: true
  4473. });
  4474. Map.addInitHook(function () {
  4475. if (this.options.zoomControl) {
  4476. // @section Controls
  4477. // @property zoomControl: Control.Zoom
  4478. // The default zoom control (only available if the
  4479. // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
  4480. this.zoomControl = new Zoom();
  4481. this.addControl(this.zoomControl);
  4482. }
  4483. });
  4484. // @namespace Control.Zoom
  4485. // @factory L.control.zoom(options: Control.Zoom options)
  4486. // Creates a zoom control
  4487. var zoom = function (options) {
  4488. return new Zoom(options);
  4489. };
  4490. /*
  4491. * @class Control.Scale
  4492. * @aka L.Control.Scale
  4493. * @inherits Control
  4494. *
  4495. * 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`.
  4496. *
  4497. * @example
  4498. *
  4499. * ```js
  4500. * L.control.scale().addTo(map);
  4501. * ```
  4502. */
  4503. var Scale = Control.extend({
  4504. // @section
  4505. // @aka Control.Scale options
  4506. options: {
  4507. position: 'bottomleft',
  4508. // @option maxWidth: Number = 100
  4509. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4510. maxWidth: 100,
  4511. // @option metric: Boolean = True
  4512. // Whether to show the metric scale line (m/km).
  4513. metric: true,
  4514. // @option imperial: Boolean = True
  4515. // Whether to show the imperial scale line (mi/ft).
  4516. imperial: true
  4517. // @option updateWhenIdle: Boolean = false
  4518. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4519. },
  4520. onAdd: function (map) {
  4521. var className = 'leaflet-control-scale',
  4522. container = create$1('div', className),
  4523. options = this.options;
  4524. this._addScales(options, className + '-line', container);
  4525. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4526. map.whenReady(this._update, this);
  4527. return container;
  4528. },
  4529. onRemove: function (map) {
  4530. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4531. },
  4532. _addScales: function (options, className, container) {
  4533. if (options.metric) {
  4534. this._mScale = create$1('div', className, container);
  4535. }
  4536. if (options.imperial) {
  4537. this._iScale = create$1('div', className, container);
  4538. }
  4539. },
  4540. _update: function () {
  4541. var map = this._map,
  4542. y = map.getSize().y / 2;
  4543. var maxMeters = map.distance(
  4544. map.containerPointToLatLng([0, y]),
  4545. map.containerPointToLatLng([this.options.maxWidth, y]));
  4546. this._updateScales(maxMeters);
  4547. },
  4548. _updateScales: function (maxMeters) {
  4549. if (this.options.metric && maxMeters) {
  4550. this._updateMetric(maxMeters);
  4551. }
  4552. if (this.options.imperial && maxMeters) {
  4553. this._updateImperial(maxMeters);
  4554. }
  4555. },
  4556. _updateMetric: function (maxMeters) {
  4557. var meters = this._getRoundNum(maxMeters),
  4558. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4559. this._updateScale(this._mScale, label, meters / maxMeters);
  4560. },
  4561. _updateImperial: function (maxMeters) {
  4562. var maxFeet = maxMeters * 3.2808399,
  4563. maxMiles, miles, feet;
  4564. if (maxFeet > 5280) {
  4565. maxMiles = maxFeet / 5280;
  4566. miles = this._getRoundNum(maxMiles);
  4567. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4568. } else {
  4569. feet = this._getRoundNum(maxFeet);
  4570. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4571. }
  4572. },
  4573. _updateScale: function (scale, text, ratio) {
  4574. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4575. scale.innerHTML = text;
  4576. },
  4577. _getRoundNum: function (num) {
  4578. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4579. d = num / pow10;
  4580. d = d >= 10 ? 10 :
  4581. d >= 5 ? 5 :
  4582. d >= 3 ? 3 :
  4583. d >= 2 ? 2 : 1;
  4584. return pow10 * d;
  4585. }
  4586. });
  4587. // @factory L.control.scale(options?: Control.Scale options)
  4588. // Creates an scale control with the given options.
  4589. var scale = function (options) {
  4590. return new Scale(options);
  4591. };
  4592. /*
  4593. * @class Control.Attribution
  4594. * @aka L.Control.Attribution
  4595. * @inherits Control
  4596. *
  4597. * 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.
  4598. */
  4599. var Attribution = Control.extend({
  4600. // @section
  4601. // @aka Control.Attribution options
  4602. options: {
  4603. position: 'bottomright',
  4604. // @option prefix: String = 'Leaflet'
  4605. // The HTML text shown before the attributions. Pass `false` to disable.
  4606. prefix: '<a href="https://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  4607. },
  4608. initialize: function (options) {
  4609. setOptions(this, options);
  4610. this._attributions = {};
  4611. },
  4612. onAdd: function (map) {
  4613. map.attributionControl = this;
  4614. this._container = create$1('div', 'leaflet-control-attribution');
  4615. disableClickPropagation(this._container);
  4616. // TODO ugly, refactor
  4617. for (var i in map._layers) {
  4618. if (map._layers[i].getAttribution) {
  4619. this.addAttribution(map._layers[i].getAttribution());
  4620. }
  4621. }
  4622. this._update();
  4623. return this._container;
  4624. },
  4625. // @method setPrefix(prefix: String): this
  4626. // Sets the text before the attributions.
  4627. setPrefix: function (prefix) {
  4628. this.options.prefix = prefix;
  4629. this._update();
  4630. return this;
  4631. },
  4632. // @method addAttribution(text: String): this
  4633. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  4634. addAttribution: function (text) {
  4635. if (!text) { return this; }
  4636. if (!this._attributions[text]) {
  4637. this._attributions[text] = 0;
  4638. }
  4639. this._attributions[text]++;
  4640. this._update();
  4641. return this;
  4642. },
  4643. // @method removeAttribution(text: String): this
  4644. // Removes an attribution text.
  4645. removeAttribution: function (text) {
  4646. if (!text) { return this; }
  4647. if (this._attributions[text]) {
  4648. this._attributions[text]--;
  4649. this._update();
  4650. }
  4651. return this;
  4652. },
  4653. _update: function () {
  4654. if (!this._map) { return; }
  4655. var attribs = [];
  4656. for (var i in this._attributions) {
  4657. if (this._attributions[i]) {
  4658. attribs.push(i);
  4659. }
  4660. }
  4661. var prefixAndAttribs = [];
  4662. if (this.options.prefix) {
  4663. prefixAndAttribs.push(this.options.prefix);
  4664. }
  4665. if (attribs.length) {
  4666. prefixAndAttribs.push(attribs.join(', '));
  4667. }
  4668. this._container.innerHTML = prefixAndAttribs.join(' | ');
  4669. }
  4670. });
  4671. // @namespace Map
  4672. // @section Control options
  4673. // @option attributionControl: Boolean = true
  4674. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4675. Map.mergeOptions({
  4676. attributionControl: true
  4677. });
  4678. Map.addInitHook(function () {
  4679. if (this.options.attributionControl) {
  4680. new Attribution().addTo(this);
  4681. }
  4682. });
  4683. // @namespace Control.Attribution
  4684. // @factory L.control.attribution(options: Control.Attribution options)
  4685. // Creates an attribution control.
  4686. var attribution = function (options) {
  4687. return new Attribution(options);
  4688. };
  4689. Control.Layers = Layers;
  4690. Control.Zoom = Zoom;
  4691. Control.Scale = Scale;
  4692. Control.Attribution = Attribution;
  4693. control.layers = layers;
  4694. control.zoom = zoom;
  4695. control.scale = scale;
  4696. control.attribution = attribution;
  4697. /*
  4698. L.Handler is a base class for handler classes that are used internally to inject
  4699. interaction features like dragging to classes like Map and Marker.
  4700. */
  4701. // @class Handler
  4702. // @aka L.Handler
  4703. // Abstract class for map interaction handlers
  4704. var Handler = Class.extend({
  4705. initialize: function (map) {
  4706. this._map = map;
  4707. },
  4708. // @method enable(): this
  4709. // Enables the handler
  4710. enable: function () {
  4711. if (this._enabled) { return this; }
  4712. this._enabled = true;
  4713. this.addHooks();
  4714. return this;
  4715. },
  4716. // @method disable(): this
  4717. // Disables the handler
  4718. disable: function () {
  4719. if (!this._enabled) { return this; }
  4720. this._enabled = false;
  4721. this.removeHooks();
  4722. return this;
  4723. },
  4724. // @method enabled(): Boolean
  4725. // Returns `true` if the handler is enabled
  4726. enabled: function () {
  4727. return !!this._enabled;
  4728. }
  4729. // @section Extension methods
  4730. // Classes inheriting from `Handler` must implement the two following methods:
  4731. // @method addHooks()
  4732. // Called when the handler is enabled, should add event hooks.
  4733. // @method removeHooks()
  4734. // Called when the handler is disabled, should remove the event hooks added previously.
  4735. });
  4736. // @section There is static function which can be called without instantiating L.Handler:
  4737. // @function addTo(map: Map, name: String): this
  4738. // Adds a new Handler to the given map with the given name.
  4739. Handler.addTo = function (map, name) {
  4740. map.addHandler(name, this);
  4741. return this;
  4742. };
  4743. var Mixin = {Events: Events};
  4744. /*
  4745. * @class Draggable
  4746. * @aka L.Draggable
  4747. * @inherits Evented
  4748. *
  4749. * A class for making DOM elements draggable (including touch support).
  4750. * Used internally for map and marker dragging. Only works for elements
  4751. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4752. *
  4753. * @example
  4754. * ```js
  4755. * var draggable = new L.Draggable(elementToDrag);
  4756. * draggable.enable();
  4757. * ```
  4758. */
  4759. var START = touch ? 'touchstart mousedown' : 'mousedown';
  4760. var END = {
  4761. mousedown: 'mouseup',
  4762. touchstart: 'touchend',
  4763. pointerdown: 'touchend',
  4764. MSPointerDown: 'touchend'
  4765. };
  4766. var MOVE = {
  4767. mousedown: 'mousemove',
  4768. touchstart: 'touchmove',
  4769. pointerdown: 'touchmove',
  4770. MSPointerDown: 'touchmove'
  4771. };
  4772. var Draggable = Evented.extend({
  4773. options: {
  4774. // @section
  4775. // @aka Draggable options
  4776. // @option clickTolerance: Number = 3
  4777. // The max number of pixels a user can shift the mouse pointer during a click
  4778. // for it to be considered a valid click (as opposed to a mouse drag).
  4779. clickTolerance: 3
  4780. },
  4781. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4782. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4783. initialize: function (element, dragStartTarget, preventOutline$$1, options) {
  4784. setOptions(this, options);
  4785. this._element = element;
  4786. this._dragStartTarget = dragStartTarget || element;
  4787. this._preventOutline = preventOutline$$1;
  4788. },
  4789. // @method enable()
  4790. // Enables the dragging ability
  4791. enable: function () {
  4792. if (this._enabled) { return; }
  4793. on(this._dragStartTarget, START, this._onDown, this);
  4794. this._enabled = true;
  4795. },
  4796. // @method disable()
  4797. // Disables the dragging ability
  4798. disable: function () {
  4799. if (!this._enabled) { return; }
  4800. // If we're currently dragging this draggable,
  4801. // disabling it counts as first ending the drag.
  4802. if (Draggable._dragging === this) {
  4803. this.finishDrag();
  4804. }
  4805. off(this._dragStartTarget, START, this._onDown, this);
  4806. this._enabled = false;
  4807. this._moved = false;
  4808. },
  4809. _onDown: function (e) {
  4810. // Ignore simulated events, since we handle both touch and
  4811. // mouse explicitly; otherwise we risk getting duplicates of
  4812. // touch events, see #4315.
  4813. // Also ignore the event if disabled; this happens in IE11
  4814. // under some circumstances, see #3666.
  4815. if (e._simulated || !this._enabled) { return; }
  4816. this._moved = false;
  4817. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4818. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4819. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4820. if (this._preventOutline) {
  4821. preventOutline(this._element);
  4822. }
  4823. disableImageDrag();
  4824. disableTextSelection();
  4825. if (this._moving) { return; }
  4826. // @event down: Event
  4827. // Fired when a drag is about to start.
  4828. this.fire('down');
  4829. var first = e.touches ? e.touches[0] : e,
  4830. sizedParent = getSizedParentNode(this._element);
  4831. this._startPoint = new Point(first.clientX, first.clientY);
  4832. // Cache the scale, so that we can continuously compensate for it during drag (_onMove).
  4833. this._parentScale = getScale(sizedParent);
  4834. on(document, MOVE[e.type], this._onMove, this);
  4835. on(document, END[e.type], this._onUp, this);
  4836. },
  4837. _onMove: function (e) {
  4838. // Ignore simulated events, since we handle both touch and
  4839. // mouse explicitly; otherwise we risk getting duplicates of
  4840. // touch events, see #4315.
  4841. // Also ignore the event if disabled; this happens in IE11
  4842. // under some circumstances, see #3666.
  4843. if (e._simulated || !this._enabled) { return; }
  4844. if (e.touches && e.touches.length > 1) {
  4845. this._moved = true;
  4846. return;
  4847. }
  4848. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4849. offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);
  4850. if (!offset.x && !offset.y) { return; }
  4851. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4852. // We assume that the parent container's position, border and scale do not change for the duration of the drag.
  4853. // Therefore there is no need to account for the position and border (they are eliminated by the subtraction)
  4854. // and we can use the cached value for the scale.
  4855. offset.x /= this._parentScale.x;
  4856. offset.y /= this._parentScale.y;
  4857. preventDefault(e);
  4858. if (!this._moved) {
  4859. // @event dragstart: Event
  4860. // Fired when a drag starts
  4861. this.fire('dragstart');
  4862. this._moved = true;
  4863. this._startPos = getPosition(this._element).subtract(offset);
  4864. addClass(document.body, 'leaflet-dragging');
  4865. this._lastTarget = e.target || e.srcElement;
  4866. // IE and Edge do not give the <use> element, so fetch it
  4867. // if necessary
  4868. if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
  4869. this._lastTarget = this._lastTarget.correspondingUseElement;
  4870. }
  4871. addClass(this._lastTarget, 'leaflet-drag-target');
  4872. }
  4873. this._newPos = this._startPos.add(offset);
  4874. this._moving = true;
  4875. cancelAnimFrame(this._animRequest);
  4876. this._lastEvent = e;
  4877. this._animRequest = requestAnimFrame(this._updatePosition, this, true);
  4878. },
  4879. _updatePosition: function () {
  4880. var e = {originalEvent: this._lastEvent};
  4881. // @event predrag: Event
  4882. // Fired continuously during dragging *before* each corresponding
  4883. // update of the element's position.
  4884. this.fire('predrag', e);
  4885. setPosition(this._element, this._newPos);
  4886. // @event drag: Event
  4887. // Fired continuously during dragging.
  4888. this.fire('drag', e);
  4889. },
  4890. _onUp: function (e) {
  4891. // Ignore simulated events, since we handle both touch and
  4892. // mouse explicitly; otherwise we risk getting duplicates of
  4893. // touch events, see #4315.
  4894. // Also ignore the event if disabled; this happens in IE11
  4895. // under some circumstances, see #3666.
  4896. if (e._simulated || !this._enabled) { return; }
  4897. this.finishDrag();
  4898. },
  4899. finishDrag: function () {
  4900. removeClass(document.body, 'leaflet-dragging');
  4901. if (this._lastTarget) {
  4902. removeClass(this._lastTarget, 'leaflet-drag-target');
  4903. this._lastTarget = null;
  4904. }
  4905. for (var i in MOVE) {
  4906. off(document, MOVE[i], this._onMove, this);
  4907. off(document, END[i], this._onUp, this);
  4908. }
  4909. enableImageDrag();
  4910. enableTextSelection();
  4911. if (this._moved && this._moving) {
  4912. // ensure drag is not fired after dragend
  4913. cancelAnimFrame(this._animRequest);
  4914. // @event dragend: DragEndEvent
  4915. // Fired when the drag ends.
  4916. this.fire('dragend', {
  4917. distance: this._newPos.distanceTo(this._startPos)
  4918. });
  4919. }
  4920. this._moving = false;
  4921. Draggable._dragging = false;
  4922. }
  4923. });
  4924. /*
  4925. * @namespace LineUtil
  4926. *
  4927. * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
  4928. */
  4929. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  4930. // Improves rendering performance dramatically by lessening the number of points to draw.
  4931. // @function simplify(points: Point[], tolerance: Number): Point[]
  4932. // Dramatically reduces the number of points in a polyline while retaining
  4933. // its shape and returns a new array of simplified points, using the
  4934. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  4935. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  4936. // each zoom level and also reducing visual noise. tolerance affects the amount of
  4937. // simplification (lesser value means higher quality but slower and with more points).
  4938. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  4939. function simplify(points, tolerance) {
  4940. if (!tolerance || !points.length) {
  4941. return points.slice();
  4942. }
  4943. var sqTolerance = tolerance * tolerance;
  4944. // stage 1: vertex reduction
  4945. points = _reducePoints(points, sqTolerance);
  4946. // stage 2: Douglas-Peucker simplification
  4947. points = _simplifyDP(points, sqTolerance);
  4948. return points;
  4949. }
  4950. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  4951. // Returns the distance between point `p` and segment `p1` to `p2`.
  4952. function pointToSegmentDistance(p, p1, p2) {
  4953. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  4954. }
  4955. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  4956. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  4957. function closestPointOnSegment(p, p1, p2) {
  4958. return _sqClosestPointOnSegment(p, p1, p2);
  4959. }
  4960. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  4961. function _simplifyDP(points, sqTolerance) {
  4962. var len = points.length,
  4963. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  4964. markers = new ArrayConstructor(len);
  4965. markers[0] = markers[len - 1] = 1;
  4966. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  4967. var i,
  4968. newPoints = [];
  4969. for (i = 0; i < len; i++) {
  4970. if (markers[i]) {
  4971. newPoints.push(points[i]);
  4972. }
  4973. }
  4974. return newPoints;
  4975. }
  4976. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  4977. var maxSqDist = 0,
  4978. index, i, sqDist;
  4979. for (i = first + 1; i <= last - 1; i++) {
  4980. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  4981. if (sqDist > maxSqDist) {
  4982. index = i;
  4983. maxSqDist = sqDist;
  4984. }
  4985. }
  4986. if (maxSqDist > sqTolerance) {
  4987. markers[index] = 1;
  4988. _simplifyDPStep(points, markers, sqTolerance, first, index);
  4989. _simplifyDPStep(points, markers, sqTolerance, index, last);
  4990. }
  4991. }
  4992. // reduce points that are too close to each other to a single point
  4993. function _reducePoints(points, sqTolerance) {
  4994. var reducedPoints = [points[0]];
  4995. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  4996. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  4997. reducedPoints.push(points[i]);
  4998. prev = i;
  4999. }
  5000. }
  5001. if (prev < len - 1) {
  5002. reducedPoints.push(points[len - 1]);
  5003. }
  5004. return reducedPoints;
  5005. }
  5006. var _lastCode;
  5007. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  5008. // Clips the segment a to b by rectangular bounds with the
  5009. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  5010. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  5011. // points that are on the screen or near, increasing performance.
  5012. function clipSegment(a, b, bounds, useLastCode, round) {
  5013. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  5014. codeB = _getBitCode(b, bounds),
  5015. codeOut, p, newCode;
  5016. // save 2nd code to avoid calculating it on the next segment
  5017. _lastCode = codeB;
  5018. while (true) {
  5019. // if a,b is inside the clip window (trivial accept)
  5020. if (!(codeA | codeB)) {
  5021. return [a, b];
  5022. }
  5023. // if a,b is outside the clip window (trivial reject)
  5024. if (codeA & codeB) {
  5025. return false;
  5026. }
  5027. // other cases
  5028. codeOut = codeA || codeB;
  5029. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  5030. newCode = _getBitCode(p, bounds);
  5031. if (codeOut === codeA) {
  5032. a = p;
  5033. codeA = newCode;
  5034. } else {
  5035. b = p;
  5036. codeB = newCode;
  5037. }
  5038. }
  5039. }
  5040. function _getEdgeIntersection(a, b, code, bounds, round) {
  5041. var dx = b.x - a.x,
  5042. dy = b.y - a.y,
  5043. min = bounds.min,
  5044. max = bounds.max,
  5045. x, y;
  5046. if (code & 8) { // top
  5047. x = a.x + dx * (max.y - a.y) / dy;
  5048. y = max.y;
  5049. } else if (code & 4) { // bottom
  5050. x = a.x + dx * (min.y - a.y) / dy;
  5051. y = min.y;
  5052. } else if (code & 2) { // right
  5053. x = max.x;
  5054. y = a.y + dy * (max.x - a.x) / dx;
  5055. } else if (code & 1) { // left
  5056. x = min.x;
  5057. y = a.y + dy * (min.x - a.x) / dx;
  5058. }
  5059. return new Point(x, y, round);
  5060. }
  5061. function _getBitCode(p, bounds) {
  5062. var code = 0;
  5063. if (p.x < bounds.min.x) { // left
  5064. code |= 1;
  5065. } else if (p.x > bounds.max.x) { // right
  5066. code |= 2;
  5067. }
  5068. if (p.y < bounds.min.y) { // bottom
  5069. code |= 4;
  5070. } else if (p.y > bounds.max.y) { // top
  5071. code |= 8;
  5072. }
  5073. return code;
  5074. }
  5075. // square distance (to avoid unnecessary Math.sqrt calls)
  5076. function _sqDist(p1, p2) {
  5077. var dx = p2.x - p1.x,
  5078. dy = p2.y - p1.y;
  5079. return dx * dx + dy * dy;
  5080. }
  5081. // return closest point on segment or distance to that point
  5082. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  5083. var x = p1.x,
  5084. y = p1.y,
  5085. dx = p2.x - x,
  5086. dy = p2.y - y,
  5087. dot = dx * dx + dy * dy,
  5088. t;
  5089. if (dot > 0) {
  5090. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  5091. if (t > 1) {
  5092. x = p2.x;
  5093. y = p2.y;
  5094. } else if (t > 0) {
  5095. x += dx * t;
  5096. y += dy * t;
  5097. }
  5098. }
  5099. dx = p.x - x;
  5100. dy = p.y - y;
  5101. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  5102. }
  5103. // @function isFlat(latlngs: LatLng[]): Boolean
  5104. // Returns true if `latlngs` is a flat array, false is nested.
  5105. function isFlat(latlngs) {
  5106. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  5107. }
  5108. function _flat(latlngs) {
  5109. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  5110. return isFlat(latlngs);
  5111. }
  5112. var LineUtil = (Object.freeze || Object)({
  5113. simplify: simplify,
  5114. pointToSegmentDistance: pointToSegmentDistance,
  5115. closestPointOnSegment: closestPointOnSegment,
  5116. clipSegment: clipSegment,
  5117. _getEdgeIntersection: _getEdgeIntersection,
  5118. _getBitCode: _getBitCode,
  5119. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5120. isFlat: isFlat,
  5121. _flat: _flat
  5122. });
  5123. /*
  5124. * @namespace PolyUtil
  5125. * Various utility functions for polygon geometries.
  5126. */
  5127. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5128. * 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)).
  5129. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5130. * performance. Note that polygon points needs different algorithm for clipping
  5131. * than polyline, so there's a separate method for it.
  5132. */
  5133. function clipPolygon(points, bounds, round) {
  5134. var clippedPoints,
  5135. edges = [1, 4, 2, 8],
  5136. i, j, k,
  5137. a, b,
  5138. len, edge, p;
  5139. for (i = 0, len = points.length; i < len; i++) {
  5140. points[i]._code = _getBitCode(points[i], bounds);
  5141. }
  5142. // for each edge (left, bottom, right, top)
  5143. for (k = 0; k < 4; k++) {
  5144. edge = edges[k];
  5145. clippedPoints = [];
  5146. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5147. a = points[i];
  5148. b = points[j];
  5149. // if a is inside the clip window
  5150. if (!(a._code & edge)) {
  5151. // if b is outside the clip window (a->b goes out of screen)
  5152. if (b._code & edge) {
  5153. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5154. p._code = _getBitCode(p, bounds);
  5155. clippedPoints.push(p);
  5156. }
  5157. clippedPoints.push(a);
  5158. // else if b is inside the clip window (a->b enters the screen)
  5159. } else if (!(b._code & edge)) {
  5160. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5161. p._code = _getBitCode(p, bounds);
  5162. clippedPoints.push(p);
  5163. }
  5164. }
  5165. points = clippedPoints;
  5166. }
  5167. return points;
  5168. }
  5169. var PolyUtil = (Object.freeze || Object)({
  5170. clipPolygon: clipPolygon
  5171. });
  5172. /*
  5173. * @namespace Projection
  5174. * @section
  5175. * Leaflet comes with a set of already defined Projections out of the box:
  5176. *
  5177. * @projection L.Projection.LonLat
  5178. *
  5179. * Equirectangular, or Plate Carree projection — the most simple projection,
  5180. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5181. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5182. * `EPSG:4326` and `Simple` CRS.
  5183. */
  5184. var LonLat = {
  5185. project: function (latlng) {
  5186. return new Point(latlng.lng, latlng.lat);
  5187. },
  5188. unproject: function (point) {
  5189. return new LatLng(point.y, point.x);
  5190. },
  5191. bounds: new Bounds([-180, -90], [180, 90])
  5192. };
  5193. /*
  5194. * @namespace Projection
  5195. * @projection L.Projection.Mercator
  5196. *
  5197. * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.
  5198. */
  5199. var Mercator = {
  5200. R: 6378137,
  5201. R_MINOR: 6356752.314245179,
  5202. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5203. project: function (latlng) {
  5204. var d = Math.PI / 180,
  5205. r = this.R,
  5206. y = latlng.lat * d,
  5207. tmp = this.R_MINOR / r,
  5208. e = Math.sqrt(1 - tmp * tmp),
  5209. con = e * Math.sin(y);
  5210. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5211. y = -r * Math.log(Math.max(ts, 1E-10));
  5212. return new Point(latlng.lng * d * r, y);
  5213. },
  5214. unproject: function (point) {
  5215. var d = 180 / Math.PI,
  5216. r = this.R,
  5217. tmp = this.R_MINOR / r,
  5218. e = Math.sqrt(1 - tmp * tmp),
  5219. ts = Math.exp(-point.y / r),
  5220. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5221. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5222. con = e * Math.sin(phi);
  5223. con = Math.pow((1 - con) / (1 + con), e / 2);
  5224. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5225. phi += dphi;
  5226. }
  5227. return new LatLng(phi * d, point.x * d / r);
  5228. }
  5229. };
  5230. /*
  5231. * @class Projection
  5232. * An object with methods for projecting geographical coordinates of the world onto
  5233. * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).
  5234. * @property bounds: Bounds
  5235. * The bounds (specified in CRS units) where the projection is valid
  5236. * @method project(latlng: LatLng): Point
  5237. * Projects geographical coordinates into a 2D point.
  5238. * Only accepts actual `L.LatLng` instances, not arrays.
  5239. * @method unproject(point: Point): LatLng
  5240. * The inverse of `project`. Projects a 2D point into a geographical location.
  5241. * Only accepts actual `L.Point` instances, not arrays.
  5242. * Note that the projection instances do not inherit from Leafet's `Class` object,
  5243. * and can't be instantiated. Also, new classes can't inherit from them,
  5244. * and methods can't be added to them with the `include` function.
  5245. */
  5246. var index = (Object.freeze || Object)({
  5247. LonLat: LonLat,
  5248. Mercator: Mercator,
  5249. SphericalMercator: SphericalMercator
  5250. });
  5251. /*
  5252. * @namespace CRS
  5253. * @crs L.CRS.EPSG3395
  5254. *
  5255. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5256. */
  5257. var EPSG3395 = extend({}, Earth, {
  5258. code: 'EPSG:3395',
  5259. projection: Mercator,
  5260. transformation: (function () {
  5261. var scale = 0.5 / (Math.PI * Mercator.R);
  5262. return toTransformation(scale, 0.5, -scale, 0.5);
  5263. }())
  5264. });
  5265. /*
  5266. * @namespace CRS
  5267. * @crs L.CRS.EPSG4326
  5268. *
  5269. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5270. *
  5271. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5272. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5273. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5274. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5275. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5276. */
  5277. var EPSG4326 = extend({}, Earth, {
  5278. code: 'EPSG:4326',
  5279. projection: LonLat,
  5280. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5281. });
  5282. /*
  5283. * @namespace CRS
  5284. * @crs L.CRS.Simple
  5285. *
  5286. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5287. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5288. * axis should still be inverted (going from bottom to top). `distance()` returns
  5289. * simple euclidean distance.
  5290. */
  5291. var Simple = extend({}, CRS, {
  5292. projection: LonLat,
  5293. transformation: toTransformation(1, 0, -1, 0),
  5294. scale: function (zoom) {
  5295. return Math.pow(2, zoom);
  5296. },
  5297. zoom: function (scale) {
  5298. return Math.log(scale) / Math.LN2;
  5299. },
  5300. distance: function (latlng1, latlng2) {
  5301. var dx = latlng2.lng - latlng1.lng,
  5302. dy = latlng2.lat - latlng1.lat;
  5303. return Math.sqrt(dx * dx + dy * dy);
  5304. },
  5305. infinite: true
  5306. });
  5307. CRS.Earth = Earth;
  5308. CRS.EPSG3395 = EPSG3395;
  5309. CRS.EPSG3857 = EPSG3857;
  5310. CRS.EPSG900913 = EPSG900913;
  5311. CRS.EPSG4326 = EPSG4326;
  5312. CRS.Simple = Simple;
  5313. /*
  5314. * @class Layer
  5315. * @inherits Evented
  5316. * @aka L.Layer
  5317. * @aka ILayer
  5318. *
  5319. * A set of methods from the Layer base class that all Leaflet layers use.
  5320. * Inherits all methods, options and events from `L.Evented`.
  5321. *
  5322. * @example
  5323. *
  5324. * ```js
  5325. * var layer = L.marker(latlng).addTo(map);
  5326. * layer.addTo(map);
  5327. * layer.remove();
  5328. * ```
  5329. *
  5330. * @event add: Event
  5331. * Fired after the layer is added to a map
  5332. *
  5333. * @event remove: Event
  5334. * Fired after the layer is removed from a map
  5335. */
  5336. var Layer = Evented.extend({
  5337. // Classes extending `L.Layer` will inherit the following options:
  5338. options: {
  5339. // @option pane: String = 'overlayPane'
  5340. // 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.
  5341. pane: 'overlayPane',
  5342. // @option attribution: String = null
  5343. // 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.
  5344. attribution: null,
  5345. bubblingMouseEvents: true
  5346. },
  5347. /* @section
  5348. * Classes extending `L.Layer` will inherit the following methods:
  5349. *
  5350. * @method addTo(map: Map|LayerGroup): this
  5351. * Adds the layer to the given map or layer group.
  5352. */
  5353. addTo: function (map) {
  5354. map.addLayer(this);
  5355. return this;
  5356. },
  5357. // @method remove: this
  5358. // Removes the layer from the map it is currently active on.
  5359. remove: function () {
  5360. return this.removeFrom(this._map || this._mapToAdd);
  5361. },
  5362. // @method removeFrom(map: Map): this
  5363. // Removes the layer from the given map
  5364. removeFrom: function (obj) {
  5365. if (obj) {
  5366. obj.removeLayer(this);
  5367. }
  5368. return this;
  5369. },
  5370. // @method getPane(name? : String): HTMLElement
  5371. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5372. getPane: function (name) {
  5373. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5374. },
  5375. addInteractiveTarget: function (targetEl) {
  5376. this._map._targets[stamp(targetEl)] = this;
  5377. return this;
  5378. },
  5379. removeInteractiveTarget: function (targetEl) {
  5380. delete this._map._targets[stamp(targetEl)];
  5381. return this;
  5382. },
  5383. // @method getAttribution: String
  5384. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5385. getAttribution: function () {
  5386. return this.options.attribution;
  5387. },
  5388. _layerAdd: function (e) {
  5389. var map = e.target;
  5390. // check in case layer gets added and then removed before the map is ready
  5391. if (!map.hasLayer(this)) { return; }
  5392. this._map = map;
  5393. this._zoomAnimated = map._zoomAnimated;
  5394. if (this.getEvents) {
  5395. var events = this.getEvents();
  5396. map.on(events, this);
  5397. this.once('remove', function () {
  5398. map.off(events, this);
  5399. }, this);
  5400. }
  5401. this.onAdd(map);
  5402. if (this.getAttribution && map.attributionControl) {
  5403. map.attributionControl.addAttribution(this.getAttribution());
  5404. }
  5405. this.fire('add');
  5406. map.fire('layeradd', {layer: this});
  5407. }
  5408. });
  5409. /* @section Extension methods
  5410. * @uninheritable
  5411. *
  5412. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5413. *
  5414. * @method onAdd(map: Map): this
  5415. * 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).
  5416. *
  5417. * @method onRemove(map: Map): this
  5418. * 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).
  5419. *
  5420. * @method getEvents(): Object
  5421. * 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.
  5422. *
  5423. * @method getAttribution(): String
  5424. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5425. *
  5426. * @method beforeAdd(map: Map): this
  5427. * 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.
  5428. */
  5429. /* @namespace Map
  5430. * @section Layer events
  5431. *
  5432. * @event layeradd: LayerEvent
  5433. * Fired when a new layer is added to the map.
  5434. *
  5435. * @event layerremove: LayerEvent
  5436. * Fired when some layer is removed from the map
  5437. *
  5438. * @section Methods for Layers and Controls
  5439. */
  5440. Map.include({
  5441. // @method addLayer(layer: Layer): this
  5442. // Adds the given layer to the map
  5443. addLayer: function (layer) {
  5444. if (!layer._layerAdd) {
  5445. throw new Error('The provided object is not a Layer.');
  5446. }
  5447. var id = stamp(layer);
  5448. if (this._layers[id]) { return this; }
  5449. this._layers[id] = layer;
  5450. layer._mapToAdd = this;
  5451. if (layer.beforeAdd) {
  5452. layer.beforeAdd(this);
  5453. }
  5454. this.whenReady(layer._layerAdd, layer);
  5455. return this;
  5456. },
  5457. // @method removeLayer(layer: Layer): this
  5458. // Removes the given layer from the map.
  5459. removeLayer: function (layer) {
  5460. var id = stamp(layer);
  5461. if (!this._layers[id]) { return this; }
  5462. if (this._loaded) {
  5463. layer.onRemove(this);
  5464. }
  5465. if (layer.getAttribution && this.attributionControl) {
  5466. this.attributionControl.removeAttribution(layer.getAttribution());
  5467. }
  5468. delete this._layers[id];
  5469. if (this._loaded) {
  5470. this.fire('layerremove', {layer: layer});
  5471. layer.fire('remove');
  5472. }
  5473. layer._map = layer._mapToAdd = null;
  5474. return this;
  5475. },
  5476. // @method hasLayer(layer: Layer): Boolean
  5477. // Returns `true` if the given layer is currently added to the map
  5478. hasLayer: function (layer) {
  5479. return !!layer && (stamp(layer) in this._layers);
  5480. },
  5481. /* @method eachLayer(fn: Function, context?: Object): this
  5482. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5483. * ```
  5484. * map.eachLayer(function(layer){
  5485. * layer.bindPopup('Hello');
  5486. * });
  5487. * ```
  5488. */
  5489. eachLayer: function (method, context) {
  5490. for (var i in this._layers) {
  5491. method.call(context, this._layers[i]);
  5492. }
  5493. return this;
  5494. },
  5495. _addLayers: function (layers) {
  5496. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5497. for (var i = 0, len = layers.length; i < len; i++) {
  5498. this.addLayer(layers[i]);
  5499. }
  5500. },
  5501. _addZoomLimit: function (layer) {
  5502. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5503. this._zoomBoundLayers[stamp(layer)] = layer;
  5504. this._updateZoomLevels();
  5505. }
  5506. },
  5507. _removeZoomLimit: function (layer) {
  5508. var id = stamp(layer);
  5509. if (this._zoomBoundLayers[id]) {
  5510. delete this._zoomBoundLayers[id];
  5511. this._updateZoomLevels();
  5512. }
  5513. },
  5514. _updateZoomLevels: function () {
  5515. var minZoom = Infinity,
  5516. maxZoom = -Infinity,
  5517. oldZoomSpan = this._getZoomSpan();
  5518. for (var i in this._zoomBoundLayers) {
  5519. var options = this._zoomBoundLayers[i].options;
  5520. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5521. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5522. }
  5523. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5524. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5525. // @section Map state change events
  5526. // @event zoomlevelschange: Event
  5527. // Fired when the number of zoomlevels on the map is changed due
  5528. // to adding or removing a layer.
  5529. if (oldZoomSpan !== this._getZoomSpan()) {
  5530. this.fire('zoomlevelschange');
  5531. }
  5532. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5533. this.setZoom(this._layersMaxZoom);
  5534. }
  5535. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5536. this.setZoom(this._layersMinZoom);
  5537. }
  5538. }
  5539. });
  5540. /*
  5541. * @class LayerGroup
  5542. * @aka L.LayerGroup
  5543. * @inherits Layer
  5544. *
  5545. * Used to group several layers and handle them as one. If you add it to the map,
  5546. * any layers added or removed from the group will be added/removed on the map as
  5547. * well. Extends `Layer`.
  5548. *
  5549. * @example
  5550. *
  5551. * ```js
  5552. * L.layerGroup([marker1, marker2])
  5553. * .addLayer(polyline)
  5554. * .addTo(map);
  5555. * ```
  5556. */
  5557. var LayerGroup = Layer.extend({
  5558. initialize: function (layers, options) {
  5559. setOptions(this, options);
  5560. this._layers = {};
  5561. var i, len;
  5562. if (layers) {
  5563. for (i = 0, len = layers.length; i < len; i++) {
  5564. this.addLayer(layers[i]);
  5565. }
  5566. }
  5567. },
  5568. // @method addLayer(layer: Layer): this
  5569. // Adds the given layer to the group.
  5570. addLayer: function (layer) {
  5571. var id = this.getLayerId(layer);
  5572. this._layers[id] = layer;
  5573. if (this._map) {
  5574. this._map.addLayer(layer);
  5575. }
  5576. return this;
  5577. },
  5578. // @method removeLayer(layer: Layer): this
  5579. // Removes the given layer from the group.
  5580. // @alternative
  5581. // @method removeLayer(id: Number): this
  5582. // Removes the layer with the given internal ID from the group.
  5583. removeLayer: function (layer) {
  5584. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5585. if (this._map && this._layers[id]) {
  5586. this._map.removeLayer(this._layers[id]);
  5587. }
  5588. delete this._layers[id];
  5589. return this;
  5590. },
  5591. // @method hasLayer(layer: Layer): Boolean
  5592. // Returns `true` if the given layer is currently added to the group.
  5593. // @alternative
  5594. // @method hasLayer(id: Number): Boolean
  5595. // Returns `true` if the given internal ID is currently added to the group.
  5596. hasLayer: function (layer) {
  5597. return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
  5598. },
  5599. // @method clearLayers(): this
  5600. // Removes all the layers from the group.
  5601. clearLayers: function () {
  5602. return this.eachLayer(this.removeLayer, this);
  5603. },
  5604. // @method invoke(methodName: String, …): this
  5605. // Calls `methodName` on every layer contained in this group, passing any
  5606. // additional parameters. Has no effect if the layers contained do not
  5607. // implement `methodName`.
  5608. invoke: function (methodName) {
  5609. var args = Array.prototype.slice.call(arguments, 1),
  5610. i, layer;
  5611. for (i in this._layers) {
  5612. layer = this._layers[i];
  5613. if (layer[methodName]) {
  5614. layer[methodName].apply(layer, args);
  5615. }
  5616. }
  5617. return this;
  5618. },
  5619. onAdd: function (map) {
  5620. this.eachLayer(map.addLayer, map);
  5621. },
  5622. onRemove: function (map) {
  5623. this.eachLayer(map.removeLayer, map);
  5624. },
  5625. // @method eachLayer(fn: Function, context?: Object): this
  5626. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5627. // ```js
  5628. // group.eachLayer(function (layer) {
  5629. // layer.bindPopup('Hello');
  5630. // });
  5631. // ```
  5632. eachLayer: function (method, context) {
  5633. for (var i in this._layers) {
  5634. method.call(context, this._layers[i]);
  5635. }
  5636. return this;
  5637. },
  5638. // @method getLayer(id: Number): Layer
  5639. // Returns the layer with the given internal ID.
  5640. getLayer: function (id) {
  5641. return this._layers[id];
  5642. },
  5643. // @method getLayers(): Layer[]
  5644. // Returns an array of all the layers added to the group.
  5645. getLayers: function () {
  5646. var layers = [];
  5647. this.eachLayer(layers.push, layers);
  5648. return layers;
  5649. },
  5650. // @method setZIndex(zIndex: Number): this
  5651. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5652. setZIndex: function (zIndex) {
  5653. return this.invoke('setZIndex', zIndex);
  5654. },
  5655. // @method getLayerId(layer: Layer): Number
  5656. // Returns the internal ID for a layer
  5657. getLayerId: function (layer) {
  5658. return stamp(layer);
  5659. }
  5660. });
  5661. // @factory L.layerGroup(layers?: Layer[], options?: Object)
  5662. // Create a layer group, optionally given an initial set of layers and an `options` object.
  5663. var layerGroup = function (layers, options) {
  5664. return new LayerGroup(layers, options);
  5665. };
  5666. /*
  5667. * @class FeatureGroup
  5668. * @aka L.FeatureGroup
  5669. * @inherits LayerGroup
  5670. *
  5671. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5672. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5673. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5674. * handler, it will handle events from any of the layers. This includes mouse events
  5675. * and custom events.
  5676. * * Has `layeradd` and `layerremove` events
  5677. *
  5678. * @example
  5679. *
  5680. * ```js
  5681. * L.featureGroup([marker1, marker2, polyline])
  5682. * .bindPopup('Hello world!')
  5683. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5684. * .addTo(map);
  5685. * ```
  5686. */
  5687. var FeatureGroup = LayerGroup.extend({
  5688. addLayer: function (layer) {
  5689. if (this.hasLayer(layer)) {
  5690. return this;
  5691. }
  5692. layer.addEventParent(this);
  5693. LayerGroup.prototype.addLayer.call(this, layer);
  5694. // @event layeradd: LayerEvent
  5695. // Fired when a layer is added to this `FeatureGroup`
  5696. return this.fire('layeradd', {layer: layer});
  5697. },
  5698. removeLayer: function (layer) {
  5699. if (!this.hasLayer(layer)) {
  5700. return this;
  5701. }
  5702. if (layer in this._layers) {
  5703. layer = this._layers[layer];
  5704. }
  5705. layer.removeEventParent(this);
  5706. LayerGroup.prototype.removeLayer.call(this, layer);
  5707. // @event layerremove: LayerEvent
  5708. // Fired when a layer is removed from this `FeatureGroup`
  5709. return this.fire('layerremove', {layer: layer});
  5710. },
  5711. // @method setStyle(style: Path options): this
  5712. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5713. setStyle: function (style) {
  5714. return this.invoke('setStyle', style);
  5715. },
  5716. // @method bringToFront(): this
  5717. // Brings the layer group to the top of all other layers
  5718. bringToFront: function () {
  5719. return this.invoke('bringToFront');
  5720. },
  5721. // @method bringToBack(): this
  5722. // Brings the layer group to the back of all other layers
  5723. bringToBack: function () {
  5724. return this.invoke('bringToBack');
  5725. },
  5726. // @method getBounds(): LatLngBounds
  5727. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5728. getBounds: function () {
  5729. var bounds = new LatLngBounds();
  5730. for (var id in this._layers) {
  5731. var layer = this._layers[id];
  5732. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5733. }
  5734. return bounds;
  5735. }
  5736. });
  5737. // @factory L.featureGroup(layers: Layer[])
  5738. // Create a feature group, optionally given an initial set of layers.
  5739. var featureGroup = function (layers) {
  5740. return new FeatureGroup(layers);
  5741. };
  5742. /*
  5743. * @class Icon
  5744. * @aka L.Icon
  5745. *
  5746. * Represents an icon to provide when creating a marker.
  5747. *
  5748. * @example
  5749. *
  5750. * ```js
  5751. * var myIcon = L.icon({
  5752. * iconUrl: 'my-icon.png',
  5753. * iconRetinaUrl: 'my-icon@2x.png',
  5754. * iconSize: [38, 95],
  5755. * iconAnchor: [22, 94],
  5756. * popupAnchor: [-3, -76],
  5757. * shadowUrl: 'my-icon-shadow.png',
  5758. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5759. * shadowSize: [68, 95],
  5760. * shadowAnchor: [22, 94]
  5761. * });
  5762. *
  5763. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5764. * ```
  5765. *
  5766. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5767. *
  5768. */
  5769. var Icon = Class.extend({
  5770. /* @section
  5771. * @aka Icon options
  5772. *
  5773. * @option iconUrl: String = null
  5774. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5775. *
  5776. * @option iconRetinaUrl: String = null
  5777. * The URL to a retina sized version of the icon image (absolute or relative to your
  5778. * script path). Used for Retina screen devices.
  5779. *
  5780. * @option iconSize: Point = null
  5781. * Size of the icon image in pixels.
  5782. *
  5783. * @option iconAnchor: Point = null
  5784. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5785. * will be aligned so that this point is at the marker's geographical location. Centered
  5786. * by default if size is specified, also can be set in CSS with negative margins.
  5787. *
  5788. * @option popupAnchor: Point = [0, 0]
  5789. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5790. *
  5791. * @option tooltipAnchor: Point = [0, 0]
  5792. * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
  5793. *
  5794. * @option shadowUrl: String = null
  5795. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  5796. *
  5797. * @option shadowRetinaUrl: String = null
  5798. *
  5799. * @option shadowSize: Point = null
  5800. * Size of the shadow image in pixels.
  5801. *
  5802. * @option shadowAnchor: Point = null
  5803. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  5804. * as iconAnchor if not specified).
  5805. *
  5806. * @option className: String = ''
  5807. * A custom class name to assign to both icon and shadow images. Empty by default.
  5808. */
  5809. options: {
  5810. popupAnchor: [0, 0],
  5811. tooltipAnchor: [0, 0]
  5812. },
  5813. initialize: function (options) {
  5814. setOptions(this, options);
  5815. },
  5816. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  5817. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  5818. // styled according to the options.
  5819. createIcon: function (oldIcon) {
  5820. return this._createIcon('icon', oldIcon);
  5821. },
  5822. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  5823. // As `createIcon`, but for the shadow beneath it.
  5824. createShadow: function (oldIcon) {
  5825. return this._createIcon('shadow', oldIcon);
  5826. },
  5827. _createIcon: function (name, oldIcon) {
  5828. var src = this._getIconUrl(name);
  5829. if (!src) {
  5830. if (name === 'icon') {
  5831. throw new Error('iconUrl not set in Icon options (see the docs).');
  5832. }
  5833. return null;
  5834. }
  5835. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  5836. this._setIconStyles(img, name);
  5837. return img;
  5838. },
  5839. _setIconStyles: function (img, name) {
  5840. var options = this.options;
  5841. var sizeOption = options[name + 'Size'];
  5842. if (typeof sizeOption === 'number') {
  5843. sizeOption = [sizeOption, sizeOption];
  5844. }
  5845. var size = toPoint(sizeOption),
  5846. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  5847. size && size.divideBy(2, true));
  5848. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  5849. if (anchor) {
  5850. img.style.marginLeft = (-anchor.x) + 'px';
  5851. img.style.marginTop = (-anchor.y) + 'px';
  5852. }
  5853. if (size) {
  5854. img.style.width = size.x + 'px';
  5855. img.style.height = size.y + 'px';
  5856. }
  5857. },
  5858. _createImg: function (src, el) {
  5859. el = el || document.createElement('img');
  5860. el.src = src;
  5861. return el;
  5862. },
  5863. _getIconUrl: function (name) {
  5864. return retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  5865. }
  5866. });
  5867. // @factory L.icon(options: Icon options)
  5868. // Creates an icon instance with the given options.
  5869. function icon(options) {
  5870. return new Icon(options);
  5871. }
  5872. /*
  5873. * @miniclass Icon.Default (Icon)
  5874. * @aka L.Icon.Default
  5875. * @section
  5876. *
  5877. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  5878. * no icon is specified. Points to the blue marker image distributed with Leaflet
  5879. * releases.
  5880. *
  5881. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  5882. * (which is a set of `Icon options`).
  5883. *
  5884. * If you want to _completely_ replace the default icon, override the
  5885. * `L.Marker.prototype.options.icon` with your own icon instead.
  5886. */
  5887. var IconDefault = Icon.extend({
  5888. options: {
  5889. iconUrl: 'marker-icon.png',
  5890. iconRetinaUrl: 'marker-icon-2x.png',
  5891. shadowUrl: 'marker-shadow.png',
  5892. iconSize: [25, 41],
  5893. iconAnchor: [12, 41],
  5894. popupAnchor: [1, -34],
  5895. tooltipAnchor: [16, -28],
  5896. shadowSize: [41, 41]
  5897. },
  5898. _getIconUrl: function (name) {
  5899. if (!IconDefault.imagePath) { // Deprecated, backwards-compatibility only
  5900. IconDefault.imagePath = this._detectIconPath();
  5901. }
  5902. // @option imagePath: String
  5903. // `Icon.Default` will try to auto-detect the location of the
  5904. // blue icon images. If you are placing these images in a non-standard
  5905. // way, set this option to point to the right path.
  5906. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  5907. },
  5908. _detectIconPath: function () {
  5909. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  5910. var path = getStyle(el, 'background-image') ||
  5911. getStyle(el, 'backgroundImage'); // IE8
  5912. document.body.removeChild(el);
  5913. if (path === null || path.indexOf('url') !== 0) {
  5914. path = '';
  5915. } else {
  5916. path = path.replace(/^url\(["']?/, '').replace(/marker-icon\.png["']?\)$/, '');
  5917. }
  5918. return path;
  5919. }
  5920. });
  5921. /*
  5922. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  5923. */
  5924. /* @namespace Marker
  5925. * @section Interaction handlers
  5926. *
  5927. * 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:
  5928. *
  5929. * ```js
  5930. * marker.dragging.disable();
  5931. * ```
  5932. *
  5933. * @property dragging: Handler
  5934. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  5935. */
  5936. var MarkerDrag = Handler.extend({
  5937. initialize: function (marker) {
  5938. this._marker = marker;
  5939. },
  5940. addHooks: function () {
  5941. var icon = this._marker._icon;
  5942. if (!this._draggable) {
  5943. this._draggable = new Draggable(icon, icon, true);
  5944. }
  5945. this._draggable.on({
  5946. dragstart: this._onDragStart,
  5947. predrag: this._onPreDrag,
  5948. drag: this._onDrag,
  5949. dragend: this._onDragEnd
  5950. }, this).enable();
  5951. addClass(icon, 'leaflet-marker-draggable');
  5952. },
  5953. removeHooks: function () {
  5954. this._draggable.off({
  5955. dragstart: this._onDragStart,
  5956. predrag: this._onPreDrag,
  5957. drag: this._onDrag,
  5958. dragend: this._onDragEnd
  5959. }, this).disable();
  5960. if (this._marker._icon) {
  5961. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  5962. }
  5963. },
  5964. moved: function () {
  5965. return this._draggable && this._draggable._moved;
  5966. },
  5967. _adjustPan: function (e) {
  5968. var marker = this._marker,
  5969. map = marker._map,
  5970. speed = this._marker.options.autoPanSpeed,
  5971. padding = this._marker.options.autoPanPadding,
  5972. iconPos = getPosition(marker._icon),
  5973. bounds = map.getPixelBounds(),
  5974. origin = map.getPixelOrigin();
  5975. var panBounds = toBounds(
  5976. bounds.min._subtract(origin).add(padding),
  5977. bounds.max._subtract(origin).subtract(padding)
  5978. );
  5979. if (!panBounds.contains(iconPos)) {
  5980. // Compute incremental movement
  5981. var movement = toPoint(
  5982. (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
  5983. (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
  5984. (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
  5985. (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
  5986. ).multiplyBy(speed);
  5987. map.panBy(movement, {animate: false});
  5988. this._draggable._newPos._add(movement);
  5989. this._draggable._startPos._add(movement);
  5990. setPosition(marker._icon, this._draggable._newPos);
  5991. this._onDrag(e);
  5992. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  5993. }
  5994. },
  5995. _onDragStart: function () {
  5996. // @section Dragging events
  5997. // @event dragstart: Event
  5998. // Fired when the user starts dragging the marker.
  5999. // @event movestart: Event
  6000. // Fired when the marker starts moving (because of dragging).
  6001. this._oldLatLng = this._marker.getLatLng();
  6002. this._marker
  6003. .closePopup()
  6004. .fire('movestart')
  6005. .fire('dragstart');
  6006. },
  6007. _onPreDrag: function (e) {
  6008. if (this._marker.options.autoPan) {
  6009. cancelAnimFrame(this._panRequest);
  6010. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  6011. }
  6012. },
  6013. _onDrag: function (e) {
  6014. var marker = this._marker,
  6015. shadow = marker._shadow,
  6016. iconPos = getPosition(marker._icon),
  6017. latlng = marker._map.layerPointToLatLng(iconPos);
  6018. // update shadow position
  6019. if (shadow) {
  6020. setPosition(shadow, iconPos);
  6021. }
  6022. marker._latlng = latlng;
  6023. e.latlng = latlng;
  6024. e.oldLatLng = this._oldLatLng;
  6025. // @event drag: Event
  6026. // Fired repeatedly while the user drags the marker.
  6027. marker
  6028. .fire('move', e)
  6029. .fire('drag', e);
  6030. },
  6031. _onDragEnd: function (e) {
  6032. // @event dragend: DragEndEvent
  6033. // Fired when the user stops dragging the marker.
  6034. cancelAnimFrame(this._panRequest);
  6035. // @event moveend: Event
  6036. // Fired when the marker stops moving (because of dragging).
  6037. delete this._oldLatLng;
  6038. this._marker
  6039. .fire('moveend')
  6040. .fire('dragend', e);
  6041. }
  6042. });
  6043. /*
  6044. * @class Marker
  6045. * @inherits Interactive layer
  6046. * @aka L.Marker
  6047. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  6048. *
  6049. * @example
  6050. *
  6051. * ```js
  6052. * L.marker([50.5, 30.5]).addTo(map);
  6053. * ```
  6054. */
  6055. var Marker = Layer.extend({
  6056. // @section
  6057. // @aka Marker options
  6058. options: {
  6059. // @option icon: Icon = *
  6060. // Icon instance to use for rendering the marker.
  6061. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  6062. // If not specified, a common instance of `L.Icon.Default` is used.
  6063. icon: new IconDefault(),
  6064. // Option inherited from "Interactive layer" abstract class
  6065. interactive: true,
  6066. // @option keyboard: Boolean = true
  6067. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  6068. keyboard: true,
  6069. // @option title: String = ''
  6070. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  6071. title: '',
  6072. // @option alt: String = ''
  6073. // Text for the `alt` attribute of the icon image (useful for accessibility).
  6074. alt: '',
  6075. // @option zIndexOffset: Number = 0
  6076. // 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).
  6077. zIndexOffset: 0,
  6078. // @option opacity: Number = 1.0
  6079. // The opacity of the marker.
  6080. opacity: 1,
  6081. // @option riseOnHover: Boolean = false
  6082. // If `true`, the marker will get on top of others when you hover the mouse over it.
  6083. riseOnHover: false,
  6084. // @option riseOffset: Number = 250
  6085. // The z-index offset used for the `riseOnHover` feature.
  6086. riseOffset: 250,
  6087. // @option pane: String = 'markerPane'
  6088. // `Map pane` where the markers icon will be added.
  6089. pane: 'markerPane',
  6090. // @option pane: String = 'shadowPane'
  6091. // `Map pane` where the markers shadow will be added.
  6092. shadowPane: 'shadowPane',
  6093. // @option bubblingMouseEvents: Boolean = false
  6094. // When `true`, a mouse event on this marker will trigger the same event on the map
  6095. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6096. bubblingMouseEvents: false,
  6097. // @section Draggable marker options
  6098. // @option draggable: Boolean = false
  6099. // Whether the marker is draggable with mouse/touch or not.
  6100. draggable: false,
  6101. // @option autoPan: Boolean = false
  6102. // Whether to pan the map when dragging this marker near its edge or not.
  6103. autoPan: false,
  6104. // @option autoPanPadding: Point = Point(50, 50)
  6105. // Distance (in pixels to the left/right and to the top/bottom) of the
  6106. // map edge to start panning the map.
  6107. autoPanPadding: [50, 50],
  6108. // @option autoPanSpeed: Number = 10
  6109. // Number of pixels the map should pan by.
  6110. autoPanSpeed: 10
  6111. },
  6112. /* @section
  6113. *
  6114. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  6115. */
  6116. initialize: function (latlng, options) {
  6117. setOptions(this, options);
  6118. this._latlng = toLatLng(latlng);
  6119. },
  6120. onAdd: function (map) {
  6121. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  6122. if (this._zoomAnimated) {
  6123. map.on('zoomanim', this._animateZoom, this);
  6124. }
  6125. this._initIcon();
  6126. this.update();
  6127. },
  6128. onRemove: function (map) {
  6129. if (this.dragging && this.dragging.enabled()) {
  6130. this.options.draggable = true;
  6131. this.dragging.removeHooks();
  6132. }
  6133. delete this.dragging;
  6134. if (this._zoomAnimated) {
  6135. map.off('zoomanim', this._animateZoom, this);
  6136. }
  6137. this._removeIcon();
  6138. this._removeShadow();
  6139. },
  6140. getEvents: function () {
  6141. return {
  6142. zoom: this.update,
  6143. viewreset: this.update
  6144. };
  6145. },
  6146. // @method getLatLng: LatLng
  6147. // Returns the current geographical position of the marker.
  6148. getLatLng: function () {
  6149. return this._latlng;
  6150. },
  6151. // @method setLatLng(latlng: LatLng): this
  6152. // Changes the marker position to the given point.
  6153. setLatLng: function (latlng) {
  6154. var oldLatLng = this._latlng;
  6155. this._latlng = toLatLng(latlng);
  6156. this.update();
  6157. // @event move: Event
  6158. // 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`.
  6159. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6160. },
  6161. // @method setZIndexOffset(offset: Number): this
  6162. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6163. setZIndexOffset: function (offset) {
  6164. this.options.zIndexOffset = offset;
  6165. return this.update();
  6166. },
  6167. // @method getIcon: Icon
  6168. // Returns the current icon used by the marker
  6169. getIcon: function () {
  6170. return this.options.icon;
  6171. },
  6172. // @method setIcon(icon: Icon): this
  6173. // Changes the marker icon.
  6174. setIcon: function (icon) {
  6175. this.options.icon = icon;
  6176. if (this._map) {
  6177. this._initIcon();
  6178. this.update();
  6179. }
  6180. if (this._popup) {
  6181. this.bindPopup(this._popup, this._popup.options);
  6182. }
  6183. return this;
  6184. },
  6185. getElement: function () {
  6186. return this._icon;
  6187. },
  6188. update: function () {
  6189. if (this._icon && this._map) {
  6190. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6191. this._setPos(pos);
  6192. }
  6193. return this;
  6194. },
  6195. _initIcon: function () {
  6196. var options = this.options,
  6197. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6198. var icon = options.icon.createIcon(this._icon),
  6199. addIcon = false;
  6200. // if we're not reusing the icon, remove the old one and init new one
  6201. if (icon !== this._icon) {
  6202. if (this._icon) {
  6203. this._removeIcon();
  6204. }
  6205. addIcon = true;
  6206. if (options.title) {
  6207. icon.title = options.title;
  6208. }
  6209. if (icon.tagName === 'IMG') {
  6210. icon.alt = options.alt || '';
  6211. }
  6212. }
  6213. addClass(icon, classToAdd);
  6214. if (options.keyboard) {
  6215. icon.tabIndex = '0';
  6216. }
  6217. this._icon = icon;
  6218. if (options.riseOnHover) {
  6219. this.on({
  6220. mouseover: this._bringToFront,
  6221. mouseout: this._resetZIndex
  6222. });
  6223. }
  6224. var newShadow = options.icon.createShadow(this._shadow),
  6225. addShadow = false;
  6226. if (newShadow !== this._shadow) {
  6227. this._removeShadow();
  6228. addShadow = true;
  6229. }
  6230. if (newShadow) {
  6231. addClass(newShadow, classToAdd);
  6232. newShadow.alt = '';
  6233. }
  6234. this._shadow = newShadow;
  6235. if (options.opacity < 1) {
  6236. this._updateOpacity();
  6237. }
  6238. if (addIcon) {
  6239. this.getPane().appendChild(this._icon);
  6240. }
  6241. this._initInteraction();
  6242. if (newShadow && addShadow) {
  6243. this.getPane(options.shadowPane).appendChild(this._shadow);
  6244. }
  6245. },
  6246. _removeIcon: function () {
  6247. if (this.options.riseOnHover) {
  6248. this.off({
  6249. mouseover: this._bringToFront,
  6250. mouseout: this._resetZIndex
  6251. });
  6252. }
  6253. remove(this._icon);
  6254. this.removeInteractiveTarget(this._icon);
  6255. this._icon = null;
  6256. },
  6257. _removeShadow: function () {
  6258. if (this._shadow) {
  6259. remove(this._shadow);
  6260. }
  6261. this._shadow = null;
  6262. },
  6263. _setPos: function (pos) {
  6264. if (this._icon) {
  6265. setPosition(this._icon, pos);
  6266. }
  6267. if (this._shadow) {
  6268. setPosition(this._shadow, pos);
  6269. }
  6270. this._zIndex = pos.y + this.options.zIndexOffset;
  6271. this._resetZIndex();
  6272. },
  6273. _updateZIndex: function (offset) {
  6274. if (this._icon) {
  6275. this._icon.style.zIndex = this._zIndex + offset;
  6276. }
  6277. },
  6278. _animateZoom: function (opt) {
  6279. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6280. this._setPos(pos);
  6281. },
  6282. _initInteraction: function () {
  6283. if (!this.options.interactive) { return; }
  6284. addClass(this._icon, 'leaflet-interactive');
  6285. this.addInteractiveTarget(this._icon);
  6286. if (MarkerDrag) {
  6287. var draggable = this.options.draggable;
  6288. if (this.dragging) {
  6289. draggable = this.dragging.enabled();
  6290. this.dragging.disable();
  6291. }
  6292. this.dragging = new MarkerDrag(this);
  6293. if (draggable) {
  6294. this.dragging.enable();
  6295. }
  6296. }
  6297. },
  6298. // @method setOpacity(opacity: Number): this
  6299. // Changes the opacity of the marker.
  6300. setOpacity: function (opacity) {
  6301. this.options.opacity = opacity;
  6302. if (this._map) {
  6303. this._updateOpacity();
  6304. }
  6305. return this;
  6306. },
  6307. _updateOpacity: function () {
  6308. var opacity = this.options.opacity;
  6309. if (this._icon) {
  6310. setOpacity(this._icon, opacity);
  6311. }
  6312. if (this._shadow) {
  6313. setOpacity(this._shadow, opacity);
  6314. }
  6315. },
  6316. _bringToFront: function () {
  6317. this._updateZIndex(this.options.riseOffset);
  6318. },
  6319. _resetZIndex: function () {
  6320. this._updateZIndex(0);
  6321. },
  6322. _getPopupAnchor: function () {
  6323. return this.options.icon.options.popupAnchor;
  6324. },
  6325. _getTooltipAnchor: function () {
  6326. return this.options.icon.options.tooltipAnchor;
  6327. }
  6328. });
  6329. // factory L.marker(latlng: LatLng, options? : Marker options)
  6330. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6331. // Instantiates a Marker object given a geographical point and optionally an options object.
  6332. function marker(latlng, options) {
  6333. return new Marker(latlng, options);
  6334. }
  6335. /*
  6336. * @class Path
  6337. * @aka L.Path
  6338. * @inherits Interactive layer
  6339. *
  6340. * An abstract class that contains options and constants shared between vector
  6341. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6342. */
  6343. var Path = Layer.extend({
  6344. // @section
  6345. // @aka Path options
  6346. options: {
  6347. // @option stroke: Boolean = true
  6348. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6349. stroke: true,
  6350. // @option color: String = '#3388ff'
  6351. // Stroke color
  6352. color: '#3388ff',
  6353. // @option weight: Number = 3
  6354. // Stroke width in pixels
  6355. weight: 3,
  6356. // @option opacity: Number = 1.0
  6357. // Stroke opacity
  6358. opacity: 1,
  6359. // @option lineCap: String= 'round'
  6360. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6361. lineCap: 'round',
  6362. // @option lineJoin: String = 'round'
  6363. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6364. lineJoin: 'round',
  6365. // @option dashArray: String = null
  6366. // 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).
  6367. dashArray: null,
  6368. // @option dashOffset: String = null
  6369. // 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).
  6370. dashOffset: null,
  6371. // @option fill: Boolean = depends
  6372. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6373. fill: false,
  6374. // @option fillColor: String = *
  6375. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6376. fillColor: null,
  6377. // @option fillOpacity: Number = 0.2
  6378. // Fill opacity.
  6379. fillOpacity: 0.2,
  6380. // @option fillRule: String = 'evenodd'
  6381. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6382. fillRule: 'evenodd',
  6383. // className: '',
  6384. // Option inherited from "Interactive layer" abstract class
  6385. interactive: true,
  6386. // @option bubblingMouseEvents: Boolean = true
  6387. // When `true`, a mouse event on this path will trigger the same event on the map
  6388. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6389. bubblingMouseEvents: true
  6390. },
  6391. beforeAdd: function (map) {
  6392. // Renderer is set here because we need to call renderer.getEvents
  6393. // before this.getEvents.
  6394. this._renderer = map.getRenderer(this);
  6395. },
  6396. onAdd: function () {
  6397. this._renderer._initPath(this);
  6398. this._reset();
  6399. this._renderer._addPath(this);
  6400. },
  6401. onRemove: function () {
  6402. this._renderer._removePath(this);
  6403. },
  6404. // @method redraw(): this
  6405. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6406. redraw: function () {
  6407. if (this._map) {
  6408. this._renderer._updatePath(this);
  6409. }
  6410. return this;
  6411. },
  6412. // @method setStyle(style: Path options): this
  6413. // Changes the appearance of a Path based on the options in the `Path options` object.
  6414. setStyle: function (style) {
  6415. setOptions(this, style);
  6416. if (this._renderer) {
  6417. this._renderer._updateStyle(this);
  6418. if (this.options.stroke && style && style.hasOwnProperty('weight')) {
  6419. this._updateBounds();
  6420. }
  6421. }
  6422. return this;
  6423. },
  6424. // @method bringToFront(): this
  6425. // Brings the layer to the top of all path layers.
  6426. bringToFront: function () {
  6427. if (this._renderer) {
  6428. this._renderer._bringToFront(this);
  6429. }
  6430. return this;
  6431. },
  6432. // @method bringToBack(): this
  6433. // Brings the layer to the bottom of all path layers.
  6434. bringToBack: function () {
  6435. if (this._renderer) {
  6436. this._renderer._bringToBack(this);
  6437. }
  6438. return this;
  6439. },
  6440. getElement: function () {
  6441. return this._path;
  6442. },
  6443. _reset: function () {
  6444. // defined in child classes
  6445. this._project();
  6446. this._update();
  6447. },
  6448. _clickTolerance: function () {
  6449. // used when doing hit detection for Canvas layers
  6450. return (this.options.stroke ? this.options.weight / 2 : 0) + this._renderer.options.tolerance;
  6451. }
  6452. });
  6453. /*
  6454. * @class CircleMarker
  6455. * @aka L.CircleMarker
  6456. * @inherits Path
  6457. *
  6458. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6459. */
  6460. var CircleMarker = Path.extend({
  6461. // @section
  6462. // @aka CircleMarker options
  6463. options: {
  6464. fill: true,
  6465. // @option radius: Number = 10
  6466. // Radius of the circle marker, in pixels
  6467. radius: 10
  6468. },
  6469. initialize: function (latlng, options) {
  6470. setOptions(this, options);
  6471. this._latlng = toLatLng(latlng);
  6472. this._radius = this.options.radius;
  6473. },
  6474. // @method setLatLng(latLng: LatLng): this
  6475. // Sets the position of a circle marker to a new location.
  6476. setLatLng: function (latlng) {
  6477. var oldLatLng = this._latlng;
  6478. this._latlng = toLatLng(latlng);
  6479. this.redraw();
  6480. // @event move: Event
  6481. // Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
  6482. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6483. },
  6484. // @method getLatLng(): LatLng
  6485. // Returns the current geographical position of the circle marker
  6486. getLatLng: function () {
  6487. return this._latlng;
  6488. },
  6489. // @method setRadius(radius: Number): this
  6490. // Sets the radius of a circle marker. Units are in pixels.
  6491. setRadius: function (radius) {
  6492. this.options.radius = this._radius = radius;
  6493. return this.redraw();
  6494. },
  6495. // @method getRadius(): Number
  6496. // Returns the current radius of the circle
  6497. getRadius: function () {
  6498. return this._radius;
  6499. },
  6500. setStyle : function (options) {
  6501. var radius = options && options.radius || this._radius;
  6502. Path.prototype.setStyle.call(this, options);
  6503. this.setRadius(radius);
  6504. return this;
  6505. },
  6506. _project: function () {
  6507. this._point = this._map.latLngToLayerPoint(this._latlng);
  6508. this._updateBounds();
  6509. },
  6510. _updateBounds: function () {
  6511. var r = this._radius,
  6512. r2 = this._radiusY || r,
  6513. w = this._clickTolerance(),
  6514. p = [r + w, r2 + w];
  6515. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6516. },
  6517. _update: function () {
  6518. if (this._map) {
  6519. this._updatePath();
  6520. }
  6521. },
  6522. _updatePath: function () {
  6523. this._renderer._updateCircle(this);
  6524. },
  6525. _empty: function () {
  6526. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6527. },
  6528. // Needed by the `Canvas` renderer for interactivity
  6529. _containsPoint: function (p) {
  6530. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6531. }
  6532. });
  6533. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6534. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6535. function circleMarker(latlng, options) {
  6536. return new CircleMarker(latlng, options);
  6537. }
  6538. /*
  6539. * @class Circle
  6540. * @aka L.Circle
  6541. * @inherits CircleMarker
  6542. *
  6543. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6544. *
  6545. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6546. *
  6547. * @example
  6548. *
  6549. * ```js
  6550. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6551. * ```
  6552. */
  6553. var Circle = CircleMarker.extend({
  6554. initialize: function (latlng, options, legacyOptions) {
  6555. if (typeof options === 'number') {
  6556. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6557. options = extend({}, legacyOptions, {radius: options});
  6558. }
  6559. setOptions(this, options);
  6560. this._latlng = toLatLng(latlng);
  6561. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6562. // @section
  6563. // @aka Circle options
  6564. // @option radius: Number; Radius of the circle, in meters.
  6565. this._mRadius = this.options.radius;
  6566. },
  6567. // @method setRadius(radius: Number): this
  6568. // Sets the radius of a circle. Units are in meters.
  6569. setRadius: function (radius) {
  6570. this._mRadius = radius;
  6571. return this.redraw();
  6572. },
  6573. // @method getRadius(): Number
  6574. // Returns the current radius of a circle. Units are in meters.
  6575. getRadius: function () {
  6576. return this._mRadius;
  6577. },
  6578. // @method getBounds(): LatLngBounds
  6579. // Returns the `LatLngBounds` of the path.
  6580. getBounds: function () {
  6581. var half = [this._radius, this._radiusY || this._radius];
  6582. return new LatLngBounds(
  6583. this._map.layerPointToLatLng(this._point.subtract(half)),
  6584. this._map.layerPointToLatLng(this._point.add(half)));
  6585. },
  6586. setStyle: Path.prototype.setStyle,
  6587. _project: function () {
  6588. var lng = this._latlng.lng,
  6589. lat = this._latlng.lat,
  6590. map = this._map,
  6591. crs = map.options.crs;
  6592. if (crs.distance === Earth.distance) {
  6593. var d = Math.PI / 180,
  6594. latR = (this._mRadius / Earth.R) / d,
  6595. top = map.project([lat + latR, lng]),
  6596. bottom = map.project([lat - latR, lng]),
  6597. p = top.add(bottom).divideBy(2),
  6598. lat2 = map.unproject(p).lat,
  6599. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6600. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6601. if (isNaN(lngR) || lngR === 0) {
  6602. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6603. }
  6604. this._point = p.subtract(map.getPixelOrigin());
  6605. this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
  6606. this._radiusY = p.y - top.y;
  6607. } else {
  6608. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6609. this._point = map.latLngToLayerPoint(this._latlng);
  6610. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6611. }
  6612. this._updateBounds();
  6613. }
  6614. });
  6615. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6616. // Instantiates a circle object given a geographical point, and an options object
  6617. // which contains the circle radius.
  6618. // @alternative
  6619. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6620. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6621. // Do not use in new applications or plugins.
  6622. function circle(latlng, options, legacyOptions) {
  6623. return new Circle(latlng, options, legacyOptions);
  6624. }
  6625. /*
  6626. * @class Polyline
  6627. * @aka L.Polyline
  6628. * @inherits Path
  6629. *
  6630. * A class for drawing polyline overlays on a map. Extends `Path`.
  6631. *
  6632. * @example
  6633. *
  6634. * ```js
  6635. * // create a red polyline from an array of LatLng points
  6636. * var latlngs = [
  6637. * [45.51, -122.68],
  6638. * [37.77, -122.43],
  6639. * [34.04, -118.2]
  6640. * ];
  6641. *
  6642. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6643. *
  6644. * // zoom the map to the polyline
  6645. * map.fitBounds(polyline.getBounds());
  6646. * ```
  6647. *
  6648. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6649. *
  6650. * ```js
  6651. * // create a red polyline from an array of arrays of LatLng points
  6652. * var latlngs = [
  6653. * [[45.51, -122.68],
  6654. * [37.77, -122.43],
  6655. * [34.04, -118.2]],
  6656. * [[40.78, -73.91],
  6657. * [41.83, -87.62],
  6658. * [32.76, -96.72]]
  6659. * ];
  6660. * ```
  6661. */
  6662. var Polyline = Path.extend({
  6663. // @section
  6664. // @aka Polyline options
  6665. options: {
  6666. // @option smoothFactor: Number = 1.0
  6667. // How much to simplify the polyline on each zoom level. More means
  6668. // better performance and smoother look, and less means more accurate representation.
  6669. smoothFactor: 1.0,
  6670. // @option noClip: Boolean = false
  6671. // Disable polyline clipping.
  6672. noClip: false
  6673. },
  6674. initialize: function (latlngs, options) {
  6675. setOptions(this, options);
  6676. this._setLatLngs(latlngs);
  6677. },
  6678. // @method getLatLngs(): LatLng[]
  6679. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6680. getLatLngs: function () {
  6681. return this._latlngs;
  6682. },
  6683. // @method setLatLngs(latlngs: LatLng[]): this
  6684. // Replaces all the points in the polyline with the given array of geographical points.
  6685. setLatLngs: function (latlngs) {
  6686. this._setLatLngs(latlngs);
  6687. return this.redraw();
  6688. },
  6689. // @method isEmpty(): Boolean
  6690. // Returns `true` if the Polyline has no LatLngs.
  6691. isEmpty: function () {
  6692. return !this._latlngs.length;
  6693. },
  6694. // @method closestLayerPoint(p: Point): Point
  6695. // Returns the point closest to `p` on the Polyline.
  6696. closestLayerPoint: function (p) {
  6697. var minDistance = Infinity,
  6698. minPoint = null,
  6699. closest = _sqClosestPointOnSegment,
  6700. p1, p2;
  6701. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6702. var points = this._parts[j];
  6703. for (var i = 1, len = points.length; i < len; i++) {
  6704. p1 = points[i - 1];
  6705. p2 = points[i];
  6706. var sqDist = closest(p, p1, p2, true);
  6707. if (sqDist < minDistance) {
  6708. minDistance = sqDist;
  6709. minPoint = closest(p, p1, p2);
  6710. }
  6711. }
  6712. }
  6713. if (minPoint) {
  6714. minPoint.distance = Math.sqrt(minDistance);
  6715. }
  6716. return minPoint;
  6717. },
  6718. // @method getCenter(): LatLng
  6719. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6720. getCenter: function () {
  6721. // throws error when not yet added to map as this center calculation requires projected coordinates
  6722. if (!this._map) {
  6723. throw new Error('Must add layer to map before using getCenter()');
  6724. }
  6725. var i, halfDist, segDist, dist, p1, p2, ratio,
  6726. points = this._rings[0],
  6727. len = points.length;
  6728. if (!len) { return null; }
  6729. // polyline centroid algorithm; only uses the first ring if there are multiple
  6730. for (i = 0, halfDist = 0; i < len - 1; i++) {
  6731. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  6732. }
  6733. // The line is so small in the current view that all points are on the same pixel.
  6734. if (halfDist === 0) {
  6735. return this._map.layerPointToLatLng(points[0]);
  6736. }
  6737. for (i = 0, dist = 0; i < len - 1; i++) {
  6738. p1 = points[i];
  6739. p2 = points[i + 1];
  6740. segDist = p1.distanceTo(p2);
  6741. dist += segDist;
  6742. if (dist > halfDist) {
  6743. ratio = (dist - halfDist) / segDist;
  6744. return this._map.layerPointToLatLng([
  6745. p2.x - ratio * (p2.x - p1.x),
  6746. p2.y - ratio * (p2.y - p1.y)
  6747. ]);
  6748. }
  6749. }
  6750. },
  6751. // @method getBounds(): LatLngBounds
  6752. // Returns the `LatLngBounds` of the path.
  6753. getBounds: function () {
  6754. return this._bounds;
  6755. },
  6756. // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
  6757. // Adds a given point to the polyline. By default, adds to the first ring of
  6758. // the polyline in case of a multi-polyline, but can be overridden by passing
  6759. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6760. addLatLng: function (latlng, latlngs) {
  6761. latlngs = latlngs || this._defaultShape();
  6762. latlng = toLatLng(latlng);
  6763. latlngs.push(latlng);
  6764. this._bounds.extend(latlng);
  6765. return this.redraw();
  6766. },
  6767. _setLatLngs: function (latlngs) {
  6768. this._bounds = new LatLngBounds();
  6769. this._latlngs = this._convertLatLngs(latlngs);
  6770. },
  6771. _defaultShape: function () {
  6772. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6773. },
  6774. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6775. _convertLatLngs: function (latlngs) {
  6776. var result = [],
  6777. flat = isFlat(latlngs);
  6778. for (var i = 0, len = latlngs.length; i < len; i++) {
  6779. if (flat) {
  6780. result[i] = toLatLng(latlngs[i]);
  6781. this._bounds.extend(result[i]);
  6782. } else {
  6783. result[i] = this._convertLatLngs(latlngs[i]);
  6784. }
  6785. }
  6786. return result;
  6787. },
  6788. _project: function () {
  6789. var pxBounds = new Bounds();
  6790. this._rings = [];
  6791. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  6792. if (this._bounds.isValid() && pxBounds.isValid()) {
  6793. this._rawPxBounds = pxBounds;
  6794. this._updateBounds();
  6795. }
  6796. },
  6797. _updateBounds: function () {
  6798. var w = this._clickTolerance(),
  6799. p = new Point(w, w);
  6800. this._pxBounds = new Bounds([
  6801. this._rawPxBounds.min.subtract(p),
  6802. this._rawPxBounds.max.add(p)
  6803. ]);
  6804. },
  6805. // recursively turns latlngs into a set of rings with projected coordinates
  6806. _projectLatlngs: function (latlngs, result, projectedBounds) {
  6807. var flat = latlngs[0] instanceof LatLng,
  6808. len = latlngs.length,
  6809. i, ring;
  6810. if (flat) {
  6811. ring = [];
  6812. for (i = 0; i < len; i++) {
  6813. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  6814. projectedBounds.extend(ring[i]);
  6815. }
  6816. result.push(ring);
  6817. } else {
  6818. for (i = 0; i < len; i++) {
  6819. this._projectLatlngs(latlngs[i], result, projectedBounds);
  6820. }
  6821. }
  6822. },
  6823. // clip polyline by renderer bounds so that we have less to render for performance
  6824. _clipPoints: function () {
  6825. var bounds = this._renderer._bounds;
  6826. this._parts = [];
  6827. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6828. return;
  6829. }
  6830. if (this.options.noClip) {
  6831. this._parts = this._rings;
  6832. return;
  6833. }
  6834. var parts = this._parts,
  6835. i, j, k, len, len2, segment, points;
  6836. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  6837. points = this._rings[i];
  6838. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  6839. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  6840. if (!segment) { continue; }
  6841. parts[k] = parts[k] || [];
  6842. parts[k].push(segment[0]);
  6843. // if segment goes out of screen, or it's the last one, it's the end of the line part
  6844. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  6845. parts[k].push(segment[1]);
  6846. k++;
  6847. }
  6848. }
  6849. }
  6850. },
  6851. // simplify each clipped part of the polyline for performance
  6852. _simplifyPoints: function () {
  6853. var parts = this._parts,
  6854. tolerance = this.options.smoothFactor;
  6855. for (var i = 0, len = parts.length; i < len; i++) {
  6856. parts[i] = simplify(parts[i], tolerance);
  6857. }
  6858. },
  6859. _update: function () {
  6860. if (!this._map) { return; }
  6861. this._clipPoints();
  6862. this._simplifyPoints();
  6863. this._updatePath();
  6864. },
  6865. _updatePath: function () {
  6866. this._renderer._updatePoly(this);
  6867. },
  6868. // Needed by the `Canvas` renderer for interactivity
  6869. _containsPoint: function (p, closed) {
  6870. var i, j, k, len, len2, part,
  6871. w = this._clickTolerance();
  6872. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  6873. // hit detection for polylines
  6874. for (i = 0, len = this._parts.length; i < len; i++) {
  6875. part = this._parts[i];
  6876. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6877. if (!closed && (j === 0)) { continue; }
  6878. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  6879. return true;
  6880. }
  6881. }
  6882. }
  6883. return false;
  6884. }
  6885. });
  6886. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  6887. // Instantiates a polyline object given an array of geographical points and
  6888. // optionally an options object. You can create a `Polyline` object with
  6889. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  6890. // of geographic points.
  6891. function polyline(latlngs, options) {
  6892. return new Polyline(latlngs, options);
  6893. }
  6894. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  6895. Polyline._flat = _flat;
  6896. /*
  6897. * @class Polygon
  6898. * @aka L.Polygon
  6899. * @inherits Polyline
  6900. *
  6901. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  6902. *
  6903. * 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.
  6904. *
  6905. *
  6906. * @example
  6907. *
  6908. * ```js
  6909. * // create a red polygon from an array of LatLng points
  6910. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  6911. *
  6912. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  6913. *
  6914. * // zoom the map to the polygon
  6915. * map.fitBounds(polygon.getBounds());
  6916. * ```
  6917. *
  6918. * 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:
  6919. *
  6920. * ```js
  6921. * var latlngs = [
  6922. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6923. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6924. * ];
  6925. * ```
  6926. *
  6927. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  6928. *
  6929. * ```js
  6930. * var latlngs = [
  6931. * [ // first polygon
  6932. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6933. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6934. * ],
  6935. * [ // second polygon
  6936. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  6937. * ]
  6938. * ];
  6939. * ```
  6940. */
  6941. var Polygon = Polyline.extend({
  6942. options: {
  6943. fill: true
  6944. },
  6945. isEmpty: function () {
  6946. return !this._latlngs.length || !this._latlngs[0].length;
  6947. },
  6948. getCenter: function () {
  6949. // throws error when not yet added to map as this center calculation requires projected coordinates
  6950. if (!this._map) {
  6951. throw new Error('Must add layer to map before using getCenter()');
  6952. }
  6953. var i, j, p1, p2, f, area, x, y, center,
  6954. points = this._rings[0],
  6955. len = points.length;
  6956. if (!len) { return null; }
  6957. // polygon centroid algorithm; only uses the first ring if there are multiple
  6958. area = x = y = 0;
  6959. for (i = 0, j = len - 1; i < len; j = i++) {
  6960. p1 = points[i];
  6961. p2 = points[j];
  6962. f = p1.y * p2.x - p2.y * p1.x;
  6963. x += (p1.x + p2.x) * f;
  6964. y += (p1.y + p2.y) * f;
  6965. area += f * 3;
  6966. }
  6967. if (area === 0) {
  6968. // Polygon is so small that all points are on same pixel.
  6969. center = points[0];
  6970. } else {
  6971. center = [x / area, y / area];
  6972. }
  6973. return this._map.layerPointToLatLng(center);
  6974. },
  6975. _convertLatLngs: function (latlngs) {
  6976. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  6977. len = result.length;
  6978. // remove last point if it equals first one
  6979. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  6980. result.pop();
  6981. }
  6982. return result;
  6983. },
  6984. _setLatLngs: function (latlngs) {
  6985. Polyline.prototype._setLatLngs.call(this, latlngs);
  6986. if (isFlat(this._latlngs)) {
  6987. this._latlngs = [this._latlngs];
  6988. }
  6989. },
  6990. _defaultShape: function () {
  6991. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  6992. },
  6993. _clipPoints: function () {
  6994. // polygons need a different clipping algorithm so we redefine that
  6995. var bounds = this._renderer._bounds,
  6996. w = this.options.weight,
  6997. p = new Point(w, w);
  6998. // increase clip padding by stroke width to avoid stroke on clip edges
  6999. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  7000. this._parts = [];
  7001. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7002. return;
  7003. }
  7004. if (this.options.noClip) {
  7005. this._parts = this._rings;
  7006. return;
  7007. }
  7008. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  7009. clipped = clipPolygon(this._rings[i], bounds, true);
  7010. if (clipped.length) {
  7011. this._parts.push(clipped);
  7012. }
  7013. }
  7014. },
  7015. _updatePath: function () {
  7016. this._renderer._updatePoly(this, true);
  7017. },
  7018. // Needed by the `Canvas` renderer for interactivity
  7019. _containsPoint: function (p) {
  7020. var inside = false,
  7021. part, p1, p2, i, j, k, len, len2;
  7022. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  7023. // ray casting algorithm for detecting if point is in polygon
  7024. for (i = 0, len = this._parts.length; i < len; i++) {
  7025. part = this._parts[i];
  7026. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7027. p1 = part[j];
  7028. p2 = part[k];
  7029. 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)) {
  7030. inside = !inside;
  7031. }
  7032. }
  7033. }
  7034. // also check if it's on polygon stroke
  7035. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  7036. }
  7037. });
  7038. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  7039. function polygon(latlngs, options) {
  7040. return new Polygon(latlngs, options);
  7041. }
  7042. /*
  7043. * @class GeoJSON
  7044. * @aka L.GeoJSON
  7045. * @inherits FeatureGroup
  7046. *
  7047. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  7048. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  7049. *
  7050. * @example
  7051. *
  7052. * ```js
  7053. * L.geoJSON(data, {
  7054. * style: function (feature) {
  7055. * return {color: feature.properties.color};
  7056. * }
  7057. * }).bindPopup(function (layer) {
  7058. * return layer.feature.properties.description;
  7059. * }).addTo(map);
  7060. * ```
  7061. */
  7062. var GeoJSON = FeatureGroup.extend({
  7063. /* @section
  7064. * @aka GeoJSON options
  7065. *
  7066. * @option pointToLayer: Function = *
  7067. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  7068. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  7069. * The default is to spawn a default `Marker`:
  7070. * ```js
  7071. * function(geoJsonPoint, latlng) {
  7072. * return L.marker(latlng);
  7073. * }
  7074. * ```
  7075. *
  7076. * @option style: Function = *
  7077. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  7078. * called internally when data is added.
  7079. * The default value is to not override any defaults:
  7080. * ```js
  7081. * function (geoJsonFeature) {
  7082. * return {}
  7083. * }
  7084. * ```
  7085. *
  7086. * @option onEachFeature: Function = *
  7087. * A `Function` that will be called once for each created `Feature`, after it has
  7088. * been created and styled. Useful for attaching events and popups to features.
  7089. * The default is to do nothing with the newly created layers:
  7090. * ```js
  7091. * function (feature, layer) {}
  7092. * ```
  7093. *
  7094. * @option filter: Function = *
  7095. * A `Function` that will be used to decide whether to include a feature or not.
  7096. * The default is to include all features:
  7097. * ```js
  7098. * function (geoJsonFeature) {
  7099. * return true;
  7100. * }
  7101. * ```
  7102. * Note: dynamically changing the `filter` option will have effect only on newly
  7103. * added data. It will _not_ re-evaluate already included features.
  7104. *
  7105. * @option coordsToLatLng: Function = *
  7106. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  7107. * The default is the `coordsToLatLng` static method.
  7108. *
  7109. * @option markersInheritOptions: Boolean = false
  7110. * Whether default Markers for "Point" type Features inherit from group options.
  7111. */
  7112. initialize: function (geojson, options) {
  7113. setOptions(this, options);
  7114. this._layers = {};
  7115. if (geojson) {
  7116. this.addData(geojson);
  7117. }
  7118. },
  7119. // @method addData( <GeoJSON> data ): this
  7120. // Adds a GeoJSON object to the layer.
  7121. addData: function (geojson) {
  7122. var features = isArray(geojson) ? geojson : geojson.features,
  7123. i, len, feature;
  7124. if (features) {
  7125. for (i = 0, len = features.length; i < len; i++) {
  7126. // only add this if geometry or geometries are set and not null
  7127. feature = features[i];
  7128. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  7129. this.addData(feature);
  7130. }
  7131. }
  7132. return this;
  7133. }
  7134. var options = this.options;
  7135. if (options.filter && !options.filter(geojson)) { return this; }
  7136. var layer = geometryToLayer(geojson, options);
  7137. if (!layer) {
  7138. return this;
  7139. }
  7140. layer.feature = asFeature(geojson);
  7141. layer.defaultOptions = layer.options;
  7142. this.resetStyle(layer);
  7143. if (options.onEachFeature) {
  7144. options.onEachFeature(geojson, layer);
  7145. }
  7146. return this.addLayer(layer);
  7147. },
  7148. // @method resetStyle( <Path> layer? ): this
  7149. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7150. // If `layer` is omitted, the style of all features in the current layer is reset.
  7151. resetStyle: function (layer) {
  7152. if (layer === undefined) {
  7153. return this.eachLayer(this.resetStyle, this);
  7154. }
  7155. // reset any custom styles
  7156. layer.options = extend({}, layer.defaultOptions);
  7157. this._setLayerStyle(layer, this.options.style);
  7158. return this;
  7159. },
  7160. // @method setStyle( <Function> style ): this
  7161. // Changes styles of GeoJSON vector layers with the given style function.
  7162. setStyle: function (style) {
  7163. return this.eachLayer(function (layer) {
  7164. this._setLayerStyle(layer, style);
  7165. }, this);
  7166. },
  7167. _setLayerStyle: function (layer, style) {
  7168. if (layer.setStyle) {
  7169. if (typeof style === 'function') {
  7170. style = style(layer.feature);
  7171. }
  7172. layer.setStyle(style);
  7173. }
  7174. }
  7175. });
  7176. // @section
  7177. // There are several static functions which can be called without instantiating L.GeoJSON:
  7178. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7179. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7180. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7181. // functions if provided as options.
  7182. function geometryToLayer(geojson, options) {
  7183. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7184. coords = geometry ? geometry.coordinates : null,
  7185. layers = [],
  7186. pointToLayer = options && options.pointToLayer,
  7187. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7188. latlng, latlngs, i, len;
  7189. if (!coords && !geometry) {
  7190. return null;
  7191. }
  7192. switch (geometry.type) {
  7193. case 'Point':
  7194. latlng = _coordsToLatLng(coords);
  7195. return _pointToLayer(pointToLayer, geojson, latlng, options);
  7196. case 'MultiPoint':
  7197. for (i = 0, len = coords.length; i < len; i++) {
  7198. latlng = _coordsToLatLng(coords[i]);
  7199. layers.push(_pointToLayer(pointToLayer, geojson, latlng, options));
  7200. }
  7201. return new FeatureGroup(layers);
  7202. case 'LineString':
  7203. case 'MultiLineString':
  7204. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7205. return new Polyline(latlngs, options);
  7206. case 'Polygon':
  7207. case 'MultiPolygon':
  7208. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7209. return new Polygon(latlngs, options);
  7210. case 'GeometryCollection':
  7211. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7212. var layer = geometryToLayer({
  7213. geometry: geometry.geometries[i],
  7214. type: 'Feature',
  7215. properties: geojson.properties
  7216. }, options);
  7217. if (layer) {
  7218. layers.push(layer);
  7219. }
  7220. }
  7221. return new FeatureGroup(layers);
  7222. default:
  7223. throw new Error('Invalid GeoJSON object.');
  7224. }
  7225. }
  7226. function _pointToLayer(pointToLayerFn, geojson, latlng, options) {
  7227. return pointToLayerFn ?
  7228. pointToLayerFn(geojson, latlng) :
  7229. new Marker(latlng, options && options.markersInheritOptions && options);
  7230. }
  7231. // @function coordsToLatLng(coords: Array): LatLng
  7232. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7233. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7234. function coordsToLatLng(coords) {
  7235. return new LatLng(coords[1], coords[0], coords[2]);
  7236. }
  7237. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7238. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7239. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7240. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7241. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7242. var latlngs = [];
  7243. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7244. latlng = levelsDeep ?
  7245. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7246. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7247. latlngs.push(latlng);
  7248. }
  7249. return latlngs;
  7250. }
  7251. // @function latLngToCoords(latlng: LatLng, precision?: Number): Array
  7252. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7253. function latLngToCoords(latlng, precision) {
  7254. precision = typeof precision === 'number' ? precision : 6;
  7255. return latlng.alt !== undefined ?
  7256. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7257. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7258. }
  7259. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  7260. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7261. // `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.
  7262. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7263. var coords = [];
  7264. for (var i = 0, len = latlngs.length; i < len; i++) {
  7265. coords.push(levelsDeep ?
  7266. latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :
  7267. latLngToCoords(latlngs[i], precision));
  7268. }
  7269. if (!levelsDeep && closed) {
  7270. coords.push(coords[0]);
  7271. }
  7272. return coords;
  7273. }
  7274. function getFeature(layer, newGeometry) {
  7275. return layer.feature ?
  7276. extend({}, layer.feature, {geometry: newGeometry}) :
  7277. asFeature(newGeometry);
  7278. }
  7279. // @function asFeature(geojson: Object): Object
  7280. // Normalize GeoJSON geometries/features into GeoJSON features.
  7281. function asFeature(geojson) {
  7282. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7283. return geojson;
  7284. }
  7285. return {
  7286. type: 'Feature',
  7287. properties: {},
  7288. geometry: geojson
  7289. };
  7290. }
  7291. var PointToGeoJSON = {
  7292. toGeoJSON: function (precision) {
  7293. return getFeature(this, {
  7294. type: 'Point',
  7295. coordinates: latLngToCoords(this.getLatLng(), precision)
  7296. });
  7297. }
  7298. };
  7299. // @namespace Marker
  7300. // @section Other methods
  7301. // @method toGeoJSON(precision?: Number): Object
  7302. // `precision` is the number of decimal places for coordinates.
  7303. // The default value is 6 places.
  7304. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7305. Marker.include(PointToGeoJSON);
  7306. // @namespace CircleMarker
  7307. // @method toGeoJSON(precision?: Number): Object
  7308. // `precision` is the number of decimal places for coordinates.
  7309. // The default value is 6 places.
  7310. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7311. Circle.include(PointToGeoJSON);
  7312. CircleMarker.include(PointToGeoJSON);
  7313. // @namespace Polyline
  7314. // @method toGeoJSON(precision?: Number): Object
  7315. // `precision` is the number of decimal places for coordinates.
  7316. // The default value is 6 places.
  7317. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7318. Polyline.include({
  7319. toGeoJSON: function (precision) {
  7320. var multi = !isFlat(this._latlngs);
  7321. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7322. return getFeature(this, {
  7323. type: (multi ? 'Multi' : '') + 'LineString',
  7324. coordinates: coords
  7325. });
  7326. }
  7327. });
  7328. // @namespace Polygon
  7329. // @method toGeoJSON(precision?: Number): Object
  7330. // `precision` is the number of decimal places for coordinates.
  7331. // The default value is 6 places.
  7332. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7333. Polygon.include({
  7334. toGeoJSON: function (precision) {
  7335. var holes = !isFlat(this._latlngs),
  7336. multi = holes && !isFlat(this._latlngs[0]);
  7337. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7338. if (!holes) {
  7339. coords = [coords];
  7340. }
  7341. return getFeature(this, {
  7342. type: (multi ? 'Multi' : '') + 'Polygon',
  7343. coordinates: coords
  7344. });
  7345. }
  7346. });
  7347. // @namespace LayerGroup
  7348. LayerGroup.include({
  7349. toMultiPoint: function (precision) {
  7350. var coords = [];
  7351. this.eachLayer(function (layer) {
  7352. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7353. });
  7354. return getFeature(this, {
  7355. type: 'MultiPoint',
  7356. coordinates: coords
  7357. });
  7358. },
  7359. // @method toGeoJSON(precision?: Number): Object
  7360. // `precision` is the number of decimal places for coordinates.
  7361. // The default value is 6 places.
  7362. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7363. toGeoJSON: function (precision) {
  7364. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7365. if (type === 'MultiPoint') {
  7366. return this.toMultiPoint(precision);
  7367. }
  7368. var isGeometryCollection = type === 'GeometryCollection',
  7369. jsons = [];
  7370. this.eachLayer(function (layer) {
  7371. if (layer.toGeoJSON) {
  7372. var json = layer.toGeoJSON(precision);
  7373. if (isGeometryCollection) {
  7374. jsons.push(json.geometry);
  7375. } else {
  7376. var feature = asFeature(json);
  7377. // Squash nested feature collections
  7378. if (feature.type === 'FeatureCollection') {
  7379. jsons.push.apply(jsons, feature.features);
  7380. } else {
  7381. jsons.push(feature);
  7382. }
  7383. }
  7384. }
  7385. });
  7386. if (isGeometryCollection) {
  7387. return getFeature(this, {
  7388. geometries: jsons,
  7389. type: 'GeometryCollection'
  7390. });
  7391. }
  7392. return {
  7393. type: 'FeatureCollection',
  7394. features: jsons
  7395. };
  7396. }
  7397. });
  7398. // @namespace GeoJSON
  7399. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7400. // Creates a GeoJSON layer. Optionally accepts an object in
  7401. // [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map
  7402. // (you can alternatively add it later with `addData` method) and an `options` object.
  7403. function geoJSON(geojson, options) {
  7404. return new GeoJSON(geojson, options);
  7405. }
  7406. // Backward compatibility.
  7407. var geoJson = geoJSON;
  7408. /*
  7409. * @class ImageOverlay
  7410. * @aka L.ImageOverlay
  7411. * @inherits Interactive layer
  7412. *
  7413. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7414. *
  7415. * @example
  7416. *
  7417. * ```js
  7418. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7419. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7420. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7421. * ```
  7422. */
  7423. var ImageOverlay = Layer.extend({
  7424. // @section
  7425. // @aka ImageOverlay options
  7426. options: {
  7427. // @option opacity: Number = 1.0
  7428. // The opacity of the image overlay.
  7429. opacity: 1,
  7430. // @option alt: String = ''
  7431. // Text for the `alt` attribute of the image (useful for accessibility).
  7432. alt: '',
  7433. // @option interactive: Boolean = false
  7434. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7435. interactive: false,
  7436. // @option crossOrigin: Boolean|String = false
  7437. // Whether the crossOrigin attribute will be added to the image.
  7438. // 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.
  7439. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  7440. crossOrigin: false,
  7441. // @option errorOverlayUrl: String = ''
  7442. // URL to the overlay image to show in place of the overlay that failed to load.
  7443. errorOverlayUrl: '',
  7444. // @option zIndex: Number = 1
  7445. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
  7446. zIndex: 1,
  7447. // @option className: String = ''
  7448. // A custom class name to assign to the image. Empty by default.
  7449. className: ''
  7450. },
  7451. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7452. this._url = url;
  7453. this._bounds = toLatLngBounds(bounds);
  7454. setOptions(this, options);
  7455. },
  7456. onAdd: function () {
  7457. if (!this._image) {
  7458. this._initImage();
  7459. if (this.options.opacity < 1) {
  7460. this._updateOpacity();
  7461. }
  7462. }
  7463. if (this.options.interactive) {
  7464. addClass(this._image, 'leaflet-interactive');
  7465. this.addInteractiveTarget(this._image);
  7466. }
  7467. this.getPane().appendChild(this._image);
  7468. this._reset();
  7469. },
  7470. onRemove: function () {
  7471. remove(this._image);
  7472. if (this.options.interactive) {
  7473. this.removeInteractiveTarget(this._image);
  7474. }
  7475. },
  7476. // @method setOpacity(opacity: Number): this
  7477. // Sets the opacity of the overlay.
  7478. setOpacity: function (opacity) {
  7479. this.options.opacity = opacity;
  7480. if (this._image) {
  7481. this._updateOpacity();
  7482. }
  7483. return this;
  7484. },
  7485. setStyle: function (styleOpts) {
  7486. if (styleOpts.opacity) {
  7487. this.setOpacity(styleOpts.opacity);
  7488. }
  7489. return this;
  7490. },
  7491. // @method bringToFront(): this
  7492. // Brings the layer to the top of all overlays.
  7493. bringToFront: function () {
  7494. if (this._map) {
  7495. toFront(this._image);
  7496. }
  7497. return this;
  7498. },
  7499. // @method bringToBack(): this
  7500. // Brings the layer to the bottom of all overlays.
  7501. bringToBack: function () {
  7502. if (this._map) {
  7503. toBack(this._image);
  7504. }
  7505. return this;
  7506. },
  7507. // @method setUrl(url: String): this
  7508. // Changes the URL of the image.
  7509. setUrl: function (url) {
  7510. this._url = url;
  7511. if (this._image) {
  7512. this._image.src = url;
  7513. }
  7514. return this;
  7515. },
  7516. // @method setBounds(bounds: LatLngBounds): this
  7517. // Update the bounds that this ImageOverlay covers
  7518. setBounds: function (bounds) {
  7519. this._bounds = toLatLngBounds(bounds);
  7520. if (this._map) {
  7521. this._reset();
  7522. }
  7523. return this;
  7524. },
  7525. getEvents: function () {
  7526. var events = {
  7527. zoom: this._reset,
  7528. viewreset: this._reset
  7529. };
  7530. if (this._zoomAnimated) {
  7531. events.zoomanim = this._animateZoom;
  7532. }
  7533. return events;
  7534. },
  7535. // @method setZIndex(value: Number): this
  7536. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7537. setZIndex: function (value) {
  7538. this.options.zIndex = value;
  7539. this._updateZIndex();
  7540. return this;
  7541. },
  7542. // @method getBounds(): LatLngBounds
  7543. // Get the bounds that this ImageOverlay covers
  7544. getBounds: function () {
  7545. return this._bounds;
  7546. },
  7547. // @method getElement(): HTMLElement
  7548. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7549. // used by this overlay.
  7550. getElement: function () {
  7551. return this._image;
  7552. },
  7553. _initImage: function () {
  7554. var wasElementSupplied = this._url.tagName === 'IMG';
  7555. var img = this._image = wasElementSupplied ? this._url : create$1('img');
  7556. addClass(img, 'leaflet-image-layer');
  7557. if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
  7558. if (this.options.className) { addClass(img, this.options.className); }
  7559. img.onselectstart = falseFn;
  7560. img.onmousemove = falseFn;
  7561. // @event load: Event
  7562. // Fired when the ImageOverlay layer has loaded its image
  7563. img.onload = bind(this.fire, this, 'load');
  7564. img.onerror = bind(this._overlayOnError, this, 'error');
  7565. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  7566. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  7567. }
  7568. if (this.options.zIndex) {
  7569. this._updateZIndex();
  7570. }
  7571. if (wasElementSupplied) {
  7572. this._url = img.src;
  7573. return;
  7574. }
  7575. img.src = this._url;
  7576. img.alt = this.options.alt;
  7577. },
  7578. _animateZoom: function (e) {
  7579. var scale = this._map.getZoomScale(e.zoom),
  7580. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7581. setTransform(this._image, offset, scale);
  7582. },
  7583. _reset: function () {
  7584. var image = this._image,
  7585. bounds = new Bounds(
  7586. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7587. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7588. size = bounds.getSize();
  7589. setPosition(image, bounds.min);
  7590. image.style.width = size.x + 'px';
  7591. image.style.height = size.y + 'px';
  7592. },
  7593. _updateOpacity: function () {
  7594. setOpacity(this._image, this.options.opacity);
  7595. },
  7596. _updateZIndex: function () {
  7597. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7598. this._image.style.zIndex = this.options.zIndex;
  7599. }
  7600. },
  7601. _overlayOnError: function () {
  7602. // @event error: Event
  7603. // Fired when the ImageOverlay layer fails to load its image
  7604. this.fire('error');
  7605. var errorUrl = this.options.errorOverlayUrl;
  7606. if (errorUrl && this._url !== errorUrl) {
  7607. this._url = errorUrl;
  7608. this._image.src = errorUrl;
  7609. }
  7610. }
  7611. });
  7612. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7613. // Instantiates an image overlay object given the URL of the image and the
  7614. // geographical bounds it is tied to.
  7615. var imageOverlay = function (url, bounds, options) {
  7616. return new ImageOverlay(url, bounds, options);
  7617. };
  7618. /*
  7619. * @class VideoOverlay
  7620. * @aka L.VideoOverlay
  7621. * @inherits ImageOverlay
  7622. *
  7623. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7624. *
  7625. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7626. * HTML5 element.
  7627. *
  7628. * @example
  7629. *
  7630. * ```js
  7631. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7632. * videoBounds = [[ 32, -130], [ 13, -100]];
  7633. * L.videoOverlay(videoUrl, videoBounds ).addTo(map);
  7634. * ```
  7635. */
  7636. var VideoOverlay = ImageOverlay.extend({
  7637. // @section
  7638. // @aka VideoOverlay options
  7639. options: {
  7640. // @option autoplay: Boolean = true
  7641. // Whether the video starts playing automatically when loaded.
  7642. autoplay: true,
  7643. // @option loop: Boolean = true
  7644. // Whether the video will loop back to the beginning when played.
  7645. loop: true,
  7646. // @option keepAspectRatio: Boolean = true
  7647. // Whether the video will save aspect ratio after the projection.
  7648. // Relevant for supported browsers. Browser compatibility- https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
  7649. keepAspectRatio: true
  7650. },
  7651. _initImage: function () {
  7652. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7653. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7654. addClass(vid, 'leaflet-image-layer');
  7655. if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
  7656. if (this.options.className) { addClass(vid, this.options.className); }
  7657. vid.onselectstart = falseFn;
  7658. vid.onmousemove = falseFn;
  7659. // @event load: Event
  7660. // Fired when the video has finished loading the first frame
  7661. vid.onloadeddata = bind(this.fire, this, 'load');
  7662. if (wasElementSupplied) {
  7663. var sourceElements = vid.getElementsByTagName('source');
  7664. var sources = [];
  7665. for (var j = 0; j < sourceElements.length; j++) {
  7666. sources.push(sourceElements[j].src);
  7667. }
  7668. this._url = (sourceElements.length > 0) ? sources : [vid.src];
  7669. return;
  7670. }
  7671. if (!isArray(this._url)) { this._url = [this._url]; }
  7672. if (!this.options.keepAspectRatio && vid.style.hasOwnProperty('objectFit')) { vid.style['objectFit'] = 'fill'; }
  7673. vid.autoplay = !!this.options.autoplay;
  7674. vid.loop = !!this.options.loop;
  7675. for (var i = 0; i < this._url.length; i++) {
  7676. var source = create$1('source');
  7677. source.src = this._url[i];
  7678. vid.appendChild(source);
  7679. }
  7680. }
  7681. // @method getElement(): HTMLVideoElement
  7682. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7683. // used by this overlay.
  7684. });
  7685. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7686. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7687. // geographical bounds it is tied to.
  7688. function videoOverlay(video, bounds, options) {
  7689. return new VideoOverlay(video, bounds, options);
  7690. }
  7691. /*
  7692. * @class SVGOverlay
  7693. * @aka L.SVGOverlay
  7694. * @inherits ImageOverlay
  7695. *
  7696. * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.
  7697. *
  7698. * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.
  7699. *
  7700. * @example
  7701. *
  7702. * ```js
  7703. * var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  7704. * svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
  7705. * svgElement.setAttribute('viewBox', "0 0 200 200");
  7706. * 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"/>';
  7707. * var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
  7708. * L.svgOverlay(svgElement, svgElementBounds).addTo(map);
  7709. * ```
  7710. */
  7711. var SVGOverlay = ImageOverlay.extend({
  7712. _initImage: function () {
  7713. var el = this._image = this._url;
  7714. addClass(el, 'leaflet-image-layer');
  7715. if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); }
  7716. if (this.options.className) { addClass(el, this.options.className); }
  7717. el.onselectstart = falseFn;
  7718. el.onmousemove = falseFn;
  7719. }
  7720. // @method getElement(): SVGElement
  7721. // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
  7722. // used by this overlay.
  7723. });
  7724. // @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)
  7725. // Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.
  7726. // A viewBox attribute is required on the SVG element to zoom in and out properly.
  7727. function svgOverlay(el, bounds, options) {
  7728. return new SVGOverlay(el, bounds, options);
  7729. }
  7730. /*
  7731. * @class DivOverlay
  7732. * @inherits Layer
  7733. * @aka L.DivOverlay
  7734. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  7735. */
  7736. // @namespace DivOverlay
  7737. var DivOverlay = Layer.extend({
  7738. // @section
  7739. // @aka DivOverlay options
  7740. options: {
  7741. // @option offset: Point = Point(0, 7)
  7742. // The offset of the popup position. Useful to control the anchor
  7743. // of the popup when opening it on some overlays.
  7744. offset: [0, 7],
  7745. // @option className: String = ''
  7746. // A custom CSS class name to assign to the popup.
  7747. className: '',
  7748. // @option pane: String = 'popupPane'
  7749. // `Map pane` where the popup will be added.
  7750. pane: 'popupPane'
  7751. },
  7752. initialize: function (options, source) {
  7753. setOptions(this, options);
  7754. this._source = source;
  7755. },
  7756. onAdd: function (map) {
  7757. this._zoomAnimated = map._zoomAnimated;
  7758. if (!this._container) {
  7759. this._initLayout();
  7760. }
  7761. if (map._fadeAnimated) {
  7762. setOpacity(this._container, 0);
  7763. }
  7764. clearTimeout(this._removeTimeout);
  7765. this.getPane().appendChild(this._container);
  7766. this.update();
  7767. if (map._fadeAnimated) {
  7768. setOpacity(this._container, 1);
  7769. }
  7770. this.bringToFront();
  7771. },
  7772. onRemove: function (map) {
  7773. if (map._fadeAnimated) {
  7774. setOpacity(this._container, 0);
  7775. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  7776. } else {
  7777. remove(this._container);
  7778. }
  7779. },
  7780. // @namespace Popup
  7781. // @method getLatLng: LatLng
  7782. // Returns the geographical point of popup.
  7783. getLatLng: function () {
  7784. return this._latlng;
  7785. },
  7786. // @method setLatLng(latlng: LatLng): this
  7787. // Sets the geographical point where the popup will open.
  7788. setLatLng: function (latlng) {
  7789. this._latlng = toLatLng(latlng);
  7790. if (this._map) {
  7791. this._updatePosition();
  7792. this._adjustPan();
  7793. }
  7794. return this;
  7795. },
  7796. // @method getContent: String|HTMLElement
  7797. // Returns the content of the popup.
  7798. getContent: function () {
  7799. return this._content;
  7800. },
  7801. // @method setContent(htmlContent: String|HTMLElement|Function): this
  7802. // 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.
  7803. setContent: function (content) {
  7804. this._content = content;
  7805. this.update();
  7806. return this;
  7807. },
  7808. // @method getElement: String|HTMLElement
  7809. // Alias for [getContent()](#popup-getcontent)
  7810. getElement: function () {
  7811. return this._container;
  7812. },
  7813. // @method update: null
  7814. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  7815. update: function () {
  7816. if (!this._map) { return; }
  7817. this._container.style.visibility = 'hidden';
  7818. this._updateContent();
  7819. this._updateLayout();
  7820. this._updatePosition();
  7821. this._container.style.visibility = '';
  7822. this._adjustPan();
  7823. },
  7824. getEvents: function () {
  7825. var events = {
  7826. zoom: this._updatePosition,
  7827. viewreset: this._updatePosition
  7828. };
  7829. if (this._zoomAnimated) {
  7830. events.zoomanim = this._animateZoom;
  7831. }
  7832. return events;
  7833. },
  7834. // @method isOpen: Boolean
  7835. // Returns `true` when the popup is visible on the map.
  7836. isOpen: function () {
  7837. return !!this._map && this._map.hasLayer(this);
  7838. },
  7839. // @method bringToFront: this
  7840. // Brings this popup in front of other popups (in the same map pane).
  7841. bringToFront: function () {
  7842. if (this._map) {
  7843. toFront(this._container);
  7844. }
  7845. return this;
  7846. },
  7847. // @method bringToBack: this
  7848. // Brings this popup to the back of other popups (in the same map pane).
  7849. bringToBack: function () {
  7850. if (this._map) {
  7851. toBack(this._container);
  7852. }
  7853. return this;
  7854. },
  7855. _prepareOpen: function (parent, layer, latlng) {
  7856. if (!(layer instanceof Layer)) {
  7857. latlng = layer;
  7858. layer = parent;
  7859. }
  7860. if (layer instanceof FeatureGroup) {
  7861. for (var id in parent._layers) {
  7862. layer = parent._layers[id];
  7863. break;
  7864. }
  7865. }
  7866. if (!latlng) {
  7867. if (layer.getCenter) {
  7868. latlng = layer.getCenter();
  7869. } else if (layer.getLatLng) {
  7870. latlng = layer.getLatLng();
  7871. } else {
  7872. throw new Error('Unable to get source layer LatLng.');
  7873. }
  7874. }
  7875. // set overlay source to this layer
  7876. this._source = layer;
  7877. // update the overlay (content, layout, ect...)
  7878. this.update();
  7879. return latlng;
  7880. },
  7881. _updateContent: function () {
  7882. if (!this._content) { return; }
  7883. var node = this._contentNode;
  7884. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  7885. if (typeof content === 'string') {
  7886. node.innerHTML = content;
  7887. } else {
  7888. while (node.hasChildNodes()) {
  7889. node.removeChild(node.firstChild);
  7890. }
  7891. node.appendChild(content);
  7892. }
  7893. this.fire('contentupdate');
  7894. },
  7895. _updatePosition: function () {
  7896. if (!this._map) { return; }
  7897. var pos = this._map.latLngToLayerPoint(this._latlng),
  7898. offset = toPoint(this.options.offset),
  7899. anchor = this._getAnchor();
  7900. if (this._zoomAnimated) {
  7901. setPosition(this._container, pos.add(anchor));
  7902. } else {
  7903. offset = offset.add(pos).add(anchor);
  7904. }
  7905. var bottom = this._containerBottom = -offset.y,
  7906. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  7907. // bottom position the popup in case the height of the popup changes (images loading etc)
  7908. this._container.style.bottom = bottom + 'px';
  7909. this._container.style.left = left + 'px';
  7910. },
  7911. _getAnchor: function () {
  7912. return [0, 0];
  7913. }
  7914. });
  7915. /*
  7916. * @class Popup
  7917. * @inherits DivOverlay
  7918. * @aka L.Popup
  7919. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  7920. * open popups while making sure that only one popup is open at one time
  7921. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  7922. *
  7923. * @example
  7924. *
  7925. * If you want to just bind a popup to marker click and then open it, it's really easy:
  7926. *
  7927. * ```js
  7928. * marker.bindPopup(popupContent).openPopup();
  7929. * ```
  7930. * Path overlays like polylines also have a `bindPopup` method.
  7931. * Here's a more complicated way to open a popup on a map:
  7932. *
  7933. * ```js
  7934. * var popup = L.popup()
  7935. * .setLatLng(latlng)
  7936. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  7937. * .openOn(map);
  7938. * ```
  7939. */
  7940. // @namespace Popup
  7941. var Popup = DivOverlay.extend({
  7942. // @section
  7943. // @aka Popup options
  7944. options: {
  7945. // @option maxWidth: Number = 300
  7946. // Max width of the popup, in pixels.
  7947. maxWidth: 300,
  7948. // @option minWidth: Number = 50
  7949. // Min width of the popup, in pixels.
  7950. minWidth: 50,
  7951. // @option maxHeight: Number = null
  7952. // If set, creates a scrollable container of the given height
  7953. // inside a popup if its content exceeds it.
  7954. maxHeight: null,
  7955. // @option autoPan: Boolean = true
  7956. // Set it to `false` if you don't want the map to do panning animation
  7957. // to fit the opened popup.
  7958. autoPan: true,
  7959. // @option autoPanPaddingTopLeft: Point = null
  7960. // The margin between the popup and the top left corner of the map
  7961. // view after autopanning was performed.
  7962. autoPanPaddingTopLeft: null,
  7963. // @option autoPanPaddingBottomRight: Point = null
  7964. // The margin between the popup and the bottom right corner of the map
  7965. // view after autopanning was performed.
  7966. autoPanPaddingBottomRight: null,
  7967. // @option autoPanPadding: Point = Point(5, 5)
  7968. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  7969. autoPanPadding: [5, 5],
  7970. // @option keepInView: Boolean = false
  7971. // Set it to `true` if you want to prevent users from panning the popup
  7972. // off of the screen while it is open.
  7973. keepInView: false,
  7974. // @option closeButton: Boolean = true
  7975. // Controls the presence of a close button in the popup.
  7976. closeButton: true,
  7977. // @option autoClose: Boolean = true
  7978. // Set it to `false` if you want to override the default behavior of
  7979. // the popup closing when another popup is opened.
  7980. autoClose: true,
  7981. // @option closeOnEscapeKey: Boolean = true
  7982. // Set it to `false` if you want to override the default behavior of
  7983. // the ESC key for closing of the popup.
  7984. closeOnEscapeKey: true,
  7985. // @option closeOnClick: Boolean = *
  7986. // Set it if you want to override the default behavior of the popup closing when user clicks
  7987. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  7988. // @option className: String = ''
  7989. // A custom CSS class name to assign to the popup.
  7990. className: ''
  7991. },
  7992. // @namespace Popup
  7993. // @method openOn(map: Map): this
  7994. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  7995. openOn: function (map) {
  7996. map.openPopup(this);
  7997. return this;
  7998. },
  7999. onAdd: function (map) {
  8000. DivOverlay.prototype.onAdd.call(this, map);
  8001. // @namespace Map
  8002. // @section Popup events
  8003. // @event popupopen: PopupEvent
  8004. // Fired when a popup is opened in the map
  8005. map.fire('popupopen', {popup: this});
  8006. if (this._source) {
  8007. // @namespace Layer
  8008. // @section Popup events
  8009. // @event popupopen: PopupEvent
  8010. // Fired when a popup bound to this layer is opened
  8011. this._source.fire('popupopen', {popup: this}, true);
  8012. // For non-path layers, we toggle the popup when clicking
  8013. // again the layer, so prevent the map to reopen it.
  8014. if (!(this._source instanceof Path)) {
  8015. this._source.on('preclick', stopPropagation);
  8016. }
  8017. }
  8018. },
  8019. onRemove: function (map) {
  8020. DivOverlay.prototype.onRemove.call(this, map);
  8021. // @namespace Map
  8022. // @section Popup events
  8023. // @event popupclose: PopupEvent
  8024. // Fired when a popup in the map is closed
  8025. map.fire('popupclose', {popup: this});
  8026. if (this._source) {
  8027. // @namespace Layer
  8028. // @section Popup events
  8029. // @event popupclose: PopupEvent
  8030. // Fired when a popup bound to this layer is closed
  8031. this._source.fire('popupclose', {popup: this}, true);
  8032. if (!(this._source instanceof Path)) {
  8033. this._source.off('preclick', stopPropagation);
  8034. }
  8035. }
  8036. },
  8037. getEvents: function () {
  8038. var events = DivOverlay.prototype.getEvents.call(this);
  8039. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  8040. events.preclick = this._close;
  8041. }
  8042. if (this.options.keepInView) {
  8043. events.moveend = this._adjustPan;
  8044. }
  8045. return events;
  8046. },
  8047. _close: function () {
  8048. if (this._map) {
  8049. this._map.closePopup(this);
  8050. }
  8051. },
  8052. _initLayout: function () {
  8053. var prefix = 'leaflet-popup',
  8054. container = this._container = create$1('div',
  8055. prefix + ' ' + (this.options.className || '') +
  8056. ' leaflet-zoom-animated');
  8057. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  8058. this._contentNode = create$1('div', prefix + '-content', wrapper);
  8059. disableClickPropagation(wrapper);
  8060. disableScrollPropagation(this._contentNode);
  8061. on(wrapper, 'contextmenu', stopPropagation);
  8062. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  8063. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  8064. if (this.options.closeButton) {
  8065. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  8066. closeButton.href = '#close';
  8067. closeButton.innerHTML = '&#215;';
  8068. on(closeButton, 'click', this._onCloseButtonClick, this);
  8069. }
  8070. },
  8071. _updateLayout: function () {
  8072. var container = this._contentNode,
  8073. style = container.style;
  8074. style.width = '';
  8075. style.whiteSpace = 'nowrap';
  8076. var width = container.offsetWidth;
  8077. width = Math.min(width, this.options.maxWidth);
  8078. width = Math.max(width, this.options.minWidth);
  8079. style.width = (width + 1) + 'px';
  8080. style.whiteSpace = '';
  8081. style.height = '';
  8082. var height = container.offsetHeight,
  8083. maxHeight = this.options.maxHeight,
  8084. scrolledClass = 'leaflet-popup-scrolled';
  8085. if (maxHeight && height > maxHeight) {
  8086. style.height = maxHeight + 'px';
  8087. addClass(container, scrolledClass);
  8088. } else {
  8089. removeClass(container, scrolledClass);
  8090. }
  8091. this._containerWidth = this._container.offsetWidth;
  8092. },
  8093. _animateZoom: function (e) {
  8094. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  8095. anchor = this._getAnchor();
  8096. setPosition(this._container, pos.add(anchor));
  8097. },
  8098. _adjustPan: function () {
  8099. if (!this.options.autoPan) { return; }
  8100. if (this._map._panAnim) { this._map._panAnim.stop(); }
  8101. var map = this._map,
  8102. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  8103. containerHeight = this._container.offsetHeight + marginBottom,
  8104. containerWidth = this._containerWidth,
  8105. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  8106. layerPos._add(getPosition(this._container));
  8107. var containerPos = map.layerPointToContainerPoint(layerPos),
  8108. padding = toPoint(this.options.autoPanPadding),
  8109. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  8110. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  8111. size = map.getSize(),
  8112. dx = 0,
  8113. dy = 0;
  8114. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  8115. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  8116. }
  8117. if (containerPos.x - dx - paddingTL.x < 0) { // left
  8118. dx = containerPos.x - paddingTL.x;
  8119. }
  8120. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  8121. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  8122. }
  8123. if (containerPos.y - dy - paddingTL.y < 0) { // top
  8124. dy = containerPos.y - paddingTL.y;
  8125. }
  8126. // @namespace Map
  8127. // @section Popup events
  8128. // @event autopanstart: Event
  8129. // Fired when the map starts autopanning when opening a popup.
  8130. if (dx || dy) {
  8131. map
  8132. .fire('autopanstart')
  8133. .panBy([dx, dy]);
  8134. }
  8135. },
  8136. _onCloseButtonClick: function (e) {
  8137. this._close();
  8138. stop(e);
  8139. },
  8140. _getAnchor: function () {
  8141. // Where should we anchor the popup on the source layer?
  8142. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  8143. }
  8144. });
  8145. // @namespace Popup
  8146. // @factory L.popup(options?: Popup options, source?: Layer)
  8147. // 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.
  8148. var popup = function (options, source) {
  8149. return new Popup(options, source);
  8150. };
  8151. /* @namespace Map
  8152. * @section Interaction Options
  8153. * @option closePopupOnClick: Boolean = true
  8154. * Set it to `false` if you don't want popups to close when user clicks the map.
  8155. */
  8156. Map.mergeOptions({
  8157. closePopupOnClick: true
  8158. });
  8159. // @namespace Map
  8160. // @section Methods for Layers and Controls
  8161. Map.include({
  8162. // @method openPopup(popup: Popup): this
  8163. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  8164. // @alternative
  8165. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  8166. // Creates a popup with the specified content and options and opens it in the given point on a map.
  8167. openPopup: function (popup, latlng, options) {
  8168. if (!(popup instanceof Popup)) {
  8169. popup = new Popup(options).setContent(popup);
  8170. }
  8171. if (latlng) {
  8172. popup.setLatLng(latlng);
  8173. }
  8174. if (this.hasLayer(popup)) {
  8175. return this;
  8176. }
  8177. if (this._popup && this._popup.options.autoClose) {
  8178. this.closePopup();
  8179. }
  8180. this._popup = popup;
  8181. return this.addLayer(popup);
  8182. },
  8183. // @method closePopup(popup?: Popup): this
  8184. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  8185. closePopup: function (popup) {
  8186. if (!popup || popup === this._popup) {
  8187. popup = this._popup;
  8188. this._popup = null;
  8189. }
  8190. if (popup) {
  8191. this.removeLayer(popup);
  8192. }
  8193. return this;
  8194. }
  8195. });
  8196. /*
  8197. * @namespace Layer
  8198. * @section Popup methods example
  8199. *
  8200. * All layers share a set of methods convenient for binding popups to it.
  8201. *
  8202. * ```js
  8203. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  8204. * layer.openPopup();
  8205. * layer.closePopup();
  8206. * ```
  8207. *
  8208. * 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.
  8209. */
  8210. // @section Popup methods
  8211. Layer.include({
  8212. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  8213. // Binds a popup to the layer with the passed `content` and sets up the
  8214. // necessary event listeners. If a `Function` is passed it will receive
  8215. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8216. bindPopup: function (content, options) {
  8217. if (content instanceof Popup) {
  8218. setOptions(content, options);
  8219. this._popup = content;
  8220. content._source = this;
  8221. } else {
  8222. if (!this._popup || options) {
  8223. this._popup = new Popup(options, this);
  8224. }
  8225. this._popup.setContent(content);
  8226. }
  8227. if (!this._popupHandlersAdded) {
  8228. this.on({
  8229. click: this._openPopup,
  8230. keypress: this._onKeyPress,
  8231. remove: this.closePopup,
  8232. move: this._movePopup
  8233. });
  8234. this._popupHandlersAdded = true;
  8235. }
  8236. return this;
  8237. },
  8238. // @method unbindPopup(): this
  8239. // Removes the popup previously bound with `bindPopup`.
  8240. unbindPopup: function () {
  8241. if (this._popup) {
  8242. this.off({
  8243. click: this._openPopup,
  8244. keypress: this._onKeyPress,
  8245. remove: this.closePopup,
  8246. move: this._movePopup
  8247. });
  8248. this._popupHandlersAdded = false;
  8249. this._popup = null;
  8250. }
  8251. return this;
  8252. },
  8253. // @method openPopup(latlng?: LatLng): this
  8254. // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
  8255. openPopup: function (layer, latlng) {
  8256. if (this._popup && this._map) {
  8257. latlng = this._popup._prepareOpen(this, layer, latlng);
  8258. // open the popup on the map
  8259. this._map.openPopup(this._popup, latlng);
  8260. }
  8261. return this;
  8262. },
  8263. // @method closePopup(): this
  8264. // Closes the popup bound to this layer if it is open.
  8265. closePopup: function () {
  8266. if (this._popup) {
  8267. this._popup._close();
  8268. }
  8269. return this;
  8270. },
  8271. // @method togglePopup(): this
  8272. // Opens or closes the popup bound to this layer depending on its current state.
  8273. togglePopup: function (target) {
  8274. if (this._popup) {
  8275. if (this._popup._map) {
  8276. this.closePopup();
  8277. } else {
  8278. this.openPopup(target);
  8279. }
  8280. }
  8281. return this;
  8282. },
  8283. // @method isPopupOpen(): boolean
  8284. // Returns `true` if the popup bound to this layer is currently open.
  8285. isPopupOpen: function () {
  8286. return (this._popup ? this._popup.isOpen() : false);
  8287. },
  8288. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8289. // Sets the content of the popup bound to this layer.
  8290. setPopupContent: function (content) {
  8291. if (this._popup) {
  8292. this._popup.setContent(content);
  8293. }
  8294. return this;
  8295. },
  8296. // @method getPopup(): Popup
  8297. // Returns the popup bound to this layer.
  8298. getPopup: function () {
  8299. return this._popup;
  8300. },
  8301. _openPopup: function (e) {
  8302. var layer = e.layer || e.target;
  8303. if (!this._popup) {
  8304. return;
  8305. }
  8306. if (!this._map) {
  8307. return;
  8308. }
  8309. // prevent map click
  8310. stop(e);
  8311. // if this inherits from Path its a vector and we can just
  8312. // open the popup at the new location
  8313. if (layer instanceof Path) {
  8314. this.openPopup(e.layer || e.target, e.latlng);
  8315. return;
  8316. }
  8317. // otherwise treat it like a marker and figure out
  8318. // if we should toggle it open/closed
  8319. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  8320. this.closePopup();
  8321. } else {
  8322. this.openPopup(layer, e.latlng);
  8323. }
  8324. },
  8325. _movePopup: function (e) {
  8326. this._popup.setLatLng(e.latlng);
  8327. },
  8328. _onKeyPress: function (e) {
  8329. if (e.originalEvent.keyCode === 13) {
  8330. this._openPopup(e);
  8331. }
  8332. }
  8333. });
  8334. /*
  8335. * @class Tooltip
  8336. * @inherits DivOverlay
  8337. * @aka L.Tooltip
  8338. * Used to display small texts on top of map layers.
  8339. *
  8340. * @example
  8341. *
  8342. * ```js
  8343. * marker.bindTooltip("my tooltip text").openTooltip();
  8344. * ```
  8345. * Note about tooltip offset. Leaflet takes two options in consideration
  8346. * for computing tooltip offsetting:
  8347. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8348. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8349. * move it to the bottom. Negatives will move to the left and top.
  8350. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8351. * should adapt this value if you use a custom icon.
  8352. */
  8353. // @namespace Tooltip
  8354. var Tooltip = DivOverlay.extend({
  8355. // @section
  8356. // @aka Tooltip options
  8357. options: {
  8358. // @option pane: String = 'tooltipPane'
  8359. // `Map pane` where the tooltip will be added.
  8360. pane: 'tooltipPane',
  8361. // @option offset: Point = Point(0, 0)
  8362. // Optional offset of the tooltip position.
  8363. offset: [0, 0],
  8364. // @option direction: String = 'auto'
  8365. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8366. // `top`, `bottom`, `center`, `auto`.
  8367. // `auto` will dynamically switch between `right` and `left` according to the tooltip
  8368. // position on the map.
  8369. direction: 'auto',
  8370. // @option permanent: Boolean = false
  8371. // Whether to open the tooltip permanently or only on mouseover.
  8372. permanent: false,
  8373. // @option sticky: Boolean = false
  8374. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8375. sticky: false,
  8376. // @option interactive: Boolean = false
  8377. // If true, the tooltip will listen to the feature events.
  8378. interactive: false,
  8379. // @option opacity: Number = 0.9
  8380. // Tooltip container opacity.
  8381. opacity: 0.9
  8382. },
  8383. onAdd: function (map) {
  8384. DivOverlay.prototype.onAdd.call(this, map);
  8385. this.setOpacity(this.options.opacity);
  8386. // @namespace Map
  8387. // @section Tooltip events
  8388. // @event tooltipopen: TooltipEvent
  8389. // Fired when a tooltip is opened in the map.
  8390. map.fire('tooltipopen', {tooltip: this});
  8391. if (this._source) {
  8392. // @namespace Layer
  8393. // @section Tooltip events
  8394. // @event tooltipopen: TooltipEvent
  8395. // Fired when a tooltip bound to this layer is opened.
  8396. this._source.fire('tooltipopen', {tooltip: this}, true);
  8397. }
  8398. },
  8399. onRemove: function (map) {
  8400. DivOverlay.prototype.onRemove.call(this, map);
  8401. // @namespace Map
  8402. // @section Tooltip events
  8403. // @event tooltipclose: TooltipEvent
  8404. // Fired when a tooltip in the map is closed.
  8405. map.fire('tooltipclose', {tooltip: this});
  8406. if (this._source) {
  8407. // @namespace Layer
  8408. // @section Tooltip events
  8409. // @event tooltipclose: TooltipEvent
  8410. // Fired when a tooltip bound to this layer is closed.
  8411. this._source.fire('tooltipclose', {tooltip: this}, true);
  8412. }
  8413. },
  8414. getEvents: function () {
  8415. var events = DivOverlay.prototype.getEvents.call(this);
  8416. if (touch && !this.options.permanent) {
  8417. events.preclick = this._close;
  8418. }
  8419. return events;
  8420. },
  8421. _close: function () {
  8422. if (this._map) {
  8423. this._map.closeTooltip(this);
  8424. }
  8425. },
  8426. _initLayout: function () {
  8427. var prefix = 'leaflet-tooltip',
  8428. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8429. this._contentNode = this._container = create$1('div', className);
  8430. },
  8431. _updateLayout: function () {},
  8432. _adjustPan: function () {},
  8433. _setPosition: function (pos) {
  8434. var map = this._map,
  8435. container = this._container,
  8436. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8437. tooltipPoint = map.layerPointToContainerPoint(pos),
  8438. direction = this.options.direction,
  8439. tooltipWidth = container.offsetWidth,
  8440. tooltipHeight = container.offsetHeight,
  8441. offset = toPoint(this.options.offset),
  8442. anchor = this._getAnchor();
  8443. if (direction === 'top') {
  8444. pos = pos.add(toPoint(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true));
  8445. } else if (direction === 'bottom') {
  8446. pos = pos.subtract(toPoint(tooltipWidth / 2 - offset.x, -offset.y, true));
  8447. } else if (direction === 'center') {
  8448. pos = pos.subtract(toPoint(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true));
  8449. } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
  8450. direction = 'right';
  8451. pos = pos.add(toPoint(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true));
  8452. } else {
  8453. direction = 'left';
  8454. pos = pos.subtract(toPoint(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true));
  8455. }
  8456. removeClass(container, 'leaflet-tooltip-right');
  8457. removeClass(container, 'leaflet-tooltip-left');
  8458. removeClass(container, 'leaflet-tooltip-top');
  8459. removeClass(container, 'leaflet-tooltip-bottom');
  8460. addClass(container, 'leaflet-tooltip-' + direction);
  8461. setPosition(container, pos);
  8462. },
  8463. _updatePosition: function () {
  8464. var pos = this._map.latLngToLayerPoint(this._latlng);
  8465. this._setPosition(pos);
  8466. },
  8467. setOpacity: function (opacity) {
  8468. this.options.opacity = opacity;
  8469. if (this._container) {
  8470. setOpacity(this._container, opacity);
  8471. }
  8472. },
  8473. _animateZoom: function (e) {
  8474. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8475. this._setPosition(pos);
  8476. },
  8477. _getAnchor: function () {
  8478. // Where should we anchor the tooltip on the source layer?
  8479. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8480. }
  8481. });
  8482. // @namespace Tooltip
  8483. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8484. // 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.
  8485. var tooltip = function (options, source) {
  8486. return new Tooltip(options, source);
  8487. };
  8488. // @namespace Map
  8489. // @section Methods for Layers and Controls
  8490. Map.include({
  8491. // @method openTooltip(tooltip: Tooltip): this
  8492. // Opens the specified tooltip.
  8493. // @alternative
  8494. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8495. // Creates a tooltip with the specified content and options and open it.
  8496. openTooltip: function (tooltip, latlng, options) {
  8497. if (!(tooltip instanceof Tooltip)) {
  8498. tooltip = new Tooltip(options).setContent(tooltip);
  8499. }
  8500. if (latlng) {
  8501. tooltip.setLatLng(latlng);
  8502. }
  8503. if (this.hasLayer(tooltip)) {
  8504. return this;
  8505. }
  8506. return this.addLayer(tooltip);
  8507. },
  8508. // @method closeTooltip(tooltip?: Tooltip): this
  8509. // Closes the tooltip given as parameter.
  8510. closeTooltip: function (tooltip) {
  8511. if (tooltip) {
  8512. this.removeLayer(tooltip);
  8513. }
  8514. return this;
  8515. }
  8516. });
  8517. /*
  8518. * @namespace Layer
  8519. * @section Tooltip methods example
  8520. *
  8521. * All layers share a set of methods convenient for binding tooltips to it.
  8522. *
  8523. * ```js
  8524. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8525. * layer.openTooltip();
  8526. * layer.closeTooltip();
  8527. * ```
  8528. */
  8529. // @section Tooltip methods
  8530. Layer.include({
  8531. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8532. // Binds a tooltip to the layer with the passed `content` and sets up the
  8533. // necessary event listeners. If a `Function` is passed it will receive
  8534. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8535. bindTooltip: function (content, options) {
  8536. if (content instanceof Tooltip) {
  8537. setOptions(content, options);
  8538. this._tooltip = content;
  8539. content._source = this;
  8540. } else {
  8541. if (!this._tooltip || options) {
  8542. this._tooltip = new Tooltip(options, this);
  8543. }
  8544. this._tooltip.setContent(content);
  8545. }
  8546. this._initTooltipInteractions();
  8547. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8548. this.openTooltip();
  8549. }
  8550. return this;
  8551. },
  8552. // @method unbindTooltip(): this
  8553. // Removes the tooltip previously bound with `bindTooltip`.
  8554. unbindTooltip: function () {
  8555. if (this._tooltip) {
  8556. this._initTooltipInteractions(true);
  8557. this.closeTooltip();
  8558. this._tooltip = null;
  8559. }
  8560. return this;
  8561. },
  8562. _initTooltipInteractions: function (remove$$1) {
  8563. if (!remove$$1 && this._tooltipHandlersAdded) { return; }
  8564. var onOff = remove$$1 ? 'off' : 'on',
  8565. events = {
  8566. remove: this.closeTooltip,
  8567. move: this._moveTooltip
  8568. };
  8569. if (!this._tooltip.options.permanent) {
  8570. events.mouseover = this._openTooltip;
  8571. events.mouseout = this.closeTooltip;
  8572. if (this._tooltip.options.sticky) {
  8573. events.mousemove = this._moveTooltip;
  8574. }
  8575. if (touch) {
  8576. events.click = this._openTooltip;
  8577. }
  8578. } else {
  8579. events.add = this._openTooltip;
  8580. }
  8581. this[onOff](events);
  8582. this._tooltipHandlersAdded = !remove$$1;
  8583. },
  8584. // @method openTooltip(latlng?: LatLng): this
  8585. // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8586. openTooltip: function (layer, latlng) {
  8587. if (this._tooltip && this._map) {
  8588. latlng = this._tooltip._prepareOpen(this, layer, latlng);
  8589. // open the tooltip on the map
  8590. this._map.openTooltip(this._tooltip, latlng);
  8591. // Tooltip container may not be defined if not permanent and never
  8592. // opened.
  8593. if (this._tooltip.options.interactive && this._tooltip._container) {
  8594. addClass(this._tooltip._container, 'leaflet-clickable');
  8595. this.addInteractiveTarget(this._tooltip._container);
  8596. }
  8597. }
  8598. return this;
  8599. },
  8600. // @method closeTooltip(): this
  8601. // Closes the tooltip bound to this layer if it is open.
  8602. closeTooltip: function () {
  8603. if (this._tooltip) {
  8604. this._tooltip._close();
  8605. if (this._tooltip.options.interactive && this._tooltip._container) {
  8606. removeClass(this._tooltip._container, 'leaflet-clickable');
  8607. this.removeInteractiveTarget(this._tooltip._container);
  8608. }
  8609. }
  8610. return this;
  8611. },
  8612. // @method toggleTooltip(): this
  8613. // Opens or closes the tooltip bound to this layer depending on its current state.
  8614. toggleTooltip: function (target) {
  8615. if (this._tooltip) {
  8616. if (this._tooltip._map) {
  8617. this.closeTooltip();
  8618. } else {
  8619. this.openTooltip(target);
  8620. }
  8621. }
  8622. return this;
  8623. },
  8624. // @method isTooltipOpen(): boolean
  8625. // Returns `true` if the tooltip bound to this layer is currently open.
  8626. isTooltipOpen: function () {
  8627. return this._tooltip.isOpen();
  8628. },
  8629. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8630. // Sets the content of the tooltip bound to this layer.
  8631. setTooltipContent: function (content) {
  8632. if (this._tooltip) {
  8633. this._tooltip.setContent(content);
  8634. }
  8635. return this;
  8636. },
  8637. // @method getTooltip(): Tooltip
  8638. // Returns the tooltip bound to this layer.
  8639. getTooltip: function () {
  8640. return this._tooltip;
  8641. },
  8642. _openTooltip: function (e) {
  8643. var layer = e.layer || e.target;
  8644. if (!this._tooltip || !this._map) {
  8645. return;
  8646. }
  8647. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  8648. },
  8649. _moveTooltip: function (e) {
  8650. var latlng = e.latlng, containerPoint, layerPoint;
  8651. if (this._tooltip.options.sticky && e.originalEvent) {
  8652. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  8653. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  8654. latlng = this._map.layerPointToLatLng(layerPoint);
  8655. }
  8656. this._tooltip.setLatLng(latlng);
  8657. }
  8658. });
  8659. /*
  8660. * @class DivIcon
  8661. * @aka L.DivIcon
  8662. * @inherits Icon
  8663. *
  8664. * Represents a lightweight icon for markers that uses a simple `<div>`
  8665. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  8666. *
  8667. * @example
  8668. * ```js
  8669. * var myIcon = L.divIcon({className: 'my-div-icon'});
  8670. * // you can set .my-div-icon styles in CSS
  8671. *
  8672. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  8673. * ```
  8674. *
  8675. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  8676. */
  8677. var DivIcon = Icon.extend({
  8678. options: {
  8679. // @section
  8680. // @aka DivIcon options
  8681. iconSize: [12, 12], // also can be set through CSS
  8682. // iconAnchor: (Point),
  8683. // popupAnchor: (Point),
  8684. // @option html: String|HTMLElement = ''
  8685. // Custom HTML code to put inside the div element, empty by default. Alternatively,
  8686. // an instance of `HTMLElement`.
  8687. html: false,
  8688. // @option bgPos: Point = [0, 0]
  8689. // Optional relative position of the background, in pixels
  8690. bgPos: null,
  8691. className: 'leaflet-div-icon'
  8692. },
  8693. createIcon: function (oldIcon) {
  8694. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  8695. options = this.options;
  8696. if (options.html instanceof Element) {
  8697. empty(div);
  8698. div.appendChild(options.html);
  8699. } else {
  8700. div.innerHTML = options.html !== false ? options.html : '';
  8701. }
  8702. if (options.bgPos) {
  8703. var bgPos = toPoint(options.bgPos);
  8704. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  8705. }
  8706. this._setIconStyles(div, 'icon');
  8707. return div;
  8708. },
  8709. createShadow: function () {
  8710. return null;
  8711. }
  8712. });
  8713. // @factory L.divIcon(options: DivIcon options)
  8714. // Creates a `DivIcon` instance with the given options.
  8715. function divIcon(options) {
  8716. return new DivIcon(options);
  8717. }
  8718. Icon.Default = IconDefault;
  8719. /*
  8720. * @class GridLayer
  8721. * @inherits Layer
  8722. * @aka L.GridLayer
  8723. *
  8724. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  8725. * 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.
  8726. *
  8727. *
  8728. * @section Synchronous usage
  8729. * @example
  8730. *
  8731. * 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.
  8732. *
  8733. * ```js
  8734. * var CanvasLayer = L.GridLayer.extend({
  8735. * createTile: function(coords){
  8736. * // create a <canvas> element for drawing
  8737. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8738. *
  8739. * // setup tile width and height according to the options
  8740. * var size = this.getTileSize();
  8741. * tile.width = size.x;
  8742. * tile.height = size.y;
  8743. *
  8744. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  8745. * var ctx = tile.getContext('2d');
  8746. *
  8747. * // return the tile so it can be rendered on screen
  8748. * return tile;
  8749. * }
  8750. * });
  8751. * ```
  8752. *
  8753. * @section Asynchronous usage
  8754. * @example
  8755. *
  8756. * 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.
  8757. *
  8758. * ```js
  8759. * var CanvasLayer = L.GridLayer.extend({
  8760. * createTile: function(coords, done){
  8761. * var error;
  8762. *
  8763. * // create a <canvas> element for drawing
  8764. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8765. *
  8766. * // setup tile width and height according to the options
  8767. * var size = this.getTileSize();
  8768. * tile.width = size.x;
  8769. * tile.height = size.y;
  8770. *
  8771. * // draw something asynchronously and pass the tile to the done() callback
  8772. * setTimeout(function() {
  8773. * done(error, tile);
  8774. * }, 1000);
  8775. *
  8776. * return tile;
  8777. * }
  8778. * });
  8779. * ```
  8780. *
  8781. * @section
  8782. */
  8783. var GridLayer = Layer.extend({
  8784. // @section
  8785. // @aka GridLayer options
  8786. options: {
  8787. // @option tileSize: Number|Point = 256
  8788. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  8789. tileSize: 256,
  8790. // @option opacity: Number = 1.0
  8791. // Opacity of the tiles. Can be used in the `createTile()` function.
  8792. opacity: 1,
  8793. // @option updateWhenIdle: Boolean = (depends)
  8794. // Load new tiles only when panning ends.
  8795. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  8796. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  8797. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  8798. updateWhenIdle: mobile,
  8799. // @option updateWhenZooming: Boolean = true
  8800. // 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.
  8801. updateWhenZooming: true,
  8802. // @option updateInterval: Number = 200
  8803. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  8804. updateInterval: 200,
  8805. // @option zIndex: Number = 1
  8806. // The explicit zIndex of the tile layer.
  8807. zIndex: 1,
  8808. // @option bounds: LatLngBounds = undefined
  8809. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  8810. bounds: null,
  8811. // @option minZoom: Number = 0
  8812. // The minimum zoom level down to which this layer will be displayed (inclusive).
  8813. minZoom: 0,
  8814. // @option maxZoom: Number = undefined
  8815. // The maximum zoom level up to which this layer will be displayed (inclusive).
  8816. maxZoom: undefined,
  8817. // @option maxNativeZoom: Number = undefined
  8818. // Maximum zoom number the tile source has available. If it is specified,
  8819. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  8820. // from `maxNativeZoom` level and auto-scaled.
  8821. maxNativeZoom: undefined,
  8822. // @option minNativeZoom: Number = undefined
  8823. // Minimum zoom number the tile source has available. If it is specified,
  8824. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  8825. // from `minNativeZoom` level and auto-scaled.
  8826. minNativeZoom: undefined,
  8827. // @option noWrap: Boolean = false
  8828. // Whether the layer is wrapped around the antimeridian. If `true`, the
  8829. // GridLayer will only be displayed once at low zoom levels. Has no
  8830. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  8831. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  8832. // tiles outside the CRS limits.
  8833. noWrap: false,
  8834. // @option pane: String = 'tilePane'
  8835. // `Map pane` where the grid layer will be added.
  8836. pane: 'tilePane',
  8837. // @option className: String = ''
  8838. // A custom class name to assign to the tile layer. Empty by default.
  8839. className: '',
  8840. // @option keepBuffer: Number = 2
  8841. // When panning the map, keep this many rows and columns of tiles before unloading them.
  8842. keepBuffer: 2
  8843. },
  8844. initialize: function (options) {
  8845. setOptions(this, options);
  8846. },
  8847. onAdd: function () {
  8848. this._initContainer();
  8849. this._levels = {};
  8850. this._tiles = {};
  8851. this._resetView();
  8852. this._update();
  8853. },
  8854. beforeAdd: function (map) {
  8855. map._addZoomLimit(this);
  8856. },
  8857. onRemove: function (map) {
  8858. this._removeAllTiles();
  8859. remove(this._container);
  8860. map._removeZoomLimit(this);
  8861. this._container = null;
  8862. this._tileZoom = undefined;
  8863. },
  8864. // @method bringToFront: this
  8865. // Brings the tile layer to the top of all tile layers.
  8866. bringToFront: function () {
  8867. if (this._map) {
  8868. toFront(this._container);
  8869. this._setAutoZIndex(Math.max);
  8870. }
  8871. return this;
  8872. },
  8873. // @method bringToBack: this
  8874. // Brings the tile layer to the bottom of all tile layers.
  8875. bringToBack: function () {
  8876. if (this._map) {
  8877. toBack(this._container);
  8878. this._setAutoZIndex(Math.min);
  8879. }
  8880. return this;
  8881. },
  8882. // @method getContainer: HTMLElement
  8883. // Returns the HTML element that contains the tiles for this layer.
  8884. getContainer: function () {
  8885. return this._container;
  8886. },
  8887. // @method setOpacity(opacity: Number): this
  8888. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  8889. setOpacity: function (opacity) {
  8890. this.options.opacity = opacity;
  8891. this._updateOpacity();
  8892. return this;
  8893. },
  8894. // @method setZIndex(zIndex: Number): this
  8895. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  8896. setZIndex: function (zIndex) {
  8897. this.options.zIndex = zIndex;
  8898. this._updateZIndex();
  8899. return this;
  8900. },
  8901. // @method isLoading: Boolean
  8902. // Returns `true` if any tile in the grid layer has not finished loading.
  8903. isLoading: function () {
  8904. return this._loading;
  8905. },
  8906. // @method redraw: this
  8907. // Causes the layer to clear all the tiles and request them again.
  8908. redraw: function () {
  8909. if (this._map) {
  8910. this._removeAllTiles();
  8911. this._update();
  8912. }
  8913. return this;
  8914. },
  8915. getEvents: function () {
  8916. var events = {
  8917. viewprereset: this._invalidateAll,
  8918. viewreset: this._resetView,
  8919. zoom: this._resetView,
  8920. moveend: this._onMoveEnd
  8921. };
  8922. if (!this.options.updateWhenIdle) {
  8923. // update tiles on move, but not more often than once per given interval
  8924. if (!this._onMove) {
  8925. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  8926. }
  8927. events.move = this._onMove;
  8928. }
  8929. if (this._zoomAnimated) {
  8930. events.zoomanim = this._animateZoom;
  8931. }
  8932. return events;
  8933. },
  8934. // @section Extension methods
  8935. // Layers extending `GridLayer` shall reimplement the following method.
  8936. // @method createTile(coords: Object, done?: Function): HTMLElement
  8937. // Called only internally, must be overridden by classes extending `GridLayer`.
  8938. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  8939. // is specified, it must be called when the tile has finished loading and drawing.
  8940. createTile: function () {
  8941. return document.createElement('div');
  8942. },
  8943. // @section
  8944. // @method getTileSize: Point
  8945. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  8946. getTileSize: function () {
  8947. var s = this.options.tileSize;
  8948. return s instanceof Point ? s : new Point(s, s);
  8949. },
  8950. _updateZIndex: function () {
  8951. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  8952. this._container.style.zIndex = this.options.zIndex;
  8953. }
  8954. },
  8955. _setAutoZIndex: function (compare) {
  8956. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  8957. var layers = this.getPane().children,
  8958. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  8959. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  8960. zIndex = layers[i].style.zIndex;
  8961. if (layers[i] !== this._container && zIndex) {
  8962. edgeZIndex = compare(edgeZIndex, +zIndex);
  8963. }
  8964. }
  8965. if (isFinite(edgeZIndex)) {
  8966. this.options.zIndex = edgeZIndex + compare(-1, 1);
  8967. this._updateZIndex();
  8968. }
  8969. },
  8970. _updateOpacity: function () {
  8971. if (!this._map) { return; }
  8972. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  8973. if (ielt9) { return; }
  8974. setOpacity(this._container, this.options.opacity);
  8975. var now = +new Date(),
  8976. nextFrame = false,
  8977. willPrune = false;
  8978. for (var key in this._tiles) {
  8979. var tile = this._tiles[key];
  8980. if (!tile.current || !tile.loaded) { continue; }
  8981. var fade = Math.min(1, (now - tile.loaded) / 200);
  8982. setOpacity(tile.el, fade);
  8983. if (fade < 1) {
  8984. nextFrame = true;
  8985. } else {
  8986. if (tile.active) {
  8987. willPrune = true;
  8988. } else {
  8989. this._onOpaqueTile(tile);
  8990. }
  8991. tile.active = true;
  8992. }
  8993. }
  8994. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  8995. if (nextFrame) {
  8996. cancelAnimFrame(this._fadeFrame);
  8997. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  8998. }
  8999. },
  9000. _onOpaqueTile: falseFn,
  9001. _initContainer: function () {
  9002. if (this._container) { return; }
  9003. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  9004. this._updateZIndex();
  9005. if (this.options.opacity < 1) {
  9006. this._updateOpacity();
  9007. }
  9008. this.getPane().appendChild(this._container);
  9009. },
  9010. _updateLevels: function () {
  9011. var zoom = this._tileZoom,
  9012. maxZoom = this.options.maxZoom;
  9013. if (zoom === undefined) { return undefined; }
  9014. for (var z in this._levels) {
  9015. if (this._levels[z].el.children.length || z === zoom) {
  9016. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  9017. this._onUpdateLevel(z);
  9018. } else {
  9019. remove(this._levels[z].el);
  9020. this._removeTilesAtZoom(z);
  9021. this._onRemoveLevel(z);
  9022. delete this._levels[z];
  9023. }
  9024. }
  9025. var level = this._levels[zoom],
  9026. map = this._map;
  9027. if (!level) {
  9028. level = this._levels[zoom] = {};
  9029. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  9030. level.el.style.zIndex = maxZoom;
  9031. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  9032. level.zoom = zoom;
  9033. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  9034. // force the browser to consider the newly added element for transition
  9035. falseFn(level.el.offsetWidth);
  9036. this._onCreateLevel(level);
  9037. }
  9038. this._level = level;
  9039. return level;
  9040. },
  9041. _onUpdateLevel: falseFn,
  9042. _onRemoveLevel: falseFn,
  9043. _onCreateLevel: falseFn,
  9044. _pruneTiles: function () {
  9045. if (!this._map) {
  9046. return;
  9047. }
  9048. var key, tile;
  9049. var zoom = this._map.getZoom();
  9050. if (zoom > this.options.maxZoom ||
  9051. zoom < this.options.minZoom) {
  9052. this._removeAllTiles();
  9053. return;
  9054. }
  9055. for (key in this._tiles) {
  9056. tile = this._tiles[key];
  9057. tile.retain = tile.current;
  9058. }
  9059. for (key in this._tiles) {
  9060. tile = this._tiles[key];
  9061. if (tile.current && !tile.active) {
  9062. var coords = tile.coords;
  9063. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  9064. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  9065. }
  9066. }
  9067. }
  9068. for (key in this._tiles) {
  9069. if (!this._tiles[key].retain) {
  9070. this._removeTile(key);
  9071. }
  9072. }
  9073. },
  9074. _removeTilesAtZoom: function (zoom) {
  9075. for (var key in this._tiles) {
  9076. if (this._tiles[key].coords.z !== zoom) {
  9077. continue;
  9078. }
  9079. this._removeTile(key);
  9080. }
  9081. },
  9082. _removeAllTiles: function () {
  9083. for (var key in this._tiles) {
  9084. this._removeTile(key);
  9085. }
  9086. },
  9087. _invalidateAll: function () {
  9088. for (var z in this._levels) {
  9089. remove(this._levels[z].el);
  9090. this._onRemoveLevel(z);
  9091. delete this._levels[z];
  9092. }
  9093. this._removeAllTiles();
  9094. this._tileZoom = undefined;
  9095. },
  9096. _retainParent: function (x, y, z, minZoom) {
  9097. var x2 = Math.floor(x / 2),
  9098. y2 = Math.floor(y / 2),
  9099. z2 = z - 1,
  9100. coords2 = new Point(+x2, +y2);
  9101. coords2.z = +z2;
  9102. var key = this._tileCoordsToKey(coords2),
  9103. tile = this._tiles[key];
  9104. if (tile && tile.active) {
  9105. tile.retain = true;
  9106. return true;
  9107. } else if (tile && tile.loaded) {
  9108. tile.retain = true;
  9109. }
  9110. if (z2 > minZoom) {
  9111. return this._retainParent(x2, y2, z2, minZoom);
  9112. }
  9113. return false;
  9114. },
  9115. _retainChildren: function (x, y, z, maxZoom) {
  9116. for (var i = 2 * x; i < 2 * x + 2; i++) {
  9117. for (var j = 2 * y; j < 2 * y + 2; j++) {
  9118. var coords = new Point(i, j);
  9119. coords.z = z + 1;
  9120. var key = this._tileCoordsToKey(coords),
  9121. tile = this._tiles[key];
  9122. if (tile && tile.active) {
  9123. tile.retain = true;
  9124. continue;
  9125. } else if (tile && tile.loaded) {
  9126. tile.retain = true;
  9127. }
  9128. if (z + 1 < maxZoom) {
  9129. this._retainChildren(i, j, z + 1, maxZoom);
  9130. }
  9131. }
  9132. }
  9133. },
  9134. _resetView: function (e) {
  9135. var animating = e && (e.pinch || e.flyTo);
  9136. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  9137. },
  9138. _animateZoom: function (e) {
  9139. this._setView(e.center, e.zoom, true, e.noUpdate);
  9140. },
  9141. _clampZoom: function (zoom) {
  9142. var options = this.options;
  9143. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  9144. return options.minNativeZoom;
  9145. }
  9146. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  9147. return options.maxNativeZoom;
  9148. }
  9149. return zoom;
  9150. },
  9151. _setView: function (center, zoom, noPrune, noUpdate) {
  9152. var tileZoom = this._clampZoom(Math.round(zoom));
  9153. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  9154. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  9155. tileZoom = undefined;
  9156. }
  9157. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  9158. if (!noUpdate || tileZoomChanged) {
  9159. this._tileZoom = tileZoom;
  9160. if (this._abortLoading) {
  9161. this._abortLoading();
  9162. }
  9163. this._updateLevels();
  9164. this._resetGrid();
  9165. if (tileZoom !== undefined) {
  9166. this._update(center);
  9167. }
  9168. if (!noPrune) {
  9169. this._pruneTiles();
  9170. }
  9171. // Flag to prevent _updateOpacity from pruning tiles during
  9172. // a zoom anim or a pinch gesture
  9173. this._noPrune = !!noPrune;
  9174. }
  9175. this._setZoomTransforms(center, zoom);
  9176. },
  9177. _setZoomTransforms: function (center, zoom) {
  9178. for (var i in this._levels) {
  9179. this._setZoomTransform(this._levels[i], center, zoom);
  9180. }
  9181. },
  9182. _setZoomTransform: function (level, center, zoom) {
  9183. var scale = this._map.getZoomScale(zoom, level.zoom),
  9184. translate = level.origin.multiplyBy(scale)
  9185. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  9186. if (any3d) {
  9187. setTransform(level.el, translate, scale);
  9188. } else {
  9189. setPosition(level.el, translate);
  9190. }
  9191. },
  9192. _resetGrid: function () {
  9193. var map = this._map,
  9194. crs = map.options.crs,
  9195. tileSize = this._tileSize = this.getTileSize(),
  9196. tileZoom = this._tileZoom;
  9197. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  9198. if (bounds) {
  9199. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  9200. }
  9201. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  9202. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  9203. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  9204. ];
  9205. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  9206. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  9207. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  9208. ];
  9209. },
  9210. _onMoveEnd: function () {
  9211. if (!this._map || this._map._animatingZoom) { return; }
  9212. this._update();
  9213. },
  9214. _getTiledPixelBounds: function (center) {
  9215. var map = this._map,
  9216. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9217. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9218. pixelCenter = map.project(center, this._tileZoom).floor(),
  9219. halfSize = map.getSize().divideBy(scale * 2);
  9220. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9221. },
  9222. // Private method to load tiles in the grid's active zoom level according to map bounds
  9223. _update: function (center) {
  9224. var map = this._map;
  9225. if (!map) { return; }
  9226. var zoom = this._clampZoom(map.getZoom());
  9227. if (center === undefined) { center = map.getCenter(); }
  9228. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  9229. var pixelBounds = this._getTiledPixelBounds(center),
  9230. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9231. tileCenter = tileRange.getCenter(),
  9232. queue = [],
  9233. margin = this.options.keepBuffer,
  9234. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9235. tileRange.getTopRight().add([margin, -margin]));
  9236. // Sanity check: panic if the tile range contains Infinity somewhere.
  9237. if (!(isFinite(tileRange.min.x) &&
  9238. isFinite(tileRange.min.y) &&
  9239. isFinite(tileRange.max.x) &&
  9240. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  9241. for (var key in this._tiles) {
  9242. var c = this._tiles[key].coords;
  9243. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9244. this._tiles[key].current = false;
  9245. }
  9246. }
  9247. // _update just loads more tiles. If the tile zoom level differs too much
  9248. // from the map's, let _setView reset levels and prune old tiles.
  9249. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  9250. // create a queue of coordinates to load tiles from
  9251. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9252. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9253. var coords = new Point(i, j);
  9254. coords.z = this._tileZoom;
  9255. if (!this._isValidTile(coords)) { continue; }
  9256. var tile = this._tiles[this._tileCoordsToKey(coords)];
  9257. if (tile) {
  9258. tile.current = true;
  9259. } else {
  9260. queue.push(coords);
  9261. }
  9262. }
  9263. }
  9264. // sort tile queue to load tiles in order of their distance to center
  9265. queue.sort(function (a, b) {
  9266. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9267. });
  9268. if (queue.length !== 0) {
  9269. // if it's the first batch of tiles to load
  9270. if (!this._loading) {
  9271. this._loading = true;
  9272. // @event loading: Event
  9273. // Fired when the grid layer starts loading tiles.
  9274. this.fire('loading');
  9275. }
  9276. // create DOM fragment to append tiles in one batch
  9277. var fragment = document.createDocumentFragment();
  9278. for (i = 0; i < queue.length; i++) {
  9279. this._addTile(queue[i], fragment);
  9280. }
  9281. this._level.el.appendChild(fragment);
  9282. }
  9283. },
  9284. _isValidTile: function (coords) {
  9285. var crs = this._map.options.crs;
  9286. if (!crs.infinite) {
  9287. // don't load tile if it's out of bounds and not wrapped
  9288. var bounds = this._globalTileRange;
  9289. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9290. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  9291. }
  9292. if (!this.options.bounds) { return true; }
  9293. // don't load tile if it doesn't intersect the bounds in options
  9294. var tileBounds = this._tileCoordsToBounds(coords);
  9295. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9296. },
  9297. _keyToBounds: function (key) {
  9298. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9299. },
  9300. _tileCoordsToNwSe: function (coords) {
  9301. var map = this._map,
  9302. tileSize = this.getTileSize(),
  9303. nwPoint = coords.scaleBy(tileSize),
  9304. sePoint = nwPoint.add(tileSize),
  9305. nw = map.unproject(nwPoint, coords.z),
  9306. se = map.unproject(sePoint, coords.z);
  9307. return [nw, se];
  9308. },
  9309. // converts tile coordinates to its geographical bounds
  9310. _tileCoordsToBounds: function (coords) {
  9311. var bp = this._tileCoordsToNwSe(coords),
  9312. bounds = new LatLngBounds(bp[0], bp[1]);
  9313. if (!this.options.noWrap) {
  9314. bounds = this._map.wrapLatLngBounds(bounds);
  9315. }
  9316. return bounds;
  9317. },
  9318. // converts tile coordinates to key for the tile cache
  9319. _tileCoordsToKey: function (coords) {
  9320. return coords.x + ':' + coords.y + ':' + coords.z;
  9321. },
  9322. // converts tile cache key to coordinates
  9323. _keyToTileCoords: function (key) {
  9324. var k = key.split(':'),
  9325. coords = new Point(+k[0], +k[1]);
  9326. coords.z = +k[2];
  9327. return coords;
  9328. },
  9329. _removeTile: function (key) {
  9330. var tile = this._tiles[key];
  9331. if (!tile) { return; }
  9332. remove(tile.el);
  9333. delete this._tiles[key];
  9334. // @event tileunload: TileEvent
  9335. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9336. this.fire('tileunload', {
  9337. tile: tile.el,
  9338. coords: this._keyToTileCoords(key)
  9339. });
  9340. },
  9341. _initTile: function (tile) {
  9342. addClass(tile, 'leaflet-tile');
  9343. var tileSize = this.getTileSize();
  9344. tile.style.width = tileSize.x + 'px';
  9345. tile.style.height = tileSize.y + 'px';
  9346. tile.onselectstart = falseFn;
  9347. tile.onmousemove = falseFn;
  9348. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9349. if (ielt9 && this.options.opacity < 1) {
  9350. setOpacity(tile, this.options.opacity);
  9351. }
  9352. // without this hack, tiles disappear after zoom on Chrome for Android
  9353. // https://github.com/Leaflet/Leaflet/issues/2078
  9354. if (android && !android23) {
  9355. tile.style.WebkitBackfaceVisibility = 'hidden';
  9356. }
  9357. },
  9358. _addTile: function (coords, container) {
  9359. var tilePos = this._getTilePos(coords),
  9360. key = this._tileCoordsToKey(coords);
  9361. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9362. this._initTile(tile);
  9363. // if createTile is defined with a second argument ("done" callback),
  9364. // we know that tile is async and will be ready later; otherwise
  9365. if (this.createTile.length < 2) {
  9366. // mark tile as ready, but delay one frame for opacity animation to happen
  9367. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9368. }
  9369. setPosition(tile, tilePos);
  9370. // save tile in cache
  9371. this._tiles[key] = {
  9372. el: tile,
  9373. coords: coords,
  9374. current: true
  9375. };
  9376. container.appendChild(tile);
  9377. // @event tileloadstart: TileEvent
  9378. // Fired when a tile is requested and starts loading.
  9379. this.fire('tileloadstart', {
  9380. tile: tile,
  9381. coords: coords
  9382. });
  9383. },
  9384. _tileReady: function (coords, err, tile) {
  9385. if (err) {
  9386. // @event tileerror: TileErrorEvent
  9387. // Fired when there is an error loading a tile.
  9388. this.fire('tileerror', {
  9389. error: err,
  9390. tile: tile,
  9391. coords: coords
  9392. });
  9393. }
  9394. var key = this._tileCoordsToKey(coords);
  9395. tile = this._tiles[key];
  9396. if (!tile) { return; }
  9397. tile.loaded = +new Date();
  9398. if (this._map._fadeAnimated) {
  9399. setOpacity(tile.el, 0);
  9400. cancelAnimFrame(this._fadeFrame);
  9401. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9402. } else {
  9403. tile.active = true;
  9404. this._pruneTiles();
  9405. }
  9406. if (!err) {
  9407. addClass(tile.el, 'leaflet-tile-loaded');
  9408. // @event tileload: TileEvent
  9409. // Fired when a tile loads.
  9410. this.fire('tileload', {
  9411. tile: tile.el,
  9412. coords: coords
  9413. });
  9414. }
  9415. if (this._noTilesToLoad()) {
  9416. this._loading = false;
  9417. // @event load: Event
  9418. // Fired when the grid layer loaded all visible tiles.
  9419. this.fire('load');
  9420. if (ielt9 || !this._map._fadeAnimated) {
  9421. requestAnimFrame(this._pruneTiles, this);
  9422. } else {
  9423. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9424. // to trigger a pruning.
  9425. setTimeout(bind(this._pruneTiles, this), 250);
  9426. }
  9427. }
  9428. },
  9429. _getTilePos: function (coords) {
  9430. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9431. },
  9432. _wrapCoords: function (coords) {
  9433. var newCoords = new Point(
  9434. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9435. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9436. newCoords.z = coords.z;
  9437. return newCoords;
  9438. },
  9439. _pxBoundsToTileRange: function (bounds) {
  9440. var tileSize = this.getTileSize();
  9441. return new Bounds(
  9442. bounds.min.unscaleBy(tileSize).floor(),
  9443. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9444. },
  9445. _noTilesToLoad: function () {
  9446. for (var key in this._tiles) {
  9447. if (!this._tiles[key].loaded) { return false; }
  9448. }
  9449. return true;
  9450. }
  9451. });
  9452. // @factory L.gridLayer(options?: GridLayer options)
  9453. // Creates a new instance of GridLayer with the supplied options.
  9454. function gridLayer(options) {
  9455. return new GridLayer(options);
  9456. }
  9457. /*
  9458. * @class TileLayer
  9459. * @inherits GridLayer
  9460. * @aka L.TileLayer
  9461. * 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`.
  9462. *
  9463. * @example
  9464. *
  9465. * ```js
  9466. * 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);
  9467. * ```
  9468. *
  9469. * @section URL template
  9470. * @example
  9471. *
  9472. * A string of the following form:
  9473. *
  9474. * ```
  9475. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9476. * ```
  9477. *
  9478. * `{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.
  9479. *
  9480. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9481. *
  9482. * ```
  9483. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9484. * ```
  9485. */
  9486. var TileLayer = GridLayer.extend({
  9487. // @section
  9488. // @aka TileLayer options
  9489. options: {
  9490. // @option minZoom: Number = 0
  9491. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9492. minZoom: 0,
  9493. // @option maxZoom: Number = 18
  9494. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9495. maxZoom: 18,
  9496. // @option subdomains: String|String[] = 'abc'
  9497. // 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.
  9498. subdomains: 'abc',
  9499. // @option errorTileUrl: String = ''
  9500. // URL to the tile image to show in place of the tile that failed to load.
  9501. errorTileUrl: '',
  9502. // @option zoomOffset: Number = 0
  9503. // The zoom number used in tile URLs will be offset with this value.
  9504. zoomOffset: 0,
  9505. // @option tms: Boolean = false
  9506. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9507. tms: false,
  9508. // @option zoomReverse: Boolean = false
  9509. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9510. zoomReverse: false,
  9511. // @option detectRetina: Boolean = false
  9512. // 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.
  9513. detectRetina: false,
  9514. // @option crossOrigin: Boolean|String = false
  9515. // Whether the crossOrigin attribute will be added to the tiles.
  9516. // 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.
  9517. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  9518. crossOrigin: false
  9519. },
  9520. initialize: function (url, options) {
  9521. this._url = url;
  9522. options = setOptions(this, options);
  9523. // detecting retina displays, adjusting tileSize and zoom levels
  9524. if (options.detectRetina && retina && options.maxZoom > 0) {
  9525. options.tileSize = Math.floor(options.tileSize / 2);
  9526. if (!options.zoomReverse) {
  9527. options.zoomOffset++;
  9528. options.maxZoom--;
  9529. } else {
  9530. options.zoomOffset--;
  9531. options.minZoom++;
  9532. }
  9533. options.minZoom = Math.max(0, options.minZoom);
  9534. }
  9535. if (typeof options.subdomains === 'string') {
  9536. options.subdomains = options.subdomains.split('');
  9537. }
  9538. // for https://github.com/Leaflet/Leaflet/issues/137
  9539. if (!android) {
  9540. this.on('tileunload', this._onTileRemove);
  9541. }
  9542. },
  9543. // @method setUrl(url: String, noRedraw?: Boolean): this
  9544. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9545. // If the URL does not change, the layer will not be redrawn unless
  9546. // the noRedraw parameter is set to false.
  9547. setUrl: function (url, noRedraw) {
  9548. if (this._url === url && noRedraw === undefined) {
  9549. noRedraw = true;
  9550. }
  9551. this._url = url;
  9552. if (!noRedraw) {
  9553. this.redraw();
  9554. }
  9555. return this;
  9556. },
  9557. // @method createTile(coords: Object, done?: Function): HTMLElement
  9558. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9559. // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
  9560. // callback is called when the tile has been loaded.
  9561. createTile: function (coords, done) {
  9562. var tile = document.createElement('img');
  9563. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9564. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9565. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  9566. tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  9567. }
  9568. /*
  9569. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  9570. http://www.w3.org/TR/WCAG20-TECHS/H67
  9571. */
  9572. tile.alt = '';
  9573. /*
  9574. Set role="presentation" to force screen readers to ignore this
  9575. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  9576. */
  9577. tile.setAttribute('role', 'presentation');
  9578. tile.src = this.getTileUrl(coords);
  9579. return tile;
  9580. },
  9581. // @section Extension methods
  9582. // @uninheritable
  9583. // Layers extending `TileLayer` might reimplement the following method.
  9584. // @method getTileUrl(coords: Object): String
  9585. // Called only internally, returns the URL for a tile given its coordinates.
  9586. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9587. getTileUrl: function (coords) {
  9588. var data = {
  9589. r: retina ? '@2x' : '',
  9590. s: this._getSubdomain(coords),
  9591. x: coords.x,
  9592. y: coords.y,
  9593. z: this._getZoomForUrl()
  9594. };
  9595. if (this._map && !this._map.options.crs.infinite) {
  9596. var invertedY = this._globalTileRange.max.y - coords.y;
  9597. if (this.options.tms) {
  9598. data['y'] = invertedY;
  9599. }
  9600. data['-y'] = invertedY;
  9601. }
  9602. return template(this._url, extend(data, this.options));
  9603. },
  9604. _tileOnLoad: function (done, tile) {
  9605. // For https://github.com/Leaflet/Leaflet/issues/3332
  9606. if (ielt9) {
  9607. setTimeout(bind(done, this, null, tile), 0);
  9608. } else {
  9609. done(null, tile);
  9610. }
  9611. },
  9612. _tileOnError: function (done, tile, e) {
  9613. var errorUrl = this.options.errorTileUrl;
  9614. if (errorUrl && tile.getAttribute('src') !== errorUrl) {
  9615. tile.src = errorUrl;
  9616. }
  9617. done(e, tile);
  9618. },
  9619. _onTileRemove: function (e) {
  9620. e.tile.onload = null;
  9621. },
  9622. _getZoomForUrl: function () {
  9623. var zoom = this._tileZoom,
  9624. maxZoom = this.options.maxZoom,
  9625. zoomReverse = this.options.zoomReverse,
  9626. zoomOffset = this.options.zoomOffset;
  9627. if (zoomReverse) {
  9628. zoom = maxZoom - zoom;
  9629. }
  9630. return zoom + zoomOffset;
  9631. },
  9632. _getSubdomain: function (tilePoint) {
  9633. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  9634. return this.options.subdomains[index];
  9635. },
  9636. // stops loading all tiles in the background layer
  9637. _abortLoading: function () {
  9638. var i, tile;
  9639. for (i in this._tiles) {
  9640. if (this._tiles[i].coords.z !== this._tileZoom) {
  9641. tile = this._tiles[i].el;
  9642. tile.onload = falseFn;
  9643. tile.onerror = falseFn;
  9644. if (!tile.complete) {
  9645. tile.src = emptyImageUrl;
  9646. remove(tile);
  9647. delete this._tiles[i];
  9648. }
  9649. }
  9650. }
  9651. },
  9652. _removeTile: function (key) {
  9653. var tile = this._tiles[key];
  9654. if (!tile) { return; }
  9655. // Cancels any pending http requests associated with the tile
  9656. // unless we're on Android's stock browser,
  9657. // see https://github.com/Leaflet/Leaflet/issues/137
  9658. if (!androidStock) {
  9659. tile.el.setAttribute('src', emptyImageUrl);
  9660. }
  9661. return GridLayer.prototype._removeTile.call(this, key);
  9662. },
  9663. _tileReady: function (coords, err, tile) {
  9664. if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) {
  9665. return;
  9666. }
  9667. return GridLayer.prototype._tileReady.call(this, coords, err, tile);
  9668. }
  9669. });
  9670. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  9671. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  9672. function tileLayer(url, options) {
  9673. return new TileLayer(url, options);
  9674. }
  9675. /*
  9676. * @class TileLayer.WMS
  9677. * @inherits TileLayer
  9678. * @aka L.TileLayer.WMS
  9679. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  9680. *
  9681. * @example
  9682. *
  9683. * ```js
  9684. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  9685. * layers: 'nexrad-n0r-900913',
  9686. * format: 'image/png',
  9687. * transparent: true,
  9688. * attribution: "Weather data © 2012 IEM Nexrad"
  9689. * });
  9690. * ```
  9691. */
  9692. var TileLayerWMS = TileLayer.extend({
  9693. // @section
  9694. // @aka TileLayer.WMS options
  9695. // If any custom options not documented here are used, they will be sent to the
  9696. // WMS server as extra parameters in each request URL. This can be useful for
  9697. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  9698. defaultWmsParams: {
  9699. service: 'WMS',
  9700. request: 'GetMap',
  9701. // @option layers: String = ''
  9702. // **(required)** Comma-separated list of WMS layers to show.
  9703. layers: '',
  9704. // @option styles: String = ''
  9705. // Comma-separated list of WMS styles.
  9706. styles: '',
  9707. // @option format: String = 'image/jpeg'
  9708. // WMS image format (use `'image/png'` for layers with transparency).
  9709. format: 'image/jpeg',
  9710. // @option transparent: Boolean = false
  9711. // If `true`, the WMS service will return images with transparency.
  9712. transparent: false,
  9713. // @option version: String = '1.1.1'
  9714. // Version of the WMS service to use
  9715. version: '1.1.1'
  9716. },
  9717. options: {
  9718. // @option crs: CRS = null
  9719. // Coordinate Reference System to use for the WMS requests, defaults to
  9720. // map CRS. Don't change this if you're not sure what it means.
  9721. crs: null,
  9722. // @option uppercase: Boolean = false
  9723. // If `true`, WMS request parameter keys will be uppercase.
  9724. uppercase: false
  9725. },
  9726. initialize: function (url, options) {
  9727. this._url = url;
  9728. var wmsParams = extend({}, this.defaultWmsParams);
  9729. // all keys that are not TileLayer options go to WMS params
  9730. for (var i in options) {
  9731. if (!(i in this.options)) {
  9732. wmsParams[i] = options[i];
  9733. }
  9734. }
  9735. options = setOptions(this, options);
  9736. var realRetina = options.detectRetina && retina ? 2 : 1;
  9737. var tileSize = this.getTileSize();
  9738. wmsParams.width = tileSize.x * realRetina;
  9739. wmsParams.height = tileSize.y * realRetina;
  9740. this.wmsParams = wmsParams;
  9741. },
  9742. onAdd: function (map) {
  9743. this._crs = this.options.crs || map.options.crs;
  9744. this._wmsVersion = parseFloat(this.wmsParams.version);
  9745. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  9746. this.wmsParams[projectionKey] = this._crs.code;
  9747. TileLayer.prototype.onAdd.call(this, map);
  9748. },
  9749. getTileUrl: function (coords) {
  9750. var tileBounds = this._tileCoordsToNwSe(coords),
  9751. crs = this._crs,
  9752. bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
  9753. min = bounds.min,
  9754. max = bounds.max,
  9755. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  9756. [min.y, min.x, max.y, max.x] :
  9757. [min.x, min.y, max.x, max.y]).join(','),
  9758. url = TileLayer.prototype.getTileUrl.call(this, coords);
  9759. return url +
  9760. getParamString(this.wmsParams, url, this.options.uppercase) +
  9761. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  9762. },
  9763. // @method setParams(params: Object, noRedraw?: Boolean): this
  9764. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  9765. setParams: function (params, noRedraw) {
  9766. extend(this.wmsParams, params);
  9767. if (!noRedraw) {
  9768. this.redraw();
  9769. }
  9770. return this;
  9771. }
  9772. });
  9773. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  9774. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  9775. function tileLayerWMS(url, options) {
  9776. return new TileLayerWMS(url, options);
  9777. }
  9778. TileLayer.WMS = TileLayerWMS;
  9779. tileLayer.wms = tileLayerWMS;
  9780. /*
  9781. * @class Renderer
  9782. * @inherits Layer
  9783. * @aka L.Renderer
  9784. *
  9785. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  9786. * DOM container of the renderer, its bounds, and its zoom animation.
  9787. *
  9788. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  9789. * itself can be added or removed to the map. All paths use a renderer, which can
  9790. * be implicit (the map will decide the type of renderer and use it automatically)
  9791. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  9792. *
  9793. * Do not use this class directly, use `SVG` and `Canvas` instead.
  9794. *
  9795. * @event update: Event
  9796. * Fired when the renderer updates its bounds, center and zoom, for example when
  9797. * its map has moved
  9798. */
  9799. var Renderer = Layer.extend({
  9800. // @section
  9801. // @aka Renderer options
  9802. options: {
  9803. // @option padding: Number = 0.1
  9804. // How much to extend the clip area around the map view (relative to its size)
  9805. // e.g. 0.1 would be 10% of map view in each direction
  9806. padding: 0.1,
  9807. // @option tolerance: Number = 0
  9808. // How much to extend click tolerance round a path/object on the map
  9809. tolerance : 0
  9810. },
  9811. initialize: function (options) {
  9812. setOptions(this, options);
  9813. stamp(this);
  9814. this._layers = this._layers || {};
  9815. },
  9816. onAdd: function () {
  9817. if (!this._container) {
  9818. this._initContainer(); // defined by renderer implementations
  9819. if (this._zoomAnimated) {
  9820. addClass(this._container, 'leaflet-zoom-animated');
  9821. }
  9822. }
  9823. this.getPane().appendChild(this._container);
  9824. this._update();
  9825. this.on('update', this._updatePaths, this);
  9826. },
  9827. onRemove: function () {
  9828. this.off('update', this._updatePaths, this);
  9829. this._destroyContainer();
  9830. },
  9831. getEvents: function () {
  9832. var events = {
  9833. viewreset: this._reset,
  9834. zoom: this._onZoom,
  9835. moveend: this._update,
  9836. zoomend: this._onZoomEnd
  9837. };
  9838. if (this._zoomAnimated) {
  9839. events.zoomanim = this._onAnimZoom;
  9840. }
  9841. return events;
  9842. },
  9843. _onAnimZoom: function (ev) {
  9844. this._updateTransform(ev.center, ev.zoom);
  9845. },
  9846. _onZoom: function () {
  9847. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  9848. },
  9849. _updateTransform: function (center, zoom) {
  9850. var scale = this._map.getZoomScale(zoom, this._zoom),
  9851. position = getPosition(this._container),
  9852. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  9853. currentCenterPoint = this._map.project(this._center, zoom),
  9854. destCenterPoint = this._map.project(center, zoom),
  9855. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  9856. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  9857. if (any3d) {
  9858. setTransform(this._container, topLeftOffset, scale);
  9859. } else {
  9860. setPosition(this._container, topLeftOffset);
  9861. }
  9862. },
  9863. _reset: function () {
  9864. this._update();
  9865. this._updateTransform(this._center, this._zoom);
  9866. for (var id in this._layers) {
  9867. this._layers[id]._reset();
  9868. }
  9869. },
  9870. _onZoomEnd: function () {
  9871. for (var id in this._layers) {
  9872. this._layers[id]._project();
  9873. }
  9874. },
  9875. _updatePaths: function () {
  9876. for (var id in this._layers) {
  9877. this._layers[id]._update();
  9878. }
  9879. },
  9880. _update: function () {
  9881. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  9882. // Subclasses are responsible of firing the 'update' event.
  9883. var p = this.options.padding,
  9884. size = this._map.getSize(),
  9885. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  9886. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  9887. this._center = this._map.getCenter();
  9888. this._zoom = this._map.getZoom();
  9889. }
  9890. });
  9891. /*
  9892. * @class Canvas
  9893. * @inherits Renderer
  9894. * @aka L.Canvas
  9895. *
  9896. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  9897. * Inherits `Renderer`.
  9898. *
  9899. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  9900. * available in all web browsers, notably IE8, and overlapping geometries might
  9901. * not display properly in some edge cases.
  9902. *
  9903. * @example
  9904. *
  9905. * Use Canvas by default for all paths in the map:
  9906. *
  9907. * ```js
  9908. * var map = L.map('map', {
  9909. * renderer: L.canvas()
  9910. * });
  9911. * ```
  9912. *
  9913. * Use a Canvas renderer with extra padding for specific vector geometries:
  9914. *
  9915. * ```js
  9916. * var map = L.map('map');
  9917. * var myRenderer = L.canvas({ padding: 0.5 });
  9918. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  9919. * var circle = L.circle( center, { renderer: myRenderer } );
  9920. * ```
  9921. */
  9922. var Canvas = Renderer.extend({
  9923. getEvents: function () {
  9924. var events = Renderer.prototype.getEvents.call(this);
  9925. events.viewprereset = this._onViewPreReset;
  9926. return events;
  9927. },
  9928. _onViewPreReset: function () {
  9929. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  9930. this._postponeUpdatePaths = true;
  9931. },
  9932. onAdd: function () {
  9933. Renderer.prototype.onAdd.call(this);
  9934. // Redraw vectors since canvas is cleared upon removal,
  9935. // in case of removing the renderer itself from the map.
  9936. this._draw();
  9937. },
  9938. _initContainer: function () {
  9939. var container = this._container = document.createElement('canvas');
  9940. on(container, 'mousemove', this._onMouseMove, this);
  9941. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  9942. on(container, 'mouseout', this._handleMouseOut, this);
  9943. this._ctx = container.getContext('2d');
  9944. },
  9945. _destroyContainer: function () {
  9946. cancelAnimFrame(this._redrawRequest);
  9947. delete this._ctx;
  9948. remove(this._container);
  9949. off(this._container);
  9950. delete this._container;
  9951. },
  9952. _updatePaths: function () {
  9953. if (this._postponeUpdatePaths) { return; }
  9954. var layer;
  9955. this._redrawBounds = null;
  9956. for (var id in this._layers) {
  9957. layer = this._layers[id];
  9958. layer._update();
  9959. }
  9960. this._redraw();
  9961. },
  9962. _update: function () {
  9963. if (this._map._animatingZoom && this._bounds) { return; }
  9964. Renderer.prototype._update.call(this);
  9965. var b = this._bounds,
  9966. container = this._container,
  9967. size = b.getSize(),
  9968. m = retina ? 2 : 1;
  9969. setPosition(container, b.min);
  9970. // set canvas size (also clearing it); use double size on retina
  9971. container.width = m * size.x;
  9972. container.height = m * size.y;
  9973. container.style.width = size.x + 'px';
  9974. container.style.height = size.y + 'px';
  9975. if (retina) {
  9976. this._ctx.scale(2, 2);
  9977. }
  9978. // translate so we use the same path coordinates after canvas element moves
  9979. this._ctx.translate(-b.min.x, -b.min.y);
  9980. // Tell paths to redraw themselves
  9981. this.fire('update');
  9982. },
  9983. _reset: function () {
  9984. Renderer.prototype._reset.call(this);
  9985. if (this._postponeUpdatePaths) {
  9986. this._postponeUpdatePaths = false;
  9987. this._updatePaths();
  9988. }
  9989. },
  9990. _initPath: function (layer) {
  9991. this._updateDashArray(layer);
  9992. this._layers[stamp(layer)] = layer;
  9993. var order = layer._order = {
  9994. layer: layer,
  9995. prev: this._drawLast,
  9996. next: null
  9997. };
  9998. if (this._drawLast) { this._drawLast.next = order; }
  9999. this._drawLast = order;
  10000. this._drawFirst = this._drawFirst || this._drawLast;
  10001. },
  10002. _addPath: function (layer) {
  10003. this._requestRedraw(layer);
  10004. },
  10005. _removePath: function (layer) {
  10006. var order = layer._order;
  10007. var next = order.next;
  10008. var prev = order.prev;
  10009. if (next) {
  10010. next.prev = prev;
  10011. } else {
  10012. this._drawLast = prev;
  10013. }
  10014. if (prev) {
  10015. prev.next = next;
  10016. } else {
  10017. this._drawFirst = next;
  10018. }
  10019. delete layer._order;
  10020. delete this._layers[stamp(layer)];
  10021. this._requestRedraw(layer);
  10022. },
  10023. _updatePath: function (layer) {
  10024. // Redraw the union of the layer's old pixel
  10025. // bounds and the new pixel bounds.
  10026. this._extendRedrawBounds(layer);
  10027. layer._project();
  10028. layer._update();
  10029. // The redraw will extend the redraw bounds
  10030. // with the new pixel bounds.
  10031. this._requestRedraw(layer);
  10032. },
  10033. _updateStyle: function (layer) {
  10034. this._updateDashArray(layer);
  10035. this._requestRedraw(layer);
  10036. },
  10037. _updateDashArray: function (layer) {
  10038. if (typeof layer.options.dashArray === 'string') {
  10039. var parts = layer.options.dashArray.split(/[, ]+/),
  10040. dashArray = [],
  10041. dashValue,
  10042. i;
  10043. for (i = 0; i < parts.length; i++) {
  10044. dashValue = Number(parts[i]);
  10045. // Ignore dash array containing invalid lengths
  10046. if (isNaN(dashValue)) { return; }
  10047. dashArray.push(dashValue);
  10048. }
  10049. layer.options._dashArray = dashArray;
  10050. } else {
  10051. layer.options._dashArray = layer.options.dashArray;
  10052. }
  10053. },
  10054. _requestRedraw: function (layer) {
  10055. if (!this._map) { return; }
  10056. this._extendRedrawBounds(layer);
  10057. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  10058. },
  10059. _extendRedrawBounds: function (layer) {
  10060. if (layer._pxBounds) {
  10061. var padding = (layer.options.weight || 0) + 1;
  10062. this._redrawBounds = this._redrawBounds || new Bounds();
  10063. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  10064. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  10065. }
  10066. },
  10067. _redraw: function () {
  10068. this._redrawRequest = null;
  10069. if (this._redrawBounds) {
  10070. this._redrawBounds.min._floor();
  10071. this._redrawBounds.max._ceil();
  10072. }
  10073. this._clear(); // clear layers in redraw bounds
  10074. this._draw(); // draw layers
  10075. this._redrawBounds = null;
  10076. },
  10077. _clear: function () {
  10078. var bounds = this._redrawBounds;
  10079. if (bounds) {
  10080. var size = bounds.getSize();
  10081. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  10082. } else {
  10083. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  10084. }
  10085. },
  10086. _draw: function () {
  10087. var layer, bounds = this._redrawBounds;
  10088. this._ctx.save();
  10089. if (bounds) {
  10090. var size = bounds.getSize();
  10091. this._ctx.beginPath();
  10092. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  10093. this._ctx.clip();
  10094. }
  10095. this._drawing = true;
  10096. for (var order = this._drawFirst; order; order = order.next) {
  10097. layer = order.layer;
  10098. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  10099. layer._updatePath();
  10100. }
  10101. }
  10102. this._drawing = false;
  10103. this._ctx.restore(); // Restore state before clipping.
  10104. },
  10105. _updatePoly: function (layer, closed) {
  10106. if (!this._drawing) { return; }
  10107. var i, j, len2, p,
  10108. parts = layer._parts,
  10109. len = parts.length,
  10110. ctx = this._ctx;
  10111. if (!len) { return; }
  10112. ctx.beginPath();
  10113. for (i = 0; i < len; i++) {
  10114. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  10115. p = parts[i][j];
  10116. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  10117. }
  10118. if (closed) {
  10119. ctx.closePath();
  10120. }
  10121. }
  10122. this._fillStroke(ctx, layer);
  10123. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  10124. },
  10125. _updateCircle: function (layer) {
  10126. if (!this._drawing || layer._empty()) { return; }
  10127. var p = layer._point,
  10128. ctx = this._ctx,
  10129. r = Math.max(Math.round(layer._radius), 1),
  10130. s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
  10131. if (s !== 1) {
  10132. ctx.save();
  10133. ctx.scale(1, s);
  10134. }
  10135. ctx.beginPath();
  10136. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  10137. if (s !== 1) {
  10138. ctx.restore();
  10139. }
  10140. this._fillStroke(ctx, layer);
  10141. },
  10142. _fillStroke: function (ctx, layer) {
  10143. var options = layer.options;
  10144. if (options.fill) {
  10145. ctx.globalAlpha = options.fillOpacity;
  10146. ctx.fillStyle = options.fillColor || options.color;
  10147. ctx.fill(options.fillRule || 'evenodd');
  10148. }
  10149. if (options.stroke && options.weight !== 0) {
  10150. if (ctx.setLineDash) {
  10151. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  10152. }
  10153. ctx.globalAlpha = options.opacity;
  10154. ctx.lineWidth = options.weight;
  10155. ctx.strokeStyle = options.color;
  10156. ctx.lineCap = options.lineCap;
  10157. ctx.lineJoin = options.lineJoin;
  10158. ctx.stroke();
  10159. }
  10160. },
  10161. // Canvas obviously doesn't have mouse events for individual drawn objects,
  10162. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  10163. _onClick: function (e) {
  10164. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  10165. for (var order = this._drawFirst; order; order = order.next) {
  10166. layer = order.layer;
  10167. if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
  10168. clickedLayer = layer;
  10169. }
  10170. }
  10171. if (clickedLayer) {
  10172. fakeStop(e);
  10173. this._fireEvent([clickedLayer], e);
  10174. }
  10175. },
  10176. _onMouseMove: function (e) {
  10177. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  10178. var point = this._map.mouseEventToLayerPoint(e);
  10179. this._handleMouseHover(e, point);
  10180. },
  10181. _handleMouseOut: function (e) {
  10182. var layer = this._hoveredLayer;
  10183. if (layer) {
  10184. // if we're leaving the layer, fire mouseout
  10185. removeClass(this._container, 'leaflet-interactive');
  10186. this._fireEvent([layer], e, 'mouseout');
  10187. this._hoveredLayer = null;
  10188. this._mouseHoverThrottled = false;
  10189. }
  10190. },
  10191. _handleMouseHover: function (e, point) {
  10192. if (this._mouseHoverThrottled) {
  10193. return;
  10194. }
  10195. var layer, candidateHoveredLayer;
  10196. for (var order = this._drawFirst; order; order = order.next) {
  10197. layer = order.layer;
  10198. if (layer.options.interactive && layer._containsPoint(point)) {
  10199. candidateHoveredLayer = layer;
  10200. }
  10201. }
  10202. if (candidateHoveredLayer !== this._hoveredLayer) {
  10203. this._handleMouseOut(e);
  10204. if (candidateHoveredLayer) {
  10205. addClass(this._container, 'leaflet-interactive'); // change cursor
  10206. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  10207. this._hoveredLayer = candidateHoveredLayer;
  10208. }
  10209. }
  10210. if (this._hoveredLayer) {
  10211. this._fireEvent([this._hoveredLayer], e);
  10212. }
  10213. this._mouseHoverThrottled = true;
  10214. setTimeout(L.bind(function () {
  10215. this._mouseHoverThrottled = false;
  10216. }, this), 32);
  10217. },
  10218. _fireEvent: function (layers, e, type) {
  10219. this._map._fireDOMEvent(e, type || e.type, layers);
  10220. },
  10221. _bringToFront: function (layer) {
  10222. var order = layer._order;
  10223. if (!order) { return; }
  10224. var next = order.next;
  10225. var prev = order.prev;
  10226. if (next) {
  10227. next.prev = prev;
  10228. } else {
  10229. // Already last
  10230. return;
  10231. }
  10232. if (prev) {
  10233. prev.next = next;
  10234. } else if (next) {
  10235. // Update first entry unless this is the
  10236. // single entry
  10237. this._drawFirst = next;
  10238. }
  10239. order.prev = this._drawLast;
  10240. this._drawLast.next = order;
  10241. order.next = null;
  10242. this._drawLast = order;
  10243. this._requestRedraw(layer);
  10244. },
  10245. _bringToBack: function (layer) {
  10246. var order = layer._order;
  10247. if (!order) { return; }
  10248. var next = order.next;
  10249. var prev = order.prev;
  10250. if (prev) {
  10251. prev.next = next;
  10252. } else {
  10253. // Already first
  10254. return;
  10255. }
  10256. if (next) {
  10257. next.prev = prev;
  10258. } else if (prev) {
  10259. // Update last entry unless this is the
  10260. // single entry
  10261. this._drawLast = prev;
  10262. }
  10263. order.prev = null;
  10264. order.next = this._drawFirst;
  10265. this._drawFirst.prev = order;
  10266. this._drawFirst = order;
  10267. this._requestRedraw(layer);
  10268. }
  10269. });
  10270. // @factory L.canvas(options?: Renderer options)
  10271. // Creates a Canvas renderer with the given options.
  10272. function canvas$1(options) {
  10273. return canvas ? new Canvas(options) : null;
  10274. }
  10275. /*
  10276. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10277. */
  10278. var vmlCreate = (function () {
  10279. try {
  10280. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10281. return function (name) {
  10282. return document.createElement('<lvml:' + name + ' class="lvml">');
  10283. };
  10284. } catch (e) {
  10285. return function (name) {
  10286. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10287. };
  10288. }
  10289. })();
  10290. /*
  10291. * @class SVG
  10292. *
  10293. *
  10294. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10295. * with old versions of Internet Explorer.
  10296. */
  10297. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10298. var vmlMixin = {
  10299. _initContainer: function () {
  10300. this._container = create$1('div', 'leaflet-vml-container');
  10301. },
  10302. _update: function () {
  10303. if (this._map._animatingZoom) { return; }
  10304. Renderer.prototype._update.call(this);
  10305. this.fire('update');
  10306. },
  10307. _initPath: function (layer) {
  10308. var container = layer._container = vmlCreate('shape');
  10309. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10310. container.coordsize = '1 1';
  10311. layer._path = vmlCreate('path');
  10312. container.appendChild(layer._path);
  10313. this._updateStyle(layer);
  10314. this._layers[stamp(layer)] = layer;
  10315. },
  10316. _addPath: function (layer) {
  10317. var container = layer._container;
  10318. this._container.appendChild(container);
  10319. if (layer.options.interactive) {
  10320. layer.addInteractiveTarget(container);
  10321. }
  10322. },
  10323. _removePath: function (layer) {
  10324. var container = layer._container;
  10325. remove(container);
  10326. layer.removeInteractiveTarget(container);
  10327. delete this._layers[stamp(layer)];
  10328. },
  10329. _updateStyle: function (layer) {
  10330. var stroke = layer._stroke,
  10331. fill = layer._fill,
  10332. options = layer.options,
  10333. container = layer._container;
  10334. container.stroked = !!options.stroke;
  10335. container.filled = !!options.fill;
  10336. if (options.stroke) {
  10337. if (!stroke) {
  10338. stroke = layer._stroke = vmlCreate('stroke');
  10339. }
  10340. container.appendChild(stroke);
  10341. stroke.weight = options.weight + 'px';
  10342. stroke.color = options.color;
  10343. stroke.opacity = options.opacity;
  10344. if (options.dashArray) {
  10345. stroke.dashStyle = isArray(options.dashArray) ?
  10346. options.dashArray.join(' ') :
  10347. options.dashArray.replace(/( *, *)/g, ' ');
  10348. } else {
  10349. stroke.dashStyle = '';
  10350. }
  10351. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10352. stroke.joinstyle = options.lineJoin;
  10353. } else if (stroke) {
  10354. container.removeChild(stroke);
  10355. layer._stroke = null;
  10356. }
  10357. if (options.fill) {
  10358. if (!fill) {
  10359. fill = layer._fill = vmlCreate('fill');
  10360. }
  10361. container.appendChild(fill);
  10362. fill.color = options.fillColor || options.color;
  10363. fill.opacity = options.fillOpacity;
  10364. } else if (fill) {
  10365. container.removeChild(fill);
  10366. layer._fill = null;
  10367. }
  10368. },
  10369. _updateCircle: function (layer) {
  10370. var p = layer._point.round(),
  10371. r = Math.round(layer._radius),
  10372. r2 = Math.round(layer._radiusY || r);
  10373. this._setPath(layer, layer._empty() ? 'M0 0' :
  10374. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10375. },
  10376. _setPath: function (layer, path) {
  10377. layer._path.v = path;
  10378. },
  10379. _bringToFront: function (layer) {
  10380. toFront(layer._container);
  10381. },
  10382. _bringToBack: function (layer) {
  10383. toBack(layer._container);
  10384. }
  10385. };
  10386. var create$2 = vml ? vmlCreate : svgCreate;
  10387. /*
  10388. * @class SVG
  10389. * @inherits Renderer
  10390. * @aka L.SVG
  10391. *
  10392. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10393. * Inherits `Renderer`.
  10394. *
  10395. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  10396. * available in all web browsers, notably Android 2.x and 3.x.
  10397. *
  10398. * Although SVG is not available on IE7 and IE8, these browsers support
  10399. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10400. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10401. * this case.
  10402. *
  10403. * @example
  10404. *
  10405. * Use SVG by default for all paths in the map:
  10406. *
  10407. * ```js
  10408. * var map = L.map('map', {
  10409. * renderer: L.svg()
  10410. * });
  10411. * ```
  10412. *
  10413. * Use a SVG renderer with extra padding for specific vector geometries:
  10414. *
  10415. * ```js
  10416. * var map = L.map('map');
  10417. * var myRenderer = L.svg({ padding: 0.5 });
  10418. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10419. * var circle = L.circle( center, { renderer: myRenderer } );
  10420. * ```
  10421. */
  10422. var SVG = Renderer.extend({
  10423. getEvents: function () {
  10424. var events = Renderer.prototype.getEvents.call(this);
  10425. events.zoomstart = this._onZoomStart;
  10426. return events;
  10427. },
  10428. _initContainer: function () {
  10429. this._container = create$2('svg');
  10430. // makes it possible to click through svg root; we'll reset it back in individual paths
  10431. this._container.setAttribute('pointer-events', 'none');
  10432. this._rootGroup = create$2('g');
  10433. this._container.appendChild(this._rootGroup);
  10434. },
  10435. _destroyContainer: function () {
  10436. remove(this._container);
  10437. off(this._container);
  10438. delete this._container;
  10439. delete this._rootGroup;
  10440. delete this._svgSize;
  10441. },
  10442. _onZoomStart: function () {
  10443. // Drag-then-pinch interactions might mess up the center and zoom.
  10444. // In this case, the easiest way to prevent this is re-do the renderer
  10445. // bounds and padding when the zooming starts.
  10446. this._update();
  10447. },
  10448. _update: function () {
  10449. if (this._map._animatingZoom && this._bounds) { return; }
  10450. Renderer.prototype._update.call(this);
  10451. var b = this._bounds,
  10452. size = b.getSize(),
  10453. container = this._container;
  10454. // set size of svg-container if changed
  10455. if (!this._svgSize || !this._svgSize.equals(size)) {
  10456. this._svgSize = size;
  10457. container.setAttribute('width', size.x);
  10458. container.setAttribute('height', size.y);
  10459. }
  10460. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10461. setPosition(container, b.min);
  10462. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10463. this.fire('update');
  10464. },
  10465. // methods below are called by vector layers implementations
  10466. _initPath: function (layer) {
  10467. var path = layer._path = create$2('path');
  10468. // @namespace Path
  10469. // @option className: String = null
  10470. // Custom class name set on an element. Only for SVG renderer.
  10471. if (layer.options.className) {
  10472. addClass(path, layer.options.className);
  10473. }
  10474. if (layer.options.interactive) {
  10475. addClass(path, 'leaflet-interactive');
  10476. }
  10477. this._updateStyle(layer);
  10478. this._layers[stamp(layer)] = layer;
  10479. },
  10480. _addPath: function (layer) {
  10481. if (!this._rootGroup) { this._initContainer(); }
  10482. this._rootGroup.appendChild(layer._path);
  10483. layer.addInteractiveTarget(layer._path);
  10484. },
  10485. _removePath: function (layer) {
  10486. remove(layer._path);
  10487. layer.removeInteractiveTarget(layer._path);
  10488. delete this._layers[stamp(layer)];
  10489. },
  10490. _updatePath: function (layer) {
  10491. layer._project();
  10492. layer._update();
  10493. },
  10494. _updateStyle: function (layer) {
  10495. var path = layer._path,
  10496. options = layer.options;
  10497. if (!path) { return; }
  10498. if (options.stroke) {
  10499. path.setAttribute('stroke', options.color);
  10500. path.setAttribute('stroke-opacity', options.opacity);
  10501. path.setAttribute('stroke-width', options.weight);
  10502. path.setAttribute('stroke-linecap', options.lineCap);
  10503. path.setAttribute('stroke-linejoin', options.lineJoin);
  10504. if (options.dashArray) {
  10505. path.setAttribute('stroke-dasharray', options.dashArray);
  10506. } else {
  10507. path.removeAttribute('stroke-dasharray');
  10508. }
  10509. if (options.dashOffset) {
  10510. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10511. } else {
  10512. path.removeAttribute('stroke-dashoffset');
  10513. }
  10514. } else {
  10515. path.setAttribute('stroke', 'none');
  10516. }
  10517. if (options.fill) {
  10518. path.setAttribute('fill', options.fillColor || options.color);
  10519. path.setAttribute('fill-opacity', options.fillOpacity);
  10520. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10521. } else {
  10522. path.setAttribute('fill', 'none');
  10523. }
  10524. },
  10525. _updatePoly: function (layer, closed) {
  10526. this._setPath(layer, pointsToPath(layer._parts, closed));
  10527. },
  10528. _updateCircle: function (layer) {
  10529. var p = layer._point,
  10530. r = Math.max(Math.round(layer._radius), 1),
  10531. r2 = Math.max(Math.round(layer._radiusY), 1) || r,
  10532. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10533. // drawing a circle with two half-arcs
  10534. var d = layer._empty() ? 'M0 0' :
  10535. 'M' + (p.x - r) + ',' + p.y +
  10536. arc + (r * 2) + ',0 ' +
  10537. arc + (-r * 2) + ',0 ';
  10538. this._setPath(layer, d);
  10539. },
  10540. _setPath: function (layer, path) {
  10541. layer._path.setAttribute('d', path);
  10542. },
  10543. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10544. _bringToFront: function (layer) {
  10545. toFront(layer._path);
  10546. },
  10547. _bringToBack: function (layer) {
  10548. toBack(layer._path);
  10549. }
  10550. });
  10551. if (vml) {
  10552. SVG.include(vmlMixin);
  10553. }
  10554. // @namespace SVG
  10555. // @factory L.svg(options?: Renderer options)
  10556. // Creates a SVG renderer with the given options.
  10557. function svg$1(options) {
  10558. return svg || vml ? new SVG(options) : null;
  10559. }
  10560. Map.include({
  10561. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10562. // Returns the instance of `Renderer` that should be used to render the given
  10563. // `Path`. It will ensure that the `renderer` options of the map and paths
  10564. // are respected, and that the renderers do exist on the map.
  10565. getRenderer: function (layer) {
  10566. // @namespace Path; @option renderer: Renderer
  10567. // Use this specific instance of `Renderer` for this path. Takes
  10568. // precedence over the map's [default renderer](#map-renderer).
  10569. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10570. if (!renderer) {
  10571. renderer = this._renderer = this._createRenderer();
  10572. }
  10573. if (!this.hasLayer(renderer)) {
  10574. this.addLayer(renderer);
  10575. }
  10576. return renderer;
  10577. },
  10578. _getPaneRenderer: function (name) {
  10579. if (name === 'overlayPane' || name === undefined) {
  10580. return false;
  10581. }
  10582. var renderer = this._paneRenderers[name];
  10583. if (renderer === undefined) {
  10584. renderer = this._createRenderer({pane: name});
  10585. this._paneRenderers[name] = renderer;
  10586. }
  10587. return renderer;
  10588. },
  10589. _createRenderer: function (options) {
  10590. // @namespace Map; @option preferCanvas: Boolean = false
  10591. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10592. // By default, all `Path`s are rendered in a `SVG` renderer.
  10593. return (this.options.preferCanvas && canvas$1(options)) || svg$1(options);
  10594. }
  10595. });
  10596. /*
  10597. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10598. */
  10599. /*
  10600. * @class Rectangle
  10601. * @aka L.Rectangle
  10602. * @inherits Polygon
  10603. *
  10604. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10605. *
  10606. * @example
  10607. *
  10608. * ```js
  10609. * // define rectangle geographical bounds
  10610. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10611. *
  10612. * // create an orange rectangle
  10613. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10614. *
  10615. * // zoom the map to the rectangle bounds
  10616. * map.fitBounds(bounds);
  10617. * ```
  10618. *
  10619. */
  10620. var Rectangle = Polygon.extend({
  10621. initialize: function (latLngBounds, options) {
  10622. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10623. },
  10624. // @method setBounds(latLngBounds: LatLngBounds): this
  10625. // Redraws the rectangle with the passed bounds.
  10626. setBounds: function (latLngBounds) {
  10627. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  10628. },
  10629. _boundsToLatLngs: function (latLngBounds) {
  10630. latLngBounds = toLatLngBounds(latLngBounds);
  10631. return [
  10632. latLngBounds.getSouthWest(),
  10633. latLngBounds.getNorthWest(),
  10634. latLngBounds.getNorthEast(),
  10635. latLngBounds.getSouthEast()
  10636. ];
  10637. }
  10638. });
  10639. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  10640. function rectangle(latLngBounds, options) {
  10641. return new Rectangle(latLngBounds, options);
  10642. }
  10643. SVG.create = create$2;
  10644. SVG.pointsToPath = pointsToPath;
  10645. GeoJSON.geometryToLayer = geometryToLayer;
  10646. GeoJSON.coordsToLatLng = coordsToLatLng;
  10647. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  10648. GeoJSON.latLngToCoords = latLngToCoords;
  10649. GeoJSON.latLngsToCoords = latLngsToCoords;
  10650. GeoJSON.getFeature = getFeature;
  10651. GeoJSON.asFeature = asFeature;
  10652. /*
  10653. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  10654. * (zoom to a selected bounding box), enabled by default.
  10655. */
  10656. // @namespace Map
  10657. // @section Interaction Options
  10658. Map.mergeOptions({
  10659. // @option boxZoom: Boolean = true
  10660. // Whether the map can be zoomed to a rectangular area specified by
  10661. // dragging the mouse while pressing the shift key.
  10662. boxZoom: true
  10663. });
  10664. var BoxZoom = Handler.extend({
  10665. initialize: function (map) {
  10666. this._map = map;
  10667. this._container = map._container;
  10668. this._pane = map._panes.overlayPane;
  10669. this._resetStateTimeout = 0;
  10670. map.on('unload', this._destroy, this);
  10671. },
  10672. addHooks: function () {
  10673. on(this._container, 'mousedown', this._onMouseDown, this);
  10674. },
  10675. removeHooks: function () {
  10676. off(this._container, 'mousedown', this._onMouseDown, this);
  10677. },
  10678. moved: function () {
  10679. return this._moved;
  10680. },
  10681. _destroy: function () {
  10682. remove(this._pane);
  10683. delete this._pane;
  10684. },
  10685. _resetState: function () {
  10686. this._resetStateTimeout = 0;
  10687. this._moved = false;
  10688. },
  10689. _clearDeferredResetState: function () {
  10690. if (this._resetStateTimeout !== 0) {
  10691. clearTimeout(this._resetStateTimeout);
  10692. this._resetStateTimeout = 0;
  10693. }
  10694. },
  10695. _onMouseDown: function (e) {
  10696. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  10697. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  10698. // will interrupt the interaction and orphan a box element in the container.
  10699. this._clearDeferredResetState();
  10700. this._resetState();
  10701. disableTextSelection();
  10702. disableImageDrag();
  10703. this._startPoint = this._map.mouseEventToContainerPoint(e);
  10704. on(document, {
  10705. contextmenu: stop,
  10706. mousemove: this._onMouseMove,
  10707. mouseup: this._onMouseUp,
  10708. keydown: this._onKeyDown
  10709. }, this);
  10710. },
  10711. _onMouseMove: function (e) {
  10712. if (!this._moved) {
  10713. this._moved = true;
  10714. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  10715. addClass(this._container, 'leaflet-crosshair');
  10716. this._map.fire('boxzoomstart');
  10717. }
  10718. this._point = this._map.mouseEventToContainerPoint(e);
  10719. var bounds = new Bounds(this._point, this._startPoint),
  10720. size = bounds.getSize();
  10721. setPosition(this._box, bounds.min);
  10722. this._box.style.width = size.x + 'px';
  10723. this._box.style.height = size.y + 'px';
  10724. },
  10725. _finish: function () {
  10726. if (this._moved) {
  10727. remove(this._box);
  10728. removeClass(this._container, 'leaflet-crosshair');
  10729. }
  10730. enableTextSelection();
  10731. enableImageDrag();
  10732. off(document, {
  10733. contextmenu: stop,
  10734. mousemove: this._onMouseMove,
  10735. mouseup: this._onMouseUp,
  10736. keydown: this._onKeyDown
  10737. }, this);
  10738. },
  10739. _onMouseUp: function (e) {
  10740. if ((e.which !== 1) && (e.button !== 1)) { return; }
  10741. this._finish();
  10742. if (!this._moved) { return; }
  10743. // Postpone to next JS tick so internal click event handling
  10744. // still see it as "moved".
  10745. this._clearDeferredResetState();
  10746. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  10747. var bounds = new LatLngBounds(
  10748. this._map.containerPointToLatLng(this._startPoint),
  10749. this._map.containerPointToLatLng(this._point));
  10750. this._map
  10751. .fitBounds(bounds)
  10752. .fire('boxzoomend', {boxZoomBounds: bounds});
  10753. },
  10754. _onKeyDown: function (e) {
  10755. if (e.keyCode === 27) {
  10756. this._finish();
  10757. }
  10758. }
  10759. });
  10760. // @section Handlers
  10761. // @property boxZoom: Handler
  10762. // Box (shift-drag with mouse) zoom handler.
  10763. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  10764. /*
  10765. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  10766. */
  10767. // @namespace Map
  10768. // @section Interaction Options
  10769. Map.mergeOptions({
  10770. // @option doubleClickZoom: Boolean|String = true
  10771. // Whether the map can be zoomed in by double clicking on it and
  10772. // zoomed out by double clicking while holding shift. If passed
  10773. // `'center'`, double-click zoom will zoom to the center of the
  10774. // view regardless of where the mouse was.
  10775. doubleClickZoom: true
  10776. });
  10777. var DoubleClickZoom = Handler.extend({
  10778. addHooks: function () {
  10779. this._map.on('dblclick', this._onDoubleClick, this);
  10780. },
  10781. removeHooks: function () {
  10782. this._map.off('dblclick', this._onDoubleClick, this);
  10783. },
  10784. _onDoubleClick: function (e) {
  10785. var map = this._map,
  10786. oldZoom = map.getZoom(),
  10787. delta = map.options.zoomDelta,
  10788. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  10789. if (map.options.doubleClickZoom === 'center') {
  10790. map.setZoom(zoom);
  10791. } else {
  10792. map.setZoomAround(e.containerPoint, zoom);
  10793. }
  10794. }
  10795. });
  10796. // @section Handlers
  10797. //
  10798. // Map properties include interaction handlers that allow you to control
  10799. // interaction behavior in runtime, enabling or disabling certain features such
  10800. // as dragging or touch zoom (see `Handler` methods). For example:
  10801. //
  10802. // ```js
  10803. // map.doubleClickZoom.disable();
  10804. // ```
  10805. //
  10806. // @property doubleClickZoom: Handler
  10807. // Double click zoom handler.
  10808. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  10809. /*
  10810. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  10811. */
  10812. // @namespace Map
  10813. // @section Interaction Options
  10814. Map.mergeOptions({
  10815. // @option dragging: Boolean = true
  10816. // Whether the map be draggable with mouse/touch or not.
  10817. dragging: true,
  10818. // @section Panning Inertia Options
  10819. // @option inertia: Boolean = *
  10820. // If enabled, panning of the map will have an inertia effect where
  10821. // the map builds momentum while dragging and continues moving in
  10822. // the same direction for some time. Feels especially nice on touch
  10823. // devices. Enabled by default unless running on old Android devices.
  10824. inertia: !android23,
  10825. // @option inertiaDeceleration: Number = 3000
  10826. // The rate with which the inertial movement slows down, in pixels/second².
  10827. inertiaDeceleration: 3400, // px/s^2
  10828. // @option inertiaMaxSpeed: Number = Infinity
  10829. // Max speed of the inertial movement, in pixels/second.
  10830. inertiaMaxSpeed: Infinity, // px/s
  10831. // @option easeLinearity: Number = 0.2
  10832. easeLinearity: 0.2,
  10833. // TODO refactor, move to CRS
  10834. // @option worldCopyJump: Boolean = false
  10835. // With this option enabled, the map tracks when you pan to another "copy"
  10836. // of the world and seamlessly jumps to the original one so that all overlays
  10837. // like markers and vector layers are still visible.
  10838. worldCopyJump: false,
  10839. // @option maxBoundsViscosity: Number = 0.0
  10840. // If `maxBounds` is set, this option will control how solid the bounds
  10841. // are when dragging the map around. The default value of `0.0` allows the
  10842. // user to drag outside the bounds at normal speed, higher values will
  10843. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  10844. // solid, preventing the user from dragging outside the bounds.
  10845. maxBoundsViscosity: 0.0
  10846. });
  10847. var Drag = Handler.extend({
  10848. addHooks: function () {
  10849. if (!this._draggable) {
  10850. var map = this._map;
  10851. this._draggable = new Draggable(map._mapPane, map._container);
  10852. this._draggable.on({
  10853. dragstart: this._onDragStart,
  10854. drag: this._onDrag,
  10855. dragend: this._onDragEnd
  10856. }, this);
  10857. this._draggable.on('predrag', this._onPreDragLimit, this);
  10858. if (map.options.worldCopyJump) {
  10859. this._draggable.on('predrag', this._onPreDragWrap, this);
  10860. map.on('zoomend', this._onZoomEnd, this);
  10861. map.whenReady(this._onZoomEnd, this);
  10862. }
  10863. }
  10864. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  10865. this._draggable.enable();
  10866. this._positions = [];
  10867. this._times = [];
  10868. },
  10869. removeHooks: function () {
  10870. removeClass(this._map._container, 'leaflet-grab');
  10871. removeClass(this._map._container, 'leaflet-touch-drag');
  10872. this._draggable.disable();
  10873. },
  10874. moved: function () {
  10875. return this._draggable && this._draggable._moved;
  10876. },
  10877. moving: function () {
  10878. return this._draggable && this._draggable._moving;
  10879. },
  10880. _onDragStart: function () {
  10881. var map = this._map;
  10882. map._stop();
  10883. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  10884. var bounds = toLatLngBounds(this._map.options.maxBounds);
  10885. this._offsetLimit = toBounds(
  10886. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  10887. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  10888. .add(this._map.getSize()));
  10889. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  10890. } else {
  10891. this._offsetLimit = null;
  10892. }
  10893. map
  10894. .fire('movestart')
  10895. .fire('dragstart');
  10896. if (map.options.inertia) {
  10897. this._positions = [];
  10898. this._times = [];
  10899. }
  10900. },
  10901. _onDrag: function (e) {
  10902. if (this._map.options.inertia) {
  10903. var time = this._lastTime = +new Date(),
  10904. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  10905. this._positions.push(pos);
  10906. this._times.push(time);
  10907. this._prunePositions(time);
  10908. }
  10909. this._map
  10910. .fire('move', e)
  10911. .fire('drag', e);
  10912. },
  10913. _prunePositions: function (time) {
  10914. while (this._positions.length > 1 && time - this._times[0] > 50) {
  10915. this._positions.shift();
  10916. this._times.shift();
  10917. }
  10918. },
  10919. _onZoomEnd: function () {
  10920. var pxCenter = this._map.getSize().divideBy(2),
  10921. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  10922. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  10923. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  10924. },
  10925. _viscousLimit: function (value, threshold) {
  10926. return value - (value - threshold) * this._viscosity;
  10927. },
  10928. _onPreDragLimit: function () {
  10929. if (!this._viscosity || !this._offsetLimit) { return; }
  10930. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  10931. var limit = this._offsetLimit;
  10932. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  10933. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  10934. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  10935. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  10936. this._draggable._newPos = this._draggable._startPos.add(offset);
  10937. },
  10938. _onPreDragWrap: function () {
  10939. // TODO refactor to be able to adjust map pane position after zoom
  10940. var worldWidth = this._worldWidth,
  10941. halfWidth = Math.round(worldWidth / 2),
  10942. dx = this._initialWorldOffset,
  10943. x = this._draggable._newPos.x,
  10944. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  10945. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  10946. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  10947. this._draggable._absPos = this._draggable._newPos.clone();
  10948. this._draggable._newPos.x = newX;
  10949. },
  10950. _onDragEnd: function (e) {
  10951. var map = this._map,
  10952. options = map.options,
  10953. noInertia = !options.inertia || this._times.length < 2;
  10954. map.fire('dragend', e);
  10955. if (noInertia) {
  10956. map.fire('moveend');
  10957. } else {
  10958. this._prunePositions(+new Date());
  10959. var direction = this._lastPos.subtract(this._positions[0]),
  10960. duration = (this._lastTime - this._times[0]) / 1000,
  10961. ease = options.easeLinearity,
  10962. speedVector = direction.multiplyBy(ease / duration),
  10963. speed = speedVector.distanceTo([0, 0]),
  10964. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  10965. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  10966. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  10967. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  10968. if (!offset.x && !offset.y) {
  10969. map.fire('moveend');
  10970. } else {
  10971. offset = map._limitOffset(offset, map.options.maxBounds);
  10972. requestAnimFrame(function () {
  10973. map.panBy(offset, {
  10974. duration: decelerationDuration,
  10975. easeLinearity: ease,
  10976. noMoveStart: true,
  10977. animate: true
  10978. });
  10979. });
  10980. }
  10981. }
  10982. }
  10983. });
  10984. // @section Handlers
  10985. // @property dragging: Handler
  10986. // Map dragging handler (by both mouse and touch).
  10987. Map.addInitHook('addHandler', 'dragging', Drag);
  10988. /*
  10989. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  10990. */
  10991. // @namespace Map
  10992. // @section Keyboard Navigation Options
  10993. Map.mergeOptions({
  10994. // @option keyboard: Boolean = true
  10995. // Makes the map focusable and allows users to navigate the map with keyboard
  10996. // arrows and `+`/`-` keys.
  10997. keyboard: true,
  10998. // @option keyboardPanDelta: Number = 80
  10999. // Amount of pixels to pan when pressing an arrow key.
  11000. keyboardPanDelta: 80
  11001. });
  11002. var Keyboard = Handler.extend({
  11003. keyCodes: {
  11004. left: [37],
  11005. right: [39],
  11006. down: [40],
  11007. up: [38],
  11008. zoomIn: [187, 107, 61, 171],
  11009. zoomOut: [189, 109, 54, 173]
  11010. },
  11011. initialize: function (map) {
  11012. this._map = map;
  11013. this._setPanDelta(map.options.keyboardPanDelta);
  11014. this._setZoomDelta(map.options.zoomDelta);
  11015. },
  11016. addHooks: function () {
  11017. var container = this._map._container;
  11018. // make the container focusable by tabbing
  11019. if (container.tabIndex <= 0) {
  11020. container.tabIndex = '0';
  11021. }
  11022. on(container, {
  11023. focus: this._onFocus,
  11024. blur: this._onBlur,
  11025. mousedown: this._onMouseDown
  11026. }, this);
  11027. this._map.on({
  11028. focus: this._addHooks,
  11029. blur: this._removeHooks
  11030. }, this);
  11031. },
  11032. removeHooks: function () {
  11033. this._removeHooks();
  11034. off(this._map._container, {
  11035. focus: this._onFocus,
  11036. blur: this._onBlur,
  11037. mousedown: this._onMouseDown
  11038. }, this);
  11039. this._map.off({
  11040. focus: this._addHooks,
  11041. blur: this._removeHooks
  11042. }, this);
  11043. },
  11044. _onMouseDown: function () {
  11045. if (this._focused) { return; }
  11046. var body = document.body,
  11047. docEl = document.documentElement,
  11048. top = body.scrollTop || docEl.scrollTop,
  11049. left = body.scrollLeft || docEl.scrollLeft;
  11050. this._map._container.focus();
  11051. window.scrollTo(left, top);
  11052. },
  11053. _onFocus: function () {
  11054. this._focused = true;
  11055. this._map.fire('focus');
  11056. },
  11057. _onBlur: function () {
  11058. this._focused = false;
  11059. this._map.fire('blur');
  11060. },
  11061. _setPanDelta: function (panDelta) {
  11062. var keys = this._panKeys = {},
  11063. codes = this.keyCodes,
  11064. i, len;
  11065. for (i = 0, len = codes.left.length; i < len; i++) {
  11066. keys[codes.left[i]] = [-1 * panDelta, 0];
  11067. }
  11068. for (i = 0, len = codes.right.length; i < len; i++) {
  11069. keys[codes.right[i]] = [panDelta, 0];
  11070. }
  11071. for (i = 0, len = codes.down.length; i < len; i++) {
  11072. keys[codes.down[i]] = [0, panDelta];
  11073. }
  11074. for (i = 0, len = codes.up.length; i < len; i++) {
  11075. keys[codes.up[i]] = [0, -1 * panDelta];
  11076. }
  11077. },
  11078. _setZoomDelta: function (zoomDelta) {
  11079. var keys = this._zoomKeys = {},
  11080. codes = this.keyCodes,
  11081. i, len;
  11082. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  11083. keys[codes.zoomIn[i]] = zoomDelta;
  11084. }
  11085. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  11086. keys[codes.zoomOut[i]] = -zoomDelta;
  11087. }
  11088. },
  11089. _addHooks: function () {
  11090. on(document, 'keydown', this._onKeyDown, this);
  11091. },
  11092. _removeHooks: function () {
  11093. off(document, 'keydown', this._onKeyDown, this);
  11094. },
  11095. _onKeyDown: function (e) {
  11096. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  11097. var key = e.keyCode,
  11098. map = this._map,
  11099. offset;
  11100. if (key in this._panKeys) {
  11101. if (!map._panAnim || !map._panAnim._inProgress) {
  11102. offset = this._panKeys[key];
  11103. if (e.shiftKey) {
  11104. offset = toPoint(offset).multiplyBy(3);
  11105. }
  11106. map.panBy(offset);
  11107. if (map.options.maxBounds) {
  11108. map.panInsideBounds(map.options.maxBounds);
  11109. }
  11110. }
  11111. } else if (key in this._zoomKeys) {
  11112. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  11113. } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
  11114. map.closePopup();
  11115. } else {
  11116. return;
  11117. }
  11118. stop(e);
  11119. }
  11120. });
  11121. // @section Handlers
  11122. // @section Handlers
  11123. // @property keyboard: Handler
  11124. // Keyboard navigation handler.
  11125. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  11126. /*
  11127. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  11128. */
  11129. // @namespace Map
  11130. // @section Interaction Options
  11131. Map.mergeOptions({
  11132. // @section Mousewheel options
  11133. // @option scrollWheelZoom: Boolean|String = true
  11134. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  11135. // it will zoom to the center of the view regardless of where the mouse was.
  11136. scrollWheelZoom: true,
  11137. // @option wheelDebounceTime: Number = 40
  11138. // Limits the rate at which a wheel can fire (in milliseconds). By default
  11139. // user can't zoom via wheel more often than once per 40 ms.
  11140. wheelDebounceTime: 40,
  11141. // @option wheelPxPerZoomLevel: Number = 60
  11142. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  11143. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  11144. // faster (and vice versa).
  11145. wheelPxPerZoomLevel: 60
  11146. });
  11147. var ScrollWheelZoom = Handler.extend({
  11148. addHooks: function () {
  11149. on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  11150. this._delta = 0;
  11151. },
  11152. removeHooks: function () {
  11153. off(this._map._container, 'mousewheel', this._onWheelScroll, this);
  11154. },
  11155. _onWheelScroll: function (e) {
  11156. var delta = getWheelDelta(e);
  11157. var debounce = this._map.options.wheelDebounceTime;
  11158. this._delta += delta;
  11159. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  11160. if (!this._startTime) {
  11161. this._startTime = +new Date();
  11162. }
  11163. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  11164. clearTimeout(this._timer);
  11165. this._timer = setTimeout(bind(this._performZoom, this), left);
  11166. stop(e);
  11167. },
  11168. _performZoom: function () {
  11169. var map = this._map,
  11170. zoom = map.getZoom(),
  11171. snap = this._map.options.zoomSnap || 0;
  11172. map._stop(); // stop panning and fly animations if any
  11173. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  11174. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  11175. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  11176. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  11177. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  11178. this._delta = 0;
  11179. this._startTime = null;
  11180. if (!delta) { return; }
  11181. if (map.options.scrollWheelZoom === 'center') {
  11182. map.setZoom(zoom + delta);
  11183. } else {
  11184. map.setZoomAround(this._lastMousePos, zoom + delta);
  11185. }
  11186. }
  11187. });
  11188. // @section Handlers
  11189. // @property scrollWheelZoom: Handler
  11190. // Scroll wheel zoom handler.
  11191. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  11192. /*
  11193. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  11194. */
  11195. // @namespace Map
  11196. // @section Interaction Options
  11197. Map.mergeOptions({
  11198. // @section Touch interaction options
  11199. // @option tap: Boolean = true
  11200. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  11201. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  11202. tap: true,
  11203. // @option tapTolerance: Number = 15
  11204. // The max number of pixels a user can shift his finger during touch
  11205. // for it to be considered a valid tap.
  11206. tapTolerance: 15
  11207. });
  11208. var Tap = Handler.extend({
  11209. addHooks: function () {
  11210. on(this._map._container, 'touchstart', this._onDown, this);
  11211. },
  11212. removeHooks: function () {
  11213. off(this._map._container, 'touchstart', this._onDown, this);
  11214. },
  11215. _onDown: function (e) {
  11216. if (!e.touches) { return; }
  11217. preventDefault(e);
  11218. this._fireClick = true;
  11219. // don't simulate click or track longpress if more than 1 touch
  11220. if (e.touches.length > 1) {
  11221. this._fireClick = false;
  11222. clearTimeout(this._holdTimeout);
  11223. return;
  11224. }
  11225. var first = e.touches[0],
  11226. el = first.target;
  11227. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  11228. // if touching a link, highlight it
  11229. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  11230. addClass(el, 'leaflet-active');
  11231. }
  11232. // simulate long hold but setting a timeout
  11233. this._holdTimeout = setTimeout(bind(function () {
  11234. if (this._isTapValid()) {
  11235. this._fireClick = false;
  11236. this._onUp();
  11237. this._simulateEvent('contextmenu', first);
  11238. }
  11239. }, this), 1000);
  11240. this._simulateEvent('mousedown', first);
  11241. on(document, {
  11242. touchmove: this._onMove,
  11243. touchend: this._onUp
  11244. }, this);
  11245. },
  11246. _onUp: function (e) {
  11247. clearTimeout(this._holdTimeout);
  11248. off(document, {
  11249. touchmove: this._onMove,
  11250. touchend: this._onUp
  11251. }, this);
  11252. if (this._fireClick && e && e.changedTouches) {
  11253. var first = e.changedTouches[0],
  11254. el = first.target;
  11255. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  11256. removeClass(el, 'leaflet-active');
  11257. }
  11258. this._simulateEvent('mouseup', first);
  11259. // simulate click if the touch didn't move too much
  11260. if (this._isTapValid()) {
  11261. this._simulateEvent('click', first);
  11262. }
  11263. }
  11264. },
  11265. _isTapValid: function () {
  11266. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11267. },
  11268. _onMove: function (e) {
  11269. var first = e.touches[0];
  11270. this._newPos = new Point(first.clientX, first.clientY);
  11271. this._simulateEvent('mousemove', first);
  11272. },
  11273. _simulateEvent: function (type, e) {
  11274. var simulatedEvent = document.createEvent('MouseEvents');
  11275. simulatedEvent._simulated = true;
  11276. e.target._simulatedClick = true;
  11277. simulatedEvent.initMouseEvent(
  11278. type, true, true, window, 1,
  11279. e.screenX, e.screenY,
  11280. e.clientX, e.clientY,
  11281. false, false, false, false, 0, null);
  11282. e.target.dispatchEvent(simulatedEvent);
  11283. }
  11284. });
  11285. // @section Handlers
  11286. // @property tap: Handler
  11287. // Mobile touch hacks (quick tap and touch hold) handler.
  11288. if (touch && !pointer) {
  11289. Map.addInitHook('addHandler', 'tap', Tap);
  11290. }
  11291. /*
  11292. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11293. */
  11294. // @namespace Map
  11295. // @section Interaction Options
  11296. Map.mergeOptions({
  11297. // @section Touch interaction options
  11298. // @option touchZoom: Boolean|String = *
  11299. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11300. // passed `'center'`, it will zoom to the center of the view regardless of
  11301. // where the touch events (fingers) were. Enabled for touch-capable web
  11302. // browsers except for old Androids.
  11303. touchZoom: touch && !android23,
  11304. // @option bounceAtZoomLimits: Boolean = true
  11305. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11306. // and then bounce back when pinch-zooming.
  11307. bounceAtZoomLimits: true
  11308. });
  11309. var TouchZoom = Handler.extend({
  11310. addHooks: function () {
  11311. addClass(this._map._container, 'leaflet-touch-zoom');
  11312. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11313. },
  11314. removeHooks: function () {
  11315. removeClass(this._map._container, 'leaflet-touch-zoom');
  11316. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11317. },
  11318. _onTouchStart: function (e) {
  11319. var map = this._map;
  11320. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  11321. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11322. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11323. this._centerPoint = map.getSize()._divideBy(2);
  11324. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11325. if (map.options.touchZoom !== 'center') {
  11326. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11327. }
  11328. this._startDist = p1.distanceTo(p2);
  11329. this._startZoom = map.getZoom();
  11330. this._moved = false;
  11331. this._zooming = true;
  11332. map._stop();
  11333. on(document, 'touchmove', this._onTouchMove, this);
  11334. on(document, 'touchend', this._onTouchEnd, this);
  11335. preventDefault(e);
  11336. },
  11337. _onTouchMove: function (e) {
  11338. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  11339. var map = this._map,
  11340. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11341. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11342. scale = p1.distanceTo(p2) / this._startDist;
  11343. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11344. if (!map.options.bounceAtZoomLimits && (
  11345. (this._zoom < map.getMinZoom() && scale < 1) ||
  11346. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11347. this._zoom = map._limitZoom(this._zoom);
  11348. }
  11349. if (map.options.touchZoom === 'center') {
  11350. this._center = this._startLatLng;
  11351. if (scale === 1) { return; }
  11352. } else {
  11353. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11354. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11355. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  11356. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11357. }
  11358. if (!this._moved) {
  11359. map._moveStart(true, false);
  11360. this._moved = true;
  11361. }
  11362. cancelAnimFrame(this._animRequest);
  11363. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  11364. this._animRequest = requestAnimFrame(moveFn, this, true);
  11365. preventDefault(e);
  11366. },
  11367. _onTouchEnd: function () {
  11368. if (!this._moved || !this._zooming) {
  11369. this._zooming = false;
  11370. return;
  11371. }
  11372. this._zooming = false;
  11373. cancelAnimFrame(this._animRequest);
  11374. off(document, 'touchmove', this._onTouchMove);
  11375. off(document, 'touchend', this._onTouchEnd);
  11376. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11377. if (this._map.options.zoomAnimation) {
  11378. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11379. } else {
  11380. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11381. }
  11382. }
  11383. });
  11384. // @section Handlers
  11385. // @property touchZoom: Handler
  11386. // Touch zoom handler.
  11387. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11388. Map.BoxZoom = BoxZoom;
  11389. Map.DoubleClickZoom = DoubleClickZoom;
  11390. Map.Drag = Drag;
  11391. Map.Keyboard = Keyboard;
  11392. Map.ScrollWheelZoom = ScrollWheelZoom;
  11393. Map.Tap = Tap;
  11394. Map.TouchZoom = TouchZoom;
  11395. Object.freeze = freeze;
  11396. exports.version = version;
  11397. exports.Control = Control;
  11398. exports.control = control;
  11399. exports.Browser = Browser;
  11400. exports.Evented = Evented;
  11401. exports.Mixin = Mixin;
  11402. exports.Util = Util;
  11403. exports.Class = Class;
  11404. exports.Handler = Handler;
  11405. exports.extend = extend;
  11406. exports.bind = bind;
  11407. exports.stamp = stamp;
  11408. exports.setOptions = setOptions;
  11409. exports.DomEvent = DomEvent;
  11410. exports.DomUtil = DomUtil;
  11411. exports.PosAnimation = PosAnimation;
  11412. exports.Draggable = Draggable;
  11413. exports.LineUtil = LineUtil;
  11414. exports.PolyUtil = PolyUtil;
  11415. exports.Point = Point;
  11416. exports.point = toPoint;
  11417. exports.Bounds = Bounds;
  11418. exports.bounds = toBounds;
  11419. exports.Transformation = Transformation;
  11420. exports.transformation = toTransformation;
  11421. exports.Projection = index;
  11422. exports.LatLng = LatLng;
  11423. exports.latLng = toLatLng;
  11424. exports.LatLngBounds = LatLngBounds;
  11425. exports.latLngBounds = toLatLngBounds;
  11426. exports.CRS = CRS;
  11427. exports.GeoJSON = GeoJSON;
  11428. exports.geoJSON = geoJSON;
  11429. exports.geoJson = geoJson;
  11430. exports.Layer = Layer;
  11431. exports.LayerGroup = LayerGroup;
  11432. exports.layerGroup = layerGroup;
  11433. exports.FeatureGroup = FeatureGroup;
  11434. exports.featureGroup = featureGroup;
  11435. exports.ImageOverlay = ImageOverlay;
  11436. exports.imageOverlay = imageOverlay;
  11437. exports.VideoOverlay = VideoOverlay;
  11438. exports.videoOverlay = videoOverlay;
  11439. exports.SVGOverlay = SVGOverlay;
  11440. exports.svgOverlay = svgOverlay;
  11441. exports.DivOverlay = DivOverlay;
  11442. exports.Popup = Popup;
  11443. exports.popup = popup;
  11444. exports.Tooltip = Tooltip;
  11445. exports.tooltip = tooltip;
  11446. exports.Icon = Icon;
  11447. exports.icon = icon;
  11448. exports.DivIcon = DivIcon;
  11449. exports.divIcon = divIcon;
  11450. exports.Marker = Marker;
  11451. exports.marker = marker;
  11452. exports.TileLayer = TileLayer;
  11453. exports.tileLayer = tileLayer;
  11454. exports.GridLayer = GridLayer;
  11455. exports.gridLayer = gridLayer;
  11456. exports.SVG = SVG;
  11457. exports.svg = svg$1;
  11458. exports.Renderer = Renderer;
  11459. exports.Canvas = Canvas;
  11460. exports.canvas = canvas$1;
  11461. exports.Path = Path;
  11462. exports.CircleMarker = CircleMarker;
  11463. exports.circleMarker = circleMarker;
  11464. exports.Circle = Circle;
  11465. exports.circle = circle;
  11466. exports.Polyline = Polyline;
  11467. exports.polyline = polyline;
  11468. exports.Polygon = Polygon;
  11469. exports.polygon = polygon;
  11470. exports.Rectangle = Rectangle;
  11471. exports.rectangle = rectangle;
  11472. exports.Map = Map;
  11473. exports.map = createMap;
  11474. var oldL = window.L;
  11475. exports.noConflict = function() {
  11476. window.L = oldL;
  11477. return this;
  11478. }
  11479. // Always export us to window global (see #2364)
  11480. window.L = exports;
  11481. })));
  11482. //# sourceMappingURL=leaflet-src.js.map