leaflet-src.js 389 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020
  1. /* @preserve
  2. * Leaflet 1.5.1+build.2e3e0ff, a JS library for interactive maps. http://leafletjs.com
  3. * (c) 2010-2018 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.5.1+build.2e3e0ffb";
  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. digits = (digits === undefined ? 6 : digits);
  110. return +(Math.round(num + ('e+' + digits)) + ('e-' + digits));
  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 = !!(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 canvas: Boolean
  1594. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1595. var canvas = (function () {
  1596. return !!document.createElement('canvas').getContext;
  1597. }());
  1598. // @property svg: Boolean
  1599. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1600. var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1601. // @property vml: Boolean
  1602. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1603. var vml = !svg && (function () {
  1604. try {
  1605. var div = document.createElement('div');
  1606. div.innerHTML = '<v:shape adj="1"/>';
  1607. var shape = div.firstChild;
  1608. shape.style.behavior = 'url(#default#VML)';
  1609. return shape && (typeof shape.adj === 'object');
  1610. } catch (e) {
  1611. return false;
  1612. }
  1613. }());
  1614. function userAgentContains(str) {
  1615. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1616. }
  1617. var Browser = (Object.freeze || Object)({
  1618. ie: ie,
  1619. ielt9: ielt9,
  1620. edge: edge,
  1621. webkit: webkit,
  1622. android: android,
  1623. android23: android23,
  1624. androidStock: androidStock,
  1625. opera: opera,
  1626. chrome: chrome,
  1627. gecko: gecko,
  1628. safari: safari,
  1629. phantom: phantom,
  1630. opera12: opera12,
  1631. win: win,
  1632. ie3d: ie3d,
  1633. webkit3d: webkit3d,
  1634. gecko3d: gecko3d,
  1635. any3d: any3d,
  1636. mobile: mobile,
  1637. mobileWebkit: mobileWebkit,
  1638. mobileWebkit3d: mobileWebkit3d,
  1639. msPointer: msPointer,
  1640. pointer: pointer,
  1641. touch: touch,
  1642. mobileOpera: mobileOpera,
  1643. mobileGecko: mobileGecko,
  1644. retina: retina,
  1645. canvas: canvas,
  1646. svg: svg,
  1647. vml: vml
  1648. });
  1649. /*
  1650. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1651. */
  1652. var POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';
  1653. var POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';
  1654. var POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';
  1655. var POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';
  1656. var TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION'];
  1657. var _pointers = {};
  1658. var _pointerDocListener = false;
  1659. // DomEvent.DoubleTap needs to know about this
  1660. var _pointersCount = 0;
  1661. // Provides a touch events wrapper for (ms)pointer events.
  1662. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1663. function addPointerListener(obj, type, handler, id) {
  1664. if (type === 'touchstart') {
  1665. _addPointerStart(obj, handler, id);
  1666. } else if (type === 'touchmove') {
  1667. _addPointerMove(obj, handler, id);
  1668. } else if (type === 'touchend') {
  1669. _addPointerEnd(obj, handler, id);
  1670. }
  1671. return this;
  1672. }
  1673. function removePointerListener(obj, type, id) {
  1674. var handler = obj['_leaflet_' + type + id];
  1675. if (type === 'touchstart') {
  1676. obj.removeEventListener(POINTER_DOWN, handler, false);
  1677. } else if (type === 'touchmove') {
  1678. obj.removeEventListener(POINTER_MOVE, handler, false);
  1679. } else if (type === 'touchend') {
  1680. obj.removeEventListener(POINTER_UP, handler, false);
  1681. obj.removeEventListener(POINTER_CANCEL, handler, false);
  1682. }
  1683. return this;
  1684. }
  1685. function _addPointerStart(obj, handler, id) {
  1686. var onDown = bind(function (e) {
  1687. if (e.pointerType !== 'mouse' && e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
  1688. // In IE11, some touch events needs to fire for form controls, or
  1689. // the controls will stop working. We keep a whitelist of tag names that
  1690. // need these events. For other target tags, we prevent default on the event.
  1691. if (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
  1692. preventDefault(e);
  1693. } else {
  1694. return;
  1695. }
  1696. }
  1697. _handlePointer(e, handler);
  1698. });
  1699. obj['_leaflet_touchstart' + id] = onDown;
  1700. obj.addEventListener(POINTER_DOWN, onDown, false);
  1701. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1702. if (!_pointerDocListener) {
  1703. // we listen documentElement as any drags that end by moving the touch off the screen get fired there
  1704. document.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1705. document.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1706. document.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true);
  1707. document.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1708. _pointerDocListener = true;
  1709. }
  1710. }
  1711. function _globalPointerDown(e) {
  1712. _pointers[e.pointerId] = e;
  1713. _pointersCount++;
  1714. }
  1715. function _globalPointerMove(e) {
  1716. if (_pointers[e.pointerId]) {
  1717. _pointers[e.pointerId] = e;
  1718. }
  1719. }
  1720. function _globalPointerUp(e) {
  1721. delete _pointers[e.pointerId];
  1722. _pointersCount--;
  1723. }
  1724. function _handlePointer(e, handler) {
  1725. e.touches = [];
  1726. for (var i in _pointers) {
  1727. e.touches.push(_pointers[i]);
  1728. }
  1729. e.changedTouches = [e];
  1730. handler(e);
  1731. }
  1732. function _addPointerMove(obj, handler, id) {
  1733. var onMove = function (e) {
  1734. // don't fire touch moves when mouse isn't down
  1735. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
  1736. _handlePointer(e, handler);
  1737. };
  1738. obj['_leaflet_touchmove' + id] = onMove;
  1739. obj.addEventListener(POINTER_MOVE, onMove, false);
  1740. }
  1741. function _addPointerEnd(obj, handler, id) {
  1742. var onUp = function (e) {
  1743. _handlePointer(e, handler);
  1744. };
  1745. obj['_leaflet_touchend' + id] = onUp;
  1746. obj.addEventListener(POINTER_UP, onUp, false);
  1747. obj.addEventListener(POINTER_CANCEL, onUp, false);
  1748. }
  1749. /*
  1750. * Extends the event handling code with double tap support for mobile browsers.
  1751. */
  1752. var _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';
  1753. var _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';
  1754. var _pre = '_leaflet_';
  1755. // inspired by Zepto touch code by Thomas Fuchs
  1756. function addDoubleTapListener(obj, handler, id) {
  1757. var last, touch$$1,
  1758. doubleTap = false,
  1759. delay = 250;
  1760. function onTouchStart(e) {
  1761. var count;
  1762. if (pointer) {
  1763. if ((!edge) || e.pointerType === 'mouse') { return; }
  1764. count = _pointersCount;
  1765. } else {
  1766. count = e.touches.length;
  1767. }
  1768. if (count > 1) { return; }
  1769. var now = Date.now(),
  1770. delta = now - (last || now);
  1771. touch$$1 = e.touches ? e.touches[0] : e;
  1772. doubleTap = (delta > 0 && delta <= delay);
  1773. last = now;
  1774. }
  1775. function onTouchEnd(e) {
  1776. if (doubleTap && !touch$$1.cancelBubble) {
  1777. if (pointer) {
  1778. if ((!edge) || e.pointerType === 'mouse') { return; }
  1779. // work around .type being readonly with MSPointer* events
  1780. var newTouch = {},
  1781. prop, i;
  1782. for (i in touch$$1) {
  1783. prop = touch$$1[i];
  1784. newTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;
  1785. }
  1786. touch$$1 = newTouch;
  1787. }
  1788. touch$$1.type = 'dblclick';
  1789. touch$$1.button = 0;
  1790. handler(touch$$1);
  1791. last = null;
  1792. }
  1793. }
  1794. obj[_pre + _touchstart + id] = onTouchStart;
  1795. obj[_pre + _touchend + id] = onTouchEnd;
  1796. obj[_pre + 'dblclick' + id] = handler;
  1797. obj.addEventListener(_touchstart, onTouchStart, false);
  1798. obj.addEventListener(_touchend, onTouchEnd, false);
  1799. // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
  1800. // the browser doesn't fire touchend/pointerup events but does fire
  1801. // native dblclicks. See #4127.
  1802. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
  1803. obj.addEventListener('dblclick', handler, false);
  1804. return this;
  1805. }
  1806. function removeDoubleTapListener(obj, id) {
  1807. var touchstart = obj[_pre + _touchstart + id],
  1808. touchend = obj[_pre + _touchend + id],
  1809. dblclick = obj[_pre + 'dblclick' + id];
  1810. obj.removeEventListener(_touchstart, touchstart, false);
  1811. obj.removeEventListener(_touchend, touchend, false);
  1812. if (!edge) {
  1813. obj.removeEventListener('dblclick', dblclick, false);
  1814. }
  1815. return this;
  1816. }
  1817. /*
  1818. * @namespace DomUtil
  1819. *
  1820. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1821. * tree, used by Leaflet internally.
  1822. *
  1823. * Most functions expecting or returning a `HTMLElement` also work for
  1824. * SVG elements. The only difference is that classes refer to CSS classes
  1825. * in HTML and SVG classes in SVG.
  1826. */
  1827. // @property TRANSFORM: String
  1828. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  1829. var TRANSFORM = testProp(
  1830. ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1831. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1832. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1833. // @property TRANSITION: String
  1834. // Vendor-prefixed transition style name.
  1835. var TRANSITION = testProp(
  1836. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1837. // @property TRANSITION_END: String
  1838. // Vendor-prefixed transitionend event name.
  1839. var TRANSITION_END =
  1840. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  1841. // @function get(id: String|HTMLElement): HTMLElement
  1842. // Returns an element given its DOM id, or returns the element itself
  1843. // if it was passed directly.
  1844. function get(id) {
  1845. return typeof id === 'string' ? document.getElementById(id) : id;
  1846. }
  1847. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1848. // Returns the value for a certain style attribute on an element,
  1849. // including computed values or values set through CSS.
  1850. function getStyle(el, style) {
  1851. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1852. if ((!value || value === 'auto') && document.defaultView) {
  1853. var css = document.defaultView.getComputedStyle(el, null);
  1854. value = css ? css[style] : null;
  1855. }
  1856. return value === 'auto' ? null : value;
  1857. }
  1858. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1859. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1860. function create$1(tagName, className, container) {
  1861. var el = document.createElement(tagName);
  1862. el.className = className || '';
  1863. if (container) {
  1864. container.appendChild(el);
  1865. }
  1866. return el;
  1867. }
  1868. // @function remove(el: HTMLElement)
  1869. // Removes `el` from its parent element
  1870. function remove(el) {
  1871. var parent = el.parentNode;
  1872. if (parent) {
  1873. parent.removeChild(el);
  1874. }
  1875. }
  1876. // @function empty(el: HTMLElement)
  1877. // Removes all of `el`'s children elements from `el`
  1878. function empty(el) {
  1879. while (el.firstChild) {
  1880. el.removeChild(el.firstChild);
  1881. }
  1882. }
  1883. // @function toFront(el: HTMLElement)
  1884. // Makes `el` the last child of its parent, so it renders in front of the other children.
  1885. function toFront(el) {
  1886. var parent = el.parentNode;
  1887. if (parent && parent.lastChild !== el) {
  1888. parent.appendChild(el);
  1889. }
  1890. }
  1891. // @function toBack(el: HTMLElement)
  1892. // Makes `el` the first child of its parent, so it renders behind the other children.
  1893. function toBack(el) {
  1894. var parent = el.parentNode;
  1895. if (parent && parent.firstChild !== el) {
  1896. parent.insertBefore(el, parent.firstChild);
  1897. }
  1898. }
  1899. // @function hasClass(el: HTMLElement, name: String): Boolean
  1900. // Returns `true` if the element's class attribute contains `name`.
  1901. function hasClass(el, name) {
  1902. if (el.classList !== undefined) {
  1903. return el.classList.contains(name);
  1904. }
  1905. var className = getClass(el);
  1906. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  1907. }
  1908. // @function addClass(el: HTMLElement, name: String)
  1909. // Adds `name` to the element's class attribute.
  1910. function addClass(el, name) {
  1911. if (el.classList !== undefined) {
  1912. var classes = splitWords(name);
  1913. for (var i = 0, len = classes.length; i < len; i++) {
  1914. el.classList.add(classes[i]);
  1915. }
  1916. } else if (!hasClass(el, name)) {
  1917. var className = getClass(el);
  1918. setClass(el, (className ? className + ' ' : '') + name);
  1919. }
  1920. }
  1921. // @function removeClass(el: HTMLElement, name: String)
  1922. // Removes `name` from the element's class attribute.
  1923. function removeClass(el, name) {
  1924. if (el.classList !== undefined) {
  1925. el.classList.remove(name);
  1926. } else {
  1927. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  1928. }
  1929. }
  1930. // @function setClass(el: HTMLElement, name: String)
  1931. // Sets the element's class.
  1932. function setClass(el, name) {
  1933. if (el.className.baseVal === undefined) {
  1934. el.className = name;
  1935. } else {
  1936. // in case of SVG element
  1937. el.className.baseVal = name;
  1938. }
  1939. }
  1940. // @function getClass(el: HTMLElement): String
  1941. // Returns the element's class.
  1942. function getClass(el) {
  1943. // Check if the element is an SVGElementInstance and use the correspondingElement instead
  1944. // (Required for linked SVG elements in IE11.)
  1945. if (el.correspondingElement) {
  1946. el = el.correspondingElement;
  1947. }
  1948. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  1949. }
  1950. // @function setOpacity(el: HTMLElement, opacity: Number)
  1951. // Set the opacity of an element (including old IE support).
  1952. // `opacity` must be a number from `0` to `1`.
  1953. function setOpacity(el, value) {
  1954. if ('opacity' in el.style) {
  1955. el.style.opacity = value;
  1956. } else if ('filter' in el.style) {
  1957. _setOpacityIE(el, value);
  1958. }
  1959. }
  1960. function _setOpacityIE(el, value) {
  1961. var filter = false,
  1962. filterName = 'DXImageTransform.Microsoft.Alpha';
  1963. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  1964. try {
  1965. filter = el.filters.item(filterName);
  1966. } catch (e) {
  1967. // don't set opacity to 1 if we haven't already set an opacity,
  1968. // it isn't needed and breaks transparent pngs.
  1969. if (value === 1) { return; }
  1970. }
  1971. value = Math.round(value * 100);
  1972. if (filter) {
  1973. filter.Enabled = (value !== 100);
  1974. filter.Opacity = value;
  1975. } else {
  1976. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  1977. }
  1978. }
  1979. // @function testProp(props: String[]): String|false
  1980. // Goes through the array of style names and returns the first name
  1981. // that is a valid style name for an element. If no such name is found,
  1982. // it returns false. Useful for vendor-prefixed styles like `transform`.
  1983. function testProp(props) {
  1984. var style = document.documentElement.style;
  1985. for (var i = 0; i < props.length; i++) {
  1986. if (props[i] in style) {
  1987. return props[i];
  1988. }
  1989. }
  1990. return false;
  1991. }
  1992. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  1993. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  1994. // and optionally scaled by `scale`. Does not have an effect if the
  1995. // browser doesn't support 3D CSS transforms.
  1996. function setTransform(el, offset, scale) {
  1997. var pos = offset || new Point(0, 0);
  1998. el.style[TRANSFORM] =
  1999. (ie3d ?
  2000. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2001. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2002. (scale ? ' scale(' + scale + ')' : '');
  2003. }
  2004. // @function setPosition(el: HTMLElement, position: Point)
  2005. // Sets the position of `el` to coordinates specified by `position`,
  2006. // using CSS translate or top/left positioning depending on the browser
  2007. // (used by Leaflet internally to position its layers).
  2008. function setPosition(el, point) {
  2009. /*eslint-disable */
  2010. el._leaflet_pos = point;
  2011. /* eslint-enable */
  2012. if (any3d) {
  2013. setTransform(el, point);
  2014. } else {
  2015. el.style.left = point.x + 'px';
  2016. el.style.top = point.y + 'px';
  2017. }
  2018. }
  2019. // @function getPosition(el: HTMLElement): Point
  2020. // Returns the coordinates of an element previously positioned with setPosition.
  2021. function getPosition(el) {
  2022. // this method is only used for elements previously positioned using setPosition,
  2023. // so it's safe to cache the position for performance
  2024. return el._leaflet_pos || new Point(0, 0);
  2025. }
  2026. // @function disableTextSelection()
  2027. // Prevents the user from generating `selectstart` DOM events, usually generated
  2028. // when the user drags the mouse through a page with text. Used internally
  2029. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2030. // the map. Affects drag interactions on the whole document.
  2031. // @function enableTextSelection()
  2032. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2033. var disableTextSelection;
  2034. var enableTextSelection;
  2035. var _userSelect;
  2036. if ('onselectstart' in document) {
  2037. disableTextSelection = function () {
  2038. on(window, 'selectstart', preventDefault);
  2039. };
  2040. enableTextSelection = function () {
  2041. off(window, 'selectstart', preventDefault);
  2042. };
  2043. } else {
  2044. var userSelectProperty = testProp(
  2045. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2046. disableTextSelection = function () {
  2047. if (userSelectProperty) {
  2048. var style = document.documentElement.style;
  2049. _userSelect = style[userSelectProperty];
  2050. style[userSelectProperty] = 'none';
  2051. }
  2052. };
  2053. enableTextSelection = function () {
  2054. if (userSelectProperty) {
  2055. document.documentElement.style[userSelectProperty] = _userSelect;
  2056. _userSelect = undefined;
  2057. }
  2058. };
  2059. }
  2060. // @function disableImageDrag()
  2061. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2062. // for `dragstart` DOM events, usually generated when the user drags an image.
  2063. function disableImageDrag() {
  2064. on(window, 'dragstart', preventDefault);
  2065. }
  2066. // @function enableImageDrag()
  2067. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2068. function enableImageDrag() {
  2069. off(window, 'dragstart', preventDefault);
  2070. }
  2071. var _outlineElement;
  2072. var _outlineStyle;
  2073. // @function preventOutline(el: HTMLElement)
  2074. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2075. // of the element `el` invisible. Used internally by Leaflet to prevent
  2076. // focusable elements from displaying an outline when the user performs a
  2077. // drag interaction on them.
  2078. function preventOutline(element) {
  2079. while (element.tabIndex === -1) {
  2080. element = element.parentNode;
  2081. }
  2082. if (!element.style) { return; }
  2083. restoreOutline();
  2084. _outlineElement = element;
  2085. _outlineStyle = element.style.outline;
  2086. element.style.outline = 'none';
  2087. on(window, 'keydown', restoreOutline);
  2088. }
  2089. // @function restoreOutline()
  2090. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2091. function restoreOutline() {
  2092. if (!_outlineElement) { return; }
  2093. _outlineElement.style.outline = _outlineStyle;
  2094. _outlineElement = undefined;
  2095. _outlineStyle = undefined;
  2096. off(window, 'keydown', restoreOutline);
  2097. }
  2098. // @function getSizedParentNode(el: HTMLElement): HTMLElement
  2099. // Finds the closest parent node which size (width and height) is not null.
  2100. function getSizedParentNode(element) {
  2101. do {
  2102. element = element.parentNode;
  2103. } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);
  2104. return element;
  2105. }
  2106. // @function getScale(el: HTMLElement): Object
  2107. // Computes the CSS scale currently applied on the element.
  2108. // Returns an object with `x` and `y` members as horizontal and vertical scales respectively,
  2109. // and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2110. function getScale(element) {
  2111. var rect = element.getBoundingClientRect(); // Read-only in old browsers.
  2112. return {
  2113. x: rect.width / element.offsetWidth || 1,
  2114. y: rect.height / element.offsetHeight || 1,
  2115. boundingClientRect: rect
  2116. };
  2117. }
  2118. var DomUtil = (Object.freeze || Object)({
  2119. TRANSFORM: TRANSFORM,
  2120. TRANSITION: TRANSITION,
  2121. TRANSITION_END: TRANSITION_END,
  2122. get: get,
  2123. getStyle: getStyle,
  2124. create: create$1,
  2125. remove: remove,
  2126. empty: empty,
  2127. toFront: toFront,
  2128. toBack: toBack,
  2129. hasClass: hasClass,
  2130. addClass: addClass,
  2131. removeClass: removeClass,
  2132. setClass: setClass,
  2133. getClass: getClass,
  2134. setOpacity: setOpacity,
  2135. testProp: testProp,
  2136. setTransform: setTransform,
  2137. setPosition: setPosition,
  2138. getPosition: getPosition,
  2139. disableTextSelection: disableTextSelection,
  2140. enableTextSelection: enableTextSelection,
  2141. disableImageDrag: disableImageDrag,
  2142. enableImageDrag: enableImageDrag,
  2143. preventOutline: preventOutline,
  2144. restoreOutline: restoreOutline,
  2145. getSizedParentNode: getSizedParentNode,
  2146. getScale: getScale
  2147. });
  2148. /*
  2149. * @namespace DomEvent
  2150. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  2151. */
  2152. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  2153. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2154. // Adds a listener function (`fn`) to a particular DOM event type of the
  2155. // element `el`. You can optionally specify the context of the listener
  2156. // (object the `this` keyword will point to). You can also pass several
  2157. // space-separated types (e.g. `'click dblclick'`).
  2158. // @alternative
  2159. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  2160. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2161. function on(obj, types, fn, context) {
  2162. if (typeof types === 'object') {
  2163. for (var type in types) {
  2164. addOne(obj, type, types[type], fn);
  2165. }
  2166. } else {
  2167. types = splitWords(types);
  2168. for (var i = 0, len = types.length; i < len; i++) {
  2169. addOne(obj, types[i], fn, context);
  2170. }
  2171. }
  2172. return this;
  2173. }
  2174. var eventsKey = '_leaflet_events';
  2175. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2176. // Removes a previously added listener function.
  2177. // Note that if you passed a custom context to on, you must pass the same
  2178. // context to `off` in order to remove the listener.
  2179. // @alternative
  2180. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  2181. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2182. function off(obj, types, fn, context) {
  2183. if (typeof types === 'object') {
  2184. for (var type in types) {
  2185. removeOne(obj, type, types[type], fn);
  2186. }
  2187. } else if (types) {
  2188. types = splitWords(types);
  2189. for (var i = 0, len = types.length; i < len; i++) {
  2190. removeOne(obj, types[i], fn, context);
  2191. }
  2192. } else {
  2193. for (var j in obj[eventsKey]) {
  2194. removeOne(obj, j, obj[eventsKey][j]);
  2195. }
  2196. delete obj[eventsKey];
  2197. }
  2198. return this;
  2199. }
  2200. function addOne(obj, type, fn, context) {
  2201. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2202. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  2203. var handler = function (e) {
  2204. return fn.call(context || obj, e || window.event);
  2205. };
  2206. var originalHandler = handler;
  2207. if (pointer && type.indexOf('touch') === 0) {
  2208. // Needs DomEvent.Pointer.js
  2209. addPointerListener(obj, type, handler, id);
  2210. } else if (touch && (type === 'dblclick') && addDoubleTapListener &&
  2211. !(pointer && chrome)) {
  2212. // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener
  2213. // See #5180
  2214. addDoubleTapListener(obj, handler, id);
  2215. } else if ('addEventListener' in obj) {
  2216. if (type === 'mousewheel') {
  2217. obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  2218. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  2219. handler = function (e) {
  2220. e = e || window.event;
  2221. if (isExternalTarget(obj, e)) {
  2222. originalHandler(e);
  2223. }
  2224. };
  2225. obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
  2226. } else {
  2227. if (type === 'click' && android) {
  2228. handler = function (e) {
  2229. filterClick(e, originalHandler);
  2230. };
  2231. }
  2232. obj.addEventListener(type, handler, false);
  2233. }
  2234. } else if ('attachEvent' in obj) {
  2235. obj.attachEvent('on' + type, handler);
  2236. }
  2237. obj[eventsKey] = obj[eventsKey] || {};
  2238. obj[eventsKey][id] = handler;
  2239. }
  2240. function removeOne(obj, type, fn, context) {
  2241. var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),
  2242. handler = obj[eventsKey] && obj[eventsKey][id];
  2243. if (!handler) { return this; }
  2244. if (pointer && type.indexOf('touch') === 0) {
  2245. removePointerListener(obj, type, id);
  2246. } else if (touch && (type === 'dblclick') && removeDoubleTapListener &&
  2247. !(pointer && chrome)) {
  2248. removeDoubleTapListener(obj, id);
  2249. } else if ('removeEventListener' in obj) {
  2250. if (type === 'mousewheel') {
  2251. obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  2252. } else {
  2253. obj.removeEventListener(
  2254. type === 'mouseenter' ? 'mouseover' :
  2255. type === 'mouseleave' ? 'mouseout' : type, handler, false);
  2256. }
  2257. } else if ('detachEvent' in obj) {
  2258. obj.detachEvent('on' + type, handler);
  2259. }
  2260. obj[eventsKey][id] = null;
  2261. }
  2262. // @function stopPropagation(ev: DOMEvent): this
  2263. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  2264. // ```js
  2265. // L.DomEvent.on(div, 'click', function (ev) {
  2266. // L.DomEvent.stopPropagation(ev);
  2267. // });
  2268. // ```
  2269. function stopPropagation(e) {
  2270. if (e.stopPropagation) {
  2271. e.stopPropagation();
  2272. } else if (e.originalEvent) { // In case of Leaflet event.
  2273. e.originalEvent._stopped = true;
  2274. } else {
  2275. e.cancelBubble = true;
  2276. }
  2277. skipped(e);
  2278. return this;
  2279. }
  2280. // @function disableScrollPropagation(el: HTMLElement): this
  2281. // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
  2282. function disableScrollPropagation(el) {
  2283. addOne(el, 'mousewheel', stopPropagation);
  2284. return this;
  2285. }
  2286. // @function disableClickPropagation(el: HTMLElement): this
  2287. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  2288. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  2289. function disableClickPropagation(el) {
  2290. on(el, 'mousedown touchstart dblclick', stopPropagation);
  2291. addOne(el, 'click', fakeStop);
  2292. return this;
  2293. }
  2294. // @function preventDefault(ev: DOMEvent): this
  2295. // Prevents the default action of the DOM Event `ev` from happening (such as
  2296. // following a link in the href of the a element, or doing a POST request
  2297. // with page reload when a `<form>` is submitted).
  2298. // Use it inside listener functions.
  2299. function preventDefault(e) {
  2300. if (e.preventDefault) {
  2301. e.preventDefault();
  2302. } else {
  2303. e.returnValue = false;
  2304. }
  2305. return this;
  2306. }
  2307. // @function stop(ev: DOMEvent): this
  2308. // Does `stopPropagation` and `preventDefault` at the same time.
  2309. function stop(e) {
  2310. preventDefault(e);
  2311. stopPropagation(e);
  2312. return this;
  2313. }
  2314. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  2315. // Gets normalized mouse position from a DOM event relative to the
  2316. // `container` (border excluded) or to the whole page if not specified.
  2317. function getMousePosition(e, container) {
  2318. if (!container) {
  2319. return new Point(e.clientX, e.clientY);
  2320. }
  2321. var scale = getScale(container),
  2322. offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)
  2323. return new Point(
  2324. // offset.left/top values are in page scale (like clientX/Y),
  2325. // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
  2326. (e.clientX - offset.left) / scale.x - container.clientLeft,
  2327. (e.clientY - offset.top) / scale.y - container.clientTop
  2328. );
  2329. }
  2330. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  2331. // and Firefox scrolls device pixels, not CSS pixels
  2332. var wheelPxFactor =
  2333. (win && chrome) ? 2 * window.devicePixelRatio :
  2334. gecko ? window.devicePixelRatio : 1;
  2335. // @function getWheelDelta(ev: DOMEvent): Number
  2336. // Gets normalized wheel delta from a mousewheel DOM event, in vertical
  2337. // pixels scrolled (negative if scrolling down).
  2338. // Events from pointing devices without precise scrolling are mapped to
  2339. // a best guess of 60 pixels.
  2340. function getWheelDelta(e) {
  2341. return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2342. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2343. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2344. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2345. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2346. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2347. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2348. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2349. 0;
  2350. }
  2351. var skipEvents = {};
  2352. function fakeStop(e) {
  2353. // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)
  2354. skipEvents[e.type] = true;
  2355. }
  2356. function skipped(e) {
  2357. var events = skipEvents[e.type];
  2358. // reset when checking, as it's only used in map container and propagates outside of the map
  2359. skipEvents[e.type] = false;
  2360. return events;
  2361. }
  2362. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2363. function isExternalTarget(el, e) {
  2364. var related = e.relatedTarget;
  2365. if (!related) { return true; }
  2366. try {
  2367. while (related && (related !== el)) {
  2368. related = related.parentNode;
  2369. }
  2370. } catch (err) {
  2371. return false;
  2372. }
  2373. return (related !== el);
  2374. }
  2375. var lastClick;
  2376. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  2377. function filterClick(e, handler) {
  2378. var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
  2379. elapsed = lastClick && (timeStamp - lastClick);
  2380. // are they closer together than 500ms yet more than 100ms?
  2381. // Android typically triggers them ~300ms apart while multiple listeners
  2382. // on the same event should be triggered far faster;
  2383. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  2384. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  2385. stop(e);
  2386. return;
  2387. }
  2388. lastClick = timeStamp;
  2389. handler(e);
  2390. }
  2391. var DomEvent = (Object.freeze || Object)({
  2392. on: on,
  2393. off: off,
  2394. stopPropagation: stopPropagation,
  2395. disableScrollPropagation: disableScrollPropagation,
  2396. disableClickPropagation: disableClickPropagation,
  2397. preventDefault: preventDefault,
  2398. stop: stop,
  2399. getMousePosition: getMousePosition,
  2400. getWheelDelta: getWheelDelta,
  2401. fakeStop: fakeStop,
  2402. skipped: skipped,
  2403. isExternalTarget: isExternalTarget,
  2404. addListener: on,
  2405. removeListener: off
  2406. });
  2407. /*
  2408. * @class PosAnimation
  2409. * @aka L.PosAnimation
  2410. * @inherits Evented
  2411. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2412. *
  2413. * @example
  2414. * ```js
  2415. * var fx = new L.PosAnimation();
  2416. * fx.run(el, [300, 500], 0.5);
  2417. * ```
  2418. *
  2419. * @constructor L.PosAnimation()
  2420. * Creates a `PosAnimation` object.
  2421. *
  2422. */
  2423. var PosAnimation = Evented.extend({
  2424. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2425. // Run an animation of a given element to a new position, optionally setting
  2426. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2427. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  2428. // `0.5` by default).
  2429. run: function (el, newPos, duration, easeLinearity) {
  2430. this.stop();
  2431. this._el = el;
  2432. this._inProgress = true;
  2433. this._duration = duration || 0.25;
  2434. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2435. this._startPos = getPosition(el);
  2436. this._offset = newPos.subtract(this._startPos);
  2437. this._startTime = +new Date();
  2438. // @event start: Event
  2439. // Fired when the animation starts
  2440. this.fire('start');
  2441. this._animate();
  2442. },
  2443. // @method stop()
  2444. // Stops the animation (if currently running).
  2445. stop: function () {
  2446. if (!this._inProgress) { return; }
  2447. this._step(true);
  2448. this._complete();
  2449. },
  2450. _animate: function () {
  2451. // animation loop
  2452. this._animId = requestAnimFrame(this._animate, this);
  2453. this._step();
  2454. },
  2455. _step: function (round) {
  2456. var elapsed = (+new Date()) - this._startTime,
  2457. duration = this._duration * 1000;
  2458. if (elapsed < duration) {
  2459. this._runFrame(this._easeOut(elapsed / duration), round);
  2460. } else {
  2461. this._runFrame(1);
  2462. this._complete();
  2463. }
  2464. },
  2465. _runFrame: function (progress, round) {
  2466. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2467. if (round) {
  2468. pos._round();
  2469. }
  2470. setPosition(this._el, pos);
  2471. // @event step: Event
  2472. // Fired continuously during the animation.
  2473. this.fire('step');
  2474. },
  2475. _complete: function () {
  2476. cancelAnimFrame(this._animId);
  2477. this._inProgress = false;
  2478. // @event end: Event
  2479. // Fired when the animation ends.
  2480. this.fire('end');
  2481. },
  2482. _easeOut: function (t) {
  2483. return 1 - Math.pow(1 - t, this._easeOutPower);
  2484. }
  2485. });
  2486. /*
  2487. * @class Map
  2488. * @aka L.Map
  2489. * @inherits Evented
  2490. *
  2491. * The central class of the API — it is used to create a map on a page and manipulate it.
  2492. *
  2493. * @example
  2494. *
  2495. * ```js
  2496. * // initialize the map on the "map" div with a given center and zoom
  2497. * var map = L.map('map', {
  2498. * center: [51.505, -0.09],
  2499. * zoom: 13
  2500. * });
  2501. * ```
  2502. *
  2503. */
  2504. var Map = Evented.extend({
  2505. options: {
  2506. // @section Map State Options
  2507. // @option crs: CRS = L.CRS.EPSG3857
  2508. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2509. // sure what it means.
  2510. crs: EPSG3857,
  2511. // @option center: LatLng = undefined
  2512. // Initial geographic center of the map
  2513. center: undefined,
  2514. // @option zoom: Number = undefined
  2515. // Initial map zoom level
  2516. zoom: undefined,
  2517. // @option minZoom: Number = *
  2518. // Minimum zoom level of the map.
  2519. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2520. // the lowest of their `minZoom` options will be used instead.
  2521. minZoom: undefined,
  2522. // @option maxZoom: Number = *
  2523. // Maximum zoom level of the map.
  2524. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2525. // the highest of their `maxZoom` options will be used instead.
  2526. maxZoom: undefined,
  2527. // @option layers: Layer[] = []
  2528. // Array of layers that will be added to the map initially
  2529. layers: [],
  2530. // @option maxBounds: LatLngBounds = null
  2531. // When this option is set, the map restricts the view to the given
  2532. // geographical bounds, bouncing the user back if the user tries to pan
  2533. // outside the view. To set the restriction dynamically, use
  2534. // [`setMaxBounds`](#map-setmaxbounds) method.
  2535. maxBounds: undefined,
  2536. // @option renderer: Renderer = *
  2537. // The default method for drawing vector layers on the map. `L.SVG`
  2538. // or `L.Canvas` by default depending on browser support.
  2539. renderer: undefined,
  2540. // @section Animation Options
  2541. // @option zoomAnimation: Boolean = true
  2542. // Whether the map zoom animation is enabled. By default it's enabled
  2543. // in all browsers that support CSS3 Transitions except Android.
  2544. zoomAnimation: true,
  2545. // @option zoomAnimationThreshold: Number = 4
  2546. // Won't animate zoom if the zoom difference exceeds this value.
  2547. zoomAnimationThreshold: 4,
  2548. // @option fadeAnimation: Boolean = true
  2549. // Whether the tile fade animation is enabled. By default it's enabled
  2550. // in all browsers that support CSS3 Transitions except Android.
  2551. fadeAnimation: true,
  2552. // @option markerZoomAnimation: Boolean = true
  2553. // Whether markers animate their zoom with the zoom animation, if disabled
  2554. // they will disappear for the length of the animation. By default it's
  2555. // enabled in all browsers that support CSS3 Transitions except Android.
  2556. markerZoomAnimation: true,
  2557. // @option transform3DLimit: Number = 2^23
  2558. // Defines the maximum size of a CSS translation transform. The default
  2559. // value should not be changed unless a web browser positions layers in
  2560. // the wrong place after doing a large `panBy`.
  2561. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2562. // @section Interaction Options
  2563. // @option zoomSnap: Number = 1
  2564. // Forces the map's zoom level to always be a multiple of this, particularly
  2565. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2566. // By default, the zoom level snaps to the nearest integer; lower values
  2567. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2568. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2569. zoomSnap: 1,
  2570. // @option zoomDelta: Number = 1
  2571. // Controls how much the map's zoom level will change after a
  2572. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2573. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2574. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2575. zoomDelta: 1,
  2576. // @option trackResize: Boolean = true
  2577. // Whether the map automatically handles browser window resize to update itself.
  2578. trackResize: true
  2579. },
  2580. initialize: function (id, options) { // (HTMLElement or String, Object)
  2581. options = setOptions(this, options);
  2582. // Make sure to assign internal flags at the beginning,
  2583. // to avoid inconsistent state in some edge cases.
  2584. this._handlers = [];
  2585. this._layers = {};
  2586. this._zoomBoundLayers = {};
  2587. this._sizeChanged = true;
  2588. this._initContainer(id);
  2589. this._initLayout();
  2590. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2591. this._onResize = bind(this._onResize, this);
  2592. this._initEvents();
  2593. if (options.maxBounds) {
  2594. this.setMaxBounds(options.maxBounds);
  2595. }
  2596. if (options.zoom !== undefined) {
  2597. this._zoom = this._limitZoom(options.zoom);
  2598. }
  2599. if (options.center && options.zoom !== undefined) {
  2600. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2601. }
  2602. this.callInitHooks();
  2603. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2604. this._zoomAnimated = TRANSITION && any3d && !mobileOpera &&
  2605. this.options.zoomAnimation;
  2606. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2607. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2608. if (this._zoomAnimated) {
  2609. this._createAnimProxy();
  2610. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2611. }
  2612. this._addLayers(this.options.layers);
  2613. },
  2614. // @section Methods for modifying map state
  2615. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2616. // Sets the view of the map (geographical center and zoom) with the given
  2617. // animation options.
  2618. setView: function (center, zoom, options) {
  2619. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2620. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2621. options = options || {};
  2622. this._stop();
  2623. if (this._loaded && !options.reset && options !== true) {
  2624. if (options.animate !== undefined) {
  2625. options.zoom = extend({animate: options.animate}, options.zoom);
  2626. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2627. }
  2628. // try animating pan or zoom
  2629. var moved = (this._zoom !== zoom) ?
  2630. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2631. this._tryAnimatedPan(center, options.pan);
  2632. if (moved) {
  2633. // prevent resize handler call, the view will refresh after animation anyway
  2634. clearTimeout(this._sizeTimer);
  2635. return this;
  2636. }
  2637. }
  2638. // animation didn't start, just reset the map view
  2639. this._resetView(center, zoom);
  2640. return this;
  2641. },
  2642. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2643. // Sets the zoom of the map.
  2644. setZoom: function (zoom, options) {
  2645. if (!this._loaded) {
  2646. this._zoom = zoom;
  2647. return this;
  2648. }
  2649. return this.setView(this.getCenter(), zoom, {zoom: options});
  2650. },
  2651. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2652. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2653. zoomIn: function (delta, options) {
  2654. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2655. return this.setZoom(this._zoom + delta, options);
  2656. },
  2657. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2658. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2659. zoomOut: function (delta, options) {
  2660. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2661. return this.setZoom(this._zoom - delta, options);
  2662. },
  2663. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2664. // Zooms the map while keeping a specified geographical point on the map
  2665. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2666. // @alternative
  2667. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2668. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2669. setZoomAround: function (latlng, zoom, options) {
  2670. var scale = this.getZoomScale(zoom),
  2671. viewHalf = this.getSize().divideBy(2),
  2672. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2673. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2674. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2675. return this.setView(newCenter, zoom, {zoom: options});
  2676. },
  2677. _getBoundsCenterZoom: function (bounds, options) {
  2678. options = options || {};
  2679. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2680. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2681. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2682. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2683. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2684. if (zoom === Infinity) {
  2685. return {
  2686. center: bounds.getCenter(),
  2687. zoom: zoom
  2688. };
  2689. }
  2690. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2691. swPoint = this.project(bounds.getSouthWest(), zoom),
  2692. nePoint = this.project(bounds.getNorthEast(), zoom),
  2693. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2694. return {
  2695. center: center,
  2696. zoom: zoom
  2697. };
  2698. },
  2699. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2700. // Sets a map view that contains the given geographical bounds with the
  2701. // maximum zoom level possible.
  2702. fitBounds: function (bounds, options) {
  2703. bounds = toLatLngBounds(bounds);
  2704. if (!bounds.isValid()) {
  2705. throw new Error('Bounds are not valid.');
  2706. }
  2707. var target = this._getBoundsCenterZoom(bounds, options);
  2708. return this.setView(target.center, target.zoom, options);
  2709. },
  2710. // @method fitWorld(options?: fitBounds options): this
  2711. // Sets a map view that mostly contains the whole world with the maximum
  2712. // zoom level possible.
  2713. fitWorld: function (options) {
  2714. return this.fitBounds([[-90, -180], [90, 180]], options);
  2715. },
  2716. // @method panTo(latlng: LatLng, options?: Pan options): this
  2717. // Pans the map to a given center.
  2718. panTo: function (center, options) { // (LatLng)
  2719. return this.setView(center, this._zoom, {pan: options});
  2720. },
  2721. // @method panBy(offset: Point, options?: Pan options): this
  2722. // Pans the map by a given number of pixels (animated).
  2723. panBy: function (offset, options) {
  2724. offset = toPoint(offset).round();
  2725. options = options || {};
  2726. if (!offset.x && !offset.y) {
  2727. return this.fire('moveend');
  2728. }
  2729. // If we pan too far, Chrome gets issues with tiles
  2730. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2731. if (options.animate !== true && !this.getSize().contains(offset)) {
  2732. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2733. return this;
  2734. }
  2735. if (!this._panAnim) {
  2736. this._panAnim = new PosAnimation();
  2737. this._panAnim.on({
  2738. 'step': this._onPanTransitionStep,
  2739. 'end': this._onPanTransitionEnd
  2740. }, this);
  2741. }
  2742. // don't fire movestart if animating inertia
  2743. if (!options.noMoveStart) {
  2744. this.fire('movestart');
  2745. }
  2746. // animate pan unless animate: false specified
  2747. if (options.animate !== false) {
  2748. addClass(this._mapPane, 'leaflet-pan-anim');
  2749. var newPos = this._getMapPanePos().subtract(offset).round();
  2750. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2751. } else {
  2752. this._rawPanBy(offset);
  2753. this.fire('move').fire('moveend');
  2754. }
  2755. return this;
  2756. },
  2757. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2758. // Sets the view of the map (geographical center and zoom) performing a smooth
  2759. // pan-zoom animation.
  2760. flyTo: function (targetCenter, targetZoom, options) {
  2761. options = options || {};
  2762. if (options.animate === false || !any3d) {
  2763. return this.setView(targetCenter, targetZoom, options);
  2764. }
  2765. this._stop();
  2766. var from = this.project(this.getCenter()),
  2767. to = this.project(targetCenter),
  2768. size = this.getSize(),
  2769. startZoom = this._zoom;
  2770. targetCenter = toLatLng(targetCenter);
  2771. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2772. var w0 = Math.max(size.x, size.y),
  2773. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2774. u1 = (to.distanceTo(from)) || 1,
  2775. rho = 1.42,
  2776. rho2 = rho * rho;
  2777. function r(i) {
  2778. var s1 = i ? -1 : 1,
  2779. s2 = i ? w1 : w0,
  2780. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2781. b1 = 2 * s2 * rho2 * u1,
  2782. b = t1 / b1,
  2783. sq = Math.sqrt(b * b + 1) - b;
  2784. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2785. // thus triggering an infinite loop in flyTo
  2786. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2787. return log;
  2788. }
  2789. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2790. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2791. function tanh(n) { return sinh(n) / cosh(n); }
  2792. var r0 = r(0);
  2793. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2794. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2795. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2796. var start = Date.now(),
  2797. S = (r(1) - r0) / rho,
  2798. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2799. function frame() {
  2800. var t = (Date.now() - start) / duration,
  2801. s = easeOut(t) * S;
  2802. if (t <= 1) {
  2803. this._flyToFrame = requestAnimFrame(frame, this);
  2804. this._move(
  2805. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2806. this.getScaleZoom(w0 / w(s), startZoom),
  2807. {flyTo: true});
  2808. } else {
  2809. this
  2810. ._move(targetCenter, targetZoom)
  2811. ._moveEnd(true);
  2812. }
  2813. }
  2814. this._moveStart(true, options.noMoveStart);
  2815. frame.call(this);
  2816. return this;
  2817. },
  2818. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2819. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2820. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2821. flyToBounds: function (bounds, options) {
  2822. var target = this._getBoundsCenterZoom(bounds, options);
  2823. return this.flyTo(target.center, target.zoom, options);
  2824. },
  2825. // @method setMaxBounds(bounds: Bounds): this
  2826. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2827. setMaxBounds: function (bounds) {
  2828. bounds = toLatLngBounds(bounds);
  2829. if (!bounds.isValid()) {
  2830. this.options.maxBounds = null;
  2831. return this.off('moveend', this._panInsideMaxBounds);
  2832. } else if (this.options.maxBounds) {
  2833. this.off('moveend', this._panInsideMaxBounds);
  2834. }
  2835. this.options.maxBounds = bounds;
  2836. if (this._loaded) {
  2837. this._panInsideMaxBounds();
  2838. }
  2839. return this.on('moveend', this._panInsideMaxBounds);
  2840. },
  2841. // @method setMinZoom(zoom: Number): this
  2842. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2843. setMinZoom: function (zoom) {
  2844. var oldZoom = this.options.minZoom;
  2845. this.options.minZoom = zoom;
  2846. if (this._loaded && oldZoom !== zoom) {
  2847. this.fire('zoomlevelschange');
  2848. if (this.getZoom() < this.options.minZoom) {
  2849. return this.setZoom(zoom);
  2850. }
  2851. }
  2852. return this;
  2853. },
  2854. // @method setMaxZoom(zoom: Number): this
  2855. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2856. setMaxZoom: function (zoom) {
  2857. var oldZoom = this.options.maxZoom;
  2858. this.options.maxZoom = zoom;
  2859. if (this._loaded && oldZoom !== zoom) {
  2860. this.fire('zoomlevelschange');
  2861. if (this.getZoom() > this.options.maxZoom) {
  2862. return this.setZoom(zoom);
  2863. }
  2864. }
  2865. return this;
  2866. },
  2867. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2868. // 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.
  2869. panInsideBounds: function (bounds, options) {
  2870. this._enforcingBounds = true;
  2871. var center = this.getCenter(),
  2872. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2873. if (!center.equals(newCenter)) {
  2874. this.panTo(newCenter, options);
  2875. }
  2876. this._enforcingBounds = false;
  2877. return this;
  2878. },
  2879. // @method panInside(latlng: LatLng, options?: options): this
  2880. // Pans the map the minimum amount to make the `latlng` visible. Use
  2881. // `padding`, `paddingTopLeft` and `paddingTopRight` options to fit
  2882. // the display to more restricted bounds, like [`fitBounds`](#map-fitbounds).
  2883. // If `latlng` is already within the (optionally padded) display bounds,
  2884. // the map will not be panned.
  2885. panInside: function (latlng, options) {
  2886. options = options || {};
  2887. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2888. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2889. center = this.getCenter(),
  2890. pixelCenter = this.project(center),
  2891. pixelPoint = this.project(latlng),
  2892. pixelBounds = this.getPixelBounds(),
  2893. halfPixelBounds = pixelBounds.getSize().divideBy(2),
  2894. paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]);
  2895. if (!paddedBounds.contains(pixelPoint)) {
  2896. this._enforcingBounds = true;
  2897. var diff = pixelCenter.subtract(pixelPoint),
  2898. newCenter = toPoint(pixelPoint.x + diff.x, pixelPoint.y + diff.y);
  2899. if (pixelPoint.x < paddedBounds.min.x || pixelPoint.x > paddedBounds.max.x) {
  2900. newCenter.x = pixelCenter.x - diff.x;
  2901. if (diff.x > 0) {
  2902. newCenter.x += halfPixelBounds.x - paddingTL.x;
  2903. } else {
  2904. newCenter.x -= halfPixelBounds.x - paddingBR.x;
  2905. }
  2906. }
  2907. if (pixelPoint.y < paddedBounds.min.y || pixelPoint.y > paddedBounds.max.y) {
  2908. newCenter.y = pixelCenter.y - diff.y;
  2909. if (diff.y > 0) {
  2910. newCenter.y += halfPixelBounds.y - paddingTL.y;
  2911. } else {
  2912. newCenter.y -= halfPixelBounds.y - paddingBR.y;
  2913. }
  2914. }
  2915. this.panTo(this.unproject(newCenter), options);
  2916. this._enforcingBounds = false;
  2917. }
  2918. return this;
  2919. },
  2920. // @method invalidateSize(options: Zoom/pan options): this
  2921. // Checks if the map container size changed and updates the map if so —
  2922. // call it after you've changed the map size dynamically, also animating
  2923. // pan by default. If `options.pan` is `false`, panning will not occur.
  2924. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2925. // that it doesn't happen often even if the method is called many
  2926. // times in a row.
  2927. // @alternative
  2928. // @method invalidateSize(animate: Boolean): this
  2929. // Checks if the map container size changed and updates the map if so —
  2930. // call it after you've changed the map size dynamically, also animating
  2931. // pan by default.
  2932. invalidateSize: function (options) {
  2933. if (!this._loaded) { return this; }
  2934. options = extend({
  2935. animate: false,
  2936. pan: true
  2937. }, options === true ? {animate: true} : options);
  2938. var oldSize = this.getSize();
  2939. this._sizeChanged = true;
  2940. this._lastCenter = null;
  2941. var newSize = this.getSize(),
  2942. oldCenter = oldSize.divideBy(2).round(),
  2943. newCenter = newSize.divideBy(2).round(),
  2944. offset = oldCenter.subtract(newCenter);
  2945. if (!offset.x && !offset.y) { return this; }
  2946. if (options.animate && options.pan) {
  2947. this.panBy(offset);
  2948. } else {
  2949. if (options.pan) {
  2950. this._rawPanBy(offset);
  2951. }
  2952. this.fire('move');
  2953. if (options.debounceMoveend) {
  2954. clearTimeout(this._sizeTimer);
  2955. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  2956. } else {
  2957. this.fire('moveend');
  2958. }
  2959. }
  2960. // @section Map state change events
  2961. // @event resize: ResizeEvent
  2962. // Fired when the map is resized.
  2963. return this.fire('resize', {
  2964. oldSize: oldSize,
  2965. newSize: newSize
  2966. });
  2967. },
  2968. // @section Methods for modifying map state
  2969. // @method stop(): this
  2970. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2971. stop: function () {
  2972. this.setZoom(this._limitZoom(this._zoom));
  2973. if (!this.options.zoomSnap) {
  2974. this.fire('viewreset');
  2975. }
  2976. return this._stop();
  2977. },
  2978. // @section Geolocation methods
  2979. // @method locate(options?: Locate options): this
  2980. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  2981. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  2982. // and optionally sets the map view to the user's location with respect to
  2983. // detection accuracy (or to the world view if geolocation failed).
  2984. // Note that, if your page doesn't use HTTPS, this method will fail in
  2985. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  2986. // See `Locate options` for more details.
  2987. locate: function (options) {
  2988. options = this._locateOptions = extend({
  2989. timeout: 10000,
  2990. watch: false
  2991. // setView: false
  2992. // maxZoom: <Number>
  2993. // maximumAge: 0
  2994. // enableHighAccuracy: false
  2995. }, options);
  2996. if (!('geolocation' in navigator)) {
  2997. this._handleGeolocationError({
  2998. code: 0,
  2999. message: 'Geolocation not supported.'
  3000. });
  3001. return this;
  3002. }
  3003. var onResponse = bind(this._handleGeolocationResponse, this),
  3004. onError = bind(this._handleGeolocationError, this);
  3005. if (options.watch) {
  3006. this._locationWatchId =
  3007. navigator.geolocation.watchPosition(onResponse, onError, options);
  3008. } else {
  3009. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  3010. }
  3011. return this;
  3012. },
  3013. // @method stopLocate(): this
  3014. // Stops watching location previously initiated by `map.locate({watch: true})`
  3015. // and aborts resetting the map view if map.locate was called with
  3016. // `{setView: true}`.
  3017. stopLocate: function () {
  3018. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  3019. navigator.geolocation.clearWatch(this._locationWatchId);
  3020. }
  3021. if (this._locateOptions) {
  3022. this._locateOptions.setView = false;
  3023. }
  3024. return this;
  3025. },
  3026. _handleGeolocationError: function (error) {
  3027. var c = error.code,
  3028. message = error.message ||
  3029. (c === 1 ? 'permission denied' :
  3030. (c === 2 ? 'position unavailable' : 'timeout'));
  3031. if (this._locateOptions.setView && !this._loaded) {
  3032. this.fitWorld();
  3033. }
  3034. // @section Location events
  3035. // @event locationerror: ErrorEvent
  3036. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  3037. this.fire('locationerror', {
  3038. code: c,
  3039. message: 'Geolocation error: ' + message + '.'
  3040. });
  3041. },
  3042. _handleGeolocationResponse: function (pos) {
  3043. var lat = pos.coords.latitude,
  3044. lng = pos.coords.longitude,
  3045. latlng = new LatLng(lat, lng),
  3046. bounds = latlng.toBounds(pos.coords.accuracy * 2),
  3047. options = this._locateOptions;
  3048. if (options.setView) {
  3049. var zoom = this.getBoundsZoom(bounds);
  3050. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  3051. }
  3052. var data = {
  3053. latlng: latlng,
  3054. bounds: bounds,
  3055. timestamp: pos.timestamp
  3056. };
  3057. for (var i in pos.coords) {
  3058. if (typeof pos.coords[i] === 'number') {
  3059. data[i] = pos.coords[i];
  3060. }
  3061. }
  3062. // @event locationfound: LocationEvent
  3063. // Fired when geolocation (using the [`locate`](#map-locate) method)
  3064. // went successfully.
  3065. this.fire('locationfound', data);
  3066. },
  3067. // TODO Appropriate docs section?
  3068. // @section Other Methods
  3069. // @method addHandler(name: String, HandlerClass: Function): this
  3070. // Adds a new `Handler` to the map, given its name and constructor function.
  3071. addHandler: function (name, HandlerClass) {
  3072. if (!HandlerClass) { return this; }
  3073. var handler = this[name] = new HandlerClass(this);
  3074. this._handlers.push(handler);
  3075. if (this.options[name]) {
  3076. handler.enable();
  3077. }
  3078. return this;
  3079. },
  3080. // @method remove(): this
  3081. // Destroys the map and clears all related event listeners.
  3082. remove: function () {
  3083. this._initEvents(true);
  3084. if (this._containerId !== this._container._leaflet_id) {
  3085. throw new Error('Map container is being reused by another instance');
  3086. }
  3087. try {
  3088. // throws error in IE6-8
  3089. delete this._container._leaflet_id;
  3090. delete this._containerId;
  3091. } catch (e) {
  3092. /*eslint-disable */
  3093. this._container._leaflet_id = undefined;
  3094. /* eslint-enable */
  3095. this._containerId = undefined;
  3096. }
  3097. if (this._locationWatchId !== undefined) {
  3098. this.stopLocate();
  3099. }
  3100. this._stop();
  3101. remove(this._mapPane);
  3102. if (this._clearControlPos) {
  3103. this._clearControlPos();
  3104. }
  3105. if (this._resizeRequest) {
  3106. cancelAnimFrame(this._resizeRequest);
  3107. this._resizeRequest = null;
  3108. }
  3109. this._clearHandlers();
  3110. if (this._loaded) {
  3111. // @section Map state change events
  3112. // @event unload: Event
  3113. // Fired when the map is destroyed with [remove](#map-remove) method.
  3114. this.fire('unload');
  3115. }
  3116. var i;
  3117. for (i in this._layers) {
  3118. this._layers[i].remove();
  3119. }
  3120. for (i in this._panes) {
  3121. remove(this._panes[i]);
  3122. }
  3123. this._layers = [];
  3124. this._panes = [];
  3125. delete this._mapPane;
  3126. delete this._renderer;
  3127. return this;
  3128. },
  3129. // @section Other Methods
  3130. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3131. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3132. // then returns it. The pane is created as a child of `container`, or
  3133. // as a child of the main map pane if not set.
  3134. createPane: function (name, container) {
  3135. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3136. pane = create$1('div', className, container || this._mapPane);
  3137. if (name) {
  3138. this._panes[name] = pane;
  3139. }
  3140. return pane;
  3141. },
  3142. // @section Methods for Getting Map State
  3143. // @method getCenter(): LatLng
  3144. // Returns the geographical center of the map view
  3145. getCenter: function () {
  3146. this._checkIfLoaded();
  3147. if (this._lastCenter && !this._moved()) {
  3148. return this._lastCenter;
  3149. }
  3150. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3151. },
  3152. // @method getZoom(): Number
  3153. // Returns the current zoom level of the map view
  3154. getZoom: function () {
  3155. return this._zoom;
  3156. },
  3157. // @method getBounds(): LatLngBounds
  3158. // Returns the geographical bounds visible in the current map view
  3159. getBounds: function () {
  3160. var bounds = this.getPixelBounds(),
  3161. sw = this.unproject(bounds.getBottomLeft()),
  3162. ne = this.unproject(bounds.getTopRight());
  3163. return new LatLngBounds(sw, ne);
  3164. },
  3165. // @method getMinZoom(): Number
  3166. // 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.
  3167. getMinZoom: function () {
  3168. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3169. },
  3170. // @method getMaxZoom(): Number
  3171. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3172. getMaxZoom: function () {
  3173. return this.options.maxZoom === undefined ?
  3174. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3175. this.options.maxZoom;
  3176. },
  3177. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
  3178. // Returns the maximum zoom level on which the given bounds fit to the map
  3179. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3180. // instead returns the minimum zoom level on which the map view fits into
  3181. // the given bounds in its entirety.
  3182. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3183. bounds = toLatLngBounds(bounds);
  3184. padding = toPoint(padding || [0, 0]);
  3185. var zoom = this.getZoom() || 0,
  3186. min = this.getMinZoom(),
  3187. max = this.getMaxZoom(),
  3188. nw = bounds.getNorthWest(),
  3189. se = bounds.getSouthEast(),
  3190. size = this.getSize().subtract(padding),
  3191. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3192. snap = any3d ? this.options.zoomSnap : 1,
  3193. scalex = size.x / boundsSize.x,
  3194. scaley = size.y / boundsSize.y,
  3195. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3196. zoom = this.getScaleZoom(scale, zoom);
  3197. if (snap) {
  3198. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3199. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3200. }
  3201. return Math.max(min, Math.min(max, zoom));
  3202. },
  3203. // @method getSize(): Point
  3204. // Returns the current size of the map container (in pixels).
  3205. getSize: function () {
  3206. if (!this._size || this._sizeChanged) {
  3207. this._size = new Point(
  3208. this._container.clientWidth || 0,
  3209. this._container.clientHeight || 0);
  3210. this._sizeChanged = false;
  3211. }
  3212. return this._size.clone();
  3213. },
  3214. // @method getPixelBounds(): Bounds
  3215. // Returns the bounds of the current map view in projected pixel
  3216. // coordinates (sometimes useful in layer and overlay implementations).
  3217. getPixelBounds: function (center, zoom) {
  3218. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3219. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3220. },
  3221. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3222. // the map pane? "left point of the map layer" can be confusing, specially
  3223. // since there can be negative offsets.
  3224. // @method getPixelOrigin(): Point
  3225. // Returns the projected pixel coordinates of the top left point of
  3226. // the map layer (useful in custom layer and overlay implementations).
  3227. getPixelOrigin: function () {
  3228. this._checkIfLoaded();
  3229. return this._pixelOrigin;
  3230. },
  3231. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3232. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3233. // If `zoom` is omitted, the map's current zoom level is used.
  3234. getPixelWorldBounds: function (zoom) {
  3235. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3236. },
  3237. // @section Other Methods
  3238. // @method getPane(pane: String|HTMLElement): HTMLElement
  3239. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3240. getPane: function (pane) {
  3241. return typeof pane === 'string' ? this._panes[pane] : pane;
  3242. },
  3243. // @method getPanes(): Object
  3244. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3245. // the panes as values.
  3246. getPanes: function () {
  3247. return this._panes;
  3248. },
  3249. // @method getContainer: HTMLElement
  3250. // Returns the HTML element that contains the map.
  3251. getContainer: function () {
  3252. return this._container;
  3253. },
  3254. // @section Conversion Methods
  3255. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3256. // Returns the scale factor to be applied to a map transition from zoom level
  3257. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3258. getZoomScale: function (toZoom, fromZoom) {
  3259. // TODO replace with universal implementation after refactoring projections
  3260. var crs = this.options.crs;
  3261. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3262. return crs.scale(toZoom) / crs.scale(fromZoom);
  3263. },
  3264. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3265. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3266. // level and everything is scaled by a factor of `scale`. Inverse of
  3267. // [`getZoomScale`](#map-getZoomScale).
  3268. getScaleZoom: function (scale, fromZoom) {
  3269. var crs = this.options.crs;
  3270. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3271. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3272. return isNaN(zoom) ? Infinity : zoom;
  3273. },
  3274. // @method project(latlng: LatLng, zoom: Number): Point
  3275. // Projects a geographical coordinate `LatLng` according to the projection
  3276. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3277. // `Transformation`. The result is pixel coordinate relative to
  3278. // the CRS origin.
  3279. project: function (latlng, zoom) {
  3280. zoom = zoom === undefined ? this._zoom : zoom;
  3281. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3282. },
  3283. // @method unproject(point: Point, zoom: Number): LatLng
  3284. // Inverse of [`project`](#map-project).
  3285. unproject: function (point, zoom) {
  3286. zoom = zoom === undefined ? this._zoom : zoom;
  3287. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3288. },
  3289. // @method layerPointToLatLng(point: Point): LatLng
  3290. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3291. // returns the corresponding geographical coordinate (for the current zoom level).
  3292. layerPointToLatLng: function (point) {
  3293. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3294. return this.unproject(projectedPoint);
  3295. },
  3296. // @method latLngToLayerPoint(latlng: LatLng): Point
  3297. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3298. // relative to the [origin pixel](#map-getpixelorigin).
  3299. latLngToLayerPoint: function (latlng) {
  3300. var projectedPoint = this.project(toLatLng(latlng))._round();
  3301. return projectedPoint._subtract(this.getPixelOrigin());
  3302. },
  3303. // @method wrapLatLng(latlng: LatLng): LatLng
  3304. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3305. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3306. // CRS's bounds.
  3307. // By default this means longitude is wrapped around the dateline so its
  3308. // value is between -180 and +180 degrees.
  3309. wrapLatLng: function (latlng) {
  3310. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3311. },
  3312. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3313. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3314. // its center is within the CRS's bounds.
  3315. // By default this means the center longitude is wrapped around the dateline so its
  3316. // value is between -180 and +180 degrees, and the majority of the bounds
  3317. // overlaps the CRS's bounds.
  3318. wrapLatLngBounds: function (latlng) {
  3319. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3320. },
  3321. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3322. // Returns the distance between two geographical coordinates according to
  3323. // the map's CRS. By default this measures distance in meters.
  3324. distance: function (latlng1, latlng2) {
  3325. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3326. },
  3327. // @method containerPointToLayerPoint(point: Point): Point
  3328. // Given a pixel coordinate relative to the map container, returns the corresponding
  3329. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3330. containerPointToLayerPoint: function (point) { // (Point)
  3331. return toPoint(point).subtract(this._getMapPanePos());
  3332. },
  3333. // @method layerPointToContainerPoint(point: Point): Point
  3334. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3335. // returns the corresponding pixel coordinate relative to the map container.
  3336. layerPointToContainerPoint: function (point) { // (Point)
  3337. return toPoint(point).add(this._getMapPanePos());
  3338. },
  3339. // @method containerPointToLatLng(point: Point): LatLng
  3340. // Given a pixel coordinate relative to the map container, returns
  3341. // the corresponding geographical coordinate (for the current zoom level).
  3342. containerPointToLatLng: function (point) {
  3343. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3344. return this.layerPointToLatLng(layerPoint);
  3345. },
  3346. // @method latLngToContainerPoint(latlng: LatLng): Point
  3347. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3348. // relative to the map container.
  3349. latLngToContainerPoint: function (latlng) {
  3350. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3351. },
  3352. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3353. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3354. // map container where the event took place.
  3355. mouseEventToContainerPoint: function (e) {
  3356. return getMousePosition(e, this._container);
  3357. },
  3358. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3359. // Given a MouseEvent object, returns the pixel coordinate relative to
  3360. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3361. mouseEventToLayerPoint: function (e) {
  3362. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3363. },
  3364. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3365. // Given a MouseEvent object, returns geographical coordinate where the
  3366. // event took place.
  3367. mouseEventToLatLng: function (e) { // (MouseEvent)
  3368. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3369. },
  3370. // map initialization methods
  3371. _initContainer: function (id) {
  3372. var container = this._container = get(id);
  3373. if (!container) {
  3374. throw new Error('Map container not found.');
  3375. } else if (container._leaflet_id) {
  3376. throw new Error('Map container is already initialized.');
  3377. }
  3378. on(container, 'scroll', this._onScroll, this);
  3379. this._containerId = stamp(container);
  3380. },
  3381. _initLayout: function () {
  3382. var container = this._container;
  3383. this._fadeAnimated = this.options.fadeAnimation && any3d;
  3384. addClass(container, 'leaflet-container' +
  3385. (touch ? ' leaflet-touch' : '') +
  3386. (retina ? ' leaflet-retina' : '') +
  3387. (ielt9 ? ' leaflet-oldie' : '') +
  3388. (safari ? ' leaflet-safari' : '') +
  3389. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3390. var position = getStyle(container, 'position');
  3391. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  3392. container.style.position = 'relative';
  3393. }
  3394. this._initPanes();
  3395. if (this._initControlPos) {
  3396. this._initControlPos();
  3397. }
  3398. },
  3399. _initPanes: function () {
  3400. var panes = this._panes = {};
  3401. this._paneRenderers = {};
  3402. // @section
  3403. //
  3404. // Panes are DOM elements used to control the ordering of layers on the map. You
  3405. // can access panes with [`map.getPane`](#map-getpane) or
  3406. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3407. // [`map.createPane`](#map-createpane) method.
  3408. //
  3409. // Every map has the following default panes that differ only in zIndex.
  3410. //
  3411. // @pane mapPane: HTMLElement = 'auto'
  3412. // Pane that contains all other map panes
  3413. this._mapPane = this.createPane('mapPane', this._container);
  3414. setPosition(this._mapPane, new Point(0, 0));
  3415. // @pane tilePane: HTMLElement = 200
  3416. // Pane for `GridLayer`s and `TileLayer`s
  3417. this.createPane('tilePane');
  3418. // @pane overlayPane: HTMLElement = 400
  3419. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  3420. this.createPane('shadowPane');
  3421. // @pane shadowPane: HTMLElement = 500
  3422. // Pane for overlay shadows (e.g. `Marker` shadows)
  3423. this.createPane('overlayPane');
  3424. // @pane markerPane: HTMLElement = 600
  3425. // Pane for `Icon`s of `Marker`s
  3426. this.createPane('markerPane');
  3427. // @pane tooltipPane: HTMLElement = 650
  3428. // Pane for `Tooltip`s.
  3429. this.createPane('tooltipPane');
  3430. // @pane popupPane: HTMLElement = 700
  3431. // Pane for `Popup`s.
  3432. this.createPane('popupPane');
  3433. if (!this.options.markerZoomAnimation) {
  3434. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3435. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3436. }
  3437. },
  3438. // private methods that modify map state
  3439. // @section Map state change events
  3440. _resetView: function (center, zoom) {
  3441. setPosition(this._mapPane, new Point(0, 0));
  3442. var loading = !this._loaded;
  3443. this._loaded = true;
  3444. zoom = this._limitZoom(zoom);
  3445. this.fire('viewprereset');
  3446. var zoomChanged = this._zoom !== zoom;
  3447. this
  3448. ._moveStart(zoomChanged, false)
  3449. ._move(center, zoom)
  3450. ._moveEnd(zoomChanged);
  3451. // @event viewreset: Event
  3452. // Fired when the map needs to redraw its content (this usually happens
  3453. // on map zoom or load). Very useful for creating custom overlays.
  3454. this.fire('viewreset');
  3455. // @event load: Event
  3456. // Fired when the map is initialized (when its center and zoom are set
  3457. // for the first time).
  3458. if (loading) {
  3459. this.fire('load');
  3460. }
  3461. },
  3462. _moveStart: function (zoomChanged, noMoveStart) {
  3463. // @event zoomstart: Event
  3464. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3465. // @event movestart: Event
  3466. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3467. if (zoomChanged) {
  3468. this.fire('zoomstart');
  3469. }
  3470. if (!noMoveStart) {
  3471. this.fire('movestart');
  3472. }
  3473. return this;
  3474. },
  3475. _move: function (center, zoom, data) {
  3476. if (zoom === undefined) {
  3477. zoom = this._zoom;
  3478. }
  3479. var zoomChanged = this._zoom !== zoom;
  3480. this._zoom = zoom;
  3481. this._lastCenter = center;
  3482. this._pixelOrigin = this._getNewPixelOrigin(center);
  3483. // @event zoom: Event
  3484. // Fired repeatedly during any change in zoom level, including zoom
  3485. // and fly animations.
  3486. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3487. this.fire('zoom', data);
  3488. }
  3489. // @event move: Event
  3490. // Fired repeatedly during any movement of the map, including pan and
  3491. // fly animations.
  3492. return this.fire('move', data);
  3493. },
  3494. _moveEnd: function (zoomChanged) {
  3495. // @event zoomend: Event
  3496. // Fired when the map has changed, after any animations.
  3497. if (zoomChanged) {
  3498. this.fire('zoomend');
  3499. }
  3500. // @event moveend: Event
  3501. // Fired when the center of the map stops changing (e.g. user stopped
  3502. // dragging the map).
  3503. return this.fire('moveend');
  3504. },
  3505. _stop: function () {
  3506. cancelAnimFrame(this._flyToFrame);
  3507. if (this._panAnim) {
  3508. this._panAnim.stop();
  3509. }
  3510. return this;
  3511. },
  3512. _rawPanBy: function (offset) {
  3513. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3514. },
  3515. _getZoomSpan: function () {
  3516. return this.getMaxZoom() - this.getMinZoom();
  3517. },
  3518. _panInsideMaxBounds: function () {
  3519. if (!this._enforcingBounds) {
  3520. this.panInsideBounds(this.options.maxBounds);
  3521. }
  3522. },
  3523. _checkIfLoaded: function () {
  3524. if (!this._loaded) {
  3525. throw new Error('Set map center and zoom first.');
  3526. }
  3527. },
  3528. // DOM event handling
  3529. // @section Interaction events
  3530. _initEvents: function (remove$$1) {
  3531. this._targets = {};
  3532. this._targets[stamp(this._container)] = this;
  3533. var onOff = remove$$1 ? off : on;
  3534. // @event click: MouseEvent
  3535. // Fired when the user clicks (or taps) the map.
  3536. // @event dblclick: MouseEvent
  3537. // Fired when the user double-clicks (or double-taps) the map.
  3538. // @event mousedown: MouseEvent
  3539. // Fired when the user pushes the mouse button on the map.
  3540. // @event mouseup: MouseEvent
  3541. // Fired when the user releases the mouse button on the map.
  3542. // @event mouseover: MouseEvent
  3543. // Fired when the mouse enters the map.
  3544. // @event mouseout: MouseEvent
  3545. // Fired when the mouse leaves the map.
  3546. // @event mousemove: MouseEvent
  3547. // Fired while the mouse moves over the map.
  3548. // @event contextmenu: MouseEvent
  3549. // Fired when the user pushes the right mouse button on the map, prevents
  3550. // default browser context menu from showing if there are listeners on
  3551. // this event. Also fired on mobile when the user holds a single touch
  3552. // for a second (also called long press).
  3553. // @event keypress: KeyboardEvent
  3554. // Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
  3555. // @event keydown: KeyboardEvent
  3556. // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
  3557. // the `keydown` event is fired for keys that produce a character value and for keys
  3558. // that do not produce a character value.
  3559. // @event keyup: KeyboardEvent
  3560. // Fired when the user releases a key from the keyboard while the map is focused.
  3561. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3562. 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
  3563. if (this.options.trackResize) {
  3564. onOff(window, 'resize', this._onResize, this);
  3565. }
  3566. if (any3d && this.options.transform3DLimit) {
  3567. (remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3568. }
  3569. },
  3570. _onResize: function () {
  3571. cancelAnimFrame(this._resizeRequest);
  3572. this._resizeRequest = requestAnimFrame(
  3573. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3574. },
  3575. _onScroll: function () {
  3576. this._container.scrollTop = 0;
  3577. this._container.scrollLeft = 0;
  3578. },
  3579. _onMoveEnd: function () {
  3580. var pos = this._getMapPanePos();
  3581. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3582. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3583. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  3584. this._resetView(this.getCenter(), this.getZoom());
  3585. }
  3586. },
  3587. _findEventTargets: function (e, type) {
  3588. var targets = [],
  3589. target,
  3590. isHover = type === 'mouseout' || type === 'mouseover',
  3591. src = e.target || e.srcElement,
  3592. dragging = false;
  3593. while (src) {
  3594. target = this._targets[stamp(src)];
  3595. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  3596. // Prevent firing click after you just dragged an object.
  3597. dragging = true;
  3598. break;
  3599. }
  3600. if (target && target.listens(type, true)) {
  3601. if (isHover && !isExternalTarget(src, e)) { break; }
  3602. targets.push(target);
  3603. if (isHover) { break; }
  3604. }
  3605. if (src === this._container) { break; }
  3606. src = src.parentNode;
  3607. }
  3608. if (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {
  3609. targets = [this];
  3610. }
  3611. return targets;
  3612. },
  3613. _handleDOMEvent: function (e) {
  3614. if (!this._loaded || skipped(e)) { return; }
  3615. var type = e.type;
  3616. if (type === 'mousedown' || type === 'keypress' || type === 'keyup' || type === 'keydown') {
  3617. // prevents outline when clicking on keyboard-focusable element
  3618. preventOutline(e.target || e.srcElement);
  3619. }
  3620. this._fireDOMEvent(e, type);
  3621. },
  3622. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3623. _fireDOMEvent: function (e, type, targets) {
  3624. if (e.type === 'click') {
  3625. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3626. // @event preclick: MouseEvent
  3627. // Fired before mouse click on the map (sometimes useful when you
  3628. // want something to happen on click before any existing click
  3629. // handlers start running).
  3630. var synth = extend({}, e);
  3631. synth.type = 'preclick';
  3632. this._fireDOMEvent(synth, synth.type, targets);
  3633. }
  3634. if (e._stopped) { return; }
  3635. // Find the layer the event is propagating from and its parents.
  3636. targets = (targets || []).concat(this._findEventTargets(e, type));
  3637. if (!targets.length) { return; }
  3638. var target = targets[0];
  3639. if (type === 'contextmenu' && target.listens(type, true)) {
  3640. preventDefault(e);
  3641. }
  3642. var data = {
  3643. originalEvent: e
  3644. };
  3645. if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
  3646. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  3647. data.containerPoint = isMarker ?
  3648. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3649. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3650. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3651. }
  3652. for (var i = 0; i < targets.length; i++) {
  3653. targets[i].fire(type, data, true);
  3654. if (data.originalEvent._stopped ||
  3655. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3656. }
  3657. },
  3658. _draggableMoved: function (obj) {
  3659. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3660. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3661. },
  3662. _clearHandlers: function () {
  3663. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3664. this._handlers[i].disable();
  3665. }
  3666. },
  3667. // @section Other Methods
  3668. // @method whenReady(fn: Function, context?: Object): this
  3669. // Runs the given function `fn` when the map gets initialized with
  3670. // a view (center and zoom) and at least one layer, or immediately
  3671. // if it's already initialized, optionally passing a function context.
  3672. whenReady: function (callback, context) {
  3673. if (this._loaded) {
  3674. callback.call(context || this, {target: this});
  3675. } else {
  3676. this.on('load', callback, context);
  3677. }
  3678. return this;
  3679. },
  3680. // private methods for getting map state
  3681. _getMapPanePos: function () {
  3682. return getPosition(this._mapPane) || new Point(0, 0);
  3683. },
  3684. _moved: function () {
  3685. var pos = this._getMapPanePos();
  3686. return pos && !pos.equals([0, 0]);
  3687. },
  3688. _getTopLeftPoint: function (center, zoom) {
  3689. var pixelOrigin = center && zoom !== undefined ?
  3690. this._getNewPixelOrigin(center, zoom) :
  3691. this.getPixelOrigin();
  3692. return pixelOrigin.subtract(this._getMapPanePos());
  3693. },
  3694. _getNewPixelOrigin: function (center, zoom) {
  3695. var viewHalf = this.getSize()._divideBy(2);
  3696. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3697. },
  3698. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3699. var topLeft = this._getNewPixelOrigin(center, zoom);
  3700. return this.project(latlng, zoom)._subtract(topLeft);
  3701. },
  3702. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3703. var topLeft = this._getNewPixelOrigin(center, zoom);
  3704. return toBounds([
  3705. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3706. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3707. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3708. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3709. ]);
  3710. },
  3711. // layer point of the current center
  3712. _getCenterLayerPoint: function () {
  3713. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3714. },
  3715. // offset of the specified place to the current center in pixels
  3716. _getCenterOffset: function (latlng) {
  3717. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3718. },
  3719. // adjust center for view to get inside bounds
  3720. _limitCenter: function (center, zoom, bounds) {
  3721. if (!bounds) { return center; }
  3722. var centerPoint = this.project(center, zoom),
  3723. viewHalf = this.getSize().divideBy(2),
  3724. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3725. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3726. // If offset is less than a pixel, ignore.
  3727. // This prevents unstable projections from getting into
  3728. // an infinite loop of tiny offsets.
  3729. if (offset.round().equals([0, 0])) {
  3730. return center;
  3731. }
  3732. return this.unproject(centerPoint.add(offset), zoom);
  3733. },
  3734. // adjust offset for view to get inside bounds
  3735. _limitOffset: function (offset, bounds) {
  3736. if (!bounds) { return offset; }
  3737. var viewBounds = this.getPixelBounds(),
  3738. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3739. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3740. },
  3741. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3742. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3743. var projectedMaxBounds = toBounds(
  3744. this.project(maxBounds.getNorthEast(), zoom),
  3745. this.project(maxBounds.getSouthWest(), zoom)
  3746. ),
  3747. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3748. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3749. dx = this._rebound(minOffset.x, -maxOffset.x),
  3750. dy = this._rebound(minOffset.y, -maxOffset.y);
  3751. return new Point(dx, dy);
  3752. },
  3753. _rebound: function (left, right) {
  3754. return left + right > 0 ?
  3755. Math.round(left - right) / 2 :
  3756. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3757. },
  3758. _limitZoom: function (zoom) {
  3759. var min = this.getMinZoom(),
  3760. max = this.getMaxZoom(),
  3761. snap = any3d ? this.options.zoomSnap : 1;
  3762. if (snap) {
  3763. zoom = Math.round(zoom / snap) * snap;
  3764. }
  3765. return Math.max(min, Math.min(max, zoom));
  3766. },
  3767. _onPanTransitionStep: function () {
  3768. this.fire('move');
  3769. },
  3770. _onPanTransitionEnd: function () {
  3771. removeClass(this._mapPane, 'leaflet-pan-anim');
  3772. this.fire('moveend');
  3773. },
  3774. _tryAnimatedPan: function (center, options) {
  3775. // difference between the new and current centers in pixels
  3776. var offset = this._getCenterOffset(center)._trunc();
  3777. // don't animate too far unless animate: true specified in options
  3778. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3779. this.panBy(offset, options);
  3780. return true;
  3781. },
  3782. _createAnimProxy: function () {
  3783. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3784. this._panes.mapPane.appendChild(proxy);
  3785. this.on('zoomanim', function (e) {
  3786. var prop = TRANSFORM,
  3787. transform = this._proxy.style[prop];
  3788. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3789. // workaround for case when transform is the same and so transitionend event is not fired
  3790. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3791. this._onZoomTransitionEnd();
  3792. }
  3793. }, this);
  3794. this.on('load moveend', function () {
  3795. var c = this.getCenter(),
  3796. z = this.getZoom();
  3797. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3798. }, this);
  3799. this._on('unload', this._destroyAnimProxy, this);
  3800. },
  3801. _destroyAnimProxy: function () {
  3802. remove(this._proxy);
  3803. delete this._proxy;
  3804. },
  3805. _catchTransitionEnd: function (e) {
  3806. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3807. this._onZoomTransitionEnd();
  3808. }
  3809. },
  3810. _nothingToAnimate: function () {
  3811. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3812. },
  3813. _tryAnimatedZoom: function (center, zoom, options) {
  3814. if (this._animatingZoom) { return true; }
  3815. options = options || {};
  3816. // don't animate if disabled, not supported or zoom difference is too large
  3817. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3818. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3819. // offset is the pixel coords of the zoom origin relative to the current center
  3820. var scale = this.getZoomScale(zoom),
  3821. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3822. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3823. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3824. requestAnimFrame(function () {
  3825. this
  3826. ._moveStart(true, false)
  3827. ._animateZoom(center, zoom, true);
  3828. }, this);
  3829. return true;
  3830. },
  3831. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3832. if (!this._mapPane) { return; }
  3833. if (startAnim) {
  3834. this._animatingZoom = true;
  3835. // remember what center/zoom to set after animation
  3836. this._animateToCenter = center;
  3837. this._animateToZoom = zoom;
  3838. addClass(this._mapPane, 'leaflet-zoom-anim');
  3839. }
  3840. // @event zoomanim: ZoomAnimEvent
  3841. // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
  3842. this.fire('zoomanim', {
  3843. center: center,
  3844. zoom: zoom,
  3845. noUpdate: noUpdate
  3846. });
  3847. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3848. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3849. },
  3850. _onZoomTransitionEnd: function () {
  3851. if (!this._animatingZoom) { return; }
  3852. if (this._mapPane) {
  3853. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3854. }
  3855. this._animatingZoom = false;
  3856. this._move(this._animateToCenter, this._animateToZoom);
  3857. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  3858. requestAnimFrame(function () {
  3859. this._moveEnd(true);
  3860. }, this);
  3861. }
  3862. });
  3863. // @section
  3864. // @factory L.map(id: String, options?: Map options)
  3865. // Instantiates a map object given the DOM ID of a `<div>` element
  3866. // and optionally an object literal with `Map options`.
  3867. //
  3868. // @alternative
  3869. // @factory L.map(el: HTMLElement, options?: Map options)
  3870. // Instantiates a map object given an instance of a `<div>` HTML element
  3871. // and optionally an object literal with `Map options`.
  3872. function createMap(id, options) {
  3873. return new Map(id, options);
  3874. }
  3875. /*
  3876. * @class Control
  3877. * @aka L.Control
  3878. * @inherits Class
  3879. *
  3880. * L.Control is a base class for implementing map controls. Handles positioning.
  3881. * All other controls extend from this class.
  3882. */
  3883. var Control = Class.extend({
  3884. // @section
  3885. // @aka Control options
  3886. options: {
  3887. // @option position: String = 'topright'
  3888. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  3889. // `'topright'`, `'bottomleft'` or `'bottomright'`
  3890. position: 'topright'
  3891. },
  3892. initialize: function (options) {
  3893. setOptions(this, options);
  3894. },
  3895. /* @section
  3896. * Classes extending L.Control will inherit the following methods:
  3897. *
  3898. * @method getPosition: string
  3899. * Returns the position of the control.
  3900. */
  3901. getPosition: function () {
  3902. return this.options.position;
  3903. },
  3904. // @method setPosition(position: string): this
  3905. // Sets the position of the control.
  3906. setPosition: function (position) {
  3907. var map = this._map;
  3908. if (map) {
  3909. map.removeControl(this);
  3910. }
  3911. this.options.position = position;
  3912. if (map) {
  3913. map.addControl(this);
  3914. }
  3915. return this;
  3916. },
  3917. // @method getContainer: HTMLElement
  3918. // Returns the HTMLElement that contains the control.
  3919. getContainer: function () {
  3920. return this._container;
  3921. },
  3922. // @method addTo(map: Map): this
  3923. // Adds the control to the given map.
  3924. addTo: function (map) {
  3925. this.remove();
  3926. this._map = map;
  3927. var container = this._container = this.onAdd(map),
  3928. pos = this.getPosition(),
  3929. corner = map._controlCorners[pos];
  3930. addClass(container, 'leaflet-control');
  3931. if (pos.indexOf('bottom') !== -1) {
  3932. corner.insertBefore(container, corner.firstChild);
  3933. } else {
  3934. corner.appendChild(container);
  3935. }
  3936. this._map.on('unload', this.remove, this);
  3937. return this;
  3938. },
  3939. // @method remove: this
  3940. // Removes the control from the map it is currently active on.
  3941. remove: function () {
  3942. if (!this._map) {
  3943. return this;
  3944. }
  3945. remove(this._container);
  3946. if (this.onRemove) {
  3947. this.onRemove(this._map);
  3948. }
  3949. this._map.off('unload', this.remove, this);
  3950. this._map = null;
  3951. return this;
  3952. },
  3953. _refocusOnMap: function (e) {
  3954. // if map exists and event is not a keyboard event
  3955. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  3956. this._map.getContainer().focus();
  3957. }
  3958. }
  3959. });
  3960. var control = function (options) {
  3961. return new Control(options);
  3962. };
  3963. /* @section Extension methods
  3964. * @uninheritable
  3965. *
  3966. * Every control should extend from `L.Control` and (re-)implement the following methods.
  3967. *
  3968. * @method onAdd(map: Map): HTMLElement
  3969. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  3970. *
  3971. * @method onRemove(map: Map)
  3972. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  3973. */
  3974. /* @namespace Map
  3975. * @section Methods for Layers and Controls
  3976. */
  3977. Map.include({
  3978. // @method addControl(control: Control): this
  3979. // Adds the given control to the map
  3980. addControl: function (control) {
  3981. control.addTo(this);
  3982. return this;
  3983. },
  3984. // @method removeControl(control: Control): this
  3985. // Removes the given control from the map
  3986. removeControl: function (control) {
  3987. control.remove();
  3988. return this;
  3989. },
  3990. _initControlPos: function () {
  3991. var corners = this._controlCorners = {},
  3992. l = 'leaflet-',
  3993. container = this._controlContainer =
  3994. create$1('div', l + 'control-container', this._container);
  3995. function createCorner(vSide, hSide) {
  3996. var className = l + vSide + ' ' + l + hSide;
  3997. corners[vSide + hSide] = create$1('div', className, container);
  3998. }
  3999. createCorner('top', 'left');
  4000. createCorner('top', 'right');
  4001. createCorner('bottom', 'left');
  4002. createCorner('bottom', 'right');
  4003. },
  4004. _clearControlPos: function () {
  4005. for (var i in this._controlCorners) {
  4006. remove(this._controlCorners[i]);
  4007. }
  4008. remove(this._controlContainer);
  4009. delete this._controlCorners;
  4010. delete this._controlContainer;
  4011. }
  4012. });
  4013. /*
  4014. * @class Control.Layers
  4015. * @aka L.Control.Layers
  4016. * @inherits Control
  4017. *
  4018. * 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`.
  4019. *
  4020. * @example
  4021. *
  4022. * ```js
  4023. * var baseLayers = {
  4024. * "Mapbox": mapbox,
  4025. * "OpenStreetMap": osm
  4026. * };
  4027. *
  4028. * var overlays = {
  4029. * "Marker": marker,
  4030. * "Roads": roadsLayer
  4031. * };
  4032. *
  4033. * L.control.layers(baseLayers, overlays).addTo(map);
  4034. * ```
  4035. *
  4036. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  4037. *
  4038. * ```js
  4039. * {
  4040. * "<someName1>": layer1,
  4041. * "<someName2>": layer2
  4042. * }
  4043. * ```
  4044. *
  4045. * The layer names can contain HTML, which allows you to add additional styling to the items:
  4046. *
  4047. * ```js
  4048. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  4049. * ```
  4050. */
  4051. var Layers = Control.extend({
  4052. // @section
  4053. // @aka Control.Layers options
  4054. options: {
  4055. // @option collapsed: Boolean = true
  4056. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  4057. collapsed: true,
  4058. position: 'topright',
  4059. // @option autoZIndex: Boolean = true
  4060. // 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.
  4061. autoZIndex: true,
  4062. // @option hideSingleBase: Boolean = false
  4063. // If `true`, the base layers in the control will be hidden when there is only one.
  4064. hideSingleBase: false,
  4065. // @option sortLayers: Boolean = false
  4066. // Whether to sort the layers. When `false`, layers will keep the order
  4067. // in which they were added to the control.
  4068. sortLayers: false,
  4069. // @option sortFunction: Function = *
  4070. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  4071. // that will be used for sorting the layers, when `sortLayers` is `true`.
  4072. // The function receives both the `L.Layer` instances and their names, as in
  4073. // `sortFunction(layerA, layerB, nameA, nameB)`.
  4074. // By default, it sorts layers alphabetically by their name.
  4075. sortFunction: function (layerA, layerB, nameA, nameB) {
  4076. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  4077. }
  4078. },
  4079. initialize: function (baseLayers, overlays, options) {
  4080. setOptions(this, options);
  4081. this._layerControlInputs = [];
  4082. this._layers = [];
  4083. this._lastZIndex = 0;
  4084. this._handlingClick = false;
  4085. for (var i in baseLayers) {
  4086. this._addLayer(baseLayers[i], i);
  4087. }
  4088. for (i in overlays) {
  4089. this._addLayer(overlays[i], i, true);
  4090. }
  4091. },
  4092. onAdd: function (map) {
  4093. this._initLayout();
  4094. this._update();
  4095. this._map = map;
  4096. map.on('zoomend', this._checkDisabledLayers, this);
  4097. for (var i = 0; i < this._layers.length; i++) {
  4098. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4099. }
  4100. return this._container;
  4101. },
  4102. addTo: function (map) {
  4103. Control.prototype.addTo.call(this, map);
  4104. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4105. return this._expandIfNotCollapsed();
  4106. },
  4107. onRemove: function () {
  4108. this._map.off('zoomend', this._checkDisabledLayers, this);
  4109. for (var i = 0; i < this._layers.length; i++) {
  4110. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4111. }
  4112. },
  4113. // @method addBaseLayer(layer: Layer, name: String): this
  4114. // Adds a base layer (radio button entry) with the given name to the control.
  4115. addBaseLayer: function (layer, name) {
  4116. this._addLayer(layer, name);
  4117. return (this._map) ? this._update() : this;
  4118. },
  4119. // @method addOverlay(layer: Layer, name: String): this
  4120. // Adds an overlay (checkbox entry) with the given name to the control.
  4121. addOverlay: function (layer, name) {
  4122. this._addLayer(layer, name, true);
  4123. return (this._map) ? this._update() : this;
  4124. },
  4125. // @method removeLayer(layer: Layer): this
  4126. // Remove the given layer from the control.
  4127. removeLayer: function (layer) {
  4128. layer.off('add remove', this._onLayerChange, this);
  4129. var obj = this._getLayer(stamp(layer));
  4130. if (obj) {
  4131. this._layers.splice(this._layers.indexOf(obj), 1);
  4132. }
  4133. return (this._map) ? this._update() : this;
  4134. },
  4135. // @method expand(): this
  4136. // Expand the control container if collapsed.
  4137. expand: function () {
  4138. addClass(this._container, 'leaflet-control-layers-expanded');
  4139. this._section.style.height = null;
  4140. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4141. if (acceptableHeight < this._section.clientHeight) {
  4142. addClass(this._section, 'leaflet-control-layers-scrollbar');
  4143. this._section.style.height = acceptableHeight + 'px';
  4144. } else {
  4145. removeClass(this._section, 'leaflet-control-layers-scrollbar');
  4146. }
  4147. this._checkDisabledLayers();
  4148. return this;
  4149. },
  4150. // @method collapse(): this
  4151. // Collapse the control container if expanded.
  4152. collapse: function () {
  4153. removeClass(this._container, 'leaflet-control-layers-expanded');
  4154. return this;
  4155. },
  4156. _initLayout: function () {
  4157. var className = 'leaflet-control-layers',
  4158. container = this._container = create$1('div', className),
  4159. collapsed = this.options.collapsed;
  4160. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4161. container.setAttribute('aria-haspopup', true);
  4162. disableClickPropagation(container);
  4163. disableScrollPropagation(container);
  4164. var section = this._section = create$1('section', className + '-list');
  4165. if (collapsed) {
  4166. this._map.on('click', this.collapse, this);
  4167. if (!android) {
  4168. on(container, {
  4169. mouseenter: this.expand,
  4170. mouseleave: this.collapse
  4171. }, this);
  4172. }
  4173. }
  4174. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4175. link.href = '#';
  4176. link.title = 'Layers';
  4177. if (touch) {
  4178. on(link, 'click', stop);
  4179. on(link, 'click', this.expand, this);
  4180. } else {
  4181. on(link, 'focus', this.expand, this);
  4182. }
  4183. if (!collapsed) {
  4184. this.expand();
  4185. }
  4186. this._baseLayersList = create$1('div', className + '-base', section);
  4187. this._separator = create$1('div', className + '-separator', section);
  4188. this._overlaysList = create$1('div', className + '-overlays', section);
  4189. container.appendChild(section);
  4190. },
  4191. _getLayer: function (id) {
  4192. for (var i = 0; i < this._layers.length; i++) {
  4193. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4194. return this._layers[i];
  4195. }
  4196. }
  4197. },
  4198. _addLayer: function (layer, name, overlay) {
  4199. if (this._map) {
  4200. layer.on('add remove', this._onLayerChange, this);
  4201. }
  4202. this._layers.push({
  4203. layer: layer,
  4204. name: name,
  4205. overlay: overlay
  4206. });
  4207. if (this.options.sortLayers) {
  4208. this._layers.sort(bind(function (a, b) {
  4209. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4210. }, this));
  4211. }
  4212. if (this.options.autoZIndex && layer.setZIndex) {
  4213. this._lastZIndex++;
  4214. layer.setZIndex(this._lastZIndex);
  4215. }
  4216. this._expandIfNotCollapsed();
  4217. },
  4218. _update: function () {
  4219. if (!this._container) { return this; }
  4220. empty(this._baseLayersList);
  4221. empty(this._overlaysList);
  4222. this._layerControlInputs = [];
  4223. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4224. for (i = 0; i < this._layers.length; i++) {
  4225. obj = this._layers[i];
  4226. this._addItem(obj);
  4227. overlaysPresent = overlaysPresent || obj.overlay;
  4228. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4229. baseLayersCount += !obj.overlay ? 1 : 0;
  4230. }
  4231. // Hide base layers section if there's only one layer.
  4232. if (this.options.hideSingleBase) {
  4233. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4234. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4235. }
  4236. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4237. return this;
  4238. },
  4239. _onLayerChange: function (e) {
  4240. if (!this._handlingClick) {
  4241. this._update();
  4242. }
  4243. var obj = this._getLayer(stamp(e.target));
  4244. // @namespace Map
  4245. // @section Layer events
  4246. // @event baselayerchange: LayersControlEvent
  4247. // Fired when the base layer is changed through the [layer control](#control-layers).
  4248. // @event overlayadd: LayersControlEvent
  4249. // Fired when an overlay is selected through the [layer control](#control-layers).
  4250. // @event overlayremove: LayersControlEvent
  4251. // Fired when an overlay is deselected through the [layer control](#control-layers).
  4252. // @namespace Control.Layers
  4253. var type = obj.overlay ?
  4254. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4255. (e.type === 'add' ? 'baselayerchange' : null);
  4256. if (type) {
  4257. this._map.fire(type, obj);
  4258. }
  4259. },
  4260. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  4261. _createRadioElement: function (name, checked) {
  4262. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4263. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4264. var radioFragment = document.createElement('div');
  4265. radioFragment.innerHTML = radioHtml;
  4266. return radioFragment.firstChild;
  4267. },
  4268. _addItem: function (obj) {
  4269. var label = document.createElement('label'),
  4270. checked = this._map.hasLayer(obj.layer),
  4271. input;
  4272. if (obj.overlay) {
  4273. input = document.createElement('input');
  4274. input.type = 'checkbox';
  4275. input.className = 'leaflet-control-layers-selector';
  4276. input.defaultChecked = checked;
  4277. } else {
  4278. input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);
  4279. }
  4280. this._layerControlInputs.push(input);
  4281. input.layerId = stamp(obj.layer);
  4282. on(input, 'click', this._onInputClick, this);
  4283. var name = document.createElement('span');
  4284. name.innerHTML = ' ' + obj.name;
  4285. // Helps from preventing layer control flicker when checkboxes are disabled
  4286. // https://github.com/Leaflet/Leaflet/issues/2771
  4287. var holder = document.createElement('div');
  4288. label.appendChild(holder);
  4289. holder.appendChild(input);
  4290. holder.appendChild(name);
  4291. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4292. container.appendChild(label);
  4293. this._checkDisabledLayers();
  4294. return label;
  4295. },
  4296. _onInputClick: function () {
  4297. var inputs = this._layerControlInputs,
  4298. input, layer;
  4299. var addedLayers = [],
  4300. removedLayers = [];
  4301. this._handlingClick = true;
  4302. for (var i = inputs.length - 1; i >= 0; i--) {
  4303. input = inputs[i];
  4304. layer = this._getLayer(input.layerId).layer;
  4305. if (input.checked) {
  4306. addedLayers.push(layer);
  4307. } else if (!input.checked) {
  4308. removedLayers.push(layer);
  4309. }
  4310. }
  4311. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4312. for (i = 0; i < removedLayers.length; i++) {
  4313. if (this._map.hasLayer(removedLayers[i])) {
  4314. this._map.removeLayer(removedLayers[i]);
  4315. }
  4316. }
  4317. for (i = 0; i < addedLayers.length; i++) {
  4318. if (!this._map.hasLayer(addedLayers[i])) {
  4319. this._map.addLayer(addedLayers[i]);
  4320. }
  4321. }
  4322. this._handlingClick = false;
  4323. this._refocusOnMap();
  4324. },
  4325. _checkDisabledLayers: function () {
  4326. var inputs = this._layerControlInputs,
  4327. input,
  4328. layer,
  4329. zoom = this._map.getZoom();
  4330. for (var i = inputs.length - 1; i >= 0; i--) {
  4331. input = inputs[i];
  4332. layer = this._getLayer(input.layerId).layer;
  4333. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4334. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4335. }
  4336. },
  4337. _expandIfNotCollapsed: function () {
  4338. if (this._map && !this.options.collapsed) {
  4339. this.expand();
  4340. }
  4341. return this;
  4342. },
  4343. _expand: function () {
  4344. // Backward compatibility, remove me in 1.1.
  4345. return this.expand();
  4346. },
  4347. _collapse: function () {
  4348. // Backward compatibility, remove me in 1.1.
  4349. return this.collapse();
  4350. }
  4351. });
  4352. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4353. // Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
  4354. var layers = function (baseLayers, overlays, options) {
  4355. return new Layers(baseLayers, overlays, options);
  4356. };
  4357. /*
  4358. * @class Control.Zoom
  4359. * @aka L.Control.Zoom
  4360. * @inherits Control
  4361. *
  4362. * 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`.
  4363. */
  4364. var Zoom = Control.extend({
  4365. // @section
  4366. // @aka Control.Zoom options
  4367. options: {
  4368. position: 'topleft',
  4369. // @option zoomInText: String = '+'
  4370. // The text set on the 'zoom in' button.
  4371. zoomInText: '+',
  4372. // @option zoomInTitle: String = 'Zoom in'
  4373. // The title set on the 'zoom in' button.
  4374. zoomInTitle: 'Zoom in',
  4375. // @option zoomOutText: String = '&#x2212;'
  4376. // The text set on the 'zoom out' button.
  4377. zoomOutText: '&#x2212;',
  4378. // @option zoomOutTitle: String = 'Zoom out'
  4379. // The title set on the 'zoom out' button.
  4380. zoomOutTitle: 'Zoom out'
  4381. },
  4382. onAdd: function (map) {
  4383. var zoomName = 'leaflet-control-zoom',
  4384. container = create$1('div', zoomName + ' leaflet-bar'),
  4385. options = this.options;
  4386. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4387. zoomName + '-in', container, this._zoomIn);
  4388. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4389. zoomName + '-out', container, this._zoomOut);
  4390. this._updateDisabled();
  4391. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4392. return container;
  4393. },
  4394. onRemove: function (map) {
  4395. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4396. },
  4397. disable: function () {
  4398. this._disabled = true;
  4399. this._updateDisabled();
  4400. return this;
  4401. },
  4402. enable: function () {
  4403. this._disabled = false;
  4404. this._updateDisabled();
  4405. return this;
  4406. },
  4407. _zoomIn: function (e) {
  4408. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4409. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4410. }
  4411. },
  4412. _zoomOut: function (e) {
  4413. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4414. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4415. }
  4416. },
  4417. _createButton: function (html, title, className, container, fn) {
  4418. var link = create$1('a', className, container);
  4419. link.innerHTML = html;
  4420. link.href = '#';
  4421. link.title = title;
  4422. /*
  4423. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4424. */
  4425. link.setAttribute('role', 'button');
  4426. link.setAttribute('aria-label', title);
  4427. disableClickPropagation(link);
  4428. on(link, 'click', stop);
  4429. on(link, 'click', fn, this);
  4430. on(link, 'click', this._refocusOnMap, this);
  4431. return link;
  4432. },
  4433. _updateDisabled: function () {
  4434. var map = this._map,
  4435. className = 'leaflet-disabled';
  4436. removeClass(this._zoomInButton, className);
  4437. removeClass(this._zoomOutButton, className);
  4438. if (this._disabled || map._zoom === map.getMinZoom()) {
  4439. addClass(this._zoomOutButton, className);
  4440. }
  4441. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4442. addClass(this._zoomInButton, className);
  4443. }
  4444. }
  4445. });
  4446. // @namespace Map
  4447. // @section Control options
  4448. // @option zoomControl: Boolean = true
  4449. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4450. Map.mergeOptions({
  4451. zoomControl: true
  4452. });
  4453. Map.addInitHook(function () {
  4454. if (this.options.zoomControl) {
  4455. // @section Controls
  4456. // @property zoomControl: Control.Zoom
  4457. // The default zoom control (only available if the
  4458. // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
  4459. this.zoomControl = new Zoom();
  4460. this.addControl(this.zoomControl);
  4461. }
  4462. });
  4463. // @namespace Control.Zoom
  4464. // @factory L.control.zoom(options: Control.Zoom options)
  4465. // Creates a zoom control
  4466. var zoom = function (options) {
  4467. return new Zoom(options);
  4468. };
  4469. /*
  4470. * @class Control.Scale
  4471. * @aka L.Control.Scale
  4472. * @inherits Control
  4473. *
  4474. * 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`.
  4475. *
  4476. * @example
  4477. *
  4478. * ```js
  4479. * L.control.scale().addTo(map);
  4480. * ```
  4481. */
  4482. var Scale = Control.extend({
  4483. // @section
  4484. // @aka Control.Scale options
  4485. options: {
  4486. position: 'bottomleft',
  4487. // @option maxWidth: Number = 100
  4488. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4489. maxWidth: 100,
  4490. // @option metric: Boolean = True
  4491. // Whether to show the metric scale line (m/km).
  4492. metric: true,
  4493. // @option imperial: Boolean = True
  4494. // Whether to show the imperial scale line (mi/ft).
  4495. imperial: true
  4496. // @option updateWhenIdle: Boolean = false
  4497. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4498. },
  4499. onAdd: function (map) {
  4500. var className = 'leaflet-control-scale',
  4501. container = create$1('div', className),
  4502. options = this.options;
  4503. this._addScales(options, className + '-line', container);
  4504. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4505. map.whenReady(this._update, this);
  4506. return container;
  4507. },
  4508. onRemove: function (map) {
  4509. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4510. },
  4511. _addScales: function (options, className, container) {
  4512. if (options.metric) {
  4513. this._mScale = create$1('div', className, container);
  4514. }
  4515. if (options.imperial) {
  4516. this._iScale = create$1('div', className, container);
  4517. }
  4518. },
  4519. _update: function () {
  4520. var map = this._map,
  4521. y = map.getSize().y / 2;
  4522. var maxMeters = map.distance(
  4523. map.containerPointToLatLng([0, y]),
  4524. map.containerPointToLatLng([this.options.maxWidth, y]));
  4525. this._updateScales(maxMeters);
  4526. },
  4527. _updateScales: function (maxMeters) {
  4528. if (this.options.metric && maxMeters) {
  4529. this._updateMetric(maxMeters);
  4530. }
  4531. if (this.options.imperial && maxMeters) {
  4532. this._updateImperial(maxMeters);
  4533. }
  4534. },
  4535. _updateMetric: function (maxMeters) {
  4536. var meters = this._getRoundNum(maxMeters),
  4537. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4538. this._updateScale(this._mScale, label, meters / maxMeters);
  4539. },
  4540. _updateImperial: function (maxMeters) {
  4541. var maxFeet = maxMeters * 3.2808399,
  4542. maxMiles, miles, feet;
  4543. if (maxFeet > 5280) {
  4544. maxMiles = maxFeet / 5280;
  4545. miles = this._getRoundNum(maxMiles);
  4546. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4547. } else {
  4548. feet = this._getRoundNum(maxFeet);
  4549. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4550. }
  4551. },
  4552. _updateScale: function (scale, text, ratio) {
  4553. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4554. scale.innerHTML = text;
  4555. },
  4556. _getRoundNum: function (num) {
  4557. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4558. d = num / pow10;
  4559. d = d >= 10 ? 10 :
  4560. d >= 5 ? 5 :
  4561. d >= 3 ? 3 :
  4562. d >= 2 ? 2 : 1;
  4563. return pow10 * d;
  4564. }
  4565. });
  4566. // @factory L.control.scale(options?: Control.Scale options)
  4567. // Creates an scale control with the given options.
  4568. var scale = function (options) {
  4569. return new Scale(options);
  4570. };
  4571. /*
  4572. * @class Control.Attribution
  4573. * @aka L.Control.Attribution
  4574. * @inherits Control
  4575. *
  4576. * 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.
  4577. */
  4578. var Attribution = Control.extend({
  4579. // @section
  4580. // @aka Control.Attribution options
  4581. options: {
  4582. position: 'bottomright',
  4583. // @option prefix: String = 'Leaflet'
  4584. // The HTML text shown before the attributions. Pass `false` to disable.
  4585. prefix: '<a href="https://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  4586. },
  4587. initialize: function (options) {
  4588. setOptions(this, options);
  4589. this._attributions = {};
  4590. },
  4591. onAdd: function (map) {
  4592. map.attributionControl = this;
  4593. this._container = create$1('div', 'leaflet-control-attribution');
  4594. disableClickPropagation(this._container);
  4595. // TODO ugly, refactor
  4596. for (var i in map._layers) {
  4597. if (map._layers[i].getAttribution) {
  4598. this.addAttribution(map._layers[i].getAttribution());
  4599. }
  4600. }
  4601. this._update();
  4602. return this._container;
  4603. },
  4604. // @method setPrefix(prefix: String): this
  4605. // Sets the text before the attributions.
  4606. setPrefix: function (prefix) {
  4607. this.options.prefix = prefix;
  4608. this._update();
  4609. return this;
  4610. },
  4611. // @method addAttribution(text: String): this
  4612. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  4613. addAttribution: function (text) {
  4614. if (!text) { return this; }
  4615. if (!this._attributions[text]) {
  4616. this._attributions[text] = 0;
  4617. }
  4618. this._attributions[text]++;
  4619. this._update();
  4620. return this;
  4621. },
  4622. // @method removeAttribution(text: String): this
  4623. // Removes an attribution text.
  4624. removeAttribution: function (text) {
  4625. if (!text) { return this; }
  4626. if (this._attributions[text]) {
  4627. this._attributions[text]--;
  4628. this._update();
  4629. }
  4630. return this;
  4631. },
  4632. _update: function () {
  4633. if (!this._map) { return; }
  4634. var attribs = [];
  4635. for (var i in this._attributions) {
  4636. if (this._attributions[i]) {
  4637. attribs.push(i);
  4638. }
  4639. }
  4640. var prefixAndAttribs = [];
  4641. if (this.options.prefix) {
  4642. prefixAndAttribs.push(this.options.prefix);
  4643. }
  4644. if (attribs.length) {
  4645. prefixAndAttribs.push(attribs.join(', '));
  4646. }
  4647. this._container.innerHTML = prefixAndAttribs.join(' | ');
  4648. }
  4649. });
  4650. // @namespace Map
  4651. // @section Control options
  4652. // @option attributionControl: Boolean = true
  4653. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4654. Map.mergeOptions({
  4655. attributionControl: true
  4656. });
  4657. Map.addInitHook(function () {
  4658. if (this.options.attributionControl) {
  4659. new Attribution().addTo(this);
  4660. }
  4661. });
  4662. // @namespace Control.Attribution
  4663. // @factory L.control.attribution(options: Control.Attribution options)
  4664. // Creates an attribution control.
  4665. var attribution = function (options) {
  4666. return new Attribution(options);
  4667. };
  4668. Control.Layers = Layers;
  4669. Control.Zoom = Zoom;
  4670. Control.Scale = Scale;
  4671. Control.Attribution = Attribution;
  4672. control.layers = layers;
  4673. control.zoom = zoom;
  4674. control.scale = scale;
  4675. control.attribution = attribution;
  4676. /*
  4677. L.Handler is a base class for handler classes that are used internally to inject
  4678. interaction features like dragging to classes like Map and Marker.
  4679. */
  4680. // @class Handler
  4681. // @aka L.Handler
  4682. // Abstract class for map interaction handlers
  4683. var Handler = Class.extend({
  4684. initialize: function (map) {
  4685. this._map = map;
  4686. },
  4687. // @method enable(): this
  4688. // Enables the handler
  4689. enable: function () {
  4690. if (this._enabled) { return this; }
  4691. this._enabled = true;
  4692. this.addHooks();
  4693. return this;
  4694. },
  4695. // @method disable(): this
  4696. // Disables the handler
  4697. disable: function () {
  4698. if (!this._enabled) { return this; }
  4699. this._enabled = false;
  4700. this.removeHooks();
  4701. return this;
  4702. },
  4703. // @method enabled(): Boolean
  4704. // Returns `true` if the handler is enabled
  4705. enabled: function () {
  4706. return !!this._enabled;
  4707. }
  4708. // @section Extension methods
  4709. // Classes inheriting from `Handler` must implement the two following methods:
  4710. // @method addHooks()
  4711. // Called when the handler is enabled, should add event hooks.
  4712. // @method removeHooks()
  4713. // Called when the handler is disabled, should remove the event hooks added previously.
  4714. });
  4715. // @section There is static function which can be called without instantiating L.Handler:
  4716. // @function addTo(map: Map, name: String): this
  4717. // Adds a new Handler to the given map with the given name.
  4718. Handler.addTo = function (map, name) {
  4719. map.addHandler(name, this);
  4720. return this;
  4721. };
  4722. var Mixin = {Events: Events};
  4723. /*
  4724. * @class Draggable
  4725. * @aka L.Draggable
  4726. * @inherits Evented
  4727. *
  4728. * A class for making DOM elements draggable (including touch support).
  4729. * Used internally for map and marker dragging. Only works for elements
  4730. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4731. *
  4732. * @example
  4733. * ```js
  4734. * var draggable = new L.Draggable(elementToDrag);
  4735. * draggable.enable();
  4736. * ```
  4737. */
  4738. var START = touch ? 'touchstart mousedown' : 'mousedown';
  4739. var END = {
  4740. mousedown: 'mouseup',
  4741. touchstart: 'touchend',
  4742. pointerdown: 'touchend',
  4743. MSPointerDown: 'touchend'
  4744. };
  4745. var MOVE = {
  4746. mousedown: 'mousemove',
  4747. touchstart: 'touchmove',
  4748. pointerdown: 'touchmove',
  4749. MSPointerDown: 'touchmove'
  4750. };
  4751. var Draggable = Evented.extend({
  4752. options: {
  4753. // @section
  4754. // @aka Draggable options
  4755. // @option clickTolerance: Number = 3
  4756. // The max number of pixels a user can shift the mouse pointer during a click
  4757. // for it to be considered a valid click (as opposed to a mouse drag).
  4758. clickTolerance: 3
  4759. },
  4760. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4761. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4762. initialize: function (element, dragStartTarget, preventOutline$$1, options) {
  4763. setOptions(this, options);
  4764. this._element = element;
  4765. this._dragStartTarget = dragStartTarget || element;
  4766. this._preventOutline = preventOutline$$1;
  4767. },
  4768. // @method enable()
  4769. // Enables the dragging ability
  4770. enable: function () {
  4771. if (this._enabled) { return; }
  4772. on(this._dragStartTarget, START, this._onDown, this);
  4773. this._enabled = true;
  4774. },
  4775. // @method disable()
  4776. // Disables the dragging ability
  4777. disable: function () {
  4778. if (!this._enabled) { return; }
  4779. // If we're currently dragging this draggable,
  4780. // disabling it counts as first ending the drag.
  4781. if (Draggable._dragging === this) {
  4782. this.finishDrag();
  4783. }
  4784. off(this._dragStartTarget, START, this._onDown, this);
  4785. this._enabled = false;
  4786. this._moved = false;
  4787. },
  4788. _onDown: function (e) {
  4789. // Ignore simulated events, since we handle both touch and
  4790. // mouse explicitly; otherwise we risk getting duplicates of
  4791. // touch events, see #4315.
  4792. // Also ignore the event if disabled; this happens in IE11
  4793. // under some circumstances, see #3666.
  4794. if (e._simulated || !this._enabled) { return; }
  4795. this._moved = false;
  4796. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4797. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4798. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4799. if (this._preventOutline) {
  4800. preventOutline(this._element);
  4801. }
  4802. disableImageDrag();
  4803. disableTextSelection();
  4804. if (this._moving) { return; }
  4805. // @event down: Event
  4806. // Fired when a drag is about to start.
  4807. this.fire('down');
  4808. var first = e.touches ? e.touches[0] : e,
  4809. sizedParent = getSizedParentNode(this._element);
  4810. this._startPoint = new Point(first.clientX, first.clientY);
  4811. // Cache the scale, so that we can continuously compensate for it during drag (_onMove).
  4812. this._parentScale = getScale(sizedParent);
  4813. on(document, MOVE[e.type], this._onMove, this);
  4814. on(document, END[e.type], this._onUp, this);
  4815. },
  4816. _onMove: function (e) {
  4817. // Ignore simulated events, since we handle both touch and
  4818. // mouse explicitly; otherwise we risk getting duplicates of
  4819. // touch events, see #4315.
  4820. // Also ignore the event if disabled; this happens in IE11
  4821. // under some circumstances, see #3666.
  4822. if (e._simulated || !this._enabled) { return; }
  4823. if (e.touches && e.touches.length > 1) {
  4824. this._moved = true;
  4825. return;
  4826. }
  4827. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4828. offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);
  4829. if (!offset.x && !offset.y) { return; }
  4830. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4831. // We assume that the parent container's position, border and scale do not change for the duration of the drag.
  4832. // Therefore there is no need to account for the position and border (they are eliminated by the subtraction)
  4833. // and we can use the cached value for the scale.
  4834. offset.x /= this._parentScale.x;
  4835. offset.y /= this._parentScale.y;
  4836. preventDefault(e);
  4837. if (!this._moved) {
  4838. // @event dragstart: Event
  4839. // Fired when a drag starts
  4840. this.fire('dragstart');
  4841. this._moved = true;
  4842. this._startPos = getPosition(this._element).subtract(offset);
  4843. addClass(document.body, 'leaflet-dragging');
  4844. this._lastTarget = e.target || e.srcElement;
  4845. // IE and Edge do not give the <use> element, so fetch it
  4846. // if necessary
  4847. if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
  4848. this._lastTarget = this._lastTarget.correspondingUseElement;
  4849. }
  4850. addClass(this._lastTarget, 'leaflet-drag-target');
  4851. }
  4852. this._newPos = this._startPos.add(offset);
  4853. this._moving = true;
  4854. cancelAnimFrame(this._animRequest);
  4855. this._lastEvent = e;
  4856. this._animRequest = requestAnimFrame(this._updatePosition, this, true);
  4857. },
  4858. _updatePosition: function () {
  4859. var e = {originalEvent: this._lastEvent};
  4860. // @event predrag: Event
  4861. // Fired continuously during dragging *before* each corresponding
  4862. // update of the element's position.
  4863. this.fire('predrag', e);
  4864. setPosition(this._element, this._newPos);
  4865. // @event drag: Event
  4866. // Fired continuously during dragging.
  4867. this.fire('drag', e);
  4868. },
  4869. _onUp: function (e) {
  4870. // Ignore simulated events, since we handle both touch and
  4871. // mouse explicitly; otherwise we risk getting duplicates of
  4872. // touch events, see #4315.
  4873. // Also ignore the event if disabled; this happens in IE11
  4874. // under some circumstances, see #3666.
  4875. if (e._simulated || !this._enabled) { return; }
  4876. this.finishDrag();
  4877. },
  4878. finishDrag: function () {
  4879. removeClass(document.body, 'leaflet-dragging');
  4880. if (this._lastTarget) {
  4881. removeClass(this._lastTarget, 'leaflet-drag-target');
  4882. this._lastTarget = null;
  4883. }
  4884. for (var i in MOVE) {
  4885. off(document, MOVE[i], this._onMove, this);
  4886. off(document, END[i], this._onUp, this);
  4887. }
  4888. enableImageDrag();
  4889. enableTextSelection();
  4890. if (this._moved && this._moving) {
  4891. // ensure drag is not fired after dragend
  4892. cancelAnimFrame(this._animRequest);
  4893. // @event dragend: DragEndEvent
  4894. // Fired when the drag ends.
  4895. this.fire('dragend', {
  4896. distance: this._newPos.distanceTo(this._startPos)
  4897. });
  4898. }
  4899. this._moving = false;
  4900. Draggable._dragging = false;
  4901. }
  4902. });
  4903. /*
  4904. * @namespace LineUtil
  4905. *
  4906. * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
  4907. */
  4908. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  4909. // Improves rendering performance dramatically by lessening the number of points to draw.
  4910. // @function simplify(points: Point[], tolerance: Number): Point[]
  4911. // Dramatically reduces the number of points in a polyline while retaining
  4912. // its shape and returns a new array of simplified points, using the
  4913. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  4914. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  4915. // each zoom level and also reducing visual noise. tolerance affects the amount of
  4916. // simplification (lesser value means higher quality but slower and with more points).
  4917. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  4918. function simplify(points, tolerance) {
  4919. if (!tolerance || !points.length) {
  4920. return points.slice();
  4921. }
  4922. var sqTolerance = tolerance * tolerance;
  4923. // stage 1: vertex reduction
  4924. points = _reducePoints(points, sqTolerance);
  4925. // stage 2: Douglas-Peucker simplification
  4926. points = _simplifyDP(points, sqTolerance);
  4927. return points;
  4928. }
  4929. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  4930. // Returns the distance between point `p` and segment `p1` to `p2`.
  4931. function pointToSegmentDistance(p, p1, p2) {
  4932. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  4933. }
  4934. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  4935. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  4936. function closestPointOnSegment(p, p1, p2) {
  4937. return _sqClosestPointOnSegment(p, p1, p2);
  4938. }
  4939. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  4940. function _simplifyDP(points, sqTolerance) {
  4941. var len = points.length,
  4942. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  4943. markers = new ArrayConstructor(len);
  4944. markers[0] = markers[len - 1] = 1;
  4945. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  4946. var i,
  4947. newPoints = [];
  4948. for (i = 0; i < len; i++) {
  4949. if (markers[i]) {
  4950. newPoints.push(points[i]);
  4951. }
  4952. }
  4953. return newPoints;
  4954. }
  4955. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  4956. var maxSqDist = 0,
  4957. index, i, sqDist;
  4958. for (i = first + 1; i <= last - 1; i++) {
  4959. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  4960. if (sqDist > maxSqDist) {
  4961. index = i;
  4962. maxSqDist = sqDist;
  4963. }
  4964. }
  4965. if (maxSqDist > sqTolerance) {
  4966. markers[index] = 1;
  4967. _simplifyDPStep(points, markers, sqTolerance, first, index);
  4968. _simplifyDPStep(points, markers, sqTolerance, index, last);
  4969. }
  4970. }
  4971. // reduce points that are too close to each other to a single point
  4972. function _reducePoints(points, sqTolerance) {
  4973. var reducedPoints = [points[0]];
  4974. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  4975. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  4976. reducedPoints.push(points[i]);
  4977. prev = i;
  4978. }
  4979. }
  4980. if (prev < len - 1) {
  4981. reducedPoints.push(points[len - 1]);
  4982. }
  4983. return reducedPoints;
  4984. }
  4985. var _lastCode;
  4986. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  4987. // Clips the segment a to b by rectangular bounds with the
  4988. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  4989. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  4990. // points that are on the screen or near, increasing performance.
  4991. function clipSegment(a, b, bounds, useLastCode, round) {
  4992. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  4993. codeB = _getBitCode(b, bounds),
  4994. codeOut, p, newCode;
  4995. // save 2nd code to avoid calculating it on the next segment
  4996. _lastCode = codeB;
  4997. while (true) {
  4998. // if a,b is inside the clip window (trivial accept)
  4999. if (!(codeA | codeB)) {
  5000. return [a, b];
  5001. }
  5002. // if a,b is outside the clip window (trivial reject)
  5003. if (codeA & codeB) {
  5004. return false;
  5005. }
  5006. // other cases
  5007. codeOut = codeA || codeB;
  5008. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  5009. newCode = _getBitCode(p, bounds);
  5010. if (codeOut === codeA) {
  5011. a = p;
  5012. codeA = newCode;
  5013. } else {
  5014. b = p;
  5015. codeB = newCode;
  5016. }
  5017. }
  5018. }
  5019. function _getEdgeIntersection(a, b, code, bounds, round) {
  5020. var dx = b.x - a.x,
  5021. dy = b.y - a.y,
  5022. min = bounds.min,
  5023. max = bounds.max,
  5024. x, y;
  5025. if (code & 8) { // top
  5026. x = a.x + dx * (max.y - a.y) / dy;
  5027. y = max.y;
  5028. } else if (code & 4) { // bottom
  5029. x = a.x + dx * (min.y - a.y) / dy;
  5030. y = min.y;
  5031. } else if (code & 2) { // right
  5032. x = max.x;
  5033. y = a.y + dy * (max.x - a.x) / dx;
  5034. } else if (code & 1) { // left
  5035. x = min.x;
  5036. y = a.y + dy * (min.x - a.x) / dx;
  5037. }
  5038. return new Point(x, y, round);
  5039. }
  5040. function _getBitCode(p, bounds) {
  5041. var code = 0;
  5042. if (p.x < bounds.min.x) { // left
  5043. code |= 1;
  5044. } else if (p.x > bounds.max.x) { // right
  5045. code |= 2;
  5046. }
  5047. if (p.y < bounds.min.y) { // bottom
  5048. code |= 4;
  5049. } else if (p.y > bounds.max.y) { // top
  5050. code |= 8;
  5051. }
  5052. return code;
  5053. }
  5054. // square distance (to avoid unnecessary Math.sqrt calls)
  5055. function _sqDist(p1, p2) {
  5056. var dx = p2.x - p1.x,
  5057. dy = p2.y - p1.y;
  5058. return dx * dx + dy * dy;
  5059. }
  5060. // return closest point on segment or distance to that point
  5061. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  5062. var x = p1.x,
  5063. y = p1.y,
  5064. dx = p2.x - x,
  5065. dy = p2.y - y,
  5066. dot = dx * dx + dy * dy,
  5067. t;
  5068. if (dot > 0) {
  5069. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  5070. if (t > 1) {
  5071. x = p2.x;
  5072. y = p2.y;
  5073. } else if (t > 0) {
  5074. x += dx * t;
  5075. y += dy * t;
  5076. }
  5077. }
  5078. dx = p.x - x;
  5079. dy = p.y - y;
  5080. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  5081. }
  5082. // @function isFlat(latlngs: LatLng[]): Boolean
  5083. // Returns true if `latlngs` is a flat array, false is nested.
  5084. function isFlat(latlngs) {
  5085. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  5086. }
  5087. function _flat(latlngs) {
  5088. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  5089. return isFlat(latlngs);
  5090. }
  5091. var LineUtil = (Object.freeze || Object)({
  5092. simplify: simplify,
  5093. pointToSegmentDistance: pointToSegmentDistance,
  5094. closestPointOnSegment: closestPointOnSegment,
  5095. clipSegment: clipSegment,
  5096. _getEdgeIntersection: _getEdgeIntersection,
  5097. _getBitCode: _getBitCode,
  5098. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5099. isFlat: isFlat,
  5100. _flat: _flat
  5101. });
  5102. /*
  5103. * @namespace PolyUtil
  5104. * Various utility functions for polygon geometries.
  5105. */
  5106. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5107. * 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)).
  5108. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5109. * performance. Note that polygon points needs different algorithm for clipping
  5110. * than polyline, so there's a separate method for it.
  5111. */
  5112. function clipPolygon(points, bounds, round) {
  5113. var clippedPoints,
  5114. edges = [1, 4, 2, 8],
  5115. i, j, k,
  5116. a, b,
  5117. len, edge, p;
  5118. for (i = 0, len = points.length; i < len; i++) {
  5119. points[i]._code = _getBitCode(points[i], bounds);
  5120. }
  5121. // for each edge (left, bottom, right, top)
  5122. for (k = 0; k < 4; k++) {
  5123. edge = edges[k];
  5124. clippedPoints = [];
  5125. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5126. a = points[i];
  5127. b = points[j];
  5128. // if a is inside the clip window
  5129. if (!(a._code & edge)) {
  5130. // if b is outside the clip window (a->b goes out of screen)
  5131. if (b._code & edge) {
  5132. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5133. p._code = _getBitCode(p, bounds);
  5134. clippedPoints.push(p);
  5135. }
  5136. clippedPoints.push(a);
  5137. // else if b is inside the clip window (a->b enters the screen)
  5138. } else if (!(b._code & edge)) {
  5139. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5140. p._code = _getBitCode(p, bounds);
  5141. clippedPoints.push(p);
  5142. }
  5143. }
  5144. points = clippedPoints;
  5145. }
  5146. return points;
  5147. }
  5148. var PolyUtil = (Object.freeze || Object)({
  5149. clipPolygon: clipPolygon
  5150. });
  5151. /*
  5152. * @namespace Projection
  5153. * @section
  5154. * Leaflet comes with a set of already defined Projections out of the box:
  5155. *
  5156. * @projection L.Projection.LonLat
  5157. *
  5158. * Equirectangular, or Plate Carree projection — the most simple projection,
  5159. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5160. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5161. * `EPSG:4326` and `Simple` CRS.
  5162. */
  5163. var LonLat = {
  5164. project: function (latlng) {
  5165. return new Point(latlng.lng, latlng.lat);
  5166. },
  5167. unproject: function (point) {
  5168. return new LatLng(point.y, point.x);
  5169. },
  5170. bounds: new Bounds([-180, -90], [180, 90])
  5171. };
  5172. /*
  5173. * @namespace Projection
  5174. * @projection L.Projection.Mercator
  5175. *
  5176. * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.
  5177. */
  5178. var Mercator = {
  5179. R: 6378137,
  5180. R_MINOR: 6356752.314245179,
  5181. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5182. project: function (latlng) {
  5183. var d = Math.PI / 180,
  5184. r = this.R,
  5185. y = latlng.lat * d,
  5186. tmp = this.R_MINOR / r,
  5187. e = Math.sqrt(1 - tmp * tmp),
  5188. con = e * Math.sin(y);
  5189. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5190. y = -r * Math.log(Math.max(ts, 1E-10));
  5191. return new Point(latlng.lng * d * r, y);
  5192. },
  5193. unproject: function (point) {
  5194. var d = 180 / Math.PI,
  5195. r = this.R,
  5196. tmp = this.R_MINOR / r,
  5197. e = Math.sqrt(1 - tmp * tmp),
  5198. ts = Math.exp(-point.y / r),
  5199. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5200. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5201. con = e * Math.sin(phi);
  5202. con = Math.pow((1 - con) / (1 + con), e / 2);
  5203. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5204. phi += dphi;
  5205. }
  5206. return new LatLng(phi * d, point.x * d / r);
  5207. }
  5208. };
  5209. /*
  5210. * @class Projection
  5211. * An object with methods for projecting geographical coordinates of the world onto
  5212. * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).
  5213. * @property bounds: Bounds
  5214. * The bounds (specified in CRS units) where the projection is valid
  5215. * @method project(latlng: LatLng): Point
  5216. * Projects geographical coordinates into a 2D point.
  5217. * Only accepts actual `L.LatLng` instances, not arrays.
  5218. * @method unproject(point: Point): LatLng
  5219. * The inverse of `project`. Projects a 2D point into a geographical location.
  5220. * Only accepts actual `L.Point` instances, not arrays.
  5221. * Note that the projection instances do not inherit from Leafet's `Class` object,
  5222. * and can't be instantiated. Also, new classes can't inherit from them,
  5223. * and methods can't be added to them with the `include` function.
  5224. */
  5225. var index = (Object.freeze || Object)({
  5226. LonLat: LonLat,
  5227. Mercator: Mercator,
  5228. SphericalMercator: SphericalMercator
  5229. });
  5230. /*
  5231. * @namespace CRS
  5232. * @crs L.CRS.EPSG3395
  5233. *
  5234. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5235. */
  5236. var EPSG3395 = extend({}, Earth, {
  5237. code: 'EPSG:3395',
  5238. projection: Mercator,
  5239. transformation: (function () {
  5240. var scale = 0.5 / (Math.PI * Mercator.R);
  5241. return toTransformation(scale, 0.5, -scale, 0.5);
  5242. }())
  5243. });
  5244. /*
  5245. * @namespace CRS
  5246. * @crs L.CRS.EPSG4326
  5247. *
  5248. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5249. *
  5250. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5251. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5252. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5253. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5254. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5255. */
  5256. var EPSG4326 = extend({}, Earth, {
  5257. code: 'EPSG:4326',
  5258. projection: LonLat,
  5259. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5260. });
  5261. /*
  5262. * @namespace CRS
  5263. * @crs L.CRS.Simple
  5264. *
  5265. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5266. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5267. * axis should still be inverted (going from bottom to top). `distance()` returns
  5268. * simple euclidean distance.
  5269. */
  5270. var Simple = extend({}, CRS, {
  5271. projection: LonLat,
  5272. transformation: toTransformation(1, 0, -1, 0),
  5273. scale: function (zoom) {
  5274. return Math.pow(2, zoom);
  5275. },
  5276. zoom: function (scale) {
  5277. return Math.log(scale) / Math.LN2;
  5278. },
  5279. distance: function (latlng1, latlng2) {
  5280. var dx = latlng2.lng - latlng1.lng,
  5281. dy = latlng2.lat - latlng1.lat;
  5282. return Math.sqrt(dx * dx + dy * dy);
  5283. },
  5284. infinite: true
  5285. });
  5286. CRS.Earth = Earth;
  5287. CRS.EPSG3395 = EPSG3395;
  5288. CRS.EPSG3857 = EPSG3857;
  5289. CRS.EPSG900913 = EPSG900913;
  5290. CRS.EPSG4326 = EPSG4326;
  5291. CRS.Simple = Simple;
  5292. /*
  5293. * @class Layer
  5294. * @inherits Evented
  5295. * @aka L.Layer
  5296. * @aka ILayer
  5297. *
  5298. * A set of methods from the Layer base class that all Leaflet layers use.
  5299. * Inherits all methods, options and events from `L.Evented`.
  5300. *
  5301. * @example
  5302. *
  5303. * ```js
  5304. * var layer = L.marker(latlng).addTo(map);
  5305. * layer.addTo(map);
  5306. * layer.remove();
  5307. * ```
  5308. *
  5309. * @event add: Event
  5310. * Fired after the layer is added to a map
  5311. *
  5312. * @event remove: Event
  5313. * Fired after the layer is removed from a map
  5314. */
  5315. var Layer = Evented.extend({
  5316. // Classes extending `L.Layer` will inherit the following options:
  5317. options: {
  5318. // @option pane: String = 'overlayPane'
  5319. // 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.
  5320. pane: 'overlayPane',
  5321. // @option attribution: String = null
  5322. // 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.
  5323. attribution: null,
  5324. bubblingMouseEvents: true
  5325. },
  5326. /* @section
  5327. * Classes extending `L.Layer` will inherit the following methods:
  5328. *
  5329. * @method addTo(map: Map|LayerGroup): this
  5330. * Adds the layer to the given map or layer group.
  5331. */
  5332. addTo: function (map) {
  5333. map.addLayer(this);
  5334. return this;
  5335. },
  5336. // @method remove: this
  5337. // Removes the layer from the map it is currently active on.
  5338. remove: function () {
  5339. return this.removeFrom(this._map || this._mapToAdd);
  5340. },
  5341. // @method removeFrom(map: Map): this
  5342. // Removes the layer from the given map
  5343. removeFrom: function (obj) {
  5344. if (obj) {
  5345. obj.removeLayer(this);
  5346. }
  5347. return this;
  5348. },
  5349. // @method getPane(name? : String): HTMLElement
  5350. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5351. getPane: function (name) {
  5352. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5353. },
  5354. addInteractiveTarget: function (targetEl) {
  5355. this._map._targets[stamp(targetEl)] = this;
  5356. return this;
  5357. },
  5358. removeInteractiveTarget: function (targetEl) {
  5359. delete this._map._targets[stamp(targetEl)];
  5360. return this;
  5361. },
  5362. // @method getAttribution: String
  5363. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5364. getAttribution: function () {
  5365. return this.options.attribution;
  5366. },
  5367. _layerAdd: function (e) {
  5368. var map = e.target;
  5369. // check in case layer gets added and then removed before the map is ready
  5370. if (!map.hasLayer(this)) { return; }
  5371. this._map = map;
  5372. this._zoomAnimated = map._zoomAnimated;
  5373. if (this.getEvents) {
  5374. var events = this.getEvents();
  5375. map.on(events, this);
  5376. this.once('remove', function () {
  5377. map.off(events, this);
  5378. }, this);
  5379. }
  5380. this.onAdd(map);
  5381. if (this.getAttribution && map.attributionControl) {
  5382. map.attributionControl.addAttribution(this.getAttribution());
  5383. }
  5384. this.fire('add');
  5385. map.fire('layeradd', {layer: this});
  5386. }
  5387. });
  5388. /* @section Extension methods
  5389. * @uninheritable
  5390. *
  5391. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5392. *
  5393. * @method onAdd(map: Map): this
  5394. * 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).
  5395. *
  5396. * @method onRemove(map: Map): this
  5397. * 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).
  5398. *
  5399. * @method getEvents(): Object
  5400. * 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.
  5401. *
  5402. * @method getAttribution(): String
  5403. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5404. *
  5405. * @method beforeAdd(map: Map): this
  5406. * 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.
  5407. */
  5408. /* @namespace Map
  5409. * @section Layer events
  5410. *
  5411. * @event layeradd: LayerEvent
  5412. * Fired when a new layer is added to the map.
  5413. *
  5414. * @event layerremove: LayerEvent
  5415. * Fired when some layer is removed from the map
  5416. *
  5417. * @section Methods for Layers and Controls
  5418. */
  5419. Map.include({
  5420. // @method addLayer(layer: Layer): this
  5421. // Adds the given layer to the map
  5422. addLayer: function (layer) {
  5423. if (!layer._layerAdd) {
  5424. throw new Error('The provided object is not a Layer.');
  5425. }
  5426. var id = stamp(layer);
  5427. if (this._layers[id]) { return this; }
  5428. this._layers[id] = layer;
  5429. layer._mapToAdd = this;
  5430. if (layer.beforeAdd) {
  5431. layer.beforeAdd(this);
  5432. }
  5433. this.whenReady(layer._layerAdd, layer);
  5434. return this;
  5435. },
  5436. // @method removeLayer(layer: Layer): this
  5437. // Removes the given layer from the map.
  5438. removeLayer: function (layer) {
  5439. var id = stamp(layer);
  5440. if (!this._layers[id]) { return this; }
  5441. if (this._loaded) {
  5442. layer.onRemove(this);
  5443. }
  5444. if (layer.getAttribution && this.attributionControl) {
  5445. this.attributionControl.removeAttribution(layer.getAttribution());
  5446. }
  5447. delete this._layers[id];
  5448. if (this._loaded) {
  5449. this.fire('layerremove', {layer: layer});
  5450. layer.fire('remove');
  5451. }
  5452. layer._map = layer._mapToAdd = null;
  5453. return this;
  5454. },
  5455. // @method hasLayer(layer: Layer): Boolean
  5456. // Returns `true` if the given layer is currently added to the map
  5457. hasLayer: function (layer) {
  5458. return !!layer && (stamp(layer) in this._layers);
  5459. },
  5460. /* @method eachLayer(fn: Function, context?: Object): this
  5461. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5462. * ```
  5463. * map.eachLayer(function(layer){
  5464. * layer.bindPopup('Hello');
  5465. * });
  5466. * ```
  5467. */
  5468. eachLayer: function (method, context) {
  5469. for (var i in this._layers) {
  5470. method.call(context, this._layers[i]);
  5471. }
  5472. return this;
  5473. },
  5474. _addLayers: function (layers) {
  5475. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5476. for (var i = 0, len = layers.length; i < len; i++) {
  5477. this.addLayer(layers[i]);
  5478. }
  5479. },
  5480. _addZoomLimit: function (layer) {
  5481. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5482. this._zoomBoundLayers[stamp(layer)] = layer;
  5483. this._updateZoomLevels();
  5484. }
  5485. },
  5486. _removeZoomLimit: function (layer) {
  5487. var id = stamp(layer);
  5488. if (this._zoomBoundLayers[id]) {
  5489. delete this._zoomBoundLayers[id];
  5490. this._updateZoomLevels();
  5491. }
  5492. },
  5493. _updateZoomLevels: function () {
  5494. var minZoom = Infinity,
  5495. maxZoom = -Infinity,
  5496. oldZoomSpan = this._getZoomSpan();
  5497. for (var i in this._zoomBoundLayers) {
  5498. var options = this._zoomBoundLayers[i].options;
  5499. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5500. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5501. }
  5502. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5503. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5504. // @section Map state change events
  5505. // @event zoomlevelschange: Event
  5506. // Fired when the number of zoomlevels on the map is changed due
  5507. // to adding or removing a layer.
  5508. if (oldZoomSpan !== this._getZoomSpan()) {
  5509. this.fire('zoomlevelschange');
  5510. }
  5511. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5512. this.setZoom(this._layersMaxZoom);
  5513. }
  5514. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5515. this.setZoom(this._layersMinZoom);
  5516. }
  5517. }
  5518. });
  5519. /*
  5520. * @class LayerGroup
  5521. * @aka L.LayerGroup
  5522. * @inherits Layer
  5523. *
  5524. * Used to group several layers and handle them as one. If you add it to the map,
  5525. * any layers added or removed from the group will be added/removed on the map as
  5526. * well. Extends `Layer`.
  5527. *
  5528. * @example
  5529. *
  5530. * ```js
  5531. * L.layerGroup([marker1, marker2])
  5532. * .addLayer(polyline)
  5533. * .addTo(map);
  5534. * ```
  5535. */
  5536. var LayerGroup = Layer.extend({
  5537. initialize: function (layers, options) {
  5538. setOptions(this, options);
  5539. this._layers = {};
  5540. var i, len;
  5541. if (layers) {
  5542. for (i = 0, len = layers.length; i < len; i++) {
  5543. this.addLayer(layers[i]);
  5544. }
  5545. }
  5546. },
  5547. // @method addLayer(layer: Layer): this
  5548. // Adds the given layer to the group.
  5549. addLayer: function (layer) {
  5550. var id = this.getLayerId(layer);
  5551. this._layers[id] = layer;
  5552. if (this._map) {
  5553. this._map.addLayer(layer);
  5554. }
  5555. return this;
  5556. },
  5557. // @method removeLayer(layer: Layer): this
  5558. // Removes the given layer from the group.
  5559. // @alternative
  5560. // @method removeLayer(id: Number): this
  5561. // Removes the layer with the given internal ID from the group.
  5562. removeLayer: function (layer) {
  5563. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5564. if (this._map && this._layers[id]) {
  5565. this._map.removeLayer(this._layers[id]);
  5566. }
  5567. delete this._layers[id];
  5568. return this;
  5569. },
  5570. // @method hasLayer(layer: Layer): Boolean
  5571. // Returns `true` if the given layer is currently added to the group.
  5572. // @alternative
  5573. // @method hasLayer(id: Number): Boolean
  5574. // Returns `true` if the given internal ID is currently added to the group.
  5575. hasLayer: function (layer) {
  5576. return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
  5577. },
  5578. // @method clearLayers(): this
  5579. // Removes all the layers from the group.
  5580. clearLayers: function () {
  5581. return this.eachLayer(this.removeLayer, this);
  5582. },
  5583. // @method invoke(methodName: String, …): this
  5584. // Calls `methodName` on every layer contained in this group, passing any
  5585. // additional parameters. Has no effect if the layers contained do not
  5586. // implement `methodName`.
  5587. invoke: function (methodName) {
  5588. var args = Array.prototype.slice.call(arguments, 1),
  5589. i, layer;
  5590. for (i in this._layers) {
  5591. layer = this._layers[i];
  5592. if (layer[methodName]) {
  5593. layer[methodName].apply(layer, args);
  5594. }
  5595. }
  5596. return this;
  5597. },
  5598. onAdd: function (map) {
  5599. this.eachLayer(map.addLayer, map);
  5600. },
  5601. onRemove: function (map) {
  5602. this.eachLayer(map.removeLayer, map);
  5603. },
  5604. // @method eachLayer(fn: Function, context?: Object): this
  5605. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5606. // ```js
  5607. // group.eachLayer(function (layer) {
  5608. // layer.bindPopup('Hello');
  5609. // });
  5610. // ```
  5611. eachLayer: function (method, context) {
  5612. for (var i in this._layers) {
  5613. method.call(context, this._layers[i]);
  5614. }
  5615. return this;
  5616. },
  5617. // @method getLayer(id: Number): Layer
  5618. // Returns the layer with the given internal ID.
  5619. getLayer: function (id) {
  5620. return this._layers[id];
  5621. },
  5622. // @method getLayers(): Layer[]
  5623. // Returns an array of all the layers added to the group.
  5624. getLayers: function () {
  5625. var layers = [];
  5626. this.eachLayer(layers.push, layers);
  5627. return layers;
  5628. },
  5629. // @method setZIndex(zIndex: Number): this
  5630. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5631. setZIndex: function (zIndex) {
  5632. return this.invoke('setZIndex', zIndex);
  5633. },
  5634. // @method getLayerId(layer: Layer): Number
  5635. // Returns the internal ID for a layer
  5636. getLayerId: function (layer) {
  5637. return stamp(layer);
  5638. }
  5639. });
  5640. // @factory L.layerGroup(layers?: Layer[], options?: Object)
  5641. // Create a layer group, optionally given an initial set of layers and an `options` object.
  5642. var layerGroup = function (layers, options) {
  5643. return new LayerGroup(layers, options);
  5644. };
  5645. /*
  5646. * @class FeatureGroup
  5647. * @aka L.FeatureGroup
  5648. * @inherits LayerGroup
  5649. *
  5650. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5651. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5652. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5653. * handler, it will handle events from any of the layers. This includes mouse events
  5654. * and custom events.
  5655. * * Has `layeradd` and `layerremove` events
  5656. *
  5657. * @example
  5658. *
  5659. * ```js
  5660. * L.featureGroup([marker1, marker2, polyline])
  5661. * .bindPopup('Hello world!')
  5662. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5663. * .addTo(map);
  5664. * ```
  5665. */
  5666. var FeatureGroup = LayerGroup.extend({
  5667. addLayer: function (layer) {
  5668. if (this.hasLayer(layer)) {
  5669. return this;
  5670. }
  5671. layer.addEventParent(this);
  5672. LayerGroup.prototype.addLayer.call(this, layer);
  5673. // @event layeradd: LayerEvent
  5674. // Fired when a layer is added to this `FeatureGroup`
  5675. return this.fire('layeradd', {layer: layer});
  5676. },
  5677. removeLayer: function (layer) {
  5678. if (!this.hasLayer(layer)) {
  5679. return this;
  5680. }
  5681. if (layer in this._layers) {
  5682. layer = this._layers[layer];
  5683. }
  5684. layer.removeEventParent(this);
  5685. LayerGroup.prototype.removeLayer.call(this, layer);
  5686. // @event layerremove: LayerEvent
  5687. // Fired when a layer is removed from this `FeatureGroup`
  5688. return this.fire('layerremove', {layer: layer});
  5689. },
  5690. // @method setStyle(style: Path options): this
  5691. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5692. setStyle: function (style) {
  5693. return this.invoke('setStyle', style);
  5694. },
  5695. // @method bringToFront(): this
  5696. // Brings the layer group to the top of all other layers
  5697. bringToFront: function () {
  5698. return this.invoke('bringToFront');
  5699. },
  5700. // @method bringToBack(): this
  5701. // Brings the layer group to the back of all other layers
  5702. bringToBack: function () {
  5703. return this.invoke('bringToBack');
  5704. },
  5705. // @method getBounds(): LatLngBounds
  5706. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5707. getBounds: function () {
  5708. var bounds = new LatLngBounds();
  5709. for (var id in this._layers) {
  5710. var layer = this._layers[id];
  5711. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5712. }
  5713. return bounds;
  5714. }
  5715. });
  5716. // @factory L.featureGroup(layers: Layer[])
  5717. // Create a feature group, optionally given an initial set of layers.
  5718. var featureGroup = function (layers) {
  5719. return new FeatureGroup(layers);
  5720. };
  5721. /*
  5722. * @class Icon
  5723. * @aka L.Icon
  5724. *
  5725. * Represents an icon to provide when creating a marker.
  5726. *
  5727. * @example
  5728. *
  5729. * ```js
  5730. * var myIcon = L.icon({
  5731. * iconUrl: 'my-icon.png',
  5732. * iconRetinaUrl: 'my-icon@2x.png',
  5733. * iconSize: [38, 95],
  5734. * iconAnchor: [22, 94],
  5735. * popupAnchor: [-3, -76],
  5736. * shadowUrl: 'my-icon-shadow.png',
  5737. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5738. * shadowSize: [68, 95],
  5739. * shadowAnchor: [22, 94]
  5740. * });
  5741. *
  5742. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5743. * ```
  5744. *
  5745. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5746. *
  5747. */
  5748. var Icon = Class.extend({
  5749. /* @section
  5750. * @aka Icon options
  5751. *
  5752. * @option iconUrl: String = null
  5753. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5754. *
  5755. * @option iconRetinaUrl: String = null
  5756. * The URL to a retina sized version of the icon image (absolute or relative to your
  5757. * script path). Used for Retina screen devices.
  5758. *
  5759. * @option iconSize: Point = null
  5760. * Size of the icon image in pixels.
  5761. *
  5762. * @option iconAnchor: Point = null
  5763. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5764. * will be aligned so that this point is at the marker's geographical location. Centered
  5765. * by default if size is specified, also can be set in CSS with negative margins.
  5766. *
  5767. * @option popupAnchor: Point = [0, 0]
  5768. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5769. *
  5770. * @option tooltipAnchor: Point = [0, 0]
  5771. * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
  5772. *
  5773. * @option shadowUrl: String = null
  5774. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  5775. *
  5776. * @option shadowRetinaUrl: String = null
  5777. *
  5778. * @option shadowSize: Point = null
  5779. * Size of the shadow image in pixels.
  5780. *
  5781. * @option shadowAnchor: Point = null
  5782. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  5783. * as iconAnchor if not specified).
  5784. *
  5785. * @option className: String = ''
  5786. * A custom class name to assign to both icon and shadow images. Empty by default.
  5787. */
  5788. options: {
  5789. popupAnchor: [0, 0],
  5790. tooltipAnchor: [0, 0]
  5791. },
  5792. initialize: function (options) {
  5793. setOptions(this, options);
  5794. },
  5795. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  5796. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  5797. // styled according to the options.
  5798. createIcon: function (oldIcon) {
  5799. return this._createIcon('icon', oldIcon);
  5800. },
  5801. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  5802. // As `createIcon`, but for the shadow beneath it.
  5803. createShadow: function (oldIcon) {
  5804. return this._createIcon('shadow', oldIcon);
  5805. },
  5806. _createIcon: function (name, oldIcon) {
  5807. var src = this._getIconUrl(name);
  5808. if (!src) {
  5809. if (name === 'icon') {
  5810. throw new Error('iconUrl not set in Icon options (see the docs).');
  5811. }
  5812. return null;
  5813. }
  5814. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  5815. this._setIconStyles(img, name);
  5816. return img;
  5817. },
  5818. _setIconStyles: function (img, name) {
  5819. var options = this.options;
  5820. var sizeOption = options[name + 'Size'];
  5821. if (typeof sizeOption === 'number') {
  5822. sizeOption = [sizeOption, sizeOption];
  5823. }
  5824. var size = toPoint(sizeOption),
  5825. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  5826. size && size.divideBy(2, true));
  5827. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  5828. if (anchor) {
  5829. img.style.marginLeft = (-anchor.x) + 'px';
  5830. img.style.marginTop = (-anchor.y) + 'px';
  5831. }
  5832. if (size) {
  5833. img.style.width = size.x + 'px';
  5834. img.style.height = size.y + 'px';
  5835. }
  5836. },
  5837. _createImg: function (src, el) {
  5838. el = el || document.createElement('img');
  5839. el.src = src;
  5840. return el;
  5841. },
  5842. _getIconUrl: function (name) {
  5843. return retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  5844. }
  5845. });
  5846. // @factory L.icon(options: Icon options)
  5847. // Creates an icon instance with the given options.
  5848. function icon(options) {
  5849. return new Icon(options);
  5850. }
  5851. /*
  5852. * @miniclass Icon.Default (Icon)
  5853. * @aka L.Icon.Default
  5854. * @section
  5855. *
  5856. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  5857. * no icon is specified. Points to the blue marker image distributed with Leaflet
  5858. * releases.
  5859. *
  5860. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  5861. * (which is a set of `Icon options`).
  5862. *
  5863. * If you want to _completely_ replace the default icon, override the
  5864. * `L.Marker.prototype.options.icon` with your own icon instead.
  5865. */
  5866. var IconDefault = Icon.extend({
  5867. options: {
  5868. iconUrl: 'marker-icon.png',
  5869. iconRetinaUrl: 'marker-icon-2x.png',
  5870. shadowUrl: 'marker-shadow.png',
  5871. iconSize: [25, 41],
  5872. iconAnchor: [12, 41],
  5873. popupAnchor: [1, -34],
  5874. tooltipAnchor: [16, -28],
  5875. shadowSize: [41, 41]
  5876. },
  5877. _getIconUrl: function (name) {
  5878. if (!IconDefault.imagePath) { // Deprecated, backwards-compatibility only
  5879. IconDefault.imagePath = this._detectIconPath();
  5880. }
  5881. // @option imagePath: String
  5882. // `Icon.Default` will try to auto-detect the location of the
  5883. // blue icon images. If you are placing these images in a non-standard
  5884. // way, set this option to point to the right path.
  5885. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  5886. },
  5887. _detectIconPath: function () {
  5888. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  5889. var path = getStyle(el, 'background-image') ||
  5890. getStyle(el, 'backgroundImage'); // IE8
  5891. document.body.removeChild(el);
  5892. if (path === null || path.indexOf('url') !== 0) {
  5893. path = '';
  5894. } else {
  5895. path = path.replace(/^url\(["']?/, '').replace(/marker-icon\.png["']?\)$/, '');
  5896. }
  5897. return path;
  5898. }
  5899. });
  5900. /*
  5901. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  5902. */
  5903. /* @namespace Marker
  5904. * @section Interaction handlers
  5905. *
  5906. * 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:
  5907. *
  5908. * ```js
  5909. * marker.dragging.disable();
  5910. * ```
  5911. *
  5912. * @property dragging: Handler
  5913. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  5914. */
  5915. var MarkerDrag = Handler.extend({
  5916. initialize: function (marker) {
  5917. this._marker = marker;
  5918. },
  5919. addHooks: function () {
  5920. var icon = this._marker._icon;
  5921. if (!this._draggable) {
  5922. this._draggable = new Draggable(icon, icon, true);
  5923. }
  5924. this._draggable.on({
  5925. dragstart: this._onDragStart,
  5926. predrag: this._onPreDrag,
  5927. drag: this._onDrag,
  5928. dragend: this._onDragEnd
  5929. }, this).enable();
  5930. addClass(icon, 'leaflet-marker-draggable');
  5931. },
  5932. removeHooks: function () {
  5933. this._draggable.off({
  5934. dragstart: this._onDragStart,
  5935. predrag: this._onPreDrag,
  5936. drag: this._onDrag,
  5937. dragend: this._onDragEnd
  5938. }, this).disable();
  5939. if (this._marker._icon) {
  5940. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  5941. }
  5942. },
  5943. moved: function () {
  5944. return this._draggable && this._draggable._moved;
  5945. },
  5946. _adjustPan: function (e) {
  5947. var marker = this._marker,
  5948. map = marker._map,
  5949. speed = this._marker.options.autoPanSpeed,
  5950. padding = this._marker.options.autoPanPadding,
  5951. iconPos = getPosition(marker._icon),
  5952. bounds = map.getPixelBounds(),
  5953. origin = map.getPixelOrigin();
  5954. var panBounds = toBounds(
  5955. bounds.min._subtract(origin).add(padding),
  5956. bounds.max._subtract(origin).subtract(padding)
  5957. );
  5958. if (!panBounds.contains(iconPos)) {
  5959. // Compute incremental movement
  5960. var movement = toPoint(
  5961. (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
  5962. (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
  5963. (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
  5964. (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
  5965. ).multiplyBy(speed);
  5966. map.panBy(movement, {animate: false});
  5967. this._draggable._newPos._add(movement);
  5968. this._draggable._startPos._add(movement);
  5969. setPosition(marker._icon, this._draggable._newPos);
  5970. this._onDrag(e);
  5971. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  5972. }
  5973. },
  5974. _onDragStart: function () {
  5975. // @section Dragging events
  5976. // @event dragstart: Event
  5977. // Fired when the user starts dragging the marker.
  5978. // @event movestart: Event
  5979. // Fired when the marker starts moving (because of dragging).
  5980. this._oldLatLng = this._marker.getLatLng();
  5981. this._marker
  5982. .closePopup()
  5983. .fire('movestart')
  5984. .fire('dragstart');
  5985. },
  5986. _onPreDrag: function (e) {
  5987. if (this._marker.options.autoPan) {
  5988. cancelAnimFrame(this._panRequest);
  5989. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  5990. }
  5991. },
  5992. _onDrag: function (e) {
  5993. var marker = this._marker,
  5994. shadow = marker._shadow,
  5995. iconPos = getPosition(marker._icon),
  5996. latlng = marker._map.layerPointToLatLng(iconPos);
  5997. // update shadow position
  5998. if (shadow) {
  5999. setPosition(shadow, iconPos);
  6000. }
  6001. marker._latlng = latlng;
  6002. e.latlng = latlng;
  6003. e.oldLatLng = this._oldLatLng;
  6004. // @event drag: Event
  6005. // Fired repeatedly while the user drags the marker.
  6006. marker
  6007. .fire('move', e)
  6008. .fire('drag', e);
  6009. },
  6010. _onDragEnd: function (e) {
  6011. // @event dragend: DragEndEvent
  6012. // Fired when the user stops dragging the marker.
  6013. cancelAnimFrame(this._panRequest);
  6014. // @event moveend: Event
  6015. // Fired when the marker stops moving (because of dragging).
  6016. delete this._oldLatLng;
  6017. this._marker
  6018. .fire('moveend')
  6019. .fire('dragend', e);
  6020. }
  6021. });
  6022. /*
  6023. * @class Marker
  6024. * @inherits Interactive layer
  6025. * @aka L.Marker
  6026. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  6027. *
  6028. * @example
  6029. *
  6030. * ```js
  6031. * L.marker([50.5, 30.5]).addTo(map);
  6032. * ```
  6033. */
  6034. var Marker = Layer.extend({
  6035. // @section
  6036. // @aka Marker options
  6037. options: {
  6038. // @option icon: Icon = *
  6039. // Icon instance to use for rendering the marker.
  6040. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  6041. // If not specified, a common instance of `L.Icon.Default` is used.
  6042. icon: new IconDefault(),
  6043. // Option inherited from "Interactive layer" abstract class
  6044. interactive: true,
  6045. // @option keyboard: Boolean = true
  6046. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  6047. keyboard: true,
  6048. // @option title: String = ''
  6049. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  6050. title: '',
  6051. // @option alt: String = ''
  6052. // Text for the `alt` attribute of the icon image (useful for accessibility).
  6053. alt: '',
  6054. // @option zIndexOffset: Number = 0
  6055. // 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).
  6056. zIndexOffset: 0,
  6057. // @option opacity: Number = 1.0
  6058. // The opacity of the marker.
  6059. opacity: 1,
  6060. // @option riseOnHover: Boolean = false
  6061. // If `true`, the marker will get on top of others when you hover the mouse over it.
  6062. riseOnHover: false,
  6063. // @option riseOffset: Number = 250
  6064. // The z-index offset used for the `riseOnHover` feature.
  6065. riseOffset: 250,
  6066. // @option pane: String = 'markerPane'
  6067. // `Map pane` where the markers icon will be added.
  6068. pane: 'markerPane',
  6069. // @option pane: String = 'shadowPane'
  6070. // `Map pane` where the markers shadow will be added.
  6071. shadowPane: 'shadowPane',
  6072. // @option bubblingMouseEvents: Boolean = false
  6073. // When `true`, a mouse event on this marker will trigger the same event on the map
  6074. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6075. bubblingMouseEvents: false,
  6076. // @section Draggable marker options
  6077. // @option draggable: Boolean = false
  6078. // Whether the marker is draggable with mouse/touch or not.
  6079. draggable: false,
  6080. // @option autoPan: Boolean = false
  6081. // Whether to pan the map when dragging this marker near its edge or not.
  6082. autoPan: false,
  6083. // @option autoPanPadding: Point = Point(50, 50)
  6084. // Distance (in pixels to the left/right and to the top/bottom) of the
  6085. // map edge to start panning the map.
  6086. autoPanPadding: [50, 50],
  6087. // @option autoPanSpeed: Number = 10
  6088. // Number of pixels the map should pan by.
  6089. autoPanSpeed: 10
  6090. },
  6091. /* @section
  6092. *
  6093. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  6094. */
  6095. initialize: function (latlng, options) {
  6096. setOptions(this, options);
  6097. this._latlng = toLatLng(latlng);
  6098. },
  6099. onAdd: function (map) {
  6100. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  6101. if (this._zoomAnimated) {
  6102. map.on('zoomanim', this._animateZoom, this);
  6103. }
  6104. this._initIcon();
  6105. this.update();
  6106. },
  6107. onRemove: function (map) {
  6108. if (this.dragging && this.dragging.enabled()) {
  6109. this.options.draggable = true;
  6110. this.dragging.removeHooks();
  6111. }
  6112. delete this.dragging;
  6113. if (this._zoomAnimated) {
  6114. map.off('zoomanim', this._animateZoom, this);
  6115. }
  6116. this._removeIcon();
  6117. this._removeShadow();
  6118. },
  6119. getEvents: function () {
  6120. return {
  6121. zoom: this.update,
  6122. viewreset: this.update
  6123. };
  6124. },
  6125. // @method getLatLng: LatLng
  6126. // Returns the current geographical position of the marker.
  6127. getLatLng: function () {
  6128. return this._latlng;
  6129. },
  6130. // @method setLatLng(latlng: LatLng): this
  6131. // Changes the marker position to the given point.
  6132. setLatLng: function (latlng) {
  6133. var oldLatLng = this._latlng;
  6134. this._latlng = toLatLng(latlng);
  6135. this.update();
  6136. // @event move: Event
  6137. // 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`.
  6138. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6139. },
  6140. // @method setZIndexOffset(offset: Number): this
  6141. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6142. setZIndexOffset: function (offset) {
  6143. this.options.zIndexOffset = offset;
  6144. return this.update();
  6145. },
  6146. // @method getIcon: Icon
  6147. // Returns the current icon used by the marker
  6148. getIcon: function () {
  6149. return this.options.icon;
  6150. },
  6151. // @method setIcon(icon: Icon): this
  6152. // Changes the marker icon.
  6153. setIcon: function (icon) {
  6154. this.options.icon = icon;
  6155. if (this._map) {
  6156. this._initIcon();
  6157. this.update();
  6158. }
  6159. if (this._popup) {
  6160. this.bindPopup(this._popup, this._popup.options);
  6161. }
  6162. return this;
  6163. },
  6164. getElement: function () {
  6165. return this._icon;
  6166. },
  6167. update: function () {
  6168. if (this._icon && this._map) {
  6169. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6170. this._setPos(pos);
  6171. }
  6172. return this;
  6173. },
  6174. _initIcon: function () {
  6175. var options = this.options,
  6176. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6177. var icon = options.icon.createIcon(this._icon),
  6178. addIcon = false;
  6179. // if we're not reusing the icon, remove the old one and init new one
  6180. if (icon !== this._icon) {
  6181. if (this._icon) {
  6182. this._removeIcon();
  6183. }
  6184. addIcon = true;
  6185. if (options.title) {
  6186. icon.title = options.title;
  6187. }
  6188. if (icon.tagName === 'IMG') {
  6189. icon.alt = options.alt || '';
  6190. }
  6191. }
  6192. addClass(icon, classToAdd);
  6193. if (options.keyboard) {
  6194. icon.tabIndex = '0';
  6195. }
  6196. this._icon = icon;
  6197. if (options.riseOnHover) {
  6198. this.on({
  6199. mouseover: this._bringToFront,
  6200. mouseout: this._resetZIndex
  6201. });
  6202. }
  6203. var newShadow = options.icon.createShadow(this._shadow),
  6204. addShadow = false;
  6205. if (newShadow !== this._shadow) {
  6206. this._removeShadow();
  6207. addShadow = true;
  6208. }
  6209. if (newShadow) {
  6210. addClass(newShadow, classToAdd);
  6211. newShadow.alt = '';
  6212. }
  6213. this._shadow = newShadow;
  6214. if (options.opacity < 1) {
  6215. this._updateOpacity();
  6216. }
  6217. if (addIcon) {
  6218. this.getPane().appendChild(this._icon);
  6219. }
  6220. this._initInteraction();
  6221. if (newShadow && addShadow) {
  6222. this.getPane(options.shadowPane).appendChild(this._shadow);
  6223. }
  6224. },
  6225. _removeIcon: function () {
  6226. if (this.options.riseOnHover) {
  6227. this.off({
  6228. mouseover: this._bringToFront,
  6229. mouseout: this._resetZIndex
  6230. });
  6231. }
  6232. remove(this._icon);
  6233. this.removeInteractiveTarget(this._icon);
  6234. this._icon = null;
  6235. },
  6236. _removeShadow: function () {
  6237. if (this._shadow) {
  6238. remove(this._shadow);
  6239. }
  6240. this._shadow = null;
  6241. },
  6242. _setPos: function (pos) {
  6243. setPosition(this._icon, pos);
  6244. if (this._shadow) {
  6245. setPosition(this._shadow, pos);
  6246. }
  6247. this._zIndex = pos.y + this.options.zIndexOffset;
  6248. this._resetZIndex();
  6249. },
  6250. _updateZIndex: function (offset) {
  6251. this._icon.style.zIndex = this._zIndex + offset;
  6252. },
  6253. _animateZoom: function (opt) {
  6254. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6255. this._setPos(pos);
  6256. },
  6257. _initInteraction: function () {
  6258. if (!this.options.interactive) { return; }
  6259. addClass(this._icon, 'leaflet-interactive');
  6260. this.addInteractiveTarget(this._icon);
  6261. if (MarkerDrag) {
  6262. var draggable = this.options.draggable;
  6263. if (this.dragging) {
  6264. draggable = this.dragging.enabled();
  6265. this.dragging.disable();
  6266. }
  6267. this.dragging = new MarkerDrag(this);
  6268. if (draggable) {
  6269. this.dragging.enable();
  6270. }
  6271. }
  6272. },
  6273. // @method setOpacity(opacity: Number): this
  6274. // Changes the opacity of the marker.
  6275. setOpacity: function (opacity) {
  6276. this.options.opacity = opacity;
  6277. if (this._map) {
  6278. this._updateOpacity();
  6279. }
  6280. return this;
  6281. },
  6282. _updateOpacity: function () {
  6283. var opacity = this.options.opacity;
  6284. if (this._icon) {
  6285. setOpacity(this._icon, opacity);
  6286. }
  6287. if (this._shadow) {
  6288. setOpacity(this._shadow, opacity);
  6289. }
  6290. },
  6291. _bringToFront: function () {
  6292. this._updateZIndex(this.options.riseOffset);
  6293. },
  6294. _resetZIndex: function () {
  6295. this._updateZIndex(0);
  6296. },
  6297. _getPopupAnchor: function () {
  6298. return this.options.icon.options.popupAnchor;
  6299. },
  6300. _getTooltipAnchor: function () {
  6301. return this.options.icon.options.tooltipAnchor;
  6302. }
  6303. });
  6304. // factory L.marker(latlng: LatLng, options? : Marker options)
  6305. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6306. // Instantiates a Marker object given a geographical point and optionally an options object.
  6307. function marker(latlng, options) {
  6308. return new Marker(latlng, options);
  6309. }
  6310. /*
  6311. * @class Path
  6312. * @aka L.Path
  6313. * @inherits Interactive layer
  6314. *
  6315. * An abstract class that contains options and constants shared between vector
  6316. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6317. */
  6318. var Path = Layer.extend({
  6319. // @section
  6320. // @aka Path options
  6321. options: {
  6322. // @option stroke: Boolean = true
  6323. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6324. stroke: true,
  6325. // @option color: String = '#3388ff'
  6326. // Stroke color
  6327. color: '#3388ff',
  6328. // @option weight: Number = 3
  6329. // Stroke width in pixels
  6330. weight: 3,
  6331. // @option opacity: Number = 1.0
  6332. // Stroke opacity
  6333. opacity: 1,
  6334. // @option lineCap: String= 'round'
  6335. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6336. lineCap: 'round',
  6337. // @option lineJoin: String = 'round'
  6338. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6339. lineJoin: 'round',
  6340. // @option dashArray: String = null
  6341. // 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).
  6342. dashArray: null,
  6343. // @option dashOffset: String = null
  6344. // 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).
  6345. dashOffset: null,
  6346. // @option fill: Boolean = depends
  6347. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6348. fill: false,
  6349. // @option fillColor: String = *
  6350. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6351. fillColor: null,
  6352. // @option fillOpacity: Number = 0.2
  6353. // Fill opacity.
  6354. fillOpacity: 0.2,
  6355. // @option fillRule: String = 'evenodd'
  6356. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6357. fillRule: 'evenodd',
  6358. // className: '',
  6359. // Option inherited from "Interactive layer" abstract class
  6360. interactive: true,
  6361. // @option bubblingMouseEvents: Boolean = true
  6362. // When `true`, a mouse event on this path will trigger the same event on the map
  6363. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6364. bubblingMouseEvents: true
  6365. },
  6366. beforeAdd: function (map) {
  6367. // Renderer is set here because we need to call renderer.getEvents
  6368. // before this.getEvents.
  6369. this._renderer = map.getRenderer(this);
  6370. },
  6371. onAdd: function () {
  6372. this._renderer._initPath(this);
  6373. this._reset();
  6374. this._renderer._addPath(this);
  6375. },
  6376. onRemove: function () {
  6377. this._renderer._removePath(this);
  6378. },
  6379. // @method redraw(): this
  6380. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6381. redraw: function () {
  6382. if (this._map) {
  6383. this._renderer._updatePath(this);
  6384. }
  6385. return this;
  6386. },
  6387. // @method setStyle(style: Path options): this
  6388. // Changes the appearance of a Path based on the options in the `Path options` object.
  6389. setStyle: function (style) {
  6390. setOptions(this, style);
  6391. if (this._renderer) {
  6392. this._renderer._updateStyle(this);
  6393. if (this.options.stroke && style.hasOwnProperty('weight')) {
  6394. this._updateBounds();
  6395. }
  6396. }
  6397. return this;
  6398. },
  6399. // @method bringToFront(): this
  6400. // Brings the layer to the top of all path layers.
  6401. bringToFront: function () {
  6402. if (this._renderer) {
  6403. this._renderer._bringToFront(this);
  6404. }
  6405. return this;
  6406. },
  6407. // @method bringToBack(): this
  6408. // Brings the layer to the bottom of all path layers.
  6409. bringToBack: function () {
  6410. if (this._renderer) {
  6411. this._renderer._bringToBack(this);
  6412. }
  6413. return this;
  6414. },
  6415. getElement: function () {
  6416. return this._path;
  6417. },
  6418. _reset: function () {
  6419. // defined in child classes
  6420. this._project();
  6421. this._update();
  6422. },
  6423. _clickTolerance: function () {
  6424. // used when doing hit detection for Canvas layers
  6425. return (this.options.stroke ? this.options.weight / 2 : 0) + this._renderer.options.tolerance;
  6426. }
  6427. });
  6428. /*
  6429. * @class CircleMarker
  6430. * @aka L.CircleMarker
  6431. * @inherits Path
  6432. *
  6433. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6434. */
  6435. var CircleMarker = Path.extend({
  6436. // @section
  6437. // @aka CircleMarker options
  6438. options: {
  6439. fill: true,
  6440. // @option radius: Number = 10
  6441. // Radius of the circle marker, in pixels
  6442. radius: 10
  6443. },
  6444. initialize: function (latlng, options) {
  6445. setOptions(this, options);
  6446. this._latlng = toLatLng(latlng);
  6447. this._radius = this.options.radius;
  6448. },
  6449. // @method setLatLng(latLng: LatLng): this
  6450. // Sets the position of a circle marker to a new location.
  6451. setLatLng: function (latlng) {
  6452. this._latlng = toLatLng(latlng);
  6453. this.redraw();
  6454. return this.fire('move', {latlng: this._latlng});
  6455. },
  6456. // @method getLatLng(): LatLng
  6457. // Returns the current geographical position of the circle marker
  6458. getLatLng: function () {
  6459. return this._latlng;
  6460. },
  6461. // @method setRadius(radius: Number): this
  6462. // Sets the radius of a circle marker. Units are in pixels.
  6463. setRadius: function (radius) {
  6464. this.options.radius = this._radius = radius;
  6465. return this.redraw();
  6466. },
  6467. // @method getRadius(): Number
  6468. // Returns the current radius of the circle
  6469. getRadius: function () {
  6470. return this._radius;
  6471. },
  6472. setStyle : function (options) {
  6473. var radius = options && options.radius || this._radius;
  6474. Path.prototype.setStyle.call(this, options);
  6475. this.setRadius(radius);
  6476. return this;
  6477. },
  6478. _project: function () {
  6479. this._point = this._map.latLngToLayerPoint(this._latlng);
  6480. this._updateBounds();
  6481. },
  6482. _updateBounds: function () {
  6483. var r = this._radius,
  6484. r2 = this._radiusY || r,
  6485. w = this._clickTolerance(),
  6486. p = [r + w, r2 + w];
  6487. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6488. },
  6489. _update: function () {
  6490. if (this._map) {
  6491. this._updatePath();
  6492. }
  6493. },
  6494. _updatePath: function () {
  6495. this._renderer._updateCircle(this);
  6496. },
  6497. _empty: function () {
  6498. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6499. },
  6500. // Needed by the `Canvas` renderer for interactivity
  6501. _containsPoint: function (p) {
  6502. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6503. }
  6504. });
  6505. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6506. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6507. function circleMarker(latlng, options) {
  6508. return new CircleMarker(latlng, options);
  6509. }
  6510. /*
  6511. * @class Circle
  6512. * @aka L.Circle
  6513. * @inherits CircleMarker
  6514. *
  6515. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6516. *
  6517. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6518. *
  6519. * @example
  6520. *
  6521. * ```js
  6522. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6523. * ```
  6524. */
  6525. var Circle = CircleMarker.extend({
  6526. initialize: function (latlng, options, legacyOptions) {
  6527. if (typeof options === 'number') {
  6528. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6529. options = extend({}, legacyOptions, {radius: options});
  6530. }
  6531. setOptions(this, options);
  6532. this._latlng = toLatLng(latlng);
  6533. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6534. // @section
  6535. // @aka Circle options
  6536. // @option radius: Number; Radius of the circle, in meters.
  6537. this._mRadius = this.options.radius;
  6538. },
  6539. // @method setRadius(radius: Number): this
  6540. // Sets the radius of a circle. Units are in meters.
  6541. setRadius: function (radius) {
  6542. this._mRadius = radius;
  6543. return this.redraw();
  6544. },
  6545. // @method getRadius(): Number
  6546. // Returns the current radius of a circle. Units are in meters.
  6547. getRadius: function () {
  6548. return this._mRadius;
  6549. },
  6550. // @method getBounds(): LatLngBounds
  6551. // Returns the `LatLngBounds` of the path.
  6552. getBounds: function () {
  6553. var half = [this._radius, this._radiusY || this._radius];
  6554. return new LatLngBounds(
  6555. this._map.layerPointToLatLng(this._point.subtract(half)),
  6556. this._map.layerPointToLatLng(this._point.add(half)));
  6557. },
  6558. setStyle: Path.prototype.setStyle,
  6559. _project: function () {
  6560. var lng = this._latlng.lng,
  6561. lat = this._latlng.lat,
  6562. map = this._map,
  6563. crs = map.options.crs;
  6564. if (crs.distance === Earth.distance) {
  6565. var d = Math.PI / 180,
  6566. latR = (this._mRadius / Earth.R) / d,
  6567. top = map.project([lat + latR, lng]),
  6568. bottom = map.project([lat - latR, lng]),
  6569. p = top.add(bottom).divideBy(2),
  6570. lat2 = map.unproject(p).lat,
  6571. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6572. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6573. if (isNaN(lngR) || lngR === 0) {
  6574. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6575. }
  6576. this._point = p.subtract(map.getPixelOrigin());
  6577. this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
  6578. this._radiusY = p.y - top.y;
  6579. } else {
  6580. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6581. this._point = map.latLngToLayerPoint(this._latlng);
  6582. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6583. }
  6584. this._updateBounds();
  6585. }
  6586. });
  6587. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6588. // Instantiates a circle object given a geographical point, and an options object
  6589. // which contains the circle radius.
  6590. // @alternative
  6591. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6592. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6593. // Do not use in new applications or plugins.
  6594. function circle(latlng, options, legacyOptions) {
  6595. return new Circle(latlng, options, legacyOptions);
  6596. }
  6597. /*
  6598. * @class Polyline
  6599. * @aka L.Polyline
  6600. * @inherits Path
  6601. *
  6602. * A class for drawing polyline overlays on a map. Extends `Path`.
  6603. *
  6604. * @example
  6605. *
  6606. * ```js
  6607. * // create a red polyline from an array of LatLng points
  6608. * var latlngs = [
  6609. * [45.51, -122.68],
  6610. * [37.77, -122.43],
  6611. * [34.04, -118.2]
  6612. * ];
  6613. *
  6614. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6615. *
  6616. * // zoom the map to the polyline
  6617. * map.fitBounds(polyline.getBounds());
  6618. * ```
  6619. *
  6620. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6621. *
  6622. * ```js
  6623. * // create a red polyline from an array of arrays of LatLng points
  6624. * var latlngs = [
  6625. * [[45.51, -122.68],
  6626. * [37.77, -122.43],
  6627. * [34.04, -118.2]],
  6628. * [[40.78, -73.91],
  6629. * [41.83, -87.62],
  6630. * [32.76, -96.72]]
  6631. * ];
  6632. * ```
  6633. */
  6634. var Polyline = Path.extend({
  6635. // @section
  6636. // @aka Polyline options
  6637. options: {
  6638. // @option smoothFactor: Number = 1.0
  6639. // How much to simplify the polyline on each zoom level. More means
  6640. // better performance and smoother look, and less means more accurate representation.
  6641. smoothFactor: 1.0,
  6642. // @option noClip: Boolean = false
  6643. // Disable polyline clipping.
  6644. noClip: false
  6645. },
  6646. initialize: function (latlngs, options) {
  6647. setOptions(this, options);
  6648. this._setLatLngs(latlngs);
  6649. },
  6650. // @method getLatLngs(): LatLng[]
  6651. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6652. getLatLngs: function () {
  6653. return this._latlngs;
  6654. },
  6655. // @method setLatLngs(latlngs: LatLng[]): this
  6656. // Replaces all the points in the polyline with the given array of geographical points.
  6657. setLatLngs: function (latlngs) {
  6658. this._setLatLngs(latlngs);
  6659. return this.redraw();
  6660. },
  6661. // @method isEmpty(): Boolean
  6662. // Returns `true` if the Polyline has no LatLngs.
  6663. isEmpty: function () {
  6664. return !this._latlngs.length;
  6665. },
  6666. // @method closestLayerPoint(p: Point): Point
  6667. // Returns the point closest to `p` on the Polyline.
  6668. closestLayerPoint: function (p) {
  6669. var minDistance = Infinity,
  6670. minPoint = null,
  6671. closest = _sqClosestPointOnSegment,
  6672. p1, p2;
  6673. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6674. var points = this._parts[j];
  6675. for (var i = 1, len = points.length; i < len; i++) {
  6676. p1 = points[i - 1];
  6677. p2 = points[i];
  6678. var sqDist = closest(p, p1, p2, true);
  6679. if (sqDist < minDistance) {
  6680. minDistance = sqDist;
  6681. minPoint = closest(p, p1, p2);
  6682. }
  6683. }
  6684. }
  6685. if (minPoint) {
  6686. minPoint.distance = Math.sqrt(minDistance);
  6687. }
  6688. return minPoint;
  6689. },
  6690. // @method getCenter(): LatLng
  6691. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6692. getCenter: function () {
  6693. // throws error when not yet added to map as this center calculation requires projected coordinates
  6694. if (!this._map) {
  6695. throw new Error('Must add layer to map before using getCenter()');
  6696. }
  6697. var i, halfDist, segDist, dist, p1, p2, ratio,
  6698. points = this._rings[0],
  6699. len = points.length;
  6700. if (!len) { return null; }
  6701. // polyline centroid algorithm; only uses the first ring if there are multiple
  6702. for (i = 0, halfDist = 0; i < len - 1; i++) {
  6703. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  6704. }
  6705. // The line is so small in the current view that all points are on the same pixel.
  6706. if (halfDist === 0) {
  6707. return this._map.layerPointToLatLng(points[0]);
  6708. }
  6709. for (i = 0, dist = 0; i < len - 1; i++) {
  6710. p1 = points[i];
  6711. p2 = points[i + 1];
  6712. segDist = p1.distanceTo(p2);
  6713. dist += segDist;
  6714. if (dist > halfDist) {
  6715. ratio = (dist - halfDist) / segDist;
  6716. return this._map.layerPointToLatLng([
  6717. p2.x - ratio * (p2.x - p1.x),
  6718. p2.y - ratio * (p2.y - p1.y)
  6719. ]);
  6720. }
  6721. }
  6722. },
  6723. // @method getBounds(): LatLngBounds
  6724. // Returns the `LatLngBounds` of the path.
  6725. getBounds: function () {
  6726. return this._bounds;
  6727. },
  6728. // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
  6729. // Adds a given point to the polyline. By default, adds to the first ring of
  6730. // the polyline in case of a multi-polyline, but can be overridden by passing
  6731. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6732. addLatLng: function (latlng, latlngs) {
  6733. latlngs = latlngs || this._defaultShape();
  6734. latlng = toLatLng(latlng);
  6735. latlngs.push(latlng);
  6736. this._bounds.extend(latlng);
  6737. return this.redraw();
  6738. },
  6739. _setLatLngs: function (latlngs) {
  6740. this._bounds = new LatLngBounds();
  6741. this._latlngs = this._convertLatLngs(latlngs);
  6742. },
  6743. _defaultShape: function () {
  6744. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6745. },
  6746. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6747. _convertLatLngs: function (latlngs) {
  6748. var result = [],
  6749. flat = isFlat(latlngs);
  6750. for (var i = 0, len = latlngs.length; i < len; i++) {
  6751. if (flat) {
  6752. result[i] = toLatLng(latlngs[i]);
  6753. this._bounds.extend(result[i]);
  6754. } else {
  6755. result[i] = this._convertLatLngs(latlngs[i]);
  6756. }
  6757. }
  6758. return result;
  6759. },
  6760. _project: function () {
  6761. var pxBounds = new Bounds();
  6762. this._rings = [];
  6763. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  6764. if (this._bounds.isValid() && pxBounds.isValid()) {
  6765. this._rawPxBounds = pxBounds;
  6766. this._updateBounds();
  6767. }
  6768. },
  6769. _updateBounds: function () {
  6770. var w = this._clickTolerance(),
  6771. p = new Point(w, w);
  6772. this._pxBounds = new Bounds([
  6773. this._rawPxBounds.min.subtract(p),
  6774. this._rawPxBounds.max.add(p)
  6775. ]);
  6776. },
  6777. // recursively turns latlngs into a set of rings with projected coordinates
  6778. _projectLatlngs: function (latlngs, result, projectedBounds) {
  6779. var flat = latlngs[0] instanceof LatLng,
  6780. len = latlngs.length,
  6781. i, ring;
  6782. if (flat) {
  6783. ring = [];
  6784. for (i = 0; i < len; i++) {
  6785. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  6786. projectedBounds.extend(ring[i]);
  6787. }
  6788. result.push(ring);
  6789. } else {
  6790. for (i = 0; i < len; i++) {
  6791. this._projectLatlngs(latlngs[i], result, projectedBounds);
  6792. }
  6793. }
  6794. },
  6795. // clip polyline by renderer bounds so that we have less to render for performance
  6796. _clipPoints: function () {
  6797. var bounds = this._renderer._bounds;
  6798. this._parts = [];
  6799. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6800. return;
  6801. }
  6802. if (this.options.noClip) {
  6803. this._parts = this._rings;
  6804. return;
  6805. }
  6806. var parts = this._parts,
  6807. i, j, k, len, len2, segment, points;
  6808. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  6809. points = this._rings[i];
  6810. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  6811. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  6812. if (!segment) { continue; }
  6813. parts[k] = parts[k] || [];
  6814. parts[k].push(segment[0]);
  6815. // if segment goes out of screen, or it's the last one, it's the end of the line part
  6816. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  6817. parts[k].push(segment[1]);
  6818. k++;
  6819. }
  6820. }
  6821. }
  6822. },
  6823. // simplify each clipped part of the polyline for performance
  6824. _simplifyPoints: function () {
  6825. var parts = this._parts,
  6826. tolerance = this.options.smoothFactor;
  6827. for (var i = 0, len = parts.length; i < len; i++) {
  6828. parts[i] = simplify(parts[i], tolerance);
  6829. }
  6830. },
  6831. _update: function () {
  6832. if (!this._map) { return; }
  6833. this._clipPoints();
  6834. this._simplifyPoints();
  6835. this._updatePath();
  6836. },
  6837. _updatePath: function () {
  6838. this._renderer._updatePoly(this);
  6839. },
  6840. // Needed by the `Canvas` renderer for interactivity
  6841. _containsPoint: function (p, closed) {
  6842. var i, j, k, len, len2, part,
  6843. w = this._clickTolerance();
  6844. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  6845. // hit detection for polylines
  6846. for (i = 0, len = this._parts.length; i < len; i++) {
  6847. part = this._parts[i];
  6848. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6849. if (!closed && (j === 0)) { continue; }
  6850. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  6851. return true;
  6852. }
  6853. }
  6854. }
  6855. return false;
  6856. }
  6857. });
  6858. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  6859. // Instantiates a polyline object given an array of geographical points and
  6860. // optionally an options object. You can create a `Polyline` object with
  6861. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  6862. // of geographic points.
  6863. function polyline(latlngs, options) {
  6864. return new Polyline(latlngs, options);
  6865. }
  6866. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  6867. Polyline._flat = _flat;
  6868. /*
  6869. * @class Polygon
  6870. * @aka L.Polygon
  6871. * @inherits Polyline
  6872. *
  6873. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  6874. *
  6875. * 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.
  6876. *
  6877. *
  6878. * @example
  6879. *
  6880. * ```js
  6881. * // create a red polygon from an array of LatLng points
  6882. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  6883. *
  6884. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  6885. *
  6886. * // zoom the map to the polygon
  6887. * map.fitBounds(polygon.getBounds());
  6888. * ```
  6889. *
  6890. * 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:
  6891. *
  6892. * ```js
  6893. * var latlngs = [
  6894. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6895. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6896. * ];
  6897. * ```
  6898. *
  6899. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  6900. *
  6901. * ```js
  6902. * var latlngs = [
  6903. * [ // first polygon
  6904. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6905. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6906. * ],
  6907. * [ // second polygon
  6908. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  6909. * ]
  6910. * ];
  6911. * ```
  6912. */
  6913. var Polygon = Polyline.extend({
  6914. options: {
  6915. fill: true
  6916. },
  6917. isEmpty: function () {
  6918. return !this._latlngs.length || !this._latlngs[0].length;
  6919. },
  6920. getCenter: function () {
  6921. // throws error when not yet added to map as this center calculation requires projected coordinates
  6922. if (!this._map) {
  6923. throw new Error('Must add layer to map before using getCenter()');
  6924. }
  6925. var i, j, p1, p2, f, area, x, y, center,
  6926. points = this._rings[0],
  6927. len = points.length;
  6928. if (!len) { return null; }
  6929. // polygon centroid algorithm; only uses the first ring if there are multiple
  6930. area = x = y = 0;
  6931. for (i = 0, j = len - 1; i < len; j = i++) {
  6932. p1 = points[i];
  6933. p2 = points[j];
  6934. f = p1.y * p2.x - p2.y * p1.x;
  6935. x += (p1.x + p2.x) * f;
  6936. y += (p1.y + p2.y) * f;
  6937. area += f * 3;
  6938. }
  6939. if (area === 0) {
  6940. // Polygon is so small that all points are on same pixel.
  6941. center = points[0];
  6942. } else {
  6943. center = [x / area, y / area];
  6944. }
  6945. return this._map.layerPointToLatLng(center);
  6946. },
  6947. _convertLatLngs: function (latlngs) {
  6948. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  6949. len = result.length;
  6950. // remove last point if it equals first one
  6951. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  6952. result.pop();
  6953. }
  6954. return result;
  6955. },
  6956. _setLatLngs: function (latlngs) {
  6957. Polyline.prototype._setLatLngs.call(this, latlngs);
  6958. if (isFlat(this._latlngs)) {
  6959. this._latlngs = [this._latlngs];
  6960. }
  6961. },
  6962. _defaultShape: function () {
  6963. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  6964. },
  6965. _clipPoints: function () {
  6966. // polygons need a different clipping algorithm so we redefine that
  6967. var bounds = this._renderer._bounds,
  6968. w = this.options.weight,
  6969. p = new Point(w, w);
  6970. // increase clip padding by stroke width to avoid stroke on clip edges
  6971. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  6972. this._parts = [];
  6973. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6974. return;
  6975. }
  6976. if (this.options.noClip) {
  6977. this._parts = this._rings;
  6978. return;
  6979. }
  6980. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  6981. clipped = clipPolygon(this._rings[i], bounds, true);
  6982. if (clipped.length) {
  6983. this._parts.push(clipped);
  6984. }
  6985. }
  6986. },
  6987. _updatePath: function () {
  6988. this._renderer._updatePoly(this, true);
  6989. },
  6990. // Needed by the `Canvas` renderer for interactivity
  6991. _containsPoint: function (p) {
  6992. var inside = false,
  6993. part, p1, p2, i, j, k, len, len2;
  6994. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  6995. // ray casting algorithm for detecting if point is in polygon
  6996. for (i = 0, len = this._parts.length; i < len; i++) {
  6997. part = this._parts[i];
  6998. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6999. p1 = part[j];
  7000. p2 = part[k];
  7001. 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)) {
  7002. inside = !inside;
  7003. }
  7004. }
  7005. }
  7006. // also check if it's on polygon stroke
  7007. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  7008. }
  7009. });
  7010. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  7011. function polygon(latlngs, options) {
  7012. return new Polygon(latlngs, options);
  7013. }
  7014. /*
  7015. * @class GeoJSON
  7016. * @aka L.GeoJSON
  7017. * @inherits FeatureGroup
  7018. *
  7019. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  7020. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  7021. *
  7022. * @example
  7023. *
  7024. * ```js
  7025. * L.geoJSON(data, {
  7026. * style: function (feature) {
  7027. * return {color: feature.properties.color};
  7028. * }
  7029. * }).bindPopup(function (layer) {
  7030. * return layer.feature.properties.description;
  7031. * }).addTo(map);
  7032. * ```
  7033. */
  7034. var GeoJSON = FeatureGroup.extend({
  7035. /* @section
  7036. * @aka GeoJSON options
  7037. *
  7038. * @option pointToLayer: Function = *
  7039. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  7040. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  7041. * The default is to spawn a default `Marker`:
  7042. * ```js
  7043. * function(geoJsonPoint, latlng) {
  7044. * return L.marker(latlng);
  7045. * }
  7046. * ```
  7047. *
  7048. * @option style: Function = *
  7049. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  7050. * called internally when data is added.
  7051. * The default value is to not override any defaults:
  7052. * ```js
  7053. * function (geoJsonFeature) {
  7054. * return {}
  7055. * }
  7056. * ```
  7057. *
  7058. * @option onEachFeature: Function = *
  7059. * A `Function` that will be called once for each created `Feature`, after it has
  7060. * been created and styled. Useful for attaching events and popups to features.
  7061. * The default is to do nothing with the newly created layers:
  7062. * ```js
  7063. * function (feature, layer) {}
  7064. * ```
  7065. *
  7066. * @option filter: Function = *
  7067. * A `Function` that will be used to decide whether to include a feature or not.
  7068. * The default is to include all features:
  7069. * ```js
  7070. * function (geoJsonFeature) {
  7071. * return true;
  7072. * }
  7073. * ```
  7074. * Note: dynamically changing the `filter` option will have effect only on newly
  7075. * added data. It will _not_ re-evaluate already included features.
  7076. *
  7077. * @option coordsToLatLng: Function = *
  7078. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  7079. * The default is the `coordsToLatLng` static method.
  7080. */
  7081. initialize: function (geojson, options) {
  7082. setOptions(this, options);
  7083. this._layers = {};
  7084. if (geojson) {
  7085. this.addData(geojson);
  7086. }
  7087. },
  7088. // @method addData( <GeoJSON> data ): this
  7089. // Adds a GeoJSON object to the layer.
  7090. addData: function (geojson) {
  7091. var features = isArray(geojson) ? geojson : geojson.features,
  7092. i, len, feature;
  7093. if (features) {
  7094. for (i = 0, len = features.length; i < len; i++) {
  7095. // only add this if geometry or geometries are set and not null
  7096. feature = features[i];
  7097. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  7098. this.addData(feature);
  7099. }
  7100. }
  7101. return this;
  7102. }
  7103. var options = this.options;
  7104. if (options.filter && !options.filter(geojson)) { return this; }
  7105. var layer = geometryToLayer(geojson, options);
  7106. if (!layer) {
  7107. return this;
  7108. }
  7109. layer.feature = asFeature(geojson);
  7110. layer.defaultOptions = layer.options;
  7111. this.resetStyle(layer);
  7112. if (options.onEachFeature) {
  7113. options.onEachFeature(geojson, layer);
  7114. }
  7115. return this.addLayer(layer);
  7116. },
  7117. // @method resetStyle( <Path> layer ): this
  7118. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7119. resetStyle: function (layer) {
  7120. // reset any custom styles
  7121. layer.options = extend({}, layer.defaultOptions);
  7122. this._setLayerStyle(layer, this.options.style);
  7123. return this;
  7124. },
  7125. // @method setStyle( <Function> style ): this
  7126. // Changes styles of GeoJSON vector layers with the given style function.
  7127. setStyle: function (style) {
  7128. return this.eachLayer(function (layer) {
  7129. this._setLayerStyle(layer, style);
  7130. }, this);
  7131. },
  7132. _setLayerStyle: function (layer, style) {
  7133. if (layer.setStyle) {
  7134. if (typeof style === 'function') {
  7135. style = style(layer.feature);
  7136. }
  7137. layer.setStyle(style);
  7138. }
  7139. }
  7140. });
  7141. // @section
  7142. // There are several static functions which can be called without instantiating L.GeoJSON:
  7143. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7144. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7145. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7146. // functions if provided as options.
  7147. function geometryToLayer(geojson, options) {
  7148. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7149. coords = geometry ? geometry.coordinates : null,
  7150. layers = [],
  7151. pointToLayer = options && options.pointToLayer,
  7152. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7153. latlng, latlngs, i, len;
  7154. if (!coords && !geometry) {
  7155. return null;
  7156. }
  7157. switch (geometry.type) {
  7158. case 'Point':
  7159. latlng = _coordsToLatLng(coords);
  7160. return pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng);
  7161. case 'MultiPoint':
  7162. for (i = 0, len = coords.length; i < len; i++) {
  7163. latlng = _coordsToLatLng(coords[i]);
  7164. layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng));
  7165. }
  7166. return new FeatureGroup(layers);
  7167. case 'LineString':
  7168. case 'MultiLineString':
  7169. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7170. return new Polyline(latlngs, options);
  7171. case 'Polygon':
  7172. case 'MultiPolygon':
  7173. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7174. return new Polygon(latlngs, options);
  7175. case 'GeometryCollection':
  7176. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7177. var layer = geometryToLayer({
  7178. geometry: geometry.geometries[i],
  7179. type: 'Feature',
  7180. properties: geojson.properties
  7181. }, options);
  7182. if (layer) {
  7183. layers.push(layer);
  7184. }
  7185. }
  7186. return new FeatureGroup(layers);
  7187. default:
  7188. throw new Error('Invalid GeoJSON object.');
  7189. }
  7190. }
  7191. // @function coordsToLatLng(coords: Array): LatLng
  7192. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7193. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7194. function coordsToLatLng(coords) {
  7195. return new LatLng(coords[1], coords[0], coords[2]);
  7196. }
  7197. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7198. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7199. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7200. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7201. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7202. var latlngs = [];
  7203. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7204. latlng = levelsDeep ?
  7205. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7206. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7207. latlngs.push(latlng);
  7208. }
  7209. return latlngs;
  7210. }
  7211. // @function latLngToCoords(latlng: LatLng, precision?: Number): Array
  7212. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7213. function latLngToCoords(latlng, precision) {
  7214. precision = typeof precision === 'number' ? precision : 6;
  7215. return latlng.alt !== undefined ?
  7216. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7217. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7218. }
  7219. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  7220. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7221. // `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.
  7222. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7223. var coords = [];
  7224. for (var i = 0, len = latlngs.length; i < len; i++) {
  7225. coords.push(levelsDeep ?
  7226. latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :
  7227. latLngToCoords(latlngs[i], precision));
  7228. }
  7229. if (!levelsDeep && closed) {
  7230. coords.push(coords[0]);
  7231. }
  7232. return coords;
  7233. }
  7234. function getFeature(layer, newGeometry) {
  7235. return layer.feature ?
  7236. extend({}, layer.feature, {geometry: newGeometry}) :
  7237. asFeature(newGeometry);
  7238. }
  7239. // @function asFeature(geojson: Object): Object
  7240. // Normalize GeoJSON geometries/features into GeoJSON features.
  7241. function asFeature(geojson) {
  7242. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7243. return geojson;
  7244. }
  7245. return {
  7246. type: 'Feature',
  7247. properties: {},
  7248. geometry: geojson
  7249. };
  7250. }
  7251. var PointToGeoJSON = {
  7252. toGeoJSON: function (precision) {
  7253. return getFeature(this, {
  7254. type: 'Point',
  7255. coordinates: latLngToCoords(this.getLatLng(), precision)
  7256. });
  7257. }
  7258. };
  7259. // @namespace Marker
  7260. // @method toGeoJSON(precision?: Number): Object
  7261. // `precision` is the number of decimal places for coordinates.
  7262. // The default value is 6 places.
  7263. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7264. Marker.include(PointToGeoJSON);
  7265. // @namespace CircleMarker
  7266. // @method toGeoJSON(precision?: Number): Object
  7267. // `precision` is the number of decimal places for coordinates.
  7268. // The default value is 6 places.
  7269. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7270. Circle.include(PointToGeoJSON);
  7271. CircleMarker.include(PointToGeoJSON);
  7272. // @namespace Polyline
  7273. // @method toGeoJSON(precision?: Number): Object
  7274. // `precision` is the number of decimal places for coordinates.
  7275. // The default value is 6 places.
  7276. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7277. Polyline.include({
  7278. toGeoJSON: function (precision) {
  7279. var multi = !isFlat(this._latlngs);
  7280. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7281. return getFeature(this, {
  7282. type: (multi ? 'Multi' : '') + 'LineString',
  7283. coordinates: coords
  7284. });
  7285. }
  7286. });
  7287. // @namespace Polygon
  7288. // @method toGeoJSON(precision?: Number): Object
  7289. // `precision` is the number of decimal places for coordinates.
  7290. // The default value is 6 places.
  7291. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7292. Polygon.include({
  7293. toGeoJSON: function (precision) {
  7294. var holes = !isFlat(this._latlngs),
  7295. multi = holes && !isFlat(this._latlngs[0]);
  7296. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7297. if (!holes) {
  7298. coords = [coords];
  7299. }
  7300. return getFeature(this, {
  7301. type: (multi ? 'Multi' : '') + 'Polygon',
  7302. coordinates: coords
  7303. });
  7304. }
  7305. });
  7306. // @namespace LayerGroup
  7307. LayerGroup.include({
  7308. toMultiPoint: function (precision) {
  7309. var coords = [];
  7310. this.eachLayer(function (layer) {
  7311. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7312. });
  7313. return getFeature(this, {
  7314. type: 'MultiPoint',
  7315. coordinates: coords
  7316. });
  7317. },
  7318. // @method toGeoJSON(precision?: Number): Object
  7319. // `precision` is the number of decimal places for coordinates.
  7320. // The default value is 6 places.
  7321. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7322. toGeoJSON: function (precision) {
  7323. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7324. if (type === 'MultiPoint') {
  7325. return this.toMultiPoint(precision);
  7326. }
  7327. var isGeometryCollection = type === 'GeometryCollection',
  7328. jsons = [];
  7329. this.eachLayer(function (layer) {
  7330. if (layer.toGeoJSON) {
  7331. var json = layer.toGeoJSON(precision);
  7332. if (isGeometryCollection) {
  7333. jsons.push(json.geometry);
  7334. } else {
  7335. var feature = asFeature(json);
  7336. // Squash nested feature collections
  7337. if (feature.type === 'FeatureCollection') {
  7338. jsons.push.apply(jsons, feature.features);
  7339. } else {
  7340. jsons.push(feature);
  7341. }
  7342. }
  7343. }
  7344. });
  7345. if (isGeometryCollection) {
  7346. return getFeature(this, {
  7347. geometries: jsons,
  7348. type: 'GeometryCollection'
  7349. });
  7350. }
  7351. return {
  7352. type: 'FeatureCollection',
  7353. features: jsons
  7354. };
  7355. }
  7356. });
  7357. // @namespace GeoJSON
  7358. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7359. // Creates a GeoJSON layer. Optionally accepts an object in
  7360. // [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map
  7361. // (you can alternatively add it later with `addData` method) and an `options` object.
  7362. function geoJSON(geojson, options) {
  7363. return new GeoJSON(geojson, options);
  7364. }
  7365. // Backward compatibility.
  7366. var geoJson = geoJSON;
  7367. /*
  7368. * @class ImageOverlay
  7369. * @aka L.ImageOverlay
  7370. * @inherits Interactive layer
  7371. *
  7372. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7373. *
  7374. * @example
  7375. *
  7376. * ```js
  7377. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7378. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7379. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7380. * ```
  7381. */
  7382. var ImageOverlay = Layer.extend({
  7383. // @section
  7384. // @aka ImageOverlay options
  7385. options: {
  7386. // @option opacity: Number = 1.0
  7387. // The opacity of the image overlay.
  7388. opacity: 1,
  7389. // @option alt: String = ''
  7390. // Text for the `alt` attribute of the image (useful for accessibility).
  7391. alt: '',
  7392. // @option interactive: Boolean = false
  7393. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7394. interactive: false,
  7395. // @option crossOrigin: Boolean|String = false
  7396. // Whether the crossOrigin attribute will be added to the image.
  7397. // 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.
  7398. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  7399. crossOrigin: false,
  7400. // @option errorOverlayUrl: String = ''
  7401. // URL to the overlay image to show in place of the overlay that failed to load.
  7402. errorOverlayUrl: '',
  7403. // @option zIndex: Number = 1
  7404. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
  7405. zIndex: 1,
  7406. // @option className: String = ''
  7407. // A custom class name to assign to the image. Empty by default.
  7408. className: ''
  7409. },
  7410. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7411. this._url = url;
  7412. this._bounds = toLatLngBounds(bounds);
  7413. setOptions(this, options);
  7414. },
  7415. onAdd: function () {
  7416. if (!this._image) {
  7417. this._initImage();
  7418. if (this.options.opacity < 1) {
  7419. this._updateOpacity();
  7420. }
  7421. }
  7422. if (this.options.interactive) {
  7423. addClass(this._image, 'leaflet-interactive');
  7424. this.addInteractiveTarget(this._image);
  7425. }
  7426. this.getPane().appendChild(this._image);
  7427. this._reset();
  7428. },
  7429. onRemove: function () {
  7430. remove(this._image);
  7431. if (this.options.interactive) {
  7432. this.removeInteractiveTarget(this._image);
  7433. }
  7434. },
  7435. // @method setOpacity(opacity: Number): this
  7436. // Sets the opacity of the overlay.
  7437. setOpacity: function (opacity) {
  7438. this.options.opacity = opacity;
  7439. if (this._image) {
  7440. this._updateOpacity();
  7441. }
  7442. return this;
  7443. },
  7444. setStyle: function (styleOpts) {
  7445. if (styleOpts.opacity) {
  7446. this.setOpacity(styleOpts.opacity);
  7447. }
  7448. return this;
  7449. },
  7450. // @method bringToFront(): this
  7451. // Brings the layer to the top of all overlays.
  7452. bringToFront: function () {
  7453. if (this._map) {
  7454. toFront(this._image);
  7455. }
  7456. return this;
  7457. },
  7458. // @method bringToBack(): this
  7459. // Brings the layer to the bottom of all overlays.
  7460. bringToBack: function () {
  7461. if (this._map) {
  7462. toBack(this._image);
  7463. }
  7464. return this;
  7465. },
  7466. // @method setUrl(url: String): this
  7467. // Changes the URL of the image.
  7468. setUrl: function (url) {
  7469. this._url = url;
  7470. if (this._image) {
  7471. this._image.src = url;
  7472. }
  7473. return this;
  7474. },
  7475. // @method setBounds(bounds: LatLngBounds): this
  7476. // Update the bounds that this ImageOverlay covers
  7477. setBounds: function (bounds) {
  7478. this._bounds = toLatLngBounds(bounds);
  7479. if (this._map) {
  7480. this._reset();
  7481. }
  7482. return this;
  7483. },
  7484. getEvents: function () {
  7485. var events = {
  7486. zoom: this._reset,
  7487. viewreset: this._reset
  7488. };
  7489. if (this._zoomAnimated) {
  7490. events.zoomanim = this._animateZoom;
  7491. }
  7492. return events;
  7493. },
  7494. // @method setZIndex(value: Number): this
  7495. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7496. setZIndex: function (value) {
  7497. this.options.zIndex = value;
  7498. this._updateZIndex();
  7499. return this;
  7500. },
  7501. // @method getBounds(): LatLngBounds
  7502. // Get the bounds that this ImageOverlay covers
  7503. getBounds: function () {
  7504. return this._bounds;
  7505. },
  7506. // @method getElement(): HTMLElement
  7507. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7508. // used by this overlay.
  7509. getElement: function () {
  7510. return this._image;
  7511. },
  7512. _initImage: function () {
  7513. var wasElementSupplied = this._url.tagName === 'IMG';
  7514. var img = this._image = wasElementSupplied ? this._url : create$1('img');
  7515. addClass(img, 'leaflet-image-layer');
  7516. if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
  7517. if (this.options.className) { addClass(img, this.options.className); }
  7518. img.onselectstart = falseFn;
  7519. img.onmousemove = falseFn;
  7520. // @event load: Event
  7521. // Fired when the ImageOverlay layer has loaded its image
  7522. img.onload = bind(this.fire, this, 'load');
  7523. img.onerror = bind(this._overlayOnError, this, 'error');
  7524. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  7525. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  7526. }
  7527. if (this.options.zIndex) {
  7528. this._updateZIndex();
  7529. }
  7530. if (wasElementSupplied) {
  7531. this._url = img.src;
  7532. return;
  7533. }
  7534. img.src = this._url;
  7535. img.alt = this.options.alt;
  7536. },
  7537. _animateZoom: function (e) {
  7538. var scale = this._map.getZoomScale(e.zoom),
  7539. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7540. setTransform(this._image, offset, scale);
  7541. },
  7542. _reset: function () {
  7543. var image = this._image,
  7544. bounds = new Bounds(
  7545. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7546. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7547. size = bounds.getSize();
  7548. setPosition(image, bounds.min);
  7549. image.style.width = size.x + 'px';
  7550. image.style.height = size.y + 'px';
  7551. },
  7552. _updateOpacity: function () {
  7553. setOpacity(this._image, this.options.opacity);
  7554. },
  7555. _updateZIndex: function () {
  7556. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7557. this._image.style.zIndex = this.options.zIndex;
  7558. }
  7559. },
  7560. _overlayOnError: function () {
  7561. // @event error: Event
  7562. // Fired when the ImageOverlay layer fails to load its image
  7563. this.fire('error');
  7564. var errorUrl = this.options.errorOverlayUrl;
  7565. if (errorUrl && this._url !== errorUrl) {
  7566. this._url = errorUrl;
  7567. this._image.src = errorUrl;
  7568. }
  7569. }
  7570. });
  7571. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7572. // Instantiates an image overlay object given the URL of the image and the
  7573. // geographical bounds it is tied to.
  7574. var imageOverlay = function (url, bounds, options) {
  7575. return new ImageOverlay(url, bounds, options);
  7576. };
  7577. /*
  7578. * @class VideoOverlay
  7579. * @aka L.VideoOverlay
  7580. * @inherits ImageOverlay
  7581. *
  7582. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7583. *
  7584. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7585. * HTML5 element.
  7586. *
  7587. * @example
  7588. *
  7589. * ```js
  7590. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7591. * videoBounds = [[ 32, -130], [ 13, -100]];
  7592. * L.videoOverlay(videoUrl, videoBounds ).addTo(map);
  7593. * ```
  7594. */
  7595. var VideoOverlay = ImageOverlay.extend({
  7596. // @section
  7597. // @aka VideoOverlay options
  7598. options: {
  7599. // @option autoplay: Boolean = true
  7600. // Whether the video starts playing automatically when loaded.
  7601. autoplay: true,
  7602. // @option loop: Boolean = true
  7603. // Whether the video will loop back to the beginning when played.
  7604. loop: true,
  7605. // @option keepAspectRatio: Boolean = true
  7606. // Whether the video will save aspect ratio after the projection.
  7607. // Relevant for supported browsers. Browser compatibility- https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
  7608. keepAspectRatio: true
  7609. },
  7610. _initImage: function () {
  7611. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7612. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7613. addClass(vid, 'leaflet-image-layer');
  7614. if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
  7615. vid.onselectstart = falseFn;
  7616. vid.onmousemove = falseFn;
  7617. // @event load: Event
  7618. // Fired when the video has finished loading the first frame
  7619. vid.onloadeddata = bind(this.fire, this, 'load');
  7620. if (wasElementSupplied) {
  7621. var sourceElements = vid.getElementsByTagName('source');
  7622. var sources = [];
  7623. for (var j = 0; j < sourceElements.length; j++) {
  7624. sources.push(sourceElements[j].src);
  7625. }
  7626. this._url = (sourceElements.length > 0) ? sources : [vid.src];
  7627. return;
  7628. }
  7629. if (!isArray(this._url)) { this._url = [this._url]; }
  7630. if (!this.options.keepAspectRatio && vid.style.hasOwnProperty('objectFit')) { vid.style['objectFit'] = 'fill'; }
  7631. vid.autoplay = !!this.options.autoplay;
  7632. vid.loop = !!this.options.loop;
  7633. for (var i = 0; i < this._url.length; i++) {
  7634. var source = create$1('source');
  7635. source.src = this._url[i];
  7636. vid.appendChild(source);
  7637. }
  7638. }
  7639. // @method getElement(): HTMLVideoElement
  7640. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7641. // used by this overlay.
  7642. });
  7643. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7644. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7645. // geographical bounds it is tied to.
  7646. function videoOverlay(video, bounds, options) {
  7647. return new VideoOverlay(video, bounds, options);
  7648. }
  7649. /*
  7650. * @class SVGOverlay
  7651. * @aka L.SVGOverlay
  7652. * @inherits ImageOverlay
  7653. *
  7654. * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.
  7655. *
  7656. * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.
  7657. *
  7658. * @example
  7659. *
  7660. * ```js
  7661. * var element = '<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><image xlink:href="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" height="200" width="200"/></svg>',
  7662. * elementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
  7663. * L.svgOverlay(element, elementBounds).addTo(map);
  7664. * ```
  7665. */
  7666. var SVGOverlay = ImageOverlay.extend({
  7667. _initImage: function () {
  7668. var el = this._image = this._url;
  7669. addClass(el, 'leaflet-image-layer');
  7670. if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); }
  7671. el.onselectstart = falseFn;
  7672. el.onmousemove = falseFn;
  7673. }
  7674. // @method getElement(): SVGElement
  7675. // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
  7676. // used by this overlay.
  7677. });
  7678. // @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)
  7679. // Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.
  7680. // A viewBox attribute is required on the SVG element to zoom in and out properly.
  7681. function svgOverlay(el, bounds, options) {
  7682. return new SVGOverlay(el, bounds, options);
  7683. }
  7684. /*
  7685. * @class DivOverlay
  7686. * @inherits Layer
  7687. * @aka L.DivOverlay
  7688. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  7689. */
  7690. // @namespace DivOverlay
  7691. var DivOverlay = Layer.extend({
  7692. // @section
  7693. // @aka DivOverlay options
  7694. options: {
  7695. // @option offset: Point = Point(0, 7)
  7696. // The offset of the popup position. Useful to control the anchor
  7697. // of the popup when opening it on some overlays.
  7698. offset: [0, 7],
  7699. // @option className: String = ''
  7700. // A custom CSS class name to assign to the popup.
  7701. className: '',
  7702. // @option pane: String = 'popupPane'
  7703. // `Map pane` where the popup will be added.
  7704. pane: 'popupPane'
  7705. },
  7706. initialize: function (options, source) {
  7707. setOptions(this, options);
  7708. this._source = source;
  7709. },
  7710. onAdd: function (map) {
  7711. this._zoomAnimated = map._zoomAnimated;
  7712. if (!this._container) {
  7713. this._initLayout();
  7714. }
  7715. if (map._fadeAnimated) {
  7716. setOpacity(this._container, 0);
  7717. }
  7718. clearTimeout(this._removeTimeout);
  7719. this.getPane().appendChild(this._container);
  7720. this.update();
  7721. if (map._fadeAnimated) {
  7722. setOpacity(this._container, 1);
  7723. }
  7724. this.bringToFront();
  7725. },
  7726. onRemove: function (map) {
  7727. if (map._fadeAnimated) {
  7728. setOpacity(this._container, 0);
  7729. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  7730. } else {
  7731. remove(this._container);
  7732. }
  7733. },
  7734. // @namespace Popup
  7735. // @method getLatLng: LatLng
  7736. // Returns the geographical point of popup.
  7737. getLatLng: function () {
  7738. return this._latlng;
  7739. },
  7740. // @method setLatLng(latlng: LatLng): this
  7741. // Sets the geographical point where the popup will open.
  7742. setLatLng: function (latlng) {
  7743. this._latlng = toLatLng(latlng);
  7744. if (this._map) {
  7745. this._updatePosition();
  7746. this._adjustPan();
  7747. }
  7748. return this;
  7749. },
  7750. // @method getContent: String|HTMLElement
  7751. // Returns the content of the popup.
  7752. getContent: function () {
  7753. return this._content;
  7754. },
  7755. // @method setContent(htmlContent: String|HTMLElement|Function): this
  7756. // 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.
  7757. setContent: function (content) {
  7758. this._content = content;
  7759. this.update();
  7760. return this;
  7761. },
  7762. // @method getElement: String|HTMLElement
  7763. // Alias for [getContent()](#popup-getcontent)
  7764. getElement: function () {
  7765. return this._container;
  7766. },
  7767. // @method update: null
  7768. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  7769. update: function () {
  7770. if (!this._map) { return; }
  7771. this._container.style.visibility = 'hidden';
  7772. this._updateContent();
  7773. this._updateLayout();
  7774. this._updatePosition();
  7775. this._container.style.visibility = '';
  7776. this._adjustPan();
  7777. },
  7778. getEvents: function () {
  7779. var events = {
  7780. zoom: this._updatePosition,
  7781. viewreset: this._updatePosition
  7782. };
  7783. if (this._zoomAnimated) {
  7784. events.zoomanim = this._animateZoom;
  7785. }
  7786. return events;
  7787. },
  7788. // @method isOpen: Boolean
  7789. // Returns `true` when the popup is visible on the map.
  7790. isOpen: function () {
  7791. return !!this._map && this._map.hasLayer(this);
  7792. },
  7793. // @method bringToFront: this
  7794. // Brings this popup in front of other popups (in the same map pane).
  7795. bringToFront: function () {
  7796. if (this._map) {
  7797. toFront(this._container);
  7798. }
  7799. return this;
  7800. },
  7801. // @method bringToBack: this
  7802. // Brings this popup to the back of other popups (in the same map pane).
  7803. bringToBack: function () {
  7804. if (this._map) {
  7805. toBack(this._container);
  7806. }
  7807. return this;
  7808. },
  7809. _prepareOpen: function (parent, layer, latlng) {
  7810. if (!(layer instanceof Layer)) {
  7811. latlng = layer;
  7812. layer = parent;
  7813. }
  7814. if (layer instanceof FeatureGroup) {
  7815. for (var id in parent._layers) {
  7816. layer = parent._layers[id];
  7817. break;
  7818. }
  7819. }
  7820. if (!latlng) {
  7821. if (layer.getCenter) {
  7822. latlng = layer.getCenter();
  7823. } else if (layer.getLatLng) {
  7824. latlng = layer.getLatLng();
  7825. } else {
  7826. throw new Error('Unable to get source layer LatLng.');
  7827. }
  7828. }
  7829. // set overlay source to this layer
  7830. this._source = layer;
  7831. // update the overlay (content, layout, ect...)
  7832. this.update();
  7833. return latlng;
  7834. },
  7835. _updateContent: function () {
  7836. if (!this._content) { return; }
  7837. var node = this._contentNode;
  7838. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  7839. if (typeof content === 'string') {
  7840. node.innerHTML = content;
  7841. } else {
  7842. while (node.hasChildNodes()) {
  7843. node.removeChild(node.firstChild);
  7844. }
  7845. node.appendChild(content);
  7846. }
  7847. this.fire('contentupdate');
  7848. },
  7849. _updatePosition: function () {
  7850. if (!this._map) { return; }
  7851. var pos = this._map.latLngToLayerPoint(this._latlng),
  7852. offset = toPoint(this.options.offset),
  7853. anchor = this._getAnchor();
  7854. if (this._zoomAnimated) {
  7855. setPosition(this._container, pos.add(anchor));
  7856. } else {
  7857. offset = offset.add(pos).add(anchor);
  7858. }
  7859. var bottom = this._containerBottom = -offset.y,
  7860. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  7861. // bottom position the popup in case the height of the popup changes (images loading etc)
  7862. this._container.style.bottom = bottom + 'px';
  7863. this._container.style.left = left + 'px';
  7864. },
  7865. _getAnchor: function () {
  7866. return [0, 0];
  7867. }
  7868. });
  7869. /*
  7870. * @class Popup
  7871. * @inherits DivOverlay
  7872. * @aka L.Popup
  7873. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  7874. * open popups while making sure that only one popup is open at one time
  7875. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  7876. *
  7877. * @example
  7878. *
  7879. * If you want to just bind a popup to marker click and then open it, it's really easy:
  7880. *
  7881. * ```js
  7882. * marker.bindPopup(popupContent).openPopup();
  7883. * ```
  7884. * Path overlays like polylines also have a `bindPopup` method.
  7885. * Here's a more complicated way to open a popup on a map:
  7886. *
  7887. * ```js
  7888. * var popup = L.popup()
  7889. * .setLatLng(latlng)
  7890. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  7891. * .openOn(map);
  7892. * ```
  7893. */
  7894. // @namespace Popup
  7895. var Popup = DivOverlay.extend({
  7896. // @section
  7897. // @aka Popup options
  7898. options: {
  7899. // @option maxWidth: Number = 300
  7900. // Max width of the popup, in pixels.
  7901. maxWidth: 300,
  7902. // @option minWidth: Number = 50
  7903. // Min width of the popup, in pixels.
  7904. minWidth: 50,
  7905. // @option maxHeight: Number = null
  7906. // If set, creates a scrollable container of the given height
  7907. // inside a popup if its content exceeds it.
  7908. maxHeight: null,
  7909. // @option autoPan: Boolean = true
  7910. // Set it to `false` if you don't want the map to do panning animation
  7911. // to fit the opened popup.
  7912. autoPan: true,
  7913. // @option autoPanPaddingTopLeft: Point = null
  7914. // The margin between the popup and the top left corner of the map
  7915. // view after autopanning was performed.
  7916. autoPanPaddingTopLeft: null,
  7917. // @option autoPanPaddingBottomRight: Point = null
  7918. // The margin between the popup and the bottom right corner of the map
  7919. // view after autopanning was performed.
  7920. autoPanPaddingBottomRight: null,
  7921. // @option autoPanPadding: Point = Point(5, 5)
  7922. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  7923. autoPanPadding: [5, 5],
  7924. // @option keepInView: Boolean = false
  7925. // Set it to `true` if you want to prevent users from panning the popup
  7926. // off of the screen while it is open.
  7927. keepInView: false,
  7928. // @option closeButton: Boolean = true
  7929. // Controls the presence of a close button in the popup.
  7930. closeButton: true,
  7931. // @option autoClose: Boolean = true
  7932. // Set it to `false` if you want to override the default behavior of
  7933. // the popup closing when another popup is opened.
  7934. autoClose: true,
  7935. // @option closeOnEscapeKey: Boolean = true
  7936. // Set it to `false` if you want to override the default behavior of
  7937. // the ESC key for closing of the popup.
  7938. closeOnEscapeKey: true,
  7939. // @option closeOnClick: Boolean = *
  7940. // Set it if you want to override the default behavior of the popup closing when user clicks
  7941. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  7942. // @option className: String = ''
  7943. // A custom CSS class name to assign to the popup.
  7944. className: ''
  7945. },
  7946. // @namespace Popup
  7947. // @method openOn(map: Map): this
  7948. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  7949. openOn: function (map) {
  7950. map.openPopup(this);
  7951. return this;
  7952. },
  7953. onAdd: function (map) {
  7954. DivOverlay.prototype.onAdd.call(this, map);
  7955. // @namespace Map
  7956. // @section Popup events
  7957. // @event popupopen: PopupEvent
  7958. // Fired when a popup is opened in the map
  7959. map.fire('popupopen', {popup: this});
  7960. if (this._source) {
  7961. // @namespace Layer
  7962. // @section Popup events
  7963. // @event popupopen: PopupEvent
  7964. // Fired when a popup bound to this layer is opened
  7965. this._source.fire('popupopen', {popup: this}, true);
  7966. // For non-path layers, we toggle the popup when clicking
  7967. // again the layer, so prevent the map to reopen it.
  7968. if (!(this._source instanceof Path)) {
  7969. this._source.on('preclick', stopPropagation);
  7970. }
  7971. }
  7972. },
  7973. onRemove: function (map) {
  7974. DivOverlay.prototype.onRemove.call(this, map);
  7975. // @namespace Map
  7976. // @section Popup events
  7977. // @event popupclose: PopupEvent
  7978. // Fired when a popup in the map is closed
  7979. map.fire('popupclose', {popup: this});
  7980. if (this._source) {
  7981. // @namespace Layer
  7982. // @section Popup events
  7983. // @event popupclose: PopupEvent
  7984. // Fired when a popup bound to this layer is closed
  7985. this._source.fire('popupclose', {popup: this}, true);
  7986. if (!(this._source instanceof Path)) {
  7987. this._source.off('preclick', stopPropagation);
  7988. }
  7989. }
  7990. },
  7991. getEvents: function () {
  7992. var events = DivOverlay.prototype.getEvents.call(this);
  7993. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  7994. events.preclick = this._close;
  7995. }
  7996. if (this.options.keepInView) {
  7997. events.moveend = this._adjustPan;
  7998. }
  7999. return events;
  8000. },
  8001. _close: function () {
  8002. if (this._map) {
  8003. this._map.closePopup(this);
  8004. }
  8005. },
  8006. _initLayout: function () {
  8007. var prefix = 'leaflet-popup',
  8008. container = this._container = create$1('div',
  8009. prefix + ' ' + (this.options.className || '') +
  8010. ' leaflet-zoom-animated');
  8011. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  8012. this._contentNode = create$1('div', prefix + '-content', wrapper);
  8013. disableClickPropagation(wrapper);
  8014. disableScrollPropagation(this._contentNode);
  8015. on(wrapper, 'contextmenu', stopPropagation);
  8016. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  8017. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  8018. if (this.options.closeButton) {
  8019. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  8020. closeButton.href = '#close';
  8021. closeButton.innerHTML = '&#215;';
  8022. on(closeButton, 'click', this._onCloseButtonClick, this);
  8023. }
  8024. },
  8025. _updateLayout: function () {
  8026. var container = this._contentNode,
  8027. style = container.style;
  8028. style.width = '';
  8029. style.whiteSpace = 'nowrap';
  8030. var width = container.offsetWidth;
  8031. width = Math.min(width, this.options.maxWidth);
  8032. width = Math.max(width, this.options.minWidth);
  8033. style.width = (width + 1) + 'px';
  8034. style.whiteSpace = '';
  8035. style.height = '';
  8036. var height = container.offsetHeight,
  8037. maxHeight = this.options.maxHeight,
  8038. scrolledClass = 'leaflet-popup-scrolled';
  8039. if (maxHeight && height > maxHeight) {
  8040. style.height = maxHeight + 'px';
  8041. addClass(container, scrolledClass);
  8042. } else {
  8043. removeClass(container, scrolledClass);
  8044. }
  8045. this._containerWidth = this._container.offsetWidth;
  8046. },
  8047. _animateZoom: function (e) {
  8048. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  8049. anchor = this._getAnchor();
  8050. setPosition(this._container, pos.add(anchor));
  8051. },
  8052. _adjustPan: function () {
  8053. if (!this.options.autoPan) { return; }
  8054. if (this._map._panAnim) { this._map._panAnim.stop(); }
  8055. var map = this._map,
  8056. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  8057. containerHeight = this._container.offsetHeight + marginBottom,
  8058. containerWidth = this._containerWidth,
  8059. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  8060. layerPos._add(getPosition(this._container));
  8061. var containerPos = map.layerPointToContainerPoint(layerPos),
  8062. padding = toPoint(this.options.autoPanPadding),
  8063. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  8064. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  8065. size = map.getSize(),
  8066. dx = 0,
  8067. dy = 0;
  8068. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  8069. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  8070. }
  8071. if (containerPos.x - dx - paddingTL.x < 0) { // left
  8072. dx = containerPos.x - paddingTL.x;
  8073. }
  8074. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  8075. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  8076. }
  8077. if (containerPos.y - dy - paddingTL.y < 0) { // top
  8078. dy = containerPos.y - paddingTL.y;
  8079. }
  8080. // @namespace Map
  8081. // @section Popup events
  8082. // @event autopanstart: Event
  8083. // Fired when the map starts autopanning when opening a popup.
  8084. if (dx || dy) {
  8085. map
  8086. .fire('autopanstart')
  8087. .panBy([dx, dy]);
  8088. }
  8089. },
  8090. _onCloseButtonClick: function (e) {
  8091. this._close();
  8092. stop(e);
  8093. },
  8094. _getAnchor: function () {
  8095. // Where should we anchor the popup on the source layer?
  8096. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  8097. }
  8098. });
  8099. // @namespace Popup
  8100. // @factory L.popup(options?: Popup options, source?: Layer)
  8101. // 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.
  8102. var popup = function (options, source) {
  8103. return new Popup(options, source);
  8104. };
  8105. /* @namespace Map
  8106. * @section Interaction Options
  8107. * @option closePopupOnClick: Boolean = true
  8108. * Set it to `false` if you don't want popups to close when user clicks the map.
  8109. */
  8110. Map.mergeOptions({
  8111. closePopupOnClick: true
  8112. });
  8113. // @namespace Map
  8114. // @section Methods for Layers and Controls
  8115. Map.include({
  8116. // @method openPopup(popup: Popup): this
  8117. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  8118. // @alternative
  8119. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  8120. // Creates a popup with the specified content and options and opens it in the given point on a map.
  8121. openPopup: function (popup, latlng, options) {
  8122. if (!(popup instanceof Popup)) {
  8123. popup = new Popup(options).setContent(popup);
  8124. }
  8125. if (latlng) {
  8126. popup.setLatLng(latlng);
  8127. }
  8128. if (this.hasLayer(popup)) {
  8129. return this;
  8130. }
  8131. if (this._popup && this._popup.options.autoClose) {
  8132. this.closePopup();
  8133. }
  8134. this._popup = popup;
  8135. return this.addLayer(popup);
  8136. },
  8137. // @method closePopup(popup?: Popup): this
  8138. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  8139. closePopup: function (popup) {
  8140. if (!popup || popup === this._popup) {
  8141. popup = this._popup;
  8142. this._popup = null;
  8143. }
  8144. if (popup) {
  8145. this.removeLayer(popup);
  8146. }
  8147. return this;
  8148. }
  8149. });
  8150. /*
  8151. * @namespace Layer
  8152. * @section Popup methods example
  8153. *
  8154. * All layers share a set of methods convenient for binding popups to it.
  8155. *
  8156. * ```js
  8157. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  8158. * layer.openPopup();
  8159. * layer.closePopup();
  8160. * ```
  8161. *
  8162. * 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.
  8163. */
  8164. // @section Popup methods
  8165. Layer.include({
  8166. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  8167. // Binds a popup to the layer with the passed `content` and sets up the
  8168. // necessary event listeners. If a `Function` is passed it will receive
  8169. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8170. bindPopup: function (content, options) {
  8171. if (content instanceof Popup) {
  8172. setOptions(content, options);
  8173. this._popup = content;
  8174. content._source = this;
  8175. } else {
  8176. if (!this._popup || options) {
  8177. this._popup = new Popup(options, this);
  8178. }
  8179. this._popup.setContent(content);
  8180. }
  8181. if (!this._popupHandlersAdded) {
  8182. this.on({
  8183. click: this._openPopup,
  8184. keypress: this._onKeyPress,
  8185. remove: this.closePopup,
  8186. move: this._movePopup
  8187. });
  8188. this._popupHandlersAdded = true;
  8189. }
  8190. return this;
  8191. },
  8192. // @method unbindPopup(): this
  8193. // Removes the popup previously bound with `bindPopup`.
  8194. unbindPopup: function () {
  8195. if (this._popup) {
  8196. this.off({
  8197. click: this._openPopup,
  8198. keypress: this._onKeyPress,
  8199. remove: this.closePopup,
  8200. move: this._movePopup
  8201. });
  8202. this._popupHandlersAdded = false;
  8203. this._popup = null;
  8204. }
  8205. return this;
  8206. },
  8207. // @method openPopup(latlng?: LatLng): this
  8208. // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
  8209. openPopup: function (layer, latlng) {
  8210. if (this._popup && this._map) {
  8211. latlng = this._popup._prepareOpen(this, layer, latlng);
  8212. // open the popup on the map
  8213. this._map.openPopup(this._popup, latlng);
  8214. }
  8215. return this;
  8216. },
  8217. // @method closePopup(): this
  8218. // Closes the popup bound to this layer if it is open.
  8219. closePopup: function () {
  8220. if (this._popup) {
  8221. this._popup._close();
  8222. }
  8223. return this;
  8224. },
  8225. // @method togglePopup(): this
  8226. // Opens or closes the popup bound to this layer depending on its current state.
  8227. togglePopup: function (target) {
  8228. if (this._popup) {
  8229. if (this._popup._map) {
  8230. this.closePopup();
  8231. } else {
  8232. this.openPopup(target);
  8233. }
  8234. }
  8235. return this;
  8236. },
  8237. // @method isPopupOpen(): boolean
  8238. // Returns `true` if the popup bound to this layer is currently open.
  8239. isPopupOpen: function () {
  8240. return (this._popup ? this._popup.isOpen() : false);
  8241. },
  8242. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8243. // Sets the content of the popup bound to this layer.
  8244. setPopupContent: function (content) {
  8245. if (this._popup) {
  8246. this._popup.setContent(content);
  8247. }
  8248. return this;
  8249. },
  8250. // @method getPopup(): Popup
  8251. // Returns the popup bound to this layer.
  8252. getPopup: function () {
  8253. return this._popup;
  8254. },
  8255. _openPopup: function (e) {
  8256. var layer = e.layer || e.target;
  8257. if (!this._popup) {
  8258. return;
  8259. }
  8260. if (!this._map) {
  8261. return;
  8262. }
  8263. // prevent map click
  8264. stop(e);
  8265. // if this inherits from Path its a vector and we can just
  8266. // open the popup at the new location
  8267. if (layer instanceof Path) {
  8268. this.openPopup(e.layer || e.target, e.latlng);
  8269. return;
  8270. }
  8271. // otherwise treat it like a marker and figure out
  8272. // if we should toggle it open/closed
  8273. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  8274. this.closePopup();
  8275. } else {
  8276. this.openPopup(layer, e.latlng);
  8277. }
  8278. },
  8279. _movePopup: function (e) {
  8280. this._popup.setLatLng(e.latlng);
  8281. },
  8282. _onKeyPress: function (e) {
  8283. if (e.originalEvent.keyCode === 13) {
  8284. this._openPopup(e);
  8285. }
  8286. }
  8287. });
  8288. /*
  8289. * @class Tooltip
  8290. * @inherits DivOverlay
  8291. * @aka L.Tooltip
  8292. * Used to display small texts on top of map layers.
  8293. *
  8294. * @example
  8295. *
  8296. * ```js
  8297. * marker.bindTooltip("my tooltip text").openTooltip();
  8298. * ```
  8299. * Note about tooltip offset. Leaflet takes two options in consideration
  8300. * for computing tooltip offsetting:
  8301. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8302. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8303. * move it to the bottom. Negatives will move to the left and top.
  8304. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8305. * should adapt this value if you use a custom icon.
  8306. */
  8307. // @namespace Tooltip
  8308. var Tooltip = DivOverlay.extend({
  8309. // @section
  8310. // @aka Tooltip options
  8311. options: {
  8312. // @option pane: String = 'tooltipPane'
  8313. // `Map pane` where the tooltip will be added.
  8314. pane: 'tooltipPane',
  8315. // @option offset: Point = Point(0, 0)
  8316. // Optional offset of the tooltip position.
  8317. offset: [0, 0],
  8318. // @option direction: String = 'auto'
  8319. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8320. // `top`, `bottom`, `center`, `auto`.
  8321. // `auto` will dynamically switch between `right` and `left` according to the tooltip
  8322. // position on the map.
  8323. direction: 'auto',
  8324. // @option permanent: Boolean = false
  8325. // Whether to open the tooltip permanently or only on mouseover.
  8326. permanent: false,
  8327. // @option sticky: Boolean = false
  8328. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8329. sticky: false,
  8330. // @option interactive: Boolean = false
  8331. // If true, the tooltip will listen to the feature events.
  8332. interactive: false,
  8333. // @option opacity: Number = 0.9
  8334. // Tooltip container opacity.
  8335. opacity: 0.9
  8336. },
  8337. onAdd: function (map) {
  8338. DivOverlay.prototype.onAdd.call(this, map);
  8339. this.setOpacity(this.options.opacity);
  8340. // @namespace Map
  8341. // @section Tooltip events
  8342. // @event tooltipopen: TooltipEvent
  8343. // Fired when a tooltip is opened in the map.
  8344. map.fire('tooltipopen', {tooltip: this});
  8345. if (this._source) {
  8346. // @namespace Layer
  8347. // @section Tooltip events
  8348. // @event tooltipopen: TooltipEvent
  8349. // Fired when a tooltip bound to this layer is opened.
  8350. this._source.fire('tooltipopen', {tooltip: this}, true);
  8351. }
  8352. },
  8353. onRemove: function (map) {
  8354. DivOverlay.prototype.onRemove.call(this, map);
  8355. // @namespace Map
  8356. // @section Tooltip events
  8357. // @event tooltipclose: TooltipEvent
  8358. // Fired when a tooltip in the map is closed.
  8359. map.fire('tooltipclose', {tooltip: this});
  8360. if (this._source) {
  8361. // @namespace Layer
  8362. // @section Tooltip events
  8363. // @event tooltipclose: TooltipEvent
  8364. // Fired when a tooltip bound to this layer is closed.
  8365. this._source.fire('tooltipclose', {tooltip: this}, true);
  8366. }
  8367. },
  8368. getEvents: function () {
  8369. var events = DivOverlay.prototype.getEvents.call(this);
  8370. if (touch && !this.options.permanent) {
  8371. events.preclick = this._close;
  8372. }
  8373. return events;
  8374. },
  8375. _close: function () {
  8376. if (this._map) {
  8377. this._map.closeTooltip(this);
  8378. }
  8379. },
  8380. _initLayout: function () {
  8381. var prefix = 'leaflet-tooltip',
  8382. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8383. this._contentNode = this._container = create$1('div', className);
  8384. },
  8385. _updateLayout: function () {},
  8386. _adjustPan: function () {},
  8387. _setPosition: function (pos) {
  8388. var map = this._map,
  8389. container = this._container,
  8390. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8391. tooltipPoint = map.layerPointToContainerPoint(pos),
  8392. direction = this.options.direction,
  8393. tooltipWidth = container.offsetWidth,
  8394. tooltipHeight = container.offsetHeight,
  8395. offset = toPoint(this.options.offset),
  8396. anchor = this._getAnchor();
  8397. if (direction === 'top') {
  8398. pos = pos.add(toPoint(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true));
  8399. } else if (direction === 'bottom') {
  8400. pos = pos.subtract(toPoint(tooltipWidth / 2 - offset.x, -offset.y, true));
  8401. } else if (direction === 'center') {
  8402. pos = pos.subtract(toPoint(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true));
  8403. } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
  8404. direction = 'right';
  8405. pos = pos.add(toPoint(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true));
  8406. } else {
  8407. direction = 'left';
  8408. pos = pos.subtract(toPoint(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true));
  8409. }
  8410. removeClass(container, 'leaflet-tooltip-right');
  8411. removeClass(container, 'leaflet-tooltip-left');
  8412. removeClass(container, 'leaflet-tooltip-top');
  8413. removeClass(container, 'leaflet-tooltip-bottom');
  8414. addClass(container, 'leaflet-tooltip-' + direction);
  8415. setPosition(container, pos);
  8416. },
  8417. _updatePosition: function () {
  8418. var pos = this._map.latLngToLayerPoint(this._latlng);
  8419. this._setPosition(pos);
  8420. },
  8421. setOpacity: function (opacity) {
  8422. this.options.opacity = opacity;
  8423. if (this._container) {
  8424. setOpacity(this._container, opacity);
  8425. }
  8426. },
  8427. _animateZoom: function (e) {
  8428. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8429. this._setPosition(pos);
  8430. },
  8431. _getAnchor: function () {
  8432. // Where should we anchor the tooltip on the source layer?
  8433. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8434. }
  8435. });
  8436. // @namespace Tooltip
  8437. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8438. // 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.
  8439. var tooltip = function (options, source) {
  8440. return new Tooltip(options, source);
  8441. };
  8442. // @namespace Map
  8443. // @section Methods for Layers and Controls
  8444. Map.include({
  8445. // @method openTooltip(tooltip: Tooltip): this
  8446. // Opens the specified tooltip.
  8447. // @alternative
  8448. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8449. // Creates a tooltip with the specified content and options and open it.
  8450. openTooltip: function (tooltip, latlng, options) {
  8451. if (!(tooltip instanceof Tooltip)) {
  8452. tooltip = new Tooltip(options).setContent(tooltip);
  8453. }
  8454. if (latlng) {
  8455. tooltip.setLatLng(latlng);
  8456. }
  8457. if (this.hasLayer(tooltip)) {
  8458. return this;
  8459. }
  8460. return this.addLayer(tooltip);
  8461. },
  8462. // @method closeTooltip(tooltip?: Tooltip): this
  8463. // Closes the tooltip given as parameter.
  8464. closeTooltip: function (tooltip) {
  8465. if (tooltip) {
  8466. this.removeLayer(tooltip);
  8467. }
  8468. return this;
  8469. }
  8470. });
  8471. /*
  8472. * @namespace Layer
  8473. * @section Tooltip methods example
  8474. *
  8475. * All layers share a set of methods convenient for binding tooltips to it.
  8476. *
  8477. * ```js
  8478. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8479. * layer.openTooltip();
  8480. * layer.closeTooltip();
  8481. * ```
  8482. */
  8483. // @section Tooltip methods
  8484. Layer.include({
  8485. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8486. // Binds a tooltip to the layer with the passed `content` and sets up the
  8487. // necessary event listeners. If a `Function` is passed it will receive
  8488. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8489. bindTooltip: function (content, options) {
  8490. if (content instanceof Tooltip) {
  8491. setOptions(content, options);
  8492. this._tooltip = content;
  8493. content._source = this;
  8494. } else {
  8495. if (!this._tooltip || options) {
  8496. this._tooltip = new Tooltip(options, this);
  8497. }
  8498. this._tooltip.setContent(content);
  8499. }
  8500. this._initTooltipInteractions();
  8501. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8502. this.openTooltip();
  8503. }
  8504. return this;
  8505. },
  8506. // @method unbindTooltip(): this
  8507. // Removes the tooltip previously bound with `bindTooltip`.
  8508. unbindTooltip: function () {
  8509. if (this._tooltip) {
  8510. this._initTooltipInteractions(true);
  8511. this.closeTooltip();
  8512. this._tooltip = null;
  8513. }
  8514. return this;
  8515. },
  8516. _initTooltipInteractions: function (remove$$1) {
  8517. if (!remove$$1 && this._tooltipHandlersAdded) { return; }
  8518. var onOff = remove$$1 ? 'off' : 'on',
  8519. events = {
  8520. remove: this.closeTooltip,
  8521. move: this._moveTooltip
  8522. };
  8523. if (!this._tooltip.options.permanent) {
  8524. events.mouseover = this._openTooltip;
  8525. events.mouseout = this.closeTooltip;
  8526. if (this._tooltip.options.sticky) {
  8527. events.mousemove = this._moveTooltip;
  8528. }
  8529. if (touch) {
  8530. events.click = this._openTooltip;
  8531. }
  8532. } else {
  8533. events.add = this._openTooltip;
  8534. }
  8535. this[onOff](events);
  8536. this._tooltipHandlersAdded = !remove$$1;
  8537. },
  8538. // @method openTooltip(latlng?: LatLng): this
  8539. // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8540. openTooltip: function (layer, latlng) {
  8541. if (this._tooltip && this._map) {
  8542. latlng = this._tooltip._prepareOpen(this, layer, latlng);
  8543. // open the tooltip on the map
  8544. this._map.openTooltip(this._tooltip, latlng);
  8545. // Tooltip container may not be defined if not permanent and never
  8546. // opened.
  8547. if (this._tooltip.options.interactive && this._tooltip._container) {
  8548. addClass(this._tooltip._container, 'leaflet-clickable');
  8549. this.addInteractiveTarget(this._tooltip._container);
  8550. }
  8551. }
  8552. return this;
  8553. },
  8554. // @method closeTooltip(): this
  8555. // Closes the tooltip bound to this layer if it is open.
  8556. closeTooltip: function () {
  8557. if (this._tooltip) {
  8558. this._tooltip._close();
  8559. if (this._tooltip.options.interactive && this._tooltip._container) {
  8560. removeClass(this._tooltip._container, 'leaflet-clickable');
  8561. this.removeInteractiveTarget(this._tooltip._container);
  8562. }
  8563. }
  8564. return this;
  8565. },
  8566. // @method toggleTooltip(): this
  8567. // Opens or closes the tooltip bound to this layer depending on its current state.
  8568. toggleTooltip: function (target) {
  8569. if (this._tooltip) {
  8570. if (this._tooltip._map) {
  8571. this.closeTooltip();
  8572. } else {
  8573. this.openTooltip(target);
  8574. }
  8575. }
  8576. return this;
  8577. },
  8578. // @method isTooltipOpen(): boolean
  8579. // Returns `true` if the tooltip bound to this layer is currently open.
  8580. isTooltipOpen: function () {
  8581. return this._tooltip.isOpen();
  8582. },
  8583. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8584. // Sets the content of the tooltip bound to this layer.
  8585. setTooltipContent: function (content) {
  8586. if (this._tooltip) {
  8587. this._tooltip.setContent(content);
  8588. }
  8589. return this;
  8590. },
  8591. // @method getTooltip(): Tooltip
  8592. // Returns the tooltip bound to this layer.
  8593. getTooltip: function () {
  8594. return this._tooltip;
  8595. },
  8596. _openTooltip: function (e) {
  8597. var layer = e.layer || e.target;
  8598. if (!this._tooltip || !this._map) {
  8599. return;
  8600. }
  8601. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  8602. },
  8603. _moveTooltip: function (e) {
  8604. var latlng = e.latlng, containerPoint, layerPoint;
  8605. if (this._tooltip.options.sticky && e.originalEvent) {
  8606. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  8607. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  8608. latlng = this._map.layerPointToLatLng(layerPoint);
  8609. }
  8610. this._tooltip.setLatLng(latlng);
  8611. }
  8612. });
  8613. /*
  8614. * @class DivIcon
  8615. * @aka L.DivIcon
  8616. * @inherits Icon
  8617. *
  8618. * Represents a lightweight icon for markers that uses a simple `<div>`
  8619. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  8620. *
  8621. * @example
  8622. * ```js
  8623. * var myIcon = L.divIcon({className: 'my-div-icon'});
  8624. * // you can set .my-div-icon styles in CSS
  8625. *
  8626. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  8627. * ```
  8628. *
  8629. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  8630. */
  8631. var DivIcon = Icon.extend({
  8632. options: {
  8633. // @section
  8634. // @aka DivIcon options
  8635. iconSize: [12, 12], // also can be set through CSS
  8636. // iconAnchor: (Point),
  8637. // popupAnchor: (Point),
  8638. // @option html: String|HTMLElement = ''
  8639. // Custom HTML code to put inside the div element, empty by default. Alternatively,
  8640. // an instance of `HTMLElement`.
  8641. html: false,
  8642. // @option bgPos: Point = [0, 0]
  8643. // Optional relative position of the background, in pixels
  8644. bgPos: null,
  8645. className: 'leaflet-div-icon'
  8646. },
  8647. createIcon: function (oldIcon) {
  8648. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  8649. options = this.options;
  8650. if (options.html instanceof Element) {
  8651. empty(div);
  8652. div.appendChild(options.html);
  8653. } else {
  8654. div.innerHTML = options.html !== false ? options.html : '';
  8655. }
  8656. if (options.bgPos) {
  8657. var bgPos = toPoint(options.bgPos);
  8658. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  8659. }
  8660. this._setIconStyles(div, 'icon');
  8661. return div;
  8662. },
  8663. createShadow: function () {
  8664. return null;
  8665. }
  8666. });
  8667. // @factory L.divIcon(options: DivIcon options)
  8668. // Creates a `DivIcon` instance with the given options.
  8669. function divIcon(options) {
  8670. return new DivIcon(options);
  8671. }
  8672. Icon.Default = IconDefault;
  8673. /*
  8674. * @class GridLayer
  8675. * @inherits Layer
  8676. * @aka L.GridLayer
  8677. *
  8678. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  8679. * 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.
  8680. *
  8681. *
  8682. * @section Synchronous usage
  8683. * @example
  8684. *
  8685. * 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.
  8686. *
  8687. * ```js
  8688. * var CanvasLayer = L.GridLayer.extend({
  8689. * createTile: function(coords){
  8690. * // create a <canvas> element for drawing
  8691. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8692. *
  8693. * // setup tile width and height according to the options
  8694. * var size = this.getTileSize();
  8695. * tile.width = size.x;
  8696. * tile.height = size.y;
  8697. *
  8698. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  8699. * var ctx = tile.getContext('2d');
  8700. *
  8701. * // return the tile so it can be rendered on screen
  8702. * return tile;
  8703. * }
  8704. * });
  8705. * ```
  8706. *
  8707. * @section Asynchronous usage
  8708. * @example
  8709. *
  8710. * 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.
  8711. *
  8712. * ```js
  8713. * var CanvasLayer = L.GridLayer.extend({
  8714. * createTile: function(coords, done){
  8715. * var error;
  8716. *
  8717. * // create a <canvas> element for drawing
  8718. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8719. *
  8720. * // setup tile width and height according to the options
  8721. * var size = this.getTileSize();
  8722. * tile.width = size.x;
  8723. * tile.height = size.y;
  8724. *
  8725. * // draw something asynchronously and pass the tile to the done() callback
  8726. * setTimeout(function() {
  8727. * done(error, tile);
  8728. * }, 1000);
  8729. *
  8730. * return tile;
  8731. * }
  8732. * });
  8733. * ```
  8734. *
  8735. * @section
  8736. */
  8737. var GridLayer = Layer.extend({
  8738. // @section
  8739. // @aka GridLayer options
  8740. options: {
  8741. // @option tileSize: Number|Point = 256
  8742. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  8743. tileSize: 256,
  8744. // @option opacity: Number = 1.0
  8745. // Opacity of the tiles. Can be used in the `createTile()` function.
  8746. opacity: 1,
  8747. // @option updateWhenIdle: Boolean = (depends)
  8748. // Load new tiles only when panning ends.
  8749. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  8750. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  8751. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  8752. updateWhenIdle: mobile,
  8753. // @option updateWhenZooming: Boolean = true
  8754. // 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.
  8755. updateWhenZooming: true,
  8756. // @option updateInterval: Number = 200
  8757. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  8758. updateInterval: 200,
  8759. // @option zIndex: Number = 1
  8760. // The explicit zIndex of the tile layer.
  8761. zIndex: 1,
  8762. // @option bounds: LatLngBounds = undefined
  8763. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  8764. bounds: null,
  8765. // @option minZoom: Number = 0
  8766. // The minimum zoom level down to which this layer will be displayed (inclusive).
  8767. minZoom: 0,
  8768. // @option maxZoom: Number = undefined
  8769. // The maximum zoom level up to which this layer will be displayed (inclusive).
  8770. maxZoom: undefined,
  8771. // @option maxNativeZoom: Number = undefined
  8772. // Maximum zoom number the tile source has available. If it is specified,
  8773. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  8774. // from `maxNativeZoom` level and auto-scaled.
  8775. maxNativeZoom: undefined,
  8776. // @option minNativeZoom: Number = undefined
  8777. // Minimum zoom number the tile source has available. If it is specified,
  8778. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  8779. // from `minNativeZoom` level and auto-scaled.
  8780. minNativeZoom: undefined,
  8781. // @option noWrap: Boolean = false
  8782. // Whether the layer is wrapped around the antimeridian. If `true`, the
  8783. // GridLayer will only be displayed once at low zoom levels. Has no
  8784. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  8785. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  8786. // tiles outside the CRS limits.
  8787. noWrap: false,
  8788. // @option pane: String = 'tilePane'
  8789. // `Map pane` where the grid layer will be added.
  8790. pane: 'tilePane',
  8791. // @option className: String = ''
  8792. // A custom class name to assign to the tile layer. Empty by default.
  8793. className: '',
  8794. // @option keepBuffer: Number = 2
  8795. // When panning the map, keep this many rows and columns of tiles before unloading them.
  8796. keepBuffer: 2
  8797. },
  8798. initialize: function (options) {
  8799. setOptions(this, options);
  8800. },
  8801. onAdd: function () {
  8802. this._initContainer();
  8803. this._levels = {};
  8804. this._tiles = {};
  8805. this._resetView();
  8806. this._update();
  8807. },
  8808. beforeAdd: function (map) {
  8809. map._addZoomLimit(this);
  8810. },
  8811. onRemove: function (map) {
  8812. this._removeAllTiles();
  8813. remove(this._container);
  8814. map._removeZoomLimit(this);
  8815. this._container = null;
  8816. this._tileZoom = undefined;
  8817. },
  8818. // @method bringToFront: this
  8819. // Brings the tile layer to the top of all tile layers.
  8820. bringToFront: function () {
  8821. if (this._map) {
  8822. toFront(this._container);
  8823. this._setAutoZIndex(Math.max);
  8824. }
  8825. return this;
  8826. },
  8827. // @method bringToBack: this
  8828. // Brings the tile layer to the bottom of all tile layers.
  8829. bringToBack: function () {
  8830. if (this._map) {
  8831. toBack(this._container);
  8832. this._setAutoZIndex(Math.min);
  8833. }
  8834. return this;
  8835. },
  8836. // @method getContainer: HTMLElement
  8837. // Returns the HTML element that contains the tiles for this layer.
  8838. getContainer: function () {
  8839. return this._container;
  8840. },
  8841. // @method setOpacity(opacity: Number): this
  8842. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  8843. setOpacity: function (opacity) {
  8844. this.options.opacity = opacity;
  8845. this._updateOpacity();
  8846. return this;
  8847. },
  8848. // @method setZIndex(zIndex: Number): this
  8849. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  8850. setZIndex: function (zIndex) {
  8851. this.options.zIndex = zIndex;
  8852. this._updateZIndex();
  8853. return this;
  8854. },
  8855. // @method isLoading: Boolean
  8856. // Returns `true` if any tile in the grid layer has not finished loading.
  8857. isLoading: function () {
  8858. return this._loading;
  8859. },
  8860. // @method redraw: this
  8861. // Causes the layer to clear all the tiles and request them again.
  8862. redraw: function () {
  8863. if (this._map) {
  8864. this._removeAllTiles();
  8865. this._update();
  8866. }
  8867. return this;
  8868. },
  8869. getEvents: function () {
  8870. var events = {
  8871. viewprereset: this._invalidateAll,
  8872. viewreset: this._resetView,
  8873. zoom: this._resetView,
  8874. moveend: this._onMoveEnd
  8875. };
  8876. if (!this.options.updateWhenIdle) {
  8877. // update tiles on move, but not more often than once per given interval
  8878. if (!this._onMove) {
  8879. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  8880. }
  8881. events.move = this._onMove;
  8882. }
  8883. if (this._zoomAnimated) {
  8884. events.zoomanim = this._animateZoom;
  8885. }
  8886. return events;
  8887. },
  8888. // @section Extension methods
  8889. // Layers extending `GridLayer` shall reimplement the following method.
  8890. // @method createTile(coords: Object, done?: Function): HTMLElement
  8891. // Called only internally, must be overridden by classes extending `GridLayer`.
  8892. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  8893. // is specified, it must be called when the tile has finished loading and drawing.
  8894. createTile: function () {
  8895. return document.createElement('div');
  8896. },
  8897. // @section
  8898. // @method getTileSize: Point
  8899. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  8900. getTileSize: function () {
  8901. var s = this.options.tileSize;
  8902. return s instanceof Point ? s : new Point(s, s);
  8903. },
  8904. _updateZIndex: function () {
  8905. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  8906. this._container.style.zIndex = this.options.zIndex;
  8907. }
  8908. },
  8909. _setAutoZIndex: function (compare) {
  8910. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  8911. var layers = this.getPane().children,
  8912. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  8913. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  8914. zIndex = layers[i].style.zIndex;
  8915. if (layers[i] !== this._container && zIndex) {
  8916. edgeZIndex = compare(edgeZIndex, +zIndex);
  8917. }
  8918. }
  8919. if (isFinite(edgeZIndex)) {
  8920. this.options.zIndex = edgeZIndex + compare(-1, 1);
  8921. this._updateZIndex();
  8922. }
  8923. },
  8924. _updateOpacity: function () {
  8925. if (!this._map) { return; }
  8926. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  8927. if (ielt9) { return; }
  8928. setOpacity(this._container, this.options.opacity);
  8929. var now = +new Date(),
  8930. nextFrame = false,
  8931. willPrune = false;
  8932. for (var key in this._tiles) {
  8933. var tile = this._tiles[key];
  8934. if (!tile.current || !tile.loaded) { continue; }
  8935. var fade = Math.min(1, (now - tile.loaded) / 200);
  8936. setOpacity(tile.el, fade);
  8937. if (fade < 1) {
  8938. nextFrame = true;
  8939. } else {
  8940. if (tile.active) {
  8941. willPrune = true;
  8942. } else {
  8943. this._onOpaqueTile(tile);
  8944. }
  8945. tile.active = true;
  8946. }
  8947. }
  8948. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  8949. if (nextFrame) {
  8950. cancelAnimFrame(this._fadeFrame);
  8951. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  8952. }
  8953. },
  8954. _onOpaqueTile: falseFn,
  8955. _initContainer: function () {
  8956. if (this._container) { return; }
  8957. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  8958. this._updateZIndex();
  8959. if (this.options.opacity < 1) {
  8960. this._updateOpacity();
  8961. }
  8962. this.getPane().appendChild(this._container);
  8963. },
  8964. _updateLevels: function () {
  8965. var zoom = this._tileZoom,
  8966. maxZoom = this.options.maxZoom;
  8967. if (zoom === undefined) { return undefined; }
  8968. for (var z in this._levels) {
  8969. if (this._levels[z].el.children.length || z === zoom) {
  8970. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  8971. this._onUpdateLevel(z);
  8972. } else {
  8973. remove(this._levels[z].el);
  8974. this._removeTilesAtZoom(z);
  8975. this._onRemoveLevel(z);
  8976. delete this._levels[z];
  8977. }
  8978. }
  8979. var level = this._levels[zoom],
  8980. map = this._map;
  8981. if (!level) {
  8982. level = this._levels[zoom] = {};
  8983. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  8984. level.el.style.zIndex = maxZoom;
  8985. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  8986. level.zoom = zoom;
  8987. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  8988. // force the browser to consider the newly added element for transition
  8989. falseFn(level.el.offsetWidth);
  8990. this._onCreateLevel(level);
  8991. }
  8992. this._level = level;
  8993. return level;
  8994. },
  8995. _onUpdateLevel: falseFn,
  8996. _onRemoveLevel: falseFn,
  8997. _onCreateLevel: falseFn,
  8998. _pruneTiles: function () {
  8999. if (!this._map) {
  9000. return;
  9001. }
  9002. var key, tile;
  9003. var zoom = this._map.getZoom();
  9004. if (zoom > this.options.maxZoom ||
  9005. zoom < this.options.minZoom) {
  9006. this._removeAllTiles();
  9007. return;
  9008. }
  9009. for (key in this._tiles) {
  9010. tile = this._tiles[key];
  9011. tile.retain = tile.current;
  9012. }
  9013. for (key in this._tiles) {
  9014. tile = this._tiles[key];
  9015. if (tile.current && !tile.active) {
  9016. var coords = tile.coords;
  9017. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  9018. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  9019. }
  9020. }
  9021. }
  9022. for (key in this._tiles) {
  9023. if (!this._tiles[key].retain) {
  9024. this._removeTile(key);
  9025. }
  9026. }
  9027. },
  9028. _removeTilesAtZoom: function (zoom) {
  9029. for (var key in this._tiles) {
  9030. if (this._tiles[key].coords.z !== zoom) {
  9031. continue;
  9032. }
  9033. this._removeTile(key);
  9034. }
  9035. },
  9036. _removeAllTiles: function () {
  9037. for (var key in this._tiles) {
  9038. this._removeTile(key);
  9039. }
  9040. },
  9041. _invalidateAll: function () {
  9042. for (var z in this._levels) {
  9043. remove(this._levels[z].el);
  9044. this._onRemoveLevel(z);
  9045. delete this._levels[z];
  9046. }
  9047. this._removeAllTiles();
  9048. this._tileZoom = undefined;
  9049. },
  9050. _retainParent: function (x, y, z, minZoom) {
  9051. var x2 = Math.floor(x / 2),
  9052. y2 = Math.floor(y / 2),
  9053. z2 = z - 1,
  9054. coords2 = new Point(+x2, +y2);
  9055. coords2.z = +z2;
  9056. var key = this._tileCoordsToKey(coords2),
  9057. tile = this._tiles[key];
  9058. if (tile && tile.active) {
  9059. tile.retain = true;
  9060. return true;
  9061. } else if (tile && tile.loaded) {
  9062. tile.retain = true;
  9063. }
  9064. if (z2 > minZoom) {
  9065. return this._retainParent(x2, y2, z2, minZoom);
  9066. }
  9067. return false;
  9068. },
  9069. _retainChildren: function (x, y, z, maxZoom) {
  9070. for (var i = 2 * x; i < 2 * x + 2; i++) {
  9071. for (var j = 2 * y; j < 2 * y + 2; j++) {
  9072. var coords = new Point(i, j);
  9073. coords.z = z + 1;
  9074. var key = this._tileCoordsToKey(coords),
  9075. tile = this._tiles[key];
  9076. if (tile && tile.active) {
  9077. tile.retain = true;
  9078. continue;
  9079. } else if (tile && tile.loaded) {
  9080. tile.retain = true;
  9081. }
  9082. if (z + 1 < maxZoom) {
  9083. this._retainChildren(i, j, z + 1, maxZoom);
  9084. }
  9085. }
  9086. }
  9087. },
  9088. _resetView: function (e) {
  9089. var animating = e && (e.pinch || e.flyTo);
  9090. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  9091. },
  9092. _animateZoom: function (e) {
  9093. this._setView(e.center, e.zoom, true, e.noUpdate);
  9094. },
  9095. _clampZoom: function (zoom) {
  9096. var options = this.options;
  9097. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  9098. return options.minNativeZoom;
  9099. }
  9100. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  9101. return options.maxNativeZoom;
  9102. }
  9103. return zoom;
  9104. },
  9105. _setView: function (center, zoom, noPrune, noUpdate) {
  9106. var tileZoom = this._clampZoom(Math.round(zoom));
  9107. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  9108. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  9109. tileZoom = undefined;
  9110. }
  9111. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  9112. if (!noUpdate || tileZoomChanged) {
  9113. this._tileZoom = tileZoom;
  9114. if (this._abortLoading) {
  9115. this._abortLoading();
  9116. }
  9117. this._updateLevels();
  9118. this._resetGrid();
  9119. if (tileZoom !== undefined) {
  9120. this._update(center);
  9121. }
  9122. if (!noPrune) {
  9123. this._pruneTiles();
  9124. }
  9125. // Flag to prevent _updateOpacity from pruning tiles during
  9126. // a zoom anim or a pinch gesture
  9127. this._noPrune = !!noPrune;
  9128. }
  9129. this._setZoomTransforms(center, zoom);
  9130. },
  9131. _setZoomTransforms: function (center, zoom) {
  9132. for (var i in this._levels) {
  9133. this._setZoomTransform(this._levels[i], center, zoom);
  9134. }
  9135. },
  9136. _setZoomTransform: function (level, center, zoom) {
  9137. var scale = this._map.getZoomScale(zoom, level.zoom),
  9138. translate = level.origin.multiplyBy(scale)
  9139. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  9140. if (any3d) {
  9141. setTransform(level.el, translate, scale);
  9142. } else {
  9143. setPosition(level.el, translate);
  9144. }
  9145. },
  9146. _resetGrid: function () {
  9147. var map = this._map,
  9148. crs = map.options.crs,
  9149. tileSize = this._tileSize = this.getTileSize(),
  9150. tileZoom = this._tileZoom;
  9151. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  9152. if (bounds) {
  9153. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  9154. }
  9155. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  9156. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  9157. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  9158. ];
  9159. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  9160. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  9161. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  9162. ];
  9163. },
  9164. _onMoveEnd: function () {
  9165. if (!this._map || this._map._animatingZoom) { return; }
  9166. this._update();
  9167. },
  9168. _getTiledPixelBounds: function (center) {
  9169. var map = this._map,
  9170. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9171. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9172. pixelCenter = map.project(center, this._tileZoom).floor(),
  9173. halfSize = map.getSize().divideBy(scale * 2);
  9174. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9175. },
  9176. // Private method to load tiles in the grid's active zoom level according to map bounds
  9177. _update: function (center) {
  9178. var map = this._map;
  9179. if (!map) { return; }
  9180. var zoom = this._clampZoom(map.getZoom());
  9181. if (center === undefined) { center = map.getCenter(); }
  9182. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  9183. var pixelBounds = this._getTiledPixelBounds(center),
  9184. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9185. tileCenter = tileRange.getCenter(),
  9186. queue = [],
  9187. margin = this.options.keepBuffer,
  9188. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9189. tileRange.getTopRight().add([margin, -margin]));
  9190. // Sanity check: panic if the tile range contains Infinity somewhere.
  9191. if (!(isFinite(tileRange.min.x) &&
  9192. isFinite(tileRange.min.y) &&
  9193. isFinite(tileRange.max.x) &&
  9194. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  9195. for (var key in this._tiles) {
  9196. var c = this._tiles[key].coords;
  9197. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9198. this._tiles[key].current = false;
  9199. }
  9200. }
  9201. // _update just loads more tiles. If the tile zoom level differs too much
  9202. // from the map's, let _setView reset levels and prune old tiles.
  9203. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  9204. // create a queue of coordinates to load tiles from
  9205. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9206. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9207. var coords = new Point(i, j);
  9208. coords.z = this._tileZoom;
  9209. if (!this._isValidTile(coords)) { continue; }
  9210. var tile = this._tiles[this._tileCoordsToKey(coords)];
  9211. if (tile) {
  9212. tile.current = true;
  9213. } else {
  9214. queue.push(coords);
  9215. }
  9216. }
  9217. }
  9218. // sort tile queue to load tiles in order of their distance to center
  9219. queue.sort(function (a, b) {
  9220. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9221. });
  9222. if (queue.length !== 0) {
  9223. // if it's the first batch of tiles to load
  9224. if (!this._loading) {
  9225. this._loading = true;
  9226. // @event loading: Event
  9227. // Fired when the grid layer starts loading tiles.
  9228. this.fire('loading');
  9229. }
  9230. // create DOM fragment to append tiles in one batch
  9231. var fragment = document.createDocumentFragment();
  9232. for (i = 0; i < queue.length; i++) {
  9233. this._addTile(queue[i], fragment);
  9234. }
  9235. this._level.el.appendChild(fragment);
  9236. }
  9237. },
  9238. _isValidTile: function (coords) {
  9239. var crs = this._map.options.crs;
  9240. if (!crs.infinite) {
  9241. // don't load tile if it's out of bounds and not wrapped
  9242. var bounds = this._globalTileRange;
  9243. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9244. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  9245. }
  9246. if (!this.options.bounds) { return true; }
  9247. // don't load tile if it doesn't intersect the bounds in options
  9248. var tileBounds = this._tileCoordsToBounds(coords);
  9249. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9250. },
  9251. _keyToBounds: function (key) {
  9252. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9253. },
  9254. _tileCoordsToNwSe: function (coords) {
  9255. var map = this._map,
  9256. tileSize = this.getTileSize(),
  9257. nwPoint = coords.scaleBy(tileSize),
  9258. sePoint = nwPoint.add(tileSize),
  9259. nw = map.unproject(nwPoint, coords.z),
  9260. se = map.unproject(sePoint, coords.z);
  9261. return [nw, se];
  9262. },
  9263. // converts tile coordinates to its geographical bounds
  9264. _tileCoordsToBounds: function (coords) {
  9265. var bp = this._tileCoordsToNwSe(coords),
  9266. bounds = new LatLngBounds(bp[0], bp[1]);
  9267. if (!this.options.noWrap) {
  9268. bounds = this._map.wrapLatLngBounds(bounds);
  9269. }
  9270. return bounds;
  9271. },
  9272. // converts tile coordinates to key for the tile cache
  9273. _tileCoordsToKey: function (coords) {
  9274. return coords.x + ':' + coords.y + ':' + coords.z;
  9275. },
  9276. // converts tile cache key to coordinates
  9277. _keyToTileCoords: function (key) {
  9278. var k = key.split(':'),
  9279. coords = new Point(+k[0], +k[1]);
  9280. coords.z = +k[2];
  9281. return coords;
  9282. },
  9283. _removeTile: function (key) {
  9284. var tile = this._tiles[key];
  9285. if (!tile) { return; }
  9286. remove(tile.el);
  9287. delete this._tiles[key];
  9288. // @event tileunload: TileEvent
  9289. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9290. this.fire('tileunload', {
  9291. tile: tile.el,
  9292. coords: this._keyToTileCoords(key)
  9293. });
  9294. },
  9295. _initTile: function (tile) {
  9296. addClass(tile, 'leaflet-tile');
  9297. var tileSize = this.getTileSize();
  9298. tile.style.width = tileSize.x + 'px';
  9299. tile.style.height = tileSize.y + 'px';
  9300. tile.onselectstart = falseFn;
  9301. tile.onmousemove = falseFn;
  9302. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9303. if (ielt9 && this.options.opacity < 1) {
  9304. setOpacity(tile, this.options.opacity);
  9305. }
  9306. // without this hack, tiles disappear after zoom on Chrome for Android
  9307. // https://github.com/Leaflet/Leaflet/issues/2078
  9308. if (android && !android23) {
  9309. tile.style.WebkitBackfaceVisibility = 'hidden';
  9310. }
  9311. },
  9312. _addTile: function (coords, container) {
  9313. var tilePos = this._getTilePos(coords),
  9314. key = this._tileCoordsToKey(coords);
  9315. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9316. this._initTile(tile);
  9317. // if createTile is defined with a second argument ("done" callback),
  9318. // we know that tile is async and will be ready later; otherwise
  9319. if (this.createTile.length < 2) {
  9320. // mark tile as ready, but delay one frame for opacity animation to happen
  9321. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9322. }
  9323. setPosition(tile, tilePos);
  9324. // save tile in cache
  9325. this._tiles[key] = {
  9326. el: tile,
  9327. coords: coords,
  9328. current: true
  9329. };
  9330. container.appendChild(tile);
  9331. // @event tileloadstart: TileEvent
  9332. // Fired when a tile is requested and starts loading.
  9333. this.fire('tileloadstart', {
  9334. tile: tile,
  9335. coords: coords
  9336. });
  9337. },
  9338. _tileReady: function (coords, err, tile) {
  9339. if (err) {
  9340. // @event tileerror: TileErrorEvent
  9341. // Fired when there is an error loading a tile.
  9342. this.fire('tileerror', {
  9343. error: err,
  9344. tile: tile,
  9345. coords: coords
  9346. });
  9347. }
  9348. var key = this._tileCoordsToKey(coords);
  9349. tile = this._tiles[key];
  9350. if (!tile) { return; }
  9351. tile.loaded = +new Date();
  9352. if (this._map._fadeAnimated) {
  9353. setOpacity(tile.el, 0);
  9354. cancelAnimFrame(this._fadeFrame);
  9355. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9356. } else {
  9357. tile.active = true;
  9358. this._pruneTiles();
  9359. }
  9360. if (!err) {
  9361. addClass(tile.el, 'leaflet-tile-loaded');
  9362. // @event tileload: TileEvent
  9363. // Fired when a tile loads.
  9364. this.fire('tileload', {
  9365. tile: tile.el,
  9366. coords: coords
  9367. });
  9368. }
  9369. if (this._noTilesToLoad()) {
  9370. this._loading = false;
  9371. // @event load: Event
  9372. // Fired when the grid layer loaded all visible tiles.
  9373. this.fire('load');
  9374. if (ielt9 || !this._map._fadeAnimated) {
  9375. requestAnimFrame(this._pruneTiles, this);
  9376. } else {
  9377. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9378. // to trigger a pruning.
  9379. setTimeout(bind(this._pruneTiles, this), 250);
  9380. }
  9381. }
  9382. },
  9383. _getTilePos: function (coords) {
  9384. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9385. },
  9386. _wrapCoords: function (coords) {
  9387. var newCoords = new Point(
  9388. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9389. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9390. newCoords.z = coords.z;
  9391. return newCoords;
  9392. },
  9393. _pxBoundsToTileRange: function (bounds) {
  9394. var tileSize = this.getTileSize();
  9395. return new Bounds(
  9396. bounds.min.unscaleBy(tileSize).floor(),
  9397. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9398. },
  9399. _noTilesToLoad: function () {
  9400. for (var key in this._tiles) {
  9401. if (!this._tiles[key].loaded) { return false; }
  9402. }
  9403. return true;
  9404. }
  9405. });
  9406. // @factory L.gridLayer(options?: GridLayer options)
  9407. // Creates a new instance of GridLayer with the supplied options.
  9408. function gridLayer(options) {
  9409. return new GridLayer(options);
  9410. }
  9411. /*
  9412. * @class TileLayer
  9413. * @inherits GridLayer
  9414. * @aka L.TileLayer
  9415. * 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`.
  9416. *
  9417. * @example
  9418. *
  9419. * ```js
  9420. * 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);
  9421. * ```
  9422. *
  9423. * @section URL template
  9424. * @example
  9425. *
  9426. * A string of the following form:
  9427. *
  9428. * ```
  9429. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9430. * ```
  9431. *
  9432. * `{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.
  9433. *
  9434. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9435. *
  9436. * ```
  9437. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9438. * ```
  9439. */
  9440. var TileLayer = GridLayer.extend({
  9441. // @section
  9442. // @aka TileLayer options
  9443. options: {
  9444. // @option minZoom: Number = 0
  9445. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9446. minZoom: 0,
  9447. // @option maxZoom: Number = 18
  9448. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9449. maxZoom: 18,
  9450. // @option subdomains: String|String[] = 'abc'
  9451. // 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.
  9452. subdomains: 'abc',
  9453. // @option errorTileUrl: String = ''
  9454. // URL to the tile image to show in place of the tile that failed to load.
  9455. errorTileUrl: '',
  9456. // @option zoomOffset: Number = 0
  9457. // The zoom number used in tile URLs will be offset with this value.
  9458. zoomOffset: 0,
  9459. // @option tms: Boolean = false
  9460. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9461. tms: false,
  9462. // @option zoomReverse: Boolean = false
  9463. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9464. zoomReverse: false,
  9465. // @option detectRetina: Boolean = false
  9466. // 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.
  9467. detectRetina: false,
  9468. // @option crossOrigin: Boolean|String = false
  9469. // Whether the crossOrigin attribute will be added to the tiles.
  9470. // 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.
  9471. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  9472. crossOrigin: false
  9473. },
  9474. initialize: function (url, options) {
  9475. this._url = url;
  9476. options = setOptions(this, options);
  9477. // detecting retina displays, adjusting tileSize and zoom levels
  9478. if (options.detectRetina && retina && options.maxZoom > 0) {
  9479. options.tileSize = Math.floor(options.tileSize / 2);
  9480. if (!options.zoomReverse) {
  9481. options.zoomOffset++;
  9482. options.maxZoom--;
  9483. } else {
  9484. options.zoomOffset--;
  9485. options.minZoom++;
  9486. }
  9487. options.minZoom = Math.max(0, options.minZoom);
  9488. }
  9489. if (typeof options.subdomains === 'string') {
  9490. options.subdomains = options.subdomains.split('');
  9491. }
  9492. // for https://github.com/Leaflet/Leaflet/issues/137
  9493. if (!android) {
  9494. this.on('tileunload', this._onTileRemove);
  9495. }
  9496. },
  9497. // @method setUrl(url: String, noRedraw?: Boolean): this
  9498. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9499. // If the URL does not change, the layer will not be redrawn unless
  9500. // the noRedraw parameter is set to false.
  9501. setUrl: function (url, noRedraw) {
  9502. if (this._url === url && noRedraw === undefined) {
  9503. noRedraw = true;
  9504. }
  9505. this._url = url;
  9506. if (!noRedraw) {
  9507. this.redraw();
  9508. }
  9509. return this;
  9510. },
  9511. // @method createTile(coords: Object, done?: Function): HTMLElement
  9512. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9513. // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
  9514. // callback is called when the tile has been loaded.
  9515. createTile: function (coords, done) {
  9516. var tile = document.createElement('img');
  9517. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9518. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9519. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  9520. tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  9521. }
  9522. /*
  9523. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  9524. http://www.w3.org/TR/WCAG20-TECHS/H67
  9525. */
  9526. tile.alt = '';
  9527. /*
  9528. Set role="presentation" to force screen readers to ignore this
  9529. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  9530. */
  9531. tile.setAttribute('role', 'presentation');
  9532. tile.src = this.getTileUrl(coords);
  9533. return tile;
  9534. },
  9535. // @section Extension methods
  9536. // @uninheritable
  9537. // Layers extending `TileLayer` might reimplement the following method.
  9538. // @method getTileUrl(coords: Object): String
  9539. // Called only internally, returns the URL for a tile given its coordinates.
  9540. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9541. getTileUrl: function (coords) {
  9542. var data = {
  9543. r: retina ? '@2x' : '',
  9544. s: this._getSubdomain(coords),
  9545. x: coords.x,
  9546. y: coords.y,
  9547. z: this._getZoomForUrl()
  9548. };
  9549. if (this._map && !this._map.options.crs.infinite) {
  9550. var invertedY = this._globalTileRange.max.y - coords.y;
  9551. if (this.options.tms) {
  9552. data['y'] = invertedY;
  9553. }
  9554. data['-y'] = invertedY;
  9555. }
  9556. return template(this._url, extend(data, this.options));
  9557. },
  9558. _tileOnLoad: function (done, tile) {
  9559. // For https://github.com/Leaflet/Leaflet/issues/3332
  9560. if (ielt9) {
  9561. setTimeout(bind(done, this, null, tile), 0);
  9562. } else {
  9563. done(null, tile);
  9564. }
  9565. },
  9566. _tileOnError: function (done, tile, e) {
  9567. var errorUrl = this.options.errorTileUrl;
  9568. if (errorUrl && tile.getAttribute('src') !== errorUrl) {
  9569. tile.src = errorUrl;
  9570. }
  9571. done(e, tile);
  9572. },
  9573. _onTileRemove: function (e) {
  9574. e.tile.onload = null;
  9575. },
  9576. _getZoomForUrl: function () {
  9577. var zoom = this._tileZoom,
  9578. maxZoom = this.options.maxZoom,
  9579. zoomReverse = this.options.zoomReverse,
  9580. zoomOffset = this.options.zoomOffset;
  9581. if (zoomReverse) {
  9582. zoom = maxZoom - zoom;
  9583. }
  9584. return zoom + zoomOffset;
  9585. },
  9586. _getSubdomain: function (tilePoint) {
  9587. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  9588. return this.options.subdomains[index];
  9589. },
  9590. // stops loading all tiles in the background layer
  9591. _abortLoading: function () {
  9592. var i, tile;
  9593. for (i in this._tiles) {
  9594. if (this._tiles[i].coords.z !== this._tileZoom) {
  9595. tile = this._tiles[i].el;
  9596. tile.onload = falseFn;
  9597. tile.onerror = falseFn;
  9598. if (!tile.complete) {
  9599. tile.src = emptyImageUrl;
  9600. remove(tile);
  9601. delete this._tiles[i];
  9602. }
  9603. }
  9604. }
  9605. },
  9606. _removeTile: function (key) {
  9607. var tile = this._tiles[key];
  9608. if (!tile) { return; }
  9609. // Cancels any pending http requests associated with the tile
  9610. // unless we're on Android's stock browser,
  9611. // see https://github.com/Leaflet/Leaflet/issues/137
  9612. if (!androidStock) {
  9613. tile.el.setAttribute('src', emptyImageUrl);
  9614. }
  9615. return GridLayer.prototype._removeTile.call(this, key);
  9616. },
  9617. _tileReady: function (coords, err, tile) {
  9618. if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) {
  9619. return;
  9620. }
  9621. return GridLayer.prototype._tileReady.call(this, coords, err, tile);
  9622. }
  9623. });
  9624. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  9625. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  9626. function tileLayer(url, options) {
  9627. return new TileLayer(url, options);
  9628. }
  9629. /*
  9630. * @class TileLayer.WMS
  9631. * @inherits TileLayer
  9632. * @aka L.TileLayer.WMS
  9633. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  9634. *
  9635. * @example
  9636. *
  9637. * ```js
  9638. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  9639. * layers: 'nexrad-n0r-900913',
  9640. * format: 'image/png',
  9641. * transparent: true,
  9642. * attribution: "Weather data © 2012 IEM Nexrad"
  9643. * });
  9644. * ```
  9645. */
  9646. var TileLayerWMS = TileLayer.extend({
  9647. // @section
  9648. // @aka TileLayer.WMS options
  9649. // If any custom options not documented here are used, they will be sent to the
  9650. // WMS server as extra parameters in each request URL. This can be useful for
  9651. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  9652. defaultWmsParams: {
  9653. service: 'WMS',
  9654. request: 'GetMap',
  9655. // @option layers: String = ''
  9656. // **(required)** Comma-separated list of WMS layers to show.
  9657. layers: '',
  9658. // @option styles: String = ''
  9659. // Comma-separated list of WMS styles.
  9660. styles: '',
  9661. // @option format: String = 'image/jpeg'
  9662. // WMS image format (use `'image/png'` for layers with transparency).
  9663. format: 'image/jpeg',
  9664. // @option transparent: Boolean = false
  9665. // If `true`, the WMS service will return images with transparency.
  9666. transparent: false,
  9667. // @option version: String = '1.1.1'
  9668. // Version of the WMS service to use
  9669. version: '1.1.1'
  9670. },
  9671. options: {
  9672. // @option crs: CRS = null
  9673. // Coordinate Reference System to use for the WMS requests, defaults to
  9674. // map CRS. Don't change this if you're not sure what it means.
  9675. crs: null,
  9676. // @option uppercase: Boolean = false
  9677. // If `true`, WMS request parameter keys will be uppercase.
  9678. uppercase: false
  9679. },
  9680. initialize: function (url, options) {
  9681. this._url = url;
  9682. var wmsParams = extend({}, this.defaultWmsParams);
  9683. // all keys that are not TileLayer options go to WMS params
  9684. for (var i in options) {
  9685. if (!(i in this.options)) {
  9686. wmsParams[i] = options[i];
  9687. }
  9688. }
  9689. options = setOptions(this, options);
  9690. var realRetina = options.detectRetina && retina ? 2 : 1;
  9691. var tileSize = this.getTileSize();
  9692. wmsParams.width = tileSize.x * realRetina;
  9693. wmsParams.height = tileSize.y * realRetina;
  9694. this.wmsParams = wmsParams;
  9695. },
  9696. onAdd: function (map) {
  9697. this._crs = this.options.crs || map.options.crs;
  9698. this._wmsVersion = parseFloat(this.wmsParams.version);
  9699. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  9700. this.wmsParams[projectionKey] = this._crs.code;
  9701. TileLayer.prototype.onAdd.call(this, map);
  9702. },
  9703. getTileUrl: function (coords) {
  9704. var tileBounds = this._tileCoordsToNwSe(coords),
  9705. crs = this._crs,
  9706. bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
  9707. min = bounds.min,
  9708. max = bounds.max,
  9709. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  9710. [min.y, min.x, max.y, max.x] :
  9711. [min.x, min.y, max.x, max.y]).join(','),
  9712. url = TileLayer.prototype.getTileUrl.call(this, coords);
  9713. return url +
  9714. getParamString(this.wmsParams, url, this.options.uppercase) +
  9715. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  9716. },
  9717. // @method setParams(params: Object, noRedraw?: Boolean): this
  9718. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  9719. setParams: function (params, noRedraw) {
  9720. extend(this.wmsParams, params);
  9721. if (!noRedraw) {
  9722. this.redraw();
  9723. }
  9724. return this;
  9725. }
  9726. });
  9727. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  9728. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  9729. function tileLayerWMS(url, options) {
  9730. return new TileLayerWMS(url, options);
  9731. }
  9732. TileLayer.WMS = TileLayerWMS;
  9733. tileLayer.wms = tileLayerWMS;
  9734. /*
  9735. * @class Renderer
  9736. * @inherits Layer
  9737. * @aka L.Renderer
  9738. *
  9739. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  9740. * DOM container of the renderer, its bounds, and its zoom animation.
  9741. *
  9742. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  9743. * itself can be added or removed to the map. All paths use a renderer, which can
  9744. * be implicit (the map will decide the type of renderer and use it automatically)
  9745. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  9746. *
  9747. * Do not use this class directly, use `SVG` and `Canvas` instead.
  9748. *
  9749. * @event update: Event
  9750. * Fired when the renderer updates its bounds, center and zoom, for example when
  9751. * its map has moved
  9752. */
  9753. var Renderer = Layer.extend({
  9754. // @section
  9755. // @aka Renderer options
  9756. options: {
  9757. // @option padding: Number = 0.1
  9758. // How much to extend the clip area around the map view (relative to its size)
  9759. // e.g. 0.1 would be 10% of map view in each direction
  9760. padding: 0.1,
  9761. // @option tolerance: Number = 0
  9762. // How much to extend click tolerance round a path/object on the map
  9763. tolerance : 0
  9764. },
  9765. initialize: function (options) {
  9766. setOptions(this, options);
  9767. stamp(this);
  9768. this._layers = this._layers || {};
  9769. },
  9770. onAdd: function () {
  9771. if (!this._container) {
  9772. this._initContainer(); // defined by renderer implementations
  9773. if (this._zoomAnimated) {
  9774. addClass(this._container, 'leaflet-zoom-animated');
  9775. }
  9776. }
  9777. this.getPane().appendChild(this._container);
  9778. this._update();
  9779. this.on('update', this._updatePaths, this);
  9780. },
  9781. onRemove: function () {
  9782. this.off('update', this._updatePaths, this);
  9783. this._destroyContainer();
  9784. },
  9785. getEvents: function () {
  9786. var events = {
  9787. viewreset: this._reset,
  9788. zoom: this._onZoom,
  9789. moveend: this._update,
  9790. zoomend: this._onZoomEnd
  9791. };
  9792. if (this._zoomAnimated) {
  9793. events.zoomanim = this._onAnimZoom;
  9794. }
  9795. return events;
  9796. },
  9797. _onAnimZoom: function (ev) {
  9798. this._updateTransform(ev.center, ev.zoom);
  9799. },
  9800. _onZoom: function () {
  9801. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  9802. },
  9803. _updateTransform: function (center, zoom) {
  9804. var scale = this._map.getZoomScale(zoom, this._zoom),
  9805. position = getPosition(this._container),
  9806. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  9807. currentCenterPoint = this._map.project(this._center, zoom),
  9808. destCenterPoint = this._map.project(center, zoom),
  9809. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  9810. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  9811. if (any3d) {
  9812. setTransform(this._container, topLeftOffset, scale);
  9813. } else {
  9814. setPosition(this._container, topLeftOffset);
  9815. }
  9816. },
  9817. _reset: function () {
  9818. this._update();
  9819. this._updateTransform(this._center, this._zoom);
  9820. for (var id in this._layers) {
  9821. this._layers[id]._reset();
  9822. }
  9823. },
  9824. _onZoomEnd: function () {
  9825. for (var id in this._layers) {
  9826. this._layers[id]._project();
  9827. }
  9828. },
  9829. _updatePaths: function () {
  9830. for (var id in this._layers) {
  9831. this._layers[id]._update();
  9832. }
  9833. },
  9834. _update: function () {
  9835. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  9836. // Subclasses are responsible of firing the 'update' event.
  9837. var p = this.options.padding,
  9838. size = this._map.getSize(),
  9839. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  9840. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  9841. this._center = this._map.getCenter();
  9842. this._zoom = this._map.getZoom();
  9843. }
  9844. });
  9845. /*
  9846. * @class Canvas
  9847. * @inherits Renderer
  9848. * @aka L.Canvas
  9849. *
  9850. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  9851. * Inherits `Renderer`.
  9852. *
  9853. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  9854. * available in all web browsers, notably IE8, and overlapping geometries might
  9855. * not display properly in some edge cases.
  9856. *
  9857. * @example
  9858. *
  9859. * Use Canvas by default for all paths in the map:
  9860. *
  9861. * ```js
  9862. * var map = L.map('map', {
  9863. * renderer: L.canvas()
  9864. * });
  9865. * ```
  9866. *
  9867. * Use a Canvas renderer with extra padding for specific vector geometries:
  9868. *
  9869. * ```js
  9870. * var map = L.map('map');
  9871. * var myRenderer = L.canvas({ padding: 0.5 });
  9872. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  9873. * var circle = L.circle( center, { renderer: myRenderer } );
  9874. * ```
  9875. */
  9876. var Canvas = Renderer.extend({
  9877. getEvents: function () {
  9878. var events = Renderer.prototype.getEvents.call(this);
  9879. events.viewprereset = this._onViewPreReset;
  9880. return events;
  9881. },
  9882. _onViewPreReset: function () {
  9883. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  9884. this._postponeUpdatePaths = true;
  9885. },
  9886. onAdd: function () {
  9887. Renderer.prototype.onAdd.call(this);
  9888. // Redraw vectors since canvas is cleared upon removal,
  9889. // in case of removing the renderer itself from the map.
  9890. this._draw();
  9891. },
  9892. _initContainer: function () {
  9893. var container = this._container = document.createElement('canvas');
  9894. on(container, 'mousemove', throttle(this._onMouseMove, 32, this), this);
  9895. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  9896. on(container, 'mouseout', this._handleMouseOut, this);
  9897. this._ctx = container.getContext('2d');
  9898. },
  9899. _destroyContainer: function () {
  9900. cancelAnimFrame(this._redrawRequest);
  9901. delete this._ctx;
  9902. remove(this._container);
  9903. off(this._container);
  9904. delete this._container;
  9905. },
  9906. _updatePaths: function () {
  9907. if (this._postponeUpdatePaths) { return; }
  9908. var layer;
  9909. this._redrawBounds = null;
  9910. for (var id in this._layers) {
  9911. layer = this._layers[id];
  9912. layer._update();
  9913. }
  9914. this._redraw();
  9915. },
  9916. _update: function () {
  9917. if (this._map._animatingZoom && this._bounds) { return; }
  9918. Renderer.prototype._update.call(this);
  9919. var b = this._bounds,
  9920. container = this._container,
  9921. size = b.getSize(),
  9922. m = retina ? 2 : 1;
  9923. setPosition(container, b.min);
  9924. // set canvas size (also clearing it); use double size on retina
  9925. container.width = m * size.x;
  9926. container.height = m * size.y;
  9927. container.style.width = size.x + 'px';
  9928. container.style.height = size.y + 'px';
  9929. if (retina) {
  9930. this._ctx.scale(2, 2);
  9931. }
  9932. // translate so we use the same path coordinates after canvas element moves
  9933. this._ctx.translate(-b.min.x, -b.min.y);
  9934. // Tell paths to redraw themselves
  9935. this.fire('update');
  9936. },
  9937. _reset: function () {
  9938. Renderer.prototype._reset.call(this);
  9939. if (this._postponeUpdatePaths) {
  9940. this._postponeUpdatePaths = false;
  9941. this._updatePaths();
  9942. }
  9943. },
  9944. _initPath: function (layer) {
  9945. this._updateDashArray(layer);
  9946. this._layers[stamp(layer)] = layer;
  9947. var order = layer._order = {
  9948. layer: layer,
  9949. prev: this._drawLast,
  9950. next: null
  9951. };
  9952. if (this._drawLast) { this._drawLast.next = order; }
  9953. this._drawLast = order;
  9954. this._drawFirst = this._drawFirst || this._drawLast;
  9955. },
  9956. _addPath: function (layer) {
  9957. this._requestRedraw(layer);
  9958. },
  9959. _removePath: function (layer) {
  9960. var order = layer._order;
  9961. var next = order.next;
  9962. var prev = order.prev;
  9963. if (next) {
  9964. next.prev = prev;
  9965. } else {
  9966. this._drawLast = prev;
  9967. }
  9968. if (prev) {
  9969. prev.next = next;
  9970. } else {
  9971. this._drawFirst = next;
  9972. }
  9973. delete layer._order;
  9974. delete this._layers[stamp(layer)];
  9975. this._requestRedraw(layer);
  9976. },
  9977. _updatePath: function (layer) {
  9978. // Redraw the union of the layer's old pixel
  9979. // bounds and the new pixel bounds.
  9980. this._extendRedrawBounds(layer);
  9981. layer._project();
  9982. layer._update();
  9983. // The redraw will extend the redraw bounds
  9984. // with the new pixel bounds.
  9985. this._requestRedraw(layer);
  9986. },
  9987. _updateStyle: function (layer) {
  9988. this._updateDashArray(layer);
  9989. this._requestRedraw(layer);
  9990. },
  9991. _updateDashArray: function (layer) {
  9992. if (typeof layer.options.dashArray === 'string') {
  9993. var parts = layer.options.dashArray.split(/[, ]+/),
  9994. dashArray = [],
  9995. dashValue,
  9996. i;
  9997. for (i = 0; i < parts.length; i++) {
  9998. dashValue = Number(parts[i]);
  9999. // Ignore dash array containing invalid lengths
  10000. if (isNaN(dashValue)) { return; }
  10001. dashArray.push(dashValue);
  10002. }
  10003. layer.options._dashArray = dashArray;
  10004. } else {
  10005. layer.options._dashArray = layer.options.dashArray;
  10006. }
  10007. },
  10008. _requestRedraw: function (layer) {
  10009. if (!this._map) { return; }
  10010. this._extendRedrawBounds(layer);
  10011. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  10012. },
  10013. _extendRedrawBounds: function (layer) {
  10014. if (layer._pxBounds) {
  10015. var padding = (layer.options.weight || 0) + 1;
  10016. this._redrawBounds = this._redrawBounds || new Bounds();
  10017. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  10018. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  10019. }
  10020. },
  10021. _redraw: function () {
  10022. this._redrawRequest = null;
  10023. if (this._redrawBounds) {
  10024. this._redrawBounds.min._floor();
  10025. this._redrawBounds.max._ceil();
  10026. }
  10027. this._clear(); // clear layers in redraw bounds
  10028. this._draw(); // draw layers
  10029. this._redrawBounds = null;
  10030. },
  10031. _clear: function () {
  10032. var bounds = this._redrawBounds;
  10033. if (bounds) {
  10034. var size = bounds.getSize();
  10035. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  10036. } else {
  10037. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  10038. }
  10039. },
  10040. _draw: function () {
  10041. var layer, bounds = this._redrawBounds;
  10042. this._ctx.save();
  10043. if (bounds) {
  10044. var size = bounds.getSize();
  10045. this._ctx.beginPath();
  10046. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  10047. this._ctx.clip();
  10048. }
  10049. this._drawing = true;
  10050. for (var order = this._drawFirst; order; order = order.next) {
  10051. layer = order.layer;
  10052. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  10053. layer._updatePath();
  10054. }
  10055. }
  10056. this._drawing = false;
  10057. this._ctx.restore(); // Restore state before clipping.
  10058. },
  10059. _updatePoly: function (layer, closed) {
  10060. if (!this._drawing) { return; }
  10061. var i, j, len2, p,
  10062. parts = layer._parts,
  10063. len = parts.length,
  10064. ctx = this._ctx;
  10065. if (!len) { return; }
  10066. ctx.beginPath();
  10067. for (i = 0; i < len; i++) {
  10068. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  10069. p = parts[i][j];
  10070. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  10071. }
  10072. if (closed) {
  10073. ctx.closePath();
  10074. }
  10075. }
  10076. this._fillStroke(ctx, layer);
  10077. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  10078. },
  10079. _updateCircle: function (layer) {
  10080. if (!this._drawing || layer._empty()) { return; }
  10081. var p = layer._point,
  10082. ctx = this._ctx,
  10083. r = Math.max(Math.round(layer._radius), 1),
  10084. s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
  10085. if (s !== 1) {
  10086. ctx.save();
  10087. ctx.scale(1, s);
  10088. }
  10089. ctx.beginPath();
  10090. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  10091. if (s !== 1) {
  10092. ctx.restore();
  10093. }
  10094. this._fillStroke(ctx, layer);
  10095. },
  10096. _fillStroke: function (ctx, layer) {
  10097. var options = layer.options;
  10098. if (options.fill) {
  10099. ctx.globalAlpha = options.fillOpacity;
  10100. ctx.fillStyle = options.fillColor || options.color;
  10101. ctx.fill(options.fillRule || 'evenodd');
  10102. }
  10103. if (options.stroke && options.weight !== 0) {
  10104. if (ctx.setLineDash) {
  10105. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  10106. }
  10107. ctx.globalAlpha = options.opacity;
  10108. ctx.lineWidth = options.weight;
  10109. ctx.strokeStyle = options.color;
  10110. ctx.lineCap = options.lineCap;
  10111. ctx.lineJoin = options.lineJoin;
  10112. ctx.stroke();
  10113. }
  10114. },
  10115. // Canvas obviously doesn't have mouse events for individual drawn objects,
  10116. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  10117. _onClick: function (e) {
  10118. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  10119. for (var order = this._drawFirst; order; order = order.next) {
  10120. layer = order.layer;
  10121. if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
  10122. clickedLayer = layer;
  10123. }
  10124. }
  10125. if (clickedLayer) {
  10126. fakeStop(e);
  10127. this._fireEvent([clickedLayer], e);
  10128. }
  10129. },
  10130. _onMouseMove: function (e) {
  10131. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  10132. var point = this._map.mouseEventToLayerPoint(e);
  10133. this._handleMouseHover(e, point);
  10134. },
  10135. _handleMouseOut: function (e) {
  10136. var layer = this._hoveredLayer;
  10137. if (layer) {
  10138. // if we're leaving the layer, fire mouseout
  10139. removeClass(this._container, 'leaflet-interactive');
  10140. this._fireEvent([layer], e, 'mouseout');
  10141. this._hoveredLayer = null;
  10142. }
  10143. },
  10144. _handleMouseHover: function (e, point) {
  10145. var layer, candidateHoveredLayer;
  10146. for (var order = this._drawFirst; order; order = order.next) {
  10147. layer = order.layer;
  10148. if (layer.options.interactive && layer._containsPoint(point)) {
  10149. candidateHoveredLayer = layer;
  10150. }
  10151. }
  10152. if (candidateHoveredLayer !== this._hoveredLayer) {
  10153. this._handleMouseOut(e);
  10154. if (candidateHoveredLayer) {
  10155. addClass(this._container, 'leaflet-interactive'); // change cursor
  10156. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  10157. this._hoveredLayer = candidateHoveredLayer;
  10158. }
  10159. }
  10160. if (this._hoveredLayer) {
  10161. this._fireEvent([this._hoveredLayer], e);
  10162. }
  10163. },
  10164. _fireEvent: function (layers, e, type) {
  10165. this._map._fireDOMEvent(e, type || e.type, layers);
  10166. },
  10167. _bringToFront: function (layer) {
  10168. var order = layer._order;
  10169. if (!order) { return; }
  10170. var next = order.next;
  10171. var prev = order.prev;
  10172. if (next) {
  10173. next.prev = prev;
  10174. } else {
  10175. // Already last
  10176. return;
  10177. }
  10178. if (prev) {
  10179. prev.next = next;
  10180. } else if (next) {
  10181. // Update first entry unless this is the
  10182. // single entry
  10183. this._drawFirst = next;
  10184. }
  10185. order.prev = this._drawLast;
  10186. this._drawLast.next = order;
  10187. order.next = null;
  10188. this._drawLast = order;
  10189. this._requestRedraw(layer);
  10190. },
  10191. _bringToBack: function (layer) {
  10192. var order = layer._order;
  10193. if (!order) { return; }
  10194. var next = order.next;
  10195. var prev = order.prev;
  10196. if (prev) {
  10197. prev.next = next;
  10198. } else {
  10199. // Already first
  10200. return;
  10201. }
  10202. if (next) {
  10203. next.prev = prev;
  10204. } else if (prev) {
  10205. // Update last entry unless this is the
  10206. // single entry
  10207. this._drawLast = prev;
  10208. }
  10209. order.prev = null;
  10210. order.next = this._drawFirst;
  10211. this._drawFirst.prev = order;
  10212. this._drawFirst = order;
  10213. this._requestRedraw(layer);
  10214. }
  10215. });
  10216. // @factory L.canvas(options?: Renderer options)
  10217. // Creates a Canvas renderer with the given options.
  10218. function canvas$1(options) {
  10219. return canvas ? new Canvas(options) : null;
  10220. }
  10221. /*
  10222. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10223. */
  10224. var vmlCreate = (function () {
  10225. try {
  10226. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10227. return function (name) {
  10228. return document.createElement('<lvml:' + name + ' class="lvml">');
  10229. };
  10230. } catch (e) {
  10231. return function (name) {
  10232. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10233. };
  10234. }
  10235. })();
  10236. /*
  10237. * @class SVG
  10238. *
  10239. *
  10240. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10241. * with old versions of Internet Explorer.
  10242. */
  10243. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10244. var vmlMixin = {
  10245. _initContainer: function () {
  10246. this._container = create$1('div', 'leaflet-vml-container');
  10247. },
  10248. _update: function () {
  10249. if (this._map._animatingZoom) { return; }
  10250. Renderer.prototype._update.call(this);
  10251. this.fire('update');
  10252. },
  10253. _initPath: function (layer) {
  10254. var container = layer._container = vmlCreate('shape');
  10255. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10256. container.coordsize = '1 1';
  10257. layer._path = vmlCreate('path');
  10258. container.appendChild(layer._path);
  10259. this._updateStyle(layer);
  10260. this._layers[stamp(layer)] = layer;
  10261. },
  10262. _addPath: function (layer) {
  10263. var container = layer._container;
  10264. this._container.appendChild(container);
  10265. if (layer.options.interactive) {
  10266. layer.addInteractiveTarget(container);
  10267. }
  10268. },
  10269. _removePath: function (layer) {
  10270. var container = layer._container;
  10271. remove(container);
  10272. layer.removeInteractiveTarget(container);
  10273. delete this._layers[stamp(layer)];
  10274. },
  10275. _updateStyle: function (layer) {
  10276. var stroke = layer._stroke,
  10277. fill = layer._fill,
  10278. options = layer.options,
  10279. container = layer._container;
  10280. container.stroked = !!options.stroke;
  10281. container.filled = !!options.fill;
  10282. if (options.stroke) {
  10283. if (!stroke) {
  10284. stroke = layer._stroke = vmlCreate('stroke');
  10285. }
  10286. container.appendChild(stroke);
  10287. stroke.weight = options.weight + 'px';
  10288. stroke.color = options.color;
  10289. stroke.opacity = options.opacity;
  10290. if (options.dashArray) {
  10291. stroke.dashStyle = isArray(options.dashArray) ?
  10292. options.dashArray.join(' ') :
  10293. options.dashArray.replace(/( *, *)/g, ' ');
  10294. } else {
  10295. stroke.dashStyle = '';
  10296. }
  10297. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10298. stroke.joinstyle = options.lineJoin;
  10299. } else if (stroke) {
  10300. container.removeChild(stroke);
  10301. layer._stroke = null;
  10302. }
  10303. if (options.fill) {
  10304. if (!fill) {
  10305. fill = layer._fill = vmlCreate('fill');
  10306. }
  10307. container.appendChild(fill);
  10308. fill.color = options.fillColor || options.color;
  10309. fill.opacity = options.fillOpacity;
  10310. } else if (fill) {
  10311. container.removeChild(fill);
  10312. layer._fill = null;
  10313. }
  10314. },
  10315. _updateCircle: function (layer) {
  10316. var p = layer._point.round(),
  10317. r = Math.round(layer._radius),
  10318. r2 = Math.round(layer._radiusY || r);
  10319. this._setPath(layer, layer._empty() ? 'M0 0' :
  10320. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10321. },
  10322. _setPath: function (layer, path) {
  10323. layer._path.v = path;
  10324. },
  10325. _bringToFront: function (layer) {
  10326. toFront(layer._container);
  10327. },
  10328. _bringToBack: function (layer) {
  10329. toBack(layer._container);
  10330. }
  10331. };
  10332. var create$2 = vml ? vmlCreate : svgCreate;
  10333. /*
  10334. * @class SVG
  10335. * @inherits Renderer
  10336. * @aka L.SVG
  10337. *
  10338. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10339. * Inherits `Renderer`.
  10340. *
  10341. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  10342. * available in all web browsers, notably Android 2.x and 3.x.
  10343. *
  10344. * Although SVG is not available on IE7 and IE8, these browsers support
  10345. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10346. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10347. * this case.
  10348. *
  10349. * @example
  10350. *
  10351. * Use SVG by default for all paths in the map:
  10352. *
  10353. * ```js
  10354. * var map = L.map('map', {
  10355. * renderer: L.svg()
  10356. * });
  10357. * ```
  10358. *
  10359. * Use a SVG renderer with extra padding for specific vector geometries:
  10360. *
  10361. * ```js
  10362. * var map = L.map('map');
  10363. * var myRenderer = L.svg({ padding: 0.5 });
  10364. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10365. * var circle = L.circle( center, { renderer: myRenderer } );
  10366. * ```
  10367. */
  10368. var SVG = Renderer.extend({
  10369. getEvents: function () {
  10370. var events = Renderer.prototype.getEvents.call(this);
  10371. events.zoomstart = this._onZoomStart;
  10372. return events;
  10373. },
  10374. _initContainer: function () {
  10375. this._container = create$2('svg');
  10376. // makes it possible to click through svg root; we'll reset it back in individual paths
  10377. this._container.setAttribute('pointer-events', 'none');
  10378. this._rootGroup = create$2('g');
  10379. this._container.appendChild(this._rootGroup);
  10380. },
  10381. _destroyContainer: function () {
  10382. remove(this._container);
  10383. off(this._container);
  10384. delete this._container;
  10385. delete this._rootGroup;
  10386. delete this._svgSize;
  10387. },
  10388. _onZoomStart: function () {
  10389. // Drag-then-pinch interactions might mess up the center and zoom.
  10390. // In this case, the easiest way to prevent this is re-do the renderer
  10391. // bounds and padding when the zooming starts.
  10392. this._update();
  10393. },
  10394. _update: function () {
  10395. if (this._map._animatingZoom && this._bounds) { return; }
  10396. Renderer.prototype._update.call(this);
  10397. var b = this._bounds,
  10398. size = b.getSize(),
  10399. container = this._container;
  10400. // set size of svg-container if changed
  10401. if (!this._svgSize || !this._svgSize.equals(size)) {
  10402. this._svgSize = size;
  10403. container.setAttribute('width', size.x);
  10404. container.setAttribute('height', size.y);
  10405. }
  10406. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10407. setPosition(container, b.min);
  10408. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10409. this.fire('update');
  10410. },
  10411. // methods below are called by vector layers implementations
  10412. _initPath: function (layer) {
  10413. var path = layer._path = create$2('path');
  10414. // @namespace Path
  10415. // @option className: String = null
  10416. // Custom class name set on an element. Only for SVG renderer.
  10417. if (layer.options.className) {
  10418. addClass(path, layer.options.className);
  10419. }
  10420. if (layer.options.interactive) {
  10421. addClass(path, 'leaflet-interactive');
  10422. }
  10423. this._updateStyle(layer);
  10424. this._layers[stamp(layer)] = layer;
  10425. },
  10426. _addPath: function (layer) {
  10427. if (!this._rootGroup) { this._initContainer(); }
  10428. this._rootGroup.appendChild(layer._path);
  10429. layer.addInteractiveTarget(layer._path);
  10430. },
  10431. _removePath: function (layer) {
  10432. remove(layer._path);
  10433. layer.removeInteractiveTarget(layer._path);
  10434. delete this._layers[stamp(layer)];
  10435. },
  10436. _updatePath: function (layer) {
  10437. layer._project();
  10438. layer._update();
  10439. },
  10440. _updateStyle: function (layer) {
  10441. var path = layer._path,
  10442. options = layer.options;
  10443. if (!path) { return; }
  10444. if (options.stroke) {
  10445. path.setAttribute('stroke', options.color);
  10446. path.setAttribute('stroke-opacity', options.opacity);
  10447. path.setAttribute('stroke-width', options.weight);
  10448. path.setAttribute('stroke-linecap', options.lineCap);
  10449. path.setAttribute('stroke-linejoin', options.lineJoin);
  10450. if (options.dashArray) {
  10451. path.setAttribute('stroke-dasharray', options.dashArray);
  10452. } else {
  10453. path.removeAttribute('stroke-dasharray');
  10454. }
  10455. if (options.dashOffset) {
  10456. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10457. } else {
  10458. path.removeAttribute('stroke-dashoffset');
  10459. }
  10460. } else {
  10461. path.setAttribute('stroke', 'none');
  10462. }
  10463. if (options.fill) {
  10464. path.setAttribute('fill', options.fillColor || options.color);
  10465. path.setAttribute('fill-opacity', options.fillOpacity);
  10466. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10467. } else {
  10468. path.setAttribute('fill', 'none');
  10469. }
  10470. },
  10471. _updatePoly: function (layer, closed) {
  10472. this._setPath(layer, pointsToPath(layer._parts, closed));
  10473. },
  10474. _updateCircle: function (layer) {
  10475. var p = layer._point,
  10476. r = Math.max(Math.round(layer._radius), 1),
  10477. r2 = Math.max(Math.round(layer._radiusY), 1) || r,
  10478. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10479. // drawing a circle with two half-arcs
  10480. var d = layer._empty() ? 'M0 0' :
  10481. 'M' + (p.x - r) + ',' + p.y +
  10482. arc + (r * 2) + ',0 ' +
  10483. arc + (-r * 2) + ',0 ';
  10484. this._setPath(layer, d);
  10485. },
  10486. _setPath: function (layer, path) {
  10487. layer._path.setAttribute('d', path);
  10488. },
  10489. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10490. _bringToFront: function (layer) {
  10491. toFront(layer._path);
  10492. },
  10493. _bringToBack: function (layer) {
  10494. toBack(layer._path);
  10495. }
  10496. });
  10497. if (vml) {
  10498. SVG.include(vmlMixin);
  10499. }
  10500. // @namespace SVG
  10501. // @factory L.svg(options?: Renderer options)
  10502. // Creates a SVG renderer with the given options.
  10503. function svg$1(options) {
  10504. return svg || vml ? new SVG(options) : null;
  10505. }
  10506. Map.include({
  10507. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10508. // Returns the instance of `Renderer` that should be used to render the given
  10509. // `Path`. It will ensure that the `renderer` options of the map and paths
  10510. // are respected, and that the renderers do exist on the map.
  10511. getRenderer: function (layer) {
  10512. // @namespace Path; @option renderer: Renderer
  10513. // Use this specific instance of `Renderer` for this path. Takes
  10514. // precedence over the map's [default renderer](#map-renderer).
  10515. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10516. if (!renderer) {
  10517. renderer = this._renderer = this._createRenderer();
  10518. }
  10519. if (!this.hasLayer(renderer)) {
  10520. this.addLayer(renderer);
  10521. }
  10522. return renderer;
  10523. },
  10524. _getPaneRenderer: function (name) {
  10525. if (name === 'overlayPane' || name === undefined) {
  10526. return false;
  10527. }
  10528. var renderer = this._paneRenderers[name];
  10529. if (renderer === undefined) {
  10530. renderer = this._createRenderer({pane: name});
  10531. this._paneRenderers[name] = renderer;
  10532. }
  10533. return renderer;
  10534. },
  10535. _createRenderer: function (options) {
  10536. // @namespace Map; @option preferCanvas: Boolean = false
  10537. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10538. // By default, all `Path`s are rendered in a `SVG` renderer.
  10539. return (this.options.preferCanvas && canvas$1(options)) || svg$1(options);
  10540. }
  10541. });
  10542. /*
  10543. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10544. */
  10545. /*
  10546. * @class Rectangle
  10547. * @aka L.Rectangle
  10548. * @inherits Polygon
  10549. *
  10550. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10551. *
  10552. * @example
  10553. *
  10554. * ```js
  10555. * // define rectangle geographical bounds
  10556. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10557. *
  10558. * // create an orange rectangle
  10559. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10560. *
  10561. * // zoom the map to the rectangle bounds
  10562. * map.fitBounds(bounds);
  10563. * ```
  10564. *
  10565. */
  10566. var Rectangle = Polygon.extend({
  10567. initialize: function (latLngBounds, options) {
  10568. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10569. },
  10570. // @method setBounds(latLngBounds: LatLngBounds): this
  10571. // Redraws the rectangle with the passed bounds.
  10572. setBounds: function (latLngBounds) {
  10573. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  10574. },
  10575. _boundsToLatLngs: function (latLngBounds) {
  10576. latLngBounds = toLatLngBounds(latLngBounds);
  10577. return [
  10578. latLngBounds.getSouthWest(),
  10579. latLngBounds.getNorthWest(),
  10580. latLngBounds.getNorthEast(),
  10581. latLngBounds.getSouthEast()
  10582. ];
  10583. }
  10584. });
  10585. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  10586. function rectangle(latLngBounds, options) {
  10587. return new Rectangle(latLngBounds, options);
  10588. }
  10589. SVG.create = create$2;
  10590. SVG.pointsToPath = pointsToPath;
  10591. GeoJSON.geometryToLayer = geometryToLayer;
  10592. GeoJSON.coordsToLatLng = coordsToLatLng;
  10593. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  10594. GeoJSON.latLngToCoords = latLngToCoords;
  10595. GeoJSON.latLngsToCoords = latLngsToCoords;
  10596. GeoJSON.getFeature = getFeature;
  10597. GeoJSON.asFeature = asFeature;
  10598. /*
  10599. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  10600. * (zoom to a selected bounding box), enabled by default.
  10601. */
  10602. // @namespace Map
  10603. // @section Interaction Options
  10604. Map.mergeOptions({
  10605. // @option boxZoom: Boolean = true
  10606. // Whether the map can be zoomed to a rectangular area specified by
  10607. // dragging the mouse while pressing the shift key.
  10608. boxZoom: true
  10609. });
  10610. var BoxZoom = Handler.extend({
  10611. initialize: function (map) {
  10612. this._map = map;
  10613. this._container = map._container;
  10614. this._pane = map._panes.overlayPane;
  10615. this._resetStateTimeout = 0;
  10616. map.on('unload', this._destroy, this);
  10617. },
  10618. addHooks: function () {
  10619. on(this._container, 'mousedown', this._onMouseDown, this);
  10620. },
  10621. removeHooks: function () {
  10622. off(this._container, 'mousedown', this._onMouseDown, this);
  10623. },
  10624. moved: function () {
  10625. return this._moved;
  10626. },
  10627. _destroy: function () {
  10628. remove(this._pane);
  10629. delete this._pane;
  10630. },
  10631. _resetState: function () {
  10632. this._resetStateTimeout = 0;
  10633. this._moved = false;
  10634. },
  10635. _clearDeferredResetState: function () {
  10636. if (this._resetStateTimeout !== 0) {
  10637. clearTimeout(this._resetStateTimeout);
  10638. this._resetStateTimeout = 0;
  10639. }
  10640. },
  10641. _onMouseDown: function (e) {
  10642. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  10643. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  10644. // will interrupt the interaction and orphan a box element in the container.
  10645. this._clearDeferredResetState();
  10646. this._resetState();
  10647. disableTextSelection();
  10648. disableImageDrag();
  10649. this._startPoint = this._map.mouseEventToContainerPoint(e);
  10650. on(document, {
  10651. contextmenu: stop,
  10652. mousemove: this._onMouseMove,
  10653. mouseup: this._onMouseUp,
  10654. keydown: this._onKeyDown
  10655. }, this);
  10656. },
  10657. _onMouseMove: function (e) {
  10658. if (!this._moved) {
  10659. this._moved = true;
  10660. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  10661. addClass(this._container, 'leaflet-crosshair');
  10662. this._map.fire('boxzoomstart');
  10663. }
  10664. this._point = this._map.mouseEventToContainerPoint(e);
  10665. var bounds = new Bounds(this._point, this._startPoint),
  10666. size = bounds.getSize();
  10667. setPosition(this._box, bounds.min);
  10668. this._box.style.width = size.x + 'px';
  10669. this._box.style.height = size.y + 'px';
  10670. },
  10671. _finish: function () {
  10672. if (this._moved) {
  10673. remove(this._box);
  10674. removeClass(this._container, 'leaflet-crosshair');
  10675. }
  10676. enableTextSelection();
  10677. enableImageDrag();
  10678. off(document, {
  10679. contextmenu: stop,
  10680. mousemove: this._onMouseMove,
  10681. mouseup: this._onMouseUp,
  10682. keydown: this._onKeyDown
  10683. }, this);
  10684. },
  10685. _onMouseUp: function (e) {
  10686. if ((e.which !== 1) && (e.button !== 1)) { return; }
  10687. this._finish();
  10688. if (!this._moved) { return; }
  10689. // Postpone to next JS tick so internal click event handling
  10690. // still see it as "moved".
  10691. this._clearDeferredResetState();
  10692. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  10693. var bounds = new LatLngBounds(
  10694. this._map.containerPointToLatLng(this._startPoint),
  10695. this._map.containerPointToLatLng(this._point));
  10696. this._map
  10697. .fitBounds(bounds)
  10698. .fire('boxzoomend', {boxZoomBounds: bounds});
  10699. },
  10700. _onKeyDown: function (e) {
  10701. if (e.keyCode === 27) {
  10702. this._finish();
  10703. }
  10704. }
  10705. });
  10706. // @section Handlers
  10707. // @property boxZoom: Handler
  10708. // Box (shift-drag with mouse) zoom handler.
  10709. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  10710. /*
  10711. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  10712. */
  10713. // @namespace Map
  10714. // @section Interaction Options
  10715. Map.mergeOptions({
  10716. // @option doubleClickZoom: Boolean|String = true
  10717. // Whether the map can be zoomed in by double clicking on it and
  10718. // zoomed out by double clicking while holding shift. If passed
  10719. // `'center'`, double-click zoom will zoom to the center of the
  10720. // view regardless of where the mouse was.
  10721. doubleClickZoom: true
  10722. });
  10723. var DoubleClickZoom = Handler.extend({
  10724. addHooks: function () {
  10725. this._map.on('dblclick', this._onDoubleClick, this);
  10726. },
  10727. removeHooks: function () {
  10728. this._map.off('dblclick', this._onDoubleClick, this);
  10729. },
  10730. _onDoubleClick: function (e) {
  10731. var map = this._map,
  10732. oldZoom = map.getZoom(),
  10733. delta = map.options.zoomDelta,
  10734. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  10735. if (map.options.doubleClickZoom === 'center') {
  10736. map.setZoom(zoom);
  10737. } else {
  10738. map.setZoomAround(e.containerPoint, zoom);
  10739. }
  10740. }
  10741. });
  10742. // @section Handlers
  10743. //
  10744. // Map properties include interaction handlers that allow you to control
  10745. // interaction behavior in runtime, enabling or disabling certain features such
  10746. // as dragging or touch zoom (see `Handler` methods). For example:
  10747. //
  10748. // ```js
  10749. // map.doubleClickZoom.disable();
  10750. // ```
  10751. //
  10752. // @property doubleClickZoom: Handler
  10753. // Double click zoom handler.
  10754. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  10755. /*
  10756. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  10757. */
  10758. // @namespace Map
  10759. // @section Interaction Options
  10760. Map.mergeOptions({
  10761. // @option dragging: Boolean = true
  10762. // Whether the map be draggable with mouse/touch or not.
  10763. dragging: true,
  10764. // @section Panning Inertia Options
  10765. // @option inertia: Boolean = *
  10766. // If enabled, panning of the map will have an inertia effect where
  10767. // the map builds momentum while dragging and continues moving in
  10768. // the same direction for some time. Feels especially nice on touch
  10769. // devices. Enabled by default unless running on old Android devices.
  10770. inertia: !android23,
  10771. // @option inertiaDeceleration: Number = 3000
  10772. // The rate with which the inertial movement slows down, in pixels/second².
  10773. inertiaDeceleration: 3400, // px/s^2
  10774. // @option inertiaMaxSpeed: Number = Infinity
  10775. // Max speed of the inertial movement, in pixels/second.
  10776. inertiaMaxSpeed: Infinity, // px/s
  10777. // @option easeLinearity: Number = 0.2
  10778. easeLinearity: 0.2,
  10779. // TODO refactor, move to CRS
  10780. // @option worldCopyJump: Boolean = false
  10781. // With this option enabled, the map tracks when you pan to another "copy"
  10782. // of the world and seamlessly jumps to the original one so that all overlays
  10783. // like markers and vector layers are still visible.
  10784. worldCopyJump: false,
  10785. // @option maxBoundsViscosity: Number = 0.0
  10786. // If `maxBounds` is set, this option will control how solid the bounds
  10787. // are when dragging the map around. The default value of `0.0` allows the
  10788. // user to drag outside the bounds at normal speed, higher values will
  10789. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  10790. // solid, preventing the user from dragging outside the bounds.
  10791. maxBoundsViscosity: 0.0
  10792. });
  10793. var Drag = Handler.extend({
  10794. addHooks: function () {
  10795. if (!this._draggable) {
  10796. var map = this._map;
  10797. this._draggable = new Draggable(map._mapPane, map._container);
  10798. this._draggable.on({
  10799. dragstart: this._onDragStart,
  10800. drag: this._onDrag,
  10801. dragend: this._onDragEnd
  10802. }, this);
  10803. this._draggable.on('predrag', this._onPreDragLimit, this);
  10804. if (map.options.worldCopyJump) {
  10805. this._draggable.on('predrag', this._onPreDragWrap, this);
  10806. map.on('zoomend', this._onZoomEnd, this);
  10807. map.whenReady(this._onZoomEnd, this);
  10808. }
  10809. }
  10810. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  10811. this._draggable.enable();
  10812. this._positions = [];
  10813. this._times = [];
  10814. },
  10815. removeHooks: function () {
  10816. removeClass(this._map._container, 'leaflet-grab');
  10817. removeClass(this._map._container, 'leaflet-touch-drag');
  10818. this._draggable.disable();
  10819. },
  10820. moved: function () {
  10821. return this._draggable && this._draggable._moved;
  10822. },
  10823. moving: function () {
  10824. return this._draggable && this._draggable._moving;
  10825. },
  10826. _onDragStart: function () {
  10827. var map = this._map;
  10828. map._stop();
  10829. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  10830. var bounds = toLatLngBounds(this._map.options.maxBounds);
  10831. this._offsetLimit = toBounds(
  10832. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  10833. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  10834. .add(this._map.getSize()));
  10835. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  10836. } else {
  10837. this._offsetLimit = null;
  10838. }
  10839. map
  10840. .fire('movestart')
  10841. .fire('dragstart');
  10842. if (map.options.inertia) {
  10843. this._positions = [];
  10844. this._times = [];
  10845. }
  10846. },
  10847. _onDrag: function (e) {
  10848. if (this._map.options.inertia) {
  10849. var time = this._lastTime = +new Date(),
  10850. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  10851. this._positions.push(pos);
  10852. this._times.push(time);
  10853. this._prunePositions(time);
  10854. }
  10855. this._map
  10856. .fire('move', e)
  10857. .fire('drag', e);
  10858. },
  10859. _prunePositions: function (time) {
  10860. while (this._positions.length > 1 && time - this._times[0] > 50) {
  10861. this._positions.shift();
  10862. this._times.shift();
  10863. }
  10864. },
  10865. _onZoomEnd: function () {
  10866. var pxCenter = this._map.getSize().divideBy(2),
  10867. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  10868. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  10869. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  10870. },
  10871. _viscousLimit: function (value, threshold) {
  10872. return value - (value - threshold) * this._viscosity;
  10873. },
  10874. _onPreDragLimit: function () {
  10875. if (!this._viscosity || !this._offsetLimit) { return; }
  10876. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  10877. var limit = this._offsetLimit;
  10878. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  10879. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  10880. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  10881. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  10882. this._draggable._newPos = this._draggable._startPos.add(offset);
  10883. },
  10884. _onPreDragWrap: function () {
  10885. // TODO refactor to be able to adjust map pane position after zoom
  10886. var worldWidth = this._worldWidth,
  10887. halfWidth = Math.round(worldWidth / 2),
  10888. dx = this._initialWorldOffset,
  10889. x = this._draggable._newPos.x,
  10890. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  10891. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  10892. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  10893. this._draggable._absPos = this._draggable._newPos.clone();
  10894. this._draggable._newPos.x = newX;
  10895. },
  10896. _onDragEnd: function (e) {
  10897. var map = this._map,
  10898. options = map.options,
  10899. noInertia = !options.inertia || this._times.length < 2;
  10900. map.fire('dragend', e);
  10901. if (noInertia) {
  10902. map.fire('moveend');
  10903. } else {
  10904. this._prunePositions(+new Date());
  10905. var direction = this._lastPos.subtract(this._positions[0]),
  10906. duration = (this._lastTime - this._times[0]) / 1000,
  10907. ease = options.easeLinearity,
  10908. speedVector = direction.multiplyBy(ease / duration),
  10909. speed = speedVector.distanceTo([0, 0]),
  10910. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  10911. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  10912. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  10913. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  10914. if (!offset.x && !offset.y) {
  10915. map.fire('moveend');
  10916. } else {
  10917. offset = map._limitOffset(offset, map.options.maxBounds);
  10918. requestAnimFrame(function () {
  10919. map.panBy(offset, {
  10920. duration: decelerationDuration,
  10921. easeLinearity: ease,
  10922. noMoveStart: true,
  10923. animate: true
  10924. });
  10925. });
  10926. }
  10927. }
  10928. }
  10929. });
  10930. // @section Handlers
  10931. // @property dragging: Handler
  10932. // Map dragging handler (by both mouse and touch).
  10933. Map.addInitHook('addHandler', 'dragging', Drag);
  10934. /*
  10935. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  10936. */
  10937. // @namespace Map
  10938. // @section Keyboard Navigation Options
  10939. Map.mergeOptions({
  10940. // @option keyboard: Boolean = true
  10941. // Makes the map focusable and allows users to navigate the map with keyboard
  10942. // arrows and `+`/`-` keys.
  10943. keyboard: true,
  10944. // @option keyboardPanDelta: Number = 80
  10945. // Amount of pixels to pan when pressing an arrow key.
  10946. keyboardPanDelta: 80
  10947. });
  10948. var Keyboard = Handler.extend({
  10949. keyCodes: {
  10950. left: [37],
  10951. right: [39],
  10952. down: [40],
  10953. up: [38],
  10954. zoomIn: [187, 107, 61, 171],
  10955. zoomOut: [189, 109, 54, 173]
  10956. },
  10957. initialize: function (map) {
  10958. this._map = map;
  10959. this._setPanDelta(map.options.keyboardPanDelta);
  10960. this._setZoomDelta(map.options.zoomDelta);
  10961. },
  10962. addHooks: function () {
  10963. var container = this._map._container;
  10964. // make the container focusable by tabbing
  10965. if (container.tabIndex <= 0) {
  10966. container.tabIndex = '0';
  10967. }
  10968. on(container, {
  10969. focus: this._onFocus,
  10970. blur: this._onBlur,
  10971. mousedown: this._onMouseDown
  10972. }, this);
  10973. this._map.on({
  10974. focus: this._addHooks,
  10975. blur: this._removeHooks
  10976. }, this);
  10977. },
  10978. removeHooks: function () {
  10979. this._removeHooks();
  10980. off(this._map._container, {
  10981. focus: this._onFocus,
  10982. blur: this._onBlur,
  10983. mousedown: this._onMouseDown
  10984. }, this);
  10985. this._map.off({
  10986. focus: this._addHooks,
  10987. blur: this._removeHooks
  10988. }, this);
  10989. },
  10990. _onMouseDown: function () {
  10991. if (this._focused) { return; }
  10992. var body = document.body,
  10993. docEl = document.documentElement,
  10994. top = body.scrollTop || docEl.scrollTop,
  10995. left = body.scrollLeft || docEl.scrollLeft;
  10996. this._map._container.focus();
  10997. window.scrollTo(left, top);
  10998. },
  10999. _onFocus: function () {
  11000. this._focused = true;
  11001. this._map.fire('focus');
  11002. },
  11003. _onBlur: function () {
  11004. this._focused = false;
  11005. this._map.fire('blur');
  11006. },
  11007. _setPanDelta: function (panDelta) {
  11008. var keys = this._panKeys = {},
  11009. codes = this.keyCodes,
  11010. i, len;
  11011. for (i = 0, len = codes.left.length; i < len; i++) {
  11012. keys[codes.left[i]] = [-1 * panDelta, 0];
  11013. }
  11014. for (i = 0, len = codes.right.length; i < len; i++) {
  11015. keys[codes.right[i]] = [panDelta, 0];
  11016. }
  11017. for (i = 0, len = codes.down.length; i < len; i++) {
  11018. keys[codes.down[i]] = [0, panDelta];
  11019. }
  11020. for (i = 0, len = codes.up.length; i < len; i++) {
  11021. keys[codes.up[i]] = [0, -1 * panDelta];
  11022. }
  11023. },
  11024. _setZoomDelta: function (zoomDelta) {
  11025. var keys = this._zoomKeys = {},
  11026. codes = this.keyCodes,
  11027. i, len;
  11028. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  11029. keys[codes.zoomIn[i]] = zoomDelta;
  11030. }
  11031. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  11032. keys[codes.zoomOut[i]] = -zoomDelta;
  11033. }
  11034. },
  11035. _addHooks: function () {
  11036. on(document, 'keydown', this._onKeyDown, this);
  11037. },
  11038. _removeHooks: function () {
  11039. off(document, 'keydown', this._onKeyDown, this);
  11040. },
  11041. _onKeyDown: function (e) {
  11042. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  11043. var key = e.keyCode,
  11044. map = this._map,
  11045. offset;
  11046. if (key in this._panKeys) {
  11047. if (!map._panAnim || !map._panAnim._inProgress) {
  11048. offset = this._panKeys[key];
  11049. if (e.shiftKey) {
  11050. offset = toPoint(offset).multiplyBy(3);
  11051. }
  11052. map.panBy(offset);
  11053. if (map.options.maxBounds) {
  11054. map.panInsideBounds(map.options.maxBounds);
  11055. }
  11056. }
  11057. } else if (key in this._zoomKeys) {
  11058. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  11059. } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
  11060. map.closePopup();
  11061. } else {
  11062. return;
  11063. }
  11064. stop(e);
  11065. }
  11066. });
  11067. // @section Handlers
  11068. // @section Handlers
  11069. // @property keyboard: Handler
  11070. // Keyboard navigation handler.
  11071. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  11072. /*
  11073. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  11074. */
  11075. // @namespace Map
  11076. // @section Interaction Options
  11077. Map.mergeOptions({
  11078. // @section Mousewheel options
  11079. // @option scrollWheelZoom: Boolean|String = true
  11080. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  11081. // it will zoom to the center of the view regardless of where the mouse was.
  11082. scrollWheelZoom: true,
  11083. // @option wheelDebounceTime: Number = 40
  11084. // Limits the rate at which a wheel can fire (in milliseconds). By default
  11085. // user can't zoom via wheel more often than once per 40 ms.
  11086. wheelDebounceTime: 40,
  11087. // @option wheelPxPerZoomLevel: Number = 60
  11088. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  11089. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  11090. // faster (and vice versa).
  11091. wheelPxPerZoomLevel: 60
  11092. });
  11093. var ScrollWheelZoom = Handler.extend({
  11094. addHooks: function () {
  11095. on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  11096. this._delta = 0;
  11097. },
  11098. removeHooks: function () {
  11099. off(this._map._container, 'mousewheel', this._onWheelScroll, this);
  11100. },
  11101. _onWheelScroll: function (e) {
  11102. var delta = getWheelDelta(e);
  11103. var debounce = this._map.options.wheelDebounceTime;
  11104. this._delta += delta;
  11105. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  11106. if (!this._startTime) {
  11107. this._startTime = +new Date();
  11108. }
  11109. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  11110. clearTimeout(this._timer);
  11111. this._timer = setTimeout(bind(this._performZoom, this), left);
  11112. stop(e);
  11113. },
  11114. _performZoom: function () {
  11115. var map = this._map,
  11116. zoom = map.getZoom(),
  11117. snap = this._map.options.zoomSnap || 0;
  11118. map._stop(); // stop panning and fly animations if any
  11119. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  11120. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  11121. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  11122. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  11123. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  11124. this._delta = 0;
  11125. this._startTime = null;
  11126. if (!delta) { return; }
  11127. if (map.options.scrollWheelZoom === 'center') {
  11128. map.setZoom(zoom + delta);
  11129. } else {
  11130. map.setZoomAround(this._lastMousePos, zoom + delta);
  11131. }
  11132. }
  11133. });
  11134. // @section Handlers
  11135. // @property scrollWheelZoom: Handler
  11136. // Scroll wheel zoom handler.
  11137. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  11138. /*
  11139. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  11140. */
  11141. // @namespace Map
  11142. // @section Interaction Options
  11143. Map.mergeOptions({
  11144. // @section Touch interaction options
  11145. // @option tap: Boolean = true
  11146. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  11147. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  11148. tap: true,
  11149. // @option tapTolerance: Number = 15
  11150. // The max number of pixels a user can shift his finger during touch
  11151. // for it to be considered a valid tap.
  11152. tapTolerance: 15
  11153. });
  11154. var Tap = Handler.extend({
  11155. addHooks: function () {
  11156. on(this._map._container, 'touchstart', this._onDown, this);
  11157. },
  11158. removeHooks: function () {
  11159. off(this._map._container, 'touchstart', this._onDown, this);
  11160. },
  11161. _onDown: function (e) {
  11162. if (!e.touches) { return; }
  11163. preventDefault(e);
  11164. this._fireClick = true;
  11165. // don't simulate click or track longpress if more than 1 touch
  11166. if (e.touches.length > 1) {
  11167. this._fireClick = false;
  11168. clearTimeout(this._holdTimeout);
  11169. return;
  11170. }
  11171. var first = e.touches[0],
  11172. el = first.target;
  11173. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  11174. // if touching a link, highlight it
  11175. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  11176. addClass(el, 'leaflet-active');
  11177. }
  11178. // simulate long hold but setting a timeout
  11179. this._holdTimeout = setTimeout(bind(function () {
  11180. if (this._isTapValid()) {
  11181. this._fireClick = false;
  11182. this._onUp();
  11183. this._simulateEvent('contextmenu', first);
  11184. }
  11185. }, this), 1000);
  11186. this._simulateEvent('mousedown', first);
  11187. on(document, {
  11188. touchmove: this._onMove,
  11189. touchend: this._onUp
  11190. }, this);
  11191. },
  11192. _onUp: function (e) {
  11193. clearTimeout(this._holdTimeout);
  11194. off(document, {
  11195. touchmove: this._onMove,
  11196. touchend: this._onUp
  11197. }, this);
  11198. if (this._fireClick && e && e.changedTouches) {
  11199. var first = e.changedTouches[0],
  11200. el = first.target;
  11201. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  11202. removeClass(el, 'leaflet-active');
  11203. }
  11204. this._simulateEvent('mouseup', first);
  11205. // simulate click if the touch didn't move too much
  11206. if (this._isTapValid()) {
  11207. this._simulateEvent('click', first);
  11208. }
  11209. }
  11210. },
  11211. _isTapValid: function () {
  11212. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11213. },
  11214. _onMove: function (e) {
  11215. var first = e.touches[0];
  11216. this._newPos = new Point(first.clientX, first.clientY);
  11217. this._simulateEvent('mousemove', first);
  11218. },
  11219. _simulateEvent: function (type, e) {
  11220. var simulatedEvent = document.createEvent('MouseEvents');
  11221. simulatedEvent._simulated = true;
  11222. e.target._simulatedClick = true;
  11223. simulatedEvent.initMouseEvent(
  11224. type, true, true, window, 1,
  11225. e.screenX, e.screenY,
  11226. e.clientX, e.clientY,
  11227. false, false, false, false, 0, null);
  11228. e.target.dispatchEvent(simulatedEvent);
  11229. }
  11230. });
  11231. // @section Handlers
  11232. // @property tap: Handler
  11233. // Mobile touch hacks (quick tap and touch hold) handler.
  11234. if (touch && !pointer) {
  11235. Map.addInitHook('addHandler', 'tap', Tap);
  11236. }
  11237. /*
  11238. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11239. */
  11240. // @namespace Map
  11241. // @section Interaction Options
  11242. Map.mergeOptions({
  11243. // @section Touch interaction options
  11244. // @option touchZoom: Boolean|String = *
  11245. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11246. // passed `'center'`, it will zoom to the center of the view regardless of
  11247. // where the touch events (fingers) were. Enabled for touch-capable web
  11248. // browsers except for old Androids.
  11249. touchZoom: touch && !android23,
  11250. // @option bounceAtZoomLimits: Boolean = true
  11251. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11252. // and then bounce back when pinch-zooming.
  11253. bounceAtZoomLimits: true
  11254. });
  11255. var TouchZoom = Handler.extend({
  11256. addHooks: function () {
  11257. addClass(this._map._container, 'leaflet-touch-zoom');
  11258. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11259. },
  11260. removeHooks: function () {
  11261. removeClass(this._map._container, 'leaflet-touch-zoom');
  11262. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11263. },
  11264. _onTouchStart: function (e) {
  11265. var map = this._map;
  11266. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  11267. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11268. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11269. this._centerPoint = map.getSize()._divideBy(2);
  11270. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11271. if (map.options.touchZoom !== 'center') {
  11272. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11273. }
  11274. this._startDist = p1.distanceTo(p2);
  11275. this._startZoom = map.getZoom();
  11276. this._moved = false;
  11277. this._zooming = true;
  11278. map._stop();
  11279. on(document, 'touchmove', this._onTouchMove, this);
  11280. on(document, 'touchend', this._onTouchEnd, this);
  11281. preventDefault(e);
  11282. },
  11283. _onTouchMove: function (e) {
  11284. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  11285. var map = this._map,
  11286. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11287. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11288. scale = p1.distanceTo(p2) / this._startDist;
  11289. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11290. if (!map.options.bounceAtZoomLimits && (
  11291. (this._zoom < map.getMinZoom() && scale < 1) ||
  11292. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11293. this._zoom = map._limitZoom(this._zoom);
  11294. }
  11295. if (map.options.touchZoom === 'center') {
  11296. this._center = this._startLatLng;
  11297. if (scale === 1) { return; }
  11298. } else {
  11299. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11300. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11301. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  11302. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11303. }
  11304. if (!this._moved) {
  11305. map._moveStart(true, false);
  11306. this._moved = true;
  11307. }
  11308. cancelAnimFrame(this._animRequest);
  11309. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  11310. this._animRequest = requestAnimFrame(moveFn, this, true);
  11311. preventDefault(e);
  11312. },
  11313. _onTouchEnd: function () {
  11314. if (!this._moved || !this._zooming) {
  11315. this._zooming = false;
  11316. return;
  11317. }
  11318. this._zooming = false;
  11319. cancelAnimFrame(this._animRequest);
  11320. off(document, 'touchmove', this._onTouchMove);
  11321. off(document, 'touchend', this._onTouchEnd);
  11322. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11323. if (this._map.options.zoomAnimation) {
  11324. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11325. } else {
  11326. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11327. }
  11328. }
  11329. });
  11330. // @section Handlers
  11331. // @property touchZoom: Handler
  11332. // Touch zoom handler.
  11333. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11334. Map.BoxZoom = BoxZoom;
  11335. Map.DoubleClickZoom = DoubleClickZoom;
  11336. Map.Drag = Drag;
  11337. Map.Keyboard = Keyboard;
  11338. Map.ScrollWheelZoom = ScrollWheelZoom;
  11339. Map.Tap = Tap;
  11340. Map.TouchZoom = TouchZoom;
  11341. Object.freeze = freeze;
  11342. exports.version = version;
  11343. exports.Control = Control;
  11344. exports.control = control;
  11345. exports.Browser = Browser;
  11346. exports.Evented = Evented;
  11347. exports.Mixin = Mixin;
  11348. exports.Util = Util;
  11349. exports.Class = Class;
  11350. exports.Handler = Handler;
  11351. exports.extend = extend;
  11352. exports.bind = bind;
  11353. exports.stamp = stamp;
  11354. exports.setOptions = setOptions;
  11355. exports.DomEvent = DomEvent;
  11356. exports.DomUtil = DomUtil;
  11357. exports.PosAnimation = PosAnimation;
  11358. exports.Draggable = Draggable;
  11359. exports.LineUtil = LineUtil;
  11360. exports.PolyUtil = PolyUtil;
  11361. exports.Point = Point;
  11362. exports.point = toPoint;
  11363. exports.Bounds = Bounds;
  11364. exports.bounds = toBounds;
  11365. exports.Transformation = Transformation;
  11366. exports.transformation = toTransformation;
  11367. exports.Projection = index;
  11368. exports.LatLng = LatLng;
  11369. exports.latLng = toLatLng;
  11370. exports.LatLngBounds = LatLngBounds;
  11371. exports.latLngBounds = toLatLngBounds;
  11372. exports.CRS = CRS;
  11373. exports.GeoJSON = GeoJSON;
  11374. exports.geoJSON = geoJSON;
  11375. exports.geoJson = geoJson;
  11376. exports.Layer = Layer;
  11377. exports.LayerGroup = LayerGroup;
  11378. exports.layerGroup = layerGroup;
  11379. exports.FeatureGroup = FeatureGroup;
  11380. exports.featureGroup = featureGroup;
  11381. exports.ImageOverlay = ImageOverlay;
  11382. exports.imageOverlay = imageOverlay;
  11383. exports.VideoOverlay = VideoOverlay;
  11384. exports.videoOverlay = videoOverlay;
  11385. exports.SVGOverlay = SVGOverlay;
  11386. exports.svgOverlay = svgOverlay;
  11387. exports.DivOverlay = DivOverlay;
  11388. exports.Popup = Popup;
  11389. exports.popup = popup;
  11390. exports.Tooltip = Tooltip;
  11391. exports.tooltip = tooltip;
  11392. exports.Icon = Icon;
  11393. exports.icon = icon;
  11394. exports.DivIcon = DivIcon;
  11395. exports.divIcon = divIcon;
  11396. exports.Marker = Marker;
  11397. exports.marker = marker;
  11398. exports.TileLayer = TileLayer;
  11399. exports.tileLayer = tileLayer;
  11400. exports.GridLayer = GridLayer;
  11401. exports.gridLayer = gridLayer;
  11402. exports.SVG = SVG;
  11403. exports.svg = svg$1;
  11404. exports.Renderer = Renderer;
  11405. exports.Canvas = Canvas;
  11406. exports.canvas = canvas$1;
  11407. exports.Path = Path;
  11408. exports.CircleMarker = CircleMarker;
  11409. exports.circleMarker = circleMarker;
  11410. exports.Circle = Circle;
  11411. exports.circle = circle;
  11412. exports.Polyline = Polyline;
  11413. exports.polyline = polyline;
  11414. exports.Polygon = Polygon;
  11415. exports.polygon = polygon;
  11416. exports.Rectangle = Rectangle;
  11417. exports.rectangle = rectangle;
  11418. exports.Map = Map;
  11419. exports.map = createMap;
  11420. var oldL = window.L;
  11421. exports.noConflict = function() {
  11422. window.L = oldL;
  11423. return this;
  11424. }
  11425. // Always export us to window global (see #2364)
  11426. window.L = exports;
  11427. })));
  11428. //# sourceMappingURL=leaflet-src.js.map