leaflet-src.js 364 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243
  1. /*
  2. Leaflet 1.0.3+ed36a04, a JS library for interactive maps. http://leafletjs.com
  3. (c) 2010-2016 Vladimir Agafonkin, (c) 2010-2011 CloudMade
  4. */
  5. (function (window, document, undefined) {
  6. var L = {
  7. version: "1.0.3+ed36a04"
  8. };
  9. function expose() {
  10. var oldL = window.L;
  11. L.noConflict = function () {
  12. window.L = oldL;
  13. return this;
  14. };
  15. window.L = L;
  16. }
  17. // define Leaflet for Node module pattern loaders, including Browserify
  18. if (typeof module === 'object' && typeof module.exports === 'object') {
  19. module.exports = L;
  20. // define Leaflet as an AMD module
  21. } else if (typeof define === 'function' && define.amd) {
  22. define(L);
  23. }
  24. // define Leaflet as a global L variable, saving the original L to restore later if needed
  25. if (typeof window !== 'undefined') {
  26. expose();
  27. }
  28. /*
  29. * @namespace Util
  30. *
  31. * Various utility functions, used by Leaflet internally.
  32. */
  33. L.Util = {
  34. // @function extend(dest: Object, src?: Object): Object
  35. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  36. extend: function (dest) {
  37. var i, j, len, src;
  38. for (j = 1, len = arguments.length; j < len; j++) {
  39. src = arguments[j];
  40. for (i in src) {
  41. dest[i] = src[i];
  42. }
  43. }
  44. return dest;
  45. },
  46. // @function create(proto: Object, properties?: Object): Object
  47. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  48. create: Object.create || (function () {
  49. function F() {}
  50. return function (proto) {
  51. F.prototype = proto;
  52. return new F();
  53. };
  54. })(),
  55. // @function bind(fn: Function, …): Function
  56. // Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
  57. // Has a `L.bind()` shortcut.
  58. bind: function (fn, obj) {
  59. var slice = Array.prototype.slice;
  60. if (fn.bind) {
  61. return fn.bind.apply(fn, slice.call(arguments, 1));
  62. }
  63. var args = slice.call(arguments, 2);
  64. return function () {
  65. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  66. };
  67. },
  68. // @function stamp(obj: Object): Number
  69. // Returns the unique ID of an object, assiging it one if it doesn't have it.
  70. stamp: function (obj) {
  71. /*eslint-disable */
  72. obj._leaflet_id = obj._leaflet_id || ++L.Util.lastId;
  73. return obj._leaflet_id;
  74. /*eslint-enable */
  75. },
  76. // @property lastId: Number
  77. // Last unique ID used by [`stamp()`](#util-stamp)
  78. lastId: 0,
  79. // @function throttle(fn: Function, time: Number, context: Object): Function
  80. // Returns a function which executes function `fn` with the given scope `context`
  81. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  82. // `fn` will be called no more than one time per given amount of `time`. The arguments
  83. // received by the bound function will be any arguments passed when binding the
  84. // function, followed by any arguments passed when invoking the bound function.
  85. // Has an `L.bind` shortcut.
  86. throttle: function (fn, time, context) {
  87. var lock, args, wrapperFn, later;
  88. later = function () {
  89. // reset lock and call if queued
  90. lock = false;
  91. if (args) {
  92. wrapperFn.apply(context, args);
  93. args = false;
  94. }
  95. };
  96. wrapperFn = function () {
  97. if (lock) {
  98. // called too soon, queue to call later
  99. args = arguments;
  100. } else {
  101. // call and lock until later
  102. fn.apply(context, arguments);
  103. setTimeout(later, time);
  104. lock = true;
  105. }
  106. };
  107. return wrapperFn;
  108. },
  109. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  110. // Returns the number `num` modulo `range` in such a way so it lies within
  111. // `range[0]` and `range[1]`. The returned value will be always smaller than
  112. // `range[1]` unless `includeMax` is set to `true`.
  113. wrapNum: function (x, range, includeMax) {
  114. var max = range[1],
  115. min = range[0],
  116. d = max - min;
  117. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  118. },
  119. // @function falseFn(): Function
  120. // Returns a function which always returns `false`.
  121. falseFn: function () { return false; },
  122. // @function formatNum(num: Number, digits?: Number): Number
  123. // Returns the number `num` rounded to `digits` decimals, or to 5 decimals by default.
  124. formatNum: function (num, digits) {
  125. var pow = Math.pow(10, digits || 5);
  126. return Math.round(num * pow) / pow;
  127. },
  128. // @function trim(str: String): String
  129. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  130. trim: function (str) {
  131. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  132. },
  133. // @function splitWords(str: String): String[]
  134. // Trims and splits the string on whitespace and returns the array of parts.
  135. splitWords: function (str) {
  136. return L.Util.trim(str).split(/\s+/);
  137. },
  138. // @function setOptions(obj: Object, options: Object): Object
  139. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  140. setOptions: function (obj, options) {
  141. if (!obj.hasOwnProperty('options')) {
  142. obj.options = obj.options ? L.Util.create(obj.options) : {};
  143. }
  144. for (var i in options) {
  145. obj.options[i] = options[i];
  146. }
  147. return obj.options;
  148. },
  149. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  150. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  151. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  152. // be appended at the end. If `uppercase` is `true`, the parameter names will
  153. // be uppercased (e.g. `'?A=foo&B=bar'`)
  154. getParamString: function (obj, existingUrl, uppercase) {
  155. var params = [];
  156. for (var i in obj) {
  157. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  158. }
  159. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  160. },
  161. // @function template(str: String, data: Object): String
  162. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  163. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  164. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  165. // data values — they will be evaluated passing `data` as an argument.
  166. template: function (str, data) {
  167. return str.replace(L.Util.templateRe, function (str, key) {
  168. var value = data[key];
  169. if (value === undefined) {
  170. throw new Error('No value provided for variable ' + str);
  171. } else if (typeof value === 'function') {
  172. value = value(data);
  173. }
  174. return value;
  175. });
  176. },
  177. templateRe: /\{ *([\w_\-]+) *\}/g,
  178. // @function isArray(obj): Boolean
  179. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  180. isArray: Array.isArray || function (obj) {
  181. return (Object.prototype.toString.call(obj) === '[object Array]');
  182. },
  183. // @function indexOf(array: Array, el: Object): Number
  184. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  185. indexOf: function (array, el) {
  186. for (var i = 0; i < array.length; i++) {
  187. if (array[i] === el) { return i; }
  188. }
  189. return -1;
  190. },
  191. // @property emptyImageUrl: String
  192. // Data URI string containing a base64-encoded empty GIF image.
  193. // Used as a hack to free memory from unused images on WebKit-powered
  194. // mobile devices (by setting image `src` to this string).
  195. emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
  196. };
  197. (function () {
  198. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  199. function getPrefixed(name) {
  200. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  201. }
  202. var lastTime = 0;
  203. // fallback for IE 7-8
  204. function timeoutDefer(fn) {
  205. var time = +new Date(),
  206. timeToCall = Math.max(0, 16 - (time - lastTime));
  207. lastTime = time + timeToCall;
  208. return window.setTimeout(fn, timeToCall);
  209. }
  210. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer,
  211. cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  212. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  213. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  214. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  215. // `context` if given. When `immediate` is set, `fn` is called immediately if
  216. // the browser doesn't have native support for
  217. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  218. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  219. L.Util.requestAnimFrame = function (fn, context, immediate) {
  220. if (immediate && requestFn === timeoutDefer) {
  221. fn.call(context);
  222. } else {
  223. return requestFn.call(window, L.bind(fn, context));
  224. }
  225. };
  226. // @function cancelAnimFrame(id: Number): undefined
  227. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  228. L.Util.cancelAnimFrame = function (id) {
  229. if (id) {
  230. cancelFn.call(window, id);
  231. }
  232. };
  233. })();
  234. // shortcuts for most used utility functions
  235. L.extend = L.Util.extend;
  236. L.bind = L.Util.bind;
  237. L.stamp = L.Util.stamp;
  238. L.setOptions = L.Util.setOptions;
  239. // @class Class
  240. // @aka L.Class
  241. // @section
  242. // @uninheritable
  243. // Thanks to John Resig and Dean Edwards for inspiration!
  244. L.Class = function () {};
  245. L.Class.extend = function (props) {
  246. // @function extend(props: Object): Function
  247. // [Extends the current class](#class-inheritance) given the properties to be included.
  248. // Returns a Javascript function that is a class constructor (to be called with `new`).
  249. var NewClass = function () {
  250. // call the constructor
  251. if (this.initialize) {
  252. this.initialize.apply(this, arguments);
  253. }
  254. // call all constructor hooks
  255. this.callInitHooks();
  256. };
  257. var parentProto = NewClass.__super__ = this.prototype;
  258. var proto = L.Util.create(parentProto);
  259. proto.constructor = NewClass;
  260. NewClass.prototype = proto;
  261. // inherit parent's statics
  262. for (var i in this) {
  263. if (this.hasOwnProperty(i) && i !== 'prototype') {
  264. NewClass[i] = this[i];
  265. }
  266. }
  267. // mix static properties into the class
  268. if (props.statics) {
  269. L.extend(NewClass, props.statics);
  270. delete props.statics;
  271. }
  272. // mix includes into the prototype
  273. if (props.includes) {
  274. L.Util.extend.apply(null, [proto].concat(props.includes));
  275. delete props.includes;
  276. }
  277. // merge options
  278. if (proto.options) {
  279. props.options = L.Util.extend(L.Util.create(proto.options), props.options);
  280. }
  281. // mix given properties into the prototype
  282. L.extend(proto, props);
  283. proto._initHooks = [];
  284. // add method for calling all hooks
  285. proto.callInitHooks = function () {
  286. if (this._initHooksCalled) { return; }
  287. if (parentProto.callInitHooks) {
  288. parentProto.callInitHooks.call(this);
  289. }
  290. this._initHooksCalled = true;
  291. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  292. proto._initHooks[i].call(this);
  293. }
  294. };
  295. return NewClass;
  296. };
  297. // @function include(properties: Object): this
  298. // [Includes a mixin](#class-includes) into the current class.
  299. L.Class.include = function (props) {
  300. L.extend(this.prototype, props);
  301. return this;
  302. };
  303. // @function mergeOptions(options: Object): this
  304. // [Merges `options`](#class-options) into the defaults of the class.
  305. L.Class.mergeOptions = function (options) {
  306. L.extend(this.prototype.options, options);
  307. return this;
  308. };
  309. // @function addInitHook(fn: Function): this
  310. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  311. L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
  312. var args = Array.prototype.slice.call(arguments, 1);
  313. var init = typeof fn === 'function' ? fn : function () {
  314. this[fn].apply(this, args);
  315. };
  316. this.prototype._initHooks = this.prototype._initHooks || [];
  317. this.prototype._initHooks.push(init);
  318. return this;
  319. };
  320. /*
  321. * @class Evented
  322. * @aka L.Evented
  323. * @inherits Class
  324. *
  325. * A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event).
  326. *
  327. * @example
  328. *
  329. * ```js
  330. * map.on('click', function(e) {
  331. * alert(e.latlng);
  332. * } );
  333. * ```
  334. *
  335. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  336. *
  337. * ```js
  338. * function onClick(e) { ... }
  339. *
  340. * map.on('click', onClick);
  341. * map.off('click', onClick);
  342. * ```
  343. */
  344. L.Evented = L.Class.extend({
  345. /* @method on(type: String, fn: Function, context?: Object): this
  346. * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).
  347. *
  348. * @alternative
  349. * @method on(eventMap: Object): this
  350. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  351. */
  352. on: function (types, fn, context) {
  353. // types can be a map of types/handlers
  354. if (typeof types === 'object') {
  355. for (var type in types) {
  356. // we don't process space-separated events here for performance;
  357. // it's a hot path since Layer uses the on(obj) syntax
  358. this._on(type, types[type], fn);
  359. }
  360. } else {
  361. // types can be a string of space-separated words
  362. types = L.Util.splitWords(types);
  363. for (var i = 0, len = types.length; i < len; i++) {
  364. this._on(types[i], fn, context);
  365. }
  366. }
  367. return this;
  368. },
  369. /* @method off(type: String, fn?: Function, context?: Object): this
  370. * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.
  371. *
  372. * @alternative
  373. * @method off(eventMap: Object): this
  374. * Removes a set of type/listener pairs.
  375. *
  376. * @alternative
  377. * @method off: this
  378. * Removes all listeners to all events on the object.
  379. */
  380. off: function (types, fn, context) {
  381. if (!types) {
  382. // clear all listeners if called without arguments
  383. delete this._events;
  384. } else if (typeof types === 'object') {
  385. for (var type in types) {
  386. this._off(type, types[type], fn);
  387. }
  388. } else {
  389. types = L.Util.splitWords(types);
  390. for (var i = 0, len = types.length; i < len; i++) {
  391. this._off(types[i], fn, context);
  392. }
  393. }
  394. return this;
  395. },
  396. // attach listener (without syntactic sugar now)
  397. _on: function (type, fn, context) {
  398. this._events = this._events || {};
  399. /* get/init listeners for type */
  400. var typeListeners = this._events[type];
  401. if (!typeListeners) {
  402. typeListeners = [];
  403. this._events[type] = typeListeners;
  404. }
  405. if (context === this) {
  406. // Less memory footprint.
  407. context = undefined;
  408. }
  409. var newListener = {fn: fn, ctx: context},
  410. listeners = typeListeners;
  411. // check if fn already there
  412. for (var i = 0, len = listeners.length; i < len; i++) {
  413. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  414. return;
  415. }
  416. }
  417. listeners.push(newListener);
  418. },
  419. _off: function (type, fn, context) {
  420. var listeners,
  421. i,
  422. len;
  423. if (!this._events) { return; }
  424. listeners = this._events[type];
  425. if (!listeners) {
  426. return;
  427. }
  428. if (!fn) {
  429. // Set all removed listeners to noop so they are not called if remove happens in fire
  430. for (i = 0, len = listeners.length; i < len; i++) {
  431. listeners[i].fn = L.Util.falseFn;
  432. }
  433. // clear all listeners for a type if function isn't specified
  434. delete this._events[type];
  435. return;
  436. }
  437. if (context === this) {
  438. context = undefined;
  439. }
  440. if (listeners) {
  441. // find fn and remove it
  442. for (i = 0, len = listeners.length; i < len; i++) {
  443. var l = listeners[i];
  444. if (l.ctx !== context) { continue; }
  445. if (l.fn === fn) {
  446. // set the removed listener to noop so that's not called if remove happens in fire
  447. l.fn = L.Util.falseFn;
  448. if (this._firingCount) {
  449. /* copy array in case events are being fired */
  450. this._events[type] = listeners = listeners.slice();
  451. }
  452. listeners.splice(i, 1);
  453. return;
  454. }
  455. }
  456. }
  457. },
  458. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  459. // Fires an event of the specified type. You can optionally provide an data
  460. // object — the first argument of the listener function will contain its
  461. // properties. The event can optionally be propagated to event parents.
  462. fire: function (type, data, propagate) {
  463. if (!this.listens(type, propagate)) { return this; }
  464. var event = L.Util.extend({}, data, {type: type, target: this});
  465. if (this._events) {
  466. var listeners = this._events[type];
  467. if (listeners) {
  468. this._firingCount = (this._firingCount + 1) || 1;
  469. for (var i = 0, len = listeners.length; i < len; i++) {
  470. var l = listeners[i];
  471. l.fn.call(l.ctx || this, event);
  472. }
  473. this._firingCount--;
  474. }
  475. }
  476. if (propagate) {
  477. // propagate the event to parents (set with addEventParent)
  478. this._propagateEvent(event);
  479. }
  480. return this;
  481. },
  482. // @method listens(type: String): Boolean
  483. // Returns `true` if a particular event type has any listeners attached to it.
  484. listens: function (type, propagate) {
  485. var listeners = this._events && this._events[type];
  486. if (listeners && listeners.length) { return true; }
  487. if (propagate) {
  488. // also check parents for listeners if event propagates
  489. for (var id in this._eventParents) {
  490. if (this._eventParents[id].listens(type, propagate)) { return true; }
  491. }
  492. }
  493. return false;
  494. },
  495. // @method once(…): this
  496. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  497. once: function (types, fn, context) {
  498. if (typeof types === 'object') {
  499. for (var type in types) {
  500. this.once(type, types[type], fn);
  501. }
  502. return this;
  503. }
  504. var handler = L.bind(function () {
  505. this
  506. .off(types, fn, context)
  507. .off(types, handler, context);
  508. }, this);
  509. // add a listener that's executed once and removed after that
  510. return this
  511. .on(types, fn, context)
  512. .on(types, handler, context);
  513. },
  514. // @method addEventParent(obj: Evented): this
  515. // Adds an event parent - an `Evented` that will receive propagated events
  516. addEventParent: function (obj) {
  517. this._eventParents = this._eventParents || {};
  518. this._eventParents[L.stamp(obj)] = obj;
  519. return this;
  520. },
  521. // @method removeEventParent(obj: Evented): this
  522. // Removes an event parent, so it will stop receiving propagated events
  523. removeEventParent: function (obj) {
  524. if (this._eventParents) {
  525. delete this._eventParents[L.stamp(obj)];
  526. }
  527. return this;
  528. },
  529. _propagateEvent: function (e) {
  530. for (var id in this._eventParents) {
  531. this._eventParents[id].fire(e.type, L.extend({layer: e.target}, e), true);
  532. }
  533. }
  534. });
  535. var proto = L.Evented.prototype;
  536. // aliases; we should ditch those eventually
  537. // @method addEventListener(…): this
  538. // Alias to [`on(…)`](#evented-on)
  539. proto.addEventListener = proto.on;
  540. // @method removeEventListener(…): this
  541. // Alias to [`off(…)`](#evented-off)
  542. // @method clearAllEventListeners(…): this
  543. // Alias to [`off()`](#evented-off)
  544. proto.removeEventListener = proto.clearAllEventListeners = proto.off;
  545. // @method addOneTimeEventListener(…): this
  546. // Alias to [`once(…)`](#evented-once)
  547. proto.addOneTimeEventListener = proto.once;
  548. // @method fireEvent(…): this
  549. // Alias to [`fire(…)`](#evented-fire)
  550. proto.fireEvent = proto.fire;
  551. // @method hasEventListeners(…): Boolean
  552. // Alias to [`listens(…)`](#evented-listens)
  553. proto.hasEventListeners = proto.listens;
  554. L.Mixin = {Events: proto};
  555. /*
  556. * @namespace Browser
  557. * @aka L.Browser
  558. *
  559. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  560. *
  561. * @example
  562. *
  563. * ```js
  564. * if (L.Browser.ielt9) {
  565. * alert('Upgrade your browser, dude!');
  566. * }
  567. * ```
  568. */
  569. (function () {
  570. var ua = navigator.userAgent.toLowerCase(),
  571. doc = document.documentElement,
  572. ie = 'ActiveXObject' in window,
  573. webkit = ua.indexOf('webkit') !== -1,
  574. phantomjs = ua.indexOf('phantom') !== -1,
  575. android23 = ua.search('android [23]') !== -1,
  576. chrome = ua.indexOf('chrome') !== -1,
  577. gecko = ua.indexOf('gecko') !== -1 && !webkit && !window.opera && !ie,
  578. win = navigator.platform.indexOf('Win') === 0,
  579. mobile = typeof orientation !== 'undefined' || ua.indexOf('mobile') !== -1,
  580. msPointer = !window.PointerEvent && window.MSPointerEvent,
  581. //pointer = window.PointerEvent || msPointer,
  582. pointer = (window.PointerEvent && window.navigator.pointerEnabled && window.navigator.maxTouchPoints) ||
  583. msPointer,
  584. ie3d = ie && ('transition' in doc.style),
  585. webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23,
  586. gecko3d = 'MozPerspective' in doc.style,
  587. opera12 = 'OTransition' in doc.style;
  588. //var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
  589. // (window.DocumentTouch && document instanceof window.DocumentTouch));
  590. var touch = !window.L_NO_TOUCH && !phantomjs && (function () {
  591. var startName = 'ontouchstart';
  592. // IE10+ (We simulate these into touch* events in L.DomEvent and L.DomEvent.Pointer) or WebKit, etc.
  593. if (pointer || (startName in doc)) {
  594. return true;
  595. }
  596. // Firefox/Gecko
  597. var div = document.createElement('div'),
  598. supported = false;
  599. if (!div.setAttribute) {
  600. return false;
  601. }
  602. div.setAttribute(startName, 'return;');
  603. if (typeof div[startName] === 'function') {
  604. supported = true;
  605. }
  606. div.removeAttribute(startName);
  607. div = null;
  608. return supported;
  609. }());
  610. L.Browser = {
  611. // @property ie: Boolean
  612. // `true` for all Internet Explorer versions (not Edge).
  613. ie: ie,
  614. // @property ielt9: Boolean
  615. // `true` for Internet Explorer versions less than 9.
  616. ielt9: ie && !document.addEventListener,
  617. // @property edge: Boolean
  618. // `true` for the Edge web browser.
  619. edge: 'msLaunchUri' in navigator && !('documentMode' in document),
  620. // @property webkit: Boolean
  621. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  622. webkit: webkit,
  623. // @property gecko: Boolean
  624. // `true` for gecko-based browsers like Firefox.
  625. gecko: gecko,
  626. // @property android: Boolean
  627. // `true` for any browser running on an Android platform.
  628. android: ua.indexOf('android') !== -1,
  629. // @property android23: Boolean
  630. // `true` for browsers running on Android 2 or Android 3.
  631. android23: android23,
  632. // @property chrome: Boolean
  633. // `true` for the Chrome browser.
  634. chrome: chrome,
  635. // @property safari: Boolean
  636. // `true` for the Safari browser.
  637. safari: !chrome && ua.indexOf('safari') !== -1,
  638. // @property win: Boolean
  639. // `true` when the browser is running in a Windows platform
  640. win: win,
  641. // @property ie3d: Boolean
  642. // `true` for all Internet Explorer versions supporting CSS transforms.
  643. ie3d: ie3d,
  644. // @property webkit3d: Boolean
  645. // `true` for webkit-based browsers supporting CSS transforms.
  646. webkit3d: webkit3d,
  647. // @property gecko3d: Boolean
  648. // `true` for gecko-based browsers supporting CSS transforms.
  649. gecko3d: gecko3d,
  650. // @property opera12: Boolean
  651. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  652. opera12: opera12,
  653. // @property any3d: Boolean
  654. // `true` for all browsers supporting CSS transforms.
  655. any3d: !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantomjs,
  656. // @property mobile: Boolean
  657. // `true` for all browsers running in a mobile device.
  658. mobile: mobile,
  659. // @property mobileWebkit: Boolean
  660. // `true` for all webkit-based browsers in a mobile device.
  661. mobileWebkit: mobile && webkit,
  662. // @property mobileWebkit3d: Boolean
  663. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  664. mobileWebkit3d: mobile && webkit3d,
  665. // @property mobileOpera: Boolean
  666. // `true` for the Opera browser in a mobile device.
  667. mobileOpera: mobile && window.opera,
  668. // @property mobileGecko: Boolean
  669. // `true` for gecko-based browsers running in a mobile device.
  670. mobileGecko: mobile && gecko,
  671. // @property touch: Boolean
  672. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  673. // This does not necessarily mean that the browser is running in a computer with
  674. // a touchscreen, it only means that the browser is capable of understanding
  675. // touch events.
  676. touch: !!touch,
  677. // @property msPointer: Boolean
  678. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  679. msPointer: !!msPointer,
  680. // @property pointer: Boolean
  681. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  682. pointer: !!pointer,
  683. // @property retina: Boolean
  684. // `true` for browsers on a high-resolution "retina" screen.
  685. retina: (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1
  686. };
  687. }());
  688. /*
  689. * @class Point
  690. * @aka L.Point
  691. *
  692. * Represents a point with `x` and `y` coordinates in pixels.
  693. *
  694. * @example
  695. *
  696. * ```js
  697. * var point = L.point(200, 300);
  698. * ```
  699. *
  700. * 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:
  701. *
  702. * ```js
  703. * map.panBy([200, 300]);
  704. * map.panBy(L.point(200, 300));
  705. * ```
  706. */
  707. L.Point = function (x, y, round) {
  708. // @property x: Number; The `x` coordinate of the point
  709. this.x = (round ? Math.round(x) : x);
  710. // @property y: Number; The `y` coordinate of the point
  711. this.y = (round ? Math.round(y) : y);
  712. };
  713. L.Point.prototype = {
  714. // @method clone(): Point
  715. // Returns a copy of the current point.
  716. clone: function () {
  717. return new L.Point(this.x, this.y);
  718. },
  719. // @method add(otherPoint: Point): Point
  720. // Returns the result of addition of the current and the given points.
  721. add: function (point) {
  722. // non-destructive, returns a new point
  723. return this.clone()._add(L.point(point));
  724. },
  725. _add: function (point) {
  726. // destructive, used directly for performance in situations where it's safe to modify existing point
  727. this.x += point.x;
  728. this.y += point.y;
  729. return this;
  730. },
  731. // @method subtract(otherPoint: Point): Point
  732. // Returns the result of subtraction of the given point from the current.
  733. subtract: function (point) {
  734. return this.clone()._subtract(L.point(point));
  735. },
  736. _subtract: function (point) {
  737. this.x -= point.x;
  738. this.y -= point.y;
  739. return this;
  740. },
  741. // @method divideBy(num: Number): Point
  742. // Returns the result of division of the current point by the given number.
  743. divideBy: function (num) {
  744. return this.clone()._divideBy(num);
  745. },
  746. _divideBy: function (num) {
  747. this.x /= num;
  748. this.y /= num;
  749. return this;
  750. },
  751. // @method multiplyBy(num: Number): Point
  752. // Returns the result of multiplication of the current point by the given number.
  753. multiplyBy: function (num) {
  754. return this.clone()._multiplyBy(num);
  755. },
  756. _multiplyBy: function (num) {
  757. this.x *= num;
  758. this.y *= num;
  759. return this;
  760. },
  761. // @method scaleBy(scale: Point): Point
  762. // Multiply each coordinate of the current point by each coordinate of
  763. // `scale`. In linear algebra terms, multiply the point by the
  764. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  765. // defined by `scale`.
  766. scaleBy: function (point) {
  767. return new L.Point(this.x * point.x, this.y * point.y);
  768. },
  769. // @method unscaleBy(scale: Point): Point
  770. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  771. // each coordinate of `scale`.
  772. unscaleBy: function (point) {
  773. return new L.Point(this.x / point.x, this.y / point.y);
  774. },
  775. // @method round(): Point
  776. // Returns a copy of the current point with rounded coordinates.
  777. round: function () {
  778. return this.clone()._round();
  779. },
  780. _round: function () {
  781. this.x = Math.round(this.x);
  782. this.y = Math.round(this.y);
  783. return this;
  784. },
  785. // @method floor(): Point
  786. // Returns a copy of the current point with floored coordinates (rounded down).
  787. floor: function () {
  788. return this.clone()._floor();
  789. },
  790. _floor: function () {
  791. this.x = Math.floor(this.x);
  792. this.y = Math.floor(this.y);
  793. return this;
  794. },
  795. // @method ceil(): Point
  796. // Returns a copy of the current point with ceiled coordinates (rounded up).
  797. ceil: function () {
  798. return this.clone()._ceil();
  799. },
  800. _ceil: function () {
  801. this.x = Math.ceil(this.x);
  802. this.y = Math.ceil(this.y);
  803. return this;
  804. },
  805. // @method distanceTo(otherPoint: Point): Number
  806. // Returns the cartesian distance between the current and the given points.
  807. distanceTo: function (point) {
  808. point = L.point(point);
  809. var x = point.x - this.x,
  810. y = point.y - this.y;
  811. return Math.sqrt(x * x + y * y);
  812. },
  813. // @method equals(otherPoint: Point): Boolean
  814. // Returns `true` if the given point has the same coordinates.
  815. equals: function (point) {
  816. point = L.point(point);
  817. return point.x === this.x &&
  818. point.y === this.y;
  819. },
  820. // @method contains(otherPoint: Point): Boolean
  821. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  822. contains: function (point) {
  823. point = L.point(point);
  824. return Math.abs(point.x) <= Math.abs(this.x) &&
  825. Math.abs(point.y) <= Math.abs(this.y);
  826. },
  827. // @method toString(): String
  828. // Returns a string representation of the point for debugging purposes.
  829. toString: function () {
  830. return 'Point(' +
  831. L.Util.formatNum(this.x) + ', ' +
  832. L.Util.formatNum(this.y) + ')';
  833. }
  834. };
  835. // @factory L.point(x: Number, y: Number, round?: Boolean)
  836. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  837. // @alternative
  838. // @factory L.point(coords: Number[])
  839. // Expects an array of the form `[x, y]` instead.
  840. // @alternative
  841. // @factory L.point(coords: Object)
  842. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  843. L.point = function (x, y, round) {
  844. if (x instanceof L.Point) {
  845. return x;
  846. }
  847. if (L.Util.isArray(x)) {
  848. return new L.Point(x[0], x[1]);
  849. }
  850. if (x === undefined || x === null) {
  851. return x;
  852. }
  853. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  854. return new L.Point(x.x, x.y);
  855. }
  856. return new L.Point(x, y, round);
  857. };
  858. /*
  859. * @class Bounds
  860. * @aka L.Bounds
  861. *
  862. * Represents a rectangular area in pixel coordinates.
  863. *
  864. * @example
  865. *
  866. * ```js
  867. * var p1 = L.point(10, 10),
  868. * p2 = L.point(40, 60),
  869. * bounds = L.bounds(p1, p2);
  870. * ```
  871. *
  872. * 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:
  873. *
  874. * ```js
  875. * otherBounds.intersects([[10, 10], [40, 60]]);
  876. * ```
  877. */
  878. L.Bounds = function (a, b) {
  879. if (!a) { return; }
  880. var points = b ? [a, b] : a;
  881. for (var i = 0, len = points.length; i < len; i++) {
  882. this.extend(points[i]);
  883. }
  884. };
  885. L.Bounds.prototype = {
  886. // @method extend(point: Point): this
  887. // Extends the bounds to contain the given point.
  888. extend: function (point) { // (Point)
  889. point = L.point(point);
  890. // @property min: Point
  891. // The top left corner of the rectangle.
  892. // @property max: Point
  893. // The bottom right corner of the rectangle.
  894. if (!this.min && !this.max) {
  895. this.min = point.clone();
  896. this.max = point.clone();
  897. } else {
  898. this.min.x = Math.min(point.x, this.min.x);
  899. this.max.x = Math.max(point.x, this.max.x);
  900. this.min.y = Math.min(point.y, this.min.y);
  901. this.max.y = Math.max(point.y, this.max.y);
  902. }
  903. return this;
  904. },
  905. // @method getCenter(round?: Boolean): Point
  906. // Returns the center point of the bounds.
  907. getCenter: function (round) {
  908. return new L.Point(
  909. (this.min.x + this.max.x) / 2,
  910. (this.min.y + this.max.y) / 2, round);
  911. },
  912. // @method getBottomLeft(): Point
  913. // Returns the bottom-left point of the bounds.
  914. getBottomLeft: function () {
  915. return new L.Point(this.min.x, this.max.y);
  916. },
  917. // @method getTopRight(): Point
  918. // Returns the top-right point of the bounds.
  919. getTopRight: function () { // -> Point
  920. return new L.Point(this.max.x, this.min.y);
  921. },
  922. // @method getSize(): Point
  923. // Returns the size of the given bounds
  924. getSize: function () {
  925. return this.max.subtract(this.min);
  926. },
  927. // @method contains(otherBounds: Bounds): Boolean
  928. // Returns `true` if the rectangle contains the given one.
  929. // @alternative
  930. // @method contains(point: Point): Boolean
  931. // Returns `true` if the rectangle contains the given point.
  932. contains: function (obj) {
  933. var min, max;
  934. if (typeof obj[0] === 'number' || obj instanceof L.Point) {
  935. obj = L.point(obj);
  936. } else {
  937. obj = L.bounds(obj);
  938. }
  939. if (obj instanceof L.Bounds) {
  940. min = obj.min;
  941. max = obj.max;
  942. } else {
  943. min = max = obj;
  944. }
  945. return (min.x >= this.min.x) &&
  946. (max.x <= this.max.x) &&
  947. (min.y >= this.min.y) &&
  948. (max.y <= this.max.y);
  949. },
  950. // @method intersects(otherBounds: Bounds): Boolean
  951. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  952. // intersect if they have at least one point in common.
  953. intersects: function (bounds) { // (Bounds) -> Boolean
  954. bounds = L.bounds(bounds);
  955. var min = this.min,
  956. max = this.max,
  957. min2 = bounds.min,
  958. max2 = bounds.max,
  959. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  960. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  961. return xIntersects && yIntersects;
  962. },
  963. // @method overlaps(otherBounds: Bounds): Boolean
  964. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  965. // overlap if their intersection is an area.
  966. overlaps: function (bounds) { // (Bounds) -> Boolean
  967. bounds = L.bounds(bounds);
  968. var min = this.min,
  969. max = this.max,
  970. min2 = bounds.min,
  971. max2 = bounds.max,
  972. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  973. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  974. return xOverlaps && yOverlaps;
  975. },
  976. isValid: function () {
  977. return !!(this.min && this.max);
  978. }
  979. };
  980. // @factory L.bounds(topLeft: Point, bottomRight: Point)
  981. // Creates a Bounds object from two coordinates (usually top-left and bottom-right corners).
  982. // @alternative
  983. // @factory L.bounds(points: Point[])
  984. // Creates a Bounds object from the points it contains
  985. L.bounds = function (a, b) {
  986. if (!a || a instanceof L.Bounds) {
  987. return a;
  988. }
  989. return new L.Bounds(a, b);
  990. };
  991. /*
  992. * @class Transformation
  993. * @aka L.Transformation
  994. *
  995. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  996. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  997. * the reverse. Used by Leaflet in its projections code.
  998. *
  999. * @example
  1000. *
  1001. * ```js
  1002. * var transformation = new L.Transformation(2, 5, -1, 10),
  1003. * p = L.point(1, 2),
  1004. * p2 = transformation.transform(p), // L.point(7, 8)
  1005. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1006. * ```
  1007. */
  1008. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1009. // Creates a `Transformation` object with the given coefficients.
  1010. L.Transformation = function (a, b, c, d) {
  1011. this._a = a;
  1012. this._b = b;
  1013. this._c = c;
  1014. this._d = d;
  1015. };
  1016. L.Transformation.prototype = {
  1017. // @method transform(point: Point, scale?: Number): Point
  1018. // Returns a transformed point, optionally multiplied by the given scale.
  1019. // Only accepts actual `L.Point` instances, not arrays.
  1020. transform: function (point, scale) { // (Point, Number) -> Point
  1021. return this._transform(point.clone(), scale);
  1022. },
  1023. // destructive transform (faster)
  1024. _transform: function (point, scale) {
  1025. scale = scale || 1;
  1026. point.x = scale * (this._a * point.x + this._b);
  1027. point.y = scale * (this._c * point.y + this._d);
  1028. return point;
  1029. },
  1030. // @method untransform(point: Point, scale?: Number): Point
  1031. // Returns the reverse transformation of the given point, optionally divided
  1032. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1033. untransform: function (point, scale) {
  1034. scale = scale || 1;
  1035. return new L.Point(
  1036. (point.x / scale - this._b) / this._a,
  1037. (point.y / scale - this._d) / this._c);
  1038. }
  1039. };
  1040. /*
  1041. * @namespace DomUtil
  1042. *
  1043. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1044. * tree, used by Leaflet internally.
  1045. *
  1046. * Most functions expecting or returning a `HTMLElement` also work for
  1047. * SVG elements. The only difference is that classes refer to CSS classes
  1048. * in HTML and SVG classes in SVG.
  1049. */
  1050. L.DomUtil = {
  1051. // @function get(id: String|HTMLElement): HTMLElement
  1052. // Returns an element given its DOM id, or returns the element itself
  1053. // if it was passed directly.
  1054. get: function (id) {
  1055. return typeof id === 'string' ? document.getElementById(id) : id;
  1056. },
  1057. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1058. // Returns the value for a certain style attribute on an element,
  1059. // including computed values or values set through CSS.
  1060. getStyle: function (el, style) {
  1061. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1062. if ((!value || value === 'auto') && document.defaultView) {
  1063. var css = document.defaultView.getComputedStyle(el, null);
  1064. value = css ? css[style] : null;
  1065. }
  1066. return value === 'auto' ? null : value;
  1067. },
  1068. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1069. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1070. create: function (tagName, className, container) {
  1071. var el = document.createElement(tagName);
  1072. el.className = className || '';
  1073. if (container) {
  1074. container.appendChild(el);
  1075. }
  1076. return el;
  1077. },
  1078. // @function remove(el: HTMLElement)
  1079. // Removes `el` from its parent element
  1080. remove: function (el) {
  1081. var parent = el.parentNode;
  1082. if (parent) {
  1083. parent.removeChild(el);
  1084. }
  1085. },
  1086. // @function empty(el: HTMLElement)
  1087. // Removes all of `el`'s children elements from `el`
  1088. empty: function (el) {
  1089. while (el.firstChild) {
  1090. el.removeChild(el.firstChild);
  1091. }
  1092. },
  1093. // @function toFront(el: HTMLElement)
  1094. // Makes `el` the last children of its parent, so it renders in front of the other children.
  1095. toFront: function (el) {
  1096. el.parentNode.appendChild(el);
  1097. },
  1098. // @function toBack(el: HTMLElement)
  1099. // Makes `el` the first children of its parent, so it renders back from the other children.
  1100. toBack: function (el) {
  1101. var parent = el.parentNode;
  1102. parent.insertBefore(el, parent.firstChild);
  1103. },
  1104. // @function hasClass(el: HTMLElement, name: String): Boolean
  1105. // Returns `true` if the element's class attribute contains `name`.
  1106. hasClass: function (el, name) {
  1107. if (el.classList !== undefined) {
  1108. return el.classList.contains(name);
  1109. }
  1110. var className = L.DomUtil.getClass(el);
  1111. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  1112. },
  1113. // @function addClass(el: HTMLElement, name: String)
  1114. // Adds `name` to the element's class attribute.
  1115. addClass: function (el, name) {
  1116. if (el.classList !== undefined) {
  1117. var classes = L.Util.splitWords(name);
  1118. for (var i = 0, len = classes.length; i < len; i++) {
  1119. el.classList.add(classes[i]);
  1120. }
  1121. } else if (!L.DomUtil.hasClass(el, name)) {
  1122. var className = L.DomUtil.getClass(el);
  1123. L.DomUtil.setClass(el, (className ? className + ' ' : '') + name);
  1124. }
  1125. },
  1126. // @function removeClass(el: HTMLElement, name: String)
  1127. // Removes `name` from the element's class attribute.
  1128. removeClass: function (el, name) {
  1129. if (el.classList !== undefined) {
  1130. el.classList.remove(name);
  1131. } else {
  1132. L.DomUtil.setClass(el, L.Util.trim((' ' + L.DomUtil.getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  1133. }
  1134. },
  1135. // @function setClass(el: HTMLElement, name: String)
  1136. // Sets the element's class.
  1137. setClass: function (el, name) {
  1138. if (el.className.baseVal === undefined) {
  1139. el.className = name;
  1140. } else {
  1141. // in case of SVG element
  1142. el.className.baseVal = name;
  1143. }
  1144. },
  1145. // @function getClass(el: HTMLElement): String
  1146. // Returns the element's class.
  1147. getClass: function (el) {
  1148. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  1149. },
  1150. // @function setOpacity(el: HTMLElement, opacity: Number)
  1151. // Set the opacity of an element (including old IE support).
  1152. // `opacity` must be a number from `0` to `1`.
  1153. setOpacity: function (el, value) {
  1154. if ('opacity' in el.style) {
  1155. el.style.opacity = value;
  1156. } else if ('filter' in el.style) {
  1157. L.DomUtil._setOpacityIE(el, value);
  1158. }
  1159. },
  1160. _setOpacityIE: function (el, value) {
  1161. var filter = false,
  1162. filterName = 'DXImageTransform.Microsoft.Alpha';
  1163. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  1164. try {
  1165. filter = el.filters.item(filterName);
  1166. } catch (e) {
  1167. // don't set opacity to 1 if we haven't already set an opacity,
  1168. // it isn't needed and breaks transparent pngs.
  1169. if (value === 1) { return; }
  1170. }
  1171. value = Math.round(value * 100);
  1172. if (filter) {
  1173. filter.Enabled = (value !== 100);
  1174. filter.Opacity = value;
  1175. } else {
  1176. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  1177. }
  1178. },
  1179. // @function testProp(props: String[]): String|false
  1180. // Goes through the array of style names and returns the first name
  1181. // that is a valid style name for an element. If no such name is found,
  1182. // it returns false. Useful for vendor-prefixed styles like `transform`.
  1183. testProp: function (props) {
  1184. var style = document.documentElement.style;
  1185. for (var i = 0; i < props.length; i++) {
  1186. if (props[i] in style) {
  1187. return props[i];
  1188. }
  1189. }
  1190. return false;
  1191. },
  1192. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  1193. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  1194. // and optionally scaled by `scale`. Does not have an effect if the
  1195. // browser doesn't support 3D CSS transforms.
  1196. setTransform: function (el, offset, scale) {
  1197. var pos = offset || new L.Point(0, 0);
  1198. el.style[L.DomUtil.TRANSFORM] =
  1199. (L.Browser.ie3d ?
  1200. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  1201. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  1202. (scale ? ' scale(' + scale + ')' : '');
  1203. },
  1204. // @function setPosition(el: HTMLElement, position: Point)
  1205. // Sets the position of `el` to coordinates specified by `position`,
  1206. // using CSS translate or top/left positioning depending on the browser
  1207. // (used by Leaflet internally to position its layers).
  1208. setPosition: function (el, point) { // (HTMLElement, Point[, Boolean])
  1209. /*eslint-disable */
  1210. el._leaflet_pos = point;
  1211. /*eslint-enable */
  1212. if (L.Browser.any3d) {
  1213. L.DomUtil.setTransform(el, point);
  1214. } else {
  1215. el.style.left = point.x + 'px';
  1216. el.style.top = point.y + 'px';
  1217. }
  1218. },
  1219. // @function getPosition(el: HTMLElement): Point
  1220. // Returns the coordinates of an element previously positioned with setPosition.
  1221. getPosition: function (el) {
  1222. // this method is only used for elements previously positioned using setPosition,
  1223. // so it's safe to cache the position for performance
  1224. return el._leaflet_pos || new L.Point(0, 0);
  1225. }
  1226. };
  1227. (function () {
  1228. // prefix style property names
  1229. // @property TRANSFORM: String
  1230. // Vendor-prefixed fransform style name (e.g. `'webkitTransform'` for WebKit).
  1231. L.DomUtil.TRANSFORM = L.DomUtil.testProp(
  1232. ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1233. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1234. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1235. // @property TRANSITION: String
  1236. // Vendor-prefixed transform style name.
  1237. var transition = L.DomUtil.TRANSITION = L.DomUtil.testProp(
  1238. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1239. L.DomUtil.TRANSITION_END =
  1240. transition === 'webkitTransition' || transition === 'OTransition' ? transition + 'End' : 'transitionend';
  1241. // @function disableTextSelection()
  1242. // Prevents the user from generating `selectstart` DOM events, usually generated
  1243. // when the user drags the mouse through a page with text. Used internally
  1244. // by Leaflet to override the behaviour of any click-and-drag interaction on
  1245. // the map. Affects drag interactions on the whole document.
  1246. // @function enableTextSelection()
  1247. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  1248. if ('onselectstart' in document) {
  1249. L.DomUtil.disableTextSelection = function () {
  1250. L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
  1251. };
  1252. L.DomUtil.enableTextSelection = function () {
  1253. L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
  1254. };
  1255. } else {
  1256. var userSelectProperty = L.DomUtil.testProp(
  1257. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  1258. L.DomUtil.disableTextSelection = function () {
  1259. if (userSelectProperty) {
  1260. var style = document.documentElement.style;
  1261. this._userSelect = style[userSelectProperty];
  1262. style[userSelectProperty] = 'none';
  1263. }
  1264. };
  1265. L.DomUtil.enableTextSelection = function () {
  1266. if (userSelectProperty) {
  1267. document.documentElement.style[userSelectProperty] = this._userSelect;
  1268. delete this._userSelect;
  1269. }
  1270. };
  1271. }
  1272. // @function disableImageDrag()
  1273. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  1274. // for `dragstart` DOM events, usually generated when the user drags an image.
  1275. L.DomUtil.disableImageDrag = function () {
  1276. L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
  1277. };
  1278. // @function enableImageDrag()
  1279. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  1280. L.DomUtil.enableImageDrag = function () {
  1281. L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
  1282. };
  1283. // @function preventOutline(el: HTMLElement)
  1284. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  1285. // of the element `el` invisible. Used internally by Leaflet to prevent
  1286. // focusable elements from displaying an outline when the user performs a
  1287. // drag interaction on them.
  1288. L.DomUtil.preventOutline = function (element) {
  1289. while (element.tabIndex === -1) {
  1290. element = element.parentNode;
  1291. }
  1292. if (!element || !element.style) { return; }
  1293. L.DomUtil.restoreOutline();
  1294. this._outlineElement = element;
  1295. this._outlineStyle = element.style.outline;
  1296. element.style.outline = 'none';
  1297. L.DomEvent.on(window, 'keydown', L.DomUtil.restoreOutline, this);
  1298. };
  1299. // @function restoreOutline()
  1300. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  1301. L.DomUtil.restoreOutline = function () {
  1302. if (!this._outlineElement) { return; }
  1303. this._outlineElement.style.outline = this._outlineStyle;
  1304. delete this._outlineElement;
  1305. delete this._outlineStyle;
  1306. L.DomEvent.off(window, 'keydown', L.DomUtil.restoreOutline, this);
  1307. };
  1308. })();
  1309. /* @class LatLng
  1310. * @aka L.LatLng
  1311. *
  1312. * Represents a geographical point with a certain latitude and longitude.
  1313. *
  1314. * @example
  1315. *
  1316. * ```
  1317. * var latlng = L.latLng(50.5, 30.5);
  1318. * ```
  1319. *
  1320. * 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:
  1321. *
  1322. * ```
  1323. * map.panTo([50, 30]);
  1324. * map.panTo({lon: 30, lat: 50});
  1325. * map.panTo({lat: 50, lng: 30});
  1326. * map.panTo(L.latLng(50, 30));
  1327. * ```
  1328. */
  1329. L.LatLng = function (lat, lng, alt) {
  1330. if (isNaN(lat) || isNaN(lng)) {
  1331. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1332. }
  1333. // @property lat: Number
  1334. // Latitude in degrees
  1335. this.lat = +lat;
  1336. // @property lng: Number
  1337. // Longitude in degrees
  1338. this.lng = +lng;
  1339. // @property alt: Number
  1340. // Altitude in meters (optional)
  1341. if (alt !== undefined) {
  1342. this.alt = +alt;
  1343. }
  1344. };
  1345. L.extend(L.LatLng, {
  1346. DEG_TO_RAD: Math.PI / 180,
  1347. RAD_TO_DEG: 180 / Math.PI,
  1348. MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
  1349. });
  1350. L.LatLng.prototype = {
  1351. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1352. // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overriden by setting `maxMargin` to a small number.
  1353. equals: function (obj, maxMargin) {
  1354. if (!obj) { return false; }
  1355. obj = L.latLng(obj);
  1356. var margin = Math.max(
  1357. Math.abs(this.lat - obj.lat),
  1358. Math.abs(this.lng - obj.lng));
  1359. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1360. },
  1361. // @method toString(): String
  1362. // Returns a string representation of the point (for debugging purposes).
  1363. toString: function (precision) {
  1364. return 'LatLng(' +
  1365. L.Util.formatNum(this.lat, precision) + ', ' +
  1366. L.Util.formatNum(this.lng, precision) + ')';
  1367. },
  1368. // @method distanceTo(otherLatLng: LatLng): Number
  1369. // Returns the distance (in meters) to the given `LatLng` calculated using the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula).
  1370. distanceTo: function (other) {
  1371. return L.CRS.Earth.distance(this, L.latLng(other));
  1372. },
  1373. // @method wrap(): LatLng
  1374. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1375. wrap: function () {
  1376. return L.CRS.Earth.wrapLatLng(this);
  1377. },
  1378. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1379. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1380. toBounds: function (sizeInMeters) {
  1381. var latAccuracy = 180 * sizeInMeters / 40075017,
  1382. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1383. return L.latLngBounds(
  1384. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1385. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1386. },
  1387. clone: function () {
  1388. return new L.LatLng(this.lat, this.lng, this.alt);
  1389. }
  1390. };
  1391. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1392. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1393. // @alternative
  1394. // @factory L.latLng(coords: Array): LatLng
  1395. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1396. // @alternative
  1397. // @factory L.latLng(coords: Object): LatLng
  1398. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1399. L.latLng = function (a, b, c) {
  1400. if (a instanceof L.LatLng) {
  1401. return a;
  1402. }
  1403. if (L.Util.isArray(a) && typeof a[0] !== 'object') {
  1404. if (a.length === 3) {
  1405. return new L.LatLng(a[0], a[1], a[2]);
  1406. }
  1407. if (a.length === 2) {
  1408. return new L.LatLng(a[0], a[1]);
  1409. }
  1410. return null;
  1411. }
  1412. if (a === undefined || a === null) {
  1413. return a;
  1414. }
  1415. if (typeof a === 'object' && 'lat' in a) {
  1416. return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1417. }
  1418. if (b === undefined) {
  1419. return null;
  1420. }
  1421. return new L.LatLng(a, b, c);
  1422. };
  1423. /*
  1424. * @class LatLngBounds
  1425. * @aka L.LatLngBounds
  1426. *
  1427. * Represents a rectangular geographical area on a map.
  1428. *
  1429. * @example
  1430. *
  1431. * ```js
  1432. * var corner1 = L.latLng(40.712, -74.227),
  1433. * corner2 = L.latLng(40.774, -74.125),
  1434. * bounds = L.latLngBounds(corner1, corner2);
  1435. * ```
  1436. *
  1437. * 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:
  1438. *
  1439. * ```js
  1440. * map.fitBounds([
  1441. * [40.712, -74.227],
  1442. * [40.774, -74.125]
  1443. * ]);
  1444. * ```
  1445. *
  1446. * 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.
  1447. */
  1448. L.LatLngBounds = function (corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  1449. if (!corner1) { return; }
  1450. var latlngs = corner2 ? [corner1, corner2] : corner1;
  1451. for (var i = 0, len = latlngs.length; i < len; i++) {
  1452. this.extend(latlngs[i]);
  1453. }
  1454. };
  1455. L.LatLngBounds.prototype = {
  1456. // @method extend(latlng: LatLng): this
  1457. // Extend the bounds to contain the given point
  1458. // @alternative
  1459. // @method extend(otherBounds: LatLngBounds): this
  1460. // Extend the bounds to contain the given bounds
  1461. extend: function (obj) {
  1462. var sw = this._southWest,
  1463. ne = this._northEast,
  1464. sw2, ne2;
  1465. if (obj instanceof L.LatLng) {
  1466. sw2 = obj;
  1467. ne2 = obj;
  1468. } else if (obj instanceof L.LatLngBounds) {
  1469. sw2 = obj._southWest;
  1470. ne2 = obj._northEast;
  1471. if (!sw2 || !ne2) { return this; }
  1472. } else {
  1473. return obj ? this.extend(L.latLng(obj) || L.latLngBounds(obj)) : this;
  1474. }
  1475. if (!sw && !ne) {
  1476. this._southWest = new L.LatLng(sw2.lat, sw2.lng);
  1477. this._northEast = new L.LatLng(ne2.lat, ne2.lng);
  1478. } else {
  1479. sw.lat = Math.min(sw2.lat, sw.lat);
  1480. sw.lng = Math.min(sw2.lng, sw.lng);
  1481. ne.lat = Math.max(ne2.lat, ne.lat);
  1482. ne.lng = Math.max(ne2.lng, ne.lng);
  1483. }
  1484. return this;
  1485. },
  1486. // @method pad(bufferRatio: Number): LatLngBounds
  1487. // Returns bigger bounds created by extending the current bounds by a given percentage in each direction.
  1488. pad: function (bufferRatio) {
  1489. var sw = this._southWest,
  1490. ne = this._northEast,
  1491. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  1492. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  1493. return new L.LatLngBounds(
  1494. new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  1495. new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  1496. },
  1497. // @method getCenter(): LatLng
  1498. // Returns the center point of the bounds.
  1499. getCenter: function () {
  1500. return new L.LatLng(
  1501. (this._southWest.lat + this._northEast.lat) / 2,
  1502. (this._southWest.lng + this._northEast.lng) / 2);
  1503. },
  1504. // @method getSouthWest(): LatLng
  1505. // Returns the south-west point of the bounds.
  1506. getSouthWest: function () {
  1507. return this._southWest;
  1508. },
  1509. // @method getNorthEast(): LatLng
  1510. // Returns the north-east point of the bounds.
  1511. getNorthEast: function () {
  1512. return this._northEast;
  1513. },
  1514. // @method getNorthWest(): LatLng
  1515. // Returns the north-west point of the bounds.
  1516. getNorthWest: function () {
  1517. return new L.LatLng(this.getNorth(), this.getWest());
  1518. },
  1519. // @method getSouthEast(): LatLng
  1520. // Returns the south-east point of the bounds.
  1521. getSouthEast: function () {
  1522. return new L.LatLng(this.getSouth(), this.getEast());
  1523. },
  1524. // @method getWest(): Number
  1525. // Returns the west longitude of the bounds
  1526. getWest: function () {
  1527. return this._southWest.lng;
  1528. },
  1529. // @method getSouth(): Number
  1530. // Returns the south latitude of the bounds
  1531. getSouth: function () {
  1532. return this._southWest.lat;
  1533. },
  1534. // @method getEast(): Number
  1535. // Returns the east longitude of the bounds
  1536. getEast: function () {
  1537. return this._northEast.lng;
  1538. },
  1539. // @method getNorth(): Number
  1540. // Returns the north latitude of the bounds
  1541. getNorth: function () {
  1542. return this._northEast.lat;
  1543. },
  1544. // @method contains(otherBounds: LatLngBounds): Boolean
  1545. // Returns `true` if the rectangle contains the given one.
  1546. // @alternative
  1547. // @method contains (latlng: LatLng): Boolean
  1548. // Returns `true` if the rectangle contains the given point.
  1549. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1550. if (typeof obj[0] === 'number' || obj instanceof L.LatLng || 'lat' in obj) {
  1551. obj = L.latLng(obj);
  1552. } else {
  1553. obj = L.latLngBounds(obj);
  1554. }
  1555. var sw = this._southWest,
  1556. ne = this._northEast,
  1557. sw2, ne2;
  1558. if (obj instanceof L.LatLngBounds) {
  1559. sw2 = obj.getSouthWest();
  1560. ne2 = obj.getNorthEast();
  1561. } else {
  1562. sw2 = ne2 = obj;
  1563. }
  1564. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1565. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1566. },
  1567. // @method intersects(otherBounds: LatLngBounds): Boolean
  1568. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1569. intersects: function (bounds) {
  1570. bounds = L.latLngBounds(bounds);
  1571. var sw = this._southWest,
  1572. ne = this._northEast,
  1573. sw2 = bounds.getSouthWest(),
  1574. ne2 = bounds.getNorthEast(),
  1575. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1576. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1577. return latIntersects && lngIntersects;
  1578. },
  1579. // @method overlaps(otherBounds: Bounds): Boolean
  1580. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1581. overlaps: function (bounds) {
  1582. bounds = L.latLngBounds(bounds);
  1583. var sw = this._southWest,
  1584. ne = this._northEast,
  1585. sw2 = bounds.getSouthWest(),
  1586. ne2 = bounds.getNorthEast(),
  1587. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1588. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1589. return latOverlaps && lngOverlaps;
  1590. },
  1591. // @method toBBoxString(): String
  1592. // 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.
  1593. toBBoxString: function () {
  1594. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1595. },
  1596. // @method equals(otherBounds: LatLngBounds): Boolean
  1597. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds.
  1598. equals: function (bounds) {
  1599. if (!bounds) { return false; }
  1600. bounds = L.latLngBounds(bounds);
  1601. return this._southWest.equals(bounds.getSouthWest()) &&
  1602. this._northEast.equals(bounds.getNorthEast());
  1603. },
  1604. // @method isValid(): Boolean
  1605. // Returns `true` if the bounds are properly initialized.
  1606. isValid: function () {
  1607. return !!(this._southWest && this._northEast);
  1608. }
  1609. };
  1610. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1611. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1612. // @alternative
  1613. // @factory L.latLngBounds(latlngs: LatLng[])
  1614. // 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).
  1615. L.latLngBounds = function (a, b) {
  1616. if (a instanceof L.LatLngBounds) {
  1617. return a;
  1618. }
  1619. return new L.LatLngBounds(a, b);
  1620. };
  1621. /*
  1622. * @namespace Projection
  1623. * @section
  1624. * Leaflet comes with a set of already defined Projections out of the box:
  1625. *
  1626. * @projection L.Projection.LonLat
  1627. *
  1628. * Equirectangular, or Plate Carree projection — the most simple projection,
  1629. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  1630. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  1631. * `EPSG:3395` and `Simple` CRS.
  1632. */
  1633. L.Projection = {};
  1634. L.Projection.LonLat = {
  1635. project: function (latlng) {
  1636. return new L.Point(latlng.lng, latlng.lat);
  1637. },
  1638. unproject: function (point) {
  1639. return new L.LatLng(point.y, point.x);
  1640. },
  1641. bounds: L.bounds([-180, -90], [180, 90])
  1642. };
  1643. /*
  1644. * @namespace Projection
  1645. * @projection L.Projection.SphericalMercator
  1646. *
  1647. * Spherical Mercator projection — the most common projection for online maps,
  1648. * used by almost all free and commercial tile providers. Assumes that Earth is
  1649. * a sphere. Used by the `EPSG:3857` CRS.
  1650. */
  1651. L.Projection.SphericalMercator = {
  1652. R: 6378137,
  1653. MAX_LATITUDE: 85.0511287798,
  1654. project: function (latlng) {
  1655. var d = Math.PI / 180,
  1656. max = this.MAX_LATITUDE,
  1657. lat = Math.max(Math.min(max, latlng.lat), -max),
  1658. sin = Math.sin(lat * d);
  1659. return new L.Point(
  1660. this.R * latlng.lng * d,
  1661. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1662. },
  1663. unproject: function (point) {
  1664. var d = 180 / Math.PI;
  1665. return new L.LatLng(
  1666. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1667. point.x * d / this.R);
  1668. },
  1669. bounds: (function () {
  1670. var d = 6378137 * Math.PI;
  1671. return L.bounds([-d, -d], [d, d]);
  1672. })()
  1673. };
  1674. /*
  1675. * @class CRS
  1676. * @aka L.CRS
  1677. * Abstract class that defines coordinate reference systems for projecting
  1678. * geographical points into pixel (screen) coordinates and back (and to
  1679. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1680. * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
  1681. *
  1682. * Leaflet defines the most usual CRSs by default. If you want to use a
  1683. * CRS not defined by default, take a look at the
  1684. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1685. */
  1686. L.CRS = {
  1687. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1688. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1689. latLngToPoint: function (latlng, zoom) {
  1690. var projectedPoint = this.projection.project(latlng),
  1691. scale = this.scale(zoom);
  1692. return this.transformation._transform(projectedPoint, scale);
  1693. },
  1694. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1695. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1696. // zoom into geographical coordinates.
  1697. pointToLatLng: function (point, zoom) {
  1698. var scale = this.scale(zoom),
  1699. untransformedPoint = this.transformation.untransform(point, scale);
  1700. return this.projection.unproject(untransformedPoint);
  1701. },
  1702. // @method project(latlng: LatLng): Point
  1703. // Projects geographical coordinates into coordinates in units accepted for
  1704. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1705. project: function (latlng) {
  1706. return this.projection.project(latlng);
  1707. },
  1708. // @method unproject(point: Point): LatLng
  1709. // Given a projected coordinate returns the corresponding LatLng.
  1710. // The inverse of `project`.
  1711. unproject: function (point) {
  1712. return this.projection.unproject(point);
  1713. },
  1714. // @method scale(zoom: Number): Number
  1715. // Returns the scale used when transforming projected coordinates into
  1716. // pixel coordinates for a particular zoom. For example, it returns
  1717. // `256 * 2^zoom` for Mercator-based CRS.
  1718. scale: function (zoom) {
  1719. return 256 * Math.pow(2, zoom);
  1720. },
  1721. // @method zoom(scale: Number): Number
  1722. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1723. // factor of `scale`.
  1724. zoom: function (scale) {
  1725. return Math.log(scale / 256) / Math.LN2;
  1726. },
  1727. // @method getProjectedBounds(zoom: Number): Bounds
  1728. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1729. getProjectedBounds: function (zoom) {
  1730. if (this.infinite) { return null; }
  1731. var b = this.projection.bounds,
  1732. s = this.scale(zoom),
  1733. min = this.transformation.transform(b.min, s),
  1734. max = this.transformation.transform(b.max, s);
  1735. return L.bounds(min, max);
  1736. },
  1737. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1738. // Returns the distance between two geographical coordinates.
  1739. // @property code: String
  1740. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1741. //
  1742. // @property wrapLng: Number[]
  1743. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1744. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1745. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1746. //
  1747. // @property wrapLat: Number[]
  1748. // Like `wrapLng`, but for the latitude (vertical) axis.
  1749. // wrapLng: [min, max],
  1750. // wrapLat: [min, max],
  1751. // @property infinite: Boolean
  1752. // If true, the coordinate space will be unbounded (infinite in both axes)
  1753. infinite: false,
  1754. // @method wrapLatLng(latlng: LatLng): LatLng
  1755. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1756. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1757. // Only accepts actual `L.LatLng` instances, not arrays.
  1758. wrapLatLng: function (latlng) {
  1759. var lng = this.wrapLng ? L.Util.wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1760. lat = this.wrapLat ? L.Util.wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1761. alt = latlng.alt;
  1762. return L.latLng(lat, lng, alt);
  1763. },
  1764. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1765. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1766. // that its center is within the CRS's bounds.
  1767. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1768. wrapLatLngBounds: function (bounds) {
  1769. var center = bounds.getCenter(),
  1770. newCenter = this.wrapLatLng(center),
  1771. latShift = center.lat - newCenter.lat,
  1772. lngShift = center.lng - newCenter.lng;
  1773. if (latShift === 0 && lngShift === 0) {
  1774. return bounds;
  1775. }
  1776. var sw = bounds.getSouthWest(),
  1777. ne = bounds.getNorthEast(),
  1778. newSw = L.latLng({lat: sw.lat - latShift, lng: sw.lng - lngShift}),
  1779. newNe = L.latLng({lat: ne.lat - latShift, lng: ne.lng - lngShift});
  1780. return new L.LatLngBounds(newSw, newNe);
  1781. }
  1782. };
  1783. /*
  1784. * @namespace CRS
  1785. * @crs L.CRS.Simple
  1786. *
  1787. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  1788. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  1789. * axis should still be inverted (going from bottom to top). `distance()` returns
  1790. * simple euclidean distance.
  1791. */
  1792. L.CRS.Simple = L.extend({}, L.CRS, {
  1793. projection: L.Projection.LonLat,
  1794. transformation: new L.Transformation(1, 0, -1, 0),
  1795. scale: function (zoom) {
  1796. return Math.pow(2, zoom);
  1797. },
  1798. zoom: function (scale) {
  1799. return Math.log(scale) / Math.LN2;
  1800. },
  1801. distance: function (latlng1, latlng2) {
  1802. var dx = latlng2.lng - latlng1.lng,
  1803. dy = latlng2.lat - latlng1.lat;
  1804. return Math.sqrt(dx * dx + dy * dy);
  1805. },
  1806. infinite: true
  1807. });
  1808. /*
  1809. * @namespace CRS
  1810. * @crs L.CRS.Earth
  1811. *
  1812. * Serves as the base for CRS that are global such that they cover the earth.
  1813. * Can only be used as the base for other CRS and cannot be used directly,
  1814. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1815. * meters.
  1816. */
  1817. L.CRS.Earth = L.extend({}, L.CRS, {
  1818. wrapLng: [-180, 180],
  1819. // Mean Earth Radius, as recommended for use by
  1820. // the International Union of Geodesy and Geophysics,
  1821. // see http://rosettacode.org/wiki/Haversine_formula
  1822. R: 6371000,
  1823. // distance between two geographical points using spherical law of cosines approximation
  1824. distance: function (latlng1, latlng2) {
  1825. var rad = Math.PI / 180,
  1826. lat1 = latlng1.lat * rad,
  1827. lat2 = latlng2.lat * rad,
  1828. a = Math.sin(lat1) * Math.sin(lat2) +
  1829. Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad);
  1830. return this.R * Math.acos(Math.min(a, 1));
  1831. }
  1832. });
  1833. /*
  1834. * @namespace CRS
  1835. * @crs L.CRS.EPSG3857
  1836. *
  1837. * The most common CRS for online maps, used by almost all free and commercial
  1838. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1839. * Map's `crs` option.
  1840. */
  1841. L.CRS.EPSG3857 = L.extend({}, L.CRS.Earth, {
  1842. code: 'EPSG:3857',
  1843. projection: L.Projection.SphericalMercator,
  1844. transformation: (function () {
  1845. var scale = 0.5 / (Math.PI * L.Projection.SphericalMercator.R);
  1846. return new L.Transformation(scale, 0.5, -scale, 0.5);
  1847. }())
  1848. });
  1849. L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
  1850. code: 'EPSG:900913'
  1851. });
  1852. /*
  1853. * @namespace CRS
  1854. * @crs L.CRS.EPSG4326
  1855. *
  1856. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  1857. *
  1858. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  1859. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  1860. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  1861. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  1862. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  1863. */
  1864. L.CRS.EPSG4326 = L.extend({}, L.CRS.Earth, {
  1865. code: 'EPSG:4326',
  1866. projection: L.Projection.LonLat,
  1867. transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.25)
  1868. });
  1869. /*
  1870. * @class Map
  1871. * @aka L.Map
  1872. * @inherits Evented
  1873. *
  1874. * The central class of the API — it is used to create a map on a page and manipulate it.
  1875. *
  1876. * @example
  1877. *
  1878. * ```js
  1879. * // initialize the map on the "map" div with a given center and zoom
  1880. * var map = L.map('map', {
  1881. * center: [51.505, -0.09],
  1882. * zoom: 13
  1883. * });
  1884. * ```
  1885. *
  1886. */
  1887. L.Map = L.Evented.extend({
  1888. options: {
  1889. // @section Map State Options
  1890. // @option crs: CRS = L.CRS.EPSG3857
  1891. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  1892. // sure what it means.
  1893. crs: L.CRS.EPSG3857,
  1894. // @option center: LatLng = undefined
  1895. // Initial geographic center of the map
  1896. center: undefined,
  1897. // @option zoom: Number = undefined
  1898. // Initial map zoom level
  1899. zoom: undefined,
  1900. // @option minZoom: Number = undefined
  1901. // Minimum zoom level of the map. Overrides any `minZoom` option set on map layers.
  1902. minZoom: undefined,
  1903. // @option maxZoom: Number = undefined
  1904. // Maximum zoom level of the map. Overrides any `maxZoom` option set on map layers.
  1905. maxZoom: undefined,
  1906. // @option layers: Layer[] = []
  1907. // Array of layers that will be added to the map initially
  1908. layers: [],
  1909. // @option maxBounds: LatLngBounds = null
  1910. // When this option is set, the map restricts the view to the given
  1911. // geographical bounds, bouncing the user back if the user tries to pan
  1912. // outside the view. To set the restriction dynamically, use
  1913. // [`setMaxBounds`](#map-setmaxbounds) method.
  1914. maxBounds: undefined,
  1915. // @option renderer: Renderer = *
  1916. // The default method for drawing vector layers on the map. `L.SVG`
  1917. // or `L.Canvas` by default depending on browser support.
  1918. renderer: undefined,
  1919. // @section Animation Options
  1920. // @option zoomAnimation: Boolean = true
  1921. // Whether the map zoom animation is enabled. By default it's enabled
  1922. // in all browsers that support CSS3 Transitions except Android.
  1923. zoomAnimation: true,
  1924. // @option zoomAnimationThreshold: Number = 4
  1925. // Won't animate zoom if the zoom difference exceeds this value.
  1926. zoomAnimationThreshold: 4,
  1927. // @option fadeAnimation: Boolean = true
  1928. // Whether the tile fade animation is enabled. By default it's enabled
  1929. // in all browsers that support CSS3 Transitions except Android.
  1930. fadeAnimation: true,
  1931. // @option markerZoomAnimation: Boolean = true
  1932. // Whether markers animate their zoom with the zoom animation, if disabled
  1933. // they will disappear for the length of the animation. By default it's
  1934. // enabled in all browsers that support CSS3 Transitions except Android.
  1935. markerZoomAnimation: true,
  1936. // @option transform3DLimit: Number = 2^23
  1937. // Defines the maximum size of a CSS translation transform. The default
  1938. // value should not be changed unless a web browser positions layers in
  1939. // the wrong place after doing a large `panBy`.
  1940. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  1941. // @section Interaction Options
  1942. // @option zoomSnap: Number = 1
  1943. // Forces the map's zoom level to always be a multiple of this, particularly
  1944. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  1945. // By default, the zoom level snaps to the nearest integer; lower values
  1946. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  1947. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  1948. zoomSnap: 1,
  1949. // @option zoomDelta: Number = 1
  1950. // Controls how much the map's zoom level will change after a
  1951. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  1952. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  1953. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  1954. zoomDelta: 1,
  1955. // @option trackResize: Boolean = true
  1956. // Whether the map automatically handles browser window resize to update itself.
  1957. trackResize: true
  1958. },
  1959. initialize: function (id, options) { // (HTMLElement or String, Object)
  1960. options = L.setOptions(this, options);
  1961. this._initContainer(id);
  1962. this._initLayout();
  1963. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  1964. this._onResize = L.bind(this._onResize, this);
  1965. this._initEvents();
  1966. if (options.maxBounds) {
  1967. this.setMaxBounds(options.maxBounds);
  1968. }
  1969. if (options.zoom !== undefined) {
  1970. this._zoom = this._limitZoom(options.zoom);
  1971. }
  1972. if (options.center && options.zoom !== undefined) {
  1973. this.setView(L.latLng(options.center), options.zoom, {reset: true});
  1974. }
  1975. this._handlers = [];
  1976. this._layers = {};
  1977. this._zoomBoundLayers = {};
  1978. this._sizeChanged = true;
  1979. this.callInitHooks();
  1980. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  1981. this._zoomAnimated = L.DomUtil.TRANSITION && L.Browser.any3d && !L.Browser.mobileOpera &&
  1982. this.options.zoomAnimation;
  1983. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  1984. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  1985. if (this._zoomAnimated) {
  1986. this._createAnimProxy();
  1987. L.DomEvent.on(this._proxy, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
  1988. }
  1989. this._addLayers(this.options.layers);
  1990. },
  1991. // @section Methods for modifying map state
  1992. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  1993. // Sets the view of the map (geographical center and zoom) with the given
  1994. // animation options.
  1995. setView: function (center, zoom, options) {
  1996. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  1997. center = this._limitCenter(L.latLng(center), zoom, this.options.maxBounds);
  1998. options = options || {};
  1999. this._stop();
  2000. if (this._loaded && !options.reset && options !== true) {
  2001. if (options.animate !== undefined) {
  2002. options.zoom = L.extend({animate: options.animate}, options.zoom);
  2003. options.pan = L.extend({animate: options.animate, duration: options.duration}, options.pan);
  2004. }
  2005. // try animating pan or zoom
  2006. var moved = (this._zoom !== zoom) ?
  2007. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2008. this._tryAnimatedPan(center, options.pan);
  2009. if (moved) {
  2010. // prevent resize handler call, the view will refresh after animation anyway
  2011. clearTimeout(this._sizeTimer);
  2012. return this;
  2013. }
  2014. }
  2015. // animation didn't start, just reset the map view
  2016. this._resetView(center, zoom);
  2017. return this;
  2018. },
  2019. // @method setZoom(zoom: Number, options: Zoom/pan options): this
  2020. // Sets the zoom of the map.
  2021. setZoom: function (zoom, options) {
  2022. if (!this._loaded) {
  2023. this._zoom = zoom;
  2024. return this;
  2025. }
  2026. return this.setView(this.getCenter(), zoom, {zoom: options});
  2027. },
  2028. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2029. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2030. zoomIn: function (delta, options) {
  2031. delta = delta || (L.Browser.any3d ? this.options.zoomDelta : 1);
  2032. return this.setZoom(this._zoom + delta, options);
  2033. },
  2034. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2035. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2036. zoomOut: function (delta, options) {
  2037. delta = delta || (L.Browser.any3d ? this.options.zoomDelta : 1);
  2038. return this.setZoom(this._zoom - delta, options);
  2039. },
  2040. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2041. // Zooms the map while keeping a specified geographical point on the map
  2042. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2043. // @alternative
  2044. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2045. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2046. setZoomAround: function (latlng, zoom, options) {
  2047. var scale = this.getZoomScale(zoom),
  2048. viewHalf = this.getSize().divideBy(2),
  2049. containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
  2050. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2051. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2052. return this.setView(newCenter, zoom, {zoom: options});
  2053. },
  2054. _getBoundsCenterZoom: function (bounds, options) {
  2055. options = options || {};
  2056. bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
  2057. var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
  2058. paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
  2059. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2060. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2061. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2062. swPoint = this.project(bounds.getSouthWest(), zoom),
  2063. nePoint = this.project(bounds.getNorthEast(), zoom),
  2064. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2065. return {
  2066. center: center,
  2067. zoom: zoom
  2068. };
  2069. },
  2070. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2071. // Sets a map view that contains the given geographical bounds with the
  2072. // maximum zoom level possible.
  2073. fitBounds: function (bounds, options) {
  2074. bounds = L.latLngBounds(bounds);
  2075. if (!bounds.isValid()) {
  2076. throw new Error('Bounds are not valid.');
  2077. }
  2078. var target = this._getBoundsCenterZoom(bounds, options);
  2079. return this.setView(target.center, target.zoom, options);
  2080. },
  2081. // @method fitWorld(options?: fitBounds options): this
  2082. // Sets a map view that mostly contains the whole world with the maximum
  2083. // zoom level possible.
  2084. fitWorld: function (options) {
  2085. return this.fitBounds([[-90, -180], [90, 180]], options);
  2086. },
  2087. // @method panTo(latlng: LatLng, options?: Pan options): this
  2088. // Pans the map to a given center.
  2089. panTo: function (center, options) { // (LatLng)
  2090. return this.setView(center, this._zoom, {pan: options});
  2091. },
  2092. // @method panBy(offset: Point): this
  2093. // Pans the map by a given number of pixels (animated).
  2094. panBy: function (offset, options) {
  2095. offset = L.point(offset).round();
  2096. options = options || {};
  2097. if (!offset.x && !offset.y) {
  2098. return this.fire('moveend');
  2099. }
  2100. // If we pan too far, Chrome gets issues with tiles
  2101. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2102. if (options.animate !== true && !this.getSize().contains(offset)) {
  2103. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2104. return this;
  2105. }
  2106. if (!this._panAnim) {
  2107. this._panAnim = new L.PosAnimation();
  2108. this._panAnim.on({
  2109. 'step': this._onPanTransitionStep,
  2110. 'end': this._onPanTransitionEnd
  2111. }, this);
  2112. }
  2113. // don't fire movestart if animating inertia
  2114. if (!options.noMoveStart) {
  2115. this.fire('movestart');
  2116. }
  2117. // animate pan unless animate: false specified
  2118. if (options.animate !== false) {
  2119. L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
  2120. var newPos = this._getMapPanePos().subtract(offset).round();
  2121. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2122. } else {
  2123. this._rawPanBy(offset);
  2124. this.fire('move').fire('moveend');
  2125. }
  2126. return this;
  2127. },
  2128. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2129. // Sets the view of the map (geographical center and zoom) performing a smooth
  2130. // pan-zoom animation.
  2131. flyTo: function (targetCenter, targetZoom, options) {
  2132. options = options || {};
  2133. if (options.animate === false || !L.Browser.any3d) {
  2134. return this.setView(targetCenter, targetZoom, options);
  2135. }
  2136. this._stop();
  2137. var from = this.project(this.getCenter()),
  2138. to = this.project(targetCenter),
  2139. size = this.getSize(),
  2140. startZoom = this._zoom;
  2141. targetCenter = L.latLng(targetCenter);
  2142. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2143. var w0 = Math.max(size.x, size.y),
  2144. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2145. u1 = (to.distanceTo(from)) || 1,
  2146. rho = 1.42,
  2147. rho2 = rho * rho;
  2148. function r(i) {
  2149. var s1 = i ? -1 : 1,
  2150. s2 = i ? w1 : w0,
  2151. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2152. b1 = 2 * s2 * rho2 * u1,
  2153. b = t1 / b1,
  2154. sq = Math.sqrt(b * b + 1) - b;
  2155. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2156. // thus triggering an infinite loop in flyTo
  2157. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2158. return log;
  2159. }
  2160. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2161. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2162. function tanh(n) { return sinh(n) / cosh(n); }
  2163. var r0 = r(0);
  2164. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2165. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2166. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2167. var start = Date.now(),
  2168. S = (r(1) - r0) / rho,
  2169. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2170. function frame() {
  2171. var t = (Date.now() - start) / duration,
  2172. s = easeOut(t) * S;
  2173. if (t <= 1) {
  2174. this._flyToFrame = L.Util.requestAnimFrame(frame, this);
  2175. this._move(
  2176. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2177. this.getScaleZoom(w0 / w(s), startZoom),
  2178. {flyTo: true});
  2179. } else {
  2180. this
  2181. ._move(targetCenter, targetZoom)
  2182. ._moveEnd(true);
  2183. }
  2184. }
  2185. this._moveStart(true);
  2186. frame.call(this);
  2187. return this;
  2188. },
  2189. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2190. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2191. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2192. flyToBounds: function (bounds, options) {
  2193. var target = this._getBoundsCenterZoom(bounds, options);
  2194. return this.flyTo(target.center, target.zoom, options);
  2195. },
  2196. // @method setMaxBounds(bounds: Bounds): this
  2197. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2198. setMaxBounds: function (bounds) {
  2199. bounds = L.latLngBounds(bounds);
  2200. if (!bounds.isValid()) {
  2201. this.options.maxBounds = null;
  2202. return this.off('moveend', this._panInsideMaxBounds);
  2203. } else if (this.options.maxBounds) {
  2204. this.off('moveend', this._panInsideMaxBounds);
  2205. }
  2206. this.options.maxBounds = bounds;
  2207. if (this._loaded) {
  2208. this._panInsideMaxBounds();
  2209. }
  2210. return this.on('moveend', this._panInsideMaxBounds);
  2211. },
  2212. // @method setMinZoom(zoom: Number): this
  2213. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2214. setMinZoom: function (zoom) {
  2215. this.options.minZoom = zoom;
  2216. if (this._loaded && this.getZoom() < this.options.minZoom) {
  2217. return this.setZoom(zoom);
  2218. }
  2219. return this;
  2220. },
  2221. // @method setMaxZoom(zoom: Number): this
  2222. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2223. setMaxZoom: function (zoom) {
  2224. this.options.maxZoom = zoom;
  2225. if (this._loaded && (this.getZoom() > this.options.maxZoom)) {
  2226. return this.setZoom(zoom);
  2227. }
  2228. return this;
  2229. },
  2230. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2231. // 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.
  2232. panInsideBounds: function (bounds, options) {
  2233. this._enforcingBounds = true;
  2234. var center = this.getCenter(),
  2235. newCenter = this._limitCenter(center, this._zoom, L.latLngBounds(bounds));
  2236. if (!center.equals(newCenter)) {
  2237. this.panTo(newCenter, options);
  2238. }
  2239. this._enforcingBounds = false;
  2240. return this;
  2241. },
  2242. // @method invalidateSize(options: Zoom/Pan options): this
  2243. // Checks if the map container size changed and updates the map if so —
  2244. // call it after you've changed the map size dynamically, also animating
  2245. // pan by default. If `options.pan` is `false`, panning will not occur.
  2246. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2247. // that it doesn't happen often even if the method is called many
  2248. // times in a row.
  2249. // @alternative
  2250. // @method invalidateSize(animate: Boolean): this
  2251. // Checks if the map container size changed and updates the map if so —
  2252. // call it after you've changed the map size dynamically, also animating
  2253. // pan by default.
  2254. invalidateSize: function (options) {
  2255. if (!this._loaded) { return this; }
  2256. options = L.extend({
  2257. animate: false,
  2258. pan: true
  2259. }, options === true ? {animate: true} : options);
  2260. var oldSize = this.getSize();
  2261. this._sizeChanged = true;
  2262. this._lastCenter = null;
  2263. var newSize = this.getSize(),
  2264. oldCenter = oldSize.divideBy(2).round(),
  2265. newCenter = newSize.divideBy(2).round(),
  2266. offset = oldCenter.subtract(newCenter);
  2267. if (!offset.x && !offset.y) { return this; }
  2268. if (options.animate && options.pan) {
  2269. this.panBy(offset);
  2270. } else {
  2271. if (options.pan) {
  2272. this._rawPanBy(offset);
  2273. }
  2274. this.fire('move');
  2275. if (options.debounceMoveend) {
  2276. clearTimeout(this._sizeTimer);
  2277. this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
  2278. } else {
  2279. this.fire('moveend');
  2280. }
  2281. }
  2282. // @section Map state change events
  2283. // @event resize: ResizeEvent
  2284. // Fired when the map is resized.
  2285. return this.fire('resize', {
  2286. oldSize: oldSize,
  2287. newSize: newSize
  2288. });
  2289. },
  2290. // @section Methods for modifying map state
  2291. // @method stop(): this
  2292. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2293. stop: function () {
  2294. this.setZoom(this._limitZoom(this._zoom));
  2295. if (!this.options.zoomSnap) {
  2296. this.fire('viewreset');
  2297. }
  2298. return this._stop();
  2299. },
  2300. // @section Geolocation methods
  2301. // @method locate(options?: Locate options): this
  2302. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  2303. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  2304. // and optionally sets the map view to the user's location with respect to
  2305. // detection accuracy (or to the world view if geolocation failed).
  2306. // Note that, if your page doesn't use HTTPS, this method will fail in
  2307. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  2308. // See `Locate options` for more details.
  2309. locate: function (options) {
  2310. options = this._locateOptions = L.extend({
  2311. timeout: 10000,
  2312. watch: false
  2313. // setView: false
  2314. // maxZoom: <Number>
  2315. // maximumAge: 0
  2316. // enableHighAccuracy: false
  2317. }, options);
  2318. if (!('geolocation' in navigator)) {
  2319. this._handleGeolocationError({
  2320. code: 0,
  2321. message: 'Geolocation not supported.'
  2322. });
  2323. return this;
  2324. }
  2325. var onResponse = L.bind(this._handleGeolocationResponse, this),
  2326. onError = L.bind(this._handleGeolocationError, this);
  2327. if (options.watch) {
  2328. this._locationWatchId =
  2329. navigator.geolocation.watchPosition(onResponse, onError, options);
  2330. } else {
  2331. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  2332. }
  2333. return this;
  2334. },
  2335. // @method stopLocate(): this
  2336. // Stops watching location previously initiated by `map.locate({watch: true})`
  2337. // and aborts resetting the map view if map.locate was called with
  2338. // `{setView: true}`.
  2339. stopLocate: function () {
  2340. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  2341. navigator.geolocation.clearWatch(this._locationWatchId);
  2342. }
  2343. if (this._locateOptions) {
  2344. this._locateOptions.setView = false;
  2345. }
  2346. return this;
  2347. },
  2348. _handleGeolocationError: function (error) {
  2349. var c = error.code,
  2350. message = error.message ||
  2351. (c === 1 ? 'permission denied' :
  2352. (c === 2 ? 'position unavailable' : 'timeout'));
  2353. if (this._locateOptions.setView && !this._loaded) {
  2354. this.fitWorld();
  2355. }
  2356. // @section Location events
  2357. // @event locationerror: ErrorEvent
  2358. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  2359. this.fire('locationerror', {
  2360. code: c,
  2361. message: 'Geolocation error: ' + message + '.'
  2362. });
  2363. },
  2364. _handleGeolocationResponse: function (pos) {
  2365. var lat = pos.coords.latitude,
  2366. lng = pos.coords.longitude,
  2367. latlng = new L.LatLng(lat, lng),
  2368. bounds = latlng.toBounds(pos.coords.accuracy),
  2369. options = this._locateOptions;
  2370. if (options.setView) {
  2371. var zoom = this.getBoundsZoom(bounds);
  2372. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  2373. }
  2374. var data = {
  2375. latlng: latlng,
  2376. bounds: bounds,
  2377. timestamp: pos.timestamp
  2378. };
  2379. for (var i in pos.coords) {
  2380. if (typeof pos.coords[i] === 'number') {
  2381. data[i] = pos.coords[i];
  2382. }
  2383. }
  2384. // @event locationfound: LocationEvent
  2385. // Fired when geolocation (using the [`locate`](#map-locate) method)
  2386. // went successfully.
  2387. this.fire('locationfound', data);
  2388. },
  2389. // @section Other Methods
  2390. // @method addHandler(name: String, HandlerClass: Function): this
  2391. // Adds a new `Handler` to the map, given its name and constructor function.
  2392. addHandler: function (name, HandlerClass) {
  2393. if (!HandlerClass) { return this; }
  2394. var handler = this[name] = new HandlerClass(this);
  2395. this._handlers.push(handler);
  2396. if (this.options[name]) {
  2397. handler.enable();
  2398. }
  2399. return this;
  2400. },
  2401. // @method remove(): this
  2402. // Destroys the map and clears all related event listeners.
  2403. remove: function () {
  2404. this._initEvents(true);
  2405. if (this._containerId !== this._container._leaflet_id) {
  2406. throw new Error('Map container is being reused by another instance');
  2407. }
  2408. try {
  2409. // throws error in IE6-8
  2410. delete this._container._leaflet_id;
  2411. delete this._containerId;
  2412. } catch (e) {
  2413. /*eslint-disable */
  2414. this._container._leaflet_id = undefined;
  2415. /*eslint-enable */
  2416. this._containerId = undefined;
  2417. }
  2418. L.DomUtil.remove(this._mapPane);
  2419. if (this._clearControlPos) {
  2420. this._clearControlPos();
  2421. }
  2422. this._clearHandlers();
  2423. if (this._loaded) {
  2424. // @section Map state change events
  2425. // @event unload: Event
  2426. // Fired when the map is destroyed with [remove](#map-remove) method.
  2427. this.fire('unload');
  2428. }
  2429. for (var i in this._layers) {
  2430. this._layers[i].remove();
  2431. }
  2432. return this;
  2433. },
  2434. // @section Other Methods
  2435. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  2436. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  2437. // then returns it. The pane is created as a children of `container`, or
  2438. // as a children of the main map pane if not set.
  2439. createPane: function (name, container) {
  2440. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  2441. pane = L.DomUtil.create('div', className, container || this._mapPane);
  2442. if (name) {
  2443. this._panes[name] = pane;
  2444. }
  2445. return pane;
  2446. },
  2447. // @section Methods for Getting Map State
  2448. // @method getCenter(): LatLng
  2449. // Returns the geographical center of the map view
  2450. getCenter: function () {
  2451. this._checkIfLoaded();
  2452. if (this._lastCenter && !this._moved()) {
  2453. return this._lastCenter;
  2454. }
  2455. return this.layerPointToLatLng(this._getCenterLayerPoint());
  2456. },
  2457. // @method getZoom(): Number
  2458. // Returns the current zoom level of the map view
  2459. getZoom: function () {
  2460. return this._zoom;
  2461. },
  2462. // @method getBounds(): LatLngBounds
  2463. // Returns the geographical bounds visible in the current map view
  2464. getBounds: function () {
  2465. var bounds = this.getPixelBounds(),
  2466. sw = this.unproject(bounds.getBottomLeft()),
  2467. ne = this.unproject(bounds.getTopRight());
  2468. return new L.LatLngBounds(sw, ne);
  2469. },
  2470. // @method getMinZoom(): Number
  2471. // 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.
  2472. getMinZoom: function () {
  2473. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  2474. },
  2475. // @method getMaxZoom(): Number
  2476. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  2477. getMaxZoom: function () {
  2478. return this.options.maxZoom === undefined ?
  2479. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  2480. this.options.maxZoom;
  2481. },
  2482. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean): Number
  2483. // Returns the maximum zoom level on which the given bounds fit to the map
  2484. // view in its entirety. If `inside` (optional) is set to `true`, the method
  2485. // instead returns the minimum zoom level on which the map view fits into
  2486. // the given bounds in its entirety.
  2487. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  2488. bounds = L.latLngBounds(bounds);
  2489. padding = L.point(padding || [0, 0]);
  2490. var zoom = this.getZoom() || 0,
  2491. min = this.getMinZoom(),
  2492. max = this.getMaxZoom(),
  2493. nw = bounds.getNorthWest(),
  2494. se = bounds.getSouthEast(),
  2495. size = this.getSize().subtract(padding),
  2496. boundsSize = L.bounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  2497. snap = L.Browser.any3d ? this.options.zoomSnap : 1;
  2498. var scale = Math.min(size.x / boundsSize.x, size.y / boundsSize.y);
  2499. zoom = this.getScaleZoom(scale, zoom);
  2500. if (snap) {
  2501. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  2502. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  2503. }
  2504. return Math.max(min, Math.min(max, zoom));
  2505. },
  2506. // @method getSize(): Point
  2507. // Returns the current size of the map container (in pixels).
  2508. getSize: function () {
  2509. if (!this._size || this._sizeChanged) {
  2510. this._size = new L.Point(
  2511. this._container.clientWidth || 0,
  2512. this._container.clientHeight || 0);
  2513. this._sizeChanged = false;
  2514. }
  2515. return this._size.clone();
  2516. },
  2517. // @method getPixelBounds(): Bounds
  2518. // Returns the bounds of the current map view in projected pixel
  2519. // coordinates (sometimes useful in layer and overlay implementations).
  2520. getPixelBounds: function (center, zoom) {
  2521. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  2522. return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  2523. },
  2524. // the map pane? "left point of the map layer" can be confusing, specially
  2525. // since there can be negative offsets.
  2526. // @method getPixelOrigin(): Point
  2527. // Returns the projected pixel coordinates of the top left point of
  2528. // the map layer (useful in custom layer and overlay implementations).
  2529. getPixelOrigin: function () {
  2530. this._checkIfLoaded();
  2531. return this._pixelOrigin;
  2532. },
  2533. // @method getPixelWorldBounds(zoom?: Number): Bounds
  2534. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  2535. // If `zoom` is omitted, the map's current zoom level is used.
  2536. getPixelWorldBounds: function (zoom) {
  2537. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  2538. },
  2539. // @section Other Methods
  2540. // @method getPane(pane: String|HTMLElement): HTMLElement
  2541. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  2542. getPane: function (pane) {
  2543. return typeof pane === 'string' ? this._panes[pane] : pane;
  2544. },
  2545. // @method getPanes(): Object
  2546. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  2547. // the panes as values.
  2548. getPanes: function () {
  2549. return this._panes;
  2550. },
  2551. // @method getContainer: HTMLElement
  2552. // Returns the HTML element that contains the map.
  2553. getContainer: function () {
  2554. return this._container;
  2555. },
  2556. // @section Conversion Methods
  2557. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  2558. // Returns the scale factor to be applied to a map transition from zoom level
  2559. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  2560. getZoomScale: function (toZoom, fromZoom) {
  2561. var crs = this.options.crs;
  2562. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  2563. return crs.scale(toZoom) / crs.scale(fromZoom);
  2564. },
  2565. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  2566. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  2567. // level and everything is scaled by a factor of `scale`. Inverse of
  2568. // [`getZoomScale`](#map-getZoomScale).
  2569. getScaleZoom: function (scale, fromZoom) {
  2570. var crs = this.options.crs;
  2571. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  2572. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  2573. return isNaN(zoom) ? Infinity : zoom;
  2574. },
  2575. // @method project(latlng: LatLng, zoom: Number): Point
  2576. // Projects a geographical coordinate `LatLng` according to the projection
  2577. // of the map's CRS, then scales it according to `zoom` and the CRS's
  2578. // `Transformation`. The result is pixel coordinate relative to
  2579. // the CRS origin.
  2580. project: function (latlng, zoom) {
  2581. zoom = zoom === undefined ? this._zoom : zoom;
  2582. return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
  2583. },
  2584. // @method unproject(point: Point, zoom: Number): LatLng
  2585. // Inverse of [`project`](#map-project).
  2586. unproject: function (point, zoom) {
  2587. zoom = zoom === undefined ? this._zoom : zoom;
  2588. return this.options.crs.pointToLatLng(L.point(point), zoom);
  2589. },
  2590. // @method layerPointToLatLng(point: Point): LatLng
  2591. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  2592. // returns the corresponding geographical coordinate (for the current zoom level).
  2593. layerPointToLatLng: function (point) {
  2594. var projectedPoint = L.point(point).add(this.getPixelOrigin());
  2595. return this.unproject(projectedPoint);
  2596. },
  2597. // @method latLngToLayerPoint(latlng: LatLng): Point
  2598. // Given a geographical coordinate, returns the corresponding pixel coordinate
  2599. // relative to the [origin pixel](#map-getpixelorigin).
  2600. latLngToLayerPoint: function (latlng) {
  2601. var projectedPoint = this.project(L.latLng(latlng))._round();
  2602. return projectedPoint._subtract(this.getPixelOrigin());
  2603. },
  2604. // @method wrapLatLng(latlng: LatLng): LatLng
  2605. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  2606. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  2607. // CRS's bounds.
  2608. // By default this means longitude is wrapped around the dateline so its
  2609. // value is between -180 and +180 degrees.
  2610. wrapLatLng: function (latlng) {
  2611. return this.options.crs.wrapLatLng(L.latLng(latlng));
  2612. },
  2613. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  2614. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  2615. // its center is within the CRS's bounds.
  2616. // By default this means the center longitude is wrapped around the dateline so its
  2617. // value is between -180 and +180 degrees, and the majority of the bounds
  2618. // overlaps the CRS's bounds.
  2619. wrapLatLngBounds: function (latlng) {
  2620. return this.options.crs.wrapLatLngBounds(L.latLngBounds(latlng));
  2621. },
  2622. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  2623. // Returns the distance between two geographical coordinates according to
  2624. // the map's CRS. By default this measures distance in meters.
  2625. distance: function (latlng1, latlng2) {
  2626. return this.options.crs.distance(L.latLng(latlng1), L.latLng(latlng2));
  2627. },
  2628. // @method containerPointToLayerPoint(point: Point): Point
  2629. // Given a pixel coordinate relative to the map container, returns the corresponding
  2630. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  2631. containerPointToLayerPoint: function (point) { // (Point)
  2632. return L.point(point).subtract(this._getMapPanePos());
  2633. },
  2634. // @method layerPointToContainerPoint(point: Point): Point
  2635. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  2636. // returns the corresponding pixel coordinate relative to the map container.
  2637. layerPointToContainerPoint: function (point) { // (Point)
  2638. return L.point(point).add(this._getMapPanePos());
  2639. },
  2640. // @method containerPointToLatLng(point: Point): LatLng
  2641. // Given a pixel coordinate relative to the map container, returns
  2642. // the corresponding geographical coordinate (for the current zoom level).
  2643. containerPointToLatLng: function (point) {
  2644. var layerPoint = this.containerPointToLayerPoint(L.point(point));
  2645. return this.layerPointToLatLng(layerPoint);
  2646. },
  2647. // @method latLngToContainerPoint(latlng: LatLng): Point
  2648. // Given a geographical coordinate, returns the corresponding pixel coordinate
  2649. // relative to the map container.
  2650. latLngToContainerPoint: function (latlng) {
  2651. return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
  2652. },
  2653. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  2654. // Given a MouseEvent object, returns the pixel coordinate relative to the
  2655. // map container where the event took place.
  2656. mouseEventToContainerPoint: function (e) {
  2657. return L.DomEvent.getMousePosition(e, this._container);
  2658. },
  2659. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  2660. // Given a MouseEvent object, returns the pixel coordinate relative to
  2661. // the [origin pixel](#map-getpixelorigin) where the event took place.
  2662. mouseEventToLayerPoint: function (e) {
  2663. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  2664. },
  2665. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  2666. // Given a MouseEvent object, returns geographical coordinate where the
  2667. // event took place.
  2668. mouseEventToLatLng: function (e) { // (MouseEvent)
  2669. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  2670. },
  2671. // map initialization methods
  2672. _initContainer: function (id) {
  2673. var container = this._container = L.DomUtil.get(id);
  2674. if (!container) {
  2675. throw new Error('Map container not found.');
  2676. } else if (container._leaflet_id) {
  2677. throw new Error('Map container is already initialized.');
  2678. }
  2679. L.DomEvent.addListener(container, 'scroll', this._onScroll, this);
  2680. this._containerId = L.Util.stamp(container);
  2681. },
  2682. _initLayout: function () {
  2683. var container = this._container;
  2684. this._fadeAnimated = this.options.fadeAnimation && L.Browser.any3d;
  2685. L.DomUtil.addClass(container, 'leaflet-container' +
  2686. (L.Browser.touch ? ' leaflet-touch' : '') +
  2687. (L.Browser.retina ? ' leaflet-retina' : '') +
  2688. (L.Browser.ielt9 ? ' leaflet-oldie' : '') +
  2689. (L.Browser.safari ? ' leaflet-safari' : '') +
  2690. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  2691. var position = L.DomUtil.getStyle(container, 'position');
  2692. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  2693. container.style.position = 'relative';
  2694. }
  2695. this._initPanes();
  2696. if (this._initControlPos) {
  2697. this._initControlPos();
  2698. }
  2699. },
  2700. _initPanes: function () {
  2701. var panes = this._panes = {};
  2702. this._paneRenderers = {};
  2703. // @section
  2704. //
  2705. // Panes are DOM elements used to control the ordering of layers on the map. You
  2706. // can access panes with [`map.getPane`](#map-getpane) or
  2707. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  2708. // [`map.createPane`](#map-createpane) method.
  2709. //
  2710. // Every map has the following default panes that differ only in zIndex.
  2711. //
  2712. // @pane mapPane: HTMLElement = 'auto'
  2713. // Pane that contains all other map panes
  2714. this._mapPane = this.createPane('mapPane', this._container);
  2715. L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
  2716. // @pane tilePane: HTMLElement = 200
  2717. // Pane for `GridLayer`s and `TileLayer`s
  2718. this.createPane('tilePane');
  2719. // @pane overlayPane: HTMLElement = 400
  2720. // Pane for vector overlays (`Path`s), like `Polyline`s and `Polygon`s
  2721. this.createPane('shadowPane');
  2722. // @pane shadowPane: HTMLElement = 500
  2723. // Pane for overlay shadows (e.g. `Marker` shadows)
  2724. this.createPane('overlayPane');
  2725. // @pane markerPane: HTMLElement = 600
  2726. // Pane for `Icon`s of `Marker`s
  2727. this.createPane('markerPane');
  2728. // @pane tooltipPane: HTMLElement = 650
  2729. // Pane for tooltip.
  2730. this.createPane('tooltipPane');
  2731. // @pane popupPane: HTMLElement = 700
  2732. // Pane for `Popup`s.
  2733. this.createPane('popupPane');
  2734. if (!this.options.markerZoomAnimation) {
  2735. L.DomUtil.addClass(panes.markerPane, 'leaflet-zoom-hide');
  2736. L.DomUtil.addClass(panes.shadowPane, 'leaflet-zoom-hide');
  2737. }
  2738. },
  2739. // private methods that modify map state
  2740. // @section Map state change events
  2741. _resetView: function (center, zoom) {
  2742. L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
  2743. var loading = !this._loaded;
  2744. this._loaded = true;
  2745. zoom = this._limitZoom(zoom);
  2746. this.fire('viewprereset');
  2747. var zoomChanged = this._zoom !== zoom;
  2748. this
  2749. ._moveStart(zoomChanged)
  2750. ._move(center, zoom)
  2751. ._moveEnd(zoomChanged);
  2752. // @event viewreset: Event
  2753. // Fired when the map needs to redraw its content (this usually happens
  2754. // on map zoom or load). Very useful for creating custom overlays.
  2755. this.fire('viewreset');
  2756. // @event load: Event
  2757. // Fired when the map is initialized (when its center and zoom are set
  2758. // for the first time).
  2759. if (loading) {
  2760. this.fire('load');
  2761. }
  2762. },
  2763. _moveStart: function (zoomChanged) {
  2764. // @event zoomstart: Event
  2765. // Fired when the map zoom is about to change (e.g. before zoom animation).
  2766. // @event movestart: Event
  2767. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  2768. if (zoomChanged) {
  2769. this.fire('zoomstart');
  2770. }
  2771. return this.fire('movestart');
  2772. },
  2773. _move: function (center, zoom, data) {
  2774. if (zoom === undefined) {
  2775. zoom = this._zoom;
  2776. }
  2777. var zoomChanged = this._zoom !== zoom;
  2778. this._zoom = zoom;
  2779. this._lastCenter = center;
  2780. this._pixelOrigin = this._getNewPixelOrigin(center);
  2781. // @event zoom: Event
  2782. // Fired repeatedly during any change in zoom level, including zoom
  2783. // and fly animations.
  2784. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  2785. this.fire('zoom', data);
  2786. }
  2787. // @event move: Event
  2788. // Fired repeatedly during any movement of the map, including pan and
  2789. // fly animations.
  2790. return this.fire('move', data);
  2791. },
  2792. _moveEnd: function (zoomChanged) {
  2793. // @event zoomend: Event
  2794. // Fired when the map has changed, after any animations.
  2795. if (zoomChanged) {
  2796. this.fire('zoomend');
  2797. }
  2798. // @event moveend: Event
  2799. // Fired when the center of the map stops changing (e.g. user stopped
  2800. // dragging the map).
  2801. return this.fire('moveend');
  2802. },
  2803. _stop: function () {
  2804. L.Util.cancelAnimFrame(this._flyToFrame);
  2805. if (this._panAnim) {
  2806. this._panAnim.stop();
  2807. }
  2808. return this;
  2809. },
  2810. _rawPanBy: function (offset) {
  2811. L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  2812. },
  2813. _getZoomSpan: function () {
  2814. return this.getMaxZoom() - this.getMinZoom();
  2815. },
  2816. _panInsideMaxBounds: function () {
  2817. if (!this._enforcingBounds) {
  2818. this.panInsideBounds(this.options.maxBounds);
  2819. }
  2820. },
  2821. _checkIfLoaded: function () {
  2822. if (!this._loaded) {
  2823. throw new Error('Set map center and zoom first.');
  2824. }
  2825. },
  2826. // DOM event handling
  2827. // @section Interaction events
  2828. _initEvents: function (remove) {
  2829. if (!L.DomEvent) { return; }
  2830. this._targets = {};
  2831. this._targets[L.stamp(this._container)] = this;
  2832. var onOff = remove ? 'off' : 'on';
  2833. // @event click: MouseEvent
  2834. // Fired when the user clicks (or taps) the map.
  2835. // @event dblclick: MouseEvent
  2836. // Fired when the user double-clicks (or double-taps) the map.
  2837. // @event mousedown: MouseEvent
  2838. // Fired when the user pushes the mouse button on the map.
  2839. // @event mouseup: MouseEvent
  2840. // Fired when the user releases the mouse button on the map.
  2841. // @event mouseover: MouseEvent
  2842. // Fired when the mouse enters the map.
  2843. // @event mouseout: MouseEvent
  2844. // Fired when the mouse leaves the map.
  2845. // @event mousemove: MouseEvent
  2846. // Fired while the mouse moves over the map.
  2847. // @event contextmenu: MouseEvent
  2848. // Fired when the user pushes the right mouse button on the map, prevents
  2849. // default browser context menu from showing if there are listeners on
  2850. // this event. Also fired on mobile when the user holds a single touch
  2851. // for a second (also called long press).
  2852. // @event keypress: KeyboardEvent
  2853. // Fired when the user presses a key from the keyboard while the map is focused.
  2854. L.DomEvent[onOff](this._container, 'click dblclick mousedown mouseup ' +
  2855. 'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this);
  2856. if (this.options.trackResize) {
  2857. L.DomEvent[onOff](window, 'resize', this._onResize, this);
  2858. }
  2859. if (L.Browser.any3d && this.options.transform3DLimit) {
  2860. this[onOff]('moveend', this._onMoveEnd);
  2861. }
  2862. },
  2863. _onResize: function () {
  2864. L.Util.cancelAnimFrame(this._resizeRequest);
  2865. this._resizeRequest = L.Util.requestAnimFrame(
  2866. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  2867. },
  2868. _onScroll: function () {
  2869. this._container.scrollTop = 0;
  2870. this._container.scrollLeft = 0;
  2871. },
  2872. _onMoveEnd: function () {
  2873. var pos = this._getMapPanePos();
  2874. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  2875. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  2876. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  2877. this._resetView(this.getCenter(), this.getZoom());
  2878. }
  2879. },
  2880. _findEventTargets: function (e, type) {
  2881. var targets = [],
  2882. target,
  2883. isHover = type === 'mouseout' || type === 'mouseover',
  2884. src = e.target || e.srcElement,
  2885. dragging = false;
  2886. while (src) {
  2887. target = this._targets[L.stamp(src)];
  2888. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  2889. // Prevent firing click after you just dragged an object.
  2890. dragging = true;
  2891. break;
  2892. }
  2893. if (target && target.listens(type, true)) {
  2894. if (isHover && !L.DomEvent._isExternalTarget(src, e)) { break; }
  2895. targets.push(target);
  2896. if (isHover) { break; }
  2897. }
  2898. if (src === this._container) { break; }
  2899. src = src.parentNode;
  2900. }
  2901. if (!targets.length && !dragging && !isHover && L.DomEvent._isExternalTarget(src, e)) {
  2902. targets = [this];
  2903. }
  2904. return targets;
  2905. },
  2906. _handleDOMEvent: function (e) {
  2907. if (!this._loaded || L.DomEvent._skipped(e)) { return; }
  2908. var type = e.type === 'keypress' && e.keyCode === 13 ? 'click' : e.type;
  2909. if (type === 'mousedown') {
  2910. // prevents outline when clicking on keyboard-focusable element
  2911. L.DomUtil.preventOutline(e.target || e.srcElement);
  2912. }
  2913. this._fireDOMEvent(e, type);
  2914. },
  2915. _fireDOMEvent: function (e, type, targets) {
  2916. if (e.type === 'click') {
  2917. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  2918. // @event preclick: MouseEvent
  2919. // Fired before mouse click on the map (sometimes useful when you
  2920. // want something to happen on click before any existing click
  2921. // handlers start running).
  2922. var synth = L.Util.extend({}, e);
  2923. synth.type = 'preclick';
  2924. this._fireDOMEvent(synth, synth.type, targets);
  2925. }
  2926. if (e._stopped) { return; }
  2927. // Find the layer the event is propagating from and its parents.
  2928. targets = (targets || []).concat(this._findEventTargets(e, type));
  2929. if (!targets.length) { return; }
  2930. var target = targets[0];
  2931. if (type === 'contextmenu' && target.listens(type, true)) {
  2932. L.DomEvent.preventDefault(e);
  2933. }
  2934. var data = {
  2935. originalEvent: e
  2936. };
  2937. if (e.type !== 'keypress') {
  2938. var isMarker = target instanceof L.Marker;
  2939. data.containerPoint = isMarker ?
  2940. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  2941. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  2942. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  2943. }
  2944. for (var i = 0; i < targets.length; i++) {
  2945. targets[i].fire(type, data, true);
  2946. if (data.originalEvent._stopped ||
  2947. (targets[i].options.nonBubblingEvents && L.Util.indexOf(targets[i].options.nonBubblingEvents, type) !== -1)) { return; }
  2948. }
  2949. },
  2950. _draggableMoved: function (obj) {
  2951. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  2952. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  2953. },
  2954. _clearHandlers: function () {
  2955. for (var i = 0, len = this._handlers.length; i < len; i++) {
  2956. this._handlers[i].disable();
  2957. }
  2958. },
  2959. // @section Other Methods
  2960. // @method whenReady(fn: Function, context?: Object): this
  2961. // Runs the given function `fn` when the map gets initialized with
  2962. // a view (center and zoom) and at least one layer, or immediately
  2963. // if it's already initialized, optionally passing a function context.
  2964. whenReady: function (callback, context) {
  2965. if (this._loaded) {
  2966. callback.call(context || this, {target: this});
  2967. } else {
  2968. this.on('load', callback, context);
  2969. }
  2970. return this;
  2971. },
  2972. // private methods for getting map state
  2973. _getMapPanePos: function () {
  2974. return L.DomUtil.getPosition(this._mapPane) || new L.Point(0, 0);
  2975. },
  2976. _moved: function () {
  2977. var pos = this._getMapPanePos();
  2978. return pos && !pos.equals([0, 0]);
  2979. },
  2980. _getTopLeftPoint: function (center, zoom) {
  2981. var pixelOrigin = center && zoom !== undefined ?
  2982. this._getNewPixelOrigin(center, zoom) :
  2983. this.getPixelOrigin();
  2984. return pixelOrigin.subtract(this._getMapPanePos());
  2985. },
  2986. _getNewPixelOrigin: function (center, zoom) {
  2987. var viewHalf = this.getSize()._divideBy(2);
  2988. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  2989. },
  2990. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  2991. var topLeft = this._getNewPixelOrigin(center, zoom);
  2992. return this.project(latlng, zoom)._subtract(topLeft);
  2993. },
  2994. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  2995. var topLeft = this._getNewPixelOrigin(center, zoom);
  2996. return L.bounds([
  2997. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  2998. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  2999. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3000. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3001. ]);
  3002. },
  3003. // layer point of the current center
  3004. _getCenterLayerPoint: function () {
  3005. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3006. },
  3007. // offset of the specified place to the current center in pixels
  3008. _getCenterOffset: function (latlng) {
  3009. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3010. },
  3011. // adjust center for view to get inside bounds
  3012. _limitCenter: function (center, zoom, bounds) {
  3013. if (!bounds) { return center; }
  3014. var centerPoint = this.project(center, zoom),
  3015. viewHalf = this.getSize().divideBy(2),
  3016. viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3017. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3018. // If offset is less than a pixel, ignore.
  3019. // This prevents unstable projections from getting into
  3020. // an infinite loop of tiny offsets.
  3021. if (offset.round().equals([0, 0])) {
  3022. return center;
  3023. }
  3024. return this.unproject(centerPoint.add(offset), zoom);
  3025. },
  3026. // adjust offset for view to get inside bounds
  3027. _limitOffset: function (offset, bounds) {
  3028. if (!bounds) { return offset; }
  3029. var viewBounds = this.getPixelBounds(),
  3030. newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3031. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3032. },
  3033. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3034. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3035. var projectedMaxBounds = L.bounds(
  3036. this.project(maxBounds.getNorthEast(), zoom),
  3037. this.project(maxBounds.getSouthWest(), zoom)
  3038. ),
  3039. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3040. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3041. dx = this._rebound(minOffset.x, -maxOffset.x),
  3042. dy = this._rebound(minOffset.y, -maxOffset.y);
  3043. return new L.Point(dx, dy);
  3044. },
  3045. _rebound: function (left, right) {
  3046. return left + right > 0 ?
  3047. Math.round(left - right) / 2 :
  3048. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3049. },
  3050. _limitZoom: function (zoom) {
  3051. var min = this.getMinZoom(),
  3052. max = this.getMaxZoom(),
  3053. snap = L.Browser.any3d ? this.options.zoomSnap : 1;
  3054. if (snap) {
  3055. zoom = Math.round(zoom / snap) * snap;
  3056. }
  3057. return Math.max(min, Math.min(max, zoom));
  3058. },
  3059. _onPanTransitionStep: function () {
  3060. this.fire('move');
  3061. },
  3062. _onPanTransitionEnd: function () {
  3063. L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
  3064. this.fire('moveend');
  3065. },
  3066. _tryAnimatedPan: function (center, options) {
  3067. // difference between the new and current centers in pixels
  3068. var offset = this._getCenterOffset(center)._floor();
  3069. // don't animate too far unless animate: true specified in options
  3070. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3071. this.panBy(offset, options);
  3072. return true;
  3073. },
  3074. _createAnimProxy: function () {
  3075. var proxy = this._proxy = L.DomUtil.create('div', 'leaflet-proxy leaflet-zoom-animated');
  3076. this._panes.mapPane.appendChild(proxy);
  3077. this.on('zoomanim', function (e) {
  3078. var prop = L.DomUtil.TRANSFORM,
  3079. transform = proxy.style[prop];
  3080. L.DomUtil.setTransform(proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3081. // workaround for case when transform is the same and so transitionend event is not fired
  3082. if (transform === proxy.style[prop] && this._animatingZoom) {
  3083. this._onZoomTransitionEnd();
  3084. }
  3085. }, this);
  3086. this.on('load moveend', function () {
  3087. var c = this.getCenter(),
  3088. z = this.getZoom();
  3089. L.DomUtil.setTransform(proxy, this.project(c, z), this.getZoomScale(z, 1));
  3090. }, this);
  3091. },
  3092. _catchTransitionEnd: function (e) {
  3093. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3094. this._onZoomTransitionEnd();
  3095. }
  3096. },
  3097. _nothingToAnimate: function () {
  3098. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3099. },
  3100. _tryAnimatedZoom: function (center, zoom, options) {
  3101. if (this._animatingZoom) { return true; }
  3102. options = options || {};
  3103. // don't animate if disabled, not supported or zoom difference is too large
  3104. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3105. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3106. // offset is the pixel coords of the zoom origin relative to the current center
  3107. var scale = this.getZoomScale(zoom),
  3108. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3109. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3110. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3111. L.Util.requestAnimFrame(function () {
  3112. this
  3113. ._moveStart(true)
  3114. ._animateZoom(center, zoom, true);
  3115. }, this);
  3116. return true;
  3117. },
  3118. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3119. if (startAnim) {
  3120. this._animatingZoom = true;
  3121. // remember what center/zoom to set after animation
  3122. this._animateToCenter = center;
  3123. this._animateToZoom = zoom;
  3124. L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
  3125. }
  3126. // @event zoomanim: ZoomAnimEvent
  3127. // Fired on every frame of a zoom animation
  3128. this.fire('zoomanim', {
  3129. center: center,
  3130. zoom: zoom,
  3131. noUpdate: noUpdate
  3132. });
  3133. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3134. setTimeout(L.bind(this._onZoomTransitionEnd, this), 250);
  3135. },
  3136. _onZoomTransitionEnd: function () {
  3137. if (!this._animatingZoom) { return; }
  3138. L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
  3139. this._animatingZoom = false;
  3140. this._move(this._animateToCenter, this._animateToZoom);
  3141. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  3142. L.Util.requestAnimFrame(function () {
  3143. this._moveEnd(true);
  3144. }, this);
  3145. }
  3146. });
  3147. // @section
  3148. // @factory L.map(id: String, options?: Map options)
  3149. // Instantiates a map object given the DOM ID of a `<div>` element
  3150. // and optionally an object literal with `Map options`.
  3151. //
  3152. // @alternative
  3153. // @factory L.map(el: HTMLElement, options?: Map options)
  3154. // Instantiates a map object given an instance of a `<div>` HTML element
  3155. // and optionally an object literal with `Map options`.
  3156. L.map = function (id, options) {
  3157. return new L.Map(id, options);
  3158. };
  3159. /*
  3160. * @class Layer
  3161. * @inherits Evented
  3162. * @aka L.Layer
  3163. * @aka ILayer
  3164. *
  3165. * A set of methods from the Layer base class that all Leaflet layers use.
  3166. * Inherits all methods, options and events from `L.Evented`.
  3167. *
  3168. * @example
  3169. *
  3170. * ```js
  3171. * var layer = L.Marker(latlng).addTo(map);
  3172. * layer.addTo(map);
  3173. * layer.remove();
  3174. * ```
  3175. *
  3176. * @event add: Event
  3177. * Fired after the layer is added to a map
  3178. *
  3179. * @event remove: Event
  3180. * Fired after the layer is removed from a map
  3181. */
  3182. L.Layer = L.Evented.extend({
  3183. // Classes extending `L.Layer` will inherit the following options:
  3184. options: {
  3185. // @option pane: String = 'overlayPane'
  3186. // 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.
  3187. pane: 'overlayPane',
  3188. nonBubblingEvents: [], // Array of events that should not be bubbled to DOM parents (like the map),
  3189. // @option attribution: String = null
  3190. // String to be shown in the attribution control, describes the layer data, e.g. "© Mapbox".
  3191. attribution: null
  3192. },
  3193. /* @section
  3194. * Classes extending `L.Layer` will inherit the following methods:
  3195. *
  3196. * @method addTo(map: Map): this
  3197. * Adds the layer to the given map
  3198. */
  3199. addTo: function (map) {
  3200. map.addLayer(this);
  3201. return this;
  3202. },
  3203. // @method remove: this
  3204. // Removes the layer from the map it is currently active on.
  3205. remove: function () {
  3206. return this.removeFrom(this._map || this._mapToAdd);
  3207. },
  3208. // @method removeFrom(map: Map): this
  3209. // Removes the layer from the given map
  3210. removeFrom: function (obj) {
  3211. if (obj) {
  3212. obj.removeLayer(this);
  3213. }
  3214. return this;
  3215. },
  3216. // @method getPane(name? : String): HTMLElement
  3217. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  3218. getPane: function (name) {
  3219. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  3220. },
  3221. addInteractiveTarget: function (targetEl) {
  3222. this._map._targets[L.stamp(targetEl)] = this;
  3223. return this;
  3224. },
  3225. removeInteractiveTarget: function (targetEl) {
  3226. delete this._map._targets[L.stamp(targetEl)];
  3227. return this;
  3228. },
  3229. // @method getAttribution: String
  3230. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  3231. getAttribution: function () {
  3232. return this.options.attribution;
  3233. },
  3234. _layerAdd: function (e) {
  3235. var map = e.target;
  3236. // check in case layer gets added and then removed before the map is ready
  3237. if (!map.hasLayer(this)) { return; }
  3238. this._map = map;
  3239. this._zoomAnimated = map._zoomAnimated;
  3240. if (this.getEvents) {
  3241. var events = this.getEvents();
  3242. map.on(events, this);
  3243. this.once('remove', function () {
  3244. map.off(events, this);
  3245. }, this);
  3246. }
  3247. this.onAdd(map);
  3248. if (this.getAttribution && map.attributionControl) {
  3249. map.attributionControl.addAttribution(this.getAttribution());
  3250. }
  3251. this.fire('add');
  3252. map.fire('layeradd', {layer: this});
  3253. }
  3254. });
  3255. /* @section Extension methods
  3256. * @uninheritable
  3257. *
  3258. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  3259. *
  3260. * @method onAdd(map: Map): this
  3261. * 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).
  3262. *
  3263. * @method onRemove(map: Map): this
  3264. * 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).
  3265. *
  3266. * @method getEvents(): Object
  3267. * 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.
  3268. *
  3269. * @method getAttribution(): String
  3270. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  3271. *
  3272. * @method beforeAdd(map: Map): this
  3273. * 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.
  3274. */
  3275. /* @namespace Map
  3276. * @section Layer events
  3277. *
  3278. * @event layeradd: LayerEvent
  3279. * Fired when a new layer is added to the map.
  3280. *
  3281. * @event layerremove: LayerEvent
  3282. * Fired when some layer is removed from the map
  3283. *
  3284. * @section Methods for Layers and Controls
  3285. */
  3286. L.Map.include({
  3287. // @method addLayer(layer: Layer): this
  3288. // Adds the given layer to the map
  3289. addLayer: function (layer) {
  3290. var id = L.stamp(layer);
  3291. if (this._layers[id]) { return this; }
  3292. this._layers[id] = layer;
  3293. layer._mapToAdd = this;
  3294. if (layer.beforeAdd) {
  3295. layer.beforeAdd(this);
  3296. }
  3297. this.whenReady(layer._layerAdd, layer);
  3298. return this;
  3299. },
  3300. // @method removeLayer(layer: Layer): this
  3301. // Removes the given layer from the map.
  3302. removeLayer: function (layer) {
  3303. var id = L.stamp(layer);
  3304. if (!this._layers[id]) { return this; }
  3305. if (this._loaded) {
  3306. layer.onRemove(this);
  3307. }
  3308. if (layer.getAttribution && this.attributionControl) {
  3309. this.attributionControl.removeAttribution(layer.getAttribution());
  3310. }
  3311. delete this._layers[id];
  3312. if (this._loaded) {
  3313. this.fire('layerremove', {layer: layer});
  3314. layer.fire('remove');
  3315. }
  3316. layer._map = layer._mapToAdd = null;
  3317. return this;
  3318. },
  3319. // @method hasLayer(layer: Layer): Boolean
  3320. // Returns `true` if the given layer is currently added to the map
  3321. hasLayer: function (layer) {
  3322. return !!layer && (L.stamp(layer) in this._layers);
  3323. },
  3324. /* @method eachLayer(fn: Function, context?: Object): this
  3325. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  3326. * ```
  3327. * map.eachLayer(function(layer){
  3328. * layer.bindPopup('Hello');
  3329. * });
  3330. * ```
  3331. */
  3332. eachLayer: function (method, context) {
  3333. for (var i in this._layers) {
  3334. method.call(context, this._layers[i]);
  3335. }
  3336. return this;
  3337. },
  3338. _addLayers: function (layers) {
  3339. layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
  3340. for (var i = 0, len = layers.length; i < len; i++) {
  3341. this.addLayer(layers[i]);
  3342. }
  3343. },
  3344. _addZoomLimit: function (layer) {
  3345. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  3346. this._zoomBoundLayers[L.stamp(layer)] = layer;
  3347. this._updateZoomLevels();
  3348. }
  3349. },
  3350. _removeZoomLimit: function (layer) {
  3351. var id = L.stamp(layer);
  3352. if (this._zoomBoundLayers[id]) {
  3353. delete this._zoomBoundLayers[id];
  3354. this._updateZoomLevels();
  3355. }
  3356. },
  3357. _updateZoomLevels: function () {
  3358. var minZoom = Infinity,
  3359. maxZoom = -Infinity,
  3360. oldZoomSpan = this._getZoomSpan();
  3361. for (var i in this._zoomBoundLayers) {
  3362. var options = this._zoomBoundLayers[i].options;
  3363. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  3364. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  3365. }
  3366. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  3367. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  3368. // @section Map state change events
  3369. // @event zoomlevelschange: Event
  3370. // Fired when the number of zoomlevels on the map is changed due
  3371. // to adding or removing a layer.
  3372. if (oldZoomSpan !== this._getZoomSpan()) {
  3373. this.fire('zoomlevelschange');
  3374. }
  3375. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  3376. this.setZoom(this._layersMaxZoom);
  3377. }
  3378. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  3379. this.setZoom(this._layersMinZoom);
  3380. }
  3381. }
  3382. });
  3383. /*
  3384. * @namespace DomEvent
  3385. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  3386. */
  3387. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  3388. var eventsKey = '_leaflet_events';
  3389. L.DomEvent = {
  3390. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  3391. // Adds a listener function (`fn`) to a particular DOM event type of the
  3392. // element `el`. You can optionally specify the context of the listener
  3393. // (object the `this` keyword will point to). You can also pass several
  3394. // space-separated types (e.g. `'click dblclick'`).
  3395. // @alternative
  3396. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  3397. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  3398. on: function (obj, types, fn, context) {
  3399. if (typeof types === 'object') {
  3400. for (var type in types) {
  3401. this._on(obj, type, types[type], fn);
  3402. }
  3403. } else {
  3404. types = L.Util.splitWords(types);
  3405. for (var i = 0, len = types.length; i < len; i++) {
  3406. this._on(obj, types[i], fn, context);
  3407. }
  3408. }
  3409. return this;
  3410. },
  3411. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  3412. // Removes a previously added listener function. If no function is specified,
  3413. // it will remove all the listeners of that particular DOM event from the element.
  3414. // Note that if you passed a custom context to on, you must pass the same
  3415. // context to `off` in order to remove the listener.
  3416. // @alternative
  3417. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  3418. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  3419. off: function (obj, types, fn, context) {
  3420. if (typeof types === 'object') {
  3421. for (var type in types) {
  3422. this._off(obj, type, types[type], fn);
  3423. }
  3424. } else {
  3425. types = L.Util.splitWords(types);
  3426. for (var i = 0, len = types.length; i < len; i++) {
  3427. this._off(obj, types[i], fn, context);
  3428. }
  3429. }
  3430. return this;
  3431. },
  3432. _on: function (obj, type, fn, context) {
  3433. var id = type + L.stamp(fn) + (context ? '_' + L.stamp(context) : '');
  3434. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  3435. var handler = function (e) {
  3436. return fn.call(context || obj, e || window.event);
  3437. };
  3438. var originalHandler = handler;
  3439. if (L.Browser.pointer && type.indexOf('touch') === 0) {
  3440. this.addPointerListener(obj, type, handler, id);
  3441. } else if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener &&
  3442. !(L.Browser.pointer && L.Browser.chrome)) {
  3443. // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener
  3444. // See #5180
  3445. this.addDoubleTapListener(obj, handler, id);
  3446. } else if ('addEventListener' in obj) {
  3447. if (type === 'mousewheel') {
  3448. obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  3449. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  3450. handler = function (e) {
  3451. e = e || window.event;
  3452. if (L.DomEvent._isExternalTarget(obj, e)) {
  3453. originalHandler(e);
  3454. }
  3455. };
  3456. obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
  3457. } else {
  3458. if (type === 'click' && L.Browser.android) {
  3459. handler = function (e) {
  3460. return L.DomEvent._filterClick(e, originalHandler);
  3461. };
  3462. }
  3463. obj.addEventListener(type, handler, false);
  3464. }
  3465. } else if ('attachEvent' in obj) {
  3466. obj.attachEvent('on' + type, handler);
  3467. }
  3468. obj[eventsKey] = obj[eventsKey] || {};
  3469. obj[eventsKey][id] = handler;
  3470. return this;
  3471. },
  3472. _off: function (obj, type, fn, context) {
  3473. var id = type + L.stamp(fn) + (context ? '_' + L.stamp(context) : ''),
  3474. handler = obj[eventsKey] && obj[eventsKey][id];
  3475. if (!handler) { return this; }
  3476. if (L.Browser.pointer && type.indexOf('touch') === 0) {
  3477. this.removePointerListener(obj, type, id);
  3478. } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
  3479. this.removeDoubleTapListener(obj, id);
  3480. } else if ('removeEventListener' in obj) {
  3481. if (type === 'mousewheel') {
  3482. obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  3483. } else {
  3484. obj.removeEventListener(
  3485. type === 'mouseenter' ? 'mouseover' :
  3486. type === 'mouseleave' ? 'mouseout' : type, handler, false);
  3487. }
  3488. } else if ('detachEvent' in obj) {
  3489. obj.detachEvent('on' + type, handler);
  3490. }
  3491. obj[eventsKey][id] = null;
  3492. return this;
  3493. },
  3494. // @function stopPropagation(ev: DOMEvent): this
  3495. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  3496. // ```js
  3497. // L.DomEvent.on(div, 'click', function (ev) {
  3498. // L.DomEvent.stopPropagation(ev);
  3499. // });
  3500. // ```
  3501. stopPropagation: function (e) {
  3502. if (e.stopPropagation) {
  3503. e.stopPropagation();
  3504. } else if (e.originalEvent) { // In case of Leaflet event.
  3505. e.originalEvent._stopped = true;
  3506. } else {
  3507. e.cancelBubble = true;
  3508. }
  3509. L.DomEvent._skipped(e);
  3510. return this;
  3511. },
  3512. // @function disableScrollPropagation(el: HTMLElement): this
  3513. // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
  3514. disableScrollPropagation: function (el) {
  3515. return L.DomEvent.on(el, 'mousewheel', L.DomEvent.stopPropagation);
  3516. },
  3517. // @function disableClickPropagation(el: HTMLElement): this
  3518. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  3519. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  3520. disableClickPropagation: function (el) {
  3521. var stop = L.DomEvent.stopPropagation;
  3522. L.DomEvent.on(el, L.Draggable.START.join(' '), stop);
  3523. return L.DomEvent.on(el, {
  3524. click: L.DomEvent._fakeStop,
  3525. dblclick: stop
  3526. });
  3527. },
  3528. // @function preventDefault(ev: DOMEvent): this
  3529. // Prevents the default action of the DOM Event `ev` from happening (such as
  3530. // following a link in the href of the a element, or doing a POST request
  3531. // with page reload when a `<form>` is submitted).
  3532. // Use it inside listener functions.
  3533. preventDefault: function (e) {
  3534. if (e.preventDefault) {
  3535. e.preventDefault();
  3536. } else {
  3537. e.returnValue = false;
  3538. }
  3539. return this;
  3540. },
  3541. // @function stop(ev): this
  3542. // Does `stopPropagation` and `preventDefault` at the same time.
  3543. stop: function (e) {
  3544. return L.DomEvent
  3545. .preventDefault(e)
  3546. .stopPropagation(e);
  3547. },
  3548. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  3549. // Gets normalized mouse position from a DOM event relative to the
  3550. // `container` or to the whole page if not specified.
  3551. getMousePosition: function (e, container) {
  3552. if (!container) {
  3553. return new L.Point(e.clientX, e.clientY);
  3554. }
  3555. var rect = container.getBoundingClientRect();
  3556. return new L.Point(
  3557. e.clientX - rect.left - container.clientLeft,
  3558. e.clientY - rect.top - container.clientTop);
  3559. },
  3560. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  3561. // and Firefox scrolls device pixels, not CSS pixels
  3562. _wheelPxFactor: (L.Browser.win && L.Browser.chrome) ? 2 :
  3563. L.Browser.gecko ? window.devicePixelRatio :
  3564. 1,
  3565. // @function getWheelDelta(ev: DOMEvent): Number
  3566. // Gets normalized wheel delta from a mousewheel DOM event, in vertical
  3567. // pixels scrolled (negative if scrolling down).
  3568. // Events from pointing devices without precise scrolling are mapped to
  3569. // a best guess of 60 pixels.
  3570. getWheelDelta: function (e) {
  3571. return (L.Browser.edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  3572. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / L.DomEvent._wheelPxFactor : // Pixels
  3573. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  3574. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  3575. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  3576. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  3577. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  3578. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  3579. 0;
  3580. },
  3581. _skipEvents: {},
  3582. _fakeStop: function (e) {
  3583. // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e)
  3584. L.DomEvent._skipEvents[e.type] = true;
  3585. },
  3586. _skipped: function (e) {
  3587. var skipped = this._skipEvents[e.type];
  3588. // reset when checking, as it's only used in map container and propagates outside of the map
  3589. this._skipEvents[e.type] = false;
  3590. return skipped;
  3591. },
  3592. // check if element really left/entered the event target (for mouseenter/mouseleave)
  3593. _isExternalTarget: function (el, e) {
  3594. var related = e.relatedTarget;
  3595. if (!related) { return true; }
  3596. try {
  3597. while (related && (related !== el)) {
  3598. related = related.parentNode;
  3599. }
  3600. } catch (err) {
  3601. return false;
  3602. }
  3603. return (related !== el);
  3604. },
  3605. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  3606. _filterClick: function (e, handler) {
  3607. var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
  3608. elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
  3609. // are they closer together than 500ms yet more than 100ms?
  3610. // Android typically triggers them ~300ms apart while multiple listeners
  3611. // on the same event should be triggered far faster;
  3612. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  3613. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  3614. L.DomEvent.stop(e);
  3615. return;
  3616. }
  3617. L.DomEvent._lastClick = timeStamp;
  3618. handler(e);
  3619. }
  3620. };
  3621. // @function addListener(…): this
  3622. // Alias to [`L.DomEvent.on`](#domevent-on)
  3623. L.DomEvent.addListener = L.DomEvent.on;
  3624. // @function removeListener(…): this
  3625. // Alias to [`L.DomEvent.off`](#domevent-off)
  3626. L.DomEvent.removeListener = L.DomEvent.off;
  3627. /*
  3628. * @class PosAnimation
  3629. * @aka L.PosAnimation
  3630. * @inherits Evented
  3631. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  3632. *
  3633. * @example
  3634. * ```js
  3635. * var fx = new L.PosAnimation();
  3636. * fx.run(el, [300, 500], 0.5);
  3637. * ```
  3638. *
  3639. * @constructor L.PosAnimation()
  3640. * Creates a `PosAnimation` object.
  3641. *
  3642. */
  3643. L.PosAnimation = L.Evented.extend({
  3644. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  3645. // Run an animation of a given element to a new position, optionally setting
  3646. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  3647. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  3648. // `0.5` by default).
  3649. run: function (el, newPos, duration, easeLinearity) {
  3650. this.stop();
  3651. this._el = el;
  3652. this._inProgress = true;
  3653. this._duration = duration || 0.25;
  3654. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  3655. this._startPos = L.DomUtil.getPosition(el);
  3656. this._offset = newPos.subtract(this._startPos);
  3657. this._startTime = +new Date();
  3658. // @event start: Event
  3659. // Fired when the animation starts
  3660. this.fire('start');
  3661. this._animate();
  3662. },
  3663. // @method stop()
  3664. // Stops the animation (if currently running).
  3665. stop: function () {
  3666. if (!this._inProgress) { return; }
  3667. this._step(true);
  3668. this._complete();
  3669. },
  3670. _animate: function () {
  3671. // animation loop
  3672. this._animId = L.Util.requestAnimFrame(this._animate, this);
  3673. this._step();
  3674. },
  3675. _step: function (round) {
  3676. var elapsed = (+new Date()) - this._startTime,
  3677. duration = this._duration * 1000;
  3678. if (elapsed < duration) {
  3679. this._runFrame(this._easeOut(elapsed / duration), round);
  3680. } else {
  3681. this._runFrame(1);
  3682. this._complete();
  3683. }
  3684. },
  3685. _runFrame: function (progress, round) {
  3686. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  3687. if (round) {
  3688. pos._round();
  3689. }
  3690. L.DomUtil.setPosition(this._el, pos);
  3691. // @event step: Event
  3692. // Fired continuously during the animation.
  3693. this.fire('step');
  3694. },
  3695. _complete: function () {
  3696. L.Util.cancelAnimFrame(this._animId);
  3697. this._inProgress = false;
  3698. // @event end: Event
  3699. // Fired when the animation ends.
  3700. this.fire('end');
  3701. },
  3702. _easeOut: function (t) {
  3703. return 1 - Math.pow(1 - t, this._easeOutPower);
  3704. }
  3705. });
  3706. /*
  3707. * @namespace Projection
  3708. * @projection L.Projection.Mercator
  3709. *
  3710. * Elliptical Mercator projection — more complex than Spherical Mercator. Takes into account that Earth is a geoid, not a perfect sphere. Used by the EPSG:3395 CRS.
  3711. */
  3712. L.Projection.Mercator = {
  3713. R: 6378137,
  3714. R_MINOR: 6356752.314245179,
  3715. bounds: L.bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  3716. project: function (latlng) {
  3717. var d = Math.PI / 180,
  3718. r = this.R,
  3719. y = latlng.lat * d,
  3720. tmp = this.R_MINOR / r,
  3721. e = Math.sqrt(1 - tmp * tmp),
  3722. con = e * Math.sin(y);
  3723. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  3724. y = -r * Math.log(Math.max(ts, 1E-10));
  3725. return new L.Point(latlng.lng * d * r, y);
  3726. },
  3727. unproject: function (point) {
  3728. var d = 180 / Math.PI,
  3729. r = this.R,
  3730. tmp = this.R_MINOR / r,
  3731. e = Math.sqrt(1 - tmp * tmp),
  3732. ts = Math.exp(-point.y / r),
  3733. phi = Math.PI / 2 - 2 * Math.atan(ts);
  3734. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  3735. con = e * Math.sin(phi);
  3736. con = Math.pow((1 - con) / (1 + con), e / 2);
  3737. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  3738. phi += dphi;
  3739. }
  3740. return new L.LatLng(phi * d, point.x * d / r);
  3741. }
  3742. };
  3743. /*
  3744. * @namespace CRS
  3745. * @crs L.CRS.EPSG3395
  3746. *
  3747. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  3748. */
  3749. L.CRS.EPSG3395 = L.extend({}, L.CRS.Earth, {
  3750. code: 'EPSG:3395',
  3751. projection: L.Projection.Mercator,
  3752. transformation: (function () {
  3753. var scale = 0.5 / (Math.PI * L.Projection.Mercator.R);
  3754. return new L.Transformation(scale, 0.5, -scale, 0.5);
  3755. }())
  3756. });
  3757. /*
  3758. * @class GridLayer
  3759. * @inherits Layer
  3760. * @aka L.GridLayer
  3761. *
  3762. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  3763. * 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.
  3764. *
  3765. *
  3766. * @section Synchronous usage
  3767. * @example
  3768. *
  3769. * 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.
  3770. *
  3771. * ```js
  3772. * var CanvasLayer = L.GridLayer.extend({
  3773. * createTile: function(coords){
  3774. * // create a <canvas> element for drawing
  3775. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  3776. *
  3777. * // setup tile width and height according to the options
  3778. * var size = this.getTileSize();
  3779. * tile.width = size.x;
  3780. * tile.height = size.y;
  3781. *
  3782. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  3783. * var ctx = tile.getContext('2d');
  3784. *
  3785. * // return the tile so it can be rendered on screen
  3786. * return tile;
  3787. * }
  3788. * });
  3789. * ```
  3790. *
  3791. * @section Asynchronous usage
  3792. * @example
  3793. *
  3794. * 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.
  3795. *
  3796. * ```js
  3797. * var CanvasLayer = L.GridLayer.extend({
  3798. * createTile: function(coords, done){
  3799. * var error;
  3800. *
  3801. * // create a <canvas> element for drawing
  3802. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  3803. *
  3804. * // setup tile width and height according to the options
  3805. * var size = this.getTileSize();
  3806. * tile.width = size.x;
  3807. * tile.height = size.y;
  3808. *
  3809. * // draw something asynchronously and pass the tile to the done() callback
  3810. * setTimeout(function() {
  3811. * done(error, tile);
  3812. * }, 1000);
  3813. *
  3814. * return tile;
  3815. * }
  3816. * });
  3817. * ```
  3818. *
  3819. * @section
  3820. */
  3821. L.GridLayer = L.Layer.extend({
  3822. // @section
  3823. // @aka GridLayer options
  3824. options: {
  3825. // @option tileSize: Number|Point = 256
  3826. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  3827. tileSize: 256,
  3828. // @option opacity: Number = 1.0
  3829. // Opacity of the tiles. Can be used in the `createTile()` function.
  3830. opacity: 1,
  3831. // @option updateWhenIdle: Boolean = depends
  3832. // If `false`, new tiles are loaded during panning, otherwise only after it (for better performance). `true` by default on mobile browsers, otherwise `false`.
  3833. updateWhenIdle: L.Browser.mobile,
  3834. // @option updateWhenZooming: Boolean = true
  3835. // 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.
  3836. updateWhenZooming: true,
  3837. // @option updateInterval: Number = 200
  3838. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  3839. updateInterval: 200,
  3840. // @option zIndex: Number = 1
  3841. // The explicit zIndex of the tile layer.
  3842. zIndex: 1,
  3843. // @option bounds: LatLngBounds = undefined
  3844. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  3845. bounds: null,
  3846. // @option minZoom: Number = 0
  3847. // The minimum zoom level that tiles will be loaded at. By default the entire map.
  3848. minZoom: 0,
  3849. // @option maxZoom: Number = undefined
  3850. // The maximum zoom level that tiles will be loaded at.
  3851. maxZoom: undefined,
  3852. // @option noWrap: Boolean = false
  3853. // Whether the layer is wrapped around the antimeridian. If `true`, the
  3854. // GridLayer will only be displayed once at low zoom levels. Has no
  3855. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  3856. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  3857. // tiles outside the CRS limits.
  3858. noWrap: false,
  3859. // @option pane: String = 'tilePane'
  3860. // `Map pane` where the grid layer will be added.
  3861. pane: 'tilePane',
  3862. // @option className: String = ''
  3863. // A custom class name to assign to the tile layer. Empty by default.
  3864. className: '',
  3865. // @option keepBuffer: Number = 2
  3866. // When panning the map, keep this many rows and columns of tiles before unloading them.
  3867. keepBuffer: 2
  3868. },
  3869. initialize: function (options) {
  3870. L.setOptions(this, options);
  3871. },
  3872. onAdd: function () {
  3873. this._initContainer();
  3874. this._levels = {};
  3875. this._tiles = {};
  3876. this._resetView();
  3877. this._update();
  3878. },
  3879. beforeAdd: function (map) {
  3880. map._addZoomLimit(this);
  3881. },
  3882. onRemove: function (map) {
  3883. this._removeAllTiles();
  3884. L.DomUtil.remove(this._container);
  3885. map._removeZoomLimit(this);
  3886. this._container = null;
  3887. this._tileZoom = null;
  3888. },
  3889. // @method bringToFront: this
  3890. // Brings the tile layer to the top of all tile layers.
  3891. bringToFront: function () {
  3892. if (this._map) {
  3893. L.DomUtil.toFront(this._container);
  3894. this._setAutoZIndex(Math.max);
  3895. }
  3896. return this;
  3897. },
  3898. // @method bringToBack: this
  3899. // Brings the tile layer to the bottom of all tile layers.
  3900. bringToBack: function () {
  3901. if (this._map) {
  3902. L.DomUtil.toBack(this._container);
  3903. this._setAutoZIndex(Math.min);
  3904. }
  3905. return this;
  3906. },
  3907. // @method getContainer: HTMLElement
  3908. // Returns the HTML element that contains the tiles for this layer.
  3909. getContainer: function () {
  3910. return this._container;
  3911. },
  3912. // @method setOpacity(opacity: Number): this
  3913. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  3914. setOpacity: function (opacity) {
  3915. this.options.opacity = opacity;
  3916. this._updateOpacity();
  3917. return this;
  3918. },
  3919. // @method setZIndex(zIndex: Number): this
  3920. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  3921. setZIndex: function (zIndex) {
  3922. this.options.zIndex = zIndex;
  3923. this._updateZIndex();
  3924. return this;
  3925. },
  3926. // @method isLoading: Boolean
  3927. // Returns `true` if any tile in the grid layer has not finished loading.
  3928. isLoading: function () {
  3929. return this._loading;
  3930. },
  3931. // @method redraw: this
  3932. // Causes the layer to clear all the tiles and request them again.
  3933. redraw: function () {
  3934. if (this._map) {
  3935. this._removeAllTiles();
  3936. this._update();
  3937. }
  3938. return this;
  3939. },
  3940. getEvents: function () {
  3941. var events = {
  3942. viewprereset: this._invalidateAll,
  3943. viewreset: this._resetView,
  3944. zoom: this._resetView,
  3945. moveend: this._onMoveEnd
  3946. };
  3947. if (!this.options.updateWhenIdle) {
  3948. // update tiles on move, but not more often than once per given interval
  3949. if (!this._onMove) {
  3950. this._onMove = L.Util.throttle(this._onMoveEnd, this.options.updateInterval, this);
  3951. }
  3952. events.move = this._onMove;
  3953. }
  3954. if (this._zoomAnimated) {
  3955. events.zoomanim = this._animateZoom;
  3956. }
  3957. return events;
  3958. },
  3959. // @section Extension methods
  3960. // Layers extending `GridLayer` shall reimplement the following method.
  3961. // @method createTile(coords: Object, done?: Function): HTMLElement
  3962. // Called only internally, must be overriden by classes extending `GridLayer`.
  3963. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  3964. // is specified, it must be called when the tile has finished loading and drawing.
  3965. createTile: function () {
  3966. return document.createElement('div');
  3967. },
  3968. // @section
  3969. // @method getTileSize: Point
  3970. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  3971. getTileSize: function () {
  3972. var s = this.options.tileSize;
  3973. return s instanceof L.Point ? s : new L.Point(s, s);
  3974. },
  3975. _updateZIndex: function () {
  3976. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  3977. this._container.style.zIndex = this.options.zIndex;
  3978. }
  3979. },
  3980. _setAutoZIndex: function (compare) {
  3981. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  3982. var layers = this.getPane().children,
  3983. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  3984. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  3985. zIndex = layers[i].style.zIndex;
  3986. if (layers[i] !== this._container && zIndex) {
  3987. edgeZIndex = compare(edgeZIndex, +zIndex);
  3988. }
  3989. }
  3990. if (isFinite(edgeZIndex)) {
  3991. this.options.zIndex = edgeZIndex + compare(-1, 1);
  3992. this._updateZIndex();
  3993. }
  3994. },
  3995. _updateOpacity: function () {
  3996. if (!this._map) { return; }
  3997. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  3998. if (L.Browser.ielt9) { return; }
  3999. L.DomUtil.setOpacity(this._container, this.options.opacity);
  4000. var now = +new Date(),
  4001. nextFrame = false,
  4002. willPrune = false;
  4003. for (var key in this._tiles) {
  4004. var tile = this._tiles[key];
  4005. if (!tile.current || !tile.loaded) { continue; }
  4006. var fade = Math.min(1, (now - tile.loaded) / 200);
  4007. L.DomUtil.setOpacity(tile.el, fade);
  4008. if (fade < 1) {
  4009. nextFrame = true;
  4010. } else {
  4011. if (tile.active) { willPrune = true; }
  4012. tile.active = true;
  4013. }
  4014. }
  4015. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  4016. if (nextFrame) {
  4017. L.Util.cancelAnimFrame(this._fadeFrame);
  4018. this._fadeFrame = L.Util.requestAnimFrame(this._updateOpacity, this);
  4019. }
  4020. },
  4021. _initContainer: function () {
  4022. if (this._container) { return; }
  4023. this._container = L.DomUtil.create('div', 'leaflet-layer ' + (this.options.className || ''));
  4024. this._updateZIndex();
  4025. if (this.options.opacity < 1) {
  4026. this._updateOpacity();
  4027. }
  4028. this.getPane().appendChild(this._container);
  4029. },
  4030. _updateLevels: function () {
  4031. var zoom = this._tileZoom,
  4032. maxZoom = this.options.maxZoom;
  4033. if (zoom === undefined) { return undefined; }
  4034. for (var z in this._levels) {
  4035. if (this._levels[z].el.children.length || z === zoom) {
  4036. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  4037. } else {
  4038. L.DomUtil.remove(this._levels[z].el);
  4039. this._removeTilesAtZoom(z);
  4040. delete this._levels[z];
  4041. }
  4042. }
  4043. var level = this._levels[zoom],
  4044. map = this._map;
  4045. if (!level) {
  4046. level = this._levels[zoom] = {};
  4047. level.el = L.DomUtil.create('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  4048. level.el.style.zIndex = maxZoom;
  4049. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  4050. level.zoom = zoom;
  4051. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  4052. // force the browser to consider the newly added element for transition
  4053. L.Util.falseFn(level.el.offsetWidth);
  4054. }
  4055. this._level = level;
  4056. return level;
  4057. },
  4058. _pruneTiles: function () {
  4059. if (!this._map) {
  4060. return;
  4061. }
  4062. var key, tile;
  4063. var zoom = this._map.getZoom();
  4064. if (zoom > this.options.maxZoom ||
  4065. zoom < this.options.minZoom) {
  4066. this._removeAllTiles();
  4067. return;
  4068. }
  4069. for (key in this._tiles) {
  4070. tile = this._tiles[key];
  4071. tile.retain = tile.current;
  4072. }
  4073. for (key in this._tiles) {
  4074. tile = this._tiles[key];
  4075. if (tile.current && !tile.active) {
  4076. var coords = tile.coords;
  4077. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  4078. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  4079. }
  4080. }
  4081. }
  4082. for (key in this._tiles) {
  4083. if (!this._tiles[key].retain) {
  4084. this._removeTile(key);
  4085. }
  4086. }
  4087. },
  4088. _removeTilesAtZoom: function (zoom) {
  4089. for (var key in this._tiles) {
  4090. if (this._tiles[key].coords.z !== zoom) {
  4091. continue;
  4092. }
  4093. this._removeTile(key);
  4094. }
  4095. },
  4096. _removeAllTiles: function () {
  4097. for (var key in this._tiles) {
  4098. this._removeTile(key);
  4099. }
  4100. },
  4101. _invalidateAll: function () {
  4102. for (var z in this._levels) {
  4103. L.DomUtil.remove(this._levels[z].el);
  4104. delete this._levels[z];
  4105. }
  4106. this._removeAllTiles();
  4107. this._tileZoom = null;
  4108. },
  4109. _retainParent: function (x, y, z, minZoom) {
  4110. var x2 = Math.floor(x / 2),
  4111. y2 = Math.floor(y / 2),
  4112. z2 = z - 1,
  4113. coords2 = new L.Point(+x2, +y2);
  4114. coords2.z = +z2;
  4115. var key = this._tileCoordsToKey(coords2),
  4116. tile = this._tiles[key];
  4117. if (tile && tile.active) {
  4118. tile.retain = true;
  4119. return true;
  4120. } else if (tile && tile.loaded) {
  4121. tile.retain = true;
  4122. }
  4123. if (z2 > minZoom) {
  4124. return this._retainParent(x2, y2, z2, minZoom);
  4125. }
  4126. return false;
  4127. },
  4128. _retainChildren: function (x, y, z, maxZoom) {
  4129. for (var i = 2 * x; i < 2 * x + 2; i++) {
  4130. for (var j = 2 * y; j < 2 * y + 2; j++) {
  4131. var coords = new L.Point(i, j);
  4132. coords.z = z + 1;
  4133. var key = this._tileCoordsToKey(coords),
  4134. tile = this._tiles[key];
  4135. if (tile && tile.active) {
  4136. tile.retain = true;
  4137. continue;
  4138. } else if (tile && tile.loaded) {
  4139. tile.retain = true;
  4140. }
  4141. if (z + 1 < maxZoom) {
  4142. this._retainChildren(i, j, z + 1, maxZoom);
  4143. }
  4144. }
  4145. }
  4146. },
  4147. _resetView: function (e) {
  4148. var animating = e && (e.pinch || e.flyTo);
  4149. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  4150. },
  4151. _animateZoom: function (e) {
  4152. this._setView(e.center, e.zoom, true, e.noUpdate);
  4153. },
  4154. _setView: function (center, zoom, noPrune, noUpdate) {
  4155. var tileZoom = Math.round(zoom);
  4156. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  4157. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  4158. tileZoom = undefined;
  4159. }
  4160. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  4161. if (!noUpdate || tileZoomChanged) {
  4162. this._tileZoom = tileZoom;
  4163. if (this._abortLoading) {
  4164. this._abortLoading();
  4165. }
  4166. this._updateLevels();
  4167. this._resetGrid();
  4168. if (tileZoom !== undefined) {
  4169. this._update(center);
  4170. }
  4171. if (!noPrune) {
  4172. this._pruneTiles();
  4173. }
  4174. // Flag to prevent _updateOpacity from pruning tiles during
  4175. // a zoom anim or a pinch gesture
  4176. this._noPrune = !!noPrune;
  4177. }
  4178. this._setZoomTransforms(center, zoom);
  4179. },
  4180. _setZoomTransforms: function (center, zoom) {
  4181. for (var i in this._levels) {
  4182. this._setZoomTransform(this._levels[i], center, zoom);
  4183. }
  4184. },
  4185. _setZoomTransform: function (level, center, zoom) {
  4186. var scale = this._map.getZoomScale(zoom, level.zoom),
  4187. translate = level.origin.multiplyBy(scale)
  4188. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  4189. if (L.Browser.any3d) {
  4190. L.DomUtil.setTransform(level.el, translate, scale);
  4191. } else {
  4192. L.DomUtil.setPosition(level.el, translate);
  4193. }
  4194. },
  4195. _resetGrid: function () {
  4196. var map = this._map,
  4197. crs = map.options.crs,
  4198. tileSize = this._tileSize = this.getTileSize(),
  4199. tileZoom = this._tileZoom;
  4200. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  4201. if (bounds) {
  4202. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  4203. }
  4204. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  4205. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  4206. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  4207. ];
  4208. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  4209. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  4210. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  4211. ];
  4212. },
  4213. _onMoveEnd: function () {
  4214. if (!this._map || this._map._animatingZoom) { return; }
  4215. this._update();
  4216. },
  4217. _getTiledPixelBounds: function (center) {
  4218. var map = this._map,
  4219. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  4220. scale = map.getZoomScale(mapZoom, this._tileZoom),
  4221. pixelCenter = map.project(center, this._tileZoom).floor(),
  4222. halfSize = map.getSize().divideBy(scale * 2);
  4223. return new L.Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  4224. },
  4225. // Private method to load tiles in the grid's active zoom level according to map bounds
  4226. _update: function (center) {
  4227. var map = this._map;
  4228. if (!map) { return; }
  4229. var zoom = map.getZoom();
  4230. if (center === undefined) { center = map.getCenter(); }
  4231. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  4232. var pixelBounds = this._getTiledPixelBounds(center),
  4233. tileRange = this._pxBoundsToTileRange(pixelBounds),
  4234. tileCenter = tileRange.getCenter(),
  4235. queue = [],
  4236. margin = this.options.keepBuffer,
  4237. noPruneRange = new L.Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  4238. tileRange.getTopRight().add([margin, -margin]));
  4239. for (var key in this._tiles) {
  4240. var c = this._tiles[key].coords;
  4241. if (c.z !== this._tileZoom || !noPruneRange.contains(L.point(c.x, c.y))) {
  4242. this._tiles[key].current = false;
  4243. }
  4244. }
  4245. // _update just loads more tiles. If the tile zoom level differs too much
  4246. // from the map's, let _setView reset levels and prune old tiles.
  4247. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  4248. // create a queue of coordinates to load tiles from
  4249. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  4250. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  4251. var coords = new L.Point(i, j);
  4252. coords.z = this._tileZoom;
  4253. if (!this._isValidTile(coords)) { continue; }
  4254. var tile = this._tiles[this._tileCoordsToKey(coords)];
  4255. if (tile) {
  4256. tile.current = true;
  4257. } else {
  4258. queue.push(coords);
  4259. }
  4260. }
  4261. }
  4262. // sort tile queue to load tiles in order of their distance to center
  4263. queue.sort(function (a, b) {
  4264. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  4265. });
  4266. if (queue.length !== 0) {
  4267. // if it's the first batch of tiles to load
  4268. if (!this._loading) {
  4269. this._loading = true;
  4270. // @event loading: Event
  4271. // Fired when the grid layer starts loading tiles.
  4272. this.fire('loading');
  4273. }
  4274. // create DOM fragment to append tiles in one batch
  4275. var fragment = document.createDocumentFragment();
  4276. for (i = 0; i < queue.length; i++) {
  4277. this._addTile(queue[i], fragment);
  4278. }
  4279. this._level.el.appendChild(fragment);
  4280. }
  4281. },
  4282. _isValidTile: function (coords) {
  4283. var crs = this._map.options.crs;
  4284. if (!crs.infinite) {
  4285. // don't load tile if it's out of bounds and not wrapped
  4286. var bounds = this._globalTileRange;
  4287. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  4288. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  4289. }
  4290. if (!this.options.bounds) { return true; }
  4291. // don't load tile if it doesn't intersect the bounds in options
  4292. var tileBounds = this._tileCoordsToBounds(coords);
  4293. return L.latLngBounds(this.options.bounds).overlaps(tileBounds);
  4294. },
  4295. _keyToBounds: function (key) {
  4296. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  4297. },
  4298. // converts tile coordinates to its geographical bounds
  4299. _tileCoordsToBounds: function (coords) {
  4300. var map = this._map,
  4301. tileSize = this.getTileSize(),
  4302. nwPoint = coords.scaleBy(tileSize),
  4303. sePoint = nwPoint.add(tileSize),
  4304. nw = map.unproject(nwPoint, coords.z),
  4305. se = map.unproject(sePoint, coords.z),
  4306. bounds = new L.LatLngBounds(nw, se);
  4307. if (!this.options.noWrap) {
  4308. map.wrapLatLngBounds(bounds);
  4309. }
  4310. return bounds;
  4311. },
  4312. // converts tile coordinates to key for the tile cache
  4313. _tileCoordsToKey: function (coords) {
  4314. return coords.x + ':' + coords.y + ':' + coords.z;
  4315. },
  4316. // converts tile cache key to coordinates
  4317. _keyToTileCoords: function (key) {
  4318. var k = key.split(':'),
  4319. coords = new L.Point(+k[0], +k[1]);
  4320. coords.z = +k[2];
  4321. return coords;
  4322. },
  4323. _removeTile: function (key) {
  4324. var tile = this._tiles[key];
  4325. if (!tile) { return; }
  4326. L.DomUtil.remove(tile.el);
  4327. delete this._tiles[key];
  4328. // @event tileunload: TileEvent
  4329. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  4330. this.fire('tileunload', {
  4331. tile: tile.el,
  4332. coords: this._keyToTileCoords(key)
  4333. });
  4334. },
  4335. _initTile: function (tile) {
  4336. L.DomUtil.addClass(tile, 'leaflet-tile');
  4337. var tileSize = this.getTileSize();
  4338. tile.style.width = tileSize.x + 'px';
  4339. tile.style.height = tileSize.y + 'px';
  4340. tile.onselectstart = L.Util.falseFn;
  4341. tile.onmousemove = L.Util.falseFn;
  4342. // update opacity on tiles in IE7-8 because of filter inheritance problems
  4343. if (L.Browser.ielt9 && this.options.opacity < 1) {
  4344. L.DomUtil.setOpacity(tile, this.options.opacity);
  4345. }
  4346. // without this hack, tiles disappear after zoom on Chrome for Android
  4347. // https://github.com/Leaflet/Leaflet/issues/2078
  4348. if (L.Browser.android && !L.Browser.android23) {
  4349. tile.style.WebkitBackfaceVisibility = 'hidden';
  4350. }
  4351. },
  4352. _addTile: function (coords, container) {
  4353. var tilePos = this._getTilePos(coords),
  4354. key = this._tileCoordsToKey(coords);
  4355. var tile = this.createTile(this._wrapCoords(coords), L.bind(this._tileReady, this, coords));
  4356. this._initTile(tile);
  4357. // if createTile is defined with a second argument ("done" callback),
  4358. // we know that tile is async and will be ready later; otherwise
  4359. if (this.createTile.length < 2) {
  4360. // mark tile as ready, but delay one frame for opacity animation to happen
  4361. L.Util.requestAnimFrame(L.bind(this._tileReady, this, coords, null, tile));
  4362. }
  4363. L.DomUtil.setPosition(tile, tilePos);
  4364. // save tile in cache
  4365. this._tiles[key] = {
  4366. el: tile,
  4367. coords: coords,
  4368. current: true
  4369. };
  4370. container.appendChild(tile);
  4371. // @event tileloadstart: TileEvent
  4372. // Fired when a tile is requested and starts loading.
  4373. this.fire('tileloadstart', {
  4374. tile: tile,
  4375. coords: coords
  4376. });
  4377. },
  4378. _tileReady: function (coords, err, tile) {
  4379. if (!this._map) { return; }
  4380. if (err) {
  4381. // @event tileerror: TileErrorEvent
  4382. // Fired when there is an error loading a tile.
  4383. this.fire('tileerror', {
  4384. error: err,
  4385. tile: tile,
  4386. coords: coords
  4387. });
  4388. }
  4389. var key = this._tileCoordsToKey(coords);
  4390. tile = this._tiles[key];
  4391. if (!tile) { return; }
  4392. tile.loaded = +new Date();
  4393. if (this._map._fadeAnimated) {
  4394. L.DomUtil.setOpacity(tile.el, 0);
  4395. L.Util.cancelAnimFrame(this._fadeFrame);
  4396. this._fadeFrame = L.Util.requestAnimFrame(this._updateOpacity, this);
  4397. } else {
  4398. tile.active = true;
  4399. this._pruneTiles();
  4400. }
  4401. if (!err) {
  4402. L.DomUtil.addClass(tile.el, 'leaflet-tile-loaded');
  4403. // @event tileload: TileEvent
  4404. // Fired when a tile loads.
  4405. this.fire('tileload', {
  4406. tile: tile.el,
  4407. coords: coords
  4408. });
  4409. }
  4410. if (this._noTilesToLoad()) {
  4411. this._loading = false;
  4412. // @event load: Event
  4413. // Fired when the grid layer loaded all visible tiles.
  4414. this.fire('load');
  4415. if (L.Browser.ielt9 || !this._map._fadeAnimated) {
  4416. L.Util.requestAnimFrame(this._pruneTiles, this);
  4417. } else {
  4418. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  4419. // to trigger a pruning.
  4420. setTimeout(L.bind(this._pruneTiles, this), 250);
  4421. }
  4422. }
  4423. },
  4424. _getTilePos: function (coords) {
  4425. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  4426. },
  4427. _wrapCoords: function (coords) {
  4428. var newCoords = new L.Point(
  4429. this._wrapX ? L.Util.wrapNum(coords.x, this._wrapX) : coords.x,
  4430. this._wrapY ? L.Util.wrapNum(coords.y, this._wrapY) : coords.y);
  4431. newCoords.z = coords.z;
  4432. return newCoords;
  4433. },
  4434. _pxBoundsToTileRange: function (bounds) {
  4435. var tileSize = this.getTileSize();
  4436. return new L.Bounds(
  4437. bounds.min.unscaleBy(tileSize).floor(),
  4438. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  4439. },
  4440. _noTilesToLoad: function () {
  4441. for (var key in this._tiles) {
  4442. if (!this._tiles[key].loaded) { return false; }
  4443. }
  4444. return true;
  4445. }
  4446. });
  4447. // @factory L.gridLayer(options?: GridLayer options)
  4448. // Creates a new instance of GridLayer with the supplied options.
  4449. L.gridLayer = function (options) {
  4450. return new L.GridLayer(options);
  4451. };
  4452. /*
  4453. * @class TileLayer
  4454. * @inherits GridLayer
  4455. * @aka L.TileLayer
  4456. * Used to load and display tile layers on the map. Extends `GridLayer`.
  4457. *
  4458. * @example
  4459. *
  4460. * ```js
  4461. * L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map);
  4462. * ```
  4463. *
  4464. * @section URL template
  4465. * @example
  4466. *
  4467. * A string of the following form:
  4468. *
  4469. * ```
  4470. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  4471. * ```
  4472. *
  4473. * `{s}` means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; `a`, `b` or `c` by default, can be omitted), `{z}` — zoom level, `{x}` and `{y}` — tile coordinates. `{r}` can be used to add @2x to the URL to load retina tiles.
  4474. *
  4475. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  4476. *
  4477. * ```
  4478. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  4479. * ```
  4480. */
  4481. L.TileLayer = L.GridLayer.extend({
  4482. // @section
  4483. // @aka TileLayer options
  4484. options: {
  4485. // @option minZoom: Number = 0
  4486. // Minimum zoom number.
  4487. minZoom: 0,
  4488. // @option maxZoom: Number = 18
  4489. // Maximum zoom number.
  4490. maxZoom: 18,
  4491. // @option maxNativeZoom: Number = null
  4492. // Maximum zoom number the tile source has available. If it is specified,
  4493. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  4494. // from `maxNativeZoom` level and auto-scaled.
  4495. maxNativeZoom: null,
  4496. // @option minNativeZoom: Number = null
  4497. // Minimum zoom number the tile source has available. If it is specified,
  4498. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  4499. // from `minNativeZoom` level and auto-scaled.
  4500. minNativeZoom: null,
  4501. // @option subdomains: String|String[] = 'abc'
  4502. // 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.
  4503. subdomains: 'abc',
  4504. // @option errorTileUrl: String = ''
  4505. // URL to the tile image to show in place of the tile that failed to load.
  4506. errorTileUrl: '',
  4507. // @option zoomOffset: Number = 0
  4508. // The zoom number used in tile URLs will be offset with this value.
  4509. zoomOffset: 0,
  4510. // @option tms: Boolean = false
  4511. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  4512. tms: false,
  4513. // @option zoomReverse: Boolean = false
  4514. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  4515. zoomReverse: false,
  4516. // @option detectRetina: Boolean = false
  4517. // 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.
  4518. detectRetina: false,
  4519. // @option crossOrigin: Boolean = false
  4520. // If true, all tiles will have their crossOrigin attribute set to ''. This is needed if you want to access tile pixel data.
  4521. crossOrigin: false
  4522. },
  4523. initialize: function (url, options) {
  4524. this._url = url;
  4525. options = L.setOptions(this, options);
  4526. // detecting retina displays, adjusting tileSize and zoom levels
  4527. if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
  4528. options.tileSize = Math.floor(options.tileSize / 2);
  4529. if (!options.zoomReverse) {
  4530. options.zoomOffset++;
  4531. options.maxZoom--;
  4532. } else {
  4533. options.zoomOffset--;
  4534. options.minZoom++;
  4535. }
  4536. options.minZoom = Math.max(0, options.minZoom);
  4537. }
  4538. if (typeof options.subdomains === 'string') {
  4539. options.subdomains = options.subdomains.split('');
  4540. }
  4541. // for https://github.com/Leaflet/Leaflet/issues/137
  4542. if (!L.Browser.android) {
  4543. this.on('tileunload', this._onTileRemove);
  4544. }
  4545. },
  4546. // @method setUrl(url: String, noRedraw?: Boolean): this
  4547. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  4548. setUrl: function (url, noRedraw) {
  4549. this._url = url;
  4550. if (!noRedraw) {
  4551. this.redraw();
  4552. }
  4553. return this;
  4554. },
  4555. // @method createTile(coords: Object, done?: Function): HTMLElement
  4556. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  4557. // to return an `<img>` HTML element with the appropiate image URL given `coords`. The `done`
  4558. // callback is called when the tile has been loaded.
  4559. createTile: function (coords, done) {
  4560. var tile = document.createElement('img');
  4561. L.DomEvent.on(tile, 'load', L.bind(this._tileOnLoad, this, done, tile));
  4562. L.DomEvent.on(tile, 'error', L.bind(this._tileOnError, this, done, tile));
  4563. if (this.options.crossOrigin) {
  4564. tile.crossOrigin = '';
  4565. }
  4566. /*
  4567. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  4568. http://www.w3.org/TR/WCAG20-TECHS/H67
  4569. */
  4570. tile.alt = '';
  4571. /*
  4572. Set role="presentation" to force screen readers to ignore this
  4573. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  4574. */
  4575. tile.setAttribute('role', 'presentation');
  4576. tile.src = this.getTileUrl(coords);
  4577. return tile;
  4578. },
  4579. // @section Extension methods
  4580. // @uninheritable
  4581. // Layers extending `TileLayer` might reimplement the following method.
  4582. // @method getTileUrl(coords: Object): String
  4583. // Called only internally, returns the URL for a tile given its coordinates.
  4584. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  4585. getTileUrl: function (coords) {
  4586. var data = {
  4587. r: L.Browser.retina ? '@2x' : '',
  4588. s: this._getSubdomain(coords),
  4589. x: coords.x,
  4590. y: coords.y,
  4591. z: this._getZoomForUrl()
  4592. };
  4593. if (this._map && !this._map.options.crs.infinite) {
  4594. var invertedY = this._globalTileRange.max.y - coords.y;
  4595. if (this.options.tms) {
  4596. data['y'] = invertedY;
  4597. }
  4598. data['-y'] = invertedY;
  4599. }
  4600. return L.Util.template(this._url, L.extend(data, this.options));
  4601. },
  4602. _tileOnLoad: function (done, tile) {
  4603. // For https://github.com/Leaflet/Leaflet/issues/3332
  4604. if (L.Browser.ielt9) {
  4605. setTimeout(L.bind(done, this, null, tile), 0);
  4606. } else {
  4607. done(null, tile);
  4608. }
  4609. },
  4610. _tileOnError: function (done, tile, e) {
  4611. var errorUrl = this.options.errorTileUrl;
  4612. if (errorUrl && tile.src !== errorUrl) {
  4613. tile.src = errorUrl;
  4614. }
  4615. done(e, tile);
  4616. },
  4617. getTileSize: function () {
  4618. var map = this._map,
  4619. tileSize = L.GridLayer.prototype.getTileSize.call(this),
  4620. zoom = this._tileZoom + this.options.zoomOffset,
  4621. minNativeZoom = this.options.minNativeZoom,
  4622. maxNativeZoom = this.options.maxNativeZoom;
  4623. // decrease tile size when scaling below minNativeZoom
  4624. if (minNativeZoom !== null && zoom < minNativeZoom) {
  4625. return tileSize.divideBy(map.getZoomScale(minNativeZoom, zoom)).round();
  4626. }
  4627. // increase tile size when scaling above maxNativeZoom
  4628. if (maxNativeZoom !== null && zoom > maxNativeZoom) {
  4629. return tileSize.divideBy(map.getZoomScale(maxNativeZoom, zoom)).round();
  4630. }
  4631. return tileSize;
  4632. },
  4633. _onTileRemove: function (e) {
  4634. e.tile.onload = null;
  4635. },
  4636. _getZoomForUrl: function () {
  4637. var zoom = this._tileZoom,
  4638. maxZoom = this.options.maxZoom,
  4639. zoomReverse = this.options.zoomReverse,
  4640. zoomOffset = this.options.zoomOffset,
  4641. minNativeZoom = this.options.minNativeZoom,
  4642. maxNativeZoom = this.options.maxNativeZoom;
  4643. if (zoomReverse) {
  4644. zoom = maxZoom - zoom;
  4645. }
  4646. zoom += zoomOffset;
  4647. if (minNativeZoom !== null && zoom < minNativeZoom) {
  4648. return minNativeZoom;
  4649. }
  4650. if (maxNativeZoom !== null && zoom > maxNativeZoom) {
  4651. return maxNativeZoom;
  4652. }
  4653. return zoom;
  4654. },
  4655. _getSubdomain: function (tilePoint) {
  4656. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  4657. return this.options.subdomains[index];
  4658. },
  4659. // stops loading all tiles in the background layer
  4660. _abortLoading: function () {
  4661. var i, tile;
  4662. for (i in this._tiles) {
  4663. if (this._tiles[i].coords.z !== this._tileZoom) {
  4664. tile = this._tiles[i].el;
  4665. tile.onload = L.Util.falseFn;
  4666. tile.onerror = L.Util.falseFn;
  4667. if (!tile.complete) {
  4668. tile.src = L.Util.emptyImageUrl;
  4669. L.DomUtil.remove(tile);
  4670. }
  4671. }
  4672. }
  4673. }
  4674. });
  4675. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  4676. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  4677. L.tileLayer = function (url, options) {
  4678. return new L.TileLayer(url, options);
  4679. };
  4680. /*
  4681. * @class TileLayer.WMS
  4682. * @inherits TileLayer
  4683. * @aka L.TileLayer.WMS
  4684. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  4685. *
  4686. * @example
  4687. *
  4688. * ```js
  4689. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  4690. * layers: 'nexrad-n0r-900913',
  4691. * format: 'image/png',
  4692. * transparent: true,
  4693. * attribution: "Weather data © 2012 IEM Nexrad"
  4694. * });
  4695. * ```
  4696. */
  4697. L.TileLayer.WMS = L.TileLayer.extend({
  4698. // @section
  4699. // @aka TileLayer.WMS options
  4700. // If any custom options not documented here are used, they will be sent to the
  4701. // WMS server as extra parameters in each request URL. This can be useful for
  4702. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  4703. defaultWmsParams: {
  4704. service: 'WMS',
  4705. request: 'GetMap',
  4706. // @option layers: String = ''
  4707. // **(required)** Comma-separated list of WMS layers to show.
  4708. layers: '',
  4709. // @option styles: String = ''
  4710. // Comma-separated list of WMS styles.
  4711. styles: '',
  4712. // @option format: String = 'image/jpeg'
  4713. // WMS image format (use `'image/png'` for layers with transparency).
  4714. format: 'image/jpeg',
  4715. // @option transparent: Boolean = false
  4716. // If `true`, the WMS service will return images with transparency.
  4717. transparent: false,
  4718. // @option version: String = '1.1.1'
  4719. // Version of the WMS service to use
  4720. version: '1.1.1'
  4721. },
  4722. options: {
  4723. // @option crs: CRS = null
  4724. // Coordinate Reference System to use for the WMS requests, defaults to
  4725. // map CRS. Don't change this if you're not sure what it means.
  4726. crs: null,
  4727. // @option uppercase: Boolean = false
  4728. // If `true`, WMS request parameter keys will be uppercase.
  4729. uppercase: false
  4730. },
  4731. initialize: function (url, options) {
  4732. this._url = url;
  4733. var wmsParams = L.extend({}, this.defaultWmsParams);
  4734. // all keys that are not TileLayer options go to WMS params
  4735. for (var i in options) {
  4736. if (!(i in this.options)) {
  4737. wmsParams[i] = options[i];
  4738. }
  4739. }
  4740. options = L.setOptions(this, options);
  4741. wmsParams.width = wmsParams.height = options.tileSize * (options.detectRetina && L.Browser.retina ? 2 : 1);
  4742. this.wmsParams = wmsParams;
  4743. },
  4744. onAdd: function (map) {
  4745. this._crs = this.options.crs || map.options.crs;
  4746. this._wmsVersion = parseFloat(this.wmsParams.version);
  4747. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  4748. this.wmsParams[projectionKey] = this._crs.code;
  4749. L.TileLayer.prototype.onAdd.call(this, map);
  4750. },
  4751. getTileUrl: function (coords) {
  4752. var tileBounds = this._tileCoordsToBounds(coords),
  4753. nw = this._crs.project(tileBounds.getNorthWest()),
  4754. se = this._crs.project(tileBounds.getSouthEast()),
  4755. bbox = (this._wmsVersion >= 1.3 && this._crs === L.CRS.EPSG4326 ?
  4756. [se.y, nw.x, nw.y, se.x] :
  4757. [nw.x, se.y, se.x, nw.y]).join(','),
  4758. url = L.TileLayer.prototype.getTileUrl.call(this, coords);
  4759. return url +
  4760. L.Util.getParamString(this.wmsParams, url, this.options.uppercase) +
  4761. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  4762. },
  4763. // @method setParams(params: Object, noRedraw?: Boolean): this
  4764. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  4765. setParams: function (params, noRedraw) {
  4766. L.extend(this.wmsParams, params);
  4767. if (!noRedraw) {
  4768. this.redraw();
  4769. }
  4770. return this;
  4771. }
  4772. });
  4773. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  4774. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  4775. L.tileLayer.wms = function (url, options) {
  4776. return new L.TileLayer.WMS(url, options);
  4777. };
  4778. /*
  4779. * @class ImageOverlay
  4780. * @aka L.ImageOverlay
  4781. * @inherits Interactive layer
  4782. *
  4783. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  4784. *
  4785. * @example
  4786. *
  4787. * ```js
  4788. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  4789. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  4790. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  4791. * ```
  4792. */
  4793. L.ImageOverlay = L.Layer.extend({
  4794. // @section
  4795. // @aka ImageOverlay options
  4796. options: {
  4797. // @option opacity: Number = 1.0
  4798. // The opacity of the image overlay.
  4799. opacity: 1,
  4800. // @option alt: String = ''
  4801. // Text for the `alt` attribute of the image (useful for accessibility).
  4802. alt: '',
  4803. // @option interactive: Boolean = false
  4804. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  4805. interactive: false,
  4806. // @option crossOrigin: Boolean = false
  4807. // If true, the image will have its crossOrigin attribute set to ''. This is needed if you want to access image pixel data.
  4808. crossOrigin: false
  4809. },
  4810. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  4811. this._url = url;
  4812. this._bounds = L.latLngBounds(bounds);
  4813. L.setOptions(this, options);
  4814. },
  4815. onAdd: function () {
  4816. if (!this._image) {
  4817. this._initImage();
  4818. if (this.options.opacity < 1) {
  4819. this._updateOpacity();
  4820. }
  4821. }
  4822. if (this.options.interactive) {
  4823. L.DomUtil.addClass(this._image, 'leaflet-interactive');
  4824. this.addInteractiveTarget(this._image);
  4825. }
  4826. this.getPane().appendChild(this._image);
  4827. this._reset();
  4828. },
  4829. onRemove: function () {
  4830. L.DomUtil.remove(this._image);
  4831. if (this.options.interactive) {
  4832. this.removeInteractiveTarget(this._image);
  4833. }
  4834. },
  4835. // @method setOpacity(opacity: Number): this
  4836. // Sets the opacity of the overlay.
  4837. setOpacity: function (opacity) {
  4838. this.options.opacity = opacity;
  4839. if (this._image) {
  4840. this._updateOpacity();
  4841. }
  4842. return this;
  4843. },
  4844. setStyle: function (styleOpts) {
  4845. if (styleOpts.opacity) {
  4846. this.setOpacity(styleOpts.opacity);
  4847. }
  4848. return this;
  4849. },
  4850. // @method bringToFront(): this
  4851. // Brings the layer to the top of all overlays.
  4852. bringToFront: function () {
  4853. if (this._map) {
  4854. L.DomUtil.toFront(this._image);
  4855. }
  4856. return this;
  4857. },
  4858. // @method bringToBack(): this
  4859. // Brings the layer to the bottom of all overlays.
  4860. bringToBack: function () {
  4861. if (this._map) {
  4862. L.DomUtil.toBack(this._image);
  4863. }
  4864. return this;
  4865. },
  4866. // @method setUrl(url: String): this
  4867. // Changes the URL of the image.
  4868. setUrl: function (url) {
  4869. this._url = url;
  4870. if (this._image) {
  4871. this._image.src = url;
  4872. }
  4873. return this;
  4874. },
  4875. // @method setBounds(bounds: LatLngBounds): this
  4876. // Update the bounds that this ImageOverlay covers
  4877. setBounds: function (bounds) {
  4878. this._bounds = bounds;
  4879. if (this._map) {
  4880. this._reset();
  4881. }
  4882. return this;
  4883. },
  4884. getEvents: function () {
  4885. var events = {
  4886. zoom: this._reset,
  4887. viewreset: this._reset
  4888. };
  4889. if (this._zoomAnimated) {
  4890. events.zoomanim = this._animateZoom;
  4891. }
  4892. return events;
  4893. },
  4894. // @method getBounds(): LatLngBounds
  4895. // Get the bounds that this ImageOverlay covers
  4896. getBounds: function () {
  4897. return this._bounds;
  4898. },
  4899. // @method getElement(): HTMLElement
  4900. // Get the img element that represents the ImageOverlay on the map
  4901. getElement: function () {
  4902. return this._image;
  4903. },
  4904. _initImage: function () {
  4905. var img = this._image = L.DomUtil.create('img',
  4906. 'leaflet-image-layer ' + (this._zoomAnimated ? 'leaflet-zoom-animated' : ''));
  4907. img.onselectstart = L.Util.falseFn;
  4908. img.onmousemove = L.Util.falseFn;
  4909. img.onload = L.bind(this.fire, this, 'load');
  4910. if (this.options.crossOrigin) {
  4911. img.crossOrigin = '';
  4912. }
  4913. img.src = this._url;
  4914. img.alt = this.options.alt;
  4915. },
  4916. _animateZoom: function (e) {
  4917. var scale = this._map.getZoomScale(e.zoom),
  4918. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  4919. L.DomUtil.setTransform(this._image, offset, scale);
  4920. },
  4921. _reset: function () {
  4922. var image = this._image,
  4923. bounds = new L.Bounds(
  4924. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  4925. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  4926. size = bounds.getSize();
  4927. L.DomUtil.setPosition(image, bounds.min);
  4928. image.style.width = size.x + 'px';
  4929. image.style.height = size.y + 'px';
  4930. },
  4931. _updateOpacity: function () {
  4932. L.DomUtil.setOpacity(this._image, this.options.opacity);
  4933. }
  4934. });
  4935. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  4936. // Instantiates an image overlay object given the URL of the image and the
  4937. // geographical bounds it is tied to.
  4938. L.imageOverlay = function (url, bounds, options) {
  4939. return new L.ImageOverlay(url, bounds, options);
  4940. };
  4941. /*
  4942. * @class Icon
  4943. * @aka L.Icon
  4944. * @inherits Layer
  4945. *
  4946. * Represents an icon to provide when creating a marker.
  4947. *
  4948. * @example
  4949. *
  4950. * ```js
  4951. * var myIcon = L.icon({
  4952. * iconUrl: 'my-icon.png',
  4953. * iconRetinaUrl: 'my-icon@2x.png',
  4954. * iconSize: [38, 95],
  4955. * iconAnchor: [22, 94],
  4956. * popupAnchor: [-3, -76],
  4957. * shadowUrl: 'my-icon-shadow.png',
  4958. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  4959. * shadowSize: [68, 95],
  4960. * shadowAnchor: [22, 94]
  4961. * });
  4962. *
  4963. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  4964. * ```
  4965. *
  4966. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  4967. *
  4968. */
  4969. L.Icon = L.Class.extend({
  4970. /* @section
  4971. * @aka Icon options
  4972. *
  4973. * @option iconUrl: String = null
  4974. * **(required)** The URL to the icon image (absolute or relative to your script path).
  4975. *
  4976. * @option iconRetinaUrl: String = null
  4977. * The URL to a retina sized version of the icon image (absolute or relative to your
  4978. * script path). Used for Retina screen devices.
  4979. *
  4980. * @option iconSize: Point = null
  4981. * Size of the icon image in pixels.
  4982. *
  4983. * @option iconAnchor: Point = null
  4984. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  4985. * will be aligned so that this point is at the marker's geographical location. Centered
  4986. * by default if size is specified, also can be set in CSS with negative margins.
  4987. *
  4988. * @option popupAnchor: Point = null
  4989. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  4990. *
  4991. * @option shadowUrl: String = null
  4992. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  4993. *
  4994. * @option shadowRetinaUrl: String = null
  4995. *
  4996. * @option shadowSize: Point = null
  4997. * Size of the shadow image in pixels.
  4998. *
  4999. * @option shadowAnchor: Point = null
  5000. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  5001. * as iconAnchor if not specified).
  5002. *
  5003. * @option className: String = ''
  5004. * A custom class name to assign to both icon and shadow images. Empty by default.
  5005. */
  5006. initialize: function (options) {
  5007. L.setOptions(this, options);
  5008. },
  5009. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  5010. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  5011. // styled according to the options.
  5012. createIcon: function (oldIcon) {
  5013. return this._createIcon('icon', oldIcon);
  5014. },
  5015. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  5016. // As `createIcon`, but for the shadow beneath it.
  5017. createShadow: function (oldIcon) {
  5018. return this._createIcon('shadow', oldIcon);
  5019. },
  5020. _createIcon: function (name, oldIcon) {
  5021. var src = this._getIconUrl(name);
  5022. if (!src) {
  5023. if (name === 'icon') {
  5024. throw new Error('iconUrl not set in Icon options (see the docs).');
  5025. }
  5026. return null;
  5027. }
  5028. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  5029. this._setIconStyles(img, name);
  5030. return img;
  5031. },
  5032. _setIconStyles: function (img, name) {
  5033. var options = this.options;
  5034. var sizeOption = options[name + 'Size'];
  5035. if (typeof sizeOption === 'number') {
  5036. sizeOption = [sizeOption, sizeOption];
  5037. }
  5038. var size = L.point(sizeOption),
  5039. anchor = L.point(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  5040. size && size.divideBy(2, true));
  5041. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  5042. if (anchor) {
  5043. img.style.marginLeft = (-anchor.x) + 'px';
  5044. img.style.marginTop = (-anchor.y) + 'px';
  5045. }
  5046. if (size) {
  5047. img.style.width = size.x + 'px';
  5048. img.style.height = size.y + 'px';
  5049. }
  5050. },
  5051. _createImg: function (src, el) {
  5052. el = el || document.createElement('img');
  5053. el.src = src;
  5054. return el;
  5055. },
  5056. _getIconUrl: function (name) {
  5057. return L.Browser.retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  5058. }
  5059. });
  5060. // @factory L.icon(options: Icon options)
  5061. // Creates an icon instance with the given options.
  5062. L.icon = function (options) {
  5063. return new L.Icon(options);
  5064. };
  5065. /*
  5066. * @miniclass Icon.Default (Icon)
  5067. * @aka L.Icon.Default
  5068. * @section
  5069. *
  5070. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  5071. * no icon is specified. Points to the blue marker image distributed with Leaflet
  5072. * releases.
  5073. *
  5074. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  5075. * (which is a set of `Icon options`).
  5076. *
  5077. * If you want to _completely_ replace the default icon, override the
  5078. * `L.Marker.prototype.options.icon` with your own icon instead.
  5079. */
  5080. L.Icon.Default = L.Icon.extend({
  5081. options: {
  5082. iconUrl: 'marker-icon.png',
  5083. iconRetinaUrl: 'marker-icon-2x.png',
  5084. // shadowUrl: 'marker-shadow.png',
  5085. iconSize: [25, 41],
  5086. iconAnchor: [12, 41],
  5087. popupAnchor: [1, -34],
  5088. tooltipAnchor: [16, -28],
  5089. // shadowSize: [41, 41]
  5090. },
  5091. _getIconUrl: function (name) {
  5092. if (!L.Icon.Default.imagePath) { // Deprecated, backwards-compatibility only
  5093. L.Icon.Default.imagePath = this._detectIconPath();
  5094. }
  5095. // @option imagePath: String
  5096. // `L.Icon.Default` will try to auto-detect the absolute location of the
  5097. // blue icon images. If you are placing these images in a non-standard
  5098. // way, set this option to point to the right absolute path.
  5099. return (this.options.imagePath || L.Icon.Default.imagePath) + L.Icon.prototype._getIconUrl.call(this, name);
  5100. },
  5101. _detectIconPath: function () {
  5102. var el = L.DomUtil.create('div', 'leaflet-default-icon-path', document.body);
  5103. var path = L.DomUtil.getStyle(el, 'background-image') ||
  5104. L.DomUtil.getStyle(el, 'backgroundImage'); // IE8
  5105. document.body.removeChild(el);
  5106. return path.indexOf('url') === 0 ?
  5107. path.replace(/^url\([\"\']?/, '').replace(/marker-icon\.png[\"\']?\)$/, '') : '';
  5108. }
  5109. });
  5110. /*
  5111. * @class Marker
  5112. * @inherits Interactive layer
  5113. * @aka L.Marker
  5114. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  5115. *
  5116. * @example
  5117. *
  5118. * ```js
  5119. * L.marker([50.5, 30.5]).addTo(map);
  5120. * ```
  5121. */
  5122. L.Marker = L.Layer.extend({
  5123. // @section
  5124. // @aka Marker options
  5125. options: {
  5126. // @option icon: Icon = *
  5127. // Icon class to use for rendering the marker. See [Icon documentation](#L.Icon) for details on how to customize the marker icon. If not specified, a new `L.Icon.Default` is used.
  5128. icon: new L.Icon.Default(),
  5129. // Option inherited from "Interactive layer" abstract class
  5130. interactive: true,
  5131. // @option draggable: Boolean = false
  5132. // Whether the marker is draggable with mouse/touch or not.
  5133. draggable: false,
  5134. // @option keyboard: Boolean = true
  5135. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  5136. keyboard: true,
  5137. // @option title: String = ''
  5138. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  5139. title: '',
  5140. // @option alt: String = ''
  5141. // Text for the `alt` attribute of the icon image (useful for accessibility).
  5142. alt: '',
  5143. // @option zIndexOffset: Number = 0
  5144. // 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).
  5145. zIndexOffset: 0,
  5146. // @option opacity: Number = 1.0
  5147. // The opacity of the marker.
  5148. opacity: 1,
  5149. // @option riseOnHover: Boolean = false
  5150. // If `true`, the marker will get on top of others when you hover the mouse over it.
  5151. riseOnHover: false,
  5152. // @option riseOffset: Number = 250
  5153. // The z-index offset used for the `riseOnHover` feature.
  5154. riseOffset: 250,
  5155. // @option pane: String = 'markerPane'
  5156. // `Map pane` where the markers icon will be added.
  5157. pane: 'markerPane',
  5158. nonBubblingEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu']
  5159. },
  5160. /* @section
  5161. *
  5162. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  5163. */
  5164. initialize: function (latlng, options) {
  5165. L.setOptions(this, options);
  5166. this._latlng = L.latLng(latlng);
  5167. },
  5168. onAdd: function (map) {
  5169. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  5170. if (this._zoomAnimated) {
  5171. map.on('zoomanim', this._animateZoom, this);
  5172. }
  5173. this._initIcon();
  5174. this.update();
  5175. },
  5176. onRemove: function (map) {
  5177. if (this.dragging && this.dragging.enabled()) {
  5178. this.options.draggable = true;
  5179. this.dragging.removeHooks();
  5180. }
  5181. if (this._zoomAnimated) {
  5182. map.off('zoomanim', this._animateZoom, this);
  5183. }
  5184. this._removeIcon();
  5185. this._removeShadow();
  5186. },
  5187. getEvents: function () {
  5188. return {
  5189. zoom: this.update,
  5190. viewreset: this.update
  5191. };
  5192. },
  5193. // @method getLatLng: LatLng
  5194. // Returns the current geographical position of the marker.
  5195. getLatLng: function () {
  5196. return this._latlng;
  5197. },
  5198. // @method setLatLng(latlng: LatLng): this
  5199. // Changes the marker position to the given point.
  5200. setLatLng: function (latlng) {
  5201. var oldLatLng = this._latlng;
  5202. this._latlng = L.latLng(latlng);
  5203. this.update();
  5204. // @event move: Event
  5205. // 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`.
  5206. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  5207. },
  5208. // @method setZIndexOffset(offset: Number): this
  5209. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  5210. setZIndexOffset: function (offset) {
  5211. this.options.zIndexOffset = offset;
  5212. return this.update();
  5213. },
  5214. // @method setIcon(icon: Icon): this
  5215. // Changes the marker icon.
  5216. setIcon: function (icon) {
  5217. this.options.icon = icon;
  5218. if (this._map) {
  5219. this._initIcon();
  5220. this.update();
  5221. }
  5222. if (this._popup) {
  5223. this.bindPopup(this._popup, this._popup.options);
  5224. }
  5225. return this;
  5226. },
  5227. getElement: function () {
  5228. return this._icon;
  5229. },
  5230. update: function () {
  5231. if (this._icon) {
  5232. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  5233. this._setPos(pos);
  5234. }
  5235. return this;
  5236. },
  5237. _initIcon: function () {
  5238. var options = this.options,
  5239. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  5240. var icon = options.icon.createIcon(this._icon),
  5241. addIcon = false;
  5242. // if we're not reusing the icon, remove the old one and init new one
  5243. if (icon !== this._icon) {
  5244. if (this._icon) {
  5245. this._removeIcon();
  5246. }
  5247. addIcon = true;
  5248. if (options.title) {
  5249. icon.title = options.title;
  5250. }
  5251. if (options.alt) {
  5252. icon.alt = options.alt;
  5253. }
  5254. }
  5255. L.DomUtil.addClass(icon, classToAdd);
  5256. if (options.keyboard) {
  5257. icon.tabIndex = '0';
  5258. }
  5259. this._icon = icon;
  5260. if (options.riseOnHover) {
  5261. this.on({
  5262. mouseover: this._bringToFront,
  5263. mouseout: this._resetZIndex
  5264. });
  5265. }
  5266. var newShadow = options.icon.createShadow(this._shadow),
  5267. addShadow = false;
  5268. if (newShadow !== this._shadow) {
  5269. this._removeShadow();
  5270. addShadow = true;
  5271. }
  5272. if (newShadow) {
  5273. L.DomUtil.addClass(newShadow, classToAdd);
  5274. newShadow.alt = '';
  5275. }
  5276. this._shadow = newShadow;
  5277. if (options.opacity < 1) {
  5278. this._updateOpacity();
  5279. }
  5280. if (addIcon) {
  5281. this.getPane().appendChild(this._icon);
  5282. }
  5283. this._initInteraction();
  5284. if (newShadow && addShadow) {
  5285. this.getPane('shadowPane').appendChild(this._shadow);
  5286. }
  5287. },
  5288. _removeIcon: function () {
  5289. if (this.options.riseOnHover) {
  5290. this.off({
  5291. mouseover: this._bringToFront,
  5292. mouseout: this._resetZIndex
  5293. });
  5294. }
  5295. L.DomUtil.remove(this._icon);
  5296. this.removeInteractiveTarget(this._icon);
  5297. this._icon = null;
  5298. },
  5299. _removeShadow: function () {
  5300. if (this._shadow) {
  5301. L.DomUtil.remove(this._shadow);
  5302. }
  5303. this._shadow = null;
  5304. },
  5305. _setPos: function (pos) {
  5306. L.DomUtil.setPosition(this._icon, pos);
  5307. if (this._shadow) {
  5308. L.DomUtil.setPosition(this._shadow, pos);
  5309. }
  5310. this._zIndex = pos.y + this.options.zIndexOffset;
  5311. this._resetZIndex();
  5312. },
  5313. _updateZIndex: function (offset) {
  5314. this._icon.style.zIndex = this._zIndex + offset;
  5315. },
  5316. _animateZoom: function (opt) {
  5317. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  5318. this._setPos(pos);
  5319. },
  5320. _initInteraction: function () {
  5321. if (!this.options.interactive) { return; }
  5322. L.DomUtil.addClass(this._icon, 'leaflet-interactive');
  5323. this.addInteractiveTarget(this._icon);
  5324. if (L.Handler.MarkerDrag) {
  5325. var draggable = this.options.draggable;
  5326. if (this.dragging) {
  5327. draggable = this.dragging.enabled();
  5328. this.dragging.disable();
  5329. }
  5330. this.dragging = new L.Handler.MarkerDrag(this);
  5331. if (draggable) {
  5332. this.dragging.enable();
  5333. }
  5334. }
  5335. },
  5336. // @method setOpacity(opacity: Number): this
  5337. // Changes the opacity of the marker.
  5338. setOpacity: function (opacity) {
  5339. this.options.opacity = opacity;
  5340. if (this._map) {
  5341. this._updateOpacity();
  5342. }
  5343. return this;
  5344. },
  5345. _updateOpacity: function () {
  5346. var opacity = this.options.opacity;
  5347. L.DomUtil.setOpacity(this._icon, opacity);
  5348. if (this._shadow) {
  5349. L.DomUtil.setOpacity(this._shadow, opacity);
  5350. }
  5351. },
  5352. _bringToFront: function () {
  5353. this._updateZIndex(this.options.riseOffset);
  5354. },
  5355. _resetZIndex: function () {
  5356. this._updateZIndex(0);
  5357. },
  5358. _getPopupAnchor: function () {
  5359. return this.options.icon.options.popupAnchor || [0, 0];
  5360. },
  5361. _getTooltipAnchor: function () {
  5362. return this.options.icon.options.tooltipAnchor || [0, 0];
  5363. }
  5364. });
  5365. // factory L.marker(latlng: LatLng, options? : Marker options)
  5366. // @factory L.marker(latlng: LatLng, options? : Marker options)
  5367. // Instantiates a Marker object given a geographical point and optionally an options object.
  5368. L.marker = function (latlng, options) {
  5369. return new L.Marker(latlng, options);
  5370. };
  5371. /*
  5372. * @class DivIcon
  5373. * @aka L.DivIcon
  5374. * @inherits Icon
  5375. *
  5376. * Represents a lightweight icon for markers that uses a simple `<div>`
  5377. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  5378. *
  5379. * @example
  5380. * ```js
  5381. * var myIcon = L.divIcon({className: 'my-div-icon'});
  5382. * // you can set .my-div-icon styles in CSS
  5383. *
  5384. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5385. * ```
  5386. *
  5387. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  5388. */
  5389. L.DivIcon = L.Icon.extend({
  5390. options: {
  5391. // @section
  5392. // @aka DivIcon options
  5393. iconSize: [12, 12], // also can be set through CSS
  5394. // iconAnchor: (Point),
  5395. // popupAnchor: (Point),
  5396. // @option html: String = ''
  5397. // Custom HTML code to put inside the div element, empty by default.
  5398. html: false,
  5399. // @option bgPos: Point = [0, 0]
  5400. // Optional relative position of the background, in pixels
  5401. bgPos: null,
  5402. className: 'leaflet-div-icon'
  5403. },
  5404. createIcon: function (oldIcon) {
  5405. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  5406. options = this.options;
  5407. div.innerHTML = options.html !== false ? options.html : '';
  5408. if (options.bgPos) {
  5409. var bgPos = L.point(options.bgPos);
  5410. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  5411. }
  5412. this._setIconStyles(div, 'icon');
  5413. return div;
  5414. },
  5415. createShadow: function () {
  5416. return null;
  5417. }
  5418. });
  5419. // @factory L.divIcon(options: DivIcon options)
  5420. // Creates a `DivIcon` instance with the given options.
  5421. L.divIcon = function (options) {
  5422. return new L.DivIcon(options);
  5423. };
  5424. /*
  5425. * @class DivOverlay
  5426. * @inherits Layer
  5427. * @aka L.DivOverlay
  5428. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  5429. */
  5430. // @namespace DivOverlay
  5431. L.DivOverlay = L.Layer.extend({
  5432. // @section
  5433. // @aka DivOverlay options
  5434. options: {
  5435. // @option offset: Point = Point(0, 7)
  5436. // The offset of the popup position. Useful to control the anchor
  5437. // of the popup when opening it on some overlays.
  5438. offset: [0, 7],
  5439. // @option className: String = ''
  5440. // A custom CSS class name to assign to the popup.
  5441. className: '',
  5442. // @option pane: String = 'popupPane'
  5443. // `Map pane` where the popup will be added.
  5444. pane: 'popupPane'
  5445. },
  5446. initialize: function (options, source) {
  5447. L.setOptions(this, options);
  5448. this._source = source;
  5449. },
  5450. onAdd: function (map) {
  5451. this._zoomAnimated = map._zoomAnimated;
  5452. if (!this._container) {
  5453. this._initLayout();
  5454. }
  5455. if (map._fadeAnimated) {
  5456. L.DomUtil.setOpacity(this._container, 0);
  5457. }
  5458. clearTimeout(this._removeTimeout);
  5459. this.getPane().appendChild(this._container);
  5460. this.update();
  5461. if (map._fadeAnimated) {
  5462. L.DomUtil.setOpacity(this._container, 1);
  5463. }
  5464. this.bringToFront();
  5465. },
  5466. onRemove: function (map) {
  5467. if (map._fadeAnimated) {
  5468. L.DomUtil.setOpacity(this._container, 0);
  5469. this._removeTimeout = setTimeout(L.bind(L.DomUtil.remove, L.DomUtil, this._container), 200);
  5470. } else {
  5471. L.DomUtil.remove(this._container);
  5472. }
  5473. },
  5474. // @namespace Popup
  5475. // @method getLatLng: LatLng
  5476. // Returns the geographical point of popup.
  5477. getLatLng: function () {
  5478. return this._latlng;
  5479. },
  5480. // @method setLatLng(latlng: LatLng): this
  5481. // Sets the geographical point where the popup will open.
  5482. setLatLng: function (latlng) {
  5483. this._latlng = L.latLng(latlng);
  5484. if (this._map) {
  5485. this._updatePosition();
  5486. this._adjustPan();
  5487. }
  5488. return this;
  5489. },
  5490. // @method getContent: String|HTMLElement
  5491. // Returns the content of the popup.
  5492. getContent: function () {
  5493. return this._content;
  5494. },
  5495. // @method setContent(htmlContent: String|HTMLElement|Function): this
  5496. // 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.
  5497. setContent: function (content) {
  5498. this._content = content;
  5499. this.update();
  5500. return this;
  5501. },
  5502. // @method getElement: String|HTMLElement
  5503. // Alias for [getContent()](#popup-getcontent)
  5504. getElement: function () {
  5505. return this._container;
  5506. },
  5507. // @method update: null
  5508. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  5509. update: function () {
  5510. if (!this._map) { return; }
  5511. this._container.style.visibility = 'hidden';
  5512. this._updateContent();
  5513. this._updateLayout();
  5514. this._updatePosition();
  5515. this._container.style.visibility = '';
  5516. this._adjustPan();
  5517. },
  5518. getEvents: function () {
  5519. var events = {
  5520. zoom: this._updatePosition,
  5521. viewreset: this._updatePosition
  5522. };
  5523. if (this._zoomAnimated) {
  5524. events.zoomanim = this._animateZoom;
  5525. }
  5526. return events;
  5527. },
  5528. // @method isOpen: Boolean
  5529. // Returns `true` when the popup is visible on the map.
  5530. isOpen: function () {
  5531. return !!this._map && this._map.hasLayer(this);
  5532. },
  5533. // @method bringToFront: this
  5534. // Brings this popup in front of other popups (in the same map pane).
  5535. bringToFront: function () {
  5536. if (this._map) {
  5537. L.DomUtil.toFront(this._container);
  5538. }
  5539. return this;
  5540. },
  5541. // @method bringToBack: this
  5542. // Brings this popup to the back of other popups (in the same map pane).
  5543. bringToBack: function () {
  5544. if (this._map) {
  5545. L.DomUtil.toBack(this._container);
  5546. }
  5547. return this;
  5548. },
  5549. _updateContent: function () {
  5550. if (!this._content) { return; }
  5551. var node = this._contentNode;
  5552. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  5553. if (typeof content === 'string') {
  5554. node.innerHTML = content;
  5555. } else {
  5556. while (node.hasChildNodes()) {
  5557. node.removeChild(node.firstChild);
  5558. }
  5559. node.appendChild(content);
  5560. }
  5561. this.fire('contentupdate');
  5562. },
  5563. _updatePosition: function () {
  5564. if (!this._map) { return; }
  5565. var pos = this._map.latLngToLayerPoint(this._latlng),
  5566. offset = L.point(this.options.offset),
  5567. anchor = this._getAnchor();
  5568. if (this._zoomAnimated) {
  5569. L.DomUtil.setPosition(this._container, pos.add(anchor));
  5570. } else {
  5571. offset = offset.add(pos).add(anchor);
  5572. }
  5573. var bottom = this._containerBottom = -offset.y,
  5574. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  5575. // bottom position the popup in case the height of the popup changes (images loading etc)
  5576. this._container.style.bottom = bottom + 'px';
  5577. this._container.style.left = left + 'px';
  5578. },
  5579. _getAnchor: function () {
  5580. return [0, 0];
  5581. }
  5582. });
  5583. /*
  5584. * @class Popup
  5585. * @inherits DivOverlay
  5586. * @aka L.Popup
  5587. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  5588. * open popups while making sure that only one popup is open at one time
  5589. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  5590. *
  5591. * @example
  5592. *
  5593. * If you want to just bind a popup to marker click and then open it, it's really easy:
  5594. *
  5595. * ```js
  5596. * marker.bindPopup(popupContent).openPopup();
  5597. * ```
  5598. * Path overlays like polylines also have a `bindPopup` method.
  5599. * Here's a more complicated way to open a popup on a map:
  5600. *
  5601. * ```js
  5602. * var popup = L.popup()
  5603. * .setLatLng(latlng)
  5604. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  5605. * .openOn(map);
  5606. * ```
  5607. */
  5608. // @namespace Popup
  5609. L.Popup = L.DivOverlay.extend({
  5610. // @section
  5611. // @aka Popup options
  5612. options: {
  5613. // @option maxWidth: Number = 300
  5614. // Max width of the popup, in pixels.
  5615. maxWidth: 300,
  5616. // @option minWidth: Number = 50
  5617. // Min width of the popup, in pixels.
  5618. minWidth: 50,
  5619. // @option maxHeight: Number = null
  5620. // If set, creates a scrollable container of the given height
  5621. // inside a popup if its content exceeds it.
  5622. maxHeight: null,
  5623. // @option autoPan: Boolean = true
  5624. // Set it to `false` if you don't want the map to do panning animation
  5625. // to fit the opened popup.
  5626. autoPan: true,
  5627. // @option autoPanPaddingTopLeft: Point = null
  5628. // The margin between the popup and the top left corner of the map
  5629. // view after autopanning was performed.
  5630. autoPanPaddingTopLeft: null,
  5631. // @option autoPanPaddingBottomRight: Point = null
  5632. // The margin between the popup and the bottom right corner of the map
  5633. // view after autopanning was performed.
  5634. autoPanPaddingBottomRight: null,
  5635. // @option autoPanPadding: Point = Point(5, 5)
  5636. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  5637. autoPanPadding: [5, 5],
  5638. // @option keepInView: Boolean = false
  5639. // Set it to `true` if you want to prevent users from panning the popup
  5640. // off of the screen while it is open.
  5641. keepInView: false,
  5642. // @option closeButton: Boolean = true
  5643. // Controls the presence of a close button in the popup.
  5644. closeButton: true,
  5645. // @option autoClose: Boolean = true
  5646. // Set it to `false` if you want to override the default behavior of
  5647. // the popup closing when user clicks the map (set globally by
  5648. // the Map's [closePopupOnClick](#map-closepopuponclick) option).
  5649. autoClose: true,
  5650. // @option className: String = ''
  5651. // A custom CSS class name to assign to the popup.
  5652. className: ''
  5653. },
  5654. // @namespace Popup
  5655. // @method openOn(map: Map): this
  5656. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  5657. openOn: function (map) {
  5658. map.openPopup(this);
  5659. return this;
  5660. },
  5661. onAdd: function (map) {
  5662. L.DivOverlay.prototype.onAdd.call(this, map);
  5663. // @namespace Map
  5664. // @section Popup events
  5665. // @event popupopen: PopupEvent
  5666. // Fired when a popup is opened in the map
  5667. map.fire('popupopen', {popup: this});
  5668. if (this._source) {
  5669. // @namespace Layer
  5670. // @section Popup events
  5671. // @event popupopen: PopupEvent
  5672. // Fired when a popup bound to this layer is opened
  5673. this._source.fire('popupopen', {popup: this}, true);
  5674. // For non-path layers, we toggle the popup when clicking
  5675. // again the layer, so prevent the map to reopen it.
  5676. if (!(this._source instanceof L.Path)) {
  5677. this._source.on('preclick', L.DomEvent.stopPropagation);
  5678. }
  5679. }
  5680. },
  5681. onRemove: function (map) {
  5682. L.DivOverlay.prototype.onRemove.call(this, map);
  5683. // @namespace Map
  5684. // @section Popup events
  5685. // @event popupclose: PopupEvent
  5686. // Fired when a popup in the map is closed
  5687. map.fire('popupclose', {popup: this});
  5688. if (this._source) {
  5689. // @namespace Layer
  5690. // @section Popup events
  5691. // @event popupclose: PopupEvent
  5692. // Fired when a popup bound to this layer is closed
  5693. this._source.fire('popupclose', {popup: this}, true);
  5694. if (!(this._source instanceof L.Path)) {
  5695. this._source.off('preclick', L.DomEvent.stopPropagation);
  5696. }
  5697. }
  5698. },
  5699. getEvents: function () {
  5700. var events = L.DivOverlay.prototype.getEvents.call(this);
  5701. if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  5702. events.preclick = this._close;
  5703. }
  5704. if (this.options.keepInView) {
  5705. events.moveend = this._adjustPan;
  5706. }
  5707. return events;
  5708. },
  5709. _close: function () {
  5710. if (this._map) {
  5711. this._map.closePopup(this);
  5712. }
  5713. },
  5714. _initLayout: function () {
  5715. var prefix = 'leaflet-popup',
  5716. container = this._container = L.DomUtil.create('div',
  5717. prefix + ' ' + (this.options.className || '') +
  5718. ' leaflet-zoom-animated');
  5719. if (this.options.closeButton) {
  5720. var closeButton = this._closeButton = L.DomUtil.create('a', prefix + '-close-button', container);
  5721. closeButton.href = '#close';
  5722. closeButton.innerHTML = '&#215;';
  5723. L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
  5724. }
  5725. var wrapper = this._wrapper = L.DomUtil.create('div', prefix + '-content-wrapper', container);
  5726. this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
  5727. L.DomEvent
  5728. .disableClickPropagation(wrapper)
  5729. .disableScrollPropagation(this._contentNode)
  5730. .on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
  5731. this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
  5732. this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
  5733. },
  5734. _updateLayout: function () {
  5735. var container = this._contentNode,
  5736. style = container.style;
  5737. style.width = '';
  5738. style.whiteSpace = 'nowrap';
  5739. var width = container.offsetWidth;
  5740. width = Math.min(width, this.options.maxWidth);
  5741. width = Math.max(width, this.options.minWidth);
  5742. style.width = (width + 1) + 'px';
  5743. style.whiteSpace = '';
  5744. style.height = '';
  5745. var height = container.offsetHeight,
  5746. maxHeight = this.options.maxHeight,
  5747. scrolledClass = 'leaflet-popup-scrolled';
  5748. if (maxHeight && height > maxHeight) {
  5749. style.height = maxHeight + 'px';
  5750. L.DomUtil.addClass(container, scrolledClass);
  5751. } else {
  5752. L.DomUtil.removeClass(container, scrolledClass);
  5753. }
  5754. this._containerWidth = this._container.offsetWidth;
  5755. },
  5756. _animateZoom: function (e) {
  5757. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  5758. anchor = this._getAnchor();
  5759. L.DomUtil.setPosition(this._container, pos.add(anchor));
  5760. },
  5761. _adjustPan: function () {
  5762. if (!this.options.autoPan || (this._map._panAnim && this._map._panAnim._inProgress)) { return; }
  5763. var map = this._map,
  5764. marginBottom = parseInt(L.DomUtil.getStyle(this._container, 'marginBottom'), 10) || 0,
  5765. containerHeight = this._container.offsetHeight + marginBottom,
  5766. containerWidth = this._containerWidth,
  5767. layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
  5768. layerPos._add(L.DomUtil.getPosition(this._container));
  5769. var containerPos = map.layerPointToContainerPoint(layerPos),
  5770. padding = L.point(this.options.autoPanPadding),
  5771. paddingTL = L.point(this.options.autoPanPaddingTopLeft || padding),
  5772. paddingBR = L.point(this.options.autoPanPaddingBottomRight || padding),
  5773. size = map.getSize(),
  5774. dx = 0,
  5775. dy = 0;
  5776. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  5777. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  5778. }
  5779. if (containerPos.x - dx - paddingTL.x < 0) { // left
  5780. dx = containerPos.x - paddingTL.x;
  5781. }
  5782. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  5783. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  5784. }
  5785. if (containerPos.y - dy - paddingTL.y < 0) { // top
  5786. dy = containerPos.y - paddingTL.y;
  5787. }
  5788. // @namespace Map
  5789. // @section Popup events
  5790. // @event autopanstart: Event
  5791. // Fired when the map starts autopanning when opening a popup.
  5792. if (dx || dy) {
  5793. map
  5794. .fire('autopanstart')
  5795. .panBy([dx, dy]);
  5796. }
  5797. },
  5798. _onCloseButtonClick: function (e) {
  5799. this._close();
  5800. L.DomEvent.stop(e);
  5801. },
  5802. _getAnchor: function () {
  5803. // Where should we anchor the popup on the source layer?
  5804. return L.point(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  5805. }
  5806. });
  5807. // @namespace Popup
  5808. // @factory L.popup(options?: Popup options, source?: Layer)
  5809. // 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.
  5810. L.popup = function (options, source) {
  5811. return new L.Popup(options, source);
  5812. };
  5813. /* @namespace Map
  5814. * @section Interaction Options
  5815. * @option closePopupOnClick: Boolean = true
  5816. * Set it to `false` if you don't want popups to close when user clicks the map.
  5817. */
  5818. L.Map.mergeOptions({
  5819. closePopupOnClick: true
  5820. });
  5821. // @namespace Map
  5822. // @section Methods for Layers and Controls
  5823. L.Map.include({
  5824. // @method openPopup(popup: Popup): this
  5825. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  5826. // @alternative
  5827. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  5828. // Creates a popup with the specified content and options and opens it in the given point on a map.
  5829. openPopup: function (popup, latlng, options) {
  5830. if (!(popup instanceof L.Popup)) {
  5831. popup = new L.Popup(options).setContent(popup);
  5832. }
  5833. if (latlng) {
  5834. popup.setLatLng(latlng);
  5835. }
  5836. if (this.hasLayer(popup)) {
  5837. return this;
  5838. }
  5839. if (this._popup && this._popup.options.autoClose) {
  5840. this.closePopup();
  5841. }
  5842. this._popup = popup;
  5843. return this.addLayer(popup);
  5844. },
  5845. // @method closePopup(popup?: Popup): this
  5846. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  5847. closePopup: function (popup) {
  5848. if (!popup || popup === this._popup) {
  5849. popup = this._popup;
  5850. this._popup = null;
  5851. }
  5852. if (popup) {
  5853. this.removeLayer(popup);
  5854. }
  5855. return this;
  5856. }
  5857. });
  5858. /*
  5859. * @namespace Layer
  5860. * @section Popup methods example
  5861. *
  5862. * All layers share a set of methods convenient for binding popups to it.
  5863. *
  5864. * ```js
  5865. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  5866. * layer.openPopup();
  5867. * layer.closePopup();
  5868. * ```
  5869. *
  5870. * 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.
  5871. */
  5872. // @section Popup methods
  5873. L.Layer.include({
  5874. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  5875. // Binds a popup to the layer with the passed `content` and sets up the
  5876. // neccessary event listeners. If a `Function` is passed it will receive
  5877. // the layer as the first argument and should return a `String` or `HTMLElement`.
  5878. bindPopup: function (content, options) {
  5879. if (content instanceof L.Popup) {
  5880. L.setOptions(content, options);
  5881. this._popup = content;
  5882. content._source = this;
  5883. } else {
  5884. if (!this._popup || options) {
  5885. this._popup = new L.Popup(options, this);
  5886. }
  5887. this._popup.setContent(content);
  5888. }
  5889. if (!this._popupHandlersAdded) {
  5890. this.on({
  5891. click: this._openPopup,
  5892. remove: this.closePopup,
  5893. move: this._movePopup
  5894. });
  5895. this._popupHandlersAdded = true;
  5896. }
  5897. return this;
  5898. },
  5899. // @method unbindPopup(): this
  5900. // Removes the popup previously bound with `bindPopup`.
  5901. unbindPopup: function () {
  5902. if (this._popup) {
  5903. this.off({
  5904. click: this._openPopup,
  5905. remove: this.closePopup,
  5906. move: this._movePopup
  5907. });
  5908. this._popupHandlersAdded = false;
  5909. this._popup = null;
  5910. }
  5911. return this;
  5912. },
  5913. // @method openPopup(latlng?: LatLng): this
  5914. // Opens the bound popup at the specificed `latlng` or at the default popup anchor if no `latlng` is passed.
  5915. openPopup: function (layer, latlng) {
  5916. if (!(layer instanceof L.Layer)) {
  5917. latlng = layer;
  5918. layer = this;
  5919. }
  5920. if (layer instanceof L.FeatureGroup) {
  5921. for (var id in this._layers) {
  5922. layer = this._layers[id];
  5923. break;
  5924. }
  5925. }
  5926. if (!latlng) {
  5927. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  5928. }
  5929. if (this._popup && this._map) {
  5930. // set popup source to this layer
  5931. this._popup._source = layer;
  5932. // update the popup (content, layout, ect...)
  5933. this._popup.update();
  5934. // open the popup on the map
  5935. this._map.openPopup(this._popup, latlng);
  5936. }
  5937. return this;
  5938. },
  5939. // @method closePopup(): this
  5940. // Closes the popup bound to this layer if it is open.
  5941. closePopup: function () {
  5942. if (this._popup) {
  5943. this._popup._close();
  5944. }
  5945. return this;
  5946. },
  5947. // @method togglePopup(): this
  5948. // Opens or closes the popup bound to this layer depending on its current state.
  5949. togglePopup: function (target) {
  5950. if (this._popup) {
  5951. if (this._popup._map) {
  5952. this.closePopup();
  5953. } else {
  5954. this.openPopup(target);
  5955. }
  5956. }
  5957. return this;
  5958. },
  5959. // @method isPopupOpen(): boolean
  5960. // Returns `true` if the popup bound to this layer is currently open.
  5961. isPopupOpen: function () {
  5962. return (this._popup ? this._popup.isOpen() : false);
  5963. },
  5964. // @method setPopupContent(content: String|HTMLElement|Popup): this
  5965. // Sets the content of the popup bound to this layer.
  5966. setPopupContent: function (content) {
  5967. if (this._popup) {
  5968. this._popup.setContent(content);
  5969. }
  5970. return this;
  5971. },
  5972. // @method getPopup(): Popup
  5973. // Returns the popup bound to this layer.
  5974. getPopup: function () {
  5975. return this._popup;
  5976. },
  5977. _openPopup: function (e) {
  5978. var layer = e.layer || e.target;
  5979. if (!this._popup) {
  5980. return;
  5981. }
  5982. if (!this._map) {
  5983. return;
  5984. }
  5985. // prevent map click
  5986. L.DomEvent.stop(e);
  5987. // if this inherits from Path its a vector and we can just
  5988. // open the popup at the new location
  5989. if (layer instanceof L.Path) {
  5990. this.openPopup(e.layer || e.target, e.latlng);
  5991. return;
  5992. }
  5993. // otherwise treat it like a marker and figure out
  5994. // if we should toggle it open/closed
  5995. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  5996. this.closePopup();
  5997. } else {
  5998. this.openPopup(layer, e.latlng);
  5999. }
  6000. },
  6001. _movePopup: function (e) {
  6002. this._popup.setLatLng(e.latlng);
  6003. }
  6004. });
  6005. /*
  6006. * @class Tooltip
  6007. * @inherits DivOverlay
  6008. * @aka L.Tooltip
  6009. * Used to display small texts on top of map layers.
  6010. *
  6011. * @example
  6012. *
  6013. * ```js
  6014. * marker.bindTooltip("my tooltip text").openTooltip();
  6015. * ```
  6016. * Note about tooltip offset. Leaflet takes two options in consideration
  6017. * for computing tooltip offseting:
  6018. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  6019. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  6020. * move it to the bottom. Negatives will move to the left and top.
  6021. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  6022. * should adapt this value if you use a custom icon.
  6023. */
  6024. // @namespace Tooltip
  6025. L.Tooltip = L.DivOverlay.extend({
  6026. // @section
  6027. // @aka Tooltip options
  6028. options: {
  6029. // @option pane: String = 'tooltipPane'
  6030. // `Map pane` where the tooltip will be added.
  6031. pane: 'tooltipPane',
  6032. // @option offset: Point = Point(0, 0)
  6033. // Optional offset of the tooltip position.
  6034. offset: [0, 0],
  6035. // @option direction: String = 'auto'
  6036. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  6037. // `top`, `bottom`, `center`, `auto`.
  6038. // `auto` will dynamicaly switch between `right` and `left` according to the tooltip
  6039. // position on the map.
  6040. direction: 'auto',
  6041. // @option permanent: Boolean = false
  6042. // Whether to open the tooltip permanently or only on mouseover.
  6043. permanent: false,
  6044. // @option sticky: Boolean = false
  6045. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  6046. sticky: false,
  6047. // @option interactive: Boolean = false
  6048. // If true, the tooltip will listen to the feature events.
  6049. interactive: false,
  6050. // @option opacity: Number = 0.9
  6051. // Tooltip container opacity.
  6052. opacity: 0.9
  6053. },
  6054. onAdd: function (map) {
  6055. L.DivOverlay.prototype.onAdd.call(this, map);
  6056. this.setOpacity(this.options.opacity);
  6057. // @namespace Map
  6058. // @section Tooltip events
  6059. // @event tooltipopen: TooltipEvent
  6060. // Fired when a tooltip is opened in the map.
  6061. map.fire('tooltipopen', {tooltip: this});
  6062. if (this._source) {
  6063. // @namespace Layer
  6064. // @section Tooltip events
  6065. // @event tooltipopen: TooltipEvent
  6066. // Fired when a tooltip bound to this layer is opened.
  6067. this._source.fire('tooltipopen', {tooltip: this}, true);
  6068. }
  6069. },
  6070. onRemove: function (map) {
  6071. L.DivOverlay.prototype.onRemove.call(this, map);
  6072. // @namespace Map
  6073. // @section Tooltip events
  6074. // @event tooltipclose: TooltipEvent
  6075. // Fired when a tooltip in the map is closed.
  6076. map.fire('tooltipclose', {tooltip: this});
  6077. if (this._source) {
  6078. // @namespace Layer
  6079. // @section Tooltip events
  6080. // @event tooltipclose: TooltipEvent
  6081. // Fired when a tooltip bound to this layer is closed.
  6082. this._source.fire('tooltipclose', {tooltip: this}, true);
  6083. }
  6084. },
  6085. getEvents: function () {
  6086. var events = L.DivOverlay.prototype.getEvents.call(this);
  6087. if (L.Browser.touch && !this.options.permanent) {
  6088. events.preclick = this._close;
  6089. }
  6090. return events;
  6091. },
  6092. _close: function () {
  6093. if (this._map) {
  6094. this._map.closeTooltip(this);
  6095. }
  6096. },
  6097. _initLayout: function () {
  6098. var prefix = 'leaflet-tooltip',
  6099. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6100. this._contentNode = this._container = L.DomUtil.create('div', className);
  6101. },
  6102. _updateLayout: function () {},
  6103. _adjustPan: function () {},
  6104. _setPosition: function (pos) {
  6105. var map = this._map,
  6106. container = this._container,
  6107. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  6108. tooltipPoint = map.layerPointToContainerPoint(pos),
  6109. direction = this.options.direction,
  6110. tooltipWidth = container.offsetWidth,
  6111. tooltipHeight = container.offsetHeight,
  6112. offset = L.point(this.options.offset),
  6113. anchor = this._getAnchor();
  6114. if (direction === 'top') {
  6115. pos = pos.add(L.point(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true));
  6116. } else if (direction === 'bottom') {
  6117. pos = pos.subtract(L.point(tooltipWidth / 2 - offset.x, -offset.y, true));
  6118. } else if (direction === 'center') {
  6119. pos = pos.subtract(L.point(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true));
  6120. } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
  6121. direction = 'right';
  6122. pos = pos.add(L.point(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true));
  6123. } else {
  6124. direction = 'left';
  6125. pos = pos.subtract(L.point(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true));
  6126. }
  6127. L.DomUtil.removeClass(container, 'leaflet-tooltip-right');
  6128. L.DomUtil.removeClass(container, 'leaflet-tooltip-left');
  6129. L.DomUtil.removeClass(container, 'leaflet-tooltip-top');
  6130. L.DomUtil.removeClass(container, 'leaflet-tooltip-bottom');
  6131. L.DomUtil.addClass(container, 'leaflet-tooltip-' + direction);
  6132. L.DomUtil.setPosition(container, pos);
  6133. },
  6134. _updatePosition: function () {
  6135. var pos = this._map.latLngToLayerPoint(this._latlng);
  6136. this._setPosition(pos);
  6137. },
  6138. setOpacity: function (opacity) {
  6139. this.options.opacity = opacity;
  6140. if (this._container) {
  6141. L.DomUtil.setOpacity(this._container, opacity);
  6142. }
  6143. },
  6144. _animateZoom: function (e) {
  6145. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  6146. this._setPosition(pos);
  6147. },
  6148. _getAnchor: function () {
  6149. // Where should we anchor the tooltip on the source layer?
  6150. return L.point(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  6151. }
  6152. });
  6153. // @namespace Tooltip
  6154. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  6155. // 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.
  6156. L.tooltip = function (options, source) {
  6157. return new L.Tooltip(options, source);
  6158. };
  6159. // @namespace Map
  6160. // @section Methods for Layers and Controls
  6161. L.Map.include({
  6162. // @method openTooltip(tooltip: Tooltip): this
  6163. // Opens the specified tooltip.
  6164. // @alternative
  6165. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  6166. // Creates a tooltip with the specified content and options and open it.
  6167. openTooltip: function (tooltip, latlng, options) {
  6168. if (!(tooltip instanceof L.Tooltip)) {
  6169. tooltip = new L.Tooltip(options).setContent(tooltip);
  6170. }
  6171. if (latlng) {
  6172. tooltip.setLatLng(latlng);
  6173. }
  6174. if (this.hasLayer(tooltip)) {
  6175. return this;
  6176. }
  6177. return this.addLayer(tooltip);
  6178. },
  6179. // @method closeTooltip(tooltip?: Tooltip): this
  6180. // Closes the tooltip given as parameter.
  6181. closeTooltip: function (tooltip) {
  6182. if (tooltip) {
  6183. this.removeLayer(tooltip);
  6184. }
  6185. return this;
  6186. }
  6187. });
  6188. /*
  6189. * @namespace Layer
  6190. * @section Tooltip methods example
  6191. *
  6192. * All layers share a set of methods convenient for binding tooltips to it.
  6193. *
  6194. * ```js
  6195. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  6196. * layer.openTooltip();
  6197. * layer.closeTooltip();
  6198. * ```
  6199. */
  6200. // @section Tooltip methods
  6201. L.Layer.include({
  6202. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  6203. // Binds a tooltip to the layer with the passed `content` and sets up the
  6204. // neccessary event listeners. If a `Function` is passed it will receive
  6205. // the layer as the first argument and should return a `String` or `HTMLElement`.
  6206. bindTooltip: function (content, options) {
  6207. if (content instanceof L.Tooltip) {
  6208. L.setOptions(content, options);
  6209. this._tooltip = content;
  6210. content._source = this;
  6211. } else {
  6212. if (!this._tooltip || options) {
  6213. this._tooltip = L.tooltip(options, this);
  6214. }
  6215. this._tooltip.setContent(content);
  6216. }
  6217. this._initTooltipInteractions();
  6218. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  6219. this.openTooltip();
  6220. }
  6221. return this;
  6222. },
  6223. // @method unbindTooltip(): this
  6224. // Removes the tooltip previously bound with `bindTooltip`.
  6225. unbindTooltip: function () {
  6226. if (this._tooltip) {
  6227. this._initTooltipInteractions(true);
  6228. this.closeTooltip();
  6229. this._tooltip = null;
  6230. }
  6231. return this;
  6232. },
  6233. _initTooltipInteractions: function (remove) {
  6234. if (!remove && this._tooltipHandlersAdded) { return; }
  6235. var onOff = remove ? 'off' : 'on',
  6236. events = {
  6237. remove: this.closeTooltip,
  6238. move: this._moveTooltip
  6239. };
  6240. if (!this._tooltip.options.permanent) {
  6241. events.mouseover = this._openTooltip;
  6242. events.mouseout = this.closeTooltip;
  6243. if (this._tooltip.options.sticky) {
  6244. events.mousemove = this._moveTooltip;
  6245. }
  6246. if (L.Browser.touch) {
  6247. events.click = this._openTooltip;
  6248. }
  6249. } else {
  6250. events.add = this._openTooltip;
  6251. }
  6252. this[onOff](events);
  6253. this._tooltipHandlersAdded = !remove;
  6254. },
  6255. // @method openTooltip(latlng?: LatLng): this
  6256. // Opens the bound tooltip at the specificed `latlng` or at the default tooltip anchor if no `latlng` is passed.
  6257. openTooltip: function (layer, latlng) {
  6258. if (!(layer instanceof L.Layer)) {
  6259. latlng = layer;
  6260. layer = this;
  6261. }
  6262. if (layer instanceof L.FeatureGroup) {
  6263. for (var id in this._layers) {
  6264. layer = this._layers[id];
  6265. break;
  6266. }
  6267. }
  6268. if (!latlng) {
  6269. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  6270. }
  6271. if (this._tooltip && this._map) {
  6272. // set tooltip source to this layer
  6273. this._tooltip._source = layer;
  6274. // update the tooltip (content, layout, ect...)
  6275. this._tooltip.update();
  6276. // open the tooltip on the map
  6277. this._map.openTooltip(this._tooltip, latlng);
  6278. // Tooltip container may not be defined if not permanent and never
  6279. // opened.
  6280. if (this._tooltip.options.interactive && this._tooltip._container) {
  6281. L.DomUtil.addClass(this._tooltip._container, 'leaflet-clickable');
  6282. this.addInteractiveTarget(this._tooltip._container);
  6283. }
  6284. }
  6285. return this;
  6286. },
  6287. // @method closeTooltip(): this
  6288. // Closes the tooltip bound to this layer if it is open.
  6289. closeTooltip: function () {
  6290. if (this._tooltip) {
  6291. this._tooltip._close();
  6292. if (this._tooltip.options.interactive && this._tooltip._container) {
  6293. L.DomUtil.removeClass(this._tooltip._container, 'leaflet-clickable');
  6294. this.removeInteractiveTarget(this._tooltip._container);
  6295. }
  6296. }
  6297. return this;
  6298. },
  6299. // @method toggleTooltip(): this
  6300. // Opens or closes the tooltip bound to this layer depending on its current state.
  6301. toggleTooltip: function (target) {
  6302. if (this._tooltip) {
  6303. if (this._tooltip._map) {
  6304. this.closeTooltip();
  6305. } else {
  6306. this.openTooltip(target);
  6307. }
  6308. }
  6309. return this;
  6310. },
  6311. // @method isTooltipOpen(): boolean
  6312. // Returns `true` if the tooltip bound to this layer is currently open.
  6313. isTooltipOpen: function () {
  6314. return this._tooltip.isOpen();
  6315. },
  6316. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  6317. // Sets the content of the tooltip bound to this layer.
  6318. setTooltipContent: function (content) {
  6319. if (this._tooltip) {
  6320. this._tooltip.setContent(content);
  6321. }
  6322. return this;
  6323. },
  6324. // @method getTooltip(): Tooltip
  6325. // Returns the tooltip bound to this layer.
  6326. getTooltip: function () {
  6327. return this._tooltip;
  6328. },
  6329. _openTooltip: function (e) {
  6330. var layer = e.layer || e.target;
  6331. if (!this._tooltip || !this._map) {
  6332. return;
  6333. }
  6334. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  6335. },
  6336. _moveTooltip: function (e) {
  6337. var latlng = e.latlng, containerPoint, layerPoint;
  6338. if (this._tooltip.options.sticky && e.originalEvent) {
  6339. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  6340. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  6341. latlng = this._map.layerPointToLatLng(layerPoint);
  6342. }
  6343. this._tooltip.setLatLng(latlng);
  6344. }
  6345. });
  6346. /*
  6347. * @class LayerGroup
  6348. * @aka L.LayerGroup
  6349. * @inherits Layer
  6350. *
  6351. * Used to group several layers and handle them as one. If you add it to the map,
  6352. * any layers added or removed from the group will be added/removed on the map as
  6353. * well. Extends `Layer`.
  6354. *
  6355. * @example
  6356. *
  6357. * ```js
  6358. * L.layerGroup([marker1, marker2])
  6359. * .addLayer(polyline)
  6360. * .addTo(map);
  6361. * ```
  6362. */
  6363. L.LayerGroup = L.Layer.extend({
  6364. initialize: function (layers) {
  6365. this._layers = {};
  6366. var i, len;
  6367. if (layers) {
  6368. for (i = 0, len = layers.length; i < len; i++) {
  6369. this.addLayer(layers[i]);
  6370. }
  6371. }
  6372. },
  6373. // @method addLayer(layer: Layer): this
  6374. // Adds the given layer to the group.
  6375. addLayer: function (layer) {
  6376. var id = this.getLayerId(layer);
  6377. this._layers[id] = layer;
  6378. if (this._map) {
  6379. this._map.addLayer(layer);
  6380. }
  6381. return this;
  6382. },
  6383. // @method removeLayer(layer: Layer): this
  6384. // Removes the given layer from the group.
  6385. // @alternative
  6386. // @method removeLayer(id: Number): this
  6387. // Removes the layer with the given internal ID from the group.
  6388. removeLayer: function (layer) {
  6389. var id = layer in this._layers ? layer : this.getLayerId(layer);
  6390. if (this._map && this._layers[id]) {
  6391. this._map.removeLayer(this._layers[id]);
  6392. }
  6393. delete this._layers[id];
  6394. return this;
  6395. },
  6396. // @method hasLayer(layer: Layer): Boolean
  6397. // Returns `true` if the given layer is currently added to the group.
  6398. hasLayer: function (layer) {
  6399. return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
  6400. },
  6401. // @method clearLayers(): this
  6402. // Removes all the layers from the group.
  6403. clearLayers: function () {
  6404. for (var i in this._layers) {
  6405. this.removeLayer(this._layers[i]);
  6406. }
  6407. return this;
  6408. },
  6409. // @method invoke(methodName: String, …): this
  6410. // Calls `methodName` on every layer contained in this group, passing any
  6411. // additional parameters. Has no effect if the layers contained do not
  6412. // implement `methodName`.
  6413. invoke: function (methodName) {
  6414. var args = Array.prototype.slice.call(arguments, 1),
  6415. i, layer;
  6416. for (i in this._layers) {
  6417. layer = this._layers[i];
  6418. if (layer[methodName]) {
  6419. layer[methodName].apply(layer, args);
  6420. }
  6421. }
  6422. return this;
  6423. },
  6424. onAdd: function (map) {
  6425. for (var i in this._layers) {
  6426. map.addLayer(this._layers[i]);
  6427. }
  6428. },
  6429. onRemove: function (map) {
  6430. for (var i in this._layers) {
  6431. map.removeLayer(this._layers[i]);
  6432. }
  6433. },
  6434. // @method eachLayer(fn: Function, context?: Object): this
  6435. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  6436. // ```js
  6437. // group.eachLayer(function (layer) {
  6438. // layer.bindPopup('Hello');
  6439. // });
  6440. // ```
  6441. eachLayer: function (method, context) {
  6442. for (var i in this._layers) {
  6443. method.call(context, this._layers[i]);
  6444. }
  6445. return this;
  6446. },
  6447. // @method getLayer(id: Number): Layer
  6448. // Returns the layer with the given internal ID.
  6449. getLayer: function (id) {
  6450. return this._layers[id];
  6451. },
  6452. // @method getLayers(): Layer[]
  6453. // Returns an array of all the layers added to the group.
  6454. getLayers: function () {
  6455. var layers = [];
  6456. for (var i in this._layers) {
  6457. layers.push(this._layers[i]);
  6458. }
  6459. return layers;
  6460. },
  6461. // @method setZIndex(zIndex: Number): this
  6462. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  6463. setZIndex: function (zIndex) {
  6464. return this.invoke('setZIndex', zIndex);
  6465. },
  6466. // @method getLayerId(layer: Layer): Number
  6467. // Returns the internal ID for a layer
  6468. getLayerId: function (layer) {
  6469. return L.stamp(layer);
  6470. }
  6471. });
  6472. // @factory L.layerGroup(layers: Layer[])
  6473. // Create a layer group, optionally given an initial set of layers.
  6474. L.layerGroup = function (layers) {
  6475. return new L.LayerGroup(layers);
  6476. };
  6477. /*
  6478. * @class FeatureGroup
  6479. * @aka L.FeatureGroup
  6480. * @inherits LayerGroup
  6481. *
  6482. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  6483. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  6484. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  6485. * handler, it will handle events from any of the layers. This includes mouse events
  6486. * and custom events.
  6487. * * Has `layeradd` and `layerremove` events
  6488. *
  6489. * @example
  6490. *
  6491. * ```js
  6492. * L.featureGroup([marker1, marker2, polyline])
  6493. * .bindPopup('Hello world!')
  6494. * .on('click', function() { alert('Clicked on a member of the group!'); })
  6495. * .addTo(map);
  6496. * ```
  6497. */
  6498. L.FeatureGroup = L.LayerGroup.extend({
  6499. addLayer: function (layer) {
  6500. if (this.hasLayer(layer)) {
  6501. return this;
  6502. }
  6503. layer.addEventParent(this);
  6504. L.LayerGroup.prototype.addLayer.call(this, layer);
  6505. // @event layeradd: LayerEvent
  6506. // Fired when a layer is added to this `FeatureGroup`
  6507. return this.fire('layeradd', {layer: layer});
  6508. },
  6509. removeLayer: function (layer) {
  6510. if (!this.hasLayer(layer)) {
  6511. return this;
  6512. }
  6513. if (layer in this._layers) {
  6514. layer = this._layers[layer];
  6515. }
  6516. layer.removeEventParent(this);
  6517. L.LayerGroup.prototype.removeLayer.call(this, layer);
  6518. // @event layerremove: LayerEvent
  6519. // Fired when a layer is removed from this `FeatureGroup`
  6520. return this.fire('layerremove', {layer: layer});
  6521. },
  6522. // @method setStyle(style: Path options): this
  6523. // Sets the given path options to each layer of the group that has a `setStyle` method.
  6524. setStyle: function (style) {
  6525. return this.invoke('setStyle', style);
  6526. },
  6527. // @method bringToFront(): this
  6528. // Brings the layer group to the top of all other layers
  6529. bringToFront: function () {
  6530. return this.invoke('bringToFront');
  6531. },
  6532. // @method bringToBack(): this
  6533. // Brings the layer group to the top of all other layers
  6534. bringToBack: function () {
  6535. return this.invoke('bringToBack');
  6536. },
  6537. // @method getBounds(): LatLngBounds
  6538. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  6539. getBounds: function () {
  6540. var bounds = new L.LatLngBounds();
  6541. for (var id in this._layers) {
  6542. var layer = this._layers[id];
  6543. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  6544. }
  6545. return bounds;
  6546. }
  6547. });
  6548. // @factory L.featureGroup(layers: Layer[])
  6549. // Create a feature group, optionally given an initial set of layers.
  6550. L.featureGroup = function (layers) {
  6551. return new L.FeatureGroup(layers);
  6552. };
  6553. /*
  6554. * @class Renderer
  6555. * @inherits Layer
  6556. * @aka L.Renderer
  6557. *
  6558. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  6559. * DOM container of the renderer, its bounds, and its zoom animation.
  6560. *
  6561. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  6562. * itself can be added or removed to the map. All paths use a renderer, which can
  6563. * be implicit (the map will decide the type of renderer and use it automatically)
  6564. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  6565. *
  6566. * Do not use this class directly, use `SVG` and `Canvas` instead.
  6567. *
  6568. * @event update: Event
  6569. * Fired when the renderer updates its bounds, center and zoom, for example when
  6570. * its map has moved
  6571. */
  6572. L.Renderer = L.Layer.extend({
  6573. // @section
  6574. // @aka Renderer options
  6575. options: {
  6576. // @option padding: Number = 0.1
  6577. // How much to extend the clip area around the map view (relative to its size)
  6578. // e.g. 0.1 would be 10% of map view in each direction
  6579. padding: 0.1
  6580. },
  6581. initialize: function (options) {
  6582. L.setOptions(this, options);
  6583. L.stamp(this);
  6584. this._layers = this._layers || {};
  6585. },
  6586. onAdd: function () {
  6587. if (!this._container) {
  6588. this._initContainer(); // defined by renderer implementations
  6589. if (this._zoomAnimated) {
  6590. L.DomUtil.addClass(this._container, 'leaflet-zoom-animated');
  6591. }
  6592. }
  6593. this.getPane().appendChild(this._container);
  6594. this._update();
  6595. this.on('update', this._updatePaths, this);
  6596. },
  6597. onRemove: function () {
  6598. L.DomUtil.remove(this._container);
  6599. this.off('update', this._updatePaths, this);
  6600. },
  6601. getEvents: function () {
  6602. var events = {
  6603. viewreset: this._reset,
  6604. zoom: this._onZoom,
  6605. moveend: this._update,
  6606. zoomend: this._onZoomEnd
  6607. };
  6608. if (this._zoomAnimated) {
  6609. events.zoomanim = this._onAnimZoom;
  6610. }
  6611. return events;
  6612. },
  6613. _onAnimZoom: function (ev) {
  6614. this._updateTransform(ev.center, ev.zoom);
  6615. },
  6616. _onZoom: function () {
  6617. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  6618. },
  6619. _updateTransform: function (center, zoom) {
  6620. var scale = this._map.getZoomScale(zoom, this._zoom),
  6621. position = L.DomUtil.getPosition(this._container),
  6622. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  6623. currentCenterPoint = this._map.project(this._center, zoom),
  6624. destCenterPoint = this._map.project(center, zoom),
  6625. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  6626. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  6627. if (L.Browser.any3d) {
  6628. L.DomUtil.setTransform(this._container, topLeftOffset, scale);
  6629. } else {
  6630. L.DomUtil.setPosition(this._container, topLeftOffset);
  6631. }
  6632. },
  6633. _reset: function () {
  6634. this._update();
  6635. this._updateTransform(this._center, this._zoom);
  6636. for (var id in this._layers) {
  6637. this._layers[id]._reset();
  6638. }
  6639. },
  6640. _onZoomEnd: function () {
  6641. for (var id in this._layers) {
  6642. this._layers[id]._project();
  6643. }
  6644. },
  6645. _updatePaths: function () {
  6646. for (var id in this._layers) {
  6647. this._layers[id]._update();
  6648. }
  6649. },
  6650. _update: function () {
  6651. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  6652. // Subclasses are responsible of firing the 'update' event.
  6653. var p = this.options.padding,
  6654. size = this._map.getSize(),
  6655. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  6656. this._bounds = new L.Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  6657. this._center = this._map.getCenter();
  6658. this._zoom = this._map.getZoom();
  6659. }
  6660. });
  6661. L.Map.include({
  6662. // @namespace Map; @method getRenderer(layer: Path): Renderer
  6663. // Returns the instance of `Renderer` that should be used to render the given
  6664. // `Path`. It will ensure that the `renderer` options of the map and paths
  6665. // are respected, and that the renderers do exist on the map.
  6666. getRenderer: function (layer) {
  6667. // @namespace Path; @option renderer: Renderer
  6668. // Use this specific instance of `Renderer` for this path. Takes
  6669. // precedence over the map's [default renderer](#map-renderer).
  6670. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  6671. if (!renderer) {
  6672. // @namespace Map; @option preferCanvas: Boolean = false
  6673. // Whether `Path`s should be rendered on a `Canvas` renderer.
  6674. // By default, all `Path`s are rendered in a `SVG` renderer.
  6675. renderer = this._renderer = (this.options.preferCanvas && L.canvas()) || L.svg();
  6676. }
  6677. if (!this.hasLayer(renderer)) {
  6678. this.addLayer(renderer);
  6679. }
  6680. return renderer;
  6681. },
  6682. _getPaneRenderer: function (name) {
  6683. if (name === 'overlayPane' || name === undefined) {
  6684. return false;
  6685. }
  6686. var renderer = this._paneRenderers[name];
  6687. if (renderer === undefined) {
  6688. renderer = (L.SVG && L.svg({pane: name})) || (L.Canvas && L.canvas({pane: name}));
  6689. this._paneRenderers[name] = renderer;
  6690. }
  6691. return renderer;
  6692. }
  6693. });
  6694. /*
  6695. * @class Path
  6696. * @aka L.Path
  6697. * @inherits Interactive layer
  6698. *
  6699. * An abstract class that contains options and constants shared between vector
  6700. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6701. */
  6702. L.Path = L.Layer.extend({
  6703. // @section
  6704. // @aka Path options
  6705. options: {
  6706. // @option stroke: Boolean = true
  6707. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6708. stroke: true,
  6709. // @option color: String = '#3388ff'
  6710. // Stroke color
  6711. color: '#3388ff',
  6712. // @option weight: Number = 3
  6713. // Stroke width in pixels
  6714. weight: 3,
  6715. // @option opacity: Number = 1.0
  6716. // Stroke opacity
  6717. opacity: 1,
  6718. // @option lineCap: String= 'round'
  6719. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6720. lineCap: 'round',
  6721. // @option lineJoin: String = 'round'
  6722. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6723. lineJoin: 'round',
  6724. // @option dashArray: String = null
  6725. // 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).
  6726. dashArray: null,
  6727. // @option dashOffset: String = null
  6728. // 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).
  6729. dashOffset: null,
  6730. // @option fill: Boolean = depends
  6731. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6732. fill: false,
  6733. // @option fillColor: String = *
  6734. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6735. fillColor: null,
  6736. // @option fillOpacity: Number = 0.2
  6737. // Fill opacity.
  6738. fillOpacity: 0.2,
  6739. // @option fillRule: String = 'evenodd'
  6740. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6741. fillRule: 'evenodd',
  6742. // className: '',
  6743. // Option inherited from "Interactive layer" abstract class
  6744. interactive: true
  6745. },
  6746. beforeAdd: function (map) {
  6747. // Renderer is set here because we need to call renderer.getEvents
  6748. // before this.getEvents.
  6749. this._renderer = map.getRenderer(this);
  6750. },
  6751. onAdd: function () {
  6752. this._renderer._initPath(this);
  6753. this._reset();
  6754. this._renderer._addPath(this);
  6755. },
  6756. onRemove: function () {
  6757. this._renderer._removePath(this);
  6758. },
  6759. // @method redraw(): this
  6760. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6761. redraw: function () {
  6762. if (this._map) {
  6763. this._renderer._updatePath(this);
  6764. }
  6765. return this;
  6766. },
  6767. // @method setStyle(style: Path options): this
  6768. // Changes the appearance of a Path based on the options in the `Path options` object.
  6769. setStyle: function (style) {
  6770. L.setOptions(this, style);
  6771. if (this._renderer) {
  6772. this._renderer._updateStyle(this);
  6773. }
  6774. return this;
  6775. },
  6776. // @method bringToFront(): this
  6777. // Brings the layer to the top of all path layers.
  6778. bringToFront: function () {
  6779. if (this._renderer) {
  6780. this._renderer._bringToFront(this);
  6781. }
  6782. return this;
  6783. },
  6784. // @method bringToBack(): this
  6785. // Brings the layer to the bottom of all path layers.
  6786. bringToBack: function () {
  6787. if (this._renderer) {
  6788. this._renderer._bringToBack(this);
  6789. }
  6790. return this;
  6791. },
  6792. getElement: function () {
  6793. return this._path;
  6794. },
  6795. _reset: function () {
  6796. // defined in children classes
  6797. this._project();
  6798. this._update();
  6799. },
  6800. _clickTolerance: function () {
  6801. // used when doing hit detection for Canvas layers
  6802. return (this.options.stroke ? this.options.weight / 2 : 0) + (L.Browser.touch ? 10 : 0);
  6803. }
  6804. });
  6805. /*
  6806. * @namespace LineUtil
  6807. *
  6808. * Various utility functions for polyine points processing, used by Leaflet internally to make polylines lightning-fast.
  6809. */
  6810. L.LineUtil = {
  6811. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  6812. // Improves rendering performance dramatically by lessening the number of points to draw.
  6813. // @function simplify(points: Point[], tolerance: Number): Point[]
  6814. // Dramatically reduces the number of points in a polyline while retaining
  6815. // its shape and returns a new array of simplified points, using the
  6816. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  6817. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  6818. // each zoom level and also reducing visual noise. tolerance affects the amount of
  6819. // simplification (lesser value means higher quality but slower and with more points).
  6820. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  6821. simplify: function (points, tolerance) {
  6822. if (!tolerance || !points.length) {
  6823. return points.slice();
  6824. }
  6825. var sqTolerance = tolerance * tolerance;
  6826. // stage 1: vertex reduction
  6827. points = this._reducePoints(points, sqTolerance);
  6828. // stage 2: Douglas-Peucker simplification
  6829. points = this._simplifyDP(points, sqTolerance);
  6830. return points;
  6831. },
  6832. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  6833. // Returns the distance between point `p` and segment `p1` to `p2`.
  6834. pointToSegmentDistance: function (p, p1, p2) {
  6835. return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
  6836. },
  6837. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  6838. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  6839. closestPointOnSegment: function (p, p1, p2) {
  6840. return this._sqClosestPointOnSegment(p, p1, p2);
  6841. },
  6842. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  6843. _simplifyDP: function (points, sqTolerance) {
  6844. var len = points.length,
  6845. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  6846. markers = new ArrayConstructor(len);
  6847. markers[0] = markers[len - 1] = 1;
  6848. this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  6849. var i,
  6850. newPoints = [];
  6851. for (i = 0; i < len; i++) {
  6852. if (markers[i]) {
  6853. newPoints.push(points[i]);
  6854. }
  6855. }
  6856. return newPoints;
  6857. },
  6858. _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
  6859. var maxSqDist = 0,
  6860. index, i, sqDist;
  6861. for (i = first + 1; i <= last - 1; i++) {
  6862. sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
  6863. if (sqDist > maxSqDist) {
  6864. index = i;
  6865. maxSqDist = sqDist;
  6866. }
  6867. }
  6868. if (maxSqDist > sqTolerance) {
  6869. markers[index] = 1;
  6870. this._simplifyDPStep(points, markers, sqTolerance, first, index);
  6871. this._simplifyDPStep(points, markers, sqTolerance, index, last);
  6872. }
  6873. },
  6874. // reduce points that are too close to each other to a single point
  6875. _reducePoints: function (points, sqTolerance) {
  6876. var reducedPoints = [points[0]];
  6877. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  6878. if (this._sqDist(points[i], points[prev]) > sqTolerance) {
  6879. reducedPoints.push(points[i]);
  6880. prev = i;
  6881. }
  6882. }
  6883. if (prev < len - 1) {
  6884. reducedPoints.push(points[len - 1]);
  6885. }
  6886. return reducedPoints;
  6887. },
  6888. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  6889. // Clips the segment a to b by rectangular bounds with the
  6890. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  6891. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  6892. // points that are on the screen or near, increasing performance.
  6893. clipSegment: function (a, b, bounds, useLastCode, round) {
  6894. var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
  6895. codeB = this._getBitCode(b, bounds),
  6896. codeOut, p, newCode;
  6897. // save 2nd code to avoid calculating it on the next segment
  6898. this._lastCode = codeB;
  6899. while (true) {
  6900. // if a,b is inside the clip window (trivial accept)
  6901. if (!(codeA | codeB)) {
  6902. return [a, b];
  6903. }
  6904. // if a,b is outside the clip window (trivial reject)
  6905. if (codeA & codeB) {
  6906. return false;
  6907. }
  6908. // other cases
  6909. codeOut = codeA || codeB;
  6910. p = this._getEdgeIntersection(a, b, codeOut, bounds, round);
  6911. newCode = this._getBitCode(p, bounds);
  6912. if (codeOut === codeA) {
  6913. a = p;
  6914. codeA = newCode;
  6915. } else {
  6916. b = p;
  6917. codeB = newCode;
  6918. }
  6919. }
  6920. },
  6921. _getEdgeIntersection: function (a, b, code, bounds, round) {
  6922. var dx = b.x - a.x,
  6923. dy = b.y - a.y,
  6924. min = bounds.min,
  6925. max = bounds.max,
  6926. x, y;
  6927. if (code & 8) { // top
  6928. x = a.x + dx * (max.y - a.y) / dy;
  6929. y = max.y;
  6930. } else if (code & 4) { // bottom
  6931. x = a.x + dx * (min.y - a.y) / dy;
  6932. y = min.y;
  6933. } else if (code & 2) { // right
  6934. x = max.x;
  6935. y = a.y + dy * (max.x - a.x) / dx;
  6936. } else if (code & 1) { // left
  6937. x = min.x;
  6938. y = a.y + dy * (min.x - a.x) / dx;
  6939. }
  6940. return new L.Point(x, y, round);
  6941. },
  6942. _getBitCode: function (p, bounds) {
  6943. var code = 0;
  6944. if (p.x < bounds.min.x) { // left
  6945. code |= 1;
  6946. } else if (p.x > bounds.max.x) { // right
  6947. code |= 2;
  6948. }
  6949. if (p.y < bounds.min.y) { // bottom
  6950. code |= 4;
  6951. } else if (p.y > bounds.max.y) { // top
  6952. code |= 8;
  6953. }
  6954. return code;
  6955. },
  6956. // square distance (to avoid unnecessary Math.sqrt calls)
  6957. _sqDist: function (p1, p2) {
  6958. var dx = p2.x - p1.x,
  6959. dy = p2.y - p1.y;
  6960. return dx * dx + dy * dy;
  6961. },
  6962. // return closest point on segment or distance to that point
  6963. _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
  6964. var x = p1.x,
  6965. y = p1.y,
  6966. dx = p2.x - x,
  6967. dy = p2.y - y,
  6968. dot = dx * dx + dy * dy,
  6969. t;
  6970. if (dot > 0) {
  6971. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  6972. if (t > 1) {
  6973. x = p2.x;
  6974. y = p2.y;
  6975. } else if (t > 0) {
  6976. x += dx * t;
  6977. y += dy * t;
  6978. }
  6979. }
  6980. dx = p.x - x;
  6981. dy = p.y - y;
  6982. return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
  6983. }
  6984. };
  6985. /*
  6986. * @class Polyline
  6987. * @aka L.Polyline
  6988. * @inherits Path
  6989. *
  6990. * A class for drawing polyline overlays on a map. Extends `Path`.
  6991. *
  6992. * @example
  6993. *
  6994. * ```js
  6995. * // create a red polyline from an array of LatLng points
  6996. * var latlngs = [
  6997. * [45.51, -122.68],
  6998. * [37.77, -122.43],
  6999. * [34.04, -118.2]
  7000. * ];
  7001. *
  7002. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  7003. *
  7004. * // zoom the map to the polyline
  7005. * map.fitBounds(polyline.getBounds());
  7006. * ```
  7007. *
  7008. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  7009. *
  7010. * ```js
  7011. * // create a red polyline from an array of arrays of LatLng points
  7012. * var latlngs = [
  7013. * [[45.51, -122.68],
  7014. * [37.77, -122.43],
  7015. * [34.04, -118.2]],
  7016. * [[40.78, -73.91],
  7017. * [41.83, -87.62],
  7018. * [32.76, -96.72]]
  7019. * ];
  7020. * ```
  7021. */
  7022. L.Polyline = L.Path.extend({
  7023. // @section
  7024. // @aka Polyline options
  7025. options: {
  7026. // @option smoothFactor: Number = 1.0
  7027. // How much to simplify the polyline on each zoom level. More means
  7028. // better performance and smoother look, and less means more accurate representation.
  7029. smoothFactor: 1.0,
  7030. // @option noClip: Boolean = false
  7031. // Disable polyline clipping.
  7032. noClip: false
  7033. },
  7034. initialize: function (latlngs, options) {
  7035. L.setOptions(this, options);
  7036. this._setLatLngs(latlngs);
  7037. },
  7038. // @method getLatLngs(): LatLng[]
  7039. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  7040. getLatLngs: function () {
  7041. return this._latlngs;
  7042. },
  7043. // @method setLatLngs(latlngs: LatLng[]): this
  7044. // Replaces all the points in the polyline with the given array of geographical points.
  7045. setLatLngs: function (latlngs) {
  7046. this._setLatLngs(latlngs);
  7047. return this.redraw();
  7048. },
  7049. // @method isEmpty(): Boolean
  7050. // Returns `true` if the Polyline has no LatLngs.
  7051. isEmpty: function () {
  7052. return !this._latlngs.length;
  7053. },
  7054. closestLayerPoint: function (p) {
  7055. var minDistance = Infinity,
  7056. minPoint = null,
  7057. closest = L.LineUtil._sqClosestPointOnSegment,
  7058. p1, p2;
  7059. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  7060. var points = this._parts[j];
  7061. for (var i = 1, len = points.length; i < len; i++) {
  7062. p1 = points[i - 1];
  7063. p2 = points[i];
  7064. var sqDist = closest(p, p1, p2, true);
  7065. if (sqDist < minDistance) {
  7066. minDistance = sqDist;
  7067. minPoint = closest(p, p1, p2);
  7068. }
  7069. }
  7070. }
  7071. if (minPoint) {
  7072. minPoint.distance = Math.sqrt(minDistance);
  7073. }
  7074. return minPoint;
  7075. },
  7076. // @method getCenter(): LatLng
  7077. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  7078. getCenter: function () {
  7079. // throws error when not yet added to map as this center calculation requires projected coordinates
  7080. if (!this._map) {
  7081. throw new Error('Must add layer to map before using getCenter()');
  7082. }
  7083. var i, halfDist, segDist, dist, p1, p2, ratio,
  7084. points = this._rings[0],
  7085. len = points.length;
  7086. if (!len) { return null; }
  7087. // polyline centroid algorithm; only uses the first ring if there are multiple
  7088. for (i = 0, halfDist = 0; i < len - 1; i++) {
  7089. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  7090. }
  7091. // The line is so small in the current view that all points are on the same pixel.
  7092. if (halfDist === 0) {
  7093. return this._map.layerPointToLatLng(points[0]);
  7094. }
  7095. for (i = 0, dist = 0; i < len - 1; i++) {
  7096. p1 = points[i];
  7097. p2 = points[i + 1];
  7098. segDist = p1.distanceTo(p2);
  7099. dist += segDist;
  7100. if (dist > halfDist) {
  7101. ratio = (dist - halfDist) / segDist;
  7102. return this._map.layerPointToLatLng([
  7103. p2.x - ratio * (p2.x - p1.x),
  7104. p2.y - ratio * (p2.y - p1.y)
  7105. ]);
  7106. }
  7107. }
  7108. },
  7109. // @method getBounds(): LatLngBounds
  7110. // Returns the `LatLngBounds` of the path.
  7111. getBounds: function () {
  7112. return this._bounds;
  7113. },
  7114. // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
  7115. // Adds a given point to the polyline. By default, adds to the first ring of
  7116. // the polyline in case of a multi-polyline, but can be overridden by passing
  7117. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  7118. addLatLng: function (latlng, latlngs) {
  7119. latlngs = latlngs || this._defaultShape();
  7120. latlng = L.latLng(latlng);
  7121. latlngs.push(latlng);
  7122. this._bounds.extend(latlng);
  7123. return this.redraw();
  7124. },
  7125. _setLatLngs: function (latlngs) {
  7126. this._bounds = new L.LatLngBounds();
  7127. this._latlngs = this._convertLatLngs(latlngs);
  7128. },
  7129. _defaultShape: function () {
  7130. return L.Polyline._flat(this._latlngs) ? this._latlngs : this._latlngs[0];
  7131. },
  7132. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  7133. _convertLatLngs: function (latlngs) {
  7134. var result = [],
  7135. flat = L.Polyline._flat(latlngs);
  7136. for (var i = 0, len = latlngs.length; i < len; i++) {
  7137. if (flat) {
  7138. result[i] = L.latLng(latlngs[i]);
  7139. this._bounds.extend(result[i]);
  7140. } else {
  7141. result[i] = this._convertLatLngs(latlngs[i]);
  7142. }
  7143. }
  7144. return result;
  7145. },
  7146. _project: function () {
  7147. var pxBounds = new L.Bounds();
  7148. this._rings = [];
  7149. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  7150. var w = this._clickTolerance(),
  7151. p = new L.Point(w, w);
  7152. if (this._bounds.isValid() && pxBounds.isValid()) {
  7153. pxBounds.min._subtract(p);
  7154. pxBounds.max._add(p);
  7155. this._pxBounds = pxBounds;
  7156. }
  7157. },
  7158. // recursively turns latlngs into a set of rings with projected coordinates
  7159. _projectLatlngs: function (latlngs, result, projectedBounds) {
  7160. var flat = latlngs[0] instanceof L.LatLng,
  7161. len = latlngs.length,
  7162. i, ring;
  7163. if (flat) {
  7164. ring = [];
  7165. for (i = 0; i < len; i++) {
  7166. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  7167. projectedBounds.extend(ring[i]);
  7168. }
  7169. result.push(ring);
  7170. } else {
  7171. for (i = 0; i < len; i++) {
  7172. this._projectLatlngs(latlngs[i], result, projectedBounds);
  7173. }
  7174. }
  7175. },
  7176. // clip polyline by renderer bounds so that we have less to render for performance
  7177. _clipPoints: function () {
  7178. var bounds = this._renderer._bounds;
  7179. this._parts = [];
  7180. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7181. return;
  7182. }
  7183. if (this.options.noClip) {
  7184. this._parts = this._rings;
  7185. return;
  7186. }
  7187. var parts = this._parts,
  7188. i, j, k, len, len2, segment, points;
  7189. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  7190. points = this._rings[i];
  7191. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  7192. segment = L.LineUtil.clipSegment(points[j], points[j + 1], bounds, j, true);
  7193. if (!segment) { continue; }
  7194. parts[k] = parts[k] || [];
  7195. parts[k].push(segment[0]);
  7196. // if segment goes out of screen, or it's the last one, it's the end of the line part
  7197. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  7198. parts[k].push(segment[1]);
  7199. k++;
  7200. }
  7201. }
  7202. }
  7203. },
  7204. // simplify each clipped part of the polyline for performance
  7205. _simplifyPoints: function () {
  7206. var parts = this._parts,
  7207. tolerance = this.options.smoothFactor;
  7208. for (var i = 0, len = parts.length; i < len; i++) {
  7209. parts[i] = L.LineUtil.simplify(parts[i], tolerance);
  7210. }
  7211. },
  7212. _update: function () {
  7213. if (!this._map) { return; }
  7214. this._clipPoints();
  7215. this._simplifyPoints();
  7216. this._updatePath();
  7217. },
  7218. _updatePath: function () {
  7219. this._renderer._updatePoly(this);
  7220. }
  7221. });
  7222. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  7223. // Instantiates a polyline object given an array of geographical points and
  7224. // optionally an options object. You can create a `Polyline` object with
  7225. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  7226. // of geographic points.
  7227. L.polyline = function (latlngs, options) {
  7228. return new L.Polyline(latlngs, options);
  7229. };
  7230. L.Polyline._flat = function (latlngs) {
  7231. // true if it's a flat array of latlngs; false if nested
  7232. return !L.Util.isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  7233. };
  7234. /*
  7235. * @namespace PolyUtil
  7236. * Various utility functions for polygon geometries.
  7237. */
  7238. L.PolyUtil = {};
  7239. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  7240. * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgeman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).
  7241. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  7242. * performance. Note that polygon points needs different algorithm for clipping
  7243. * than polyline, so there's a seperate method for it.
  7244. */
  7245. L.PolyUtil.clipPolygon = function (points, bounds, round) {
  7246. var clippedPoints,
  7247. edges = [1, 4, 2, 8],
  7248. i, j, k,
  7249. a, b,
  7250. len, edge, p,
  7251. lu = L.LineUtil;
  7252. for (i = 0, len = points.length; i < len; i++) {
  7253. points[i]._code = lu._getBitCode(points[i], bounds);
  7254. }
  7255. // for each edge (left, bottom, right, top)
  7256. for (k = 0; k < 4; k++) {
  7257. edge = edges[k];
  7258. clippedPoints = [];
  7259. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  7260. a = points[i];
  7261. b = points[j];
  7262. // if a is inside the clip window
  7263. if (!(a._code & edge)) {
  7264. // if b is outside the clip window (a->b goes out of screen)
  7265. if (b._code & edge) {
  7266. p = lu._getEdgeIntersection(b, a, edge, bounds, round);
  7267. p._code = lu._getBitCode(p, bounds);
  7268. clippedPoints.push(p);
  7269. }
  7270. clippedPoints.push(a);
  7271. // else if b is inside the clip window (a->b enters the screen)
  7272. } else if (!(b._code & edge)) {
  7273. p = lu._getEdgeIntersection(b, a, edge, bounds, round);
  7274. p._code = lu._getBitCode(p, bounds);
  7275. clippedPoints.push(p);
  7276. }
  7277. }
  7278. points = clippedPoints;
  7279. }
  7280. return points;
  7281. };
  7282. /*
  7283. * @class Polygon
  7284. * @aka L.Polygon
  7285. * @inherits Polyline
  7286. *
  7287. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  7288. *
  7289. * 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.
  7290. *
  7291. *
  7292. * @example
  7293. *
  7294. * ```js
  7295. * // create a red polygon from an array of LatLng points
  7296. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  7297. *
  7298. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  7299. *
  7300. * // zoom the map to the polygon
  7301. * map.fitBounds(polygon.getBounds());
  7302. * ```
  7303. *
  7304. * 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:
  7305. *
  7306. * ```js
  7307. * var latlngs = [
  7308. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7309. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7310. * ];
  7311. * ```
  7312. *
  7313. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  7314. *
  7315. * ```js
  7316. * var latlngs = [
  7317. * [ // first polygon
  7318. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7319. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7320. * ],
  7321. * [ // second polygon
  7322. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  7323. * ]
  7324. * ];
  7325. * ```
  7326. */
  7327. L.Polygon = L.Polyline.extend({
  7328. options: {
  7329. fill: true
  7330. },
  7331. isEmpty: function () {
  7332. return !this._latlngs.length || !this._latlngs[0].length;
  7333. },
  7334. getCenter: function () {
  7335. // throws error when not yet added to map as this center calculation requires projected coordinates
  7336. if (!this._map) {
  7337. throw new Error('Must add layer to map before using getCenter()');
  7338. }
  7339. var i, j, p1, p2, f, area, x, y, center,
  7340. points = this._rings[0],
  7341. len = points.length;
  7342. if (!len) { return null; }
  7343. // polygon centroid algorithm; only uses the first ring if there are multiple
  7344. area = x = y = 0;
  7345. for (i = 0, j = len - 1; i < len; j = i++) {
  7346. p1 = points[i];
  7347. p2 = points[j];
  7348. f = p1.y * p2.x - p2.y * p1.x;
  7349. x += (p1.x + p2.x) * f;
  7350. y += (p1.y + p2.y) * f;
  7351. area += f * 3;
  7352. }
  7353. if (area === 0) {
  7354. // Polygon is so small that all points are on same pixel.
  7355. center = points[0];
  7356. } else {
  7357. center = [x / area, y / area];
  7358. }
  7359. return this._map.layerPointToLatLng(center);
  7360. },
  7361. _convertLatLngs: function (latlngs) {
  7362. var result = L.Polyline.prototype._convertLatLngs.call(this, latlngs),
  7363. len = result.length;
  7364. // remove last point if it equals first one
  7365. if (len >= 2 && result[0] instanceof L.LatLng && result[0].equals(result[len - 1])) {
  7366. result.pop();
  7367. }
  7368. return result;
  7369. },
  7370. _setLatLngs: function (latlngs) {
  7371. L.Polyline.prototype._setLatLngs.call(this, latlngs);
  7372. if (L.Polyline._flat(this._latlngs)) {
  7373. this._latlngs = [this._latlngs];
  7374. }
  7375. },
  7376. _defaultShape: function () {
  7377. return L.Polyline._flat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  7378. },
  7379. _clipPoints: function () {
  7380. // polygons need a different clipping algorithm so we redefine that
  7381. var bounds = this._renderer._bounds,
  7382. w = this.options.weight,
  7383. p = new L.Point(w, w);
  7384. // increase clip padding by stroke width to avoid stroke on clip edges
  7385. bounds = new L.Bounds(bounds.min.subtract(p), bounds.max.add(p));
  7386. this._parts = [];
  7387. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7388. return;
  7389. }
  7390. if (this.options.noClip) {
  7391. this._parts = this._rings;
  7392. return;
  7393. }
  7394. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  7395. clipped = L.PolyUtil.clipPolygon(this._rings[i], bounds, true);
  7396. if (clipped.length) {
  7397. this._parts.push(clipped);
  7398. }
  7399. }
  7400. },
  7401. _updatePath: function () {
  7402. this._renderer._updatePoly(this, true);
  7403. }
  7404. });
  7405. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  7406. L.polygon = function (latlngs, options) {
  7407. return new L.Polygon(latlngs, options);
  7408. };
  7409. /*
  7410. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  7411. */
  7412. /*
  7413. * @class Rectangle
  7414. * @aka L.Retangle
  7415. * @inherits Polygon
  7416. *
  7417. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  7418. *
  7419. * @example
  7420. *
  7421. * ```js
  7422. * // define rectangle geographical bounds
  7423. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  7424. *
  7425. * // create an orange rectangle
  7426. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  7427. *
  7428. * // zoom the map to the rectangle bounds
  7429. * map.fitBounds(bounds);
  7430. * ```
  7431. *
  7432. */
  7433. L.Rectangle = L.Polygon.extend({
  7434. initialize: function (latLngBounds, options) {
  7435. L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  7436. },
  7437. // @method setBounds(latLngBounds: LatLngBounds): this
  7438. // Redraws the rectangle with the passed bounds.
  7439. setBounds: function (latLngBounds) {
  7440. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  7441. },
  7442. _boundsToLatLngs: function (latLngBounds) {
  7443. latLngBounds = L.latLngBounds(latLngBounds);
  7444. return [
  7445. latLngBounds.getSouthWest(),
  7446. latLngBounds.getNorthWest(),
  7447. latLngBounds.getNorthEast(),
  7448. latLngBounds.getSouthEast()
  7449. ];
  7450. }
  7451. });
  7452. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  7453. L.rectangle = function (latLngBounds, options) {
  7454. return new L.Rectangle(latLngBounds, options);
  7455. };
  7456. /*
  7457. * @class CircleMarker
  7458. * @aka L.CircleMarker
  7459. * @inherits Path
  7460. *
  7461. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  7462. */
  7463. L.CircleMarker = L.Path.extend({
  7464. // @section
  7465. // @aka CircleMarker options
  7466. options: {
  7467. fill: true,
  7468. // @option radius: Number = 10
  7469. // Radius of the circle marker, in pixels
  7470. radius: 10
  7471. },
  7472. initialize: function (latlng, options) {
  7473. L.setOptions(this, options);
  7474. this._latlng = L.latLng(latlng);
  7475. this._radius = this.options.radius;
  7476. },
  7477. // @method setLatLng(latLng: LatLng): this
  7478. // Sets the position of a circle marker to a new location.
  7479. setLatLng: function (latlng) {
  7480. this._latlng = L.latLng(latlng);
  7481. this.redraw();
  7482. return this.fire('move', {latlng: this._latlng});
  7483. },
  7484. // @method getLatLng(): LatLng
  7485. // Returns the current geographical position of the circle marker
  7486. getLatLng: function () {
  7487. return this._latlng;
  7488. },
  7489. // @method setRadius(radius: Number): this
  7490. // Sets the radius of a circle marker. Units are in pixels.
  7491. setRadius: function (radius) {
  7492. this.options.radius = this._radius = radius;
  7493. return this.redraw();
  7494. },
  7495. // @method getRadius(): Number
  7496. // Returns the current radius of the circle
  7497. getRadius: function () {
  7498. return this._radius;
  7499. },
  7500. setStyle : function (options) {
  7501. var radius = options && options.radius || this._radius;
  7502. L.Path.prototype.setStyle.call(this, options);
  7503. this.setRadius(radius);
  7504. return this;
  7505. },
  7506. _project: function () {
  7507. this._point = this._map.latLngToLayerPoint(this._latlng);
  7508. this._updateBounds();
  7509. },
  7510. _updateBounds: function () {
  7511. var r = this._radius,
  7512. r2 = this._radiusY || r,
  7513. w = this._clickTolerance(),
  7514. p = [r + w, r2 + w];
  7515. this._pxBounds = new L.Bounds(this._point.subtract(p), this._point.add(p));
  7516. },
  7517. _update: function () {
  7518. if (this._map) {
  7519. this._updatePath();
  7520. }
  7521. },
  7522. _updatePath: function () {
  7523. this._renderer._updateCircle(this);
  7524. },
  7525. _empty: function () {
  7526. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  7527. }
  7528. });
  7529. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  7530. // Instantiates a circle marker object given a geographical point, and an optional options object.
  7531. L.circleMarker = function (latlng, options) {
  7532. return new L.CircleMarker(latlng, options);
  7533. };
  7534. /*
  7535. * @class Circle
  7536. * @aka L.Circle
  7537. * @inherits CircleMarker
  7538. *
  7539. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  7540. *
  7541. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  7542. *
  7543. * @example
  7544. *
  7545. * ```js
  7546. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  7547. * ```
  7548. */
  7549. L.Circle = L.CircleMarker.extend({
  7550. initialize: function (latlng, options, legacyOptions) {
  7551. if (typeof options === 'number') {
  7552. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  7553. options = L.extend({}, legacyOptions, {radius: options});
  7554. }
  7555. L.setOptions(this, options);
  7556. this._latlng = L.latLng(latlng);
  7557. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  7558. // @section
  7559. // @aka Circle options
  7560. // @option radius: Number; Radius of the circle, in meters.
  7561. this._mRadius = this.options.radius;
  7562. },
  7563. // @method setRadius(radius: Number): this
  7564. // Sets the radius of a circle. Units are in meters.
  7565. setRadius: function (radius) {
  7566. this._mRadius = radius;
  7567. return this.redraw();
  7568. },
  7569. // @method getRadius(): Number
  7570. // Returns the current radius of a circle. Units are in meters.
  7571. getRadius: function () {
  7572. return this._mRadius;
  7573. },
  7574. // @method getBounds(): LatLngBounds
  7575. // Returns the `LatLngBounds` of the path.
  7576. getBounds: function () {
  7577. var half = [this._radius, this._radiusY || this._radius];
  7578. return new L.LatLngBounds(
  7579. this._map.layerPointToLatLng(this._point.subtract(half)),
  7580. this._map.layerPointToLatLng(this._point.add(half)));
  7581. },
  7582. setStyle: L.Path.prototype.setStyle,
  7583. _project: function () {
  7584. var lng = this._latlng.lng,
  7585. lat = this._latlng.lat,
  7586. map = this._map,
  7587. crs = map.options.crs;
  7588. if (crs.distance === L.CRS.Earth.distance) {
  7589. var d = Math.PI / 180,
  7590. latR = (this._mRadius / L.CRS.Earth.R) / d,
  7591. top = map.project([lat + latR, lng]),
  7592. bottom = map.project([lat - latR, lng]),
  7593. p = top.add(bottom).divideBy(2),
  7594. lat2 = map.unproject(p).lat,
  7595. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  7596. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  7597. if (isNaN(lngR) || lngR === 0) {
  7598. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  7599. }
  7600. this._point = p.subtract(map.getPixelOrigin());
  7601. this._radius = isNaN(lngR) ? 0 : Math.max(Math.round(p.x - map.project([lat2, lng - lngR]).x), 1);
  7602. this._radiusY = Math.max(Math.round(p.y - top.y), 1);
  7603. } else {
  7604. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  7605. this._point = map.latLngToLayerPoint(this._latlng);
  7606. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  7607. }
  7608. this._updateBounds();
  7609. }
  7610. });
  7611. // @factory L.circle(latlng: LatLng, options?: Circle options)
  7612. // Instantiates a circle object given a geographical point, and an options object
  7613. // which contains the circle radius.
  7614. // @alternative
  7615. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  7616. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  7617. // Do not use in new applications or plugins.
  7618. L.circle = function (latlng, options, legacyOptions) {
  7619. return new L.Circle(latlng, options, legacyOptions);
  7620. };
  7621. /*
  7622. * @class SVG
  7623. * @inherits Renderer
  7624. * @aka L.SVG
  7625. *
  7626. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  7627. * Inherits `Renderer`.
  7628. *
  7629. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  7630. * available in all web browsers, notably Android 2.x and 3.x.
  7631. *
  7632. * Although SVG is not available on IE7 and IE8, these browsers support
  7633. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  7634. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  7635. * this case.
  7636. *
  7637. * @example
  7638. *
  7639. * Use SVG by default for all paths in the map:
  7640. *
  7641. * ```js
  7642. * var map = L.map('map', {
  7643. * renderer: L.svg()
  7644. * });
  7645. * ```
  7646. *
  7647. * Use a SVG renderer with extra padding for specific vector geometries:
  7648. *
  7649. * ```js
  7650. * var map = L.map('map');
  7651. * var myRenderer = L.svg({ padding: 0.5 });
  7652. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  7653. * var circle = L.circle( center, { renderer: myRenderer } );
  7654. * ```
  7655. */
  7656. L.SVG = L.Renderer.extend({
  7657. getEvents: function () {
  7658. var events = L.Renderer.prototype.getEvents.call(this);
  7659. events.zoomstart = this._onZoomStart;
  7660. return events;
  7661. },
  7662. _initContainer: function () {
  7663. this._container = L.SVG.create('svg');
  7664. // makes it possible to click through svg root; we'll reset it back in individual paths
  7665. this._container.setAttribute('pointer-events', 'none');
  7666. this._rootGroup = L.SVG.create('g');
  7667. this._container.appendChild(this._rootGroup);
  7668. },
  7669. _onZoomStart: function () {
  7670. // Drag-then-pinch interactions might mess up the center and zoom.
  7671. // In this case, the easiest way to prevent this is re-do the renderer
  7672. // bounds and padding when the zooming starts.
  7673. this._update();
  7674. },
  7675. _update: function () {
  7676. if (this._map._animatingZoom && this._bounds) { return; }
  7677. L.Renderer.prototype._update.call(this);
  7678. var b = this._bounds,
  7679. size = b.getSize(),
  7680. container = this._container;
  7681. // set size of svg-container if changed
  7682. if (!this._svgSize || !this._svgSize.equals(size)) {
  7683. this._svgSize = size;
  7684. container.setAttribute('width', size.x);
  7685. container.setAttribute('height', size.y);
  7686. }
  7687. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  7688. L.DomUtil.setPosition(container, b.min);
  7689. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  7690. this.fire('update');
  7691. },
  7692. // methods below are called by vector layers implementations
  7693. _initPath: function (layer) {
  7694. var path = layer._path = L.SVG.create('path');
  7695. // @namespace Path
  7696. // @option className: String = null
  7697. // Custom class name set on an element. Only for SVG renderer.
  7698. if (layer.options.className) {
  7699. L.DomUtil.addClass(path, layer.options.className);
  7700. }
  7701. if (layer.options.interactive) {
  7702. L.DomUtil.addClass(path, 'leaflet-interactive');
  7703. }
  7704. this._updateStyle(layer);
  7705. this._layers[L.stamp(layer)] = layer;
  7706. },
  7707. _addPath: function (layer) {
  7708. this._rootGroup.appendChild(layer._path);
  7709. layer.addInteractiveTarget(layer._path);
  7710. },
  7711. _removePath: function (layer) {
  7712. L.DomUtil.remove(layer._path);
  7713. layer.removeInteractiveTarget(layer._path);
  7714. delete this._layers[L.stamp(layer)];
  7715. },
  7716. _updatePath: function (layer) {
  7717. layer._project();
  7718. layer._update();
  7719. },
  7720. _updateStyle: function (layer) {
  7721. var path = layer._path,
  7722. options = layer.options;
  7723. if (!path) { return; }
  7724. if (options.stroke) {
  7725. path.setAttribute('stroke', options.color);
  7726. path.setAttribute('stroke-opacity', options.opacity);
  7727. path.setAttribute('stroke-width', options.weight);
  7728. path.setAttribute('stroke-linecap', options.lineCap);
  7729. path.setAttribute('stroke-linejoin', options.lineJoin);
  7730. if (options.dashArray) {
  7731. path.setAttribute('stroke-dasharray', options.dashArray);
  7732. } else {
  7733. path.removeAttribute('stroke-dasharray');
  7734. }
  7735. if (options.dashOffset) {
  7736. path.setAttribute('stroke-dashoffset', options.dashOffset);
  7737. } else {
  7738. path.removeAttribute('stroke-dashoffset');
  7739. }
  7740. } else {
  7741. path.setAttribute('stroke', 'none');
  7742. }
  7743. if (options.fill) {
  7744. path.setAttribute('fill', options.fillColor || options.color);
  7745. path.setAttribute('fill-opacity', options.fillOpacity);
  7746. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  7747. } else {
  7748. path.setAttribute('fill', 'none');
  7749. }
  7750. },
  7751. _updatePoly: function (layer, closed) {
  7752. this._setPath(layer, L.SVG.pointsToPath(layer._parts, closed));
  7753. },
  7754. _updateCircle: function (layer) {
  7755. var p = layer._point,
  7756. r = layer._radius,
  7757. r2 = layer._radiusY || r,
  7758. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  7759. // drawing a circle with two half-arcs
  7760. var d = layer._empty() ? 'M0 0' :
  7761. 'M' + (p.x - r) + ',' + p.y +
  7762. arc + (r * 2) + ',0 ' +
  7763. arc + (-r * 2) + ',0 ';
  7764. this._setPath(layer, d);
  7765. },
  7766. _setPath: function (layer, path) {
  7767. layer._path.setAttribute('d', path);
  7768. },
  7769. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  7770. _bringToFront: function (layer) {
  7771. L.DomUtil.toFront(layer._path);
  7772. },
  7773. _bringToBack: function (layer) {
  7774. L.DomUtil.toBack(layer._path);
  7775. }
  7776. });
  7777. // @namespace SVG; @section
  7778. // There are several static functions which can be called without instantiating L.SVG:
  7779. L.extend(L.SVG, {
  7780. // @function create(name: String): SVGElement
  7781. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  7782. // corresponding to the class name passed. For example, using 'line' will return
  7783. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  7784. create: function (name) {
  7785. return document.createElementNS('http://www.w3.org/2000/svg', name);
  7786. },
  7787. // @function pointsToPath(rings: Point[], closed: Boolean): String
  7788. // Generates a SVG path string for multiple rings, with each ring turning
  7789. // into "M..L..L.." instructions
  7790. pointsToPath: function (rings, closed) {
  7791. var str = '',
  7792. i, j, len, len2, points, p;
  7793. for (i = 0, len = rings.length; i < len; i++) {
  7794. points = rings[i];
  7795. for (j = 0, len2 = points.length; j < len2; j++) {
  7796. p = points[j];
  7797. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  7798. }
  7799. // closes the ring for polygons; "x" is VML syntax
  7800. str += closed ? (L.Browser.svg ? 'z' : 'x') : '';
  7801. }
  7802. // SVG complains about empty path strings
  7803. return str || 'M0 0';
  7804. }
  7805. });
  7806. // @namespace Browser; @property svg: Boolean
  7807. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  7808. L.Browser.svg = !!(document.createElementNS && L.SVG.create('svg').createSVGRect);
  7809. // @namespace SVG
  7810. // @factory L.svg(options?: Renderer options)
  7811. // Creates a SVG renderer with the given options.
  7812. L.svg = function (options) {
  7813. return L.Browser.svg || L.Browser.vml ? new L.SVG(options) : null;
  7814. };
  7815. /*
  7816. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  7817. */
  7818. /*
  7819. * @class SVG
  7820. *
  7821. * Although SVG is not available on IE7 and IE8, these browsers support [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language), and the SVG renderer will fall back to VML in this case.
  7822. *
  7823. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  7824. * with old versions of Internet Explorer.
  7825. */
  7826. // @namespace Browser; @property vml: Boolean
  7827. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  7828. L.Browser.vml = !L.Browser.svg && (function () {
  7829. try {
  7830. var div = document.createElement('div');
  7831. div.innerHTML = '<v:shape adj="1"/>';
  7832. var shape = div.firstChild;
  7833. shape.style.behavior = 'url(#default#VML)';
  7834. return shape && (typeof shape.adj === 'object');
  7835. } catch (e) {
  7836. return false;
  7837. }
  7838. }());
  7839. // redefine some SVG methods to handle VML syntax which is similar but with some differences
  7840. L.SVG.include(!L.Browser.vml ? {} : {
  7841. _initContainer: function () {
  7842. this._container = L.DomUtil.create('div', 'leaflet-vml-container');
  7843. },
  7844. _update: function () {
  7845. if (this._map._animatingZoom) { return; }
  7846. L.Renderer.prototype._update.call(this);
  7847. this.fire('update');
  7848. },
  7849. _initPath: function (layer) {
  7850. var container = layer._container = L.SVG.create('shape');
  7851. L.DomUtil.addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  7852. container.coordsize = '1 1';
  7853. layer._path = L.SVG.create('path');
  7854. container.appendChild(layer._path);
  7855. this._updateStyle(layer);
  7856. this._layers[L.stamp(layer)] = layer;
  7857. },
  7858. _addPath: function (layer) {
  7859. var container = layer._container;
  7860. this._container.appendChild(container);
  7861. if (layer.options.interactive) {
  7862. layer.addInteractiveTarget(container);
  7863. }
  7864. },
  7865. _removePath: function (layer) {
  7866. var container = layer._container;
  7867. L.DomUtil.remove(container);
  7868. layer.removeInteractiveTarget(container);
  7869. delete this._layers[L.stamp(layer)];
  7870. },
  7871. _updateStyle: function (layer) {
  7872. var stroke = layer._stroke,
  7873. fill = layer._fill,
  7874. options = layer.options,
  7875. container = layer._container;
  7876. container.stroked = !!options.stroke;
  7877. container.filled = !!options.fill;
  7878. if (options.stroke) {
  7879. if (!stroke) {
  7880. stroke = layer._stroke = L.SVG.create('stroke');
  7881. }
  7882. container.appendChild(stroke);
  7883. stroke.weight = options.weight + 'px';
  7884. stroke.color = options.color;
  7885. stroke.opacity = options.opacity;
  7886. if (options.dashArray) {
  7887. stroke.dashStyle = L.Util.isArray(options.dashArray) ?
  7888. options.dashArray.join(' ') :
  7889. options.dashArray.replace(/( *, *)/g, ' ');
  7890. } else {
  7891. stroke.dashStyle = '';
  7892. }
  7893. stroke.endcap = options.lineCap.replace('butt', 'flat');
  7894. stroke.joinstyle = options.lineJoin;
  7895. } else if (stroke) {
  7896. container.removeChild(stroke);
  7897. layer._stroke = null;
  7898. }
  7899. if (options.fill) {
  7900. if (!fill) {
  7901. fill = layer._fill = L.SVG.create('fill');
  7902. }
  7903. container.appendChild(fill);
  7904. fill.color = options.fillColor || options.color;
  7905. fill.opacity = options.fillOpacity;
  7906. } else if (fill) {
  7907. container.removeChild(fill);
  7908. layer._fill = null;
  7909. }
  7910. },
  7911. _updateCircle: function (layer) {
  7912. var p = layer._point.round(),
  7913. r = Math.round(layer._radius),
  7914. r2 = Math.round(layer._radiusY || r);
  7915. this._setPath(layer, layer._empty() ? 'M0 0' :
  7916. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  7917. },
  7918. _setPath: function (layer, path) {
  7919. layer._path.v = path;
  7920. },
  7921. _bringToFront: function (layer) {
  7922. L.DomUtil.toFront(layer._container);
  7923. },
  7924. _bringToBack: function (layer) {
  7925. L.DomUtil.toBack(layer._container);
  7926. }
  7927. });
  7928. if (L.Browser.vml) {
  7929. L.SVG.create = (function () {
  7930. try {
  7931. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  7932. return function (name) {
  7933. return document.createElement('<lvml:' + name + ' class="lvml">');
  7934. };
  7935. } catch (e) {
  7936. return function (name) {
  7937. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  7938. };
  7939. }
  7940. })();
  7941. }
  7942. /*
  7943. * @class Canvas
  7944. * @inherits Renderer
  7945. * @aka L.Canvas
  7946. *
  7947. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  7948. * Inherits `Renderer`.
  7949. *
  7950. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  7951. * available in all web browsers, notably IE8, and overlapping geometries might
  7952. * not display properly in some edge cases.
  7953. *
  7954. * @example
  7955. *
  7956. * Use Canvas by default for all paths in the map:
  7957. *
  7958. * ```js
  7959. * var map = L.map('map', {
  7960. * renderer: L.canvas()
  7961. * });
  7962. * ```
  7963. *
  7964. * Use a Canvas renderer with extra padding for specific vector geometries:
  7965. *
  7966. * ```js
  7967. * var map = L.map('map');
  7968. * var myRenderer = L.canvas({ padding: 0.5 });
  7969. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  7970. * var circle = L.circle( center, { renderer: myRenderer } );
  7971. * ```
  7972. */
  7973. L.Canvas = L.Renderer.extend({
  7974. getEvents: function () {
  7975. var events = L.Renderer.prototype.getEvents.call(this);
  7976. events.viewprereset = this._onViewPreReset;
  7977. return events;
  7978. },
  7979. _onViewPreReset: function () {
  7980. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  7981. this._postponeUpdatePaths = true;
  7982. },
  7983. onAdd: function () {
  7984. L.Renderer.prototype.onAdd.call(this);
  7985. // Redraw vectors since canvas is cleared upon removal,
  7986. // in case of removing the renderer itself from the map.
  7987. this._draw();
  7988. },
  7989. _initContainer: function () {
  7990. var container = this._container = document.createElement('canvas');
  7991. L.DomEvent
  7992. .on(container, 'mousemove', L.Util.throttle(this._onMouseMove, 32, this), this)
  7993. .on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this)
  7994. .on(container, 'mouseout', this._handleMouseOut, this);
  7995. this._ctx = container.getContext('2d');
  7996. },
  7997. _updatePaths: function () {
  7998. if (this._postponeUpdatePaths) { return; }
  7999. var layer;
  8000. this._redrawBounds = null;
  8001. for (var id in this._layers) {
  8002. layer = this._layers[id];
  8003. layer._update();
  8004. }
  8005. this._redraw();
  8006. },
  8007. _update: function () {
  8008. if (this._map._animatingZoom && this._bounds) { return; }
  8009. this._drawnLayers = {};
  8010. L.Renderer.prototype._update.call(this);
  8011. var b = this._bounds,
  8012. container = this._container,
  8013. size = b.getSize(),
  8014. m = L.Browser.retina ? 2 : 1;
  8015. L.DomUtil.setPosition(container, b.min);
  8016. // set canvas size (also clearing it); use double size on retina
  8017. container.width = m * size.x;
  8018. container.height = m * size.y;
  8019. container.style.width = size.x + 'px';
  8020. container.style.height = size.y + 'px';
  8021. if (L.Browser.retina) {
  8022. this._ctx.scale(2, 2);
  8023. }
  8024. // translate so we use the same path coordinates after canvas element moves
  8025. this._ctx.translate(-b.min.x, -b.min.y);
  8026. // Tell paths to redraw themselves
  8027. this.fire('update');
  8028. },
  8029. _reset: function () {
  8030. L.Renderer.prototype._reset.call(this);
  8031. if (this._postponeUpdatePaths) {
  8032. this._postponeUpdatePaths = false;
  8033. this._updatePaths();
  8034. }
  8035. },
  8036. _initPath: function (layer) {
  8037. this._updateDashArray(layer);
  8038. this._layers[L.stamp(layer)] = layer;
  8039. var order = layer._order = {
  8040. layer: layer,
  8041. prev: this._drawLast,
  8042. next: null
  8043. };
  8044. if (this._drawLast) { this._drawLast.next = order; }
  8045. this._drawLast = order;
  8046. this._drawFirst = this._drawFirst || this._drawLast;
  8047. },
  8048. _addPath: function (layer) {
  8049. this._requestRedraw(layer);
  8050. },
  8051. _removePath: function (layer) {
  8052. var order = layer._order;
  8053. var next = order.next;
  8054. var prev = order.prev;
  8055. if (next) {
  8056. next.prev = prev;
  8057. } else {
  8058. this._drawLast = prev;
  8059. }
  8060. if (prev) {
  8061. prev.next = next;
  8062. } else {
  8063. this._drawFirst = next;
  8064. }
  8065. delete layer._order;
  8066. delete this._layers[L.stamp(layer)];
  8067. this._requestRedraw(layer);
  8068. },
  8069. _updatePath: function (layer) {
  8070. // Redraw the union of the layer's old pixel
  8071. // bounds and the new pixel bounds.
  8072. this._extendRedrawBounds(layer);
  8073. layer._project();
  8074. layer._update();
  8075. // The redraw will extend the redraw bounds
  8076. // with the new pixel bounds.
  8077. this._requestRedraw(layer);
  8078. },
  8079. _updateStyle: function (layer) {
  8080. this._updateDashArray(layer);
  8081. this._requestRedraw(layer);
  8082. },
  8083. _updateDashArray: function (layer) {
  8084. if (layer.options.dashArray) {
  8085. var parts = layer.options.dashArray.split(','),
  8086. dashArray = [],
  8087. i;
  8088. for (i = 0; i < parts.length; i++) {
  8089. dashArray.push(Number(parts[i]));
  8090. }
  8091. layer.options._dashArray = dashArray;
  8092. }
  8093. },
  8094. _requestRedraw: function (layer) {
  8095. if (!this._map) { return; }
  8096. this._extendRedrawBounds(layer);
  8097. this._redrawRequest = this._redrawRequest || L.Util.requestAnimFrame(this._redraw, this);
  8098. },
  8099. _extendRedrawBounds: function (layer) {
  8100. var padding = (layer.options.weight || 0) + 1;
  8101. this._redrawBounds = this._redrawBounds || new L.Bounds();
  8102. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  8103. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  8104. },
  8105. _redraw: function () {
  8106. this._redrawRequest = null;
  8107. if (this._redrawBounds) {
  8108. this._redrawBounds.min._floor();
  8109. this._redrawBounds.max._ceil();
  8110. }
  8111. this._clear(); // clear layers in redraw bounds
  8112. this._draw(); // draw layers
  8113. this._redrawBounds = null;
  8114. },
  8115. _clear: function () {
  8116. var bounds = this._redrawBounds;
  8117. if (bounds) {
  8118. var size = bounds.getSize();
  8119. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  8120. } else {
  8121. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  8122. }
  8123. },
  8124. _draw: function () {
  8125. var layer, bounds = this._redrawBounds;
  8126. this._ctx.save();
  8127. if (bounds) {
  8128. var size = bounds.getSize();
  8129. this._ctx.beginPath();
  8130. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  8131. this._ctx.clip();
  8132. }
  8133. this._drawing = true;
  8134. for (var order = this._drawFirst; order; order = order.next) {
  8135. layer = order.layer;
  8136. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  8137. layer._updatePath();
  8138. }
  8139. }
  8140. this._drawing = false;
  8141. this._ctx.restore(); // Restore state before clipping.
  8142. },
  8143. _updatePoly: function (layer, closed) {
  8144. if (!this._drawing) { return; }
  8145. var i, j, len2, p,
  8146. parts = layer._parts,
  8147. len = parts.length,
  8148. ctx = this._ctx;
  8149. if (!len) { return; }
  8150. this._drawnLayers[layer._leaflet_id] = layer;
  8151. ctx.beginPath();
  8152. if (ctx.setLineDash) {
  8153. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  8154. }
  8155. for (i = 0; i < len; i++) {
  8156. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  8157. p = parts[i][j];
  8158. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  8159. }
  8160. if (closed) {
  8161. ctx.closePath();
  8162. }
  8163. }
  8164. this._fillStroke(ctx, layer);
  8165. },
  8166. _updateCircle: function (layer) {
  8167. if (!this._drawing || layer._empty()) { return; }
  8168. var p = layer._point,
  8169. ctx = this._ctx,
  8170. r = layer._radius,
  8171. s = (layer._radiusY || r) / r;
  8172. this._drawnLayers[layer._leaflet_id] = layer;
  8173. if (s !== 1) {
  8174. ctx.save();
  8175. ctx.scale(1, s);
  8176. }
  8177. ctx.beginPath();
  8178. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  8179. if (s !== 1) {
  8180. ctx.restore();
  8181. }
  8182. this._fillStroke(ctx, layer);
  8183. },
  8184. _fillStroke: function (ctx, layer) {
  8185. var options = layer.options;
  8186. if (options.fill) {
  8187. ctx.globalAlpha = options.fillOpacity;
  8188. ctx.fillStyle = options.fillColor || options.color;
  8189. ctx.fill(options.fillRule || 'evenodd');
  8190. }
  8191. if (options.stroke && options.weight !== 0) {
  8192. ctx.globalAlpha = options.opacity;
  8193. ctx.lineWidth = options.weight;
  8194. ctx.strokeStyle = options.color;
  8195. ctx.lineCap = options.lineCap;
  8196. ctx.lineJoin = options.lineJoin;
  8197. ctx.stroke();
  8198. }
  8199. },
  8200. // Canvas obviously doesn't have mouse events for individual drawn objects,
  8201. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  8202. _onClick: function (e) {
  8203. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  8204. for (var order = this._drawFirst; order; order = order.next) {
  8205. layer = order.layer;
  8206. if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
  8207. clickedLayer = layer;
  8208. }
  8209. }
  8210. if (clickedLayer) {
  8211. L.DomEvent._fakeStop(e);
  8212. this._fireEvent([clickedLayer], e);
  8213. }
  8214. },
  8215. _onMouseMove: function (e) {
  8216. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  8217. var point = this._map.mouseEventToLayerPoint(e);
  8218. this._handleMouseHover(e, point);
  8219. },
  8220. _handleMouseOut: function (e) {
  8221. var layer = this._hoveredLayer;
  8222. if (layer) {
  8223. // if we're leaving the layer, fire mouseout
  8224. L.DomUtil.removeClass(this._container, 'leaflet-interactive');
  8225. this._fireEvent([layer], e, 'mouseout');
  8226. this._hoveredLayer = null;
  8227. }
  8228. },
  8229. _handleMouseHover: function (e, point) {
  8230. var layer, candidateHoveredLayer;
  8231. for (var order = this._drawFirst; order; order = order.next) {
  8232. layer = order.layer;
  8233. if (layer.options.interactive && layer._containsPoint(point)) {
  8234. candidateHoveredLayer = layer;
  8235. }
  8236. }
  8237. if (candidateHoveredLayer !== this._hoveredLayer) {
  8238. this._handleMouseOut(e);
  8239. if (candidateHoveredLayer) {
  8240. L.DomUtil.addClass(this._container, 'leaflet-interactive'); // change cursor
  8241. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  8242. this._hoveredLayer = candidateHoveredLayer;
  8243. }
  8244. }
  8245. if (this._hoveredLayer) {
  8246. this._fireEvent([this._hoveredLayer], e);
  8247. }
  8248. },
  8249. _fireEvent: function (layers, e, type) {
  8250. this._map._fireDOMEvent(e, type || e.type, layers);
  8251. },
  8252. _bringToFront: function (layer) {
  8253. var order = layer._order;
  8254. var next = order.next;
  8255. var prev = order.prev;
  8256. if (next) {
  8257. next.prev = prev;
  8258. } else {
  8259. // Already last
  8260. return;
  8261. }
  8262. if (prev) {
  8263. prev.next = next;
  8264. } else if (next) {
  8265. // Update first entry unless this is the
  8266. // signle entry
  8267. this._drawFirst = next;
  8268. }
  8269. order.prev = this._drawLast;
  8270. this._drawLast.next = order;
  8271. order.next = null;
  8272. this._drawLast = order;
  8273. this._requestRedraw(layer);
  8274. },
  8275. _bringToBack: function (layer) {
  8276. var order = layer._order;
  8277. var next = order.next;
  8278. var prev = order.prev;
  8279. if (prev) {
  8280. prev.next = next;
  8281. } else {
  8282. // Already first
  8283. return;
  8284. }
  8285. if (next) {
  8286. next.prev = prev;
  8287. } else if (prev) {
  8288. // Update last entry unless this is the
  8289. // signle entry
  8290. this._drawLast = prev;
  8291. }
  8292. order.prev = null;
  8293. order.next = this._drawFirst;
  8294. this._drawFirst.prev = order;
  8295. this._drawFirst = order;
  8296. this._requestRedraw(layer);
  8297. }
  8298. });
  8299. // @namespace Browser; @property canvas: Boolean
  8300. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  8301. L.Browser.canvas = (function () {
  8302. return !!document.createElement('canvas').getContext;
  8303. }());
  8304. // @namespace Canvas
  8305. // @factory L.canvas(options?: Renderer options)
  8306. // Creates a Canvas renderer with the given options.
  8307. L.canvas = function (options) {
  8308. return L.Browser.canvas ? new L.Canvas(options) : null;
  8309. };
  8310. L.Polyline.prototype._containsPoint = function (p, closed) {
  8311. var i, j, k, len, len2, part,
  8312. w = this._clickTolerance();
  8313. if (!this._pxBounds.contains(p)) { return false; }
  8314. // hit detection for polylines
  8315. for (i = 0, len = this._parts.length; i < len; i++) {
  8316. part = this._parts[i];
  8317. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  8318. if (!closed && (j === 0)) { continue; }
  8319. if (L.LineUtil.pointToSegmentDistance(p, part[k], part[j]) <= w) {
  8320. return true;
  8321. }
  8322. }
  8323. }
  8324. return false;
  8325. };
  8326. L.Polygon.prototype._containsPoint = function (p) {
  8327. var inside = false,
  8328. part, p1, p2, i, j, k, len, len2;
  8329. if (!this._pxBounds.contains(p)) { return false; }
  8330. // ray casting algorithm for detecting if point is in polygon
  8331. for (i = 0, len = this._parts.length; i < len; i++) {
  8332. part = this._parts[i];
  8333. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  8334. p1 = part[j];
  8335. p2 = part[k];
  8336. 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)) {
  8337. inside = !inside;
  8338. }
  8339. }
  8340. }
  8341. // also check if it's on polygon stroke
  8342. return inside || L.Polyline.prototype._containsPoint.call(this, p, true);
  8343. };
  8344. L.CircleMarker.prototype._containsPoint = function (p) {
  8345. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  8346. };
  8347. /*
  8348. * @class GeoJSON
  8349. * @aka L.GeoJSON
  8350. * @inherits FeatureGroup
  8351. *
  8352. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  8353. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  8354. *
  8355. * @example
  8356. *
  8357. * ```js
  8358. * L.geoJSON(data, {
  8359. * style: function (feature) {
  8360. * return {color: feature.properties.color};
  8361. * }
  8362. * }).bindPopup(function (layer) {
  8363. * return layer.feature.properties.description;
  8364. * }).addTo(map);
  8365. * ```
  8366. */
  8367. L.GeoJSON = L.FeatureGroup.extend({
  8368. /* @section
  8369. * @aka GeoJSON options
  8370. *
  8371. * @option pointToLayer: Function = *
  8372. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  8373. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  8374. * The default is to spawn a default `Marker`:
  8375. * ```js
  8376. * function(geoJsonPoint, latlng) {
  8377. * return L.marker(latlng);
  8378. * }
  8379. * ```
  8380. *
  8381. * @option style: Function = *
  8382. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  8383. * called internally when data is added.
  8384. * The default value is to not override any defaults:
  8385. * ```js
  8386. * function (geoJsonFeature) {
  8387. * return {}
  8388. * }
  8389. * ```
  8390. *
  8391. * @option onEachFeature: Function = *
  8392. * A `Function` that will be called once for each created `Feature`, after it has
  8393. * been created and styled. Useful for attaching events and popups to features.
  8394. * The default is to do nothing with the newly created layers:
  8395. * ```js
  8396. * function (feature, layer) {}
  8397. * ```
  8398. *
  8399. * @option filter: Function = *
  8400. * A `Function` that will be used to decide whether to include a feature or not.
  8401. * The default is to include all features:
  8402. * ```js
  8403. * function (geoJsonFeature) {
  8404. * return true;
  8405. * }
  8406. * ```
  8407. * Note: dynamically changing the `filter` option will have effect only on newly
  8408. * added data. It will _not_ re-evaluate already included features.
  8409. *
  8410. * @option coordsToLatLng: Function = *
  8411. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  8412. * The default is the `coordsToLatLng` static method.
  8413. */
  8414. initialize: function (geojson, options) {
  8415. L.setOptions(this, options);
  8416. this._layers = {};
  8417. if (geojson) {
  8418. this.addData(geojson);
  8419. }
  8420. },
  8421. // @method addData( <GeoJSON> data ): this
  8422. // Adds a GeoJSON object to the layer.
  8423. addData: function (geojson) {
  8424. var features = L.Util.isArray(geojson) ? geojson : geojson.features,
  8425. i, len, feature;
  8426. if (features) {
  8427. for (i = 0, len = features.length; i < len; i++) {
  8428. // only add this if geometry or geometries are set and not null
  8429. feature = features[i];
  8430. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  8431. this.addData(feature);
  8432. }
  8433. }
  8434. return this;
  8435. }
  8436. var options = this.options;
  8437. if (options.filter && !options.filter(geojson)) { return this; }
  8438. var layer = L.GeoJSON.geometryToLayer(geojson, options);
  8439. if (!layer) {
  8440. return this;
  8441. }
  8442. layer.feature = L.GeoJSON.asFeature(geojson);
  8443. layer.defaultOptions = layer.options;
  8444. this.resetStyle(layer);
  8445. if (options.onEachFeature) {
  8446. options.onEachFeature(geojson, layer);
  8447. }
  8448. return this.addLayer(layer);
  8449. },
  8450. // @method resetStyle( <Path> layer ): this
  8451. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  8452. resetStyle: function (layer) {
  8453. // reset any custom styles
  8454. layer.options = L.Util.extend({}, layer.defaultOptions);
  8455. this._setLayerStyle(layer, this.options.style);
  8456. return this;
  8457. },
  8458. // @method setStyle( <Function> style ): this
  8459. // Changes styles of GeoJSON vector layers with the given style function.
  8460. setStyle: function (style) {
  8461. return this.eachLayer(function (layer) {
  8462. this._setLayerStyle(layer, style);
  8463. }, this);
  8464. },
  8465. _setLayerStyle: function (layer, style) {
  8466. if (typeof style === 'function') {
  8467. style = style(layer.feature);
  8468. }
  8469. if (layer.setStyle) {
  8470. layer.setStyle(style);
  8471. }
  8472. }
  8473. });
  8474. // @section
  8475. // There are several static functions which can be called without instantiating L.GeoJSON:
  8476. L.extend(L.GeoJSON, {
  8477. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  8478. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  8479. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  8480. // functions if provided as options.
  8481. geometryToLayer: function (geojson, options) {
  8482. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  8483. coords = geometry ? geometry.coordinates : null,
  8484. layers = [],
  8485. pointToLayer = options && options.pointToLayer,
  8486. coordsToLatLng = options && options.coordsToLatLng || this.coordsToLatLng,
  8487. latlng, latlngs, i, len;
  8488. if (!coords && !geometry) {
  8489. return null;
  8490. }
  8491. switch (geometry.type) {
  8492. case 'Point':
  8493. latlng = coordsToLatLng(coords);
  8494. return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
  8495. case 'MultiPoint':
  8496. for (i = 0, len = coords.length; i < len; i++) {
  8497. latlng = coordsToLatLng(coords[i]);
  8498. layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng));
  8499. }
  8500. return new L.FeatureGroup(layers);
  8501. case 'LineString':
  8502. case 'MultiLineString':
  8503. latlngs = this.coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, coordsToLatLng);
  8504. return new L.Polyline(latlngs, options);
  8505. case 'Polygon':
  8506. case 'MultiPolygon':
  8507. latlngs = this.coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, coordsToLatLng);
  8508. return new L.Polygon(latlngs, options);
  8509. case 'GeometryCollection':
  8510. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  8511. var layer = this.geometryToLayer({
  8512. geometry: geometry.geometries[i],
  8513. type: 'Feature',
  8514. properties: geojson.properties
  8515. }, options);
  8516. if (layer) {
  8517. layers.push(layer);
  8518. }
  8519. }
  8520. return new L.FeatureGroup(layers);
  8521. default:
  8522. throw new Error('Invalid GeoJSON object.');
  8523. }
  8524. },
  8525. // @function coordsToLatLng(coords: Array): LatLng
  8526. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  8527. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  8528. coordsToLatLng: function (coords) {
  8529. return new L.LatLng(coords[1], coords[0], coords[2]);
  8530. },
  8531. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  8532. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  8533. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  8534. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  8535. coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) {
  8536. var latlngs = [];
  8537. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  8538. latlng = levelsDeep ?
  8539. this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
  8540. (coordsToLatLng || this.coordsToLatLng)(coords[i]);
  8541. latlngs.push(latlng);
  8542. }
  8543. return latlngs;
  8544. },
  8545. // @function latLngToCoords(latlng: LatLng): Array
  8546. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  8547. latLngToCoords: function (latlng) {
  8548. return latlng.alt !== undefined ?
  8549. [latlng.lng, latlng.lat, latlng.alt] :
  8550. [latlng.lng, latlng.lat];
  8551. },
  8552. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  8553. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  8554. // `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.
  8555. latLngsToCoords: function (latlngs, levelsDeep, closed) {
  8556. var coords = [];
  8557. for (var i = 0, len = latlngs.length; i < len; i++) {
  8558. coords.push(levelsDeep ?
  8559. L.GeoJSON.latLngsToCoords(latlngs[i], levelsDeep - 1, closed) :
  8560. L.GeoJSON.latLngToCoords(latlngs[i]));
  8561. }
  8562. if (!levelsDeep && closed) {
  8563. coords.push(coords[0]);
  8564. }
  8565. return coords;
  8566. },
  8567. getFeature: function (layer, newGeometry) {
  8568. return layer.feature ?
  8569. L.extend({}, layer.feature, {geometry: newGeometry}) :
  8570. L.GeoJSON.asFeature(newGeometry);
  8571. },
  8572. // @function asFeature(geojson: Object): Object
  8573. // Normalize GeoJSON geometries/features into GeoJSON features.
  8574. asFeature: function (geojson) {
  8575. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  8576. return geojson;
  8577. }
  8578. return {
  8579. type: 'Feature',
  8580. properties: {},
  8581. geometry: geojson
  8582. };
  8583. }
  8584. });
  8585. var PointToGeoJSON = {
  8586. toGeoJSON: function () {
  8587. return L.GeoJSON.getFeature(this, {
  8588. type: 'Point',
  8589. coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
  8590. });
  8591. }
  8592. };
  8593. // @namespace Marker
  8594. // @method toGeoJSON(): Object
  8595. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  8596. L.Marker.include(PointToGeoJSON);
  8597. // @namespace CircleMarker
  8598. // @method toGeoJSON(): Object
  8599. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  8600. L.Circle.include(PointToGeoJSON);
  8601. L.CircleMarker.include(PointToGeoJSON);
  8602. // @namespace Polyline
  8603. // @method toGeoJSON(): Object
  8604. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  8605. L.Polyline.prototype.toGeoJSON = function () {
  8606. var multi = !L.Polyline._flat(this._latlngs);
  8607. var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 1 : 0);
  8608. return L.GeoJSON.getFeature(this, {
  8609. type: (multi ? 'Multi' : '') + 'LineString',
  8610. coordinates: coords
  8611. });
  8612. };
  8613. // @namespace Polygon
  8614. // @method toGeoJSON(): Object
  8615. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  8616. L.Polygon.prototype.toGeoJSON = function () {
  8617. var holes = !L.Polyline._flat(this._latlngs),
  8618. multi = holes && !L.Polyline._flat(this._latlngs[0]);
  8619. var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true);
  8620. if (!holes) {
  8621. coords = [coords];
  8622. }
  8623. return L.GeoJSON.getFeature(this, {
  8624. type: (multi ? 'Multi' : '') + 'Polygon',
  8625. coordinates: coords
  8626. });
  8627. };
  8628. // @namespace LayerGroup
  8629. L.LayerGroup.include({
  8630. toMultiPoint: function () {
  8631. var coords = [];
  8632. this.eachLayer(function (layer) {
  8633. coords.push(layer.toGeoJSON().geometry.coordinates);
  8634. });
  8635. return L.GeoJSON.getFeature(this, {
  8636. type: 'MultiPoint',
  8637. coordinates: coords
  8638. });
  8639. },
  8640. // @method toGeoJSON(): Object
  8641. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `GeometryCollection`).
  8642. toGeoJSON: function () {
  8643. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  8644. if (type === 'MultiPoint') {
  8645. return this.toMultiPoint();
  8646. }
  8647. var isGeometryCollection = type === 'GeometryCollection',
  8648. jsons = [];
  8649. this.eachLayer(function (layer) {
  8650. if (layer.toGeoJSON) {
  8651. var json = layer.toGeoJSON();
  8652. jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json));
  8653. }
  8654. });
  8655. if (isGeometryCollection) {
  8656. return L.GeoJSON.getFeature(this, {
  8657. geometries: jsons,
  8658. type: 'GeometryCollection'
  8659. });
  8660. }
  8661. return {
  8662. type: 'FeatureCollection',
  8663. features: jsons
  8664. };
  8665. }
  8666. });
  8667. // @namespace GeoJSON
  8668. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  8669. // Creates a GeoJSON layer. Optionally accepts an object in
  8670. // [GeoJSON format](http://geojson.org/geojson-spec.html) to display on the map
  8671. // (you can alternatively add it later with `addData` method) and an `options` object.
  8672. L.geoJSON = function (geojson, options) {
  8673. return new L.GeoJSON(geojson, options);
  8674. };
  8675. // Backward compatibility.
  8676. L.geoJson = L.geoJSON;
  8677. /*
  8678. * @class Draggable
  8679. * @aka L.Draggable
  8680. * @inherits Evented
  8681. *
  8682. * A class for making DOM elements draggable (including touch support).
  8683. * Used internally for map and marker dragging. Only works for elements
  8684. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  8685. *
  8686. * @example
  8687. * ```js
  8688. * var draggable = new L.Draggable(elementToDrag);
  8689. * draggable.enable();
  8690. * ```
  8691. */
  8692. L.Draggable = L.Evented.extend({
  8693. options: {
  8694. // @option clickTolerance: Number = 3
  8695. // The max number of pixels a user can shift the mouse pointer during a click
  8696. // for it to be considered a valid click (as opposed to a mouse drag).
  8697. clickTolerance: 3
  8698. },
  8699. statics: {
  8700. START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
  8701. END: {
  8702. mousedown: 'mouseup',
  8703. touchstart: 'touchend',
  8704. pointerdown: 'touchend',
  8705. MSPointerDown: 'touchend'
  8706. },
  8707. MOVE: {
  8708. mousedown: 'mousemove',
  8709. touchstart: 'touchmove',
  8710. pointerdown: 'touchmove',
  8711. MSPointerDown: 'touchmove'
  8712. }
  8713. },
  8714. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline: Boolean)
  8715. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  8716. initialize: function (element, dragStartTarget, preventOutline) {
  8717. this._element = element;
  8718. this._dragStartTarget = dragStartTarget || element;
  8719. this._preventOutline = preventOutline;
  8720. },
  8721. // @method enable()
  8722. // Enables the dragging ability
  8723. enable: function () {
  8724. if (this._enabled) { return; }
  8725. L.DomEvent.on(this._dragStartTarget, L.Draggable.START.join(' '), this._onDown, this);
  8726. this._enabled = true;
  8727. },
  8728. // @method disable()
  8729. // Disables the dragging ability
  8730. disable: function () {
  8731. if (!this._enabled) { return; }
  8732. // If we're currently dragging this draggable,
  8733. // disabling it counts as first ending the drag.
  8734. if (L.Draggable._dragging === this) {
  8735. this.finishDrag();
  8736. }
  8737. L.DomEvent.off(this._dragStartTarget, L.Draggable.START.join(' '), this._onDown, this);
  8738. this._enabled = false;
  8739. this._moved = false;
  8740. },
  8741. _onDown: function (e) {
  8742. // Ignore simulated events, since we handle both touch and
  8743. // mouse explicitly; otherwise we risk getting duplicates of
  8744. // touch events, see #4315.
  8745. // Also ignore the event if disabled; this happens in IE11
  8746. // under some circumstances, see #3666.
  8747. if (e._simulated || !this._enabled) { return; }
  8748. this._moved = false;
  8749. if (L.DomUtil.hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  8750. if (L.Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  8751. L.Draggable._dragging = this; // Prevent dragging multiple objects at once.
  8752. if (this._preventOutline) {
  8753. L.DomUtil.preventOutline(this._element);
  8754. }
  8755. L.DomUtil.disableImageDrag();
  8756. L.DomUtil.disableTextSelection();
  8757. if (this._moving) { return; }
  8758. // @event down: Event
  8759. // Fired when a drag is about to start.
  8760. this.fire('down');
  8761. var first = e.touches ? e.touches[0] : e;
  8762. this._startPoint = new L.Point(first.clientX, first.clientY);
  8763. L.DomEvent
  8764. .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
  8765. .on(document, L.Draggable.END[e.type], this._onUp, this);
  8766. },
  8767. _onMove: function (e) {
  8768. // Ignore simulated events, since we handle both touch and
  8769. // mouse explicitly; otherwise we risk getting duplicates of
  8770. // touch events, see #4315.
  8771. // Also ignore the event if disabled; this happens in IE11
  8772. // under some circumstances, see #3666.
  8773. if (e._simulated || !this._enabled) { return; }
  8774. if (e.touches && e.touches.length > 1) {
  8775. this._moved = true;
  8776. return;
  8777. }
  8778. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  8779. newPoint = new L.Point(first.clientX, first.clientY),
  8780. offset = newPoint.subtract(this._startPoint);
  8781. if (!offset.x && !offset.y) { return; }
  8782. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  8783. L.DomEvent.preventDefault(e);
  8784. if (!this._moved) {
  8785. // @event dragstart: Event
  8786. // Fired when a drag starts
  8787. this.fire('dragstart');
  8788. this._moved = true;
  8789. this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
  8790. L.DomUtil.addClass(document.body, 'leaflet-dragging');
  8791. this._lastTarget = e.target || e.srcElement;
  8792. // IE and Edge do not give the <use> element, so fetch it
  8793. // if necessary
  8794. if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
  8795. this._lastTarget = this._lastTarget.correspondingUseElement;
  8796. }
  8797. L.DomUtil.addClass(this._lastTarget, 'leaflet-drag-target');
  8798. }
  8799. this._newPos = this._startPos.add(offset);
  8800. this._moving = true;
  8801. L.Util.cancelAnimFrame(this._animRequest);
  8802. this._lastEvent = e;
  8803. this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true);
  8804. },
  8805. _updatePosition: function () {
  8806. var e = {originalEvent: this._lastEvent};
  8807. // @event predrag: Event
  8808. // Fired continuously during dragging *before* each corresponding
  8809. // update of the element's position.
  8810. this.fire('predrag', e);
  8811. L.DomUtil.setPosition(this._element, this._newPos);
  8812. // @event drag: Event
  8813. // Fired continuously during dragging.
  8814. this.fire('drag', e);
  8815. },
  8816. _onUp: function (e) {
  8817. // Ignore simulated events, since we handle both touch and
  8818. // mouse explicitly; otherwise we risk getting duplicates of
  8819. // touch events, see #4315.
  8820. // Also ignore the event if disabled; this happens in IE11
  8821. // under some circumstances, see #3666.
  8822. if (e._simulated || !this._enabled) { return; }
  8823. this.finishDrag();
  8824. },
  8825. finishDrag: function () {
  8826. L.DomUtil.removeClass(document.body, 'leaflet-dragging');
  8827. if (this._lastTarget) {
  8828. L.DomUtil.removeClass(this._lastTarget, 'leaflet-drag-target');
  8829. this._lastTarget = null;
  8830. }
  8831. for (var i in L.Draggable.MOVE) {
  8832. L.DomEvent
  8833. .off(document, L.Draggable.MOVE[i], this._onMove, this)
  8834. .off(document, L.Draggable.END[i], this._onUp, this);
  8835. }
  8836. L.DomUtil.enableImageDrag();
  8837. L.DomUtil.enableTextSelection();
  8838. if (this._moved && this._moving) {
  8839. // ensure drag is not fired after dragend
  8840. L.Util.cancelAnimFrame(this._animRequest);
  8841. // @event dragend: DragEndEvent
  8842. // Fired when the drag ends.
  8843. this.fire('dragend', {
  8844. distance: this._newPos.distanceTo(this._startPos)
  8845. });
  8846. }
  8847. this._moving = false;
  8848. L.Draggable._dragging = false;
  8849. }
  8850. });
  8851. /*
  8852. L.Handler is a base class for handler classes that are used internally to inject
  8853. interaction features like dragging to classes like Map and Marker.
  8854. */
  8855. // @class Handler
  8856. // @aka L.Handler
  8857. // Abstract class for map interaction handlers
  8858. L.Handler = L.Class.extend({
  8859. initialize: function (map) {
  8860. this._map = map;
  8861. },
  8862. // @method enable(): this
  8863. // Enables the handler
  8864. enable: function () {
  8865. if (this._enabled) { return this; }
  8866. this._enabled = true;
  8867. this.addHooks();
  8868. return this;
  8869. },
  8870. // @method disable(): this
  8871. // Disables the handler
  8872. disable: function () {
  8873. if (!this._enabled) { return this; }
  8874. this._enabled = false;
  8875. this.removeHooks();
  8876. return this;
  8877. },
  8878. // @method enabled(): Boolean
  8879. // Returns `true` if the handler is enabled
  8880. enabled: function () {
  8881. return !!this._enabled;
  8882. }
  8883. // @section Extension methods
  8884. // Classes inheriting from `Handler` must implement the two following methods:
  8885. // @method addHooks()
  8886. // Called when the handler is enabled, should add event hooks.
  8887. // @method removeHooks()
  8888. // Called when the handler is disabled, should remove the event hooks added previously.
  8889. });
  8890. /*
  8891. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  8892. */
  8893. // @namespace Map
  8894. // @section Interaction Options
  8895. L.Map.mergeOptions({
  8896. // @option dragging: Boolean = true
  8897. // Whether the map be draggable with mouse/touch or not.
  8898. dragging: true,
  8899. // @section Panning Inertia Options
  8900. // @option inertia: Boolean = *
  8901. // If enabled, panning of the map will have an inertia effect where
  8902. // the map builds momentum while dragging and continues moving in
  8903. // the same direction for some time. Feels especially nice on touch
  8904. // devices. Enabled by default unless running on old Android devices.
  8905. inertia: !L.Browser.android23,
  8906. // @option inertiaDeceleration: Number = 3000
  8907. // The rate with which the inertial movement slows down, in pixels/second².
  8908. inertiaDeceleration: 3400, // px/s^2
  8909. // @option inertiaMaxSpeed: Number = Infinity
  8910. // Max speed of the inertial movement, in pixels/second.
  8911. inertiaMaxSpeed: Infinity, // px/s
  8912. // @option easeLinearity: Number = 0.2
  8913. easeLinearity: 0.2,
  8914. // @option worldCopyJump: Boolean = false
  8915. // With this option enabled, the map tracks when you pan to another "copy"
  8916. // of the world and seamlessly jumps to the original one so that all overlays
  8917. // like markers and vector layers are still visible.
  8918. worldCopyJump: false,
  8919. // @option maxBoundsViscosity: Number = 0.0
  8920. // If `maxBounds` is set, this option will control how solid the bounds
  8921. // are when dragging the map around. The default value of `0.0` allows the
  8922. // user to drag outside the bounds at normal speed, higher values will
  8923. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  8924. // solid, preventing the user from dragging outside the bounds.
  8925. maxBoundsViscosity: 0.0
  8926. });
  8927. L.Map.Drag = L.Handler.extend({
  8928. addHooks: function () {
  8929. if (!this._draggable) {
  8930. var map = this._map;
  8931. this._draggable = new L.Draggable(map._mapPane, map._container);
  8932. this._draggable.on({
  8933. down: this._onDown,
  8934. dragstart: this._onDragStart,
  8935. drag: this._onDrag,
  8936. dragend: this._onDragEnd
  8937. }, this);
  8938. this._draggable.on('predrag', this._onPreDragLimit, this);
  8939. if (map.options.worldCopyJump) {
  8940. this._draggable.on('predrag', this._onPreDragWrap, this);
  8941. map.on('zoomend', this._onZoomEnd, this);
  8942. map.whenReady(this._onZoomEnd, this);
  8943. }
  8944. }
  8945. L.DomUtil.addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  8946. this._draggable.enable();
  8947. this._positions = [];
  8948. this._times = [];
  8949. },
  8950. removeHooks: function () {
  8951. L.DomUtil.removeClass(this._map._container, 'leaflet-grab');
  8952. L.DomUtil.removeClass(this._map._container, 'leaflet-touch-drag');
  8953. this._draggable.disable();
  8954. },
  8955. moved: function () {
  8956. return this._draggable && this._draggable._moved;
  8957. },
  8958. moving: function () {
  8959. return this._draggable && this._draggable._moving;
  8960. },
  8961. _onDown: function () {
  8962. this._map._stop();
  8963. },
  8964. _onDragStart: function () {
  8965. var map = this._map;
  8966. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  8967. var bounds = L.latLngBounds(this._map.options.maxBounds);
  8968. this._offsetLimit = L.bounds(
  8969. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  8970. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  8971. .add(this._map.getSize()));
  8972. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  8973. } else {
  8974. this._offsetLimit = null;
  8975. }
  8976. map
  8977. .fire('movestart')
  8978. .fire('dragstart');
  8979. if (map.options.inertia) {
  8980. this._positions = [];
  8981. this._times = [];
  8982. }
  8983. },
  8984. _onDrag: function (e) {
  8985. if (this._map.options.inertia) {
  8986. var time = this._lastTime = +new Date(),
  8987. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  8988. this._positions.push(pos);
  8989. this._times.push(time);
  8990. if (time - this._times[0] > 50) {
  8991. this._positions.shift();
  8992. this._times.shift();
  8993. }
  8994. }
  8995. this._map
  8996. .fire('move', e)
  8997. .fire('drag', e);
  8998. },
  8999. _onZoomEnd: function () {
  9000. var pxCenter = this._map.getSize().divideBy(2),
  9001. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  9002. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  9003. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  9004. },
  9005. _viscousLimit: function (value, threshold) {
  9006. return value - (value - threshold) * this._viscosity;
  9007. },
  9008. _onPreDragLimit: function () {
  9009. if (!this._viscosity || !this._offsetLimit) { return; }
  9010. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  9011. var limit = this._offsetLimit;
  9012. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  9013. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  9014. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  9015. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  9016. this._draggable._newPos = this._draggable._startPos.add(offset);
  9017. },
  9018. _onPreDragWrap: function () {
  9019. var worldWidth = this._worldWidth,
  9020. halfWidth = Math.round(worldWidth / 2),
  9021. dx = this._initialWorldOffset,
  9022. x = this._draggable._newPos.x,
  9023. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  9024. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  9025. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  9026. this._draggable._absPos = this._draggable._newPos.clone();
  9027. this._draggable._newPos.x = newX;
  9028. },
  9029. _onDragEnd: function (e) {
  9030. var map = this._map,
  9031. options = map.options,
  9032. noInertia = !options.inertia || this._times.length < 2;
  9033. map.fire('dragend', e);
  9034. if (noInertia) {
  9035. map.fire('moveend');
  9036. } else {
  9037. var direction = this._lastPos.subtract(this._positions[0]),
  9038. duration = (this._lastTime - this._times[0]) / 1000,
  9039. ease = options.easeLinearity,
  9040. speedVector = direction.multiplyBy(ease / duration),
  9041. speed = speedVector.distanceTo([0, 0]),
  9042. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  9043. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  9044. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  9045. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  9046. if (!offset.x && !offset.y) {
  9047. map.fire('moveend');
  9048. } else {
  9049. offset = map._limitOffset(offset, map.options.maxBounds);
  9050. L.Util.requestAnimFrame(function () {
  9051. map.panBy(offset, {
  9052. duration: decelerationDuration,
  9053. easeLinearity: ease,
  9054. noMoveStart: true,
  9055. animate: true
  9056. });
  9057. });
  9058. }
  9059. }
  9060. }
  9061. });
  9062. // @section Handlers
  9063. // @property dragging: Handler
  9064. // Map dragging handler (by both mouse and touch).
  9065. L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
  9066. /*
  9067. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  9068. */
  9069. // @namespace Map
  9070. // @section Interaction Options
  9071. L.Map.mergeOptions({
  9072. // @option doubleClickZoom: Boolean|String = true
  9073. // Whether the map can be zoomed in by double clicking on it and
  9074. // zoomed out by double clicking while holding shift. If passed
  9075. // `'center'`, double-click zoom will zoom to the center of the
  9076. // view regardless of where the mouse was.
  9077. doubleClickZoom: true
  9078. });
  9079. L.Map.DoubleClickZoom = L.Handler.extend({
  9080. addHooks: function () {
  9081. this._map.on('dblclick', this._onDoubleClick, this);
  9082. },
  9083. removeHooks: function () {
  9084. this._map.off('dblclick', this._onDoubleClick, this);
  9085. },
  9086. _onDoubleClick: function (e) {
  9087. var map = this._map,
  9088. oldZoom = map.getZoom(),
  9089. delta = map.options.zoomDelta,
  9090. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  9091. if (map.options.doubleClickZoom === 'center') {
  9092. map.setZoom(zoom);
  9093. } else {
  9094. map.setZoomAround(e.containerPoint, zoom);
  9095. }
  9096. }
  9097. });
  9098. // @section Handlers
  9099. //
  9100. // Map properties include interaction handlers that allow you to control
  9101. // interaction behavior in runtime, enabling or disabling certain features such
  9102. // as dragging or touch zoom (see `Handler` methods). For example:
  9103. //
  9104. // ```js
  9105. // map.doubleClickZoom.disable();
  9106. // ```
  9107. //
  9108. // @property doubleClickZoom: Handler
  9109. // Double click zoom handler.
  9110. L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
  9111. /*
  9112. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  9113. */
  9114. // @namespace Map
  9115. // @section Interaction Options
  9116. L.Map.mergeOptions({
  9117. // @section Mousewheel options
  9118. // @option scrollWheelZoom: Boolean|String = true
  9119. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  9120. // it will zoom to the center of the view regardless of where the mouse was.
  9121. scrollWheelZoom: true,
  9122. // @option wheelDebounceTime: Number = 40
  9123. // Limits the rate at which a wheel can fire (in milliseconds). By default
  9124. // user can't zoom via wheel more often than once per 40 ms.
  9125. wheelDebounceTime: 40,
  9126. // @option wheelPxPerZoomLevel: Number = 60
  9127. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  9128. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  9129. // faster (and vice versa).
  9130. wheelPxPerZoomLevel: 60
  9131. });
  9132. L.Map.ScrollWheelZoom = L.Handler.extend({
  9133. addHooks: function () {
  9134. L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  9135. this._delta = 0;
  9136. },
  9137. removeHooks: function () {
  9138. L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll, this);
  9139. },
  9140. _onWheelScroll: function (e) {
  9141. var delta = L.DomEvent.getWheelDelta(e);
  9142. var debounce = this._map.options.wheelDebounceTime;
  9143. this._delta += delta;
  9144. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  9145. if (!this._startTime) {
  9146. this._startTime = +new Date();
  9147. }
  9148. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  9149. clearTimeout(this._timer);
  9150. this._timer = setTimeout(L.bind(this._performZoom, this), left);
  9151. L.DomEvent.stop(e);
  9152. },
  9153. _performZoom: function () {
  9154. var map = this._map,
  9155. zoom = map.getZoom(),
  9156. snap = this._map.options.zoomSnap || 0;
  9157. map._stop(); // stop panning and fly animations if any
  9158. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  9159. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  9160. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  9161. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  9162. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  9163. this._delta = 0;
  9164. this._startTime = null;
  9165. if (!delta) { return; }
  9166. if (map.options.scrollWheelZoom === 'center') {
  9167. map.setZoom(zoom + delta);
  9168. } else {
  9169. map.setZoomAround(this._lastMousePos, zoom + delta);
  9170. }
  9171. }
  9172. });
  9173. // @section Handlers
  9174. // @property scrollWheelZoom: Handler
  9175. // Scroll wheel zoom handler.
  9176. L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
  9177. /*
  9178. * Extends the event handling code with double tap support for mobile browsers.
  9179. */
  9180. L.extend(L.DomEvent, {
  9181. _touchstart: L.Browser.msPointer ? 'MSPointerDown' : L.Browser.pointer ? 'pointerdown' : 'touchstart',
  9182. _touchend: L.Browser.msPointer ? 'MSPointerUp' : L.Browser.pointer ? 'pointerup' : 'touchend',
  9183. // inspired by Zepto touch code by Thomas Fuchs
  9184. addDoubleTapListener: function (obj, handler, id) {
  9185. var last, touch,
  9186. doubleTap = false,
  9187. delay = 250;
  9188. function onTouchStart(e) {
  9189. var count;
  9190. if (L.Browser.pointer) {
  9191. if ((!L.Browser.edge) || e.pointerType === 'mouse') { return; }
  9192. count = L.DomEvent._pointersCount;
  9193. } else {
  9194. count = e.touches.length;
  9195. }
  9196. if (count > 1) { return; }
  9197. var now = Date.now(),
  9198. delta = now - (last || now);
  9199. touch = e.touches ? e.touches[0] : e;
  9200. doubleTap = (delta > 0 && delta <= delay);
  9201. last = now;
  9202. }
  9203. function onTouchEnd(e) {
  9204. if (doubleTap && !touch.cancelBubble) {
  9205. if (L.Browser.pointer) {
  9206. if ((!L.Browser.edge) || e.pointerType === 'mouse') { return; }
  9207. // work around .type being readonly with MSPointer* events
  9208. var newTouch = {},
  9209. prop, i;
  9210. for (i in touch) {
  9211. prop = touch[i];
  9212. newTouch[i] = prop && prop.bind ? prop.bind(touch) : prop;
  9213. }
  9214. touch = newTouch;
  9215. }
  9216. touch.type = 'dblclick';
  9217. handler(touch);
  9218. last = null;
  9219. }
  9220. }
  9221. var pre = '_leaflet_',
  9222. touchstart = this._touchstart,
  9223. touchend = this._touchend;
  9224. obj[pre + touchstart + id] = onTouchStart;
  9225. obj[pre + touchend + id] = onTouchEnd;
  9226. obj[pre + 'dblclick' + id] = handler;
  9227. obj.addEventListener(touchstart, onTouchStart, false);
  9228. obj.addEventListener(touchend, onTouchEnd, false);
  9229. // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
  9230. // the browser doesn't fire touchend/pointerup events but does fire
  9231. // native dblclicks. See #4127.
  9232. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
  9233. obj.addEventListener('dblclick', handler, false);
  9234. return this;
  9235. },
  9236. removeDoubleTapListener: function (obj, id) {
  9237. var pre = '_leaflet_',
  9238. touchstart = obj[pre + this._touchstart + id],
  9239. touchend = obj[pre + this._touchend + id],
  9240. dblclick = obj[pre + 'dblclick' + id];
  9241. obj.removeEventListener(this._touchstart, touchstart, false);
  9242. obj.removeEventListener(this._touchend, touchend, false);
  9243. if (!L.Browser.edge) {
  9244. obj.removeEventListener('dblclick', dblclick, false);
  9245. }
  9246. return this;
  9247. }
  9248. });
  9249. /*
  9250. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  9251. */
  9252. L.extend(L.DomEvent, {
  9253. POINTER_DOWN: L.Browser.msPointer ? 'MSPointerDown' : 'pointerdown',
  9254. POINTER_MOVE: L.Browser.msPointer ? 'MSPointerMove' : 'pointermove',
  9255. POINTER_UP: L.Browser.msPointer ? 'MSPointerUp' : 'pointerup',
  9256. POINTER_CANCEL: L.Browser.msPointer ? 'MSPointerCancel' : 'pointercancel',
  9257. TAG_WHITE_LIST: ['INPUT', 'SELECT', 'OPTION'],
  9258. _pointers: {},
  9259. _pointersCount: 0,
  9260. // Provides a touch events wrapper for (ms)pointer events.
  9261. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  9262. addPointerListener: function (obj, type, handler, id) {
  9263. if (type === 'touchstart') {
  9264. this._addPointerStart(obj, handler, id);
  9265. } else if (type === 'touchmove') {
  9266. this._addPointerMove(obj, handler, id);
  9267. } else if (type === 'touchend') {
  9268. this._addPointerEnd(obj, handler, id);
  9269. }
  9270. return this;
  9271. },
  9272. removePointerListener: function (obj, type, id) {
  9273. var handler = obj['_leaflet_' + type + id];
  9274. if (type === 'touchstart') {
  9275. obj.removeEventListener(this.POINTER_DOWN, handler, false);
  9276. } else if (type === 'touchmove') {
  9277. obj.removeEventListener(this.POINTER_MOVE, handler, false);
  9278. } else if (type === 'touchend') {
  9279. obj.removeEventListener(this.POINTER_UP, handler, false);
  9280. obj.removeEventListener(this.POINTER_CANCEL, handler, false);
  9281. }
  9282. return this;
  9283. },
  9284. _addPointerStart: function (obj, handler, id) {
  9285. var onDown = L.bind(function (e) {
  9286. if (e.pointerType !== 'mouse' && e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
  9287. // In IE11, some touch events needs to fire for form controls, or
  9288. // the controls will stop working. We keep a whitelist of tag names that
  9289. // need these events. For other target tags, we prevent default on the event.
  9290. if (this.TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
  9291. L.DomEvent.preventDefault(e);
  9292. } else {
  9293. return;
  9294. }
  9295. }
  9296. this._handlePointer(e, handler);
  9297. }, this);
  9298. obj['_leaflet_touchstart' + id] = onDown;
  9299. obj.addEventListener(this.POINTER_DOWN, onDown, false);
  9300. // need to keep track of what pointers and how many are active to provide e.touches emulation
  9301. if (!this._pointerDocListener) {
  9302. var pointerUp = L.bind(this._globalPointerUp, this);
  9303. // we listen documentElement as any drags that end by moving the touch off the screen get fired there
  9304. document.documentElement.addEventListener(this.POINTER_DOWN, L.bind(this._globalPointerDown, this), true);
  9305. document.documentElement.addEventListener(this.POINTER_MOVE, L.bind(this._globalPointerMove, this), true);
  9306. document.documentElement.addEventListener(this.POINTER_UP, pointerUp, true);
  9307. document.documentElement.addEventListener(this.POINTER_CANCEL, pointerUp, true);
  9308. this._pointerDocListener = true;
  9309. }
  9310. },
  9311. _globalPointerDown: function (e) {
  9312. this._pointers[e.pointerId] = e;
  9313. this._pointersCount++;
  9314. },
  9315. _globalPointerMove: function (e) {
  9316. if (this._pointers[e.pointerId]) {
  9317. this._pointers[e.pointerId] = e;
  9318. }
  9319. },
  9320. _globalPointerUp: function (e) {
  9321. delete this._pointers[e.pointerId];
  9322. this._pointersCount--;
  9323. },
  9324. _handlePointer: function (e, handler) {
  9325. e.touches = [];
  9326. for (var i in this._pointers) {
  9327. e.touches.push(this._pointers[i]);
  9328. }
  9329. e.changedTouches = [e];
  9330. handler(e);
  9331. },
  9332. _addPointerMove: function (obj, handler, id) {
  9333. var onMove = L.bind(function (e) {
  9334. // don't fire touch moves when mouse isn't down
  9335. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
  9336. this._handlePointer(e, handler);
  9337. }, this);
  9338. obj['_leaflet_touchmove' + id] = onMove;
  9339. obj.addEventListener(this.POINTER_MOVE, onMove, false);
  9340. },
  9341. _addPointerEnd: function (obj, handler, id) {
  9342. var onUp = L.bind(function (e) {
  9343. this._handlePointer(e, handler);
  9344. }, this);
  9345. obj['_leaflet_touchend' + id] = onUp;
  9346. obj.addEventListener(this.POINTER_UP, onUp, false);
  9347. obj.addEventListener(this.POINTER_CANCEL, onUp, false);
  9348. }
  9349. });
  9350. /*
  9351. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  9352. */
  9353. // @namespace Map
  9354. // @section Interaction Options
  9355. L.Map.mergeOptions({
  9356. // @section Touch interaction options
  9357. // @option touchZoom: Boolean|String = *
  9358. // Whether the map can be zoomed by touch-dragging with two fingers. If
  9359. // passed `'center'`, it will zoom to the center of the view regardless of
  9360. // where the touch events (fingers) were. Enabled for touch-capable web
  9361. // browsers except for old Androids.
  9362. touchZoom: L.Browser.touch && !L.Browser.android23,
  9363. // @option bounceAtZoomLimits: Boolean = true
  9364. // Set it to false if you don't want the map to zoom beyond min/max zoom
  9365. // and then bounce back when pinch-zooming.
  9366. bounceAtZoomLimits: true
  9367. });
  9368. L.Map.TouchZoom = L.Handler.extend({
  9369. addHooks: function () {
  9370. L.DomUtil.addClass(this._map._container, 'leaflet-touch-zoom');
  9371. L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
  9372. },
  9373. removeHooks: function () {
  9374. L.DomUtil.removeClass(this._map._container, 'leaflet-touch-zoom');
  9375. L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
  9376. },
  9377. _onTouchStart: function (e) {
  9378. var map = this._map;
  9379. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  9380. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  9381. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  9382. this._centerPoint = map.getSize()._divideBy(2);
  9383. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  9384. if (map.options.touchZoom !== 'center') {
  9385. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  9386. }
  9387. this._startDist = p1.distanceTo(p2);
  9388. this._startZoom = map.getZoom();
  9389. this._moved = false;
  9390. this._zooming = true;
  9391. map._stop();
  9392. L.DomEvent
  9393. .on(document, 'touchmove', this._onTouchMove, this)
  9394. .on(document, 'touchend', this._onTouchEnd, this);
  9395. L.DomEvent.preventDefault(e);
  9396. },
  9397. _onTouchMove: function (e) {
  9398. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  9399. var map = this._map,
  9400. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  9401. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  9402. scale = p1.distanceTo(p2) / this._startDist;
  9403. this._zoom = map.getScaleZoom(scale, this._startZoom);
  9404. if (!map.options.bounceAtZoomLimits && (
  9405. (this._zoom < map.getMinZoom() && scale < 1) ||
  9406. (this._zoom > map.getMaxZoom() && scale > 1))) {
  9407. this._zoom = map._limitZoom(this._zoom);
  9408. }
  9409. if (map.options.touchZoom === 'center') {
  9410. this._center = this._startLatLng;
  9411. if (scale === 1) { return; }
  9412. } else {
  9413. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  9414. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  9415. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  9416. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  9417. }
  9418. if (!this._moved) {
  9419. map._moveStart(true);
  9420. this._moved = true;
  9421. }
  9422. L.Util.cancelAnimFrame(this._animRequest);
  9423. var moveFn = L.bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  9424. this._animRequest = L.Util.requestAnimFrame(moveFn, this, true);
  9425. L.DomEvent.preventDefault(e);
  9426. },
  9427. _onTouchEnd: function () {
  9428. if (!this._moved || !this._zooming) {
  9429. this._zooming = false;
  9430. return;
  9431. }
  9432. this._zooming = false;
  9433. L.Util.cancelAnimFrame(this._animRequest);
  9434. L.DomEvent
  9435. .off(document, 'touchmove', this._onTouchMove)
  9436. .off(document, 'touchend', this._onTouchEnd);
  9437. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  9438. if (this._map.options.zoomAnimation) {
  9439. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  9440. } else {
  9441. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  9442. }
  9443. }
  9444. });
  9445. // @section Handlers
  9446. // @property touchZoom: Handler
  9447. // Touch zoom handler.
  9448. L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
  9449. /*
  9450. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  9451. */
  9452. // @namespace Map
  9453. // @section Interaction Options
  9454. L.Map.mergeOptions({
  9455. // @section Touch interaction options
  9456. // @option tap: Boolean = true
  9457. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  9458. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  9459. tap: true,
  9460. // @option tapTolerance: Number = 15
  9461. // The max number of pixels a user can shift his finger during touch
  9462. // for it to be considered a valid tap.
  9463. tapTolerance: 15
  9464. });
  9465. L.Map.Tap = L.Handler.extend({
  9466. addHooks: function () {
  9467. L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
  9468. },
  9469. removeHooks: function () {
  9470. L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
  9471. },
  9472. _onDown: function (e) {
  9473. if (!e.touches) { return; }
  9474. L.DomEvent.preventDefault(e);
  9475. this._fireClick = true;
  9476. // don't simulate click or track longpress if more than 1 touch
  9477. if (e.touches.length > 1) {
  9478. this._fireClick = false;
  9479. clearTimeout(this._holdTimeout);
  9480. return;
  9481. }
  9482. var first = e.touches[0],
  9483. el = first.target;
  9484. this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
  9485. // if touching a link, highlight it
  9486. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  9487. L.DomUtil.addClass(el, 'leaflet-active');
  9488. }
  9489. // simulate long hold but setting a timeout
  9490. this._holdTimeout = setTimeout(L.bind(function () {
  9491. if (this._isTapValid()) {
  9492. this._fireClick = false;
  9493. this._onUp();
  9494. this._simulateEvent('contextmenu', first);
  9495. }
  9496. }, this), 1000);
  9497. this._simulateEvent('mousedown', first);
  9498. L.DomEvent.on(document, {
  9499. touchmove: this._onMove,
  9500. touchend: this._onUp
  9501. }, this);
  9502. },
  9503. _onUp: function (e) {
  9504. clearTimeout(this._holdTimeout);
  9505. L.DomEvent.off(document, {
  9506. touchmove: this._onMove,
  9507. touchend: this._onUp
  9508. }, this);
  9509. if (this._fireClick && e && e.changedTouches) {
  9510. var first = e.changedTouches[0],
  9511. el = first.target;
  9512. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  9513. L.DomUtil.removeClass(el, 'leaflet-active');
  9514. }
  9515. this._simulateEvent('mouseup', first);
  9516. // simulate click if the touch didn't move too much
  9517. if (this._isTapValid()) {
  9518. this._simulateEvent('click', first);
  9519. }
  9520. }
  9521. },
  9522. _isTapValid: function () {
  9523. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  9524. },
  9525. _onMove: function (e) {
  9526. var first = e.touches[0];
  9527. this._newPos = new L.Point(first.clientX, first.clientY);
  9528. this._simulateEvent('mousemove', first);
  9529. },
  9530. _simulateEvent: function (type, e) {
  9531. var simulatedEvent = document.createEvent('MouseEvents');
  9532. simulatedEvent._simulated = true;
  9533. e.target._simulatedClick = true;
  9534. simulatedEvent.initMouseEvent(
  9535. type, true, true, window, 1,
  9536. e.screenX, e.screenY,
  9537. e.clientX, e.clientY,
  9538. false, false, false, false, 0, null);
  9539. e.target.dispatchEvent(simulatedEvent);
  9540. }
  9541. });
  9542. // @section Handlers
  9543. // @property tap: Handler
  9544. // Mobile touch hacks (quick tap and touch hold) handler.
  9545. if (L.Browser.touch && !L.Browser.pointer) {
  9546. L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
  9547. }
  9548. /*
  9549. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  9550. * (zoom to a selected bounding box), enabled by default.
  9551. */
  9552. // @namespace Map
  9553. // @section Interaction Options
  9554. L.Map.mergeOptions({
  9555. // @option boxZoom: Boolean = true
  9556. // Whether the map can be zoomed to a rectangular area specified by
  9557. // dragging the mouse while pressing the shift key.
  9558. boxZoom: true
  9559. });
  9560. L.Map.BoxZoom = L.Handler.extend({
  9561. initialize: function (map) {
  9562. this._map = map;
  9563. this._container = map._container;
  9564. this._pane = map._panes.overlayPane;
  9565. },
  9566. addHooks: function () {
  9567. L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
  9568. },
  9569. removeHooks: function () {
  9570. L.DomEvent.off(this._container, 'mousedown', this._onMouseDown, this);
  9571. },
  9572. moved: function () {
  9573. return this._moved;
  9574. },
  9575. _resetState: function () {
  9576. this._moved = false;
  9577. },
  9578. _onMouseDown: function (e) {
  9579. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  9580. this._resetState();
  9581. L.DomUtil.disableTextSelection();
  9582. L.DomUtil.disableImageDrag();
  9583. this._startPoint = this._map.mouseEventToContainerPoint(e);
  9584. L.DomEvent.on(document, {
  9585. contextmenu: L.DomEvent.stop,
  9586. mousemove: this._onMouseMove,
  9587. mouseup: this._onMouseUp,
  9588. keydown: this._onKeyDown
  9589. }, this);
  9590. },
  9591. _onMouseMove: function (e) {
  9592. if (!this._moved) {
  9593. this._moved = true;
  9594. this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._container);
  9595. L.DomUtil.addClass(this._container, 'leaflet-crosshair');
  9596. this._map.fire('boxzoomstart');
  9597. }
  9598. this._point = this._map.mouseEventToContainerPoint(e);
  9599. var bounds = new L.Bounds(this._point, this._startPoint),
  9600. size = bounds.getSize();
  9601. L.DomUtil.setPosition(this._box, bounds.min);
  9602. this._box.style.width = size.x + 'px';
  9603. this._box.style.height = size.y + 'px';
  9604. },
  9605. _finish: function () {
  9606. if (this._moved) {
  9607. L.DomUtil.remove(this._box);
  9608. L.DomUtil.removeClass(this._container, 'leaflet-crosshair');
  9609. }
  9610. L.DomUtil.enableTextSelection();
  9611. L.DomUtil.enableImageDrag();
  9612. L.DomEvent.off(document, {
  9613. contextmenu: L.DomEvent.stop,
  9614. mousemove: this._onMouseMove,
  9615. mouseup: this._onMouseUp,
  9616. keydown: this._onKeyDown
  9617. }, this);
  9618. },
  9619. _onMouseUp: function (e) {
  9620. if ((e.which !== 1) && (e.button !== 1)) { return; }
  9621. this._finish();
  9622. if (!this._moved) { return; }
  9623. // Postpone to next JS tick so internal click event handling
  9624. // still see it as "moved".
  9625. setTimeout(L.bind(this._resetState, this), 0);
  9626. var bounds = new L.LatLngBounds(
  9627. this._map.containerPointToLatLng(this._startPoint),
  9628. this._map.containerPointToLatLng(this._point));
  9629. this._map
  9630. .fitBounds(bounds)
  9631. .fire('boxzoomend', {boxZoomBounds: bounds});
  9632. },
  9633. _onKeyDown: function (e) {
  9634. if (e.keyCode === 27) {
  9635. this._finish();
  9636. }
  9637. }
  9638. });
  9639. // @section Handlers
  9640. // @property boxZoom: Handler
  9641. // Box (shift-drag with mouse) zoom handler.
  9642. L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
  9643. /*
  9644. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  9645. */
  9646. // @namespace Map
  9647. // @section Keyboard Navigation Options
  9648. L.Map.mergeOptions({
  9649. // @option keyboard: Boolean = true
  9650. // Makes the map focusable and allows users to navigate the map with keyboard
  9651. // arrows and `+`/`-` keys.
  9652. keyboard: true,
  9653. // @option keyboardPanDelta: Number = 80
  9654. // Amount of pixels to pan when pressing an arrow key.
  9655. keyboardPanDelta: 80
  9656. });
  9657. L.Map.Keyboard = L.Handler.extend({
  9658. keyCodes: {
  9659. left: [37],
  9660. right: [39],
  9661. down: [40],
  9662. up: [38],
  9663. zoomIn: [187, 107, 61, 171],
  9664. zoomOut: [189, 109, 54, 173]
  9665. },
  9666. initialize: function (map) {
  9667. this._map = map;
  9668. this._setPanDelta(map.options.keyboardPanDelta);
  9669. this._setZoomDelta(map.options.zoomDelta);
  9670. },
  9671. addHooks: function () {
  9672. var container = this._map._container;
  9673. // make the container focusable by tabbing
  9674. if (container.tabIndex <= 0) {
  9675. container.tabIndex = '0';
  9676. }
  9677. L.DomEvent.on(container, {
  9678. focus: this._onFocus,
  9679. blur: this._onBlur,
  9680. mousedown: this._onMouseDown
  9681. }, this);
  9682. this._map.on({
  9683. focus: this._addHooks,
  9684. blur: this._removeHooks
  9685. }, this);
  9686. },
  9687. removeHooks: function () {
  9688. this._removeHooks();
  9689. L.DomEvent.off(this._map._container, {
  9690. focus: this._onFocus,
  9691. blur: this._onBlur,
  9692. mousedown: this._onMouseDown
  9693. }, this);
  9694. this._map.off({
  9695. focus: this._addHooks,
  9696. blur: this._removeHooks
  9697. }, this);
  9698. },
  9699. _onMouseDown: function () {
  9700. if (this._focused) { return; }
  9701. var body = document.body,
  9702. docEl = document.documentElement,
  9703. top = body.scrollTop || docEl.scrollTop,
  9704. left = body.scrollLeft || docEl.scrollLeft;
  9705. this._map._container.focus();
  9706. window.scrollTo(left, top);
  9707. },
  9708. _onFocus: function () {
  9709. this._focused = true;
  9710. this._map.fire('focus');
  9711. },
  9712. _onBlur: function () {
  9713. this._focused = false;
  9714. this._map.fire('blur');
  9715. },
  9716. _setPanDelta: function (panDelta) {
  9717. var keys = this._panKeys = {},
  9718. codes = this.keyCodes,
  9719. i, len;
  9720. for (i = 0, len = codes.left.length; i < len; i++) {
  9721. keys[codes.left[i]] = [-1 * panDelta, 0];
  9722. }
  9723. for (i = 0, len = codes.right.length; i < len; i++) {
  9724. keys[codes.right[i]] = [panDelta, 0];
  9725. }
  9726. for (i = 0, len = codes.down.length; i < len; i++) {
  9727. keys[codes.down[i]] = [0, panDelta];
  9728. }
  9729. for (i = 0, len = codes.up.length; i < len; i++) {
  9730. keys[codes.up[i]] = [0, -1 * panDelta];
  9731. }
  9732. },
  9733. _setZoomDelta: function (zoomDelta) {
  9734. var keys = this._zoomKeys = {},
  9735. codes = this.keyCodes,
  9736. i, len;
  9737. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  9738. keys[codes.zoomIn[i]] = zoomDelta;
  9739. }
  9740. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  9741. keys[codes.zoomOut[i]] = -zoomDelta;
  9742. }
  9743. },
  9744. _addHooks: function () {
  9745. L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
  9746. },
  9747. _removeHooks: function () {
  9748. L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
  9749. },
  9750. _onKeyDown: function (e) {
  9751. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  9752. var key = e.keyCode,
  9753. map = this._map,
  9754. offset;
  9755. if (key in this._panKeys) {
  9756. if (map._panAnim && map._panAnim._inProgress) { return; }
  9757. offset = this._panKeys[key];
  9758. if (e.shiftKey) {
  9759. offset = L.point(offset).multiplyBy(3);
  9760. }
  9761. map.panBy(offset);
  9762. if (map.options.maxBounds) {
  9763. map.panInsideBounds(map.options.maxBounds);
  9764. }
  9765. } else if (key in this._zoomKeys) {
  9766. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  9767. } else if (key === 27) {
  9768. map.closePopup();
  9769. } else {
  9770. return;
  9771. }
  9772. L.DomEvent.stop(e);
  9773. }
  9774. });
  9775. // @section Handlers
  9776. // @section Handlers
  9777. // @property keyboard: Handler
  9778. // Keyboard navigation handler.
  9779. L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
  9780. /*
  9781. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  9782. */
  9783. /* @namespace Marker
  9784. * @section Interaction handlers
  9785. *
  9786. * 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:
  9787. *
  9788. * ```js
  9789. * marker.dragging.disable();
  9790. * ```
  9791. *
  9792. * @property dragging: Handler
  9793. * Marker dragging handler (by both mouse and touch).
  9794. */
  9795. L.Handler.MarkerDrag = L.Handler.extend({
  9796. initialize: function (marker) {
  9797. this._marker = marker;
  9798. },
  9799. addHooks: function () {
  9800. var icon = this._marker._icon;
  9801. if (!this._draggable) {
  9802. this._draggable = new L.Draggable(icon, icon, true);
  9803. }
  9804. this._draggable.on({
  9805. dragstart: this._onDragStart,
  9806. drag: this._onDrag,
  9807. dragend: this._onDragEnd
  9808. }, this).enable();
  9809. L.DomUtil.addClass(icon, 'leaflet-marker-draggable');
  9810. },
  9811. removeHooks: function () {
  9812. this._draggable.off({
  9813. dragstart: this._onDragStart,
  9814. drag: this._onDrag,
  9815. dragend: this._onDragEnd
  9816. }, this).disable();
  9817. if (this._marker._icon) {
  9818. L.DomUtil.removeClass(this._marker._icon, 'leaflet-marker-draggable');
  9819. }
  9820. },
  9821. moved: function () {
  9822. return this._draggable && this._draggable._moved;
  9823. },
  9824. _onDragStart: function () {
  9825. // @section Dragging events
  9826. // @event dragstart: Event
  9827. // Fired when the user starts dragging the marker.
  9828. // @event movestart: Event
  9829. // Fired when the marker starts moving (because of dragging).
  9830. this._oldLatLng = this._marker.getLatLng();
  9831. this._marker
  9832. .closePopup()
  9833. .fire('movestart')
  9834. .fire('dragstart');
  9835. },
  9836. _onDrag: function (e) {
  9837. var marker = this._marker,
  9838. shadow = marker._shadow,
  9839. iconPos = L.DomUtil.getPosition(marker._icon),
  9840. latlng = marker._map.layerPointToLatLng(iconPos);
  9841. // update shadow position
  9842. if (shadow) {
  9843. L.DomUtil.setPosition(shadow, iconPos);
  9844. }
  9845. marker._latlng = latlng;
  9846. e.latlng = latlng;
  9847. e.oldLatLng = this._oldLatLng;
  9848. // @event drag: Event
  9849. // Fired repeatedly while the user drags the marker.
  9850. marker
  9851. .fire('move', e)
  9852. .fire('drag', e);
  9853. },
  9854. _onDragEnd: function (e) {
  9855. // @event dragend: DragEndEvent
  9856. // Fired when the user stops dragging the marker.
  9857. // @event moveend: Event
  9858. // Fired when the marker stops moving (because of dragging).
  9859. delete this._oldLatLng;
  9860. this._marker
  9861. .fire('moveend')
  9862. .fire('dragend', e);
  9863. }
  9864. });
  9865. /*
  9866. * @class Control
  9867. * @aka L.Control
  9868. * @inherits Class
  9869. *
  9870. * L.Control is a base class for implementing map controls. Handles positioning.
  9871. * All other controls extend from this class.
  9872. */
  9873. L.Control = L.Class.extend({
  9874. // @section
  9875. // @aka Control options
  9876. options: {
  9877. // @option position: String = 'topright'
  9878. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  9879. // `'topright'`, `'bottomleft'` or `'bottomright'`
  9880. position: 'topright'
  9881. },
  9882. initialize: function (options) {
  9883. L.setOptions(this, options);
  9884. },
  9885. /* @section
  9886. * Classes extending L.Control will inherit the following methods:
  9887. *
  9888. * @method getPosition: string
  9889. * Returns the position of the control.
  9890. */
  9891. getPosition: function () {
  9892. return this.options.position;
  9893. },
  9894. // @method setPosition(position: string): this
  9895. // Sets the position of the control.
  9896. setPosition: function (position) {
  9897. var map = this._map;
  9898. if (map) {
  9899. map.removeControl(this);
  9900. }
  9901. this.options.position = position;
  9902. if (map) {
  9903. map.addControl(this);
  9904. }
  9905. return this;
  9906. },
  9907. // @method getContainer: HTMLElement
  9908. // Returns the HTMLElement that contains the control.
  9909. getContainer: function () {
  9910. return this._container;
  9911. },
  9912. // @method addTo(map: Map): this
  9913. // Adds the control to the given map.
  9914. addTo: function (map) {
  9915. this.remove();
  9916. this._map = map;
  9917. var container = this._container = this.onAdd(map),
  9918. pos = this.getPosition(),
  9919. corner = map._controlCorners[pos];
  9920. L.DomUtil.addClass(container, 'leaflet-control');
  9921. if (pos.indexOf('bottom') !== -1) {
  9922. corner.insertBefore(container, corner.firstChild);
  9923. } else {
  9924. corner.appendChild(container);
  9925. }
  9926. return this;
  9927. },
  9928. // @method remove: this
  9929. // Removes the control from the map it is currently active on.
  9930. remove: function () {
  9931. if (!this._map) {
  9932. return this;
  9933. }
  9934. L.DomUtil.remove(this._container);
  9935. if (this.onRemove) {
  9936. this.onRemove(this._map);
  9937. }
  9938. this._map = null;
  9939. return this;
  9940. },
  9941. _refocusOnMap: function (e) {
  9942. // if map exists and event is not a keyboard event
  9943. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  9944. this._map.getContainer().focus();
  9945. }
  9946. }
  9947. });
  9948. L.control = function (options) {
  9949. return new L.Control(options);
  9950. };
  9951. /* @section Extension methods
  9952. * @uninheritable
  9953. *
  9954. * Every control should extend from `L.Control` and (re-)implement the following methods.
  9955. *
  9956. * @method onAdd(map: Map): HTMLElement
  9957. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  9958. *
  9959. * @method onRemove(map: Map)
  9960. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  9961. */
  9962. /* @namespace Map
  9963. * @section Methods for Layers and Controls
  9964. */
  9965. L.Map.include({
  9966. // @method addControl(control: Control): this
  9967. // Adds the given control to the map
  9968. addControl: function (control) {
  9969. control.addTo(this);
  9970. return this;
  9971. },
  9972. // @method removeControl(control: Control): this
  9973. // Removes the given control from the map
  9974. removeControl: function (control) {
  9975. control.remove();
  9976. return this;
  9977. },
  9978. _initControlPos: function () {
  9979. var corners = this._controlCorners = {},
  9980. l = 'leaflet-',
  9981. container = this._controlContainer =
  9982. L.DomUtil.create('div', l + 'control-container', this._container);
  9983. function createCorner(vSide, hSide) {
  9984. var className = l + vSide + ' ' + l + hSide;
  9985. corners[vSide + hSide] = L.DomUtil.create('div', className, container);
  9986. }
  9987. createCorner('top', 'left');
  9988. createCorner('top', 'right');
  9989. createCorner('bottom', 'left');
  9990. createCorner('bottom', 'right');
  9991. },
  9992. _clearControlPos: function () {
  9993. L.DomUtil.remove(this._controlContainer);
  9994. }
  9995. });
  9996. /*
  9997. * @class Control.Zoom
  9998. * @aka L.Control.Zoom
  9999. * @inherits Control
  10000. *
  10001. * 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`.
  10002. */
  10003. L.Control.Zoom = L.Control.extend({
  10004. // @section
  10005. // @aka Control.Zoom options
  10006. options: {
  10007. position: 'topleft',
  10008. // @option zoomInText: String = '+'
  10009. // The text set on the 'zoom in' button.
  10010. zoomInText: '+',
  10011. // @option zoomInTitle: String = 'Zoom in'
  10012. // The title set on the 'zoom in' button.
  10013. zoomInTitle: 'Zoom in',
  10014. // @option zoomOutText: String = '-'
  10015. // The text set on the 'zoom out' button.
  10016. zoomOutText: '-',
  10017. // @option zoomOutTitle: String = 'Zoom out'
  10018. // The title set on the 'zoom out' button.
  10019. zoomOutTitle: 'Zoom out'
  10020. },
  10021. onAdd: function (map) {
  10022. var zoomName = 'leaflet-control-zoom',
  10023. container = L.DomUtil.create('div', zoomName + ' leaflet-bar'),
  10024. options = this.options;
  10025. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  10026. zoomName + '-in', container, this._zoomIn);
  10027. this._zoomTextButton = this._createButton(map._zoom, map._zoom,
  10028. zoomName + '-text', container, function(){});
  10029. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  10030. zoomName + '-out', container, this._zoomOut);
  10031. this._updateDisabled();
  10032. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  10033. return container;
  10034. },
  10035. onRemove: function (map) {
  10036. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  10037. },
  10038. disable: function () {
  10039. this._disabled = true;
  10040. this._updateDisabled();
  10041. return this;
  10042. },
  10043. enable: function () {
  10044. this._disabled = false;
  10045. this._updateDisabled();
  10046. return this;
  10047. },
  10048. _zoomIn: function (e) {
  10049. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  10050. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  10051. }
  10052. },
  10053. _zoomOut: function (e) {
  10054. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  10055. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  10056. }
  10057. },
  10058. _createButton: function (html, title, className, container, fn) {
  10059. var link = L.DomUtil.create('a', className, container);
  10060. link.innerHTML = html;
  10061. link.href = '#';
  10062. link.title = title;
  10063. /*
  10064. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  10065. */
  10066. link.setAttribute('role', 'button');
  10067. link.setAttribute('aria-label', title);
  10068. L.DomEvent
  10069. .on(link, 'mousedown dblclick', L.DomEvent.stopPropagation)
  10070. .on(link, 'click', L.DomEvent.stop)
  10071. .on(link, 'click', fn, this)
  10072. .on(link, 'click', this._refocusOnMap, this);
  10073. return link;
  10074. },
  10075. _updateDisabled: function () {
  10076. var map = this._map,
  10077. className = 'leaflet-disabled';
  10078. L.DomUtil.removeClass(this._zoomInButton, className);
  10079. L.DomUtil.removeClass(this._zoomOutButton, className);
  10080. if (this._disabled || map._zoom === map.getMinZoom()) {
  10081. L.DomUtil.addClass(this._zoomOutButton, className);
  10082. }
  10083. if (this._disabled || map._zoom === map.getMaxZoom()) {
  10084. L.DomUtil.addClass(this._zoomInButton, className);
  10085. }
  10086. this._zoomTextButton.innerText = map._zoom;
  10087. }
  10088. });
  10089. // @namespace Map
  10090. // @section Control options
  10091. // @option zoomControl: Boolean = true
  10092. // Whether a [zoom control](#control-zoom) is added to the map by default.
  10093. L.Map.mergeOptions({
  10094. zoomControl: true
  10095. });
  10096. L.Map.addInitHook(function () {
  10097. if (this.options.zoomControl) {
  10098. this.zoomControl = new L.Control.Zoom();
  10099. this.addControl(this.zoomControl);
  10100. }
  10101. });
  10102. // @namespace Control.Zoom
  10103. // @factory L.control.zoom(options: Control.Zoom options)
  10104. // Creates a zoom control
  10105. L.control.zoom = function (options) {
  10106. return new L.Control.Zoom(options);
  10107. };
  10108. /*
  10109. * @class Control.Attribution
  10110. * @aka L.Control.Attribution
  10111. * @inherits Control
  10112. *
  10113. * 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.
  10114. */
  10115. L.Control.Attribution = L.Control.extend({
  10116. // @section
  10117. // @aka Control.Attribution options
  10118. options: {
  10119. position: 'bottomright',
  10120. // @option prefix: String = 'Leaflet'
  10121. // The HTML text shown before the attributions. Pass `false` to disable.
  10122. prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  10123. },
  10124. initialize: function (options) {
  10125. L.setOptions(this, options);
  10126. this._attributions = {};
  10127. },
  10128. onAdd: function (map) {
  10129. map.attributionControl = this;
  10130. this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
  10131. if (L.DomEvent) {
  10132. L.DomEvent.disableClickPropagation(this._container);
  10133. }
  10134. for (var i in map._layers) {
  10135. if (map._layers[i].getAttribution) {
  10136. this.addAttribution(map._layers[i].getAttribution());
  10137. }
  10138. }
  10139. this._update();
  10140. return this._container;
  10141. },
  10142. // @method setPrefix(prefix: String): this
  10143. // Sets the text before the attributions.
  10144. setPrefix: function (prefix) {
  10145. this.options.prefix = prefix;
  10146. this._update();
  10147. return this;
  10148. },
  10149. // @method addAttribution(text: String): this
  10150. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  10151. addAttribution: function (text) {
  10152. if (!text) { return this; }
  10153. if (!this._attributions[text]) {
  10154. this._attributions[text] = 0;
  10155. }
  10156. this._attributions[text]++;
  10157. this._update();
  10158. return this;
  10159. },
  10160. // @method removeAttribution(text: String): this
  10161. // Removes an attribution text.
  10162. removeAttribution: function (text) {
  10163. if (!text) { return this; }
  10164. if (this._attributions[text]) {
  10165. this._attributions[text]--;
  10166. this._update();
  10167. }
  10168. return this;
  10169. },
  10170. _update: function () {
  10171. if (!this._map) { return; }
  10172. var attribs = [];
  10173. for (var i in this._attributions) {
  10174. if (this._attributions[i]) {
  10175. attribs.push(i);
  10176. }
  10177. }
  10178. var prefixAndAttribs = [];
  10179. if (this.options.prefix) {
  10180. prefixAndAttribs.push(this.options.prefix);
  10181. }
  10182. if (attribs.length) {
  10183. prefixAndAttribs.push(attribs.join(', '));
  10184. }
  10185. this._container.innerHTML = prefixAndAttribs.join(' | ');
  10186. }
  10187. });
  10188. // @namespace Map
  10189. // @section Control options
  10190. // @option attributionControl: Boolean = true
  10191. // Whether a [attribution control](#control-attribution) is added to the map by default.
  10192. L.Map.mergeOptions({
  10193. attributionControl: true
  10194. });
  10195. L.Map.addInitHook(function () {
  10196. if (this.options.attributionControl) {
  10197. new L.Control.Attribution().addTo(this);
  10198. }
  10199. });
  10200. // @namespace Control.Attribution
  10201. // @factory L.control.attribution(options: Control.Attribution options)
  10202. // Creates an attribution control.
  10203. L.control.attribution = function (options) {
  10204. return new L.Control.Attribution(options);
  10205. };
  10206. /*
  10207. * @class Control.Scale
  10208. * @aka L.Control.Scale
  10209. * @inherits Control
  10210. *
  10211. * 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`.
  10212. *
  10213. * @example
  10214. *
  10215. * ```js
  10216. * L.control.scale().addTo(map);
  10217. * ```
  10218. */
  10219. L.Control.Scale = L.Control.extend({
  10220. // @section
  10221. // @aka Control.Scale options
  10222. options: {
  10223. position: 'bottomleft',
  10224. // @option maxWidth: Number = 100
  10225. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  10226. maxWidth: 100,
  10227. // @option metric: Boolean = True
  10228. // Whether to show the metric scale line (m/km).
  10229. metric: true,
  10230. // @option imperial: Boolean = True
  10231. // Whether to show the imperial scale line (mi/ft).
  10232. imperial: true
  10233. // @option updateWhenIdle: Boolean = false
  10234. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  10235. },
  10236. onAdd: function (map) {
  10237. var className = 'leaflet-control-scale',
  10238. container = L.DomUtil.create('div', className),
  10239. options = this.options;
  10240. this._addScales(options, className + '-line', container);
  10241. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  10242. map.whenReady(this._update, this);
  10243. return container;
  10244. },
  10245. onRemove: function (map) {
  10246. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  10247. },
  10248. _addScales: function (options, className, container) {
  10249. if (options.metric) {
  10250. this._mScale = L.DomUtil.create('div', className, container);
  10251. }
  10252. if (options.imperial) {
  10253. this._iScale = L.DomUtil.create('div', className, container);
  10254. }
  10255. },
  10256. _update: function () {
  10257. var map = this._map,
  10258. y = map.getSize().y / 2;
  10259. var maxMeters = map.distance(
  10260. map.containerPointToLatLng([0, y]),
  10261. map.containerPointToLatLng([this.options.maxWidth, y]));
  10262. this._updateScales(maxMeters);
  10263. },
  10264. _updateScales: function (maxMeters) {
  10265. if (this.options.metric && maxMeters) {
  10266. this._updateMetric(maxMeters);
  10267. }
  10268. if (this.options.imperial && maxMeters) {
  10269. this._updateImperial(maxMeters);
  10270. }
  10271. },
  10272. _updateMetric: function (maxMeters) {
  10273. var meters = this._getRoundNum(maxMeters),
  10274. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  10275. this._updateScale(this._mScale, label, meters / maxMeters);
  10276. },
  10277. _updateImperial: function (maxMeters) {
  10278. var maxFeet = maxMeters * 3.2808399,
  10279. maxMiles, miles, feet;
  10280. if (maxFeet > 5280) {
  10281. maxMiles = maxFeet / 5280;
  10282. miles = this._getRoundNum(maxMiles);
  10283. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  10284. } else {
  10285. feet = this._getRoundNum(maxFeet);
  10286. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  10287. }
  10288. },
  10289. _updateScale: function (scale, text, ratio) {
  10290. // scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  10291. scale.style.width = '60px'
  10292. scale.innerHTML = text;
  10293. },
  10294. _getRoundNum: function (num) {
  10295. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  10296. d = num / pow10;
  10297. d = d >= 10 ? 10 :
  10298. d >= 5 ? 5 :
  10299. d >= 3 ? 3 :
  10300. d >= 2 ? 2 : 1;
  10301. return pow10 * d;
  10302. }
  10303. });
  10304. // @factory L.control.scale(options?: Control.Scale options)
  10305. // Creates an scale control with the given options.
  10306. L.control.scale = function (options) {
  10307. return new L.Control.Scale(options);
  10308. };
  10309. L.Control.Layers = L.Control.extend({
  10310. // @section
  10311. // @aka Control.Layers options
  10312. options: {
  10313. // @option collapsed: Boolean = true
  10314. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  10315. collapsed: true,
  10316. position: 'topright',
  10317. // @option autoZIndex: Boolean = true
  10318. // 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.
  10319. autoZIndex: true,
  10320. // @option hideSingleBase: Boolean = false
  10321. // If `true`, the base layers in the control will be hidden when there is only one.
  10322. hideSingleBase: false,
  10323. // @option sortLayers: Boolean = false
  10324. // Whether to sort the layers. When `false`, layers will keep the order
  10325. // in which they were added to the control.
  10326. sortLayers: false,
  10327. // @option sortFunction: Function = *
  10328. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  10329. // that will be used for sorting the layers, when `sortLayers` is `true`.
  10330. // The function receives both the `L.Layer` instances and their names, as in
  10331. // `sortFunction(layerA, layerB, nameA, nameB)`.
  10332. // By default, it sorts layers alphabetically by their name.
  10333. sortFunction: function (layerA, layerB, nameA, nameB) {
  10334. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  10335. }
  10336. },
  10337. initialize: function (baseLayers, overlays, options) {
  10338. L.setOptions(this, options);
  10339. this._layers = [];
  10340. this._lastZIndex = 0;
  10341. this._handlingClick = false;
  10342. for (var i in baseLayers) {
  10343. this._addLayer(baseLayers[i], i);
  10344. }
  10345. for (i in overlays) {
  10346. this._addLayer(overlays[i], i, true);
  10347. }
  10348. },
  10349. onAdd: function (map) {
  10350. this._initLayout();
  10351. this._update();
  10352. this._map = map;
  10353. map.on('zoomend', this._checkDisabledLayers, this);
  10354. return this._container;
  10355. },
  10356. onRemove: function () {
  10357. this._map.off('zoomend', this._checkDisabledLayers, this);
  10358. for (var i = 0; i < this._layers.length; i++) {
  10359. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  10360. }
  10361. },
  10362. // @method addBaseLayer(layer: Layer, name: String): this
  10363. // Adds a base layer (radio button entry) with the given name to the control.
  10364. addBaseLayer: function (layer, name) {
  10365. this._addLayer(layer, name);
  10366. return (this._map) ? this._update() : this;
  10367. },
  10368. // @method addOverlay(layer: Layer, name: String): this
  10369. // Adds an overlay (checkbox entry) with the given name to the control.
  10370. addOverlay: function (layer, name) {
  10371. this._addLayer(layer, name, true);
  10372. return (this._map) ? this._update() : this;
  10373. },
  10374. // @method removeLayer(layer: Layer): this
  10375. // Remove the given layer from the control.
  10376. removeLayer: function (layer) {
  10377. layer.off('add remove', this._onLayerChange, this);
  10378. var obj = this._getLayer(L.stamp(layer));
  10379. if (obj) {
  10380. this._layers.splice(this._layers.indexOf(obj), 1);
  10381. }
  10382. return (this._map) ? this._update() : this;
  10383. },
  10384. // @method expand(): this
  10385. // Expand the control container if collapsed.
  10386. expand: function () {
  10387. L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
  10388. this._form.style.height = null;
  10389. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  10390. if (acceptableHeight < this._form.clientHeight) {
  10391. L.DomUtil.addClass(this._form, 'leaflet-control-layers-scrollbar');
  10392. this._form.style.height = acceptableHeight + 'px';
  10393. } else {
  10394. L.DomUtil.removeClass(this._form, 'leaflet-control-layers-scrollbar');
  10395. }
  10396. this._checkDisabledLayers();
  10397. return this;
  10398. },
  10399. // @method collapse(): this
  10400. // Collapse the control container if expanded.
  10401. collapse: function () {
  10402. L.DomUtil.removeClass(this._container, 'leaflet-control-layers-expanded');
  10403. return this;
  10404. },
  10405. _initLayout: function () {
  10406. var className = 'leaflet-control-layers',
  10407. container = this._container = L.DomUtil.create('div', className),
  10408. collapsed = this.options.collapsed;
  10409. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  10410. container.setAttribute('aria-haspopup', true);
  10411. L.DomEvent.disableClickPropagation(container);
  10412. if (!L.Browser.touch) {
  10413. L.DomEvent.disableScrollPropagation(container);
  10414. }
  10415. var form = this._form = L.DomUtil.create('form', className + '-list');
  10416. if (collapsed) {
  10417. this._map.on('click', this.collapse, this);
  10418. if (!L.Browser.android) {
  10419. L.DomEvent.on(container, {
  10420. mouseenter: this.expand,
  10421. mouseleave: this.collapse
  10422. }, this);
  10423. }
  10424. }
  10425. var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
  10426. link.href = '#';
  10427. link.title = 'Layers';
  10428. if (L.Browser.touch) {
  10429. L.DomEvent
  10430. .on(link, 'click', L.DomEvent.stop)
  10431. .on(link, 'click', this.expand, this);
  10432. } else {
  10433. L.DomEvent.on(link, 'focus', this.expand, this);
  10434. }
  10435. // work around for Firefox Android issue https://github.com/Leaflet/Leaflet/issues/2033
  10436. L.DomEvent.on(form, 'click', function () {
  10437. setTimeout(L.bind(this._onInputClick, this), 0);
  10438. }, this);
  10439. if (!collapsed) {
  10440. this.expand();
  10441. }
  10442. this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
  10443. this._separator = L.DomUtil.create('div', className + '-separator', form);
  10444. this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
  10445. container.appendChild(form);
  10446. },
  10447. _getLayer: function (id) {
  10448. for (var i = 0; i < this._layers.length; i++) {
  10449. if (this._layers[i] && L.stamp(this._layers[i].layer) === id) {
  10450. return this._layers[i];
  10451. }
  10452. }
  10453. },
  10454. _addLayer: function (layer, name, overlay) {
  10455. layer.on('add remove', this._onLayerChange, this);
  10456. this._layers.push({
  10457. layer: layer,
  10458. name: name,
  10459. overlay: overlay
  10460. });
  10461. if (this.options.sortLayers) {
  10462. this._layers.sort(L.bind(function (a, b) {
  10463. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  10464. }, this));
  10465. }
  10466. if (this.options.autoZIndex && layer.setZIndex) {
  10467. this._lastZIndex++;
  10468. layer.setZIndex(this._lastZIndex);
  10469. }
  10470. },
  10471. _update: function () {
  10472. if (!this._container) { return this; }
  10473. L.DomUtil.empty(this._baseLayersList);
  10474. L.DomUtil.empty(this._overlaysList);
  10475. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  10476. for (i = 0; i < this._layers.length; i++) {
  10477. obj = this._layers[i];
  10478. this._addItem(obj);
  10479. overlaysPresent = overlaysPresent || obj.overlay;
  10480. baseLayersPresent = baseLayersPresent || !obj.overlay;
  10481. baseLayersCount += !obj.overlay ? 1 : 0;
  10482. }
  10483. // Hide base layers section if there's only one layer.
  10484. if (this.options.hideSingleBase) {
  10485. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  10486. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  10487. }
  10488. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  10489. return this;
  10490. },
  10491. _onLayerChange: function (e) {
  10492. if (!this._handlingClick) {
  10493. this._update();
  10494. }
  10495. var obj = this._getLayer(L.stamp(e.target));
  10496. // @namespace Map
  10497. // @section Layer events
  10498. // @event baselayerchange: LayersControlEvent
  10499. // Fired when the base layer is changed through the [layer control](#control-layers).
  10500. // @event overlayadd: LayersControlEvent
  10501. // Fired when an overlay is selected through the [layer control](#control-layers).
  10502. // @event overlayremove: LayersControlEvent
  10503. // Fired when an overlay is deselected through the [layer control](#control-layers).
  10504. // @namespace Control.Layers
  10505. var type = obj.overlay ?
  10506. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  10507. (e.type === 'add' ? 'baselayerchange' : null);
  10508. if (type) {
  10509. this._map.fire(type, obj);
  10510. }
  10511. },
  10512. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  10513. _createRadioElement: function (name, checked) {
  10514. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  10515. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  10516. var radioFragment = document.createElement('div');
  10517. radioFragment.innerHTML = radioHtml;
  10518. return radioFragment.firstChild;
  10519. },
  10520. _addItem: function (obj) {
  10521. var label = document.createElement('label'),
  10522. checked = this._map.hasLayer(obj.layer),
  10523. input;
  10524. if (obj.overlay) {
  10525. input = document.createElement('input');
  10526. input.type = 'checkbox';
  10527. input.className = 'leaflet-control-layers-selector';
  10528. input.defaultChecked = checked;
  10529. } else {
  10530. input = this._createRadioElement('leaflet-base-layers', checked);
  10531. }
  10532. input.layerId = L.stamp(obj.layer);
  10533. L.DomEvent.on(input, 'click', this._onInputClick, this);
  10534. var name = document.createElement('span');
  10535. name.innerHTML = ' ' + obj.name;
  10536. // Helps from preventing layer control flicker when checkboxes are disabled
  10537. // https://github.com/Leaflet/Leaflet/issues/2771
  10538. var holder = document.createElement('div');
  10539. label.appendChild(holder);
  10540. holder.appendChild(input);
  10541. holder.appendChild(name);
  10542. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  10543. container.appendChild(label);
  10544. this._checkDisabledLayers();
  10545. return label;
  10546. },
  10547. _onInputClick: function () {
  10548. var inputs = this._form.getElementsByTagName('input'),
  10549. input, layer, hasLayer;
  10550. var addedLayers = [],
  10551. removedLayers = [];
  10552. this._handlingClick = true;
  10553. for (var i = inputs.length - 1; i >= 0; i--) {
  10554. input = inputs[i];
  10555. layer = this._getLayer(input.layerId).layer;
  10556. hasLayer = this._map.hasLayer(layer);
  10557. if (input.checked && !hasLayer) {
  10558. addedLayers.push(layer);
  10559. } else if (!input.checked && hasLayer) {
  10560. removedLayers.push(layer);
  10561. }
  10562. }
  10563. // Bugfix issue 2318: Should remove all old layers before readding new ones
  10564. for (i = 0; i < removedLayers.length; i++) {
  10565. this._map.removeLayer(removedLayers[i]);
  10566. }
  10567. for (i = 0; i < addedLayers.length; i++) {
  10568. this._map.addLayer(addedLayers[i]);
  10569. }
  10570. this._handlingClick = false;
  10571. this._refocusOnMap();
  10572. },
  10573. _checkDisabledLayers: function () {
  10574. var inputs = this._form.getElementsByTagName('input'),
  10575. input,
  10576. layer,
  10577. zoom = this._map.getZoom();
  10578. for (var i = inputs.length - 1; i >= 0; i--) {
  10579. input = inputs[i];
  10580. layer = this._getLayer(input.layerId).layer;
  10581. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  10582. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  10583. }
  10584. },
  10585. _expand: function () {
  10586. // Backward compatibility, remove me in 1.1.
  10587. return this.expand();
  10588. },
  10589. _collapse: function () {
  10590. // Backward compatibility, remove me in 1.1.
  10591. return this.collapse();
  10592. }
  10593. });
  10594. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  10595. // 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.
  10596. L.control.layers = function (baseLayers, overlays, options) {
  10597. return new L.Control.Layers(baseLayers, overlays, options);
  10598. };
  10599. }(window, document));