leaflet-src.js 431 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513
  1. /* @preserve
  2. * Leaflet 1.9.4, a JS library for interactive maps. https://leafletjs.com
  3. * (c) 2010-2023 Vladimir Agafonkin, (c) 2010-2011 CloudMade
  4. */
  5. (function (global, factory) {
  6. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  7. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  8. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.leaflet = {}));
  9. })(this, (function (exports) { 'use strict';
  10. var version = "1.9.4";
  11. /*
  12. * @namespace Util
  13. *
  14. * Various utility functions, used by Leaflet internally.
  15. */
  16. // @function extend(dest: Object, src?: Object): Object
  17. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  18. function extend(dest) {
  19. var i, j, len, src;
  20. for (j = 1, len = arguments.length; j < len; j++) {
  21. src = arguments[j];
  22. for (i in src) {
  23. dest[i] = src[i];
  24. }
  25. }
  26. return dest;
  27. }
  28. // @function create(proto: Object, properties?: Object): Object
  29. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  30. var create$2 = Object.create || (function () {
  31. function F() {}
  32. return function (proto) {
  33. F.prototype = proto;
  34. return new F();
  35. };
  36. })();
  37. // @function bind(fn: Function, …): Function
  38. // Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
  39. // Has a `L.bind()` shortcut.
  40. function bind(fn, obj) {
  41. var slice = Array.prototype.slice;
  42. if (fn.bind) {
  43. return fn.bind.apply(fn, slice.call(arguments, 1));
  44. }
  45. var args = slice.call(arguments, 2);
  46. return function () {
  47. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  48. };
  49. }
  50. // @property lastId: Number
  51. // Last unique ID used by [`stamp()`](#util-stamp)
  52. var lastId = 0;
  53. // @function stamp(obj: Object): Number
  54. // Returns the unique ID of an object, assigning it one if it doesn't have it.
  55. function stamp(obj) {
  56. if (!('_leaflet_id' in obj)) {
  57. obj['_leaflet_id'] = ++lastId;
  58. }
  59. return obj._leaflet_id;
  60. }
  61. // @function throttle(fn: Function, time: Number, context: Object): Function
  62. // Returns a function which executes function `fn` with the given scope `context`
  63. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  64. // `fn` will be called no more than one time per given amount of `time`. The arguments
  65. // received by the bound function will be any arguments passed when binding the
  66. // function, followed by any arguments passed when invoking the bound function.
  67. // Has an `L.throttle` shortcut.
  68. function throttle(fn, time, context) {
  69. var lock, args, wrapperFn, later;
  70. later = function () {
  71. // reset lock and call if queued
  72. lock = false;
  73. if (args) {
  74. wrapperFn.apply(context, args);
  75. args = false;
  76. }
  77. };
  78. wrapperFn = function () {
  79. if (lock) {
  80. // called too soon, queue to call later
  81. args = arguments;
  82. } else {
  83. // call and lock until later
  84. fn.apply(context, arguments);
  85. setTimeout(later, time);
  86. lock = true;
  87. }
  88. };
  89. return wrapperFn;
  90. }
  91. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  92. // Returns the number `num` modulo `range` in such a way so it lies within
  93. // `range[0]` and `range[1]`. The returned value will be always smaller than
  94. // `range[1]` unless `includeMax` is set to `true`.
  95. function wrapNum(x, range, includeMax) {
  96. var max = range[1],
  97. min = range[0],
  98. d = max - min;
  99. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  100. }
  101. // @function falseFn(): Function
  102. // Returns a function which always returns `false`.
  103. function falseFn() { return false; }
  104. // @function formatNum(num: Number, precision?: Number|false): Number
  105. // Returns the number `num` rounded with specified `precision`.
  106. // The default `precision` value is 6 decimal places.
  107. // `false` can be passed to skip any processing (can be useful to avoid round-off errors).
  108. function formatNum(num, precision) {
  109. if (precision === false) { return num; }
  110. var pow = Math.pow(10, precision === undefined ? 6 : precision);
  111. return Math.round(num * pow) / pow;
  112. }
  113. // @function trim(str: String): String
  114. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  115. function trim(str) {
  116. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  117. }
  118. // @function splitWords(str: String): String[]
  119. // Trims and splits the string on whitespace and returns the array of parts.
  120. function splitWords(str) {
  121. return trim(str).split(/\s+/);
  122. }
  123. // @function setOptions(obj: Object, options: Object): Object
  124. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  125. function setOptions(obj, options) {
  126. if (!Object.prototype.hasOwnProperty.call(obj, 'options')) {
  127. obj.options = obj.options ? create$2(obj.options) : {};
  128. }
  129. for (var i in options) {
  130. obj.options[i] = options[i];
  131. }
  132. return obj.options;
  133. }
  134. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  135. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  136. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  137. // be appended at the end. If `uppercase` is `true`, the parameter names will
  138. // be uppercased (e.g. `'?A=foo&B=bar'`)
  139. function getParamString(obj, existingUrl, uppercase) {
  140. var params = [];
  141. for (var i in obj) {
  142. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  143. }
  144. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  145. }
  146. var templateRe = /\{ *([\w_ -]+) *\}/g;
  147. // @function template(str: String, data: Object): String
  148. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  149. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  150. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  151. // data values — they will be evaluated passing `data` as an argument.
  152. function template(str, data) {
  153. return str.replace(templateRe, function (str, key) {
  154. var value = data[key];
  155. if (value === undefined) {
  156. throw new Error('No value provided for variable ' + str);
  157. } else if (typeof value === 'function') {
  158. value = value(data);
  159. }
  160. return value;
  161. });
  162. }
  163. // @function isArray(obj): Boolean
  164. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  165. var isArray = Array.isArray || function (obj) {
  166. return (Object.prototype.toString.call(obj) === '[object Array]');
  167. };
  168. // @function indexOf(array: Array, el: Object): Number
  169. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  170. function indexOf(array, el) {
  171. for (var i = 0; i < array.length; i++) {
  172. if (array[i] === el) { return i; }
  173. }
  174. return -1;
  175. }
  176. // @property emptyImageUrl: String
  177. // Data URI string containing a base64-encoded empty GIF image.
  178. // Used as a hack to free memory from unused images on WebKit-powered
  179. // mobile devices (by setting image `src` to this string).
  180. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  181. // inspired by https://paulirish.com/2011/requestanimationframe-for-smart-animating/
  182. function getPrefixed(name) {
  183. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  184. }
  185. var lastTime = 0;
  186. // fallback for IE 7-8
  187. function timeoutDefer(fn) {
  188. var time = +new Date(),
  189. timeToCall = Math.max(0, 16 - (time - lastTime));
  190. lastTime = time + timeToCall;
  191. return window.setTimeout(fn, timeToCall);
  192. }
  193. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  194. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  195. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  196. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  197. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  198. // `context` if given. When `immediate` is set, `fn` is called immediately if
  199. // the browser doesn't have native support for
  200. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  201. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  202. function requestAnimFrame(fn, context, immediate) {
  203. if (immediate && requestFn === timeoutDefer) {
  204. fn.call(context);
  205. } else {
  206. return requestFn.call(window, bind(fn, context));
  207. }
  208. }
  209. // @function cancelAnimFrame(id: Number): undefined
  210. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  211. function cancelAnimFrame(id) {
  212. if (id) {
  213. cancelFn.call(window, id);
  214. }
  215. }
  216. var Util = {
  217. __proto__: null,
  218. extend: extend,
  219. create: create$2,
  220. bind: bind,
  221. get lastId () { return lastId; },
  222. stamp: stamp,
  223. throttle: throttle,
  224. wrapNum: wrapNum,
  225. falseFn: falseFn,
  226. formatNum: formatNum,
  227. trim: trim,
  228. splitWords: splitWords,
  229. setOptions: setOptions,
  230. getParamString: getParamString,
  231. template: template,
  232. isArray: isArray,
  233. indexOf: indexOf,
  234. emptyImageUrl: emptyImageUrl,
  235. requestFn: requestFn,
  236. cancelFn: cancelFn,
  237. requestAnimFrame: requestAnimFrame,
  238. cancelAnimFrame: cancelAnimFrame
  239. };
  240. // @class Class
  241. // @aka L.Class
  242. // @section
  243. // @uninheritable
  244. // Thanks to John Resig and Dean Edwards for inspiration!
  245. function Class() {}
  246. Class.extend = function (props) {
  247. // @function extend(props: Object): Function
  248. // [Extends the current class](#class-inheritance) given the properties to be included.
  249. // Returns a Javascript function that is a class constructor (to be called with `new`).
  250. var NewClass = function () {
  251. setOptions(this);
  252. // call the constructor
  253. if (this.initialize) {
  254. this.initialize.apply(this, arguments);
  255. }
  256. // call all constructor hooks
  257. this.callInitHooks();
  258. };
  259. var parentProto = NewClass.__super__ = this.prototype;
  260. var proto = create$2(parentProto);
  261. proto.constructor = NewClass;
  262. NewClass.prototype = proto;
  263. // inherit parent's statics
  264. for (var i in this) {
  265. if (Object.prototype.hasOwnProperty.call(this, i) && i !== 'prototype' && i !== '__super__') {
  266. NewClass[i] = this[i];
  267. }
  268. }
  269. // mix static properties into the class
  270. if (props.statics) {
  271. extend(NewClass, props.statics);
  272. }
  273. // mix includes into the prototype
  274. if (props.includes) {
  275. checkDeprecatedMixinEvents(props.includes);
  276. extend.apply(null, [proto].concat(props.includes));
  277. }
  278. // mix given properties into the prototype
  279. extend(proto, props);
  280. delete proto.statics;
  281. delete proto.includes;
  282. // merge options
  283. if (proto.options) {
  284. proto.options = parentProto.options ? create$2(parentProto.options) : {};
  285. extend(proto.options, props.options);
  286. }
  287. proto._initHooks = [];
  288. // add method for calling all hooks
  289. proto.callInitHooks = function () {
  290. if (this._initHooksCalled) { return; }
  291. if (parentProto.callInitHooks) {
  292. parentProto.callInitHooks.call(this);
  293. }
  294. this._initHooksCalled = true;
  295. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  296. proto._initHooks[i].call(this);
  297. }
  298. };
  299. return NewClass;
  300. };
  301. // @function include(properties: Object): this
  302. // [Includes a mixin](#class-includes) into the current class.
  303. Class.include = function (props) {
  304. var parentOptions = this.prototype.options;
  305. extend(this.prototype, props);
  306. if (props.options) {
  307. this.prototype.options = parentOptions;
  308. this.mergeOptions(props.options);
  309. }
  310. return this;
  311. };
  312. // @function mergeOptions(options: Object): this
  313. // [Merges `options`](#class-options) into the defaults of the class.
  314. Class.mergeOptions = function (options) {
  315. extend(this.prototype.options, options);
  316. return this;
  317. };
  318. // @function addInitHook(fn: Function): this
  319. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  320. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  321. var args = Array.prototype.slice.call(arguments, 1);
  322. var init = typeof fn === 'function' ? fn : function () {
  323. this[fn].apply(this, args);
  324. };
  325. this.prototype._initHooks = this.prototype._initHooks || [];
  326. this.prototype._initHooks.push(init);
  327. return this;
  328. };
  329. function checkDeprecatedMixinEvents(includes) {
  330. /* global L: true */
  331. if (typeof L === 'undefined' || !L || !L.Mixin) { return; }
  332. includes = isArray(includes) ? includes : [includes];
  333. for (var i = 0; i < includes.length; i++) {
  334. if (includes[i] === L.Mixin.Events) {
  335. console.warn('Deprecated include of L.Mixin.Events: ' +
  336. 'this property will be removed in future releases, ' +
  337. 'please inherit from L.Evented instead.', new Error().stack);
  338. }
  339. }
  340. }
  341. /*
  342. * @class Evented
  343. * @aka L.Evented
  344. * @inherits Class
  345. *
  346. * 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).
  347. *
  348. * @example
  349. *
  350. * ```js
  351. * map.on('click', function(e) {
  352. * alert(e.latlng);
  353. * } );
  354. * ```
  355. *
  356. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  357. *
  358. * ```js
  359. * function onClick(e) { ... }
  360. *
  361. * map.on('click', onClick);
  362. * map.off('click', onClick);
  363. * ```
  364. */
  365. var Events = {
  366. /* @method on(type: String, fn: Function, context?: Object): this
  367. * 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'`).
  368. *
  369. * @alternative
  370. * @method on(eventMap: Object): this
  371. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  372. */
  373. on: function (types, fn, context) {
  374. // types can be a map of types/handlers
  375. if (typeof types === 'object') {
  376. for (var type in types) {
  377. // we don't process space-separated events here for performance;
  378. // it's a hot path since Layer uses the on(obj) syntax
  379. this._on(type, types[type], fn);
  380. }
  381. } else {
  382. // types can be a string of space-separated words
  383. types = splitWords(types);
  384. for (var i = 0, len = types.length; i < len; i++) {
  385. this._on(types[i], fn, context);
  386. }
  387. }
  388. return this;
  389. },
  390. /* @method off(type: String, fn?: Function, context?: Object): this
  391. * 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.
  392. *
  393. * @alternative
  394. * @method off(eventMap: Object): this
  395. * Removes a set of type/listener pairs.
  396. *
  397. * @alternative
  398. * @method off: this
  399. * Removes all listeners to all events on the object. This includes implicitly attached events.
  400. */
  401. off: function (types, fn, context) {
  402. if (!arguments.length) {
  403. // clear all listeners if called without arguments
  404. delete this._events;
  405. } else if (typeof types === 'object') {
  406. for (var type in types) {
  407. this._off(type, types[type], fn);
  408. }
  409. } else {
  410. types = splitWords(types);
  411. var removeAll = arguments.length === 1;
  412. for (var i = 0, len = types.length; i < len; i++) {
  413. if (removeAll) {
  414. this._off(types[i]);
  415. } else {
  416. this._off(types[i], fn, context);
  417. }
  418. }
  419. }
  420. return this;
  421. },
  422. // attach listener (without syntactic sugar now)
  423. _on: function (type, fn, context, _once) {
  424. if (typeof fn !== 'function') {
  425. console.warn('wrong listener type: ' + typeof fn);
  426. return;
  427. }
  428. // check if fn already there
  429. if (this._listens(type, fn, context) !== false) {
  430. return;
  431. }
  432. if (context === this) {
  433. // Less memory footprint.
  434. context = undefined;
  435. }
  436. var newListener = {fn: fn, ctx: context};
  437. if (_once) {
  438. newListener.once = true;
  439. }
  440. this._events = this._events || {};
  441. this._events[type] = this._events[type] || [];
  442. this._events[type].push(newListener);
  443. },
  444. _off: function (type, fn, context) {
  445. var listeners,
  446. i,
  447. len;
  448. if (!this._events) {
  449. return;
  450. }
  451. listeners = this._events[type];
  452. if (!listeners) {
  453. return;
  454. }
  455. if (arguments.length === 1) { // remove all
  456. if (this._firingCount) {
  457. // Set all removed listeners to noop
  458. // so they are not called if remove happens in fire
  459. for (i = 0, len = listeners.length; i < len; i++) {
  460. listeners[i].fn = falseFn;
  461. }
  462. }
  463. // clear all listeners for a type if function isn't specified
  464. delete this._events[type];
  465. return;
  466. }
  467. if (typeof fn !== 'function') {
  468. console.warn('wrong listener type: ' + typeof fn);
  469. return;
  470. }
  471. // find fn and remove it
  472. var index = this._listens(type, fn, context);
  473. if (index !== false) {
  474. var listener = listeners[index];
  475. if (this._firingCount) {
  476. // set the removed listener to noop so that's not called if remove happens in fire
  477. listener.fn = falseFn;
  478. /* copy array in case events are being fired */
  479. this._events[type] = listeners = listeners.slice();
  480. }
  481. listeners.splice(index, 1);
  482. }
  483. },
  484. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  485. // Fires an event of the specified type. You can optionally provide a data
  486. // object — the first argument of the listener function will contain its
  487. // properties. The event can optionally be propagated to event parents.
  488. fire: function (type, data, propagate) {
  489. if (!this.listens(type, propagate)) { return this; }
  490. var event = extend({}, data, {
  491. type: type,
  492. target: this,
  493. sourceTarget: data && data.sourceTarget || this
  494. });
  495. if (this._events) {
  496. var listeners = this._events[type];
  497. if (listeners) {
  498. this._firingCount = (this._firingCount + 1) || 1;
  499. for (var i = 0, len = listeners.length; i < len; i++) {
  500. var l = listeners[i];
  501. // off overwrites l.fn, so we need to copy fn to a var
  502. var fn = l.fn;
  503. if (l.once) {
  504. this.off(type, fn, l.ctx);
  505. }
  506. fn.call(l.ctx || this, event);
  507. }
  508. this._firingCount--;
  509. }
  510. }
  511. if (propagate) {
  512. // propagate the event to parents (set with addEventParent)
  513. this._propagateEvent(event);
  514. }
  515. return this;
  516. },
  517. // @method listens(type: String, propagate?: Boolean): Boolean
  518. // @method listens(type: String, fn: Function, context?: Object, propagate?: Boolean): Boolean
  519. // Returns `true` if a particular event type has any listeners attached to it.
  520. // The verification can optionally be propagated, it will return `true` if parents have the listener attached to it.
  521. listens: function (type, fn, context, propagate) {
  522. if (typeof type !== 'string') {
  523. console.warn('"string" type argument expected');
  524. }
  525. // we don't overwrite the input `fn` value, because we need to use it for propagation
  526. var _fn = fn;
  527. if (typeof fn !== 'function') {
  528. propagate = !!fn;
  529. _fn = undefined;
  530. context = undefined;
  531. }
  532. var listeners = this._events && this._events[type];
  533. if (listeners && listeners.length) {
  534. if (this._listens(type, _fn, context) !== false) {
  535. return true;
  536. }
  537. }
  538. if (propagate) {
  539. // also check parents for listeners if event propagates
  540. for (var id in this._eventParents) {
  541. if (this._eventParents[id].listens(type, fn, context, propagate)) { return true; }
  542. }
  543. }
  544. return false;
  545. },
  546. // returns the index (number) or false
  547. _listens: function (type, fn, context) {
  548. if (!this._events) {
  549. return false;
  550. }
  551. var listeners = this._events[type] || [];
  552. if (!fn) {
  553. return !!listeners.length;
  554. }
  555. if (context === this) {
  556. // Less memory footprint.
  557. context = undefined;
  558. }
  559. for (var i = 0, len = listeners.length; i < len; i++) {
  560. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  561. return i;
  562. }
  563. }
  564. return false;
  565. },
  566. // @method once(…): this
  567. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  568. once: function (types, fn, context) {
  569. // types can be a map of types/handlers
  570. if (typeof types === 'object') {
  571. for (var type in types) {
  572. // we don't process space-separated events here for performance;
  573. // it's a hot path since Layer uses the on(obj) syntax
  574. this._on(type, types[type], fn, true);
  575. }
  576. } else {
  577. // types can be a string of space-separated words
  578. types = splitWords(types);
  579. for (var i = 0, len = types.length; i < len; i++) {
  580. this._on(types[i], fn, context, true);
  581. }
  582. }
  583. return this;
  584. },
  585. // @method addEventParent(obj: Evented): this
  586. // Adds an event parent - an `Evented` that will receive propagated events
  587. addEventParent: function (obj) {
  588. this._eventParents = this._eventParents || {};
  589. this._eventParents[stamp(obj)] = obj;
  590. return this;
  591. },
  592. // @method removeEventParent(obj: Evented): this
  593. // Removes an event parent, so it will stop receiving propagated events
  594. removeEventParent: function (obj) {
  595. if (this._eventParents) {
  596. delete this._eventParents[stamp(obj)];
  597. }
  598. return this;
  599. },
  600. _propagateEvent: function (e) {
  601. for (var id in this._eventParents) {
  602. this._eventParents[id].fire(e.type, extend({
  603. layer: e.target,
  604. propagatedFrom: e.target
  605. }, e), true);
  606. }
  607. }
  608. };
  609. // aliases; we should ditch those eventually
  610. // @method addEventListener(…): this
  611. // Alias to [`on(…)`](#evented-on)
  612. Events.addEventListener = Events.on;
  613. // @method removeEventListener(…): this
  614. // Alias to [`off(…)`](#evented-off)
  615. // @method clearAllEventListeners(…): this
  616. // Alias to [`off()`](#evented-off)
  617. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  618. // @method addOneTimeEventListener(…): this
  619. // Alias to [`once(…)`](#evented-once)
  620. Events.addOneTimeEventListener = Events.once;
  621. // @method fireEvent(…): this
  622. // Alias to [`fire(…)`](#evented-fire)
  623. Events.fireEvent = Events.fire;
  624. // @method hasEventListeners(…): Boolean
  625. // Alias to [`listens(…)`](#evented-listens)
  626. Events.hasEventListeners = Events.listens;
  627. var Evented = Class.extend(Events);
  628. /*
  629. * @class Point
  630. * @aka L.Point
  631. *
  632. * Represents a point with `x` and `y` coordinates in pixels.
  633. *
  634. * @example
  635. *
  636. * ```js
  637. * var point = L.point(200, 300);
  638. * ```
  639. *
  640. * 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:
  641. *
  642. * ```js
  643. * map.panBy([200, 300]);
  644. * map.panBy(L.point(200, 300));
  645. * ```
  646. *
  647. * Note that `Point` does not inherit from Leaflet's `Class` object,
  648. * which means new classes can't inherit from it, and new methods
  649. * can't be added to it with the `include` function.
  650. */
  651. function Point(x, y, round) {
  652. // @property x: Number; The `x` coordinate of the point
  653. this.x = (round ? Math.round(x) : x);
  654. // @property y: Number; The `y` coordinate of the point
  655. this.y = (round ? Math.round(y) : y);
  656. }
  657. var trunc = Math.trunc || function (v) {
  658. return v > 0 ? Math.floor(v) : Math.ceil(v);
  659. };
  660. Point.prototype = {
  661. // @method clone(): Point
  662. // Returns a copy of the current point.
  663. clone: function () {
  664. return new Point(this.x, this.y);
  665. },
  666. // @method add(otherPoint: Point): Point
  667. // Returns the result of addition of the current and the given points.
  668. add: function (point) {
  669. // non-destructive, returns a new point
  670. return this.clone()._add(toPoint(point));
  671. },
  672. _add: function (point) {
  673. // destructive, used directly for performance in situations where it's safe to modify existing point
  674. this.x += point.x;
  675. this.y += point.y;
  676. return this;
  677. },
  678. // @method subtract(otherPoint: Point): Point
  679. // Returns the result of subtraction of the given point from the current.
  680. subtract: function (point) {
  681. return this.clone()._subtract(toPoint(point));
  682. },
  683. _subtract: function (point) {
  684. this.x -= point.x;
  685. this.y -= point.y;
  686. return this;
  687. },
  688. // @method divideBy(num: Number): Point
  689. // Returns the result of division of the current point by the given number.
  690. divideBy: function (num) {
  691. return this.clone()._divideBy(num);
  692. },
  693. _divideBy: function (num) {
  694. this.x /= num;
  695. this.y /= num;
  696. return this;
  697. },
  698. // @method multiplyBy(num: Number): Point
  699. // Returns the result of multiplication of the current point by the given number.
  700. multiplyBy: function (num) {
  701. return this.clone()._multiplyBy(num);
  702. },
  703. _multiplyBy: function (num) {
  704. this.x *= num;
  705. this.y *= num;
  706. return this;
  707. },
  708. // @method scaleBy(scale: Point): Point
  709. // Multiply each coordinate of the current point by each coordinate of
  710. // `scale`. In linear algebra terms, multiply the point by the
  711. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  712. // defined by `scale`.
  713. scaleBy: function (point) {
  714. return new Point(this.x * point.x, this.y * point.y);
  715. },
  716. // @method unscaleBy(scale: Point): Point
  717. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  718. // each coordinate of `scale`.
  719. unscaleBy: function (point) {
  720. return new Point(this.x / point.x, this.y / point.y);
  721. },
  722. // @method round(): Point
  723. // Returns a copy of the current point with rounded coordinates.
  724. round: function () {
  725. return this.clone()._round();
  726. },
  727. _round: function () {
  728. this.x = Math.round(this.x);
  729. this.y = Math.round(this.y);
  730. return this;
  731. },
  732. // @method floor(): Point
  733. // Returns a copy of the current point with floored coordinates (rounded down).
  734. floor: function () {
  735. return this.clone()._floor();
  736. },
  737. _floor: function () {
  738. this.x = Math.floor(this.x);
  739. this.y = Math.floor(this.y);
  740. return this;
  741. },
  742. // @method ceil(): Point
  743. // Returns a copy of the current point with ceiled coordinates (rounded up).
  744. ceil: function () {
  745. return this.clone()._ceil();
  746. },
  747. _ceil: function () {
  748. this.x = Math.ceil(this.x);
  749. this.y = Math.ceil(this.y);
  750. return this;
  751. },
  752. // @method trunc(): Point
  753. // Returns a copy of the current point with truncated coordinates (rounded towards zero).
  754. trunc: function () {
  755. return this.clone()._trunc();
  756. },
  757. _trunc: function () {
  758. this.x = trunc(this.x);
  759. this.y = trunc(this.y);
  760. return this;
  761. },
  762. // @method distanceTo(otherPoint: Point): Number
  763. // Returns the cartesian distance between the current and the given points.
  764. distanceTo: function (point) {
  765. point = toPoint(point);
  766. var x = point.x - this.x,
  767. y = point.y - this.y;
  768. return Math.sqrt(x * x + y * y);
  769. },
  770. // @method equals(otherPoint: Point): Boolean
  771. // Returns `true` if the given point has the same coordinates.
  772. equals: function (point) {
  773. point = toPoint(point);
  774. return point.x === this.x &&
  775. point.y === this.y;
  776. },
  777. // @method contains(otherPoint: Point): Boolean
  778. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  779. contains: function (point) {
  780. point = toPoint(point);
  781. return Math.abs(point.x) <= Math.abs(this.x) &&
  782. Math.abs(point.y) <= Math.abs(this.y);
  783. },
  784. // @method toString(): String
  785. // Returns a string representation of the point for debugging purposes.
  786. toString: function () {
  787. return 'Point(' +
  788. formatNum(this.x) + ', ' +
  789. formatNum(this.y) + ')';
  790. }
  791. };
  792. // @factory L.point(x: Number, y: Number, round?: Boolean)
  793. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  794. // @alternative
  795. // @factory L.point(coords: Number[])
  796. // Expects an array of the form `[x, y]` instead.
  797. // @alternative
  798. // @factory L.point(coords: Object)
  799. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  800. function toPoint(x, y, round) {
  801. if (x instanceof Point) {
  802. return x;
  803. }
  804. if (isArray(x)) {
  805. return new Point(x[0], x[1]);
  806. }
  807. if (x === undefined || x === null) {
  808. return x;
  809. }
  810. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  811. return new Point(x.x, x.y);
  812. }
  813. return new Point(x, y, round);
  814. }
  815. /*
  816. * @class Bounds
  817. * @aka L.Bounds
  818. *
  819. * Represents a rectangular area in pixel coordinates.
  820. *
  821. * @example
  822. *
  823. * ```js
  824. * var p1 = L.point(10, 10),
  825. * p2 = L.point(40, 60),
  826. * bounds = L.bounds(p1, p2);
  827. * ```
  828. *
  829. * 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:
  830. *
  831. * ```js
  832. * otherBounds.intersects([[10, 10], [40, 60]]);
  833. * ```
  834. *
  835. * Note that `Bounds` does not inherit from Leaflet's `Class` object,
  836. * which means new classes can't inherit from it, and new methods
  837. * can't be added to it with the `include` function.
  838. */
  839. function Bounds(a, b) {
  840. if (!a) { return; }
  841. var points = b ? [a, b] : a;
  842. for (var i = 0, len = points.length; i < len; i++) {
  843. this.extend(points[i]);
  844. }
  845. }
  846. Bounds.prototype = {
  847. // @method extend(point: Point): this
  848. // Extends the bounds to contain the given point.
  849. // @alternative
  850. // @method extend(otherBounds: Bounds): this
  851. // Extend the bounds to contain the given bounds
  852. extend: function (obj) {
  853. var min2, max2;
  854. if (!obj) { return this; }
  855. if (obj instanceof Point || typeof obj[0] === 'number' || 'x' in obj) {
  856. min2 = max2 = toPoint(obj);
  857. } else {
  858. obj = toBounds(obj);
  859. min2 = obj.min;
  860. max2 = obj.max;
  861. if (!min2 || !max2) { return this; }
  862. }
  863. // @property min: Point
  864. // The top left corner of the rectangle.
  865. // @property max: Point
  866. // The bottom right corner of the rectangle.
  867. if (!this.min && !this.max) {
  868. this.min = min2.clone();
  869. this.max = max2.clone();
  870. } else {
  871. this.min.x = Math.min(min2.x, this.min.x);
  872. this.max.x = Math.max(max2.x, this.max.x);
  873. this.min.y = Math.min(min2.y, this.min.y);
  874. this.max.y = Math.max(max2.y, this.max.y);
  875. }
  876. return this;
  877. },
  878. // @method getCenter(round?: Boolean): Point
  879. // Returns the center point of the bounds.
  880. getCenter: function (round) {
  881. return toPoint(
  882. (this.min.x + this.max.x) / 2,
  883. (this.min.y + this.max.y) / 2, round);
  884. },
  885. // @method getBottomLeft(): Point
  886. // Returns the bottom-left point of the bounds.
  887. getBottomLeft: function () {
  888. return toPoint(this.min.x, this.max.y);
  889. },
  890. // @method getTopRight(): Point
  891. // Returns the top-right point of the bounds.
  892. getTopRight: function () { // -> Point
  893. return toPoint(this.max.x, this.min.y);
  894. },
  895. // @method getTopLeft(): Point
  896. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  897. getTopLeft: function () {
  898. return this.min; // left, top
  899. },
  900. // @method getBottomRight(): Point
  901. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  902. getBottomRight: function () {
  903. return this.max; // right, bottom
  904. },
  905. // @method getSize(): Point
  906. // Returns the size of the given bounds
  907. getSize: function () {
  908. return this.max.subtract(this.min);
  909. },
  910. // @method contains(otherBounds: Bounds): Boolean
  911. // Returns `true` if the rectangle contains the given one.
  912. // @alternative
  913. // @method contains(point: Point): Boolean
  914. // Returns `true` if the rectangle contains the given point.
  915. contains: function (obj) {
  916. var min, max;
  917. if (typeof obj[0] === 'number' || obj instanceof Point) {
  918. obj = toPoint(obj);
  919. } else {
  920. obj = toBounds(obj);
  921. }
  922. if (obj instanceof Bounds) {
  923. min = obj.min;
  924. max = obj.max;
  925. } else {
  926. min = max = obj;
  927. }
  928. return (min.x >= this.min.x) &&
  929. (max.x <= this.max.x) &&
  930. (min.y >= this.min.y) &&
  931. (max.y <= this.max.y);
  932. },
  933. // @method intersects(otherBounds: Bounds): Boolean
  934. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  935. // intersect if they have at least one point in common.
  936. intersects: function (bounds) { // (Bounds) -> Boolean
  937. bounds = toBounds(bounds);
  938. var min = this.min,
  939. max = this.max,
  940. min2 = bounds.min,
  941. max2 = bounds.max,
  942. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  943. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  944. return xIntersects && yIntersects;
  945. },
  946. // @method overlaps(otherBounds: Bounds): Boolean
  947. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  948. // overlap if their intersection is an area.
  949. overlaps: function (bounds) { // (Bounds) -> Boolean
  950. bounds = toBounds(bounds);
  951. var min = this.min,
  952. max = this.max,
  953. min2 = bounds.min,
  954. max2 = bounds.max,
  955. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  956. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  957. return xOverlaps && yOverlaps;
  958. },
  959. // @method isValid(): Boolean
  960. // Returns `true` if the bounds are properly initialized.
  961. isValid: function () {
  962. return !!(this.min && this.max);
  963. },
  964. // @method pad(bufferRatio: Number): Bounds
  965. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  966. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  967. // Negative values will retract the bounds.
  968. pad: function (bufferRatio) {
  969. var min = this.min,
  970. max = this.max,
  971. heightBuffer = Math.abs(min.x - max.x) * bufferRatio,
  972. widthBuffer = Math.abs(min.y - max.y) * bufferRatio;
  973. return toBounds(
  974. toPoint(min.x - heightBuffer, min.y - widthBuffer),
  975. toPoint(max.x + heightBuffer, max.y + widthBuffer));
  976. },
  977. // @method equals(otherBounds: Bounds): Boolean
  978. // Returns `true` if the rectangle is equivalent to the given bounds.
  979. equals: function (bounds) {
  980. if (!bounds) { return false; }
  981. bounds = toBounds(bounds);
  982. return this.min.equals(bounds.getTopLeft()) &&
  983. this.max.equals(bounds.getBottomRight());
  984. },
  985. };
  986. // @factory L.bounds(corner1: Point, corner2: Point)
  987. // Creates a Bounds object from two corners coordinate pairs.
  988. // @alternative
  989. // @factory L.bounds(points: Point[])
  990. // Creates a Bounds object from the given array of points.
  991. function toBounds(a, b) {
  992. if (!a || a instanceof Bounds) {
  993. return a;
  994. }
  995. return new Bounds(a, b);
  996. }
  997. /*
  998. * @class LatLngBounds
  999. * @aka L.LatLngBounds
  1000. *
  1001. * Represents a rectangular geographical area on a map.
  1002. *
  1003. * @example
  1004. *
  1005. * ```js
  1006. * var corner1 = L.latLng(40.712, -74.227),
  1007. * corner2 = L.latLng(40.774, -74.125),
  1008. * bounds = L.latLngBounds(corner1, corner2);
  1009. * ```
  1010. *
  1011. * 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:
  1012. *
  1013. * ```js
  1014. * map.fitBounds([
  1015. * [40.712, -74.227],
  1016. * [40.774, -74.125]
  1017. * ]);
  1018. * ```
  1019. *
  1020. * 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.
  1021. *
  1022. * Note that `LatLngBounds` does not inherit from Leaflet's `Class` object,
  1023. * which means new classes can't inherit from it, and new methods
  1024. * can't be added to it with the `include` function.
  1025. */
  1026. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  1027. if (!corner1) { return; }
  1028. var latlngs = corner2 ? [corner1, corner2] : corner1;
  1029. for (var i = 0, len = latlngs.length; i < len; i++) {
  1030. this.extend(latlngs[i]);
  1031. }
  1032. }
  1033. LatLngBounds.prototype = {
  1034. // @method extend(latlng: LatLng): this
  1035. // Extend the bounds to contain the given point
  1036. // @alternative
  1037. // @method extend(otherBounds: LatLngBounds): this
  1038. // Extend the bounds to contain the given bounds
  1039. extend: function (obj) {
  1040. var sw = this._southWest,
  1041. ne = this._northEast,
  1042. sw2, ne2;
  1043. if (obj instanceof LatLng) {
  1044. sw2 = obj;
  1045. ne2 = obj;
  1046. } else if (obj instanceof LatLngBounds) {
  1047. sw2 = obj._southWest;
  1048. ne2 = obj._northEast;
  1049. if (!sw2 || !ne2) { return this; }
  1050. } else {
  1051. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  1052. }
  1053. if (!sw && !ne) {
  1054. this._southWest = new LatLng(sw2.lat, sw2.lng);
  1055. this._northEast = new LatLng(ne2.lat, ne2.lng);
  1056. } else {
  1057. sw.lat = Math.min(sw2.lat, sw.lat);
  1058. sw.lng = Math.min(sw2.lng, sw.lng);
  1059. ne.lat = Math.max(ne2.lat, ne.lat);
  1060. ne.lng = Math.max(ne2.lng, ne.lng);
  1061. }
  1062. return this;
  1063. },
  1064. // @method pad(bufferRatio: Number): LatLngBounds
  1065. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  1066. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  1067. // Negative values will retract the bounds.
  1068. pad: function (bufferRatio) {
  1069. var sw = this._southWest,
  1070. ne = this._northEast,
  1071. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  1072. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  1073. return new LatLngBounds(
  1074. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  1075. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  1076. },
  1077. // @method getCenter(): LatLng
  1078. // Returns the center point of the bounds.
  1079. getCenter: function () {
  1080. return new LatLng(
  1081. (this._southWest.lat + this._northEast.lat) / 2,
  1082. (this._southWest.lng + this._northEast.lng) / 2);
  1083. },
  1084. // @method getSouthWest(): LatLng
  1085. // Returns the south-west point of the bounds.
  1086. getSouthWest: function () {
  1087. return this._southWest;
  1088. },
  1089. // @method getNorthEast(): LatLng
  1090. // Returns the north-east point of the bounds.
  1091. getNorthEast: function () {
  1092. return this._northEast;
  1093. },
  1094. // @method getNorthWest(): LatLng
  1095. // Returns the north-west point of the bounds.
  1096. getNorthWest: function () {
  1097. return new LatLng(this.getNorth(), this.getWest());
  1098. },
  1099. // @method getSouthEast(): LatLng
  1100. // Returns the south-east point of the bounds.
  1101. getSouthEast: function () {
  1102. return new LatLng(this.getSouth(), this.getEast());
  1103. },
  1104. // @method getWest(): Number
  1105. // Returns the west longitude of the bounds
  1106. getWest: function () {
  1107. return this._southWest.lng;
  1108. },
  1109. // @method getSouth(): Number
  1110. // Returns the south latitude of the bounds
  1111. getSouth: function () {
  1112. return this._southWest.lat;
  1113. },
  1114. // @method getEast(): Number
  1115. // Returns the east longitude of the bounds
  1116. getEast: function () {
  1117. return this._northEast.lng;
  1118. },
  1119. // @method getNorth(): Number
  1120. // Returns the north latitude of the bounds
  1121. getNorth: function () {
  1122. return this._northEast.lat;
  1123. },
  1124. // @method contains(otherBounds: LatLngBounds): Boolean
  1125. // Returns `true` if the rectangle contains the given one.
  1126. // @alternative
  1127. // @method contains (latlng: LatLng): Boolean
  1128. // Returns `true` if the rectangle contains the given point.
  1129. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1130. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1131. obj = toLatLng(obj);
  1132. } else {
  1133. obj = toLatLngBounds(obj);
  1134. }
  1135. var sw = this._southWest,
  1136. ne = this._northEast,
  1137. sw2, ne2;
  1138. if (obj instanceof LatLngBounds) {
  1139. sw2 = obj.getSouthWest();
  1140. ne2 = obj.getNorthEast();
  1141. } else {
  1142. sw2 = ne2 = obj;
  1143. }
  1144. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1145. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1146. },
  1147. // @method intersects(otherBounds: LatLngBounds): Boolean
  1148. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1149. intersects: function (bounds) {
  1150. bounds = toLatLngBounds(bounds);
  1151. var sw = this._southWest,
  1152. ne = this._northEast,
  1153. sw2 = bounds.getSouthWest(),
  1154. ne2 = bounds.getNorthEast(),
  1155. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1156. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1157. return latIntersects && lngIntersects;
  1158. },
  1159. // @method overlaps(otherBounds: LatLngBounds): Boolean
  1160. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1161. overlaps: function (bounds) {
  1162. bounds = toLatLngBounds(bounds);
  1163. var sw = this._southWest,
  1164. ne = this._northEast,
  1165. sw2 = bounds.getSouthWest(),
  1166. ne2 = bounds.getNorthEast(),
  1167. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1168. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1169. return latOverlaps && lngOverlaps;
  1170. },
  1171. // @method toBBoxString(): String
  1172. // 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.
  1173. toBBoxString: function () {
  1174. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1175. },
  1176. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1177. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.
  1178. equals: function (bounds, maxMargin) {
  1179. if (!bounds) { return false; }
  1180. bounds = toLatLngBounds(bounds);
  1181. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1182. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1183. },
  1184. // @method isValid(): Boolean
  1185. // Returns `true` if the bounds are properly initialized.
  1186. isValid: function () {
  1187. return !!(this._southWest && this._northEast);
  1188. }
  1189. };
  1190. // TODO International date line?
  1191. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1192. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1193. // @alternative
  1194. // @factory L.latLngBounds(latlngs: LatLng[])
  1195. // 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).
  1196. function toLatLngBounds(a, b) {
  1197. if (a instanceof LatLngBounds) {
  1198. return a;
  1199. }
  1200. return new LatLngBounds(a, b);
  1201. }
  1202. /* @class LatLng
  1203. * @aka L.LatLng
  1204. *
  1205. * Represents a geographical point with a certain latitude and longitude.
  1206. *
  1207. * @example
  1208. *
  1209. * ```
  1210. * var latlng = L.latLng(50.5, 30.5);
  1211. * ```
  1212. *
  1213. * 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:
  1214. *
  1215. * ```
  1216. * map.panTo([50, 30]);
  1217. * map.panTo({lon: 30, lat: 50});
  1218. * map.panTo({lat: 50, lng: 30});
  1219. * map.panTo(L.latLng(50, 30));
  1220. * ```
  1221. *
  1222. * Note that `LatLng` does not inherit from Leaflet's `Class` object,
  1223. * which means new classes can't inherit from it, and new methods
  1224. * can't be added to it with the `include` function.
  1225. */
  1226. function LatLng(lat, lng, alt) {
  1227. if (isNaN(lat) || isNaN(lng)) {
  1228. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1229. }
  1230. // @property lat: Number
  1231. // Latitude in degrees
  1232. this.lat = +lat;
  1233. // @property lng: Number
  1234. // Longitude in degrees
  1235. this.lng = +lng;
  1236. // @property alt: Number
  1237. // Altitude in meters (optional)
  1238. if (alt !== undefined) {
  1239. this.alt = +alt;
  1240. }
  1241. }
  1242. LatLng.prototype = {
  1243. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1244. // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.
  1245. equals: function (obj, maxMargin) {
  1246. if (!obj) { return false; }
  1247. obj = toLatLng(obj);
  1248. var margin = Math.max(
  1249. Math.abs(this.lat - obj.lat),
  1250. Math.abs(this.lng - obj.lng));
  1251. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1252. },
  1253. // @method toString(): String
  1254. // Returns a string representation of the point (for debugging purposes).
  1255. toString: function (precision) {
  1256. return 'LatLng(' +
  1257. formatNum(this.lat, precision) + ', ' +
  1258. formatNum(this.lng, precision) + ')';
  1259. },
  1260. // @method distanceTo(otherLatLng: LatLng): Number
  1261. // Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).
  1262. distanceTo: function (other) {
  1263. return Earth.distance(this, toLatLng(other));
  1264. },
  1265. // @method wrap(): LatLng
  1266. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1267. wrap: function () {
  1268. return Earth.wrapLatLng(this);
  1269. },
  1270. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1271. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1272. toBounds: function (sizeInMeters) {
  1273. var latAccuracy = 180 * sizeInMeters / 40075017,
  1274. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1275. return toLatLngBounds(
  1276. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1277. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1278. },
  1279. clone: function () {
  1280. return new LatLng(this.lat, this.lng, this.alt);
  1281. }
  1282. };
  1283. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1284. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1285. // @alternative
  1286. // @factory L.latLng(coords: Array): LatLng
  1287. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1288. // @alternative
  1289. // @factory L.latLng(coords: Object): LatLng
  1290. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1291. function toLatLng(a, b, c) {
  1292. if (a instanceof LatLng) {
  1293. return a;
  1294. }
  1295. if (isArray(a) && typeof a[0] !== 'object') {
  1296. if (a.length === 3) {
  1297. return new LatLng(a[0], a[1], a[2]);
  1298. }
  1299. if (a.length === 2) {
  1300. return new LatLng(a[0], a[1]);
  1301. }
  1302. return null;
  1303. }
  1304. if (a === undefined || a === null) {
  1305. return a;
  1306. }
  1307. if (typeof a === 'object' && 'lat' in a) {
  1308. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1309. }
  1310. if (b === undefined) {
  1311. return null;
  1312. }
  1313. return new LatLng(a, b, c);
  1314. }
  1315. /*
  1316. * @namespace CRS
  1317. * @crs L.CRS.Base
  1318. * Object that defines coordinate reference systems for projecting
  1319. * geographical points into pixel (screen) coordinates and back (and to
  1320. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1321. * [spatial reference system](https://en.wikipedia.org/wiki/Spatial_reference_system).
  1322. *
  1323. * Leaflet defines the most usual CRSs by default. If you want to use a
  1324. * CRS not defined by default, take a look at the
  1325. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1326. *
  1327. * Note that the CRS instances do not inherit from Leaflet's `Class` object,
  1328. * and can't be instantiated. Also, new classes can't inherit from them,
  1329. * and methods can't be added to them with the `include` function.
  1330. */
  1331. var CRS = {
  1332. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1333. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1334. latLngToPoint: function (latlng, zoom) {
  1335. var projectedPoint = this.projection.project(latlng),
  1336. scale = this.scale(zoom);
  1337. return this.transformation._transform(projectedPoint, scale);
  1338. },
  1339. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1340. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1341. // zoom into geographical coordinates.
  1342. pointToLatLng: function (point, zoom) {
  1343. var scale = this.scale(zoom),
  1344. untransformedPoint = this.transformation.untransform(point, scale);
  1345. return this.projection.unproject(untransformedPoint);
  1346. },
  1347. // @method project(latlng: LatLng): Point
  1348. // Projects geographical coordinates into coordinates in units accepted for
  1349. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1350. project: function (latlng) {
  1351. return this.projection.project(latlng);
  1352. },
  1353. // @method unproject(point: Point): LatLng
  1354. // Given a projected coordinate returns the corresponding LatLng.
  1355. // The inverse of `project`.
  1356. unproject: function (point) {
  1357. return this.projection.unproject(point);
  1358. },
  1359. // @method scale(zoom: Number): Number
  1360. // Returns the scale used when transforming projected coordinates into
  1361. // pixel coordinates for a particular zoom. For example, it returns
  1362. // `256 * 2^zoom` for Mercator-based CRS.
  1363. scale: function (zoom) {
  1364. return 256 * Math.pow(2, zoom);
  1365. },
  1366. // @method zoom(scale: Number): Number
  1367. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1368. // factor of `scale`.
  1369. zoom: function (scale) {
  1370. return Math.log(scale / 256) / Math.LN2;
  1371. },
  1372. // @method getProjectedBounds(zoom: Number): Bounds
  1373. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1374. getProjectedBounds: function (zoom) {
  1375. if (this.infinite) { return null; }
  1376. var b = this.projection.bounds,
  1377. s = this.scale(zoom),
  1378. min = this.transformation.transform(b.min, s),
  1379. max = this.transformation.transform(b.max, s);
  1380. return new Bounds(min, max);
  1381. },
  1382. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1383. // Returns the distance between two geographical coordinates.
  1384. // @property code: String
  1385. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1386. //
  1387. // @property wrapLng: Number[]
  1388. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1389. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1390. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1391. //
  1392. // @property wrapLat: Number[]
  1393. // Like `wrapLng`, but for the latitude (vertical) axis.
  1394. // wrapLng: [min, max],
  1395. // wrapLat: [min, max],
  1396. // @property infinite: Boolean
  1397. // If true, the coordinate space will be unbounded (infinite in both axes)
  1398. infinite: false,
  1399. // @method wrapLatLng(latlng: LatLng): LatLng
  1400. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1401. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1402. wrapLatLng: function (latlng) {
  1403. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1404. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1405. alt = latlng.alt;
  1406. return new LatLng(lat, lng, alt);
  1407. },
  1408. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1409. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1410. // that its center is within the CRS's bounds.
  1411. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1412. wrapLatLngBounds: function (bounds) {
  1413. var center = bounds.getCenter(),
  1414. newCenter = this.wrapLatLng(center),
  1415. latShift = center.lat - newCenter.lat,
  1416. lngShift = center.lng - newCenter.lng;
  1417. if (latShift === 0 && lngShift === 0) {
  1418. return bounds;
  1419. }
  1420. var sw = bounds.getSouthWest(),
  1421. ne = bounds.getNorthEast(),
  1422. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1423. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1424. return new LatLngBounds(newSw, newNe);
  1425. }
  1426. };
  1427. /*
  1428. * @namespace CRS
  1429. * @crs L.CRS.Earth
  1430. *
  1431. * Serves as the base for CRS that are global such that they cover the earth.
  1432. * Can only be used as the base for other CRS and cannot be used directly,
  1433. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1434. * meters.
  1435. */
  1436. var Earth = extend({}, CRS, {
  1437. wrapLng: [-180, 180],
  1438. // Mean Earth Radius, as recommended for use by
  1439. // the International Union of Geodesy and Geophysics,
  1440. // see https://rosettacode.org/wiki/Haversine_formula
  1441. R: 6371000,
  1442. // distance between two geographical points using spherical law of cosines approximation
  1443. distance: function (latlng1, latlng2) {
  1444. var rad = Math.PI / 180,
  1445. lat1 = latlng1.lat * rad,
  1446. lat2 = latlng2.lat * rad,
  1447. sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
  1448. sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
  1449. a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
  1450. c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1451. return this.R * c;
  1452. }
  1453. });
  1454. /*
  1455. * @namespace Projection
  1456. * @projection L.Projection.SphericalMercator
  1457. *
  1458. * Spherical Mercator projection — the most common projection for online maps,
  1459. * used by almost all free and commercial tile providers. Assumes that Earth is
  1460. * a sphere. Used by the `EPSG:3857` CRS.
  1461. */
  1462. var earthRadius = 6378137;
  1463. var SphericalMercator = {
  1464. R: earthRadius,
  1465. MAX_LATITUDE: 85.0511287798,
  1466. project: function (latlng) {
  1467. var d = Math.PI / 180,
  1468. max = this.MAX_LATITUDE,
  1469. lat = Math.max(Math.min(max, latlng.lat), -max),
  1470. sin = Math.sin(lat * d);
  1471. return new Point(
  1472. this.R * latlng.lng * d,
  1473. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1474. },
  1475. unproject: function (point) {
  1476. var d = 180 / Math.PI;
  1477. return new LatLng(
  1478. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1479. point.x * d / this.R);
  1480. },
  1481. bounds: (function () {
  1482. var d = earthRadius * Math.PI;
  1483. return new Bounds([-d, -d], [d, d]);
  1484. })()
  1485. };
  1486. /*
  1487. * @class Transformation
  1488. * @aka L.Transformation
  1489. *
  1490. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1491. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1492. * the reverse. Used by Leaflet in its projections code.
  1493. *
  1494. * @example
  1495. *
  1496. * ```js
  1497. * var transformation = L.transformation(2, 5, -1, 10),
  1498. * p = L.point(1, 2),
  1499. * p2 = transformation.transform(p), // L.point(7, 8)
  1500. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1501. * ```
  1502. */
  1503. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1504. // Creates a `Transformation` object with the given coefficients.
  1505. function Transformation(a, b, c, d) {
  1506. if (isArray(a)) {
  1507. // use array properties
  1508. this._a = a[0];
  1509. this._b = a[1];
  1510. this._c = a[2];
  1511. this._d = a[3];
  1512. return;
  1513. }
  1514. this._a = a;
  1515. this._b = b;
  1516. this._c = c;
  1517. this._d = d;
  1518. }
  1519. Transformation.prototype = {
  1520. // @method transform(point: Point, scale?: Number): Point
  1521. // Returns a transformed point, optionally multiplied by the given scale.
  1522. // Only accepts actual `L.Point` instances, not arrays.
  1523. transform: function (point, scale) { // (Point, Number) -> Point
  1524. return this._transform(point.clone(), scale);
  1525. },
  1526. // destructive transform (faster)
  1527. _transform: function (point, scale) {
  1528. scale = scale || 1;
  1529. point.x = scale * (this._a * point.x + this._b);
  1530. point.y = scale * (this._c * point.y + this._d);
  1531. return point;
  1532. },
  1533. // @method untransform(point: Point, scale?: Number): Point
  1534. // Returns the reverse transformation of the given point, optionally divided
  1535. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1536. untransform: function (point, scale) {
  1537. scale = scale || 1;
  1538. return new Point(
  1539. (point.x / scale - this._b) / this._a,
  1540. (point.y / scale - this._d) / this._c);
  1541. }
  1542. };
  1543. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1544. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1545. // Instantiates a Transformation object with the given coefficients.
  1546. // @alternative
  1547. // @factory L.transformation(coefficients: Array): Transformation
  1548. // Expects an coefficients array of the form
  1549. // `[a: Number, b: Number, c: Number, d: Number]`.
  1550. function toTransformation(a, b, c, d) {
  1551. return new Transformation(a, b, c, d);
  1552. }
  1553. /*
  1554. * @namespace CRS
  1555. * @crs L.CRS.EPSG3857
  1556. *
  1557. * The most common CRS for online maps, used by almost all free and commercial
  1558. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1559. * Map's `crs` option.
  1560. */
  1561. var EPSG3857 = extend({}, Earth, {
  1562. code: 'EPSG:3857',
  1563. projection: SphericalMercator,
  1564. transformation: (function () {
  1565. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1566. return toTransformation(scale, 0.5, -scale, 0.5);
  1567. }())
  1568. });
  1569. var EPSG900913 = extend({}, EPSG3857, {
  1570. code: 'EPSG:900913'
  1571. });
  1572. // @namespace SVG; @section
  1573. // There are several static functions which can be called without instantiating L.SVG:
  1574. // @function create(name: String): SVGElement
  1575. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1576. // corresponding to the class name passed. For example, using 'line' will return
  1577. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1578. function svgCreate(name) {
  1579. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1580. }
  1581. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1582. // Generates a SVG path string for multiple rings, with each ring turning
  1583. // into "M..L..L.." instructions
  1584. function pointsToPath(rings, closed) {
  1585. var str = '',
  1586. i, j, len, len2, points, p;
  1587. for (i = 0, len = rings.length; i < len; i++) {
  1588. points = rings[i];
  1589. for (j = 0, len2 = points.length; j < len2; j++) {
  1590. p = points[j];
  1591. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1592. }
  1593. // closes the ring for polygons; "x" is VML syntax
  1594. str += closed ? (Browser.svg ? 'z' : 'x') : '';
  1595. }
  1596. // SVG complains about empty path strings
  1597. return str || 'M0 0';
  1598. }
  1599. /*
  1600. * @namespace Browser
  1601. * @aka L.Browser
  1602. *
  1603. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1604. *
  1605. * @example
  1606. *
  1607. * ```js
  1608. * if (L.Browser.ielt9) {
  1609. * alert('Upgrade your browser, dude!');
  1610. * }
  1611. * ```
  1612. */
  1613. var style = document.documentElement.style;
  1614. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1615. var ie = 'ActiveXObject' in window;
  1616. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1617. var ielt9 = ie && !document.addEventListener;
  1618. // @property edge: Boolean; `true` for the Edge web browser.
  1619. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1620. // @property webkit: Boolean;
  1621. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1622. var webkit = userAgentContains('webkit');
  1623. // @property android: Boolean
  1624. // **Deprecated.** `true` for any browser running on an Android platform.
  1625. var android = userAgentContains('android');
  1626. // @property android23: Boolean; **Deprecated.** `true` for browsers running on Android 2 or Android 3.
  1627. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1628. /* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */
  1629. var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit
  1630. // @property androidStock: Boolean; **Deprecated.** `true` for the Android stock browser (i.e. not Chrome)
  1631. var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);
  1632. // @property opera: Boolean; `true` for the Opera browser
  1633. var opera = !!window.opera;
  1634. // @property chrome: Boolean; `true` for the Chrome browser.
  1635. var chrome = !edge && userAgentContains('chrome');
  1636. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1637. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1638. // @property safari: Boolean; `true` for the Safari browser.
  1639. var safari = !chrome && userAgentContains('safari');
  1640. var phantom = userAgentContains('phantom');
  1641. // @property opera12: Boolean
  1642. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1643. var opera12 = 'OTransition' in style;
  1644. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1645. var win = navigator.platform.indexOf('Win') === 0;
  1646. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1647. var ie3d = ie && ('transition' in style);
  1648. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1649. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1650. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1651. var gecko3d = 'MozPerspective' in style;
  1652. // @property any3d: Boolean
  1653. // `true` for all browsers supporting CSS transforms.
  1654. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1655. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1656. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1657. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1658. var mobileWebkit = mobile && webkit;
  1659. // @property mobileWebkit3d: Boolean
  1660. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1661. var mobileWebkit3d = mobile && webkit3d;
  1662. // @property msPointer: Boolean
  1663. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1664. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1665. // @property pointer: Boolean
  1666. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1667. var pointer = !!(window.PointerEvent || msPointer);
  1668. // @property touchNative: Boolean
  1669. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1670. // **This does not necessarily mean** that the browser is running in a computer with
  1671. // a touchscreen, it only means that the browser is capable of understanding
  1672. // touch events.
  1673. var touchNative = 'ontouchstart' in window || !!window.TouchEvent;
  1674. // @property touch: Boolean
  1675. // `true` for all browsers supporting either [touch](#browser-touch) or [pointer](#browser-pointer) events.
  1676. // Note: pointer events will be preferred (if available), and processed for all `touch*` listeners.
  1677. var touch = !window.L_NO_TOUCH && (touchNative || pointer);
  1678. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1679. var mobileOpera = mobile && opera;
  1680. // @property mobileGecko: Boolean
  1681. // `true` for gecko-based browsers running in a mobile device.
  1682. var mobileGecko = mobile && gecko;
  1683. // @property retina: Boolean
  1684. // `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%.
  1685. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1686. // @property passiveEvents: Boolean
  1687. // `true` for browsers that support passive events.
  1688. var passiveEvents = (function () {
  1689. var supportsPassiveOption = false;
  1690. try {
  1691. var opts = Object.defineProperty({}, 'passive', {
  1692. get: function () { // eslint-disable-line getter-return
  1693. supportsPassiveOption = true;
  1694. }
  1695. });
  1696. window.addEventListener('testPassiveEventSupport', falseFn, opts);
  1697. window.removeEventListener('testPassiveEventSupport', falseFn, opts);
  1698. } catch (e) {
  1699. // Errors can safely be ignored since this is only a browser support test.
  1700. }
  1701. return supportsPassiveOption;
  1702. }());
  1703. // @property canvas: Boolean
  1704. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1705. var canvas$1 = (function () {
  1706. return !!document.createElement('canvas').getContext;
  1707. }());
  1708. // @property svg: Boolean
  1709. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1710. var svg$1 = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1711. var inlineSvg = !!svg$1 && (function () {
  1712. var div = document.createElement('div');
  1713. div.innerHTML = '<svg/>';
  1714. return (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg';
  1715. })();
  1716. // @property vml: Boolean
  1717. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1718. var vml = !svg$1 && (function () {
  1719. try {
  1720. var div = document.createElement('div');
  1721. div.innerHTML = '<v:shape adj="1"/>';
  1722. var shape = div.firstChild;
  1723. shape.style.behavior = 'url(#default#VML)';
  1724. return shape && (typeof shape.adj === 'object');
  1725. } catch (e) {
  1726. return false;
  1727. }
  1728. }());
  1729. // @property mac: Boolean; `true` when the browser is running in a Mac platform
  1730. var mac = navigator.platform.indexOf('Mac') === 0;
  1731. // @property mac: Boolean; `true` when the browser is running in a Linux platform
  1732. var linux = navigator.platform.indexOf('Linux') === 0;
  1733. function userAgentContains(str) {
  1734. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1735. }
  1736. var Browser = {
  1737. ie: ie,
  1738. ielt9: ielt9,
  1739. edge: edge,
  1740. webkit: webkit,
  1741. android: android,
  1742. android23: android23,
  1743. androidStock: androidStock,
  1744. opera: opera,
  1745. chrome: chrome,
  1746. gecko: gecko,
  1747. safari: safari,
  1748. phantom: phantom,
  1749. opera12: opera12,
  1750. win: win,
  1751. ie3d: ie3d,
  1752. webkit3d: webkit3d,
  1753. gecko3d: gecko3d,
  1754. any3d: any3d,
  1755. mobile: mobile,
  1756. mobileWebkit: mobileWebkit,
  1757. mobileWebkit3d: mobileWebkit3d,
  1758. msPointer: msPointer,
  1759. pointer: pointer,
  1760. touch: touch,
  1761. touchNative: touchNative,
  1762. mobileOpera: mobileOpera,
  1763. mobileGecko: mobileGecko,
  1764. retina: retina,
  1765. passiveEvents: passiveEvents,
  1766. canvas: canvas$1,
  1767. svg: svg$1,
  1768. vml: vml,
  1769. inlineSvg: inlineSvg,
  1770. mac: mac,
  1771. linux: linux
  1772. };
  1773. /*
  1774. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1775. */
  1776. var POINTER_DOWN = Browser.msPointer ? 'MSPointerDown' : 'pointerdown';
  1777. var POINTER_MOVE = Browser.msPointer ? 'MSPointerMove' : 'pointermove';
  1778. var POINTER_UP = Browser.msPointer ? 'MSPointerUp' : 'pointerup';
  1779. var POINTER_CANCEL = Browser.msPointer ? 'MSPointerCancel' : 'pointercancel';
  1780. var pEvent = {
  1781. touchstart : POINTER_DOWN,
  1782. touchmove : POINTER_MOVE,
  1783. touchend : POINTER_UP,
  1784. touchcancel : POINTER_CANCEL
  1785. };
  1786. var handle = {
  1787. touchstart : _onPointerStart,
  1788. touchmove : _handlePointer,
  1789. touchend : _handlePointer,
  1790. touchcancel : _handlePointer
  1791. };
  1792. var _pointers = {};
  1793. var _pointerDocListener = false;
  1794. // Provides a touch events wrapper for (ms)pointer events.
  1795. // ref https://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1796. function addPointerListener(obj, type, handler) {
  1797. if (type === 'touchstart') {
  1798. _addPointerDocListener();
  1799. }
  1800. if (!handle[type]) {
  1801. console.warn('wrong event specified:', type);
  1802. return falseFn;
  1803. }
  1804. handler = handle[type].bind(this, handler);
  1805. obj.addEventListener(pEvent[type], handler, false);
  1806. return handler;
  1807. }
  1808. function removePointerListener(obj, type, handler) {
  1809. if (!pEvent[type]) {
  1810. console.warn('wrong event specified:', type);
  1811. return;
  1812. }
  1813. obj.removeEventListener(pEvent[type], handler, false);
  1814. }
  1815. function _globalPointerDown(e) {
  1816. _pointers[e.pointerId] = e;
  1817. }
  1818. function _globalPointerMove(e) {
  1819. if (_pointers[e.pointerId]) {
  1820. _pointers[e.pointerId] = e;
  1821. }
  1822. }
  1823. function _globalPointerUp(e) {
  1824. delete _pointers[e.pointerId];
  1825. }
  1826. function _addPointerDocListener() {
  1827. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1828. if (!_pointerDocListener) {
  1829. // we listen document as any drags that end by moving the touch off the screen get fired there
  1830. document.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1831. document.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1832. document.addEventListener(POINTER_UP, _globalPointerUp, true);
  1833. document.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1834. _pointerDocListener = true;
  1835. }
  1836. }
  1837. function _handlePointer(handler, e) {
  1838. if (e.pointerType === (e.MSPOINTER_TYPE_MOUSE || 'mouse')) { return; }
  1839. e.touches = [];
  1840. for (var i in _pointers) {
  1841. e.touches.push(_pointers[i]);
  1842. }
  1843. e.changedTouches = [e];
  1844. handler(e);
  1845. }
  1846. function _onPointerStart(handler, e) {
  1847. // IE10 specific: MsTouch needs preventDefault. See #2000
  1848. if (e.MSPOINTER_TYPE_TOUCH && e.pointerType === e.MSPOINTER_TYPE_TOUCH) {
  1849. preventDefault(e);
  1850. }
  1851. _handlePointer(handler, e);
  1852. }
  1853. /*
  1854. * Extends the event handling code with double tap support for mobile browsers.
  1855. *
  1856. * Note: currently most browsers fire native dblclick, with only a few exceptions
  1857. * (see https://github.com/Leaflet/Leaflet/issues/7012#issuecomment-595087386)
  1858. */
  1859. function makeDblclick(event) {
  1860. // in modern browsers `type` cannot be just overridden:
  1861. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only
  1862. var newEvent = {},
  1863. prop, i;
  1864. for (i in event) {
  1865. prop = event[i];
  1866. newEvent[i] = prop && prop.bind ? prop.bind(event) : prop;
  1867. }
  1868. event = newEvent;
  1869. newEvent.type = 'dblclick';
  1870. newEvent.detail = 2;
  1871. newEvent.isTrusted = false;
  1872. newEvent._simulated = true; // for debug purposes
  1873. return newEvent;
  1874. }
  1875. var delay = 200;
  1876. function addDoubleTapListener(obj, handler) {
  1877. // Most browsers handle double tap natively
  1878. obj.addEventListener('dblclick', handler);
  1879. // On some platforms the browser doesn't fire native dblclicks for touch events.
  1880. // It seems that in all such cases `detail` property of `click` event is always `1`.
  1881. // So here we rely on that fact to avoid excessive 'dblclick' simulation when not needed.
  1882. var last = 0,
  1883. detail;
  1884. function simDblclick(e) {
  1885. if (e.detail !== 1) {
  1886. detail = e.detail; // keep in sync to avoid false dblclick in some cases
  1887. return;
  1888. }
  1889. if (e.pointerType === 'mouse' ||
  1890. (e.sourceCapabilities && !e.sourceCapabilities.firesTouchEvents)) {
  1891. return;
  1892. }
  1893. // When clicking on an <input>, the browser generates a click on its
  1894. // <label> (and vice versa) triggering two clicks in quick succession.
  1895. // This ignores clicks on elements which are a label with a 'for'
  1896. // attribute (or children of such a label), but not children of
  1897. // a <input>.
  1898. var path = getPropagationPath(e);
  1899. if (path.some(function (el) {
  1900. return el instanceof HTMLLabelElement && el.attributes.for;
  1901. }) &&
  1902. !path.some(function (el) {
  1903. return (
  1904. el instanceof HTMLInputElement ||
  1905. el instanceof HTMLSelectElement
  1906. );
  1907. })
  1908. ) {
  1909. return;
  1910. }
  1911. var now = Date.now();
  1912. if (now - last <= delay) {
  1913. detail++;
  1914. if (detail === 2) {
  1915. handler(makeDblclick(e));
  1916. }
  1917. } else {
  1918. detail = 1;
  1919. }
  1920. last = now;
  1921. }
  1922. obj.addEventListener('click', simDblclick);
  1923. return {
  1924. dblclick: handler,
  1925. simDblclick: simDblclick
  1926. };
  1927. }
  1928. function removeDoubleTapListener(obj, handlers) {
  1929. obj.removeEventListener('dblclick', handlers.dblclick);
  1930. obj.removeEventListener('click', handlers.simDblclick);
  1931. }
  1932. /*
  1933. * @namespace DomUtil
  1934. *
  1935. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1936. * tree, used by Leaflet internally.
  1937. *
  1938. * Most functions expecting or returning a `HTMLElement` also work for
  1939. * SVG elements. The only difference is that classes refer to CSS classes
  1940. * in HTML and SVG classes in SVG.
  1941. */
  1942. // @property TRANSFORM: String
  1943. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  1944. var TRANSFORM = testProp(
  1945. ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1946. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1947. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1948. // @property TRANSITION: String
  1949. // Vendor-prefixed transition style name.
  1950. var TRANSITION = testProp(
  1951. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1952. // @property TRANSITION_END: String
  1953. // Vendor-prefixed transitionend event name.
  1954. var TRANSITION_END =
  1955. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  1956. // @function get(id: String|HTMLElement): HTMLElement
  1957. // Returns an element given its DOM id, or returns the element itself
  1958. // if it was passed directly.
  1959. function get(id) {
  1960. return typeof id === 'string' ? document.getElementById(id) : id;
  1961. }
  1962. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1963. // Returns the value for a certain style attribute on an element,
  1964. // including computed values or values set through CSS.
  1965. function getStyle(el, style) {
  1966. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1967. if ((!value || value === 'auto') && document.defaultView) {
  1968. var css = document.defaultView.getComputedStyle(el, null);
  1969. value = css ? css[style] : null;
  1970. }
  1971. return value === 'auto' ? null : value;
  1972. }
  1973. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1974. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1975. function create$1(tagName, className, container) {
  1976. var el = document.createElement(tagName);
  1977. el.className = className || '';
  1978. if (container) {
  1979. container.appendChild(el);
  1980. }
  1981. return el;
  1982. }
  1983. // @function remove(el: HTMLElement)
  1984. // Removes `el` from its parent element
  1985. function remove(el) {
  1986. var parent = el.parentNode;
  1987. if (parent) {
  1988. parent.removeChild(el);
  1989. }
  1990. }
  1991. // @function empty(el: HTMLElement)
  1992. // Removes all of `el`'s children elements from `el`
  1993. function empty(el) {
  1994. while (el.firstChild) {
  1995. el.removeChild(el.firstChild);
  1996. }
  1997. }
  1998. // @function toFront(el: HTMLElement)
  1999. // Makes `el` the last child of its parent, so it renders in front of the other children.
  2000. function toFront(el) {
  2001. var parent = el.parentNode;
  2002. if (parent && parent.lastChild !== el) {
  2003. parent.appendChild(el);
  2004. }
  2005. }
  2006. // @function toBack(el: HTMLElement)
  2007. // Makes `el` the first child of its parent, so it renders behind the other children.
  2008. function toBack(el) {
  2009. var parent = el.parentNode;
  2010. if (parent && parent.firstChild !== el) {
  2011. parent.insertBefore(el, parent.firstChild);
  2012. }
  2013. }
  2014. // @function hasClass(el: HTMLElement, name: String): Boolean
  2015. // Returns `true` if the element's class attribute contains `name`.
  2016. function hasClass(el, name) {
  2017. if (el.classList !== undefined) {
  2018. return el.classList.contains(name);
  2019. }
  2020. var className = getClass(el);
  2021. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  2022. }
  2023. // @function addClass(el: HTMLElement, name: String)
  2024. // Adds `name` to the element's class attribute.
  2025. function addClass(el, name) {
  2026. if (el.classList !== undefined) {
  2027. var classes = splitWords(name);
  2028. for (var i = 0, len = classes.length; i < len; i++) {
  2029. el.classList.add(classes[i]);
  2030. }
  2031. } else if (!hasClass(el, name)) {
  2032. var className = getClass(el);
  2033. setClass(el, (className ? className + ' ' : '') + name);
  2034. }
  2035. }
  2036. // @function removeClass(el: HTMLElement, name: String)
  2037. // Removes `name` from the element's class attribute.
  2038. function removeClass(el, name) {
  2039. if (el.classList !== undefined) {
  2040. el.classList.remove(name);
  2041. } else {
  2042. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  2043. }
  2044. }
  2045. // @function setClass(el: HTMLElement, name: String)
  2046. // Sets the element's class.
  2047. function setClass(el, name) {
  2048. if (el.className.baseVal === undefined) {
  2049. el.className = name;
  2050. } else {
  2051. // in case of SVG element
  2052. el.className.baseVal = name;
  2053. }
  2054. }
  2055. // @function getClass(el: HTMLElement): String
  2056. // Returns the element's class.
  2057. function getClass(el) {
  2058. // Check if the element is an SVGElementInstance and use the correspondingElement instead
  2059. // (Required for linked SVG elements in IE11.)
  2060. if (el.correspondingElement) {
  2061. el = el.correspondingElement;
  2062. }
  2063. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  2064. }
  2065. // @function setOpacity(el: HTMLElement, opacity: Number)
  2066. // Set the opacity of an element (including old IE support).
  2067. // `opacity` must be a number from `0` to `1`.
  2068. function setOpacity(el, value) {
  2069. if ('opacity' in el.style) {
  2070. el.style.opacity = value;
  2071. } else if ('filter' in el.style) {
  2072. _setOpacityIE(el, value);
  2073. }
  2074. }
  2075. function _setOpacityIE(el, value) {
  2076. var filter = false,
  2077. filterName = 'DXImageTransform.Microsoft.Alpha';
  2078. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  2079. try {
  2080. filter = el.filters.item(filterName);
  2081. } catch (e) {
  2082. // don't set opacity to 1 if we haven't already set an opacity,
  2083. // it isn't needed and breaks transparent pngs.
  2084. if (value === 1) { return; }
  2085. }
  2086. value = Math.round(value * 100);
  2087. if (filter) {
  2088. filter.Enabled = (value !== 100);
  2089. filter.Opacity = value;
  2090. } else {
  2091. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  2092. }
  2093. }
  2094. // @function testProp(props: String[]): String|false
  2095. // Goes through the array of style names and returns the first name
  2096. // that is a valid style name for an element. If no such name is found,
  2097. // it returns false. Useful for vendor-prefixed styles like `transform`.
  2098. function testProp(props) {
  2099. var style = document.documentElement.style;
  2100. for (var i = 0; i < props.length; i++) {
  2101. if (props[i] in style) {
  2102. return props[i];
  2103. }
  2104. }
  2105. return false;
  2106. }
  2107. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  2108. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  2109. // and optionally scaled by `scale`. Does not have an effect if the
  2110. // browser doesn't support 3D CSS transforms.
  2111. function setTransform(el, offset, scale) {
  2112. var pos = offset || new Point(0, 0);
  2113. el.style[TRANSFORM] =
  2114. (Browser.ie3d ?
  2115. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2116. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2117. (scale ? ' scale(' + scale + ')' : '');
  2118. }
  2119. // @function setPosition(el: HTMLElement, position: Point)
  2120. // Sets the position of `el` to coordinates specified by `position`,
  2121. // using CSS translate or top/left positioning depending on the browser
  2122. // (used by Leaflet internally to position its layers).
  2123. function setPosition(el, point) {
  2124. /*eslint-disable */
  2125. el._leaflet_pos = point;
  2126. /* eslint-enable */
  2127. if (Browser.any3d) {
  2128. setTransform(el, point);
  2129. } else {
  2130. el.style.left = point.x + 'px';
  2131. el.style.top = point.y + 'px';
  2132. }
  2133. }
  2134. // @function getPosition(el: HTMLElement): Point
  2135. // Returns the coordinates of an element previously positioned with setPosition.
  2136. function getPosition(el) {
  2137. // this method is only used for elements previously positioned using setPosition,
  2138. // so it's safe to cache the position for performance
  2139. return el._leaflet_pos || new Point(0, 0);
  2140. }
  2141. // @function disableTextSelection()
  2142. // Prevents the user from generating `selectstart` DOM events, usually generated
  2143. // when the user drags the mouse through a page with text. Used internally
  2144. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2145. // the map. Affects drag interactions on the whole document.
  2146. // @function enableTextSelection()
  2147. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2148. var disableTextSelection;
  2149. var enableTextSelection;
  2150. var _userSelect;
  2151. if ('onselectstart' in document) {
  2152. disableTextSelection = function () {
  2153. on(window, 'selectstart', preventDefault);
  2154. };
  2155. enableTextSelection = function () {
  2156. off(window, 'selectstart', preventDefault);
  2157. };
  2158. } else {
  2159. var userSelectProperty = testProp(
  2160. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2161. disableTextSelection = function () {
  2162. if (userSelectProperty) {
  2163. var style = document.documentElement.style;
  2164. _userSelect = style[userSelectProperty];
  2165. style[userSelectProperty] = 'none';
  2166. }
  2167. };
  2168. enableTextSelection = function () {
  2169. if (userSelectProperty) {
  2170. document.documentElement.style[userSelectProperty] = _userSelect;
  2171. _userSelect = undefined;
  2172. }
  2173. };
  2174. }
  2175. // @function disableImageDrag()
  2176. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2177. // for `dragstart` DOM events, usually generated when the user drags an image.
  2178. function disableImageDrag() {
  2179. on(window, 'dragstart', preventDefault);
  2180. }
  2181. // @function enableImageDrag()
  2182. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2183. function enableImageDrag() {
  2184. off(window, 'dragstart', preventDefault);
  2185. }
  2186. var _outlineElement, _outlineStyle;
  2187. // @function preventOutline(el: HTMLElement)
  2188. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2189. // of the element `el` invisible. Used internally by Leaflet to prevent
  2190. // focusable elements from displaying an outline when the user performs a
  2191. // drag interaction on them.
  2192. function preventOutline(element) {
  2193. while (element.tabIndex === -1) {
  2194. element = element.parentNode;
  2195. }
  2196. if (!element.style) { return; }
  2197. restoreOutline();
  2198. _outlineElement = element;
  2199. _outlineStyle = element.style.outlineStyle;
  2200. element.style.outlineStyle = 'none';
  2201. on(window, 'keydown', restoreOutline);
  2202. }
  2203. // @function restoreOutline()
  2204. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2205. function restoreOutline() {
  2206. if (!_outlineElement) { return; }
  2207. _outlineElement.style.outlineStyle = _outlineStyle;
  2208. _outlineElement = undefined;
  2209. _outlineStyle = undefined;
  2210. off(window, 'keydown', restoreOutline);
  2211. }
  2212. // @function getSizedParentNode(el: HTMLElement): HTMLElement
  2213. // Finds the closest parent node which size (width and height) is not null.
  2214. function getSizedParentNode(element) {
  2215. do {
  2216. element = element.parentNode;
  2217. } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);
  2218. return element;
  2219. }
  2220. // @function getScale(el: HTMLElement): Object
  2221. // Computes the CSS scale currently applied on the element.
  2222. // Returns an object with `x` and `y` members as horizontal and vertical scales respectively,
  2223. // and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2224. function getScale(element) {
  2225. var rect = element.getBoundingClientRect(); // Read-only in old browsers.
  2226. return {
  2227. x: rect.width / element.offsetWidth || 1,
  2228. y: rect.height / element.offsetHeight || 1,
  2229. boundingClientRect: rect
  2230. };
  2231. }
  2232. var DomUtil = {
  2233. __proto__: null,
  2234. TRANSFORM: TRANSFORM,
  2235. TRANSITION: TRANSITION,
  2236. TRANSITION_END: TRANSITION_END,
  2237. get: get,
  2238. getStyle: getStyle,
  2239. create: create$1,
  2240. remove: remove,
  2241. empty: empty,
  2242. toFront: toFront,
  2243. toBack: toBack,
  2244. hasClass: hasClass,
  2245. addClass: addClass,
  2246. removeClass: removeClass,
  2247. setClass: setClass,
  2248. getClass: getClass,
  2249. setOpacity: setOpacity,
  2250. testProp: testProp,
  2251. setTransform: setTransform,
  2252. setPosition: setPosition,
  2253. getPosition: getPosition,
  2254. get disableTextSelection () { return disableTextSelection; },
  2255. get enableTextSelection () { return enableTextSelection; },
  2256. disableImageDrag: disableImageDrag,
  2257. enableImageDrag: enableImageDrag,
  2258. preventOutline: preventOutline,
  2259. restoreOutline: restoreOutline,
  2260. getSizedParentNode: getSizedParentNode,
  2261. getScale: getScale
  2262. };
  2263. /*
  2264. * @namespace DomEvent
  2265. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  2266. */
  2267. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  2268. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2269. // Adds a listener function (`fn`) to a particular DOM event type of the
  2270. // element `el`. You can optionally specify the context of the listener
  2271. // (object the `this` keyword will point to). You can also pass several
  2272. // space-separated types (e.g. `'click dblclick'`).
  2273. // @alternative
  2274. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  2275. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2276. function on(obj, types, fn, context) {
  2277. if (types && typeof types === 'object') {
  2278. for (var type in types) {
  2279. addOne(obj, type, types[type], fn);
  2280. }
  2281. } else {
  2282. types = splitWords(types);
  2283. for (var i = 0, len = types.length; i < len; i++) {
  2284. addOne(obj, types[i], fn, context);
  2285. }
  2286. }
  2287. return this;
  2288. }
  2289. var eventsKey = '_leaflet_events';
  2290. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2291. // Removes a previously added listener function.
  2292. // Note that if you passed a custom context to on, you must pass the same
  2293. // context to `off` in order to remove the listener.
  2294. // @alternative
  2295. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  2296. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2297. // @alternative
  2298. // @function off(el: HTMLElement, types: String): this
  2299. // Removes all previously added listeners of given types.
  2300. // @alternative
  2301. // @function off(el: HTMLElement): this
  2302. // Removes all previously added listeners from given HTMLElement
  2303. function off(obj, types, fn, context) {
  2304. if (arguments.length === 1) {
  2305. batchRemove(obj);
  2306. delete obj[eventsKey];
  2307. } else if (types && typeof types === 'object') {
  2308. for (var type in types) {
  2309. removeOne(obj, type, types[type], fn);
  2310. }
  2311. } else {
  2312. types = splitWords(types);
  2313. if (arguments.length === 2) {
  2314. batchRemove(obj, function (type) {
  2315. return indexOf(types, type) !== -1;
  2316. });
  2317. } else {
  2318. for (var i = 0, len = types.length; i < len; i++) {
  2319. removeOne(obj, types[i], fn, context);
  2320. }
  2321. }
  2322. }
  2323. return this;
  2324. }
  2325. function batchRemove(obj, filterFn) {
  2326. for (var id in obj[eventsKey]) {
  2327. var type = id.split(/\d/)[0];
  2328. if (!filterFn || filterFn(type)) {
  2329. removeOne(obj, type, null, null, id);
  2330. }
  2331. }
  2332. }
  2333. var mouseSubst = {
  2334. mouseenter: 'mouseover',
  2335. mouseleave: 'mouseout',
  2336. wheel: !('onwheel' in window) && 'mousewheel'
  2337. };
  2338. function addOne(obj, type, fn, context) {
  2339. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2340. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  2341. var handler = function (e) {
  2342. return fn.call(context || obj, e || window.event);
  2343. };
  2344. var originalHandler = handler;
  2345. if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {
  2346. // Needs DomEvent.Pointer.js
  2347. handler = addPointerListener(obj, type, handler);
  2348. } else if (Browser.touch && (type === 'dblclick')) {
  2349. handler = addDoubleTapListener(obj, handler);
  2350. } else if ('addEventListener' in obj) {
  2351. if (type === 'touchstart' || type === 'touchmove' || type === 'wheel' || type === 'mousewheel') {
  2352. obj.addEventListener(mouseSubst[type] || type, handler, Browser.passiveEvents ? {passive: false} : false);
  2353. } else if (type === 'mouseenter' || type === 'mouseleave') {
  2354. handler = function (e) {
  2355. e = e || window.event;
  2356. if (isExternalTarget(obj, e)) {
  2357. originalHandler(e);
  2358. }
  2359. };
  2360. obj.addEventListener(mouseSubst[type], handler, false);
  2361. } else {
  2362. obj.addEventListener(type, originalHandler, false);
  2363. }
  2364. } else {
  2365. obj.attachEvent('on' + type, handler);
  2366. }
  2367. obj[eventsKey] = obj[eventsKey] || {};
  2368. obj[eventsKey][id] = handler;
  2369. }
  2370. function removeOne(obj, type, fn, context, id) {
  2371. id = id || type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2372. var handler = obj[eventsKey] && obj[eventsKey][id];
  2373. if (!handler) { return this; }
  2374. if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {
  2375. removePointerListener(obj, type, handler);
  2376. } else if (Browser.touch && (type === 'dblclick')) {
  2377. removeDoubleTapListener(obj, handler);
  2378. } else if ('removeEventListener' in obj) {
  2379. obj.removeEventListener(mouseSubst[type] || type, handler, false);
  2380. } else {
  2381. obj.detachEvent('on' + type, handler);
  2382. }
  2383. obj[eventsKey][id] = null;
  2384. }
  2385. // @function stopPropagation(ev: DOMEvent): this
  2386. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  2387. // ```js
  2388. // L.DomEvent.on(div, 'click', function (ev) {
  2389. // L.DomEvent.stopPropagation(ev);
  2390. // });
  2391. // ```
  2392. function stopPropagation(e) {
  2393. if (e.stopPropagation) {
  2394. e.stopPropagation();
  2395. } else if (e.originalEvent) { // In case of Leaflet event.
  2396. e.originalEvent._stopped = true;
  2397. } else {
  2398. e.cancelBubble = true;
  2399. }
  2400. return this;
  2401. }
  2402. // @function disableScrollPropagation(el: HTMLElement): this
  2403. // Adds `stopPropagation` to the element's `'wheel'` events (plus browser variants).
  2404. function disableScrollPropagation(el) {
  2405. addOne(el, 'wheel', stopPropagation);
  2406. return this;
  2407. }
  2408. // @function disableClickPropagation(el: HTMLElement): this
  2409. // Adds `stopPropagation` to the element's `'click'`, `'dblclick'`, `'contextmenu'`,
  2410. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  2411. function disableClickPropagation(el) {
  2412. on(el, 'mousedown touchstart dblclick contextmenu', stopPropagation);
  2413. el['_leaflet_disable_click'] = true;
  2414. return this;
  2415. }
  2416. // @function preventDefault(ev: DOMEvent): this
  2417. // Prevents the default action of the DOM Event `ev` from happening (such as
  2418. // following a link in the href of the a element, or doing a POST request
  2419. // with page reload when a `<form>` is submitted).
  2420. // Use it inside listener functions.
  2421. function preventDefault(e) {
  2422. if (e.preventDefault) {
  2423. e.preventDefault();
  2424. } else {
  2425. e.returnValue = false;
  2426. }
  2427. return this;
  2428. }
  2429. // @function stop(ev: DOMEvent): this
  2430. // Does `stopPropagation` and `preventDefault` at the same time.
  2431. function stop(e) {
  2432. preventDefault(e);
  2433. stopPropagation(e);
  2434. return this;
  2435. }
  2436. // @function getPropagationPath(ev: DOMEvent): Array
  2437. // Compatibility polyfill for [`Event.composedPath()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath).
  2438. // Returns an array containing the `HTMLElement`s that the given DOM event
  2439. // should propagate to (if not stopped).
  2440. function getPropagationPath(ev) {
  2441. if (ev.composedPath) {
  2442. return ev.composedPath();
  2443. }
  2444. var path = [];
  2445. var el = ev.target;
  2446. while (el) {
  2447. path.push(el);
  2448. el = el.parentNode;
  2449. }
  2450. return path;
  2451. }
  2452. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  2453. // Gets normalized mouse position from a DOM event relative to the
  2454. // `container` (border excluded) or to the whole page if not specified.
  2455. function getMousePosition(e, container) {
  2456. if (!container) {
  2457. return new Point(e.clientX, e.clientY);
  2458. }
  2459. var scale = getScale(container),
  2460. offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)
  2461. return new Point(
  2462. // offset.left/top values are in page scale (like clientX/Y),
  2463. // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
  2464. (e.clientX - offset.left) / scale.x - container.clientLeft,
  2465. (e.clientY - offset.top) / scale.y - container.clientTop
  2466. );
  2467. }
  2468. // except , Safari and
  2469. // We need double the scroll pixels (see #7403 and #4538) for all Browsers
  2470. // except OSX (Mac) -> 3x, Chrome running on Linux 1x
  2471. var wheelPxFactor =
  2472. (Browser.linux && Browser.chrome) ? window.devicePixelRatio :
  2473. Browser.mac ? window.devicePixelRatio * 3 :
  2474. window.devicePixelRatio > 0 ? 2 * window.devicePixelRatio : 1;
  2475. // @function getWheelDelta(ev: DOMEvent): Number
  2476. // Gets normalized wheel delta from a wheel DOM event, in vertical
  2477. // pixels scrolled (negative if scrolling down).
  2478. // Events from pointing devices without precise scrolling are mapped to
  2479. // a best guess of 60 pixels.
  2480. function getWheelDelta(e) {
  2481. return (Browser.edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2482. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2483. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2484. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2485. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2486. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2487. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2488. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2489. 0;
  2490. }
  2491. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2492. function isExternalTarget(el, e) {
  2493. var related = e.relatedTarget;
  2494. if (!related) { return true; }
  2495. try {
  2496. while (related && (related !== el)) {
  2497. related = related.parentNode;
  2498. }
  2499. } catch (err) {
  2500. return false;
  2501. }
  2502. return (related !== el);
  2503. }
  2504. var DomEvent = {
  2505. __proto__: null,
  2506. on: on,
  2507. off: off,
  2508. stopPropagation: stopPropagation,
  2509. disableScrollPropagation: disableScrollPropagation,
  2510. disableClickPropagation: disableClickPropagation,
  2511. preventDefault: preventDefault,
  2512. stop: stop,
  2513. getPropagationPath: getPropagationPath,
  2514. getMousePosition: getMousePosition,
  2515. getWheelDelta: getWheelDelta,
  2516. isExternalTarget: isExternalTarget,
  2517. addListener: on,
  2518. removeListener: off
  2519. };
  2520. /*
  2521. * @class PosAnimation
  2522. * @aka L.PosAnimation
  2523. * @inherits Evented
  2524. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2525. *
  2526. * @example
  2527. * ```js
  2528. * var myPositionMarker = L.marker([48.864716, 2.294694]).addTo(map);
  2529. *
  2530. * myPositionMarker.on("click", function() {
  2531. * var pos = map.latLngToLayerPoint(myPositionMarker.getLatLng());
  2532. * pos.y -= 25;
  2533. * var fx = new L.PosAnimation();
  2534. *
  2535. * fx.once('end',function() {
  2536. * pos.y += 25;
  2537. * fx.run(myPositionMarker._icon, pos, 0.8);
  2538. * });
  2539. *
  2540. * fx.run(myPositionMarker._icon, pos, 0.3);
  2541. * });
  2542. *
  2543. * ```
  2544. *
  2545. * @constructor L.PosAnimation()
  2546. * Creates a `PosAnimation` object.
  2547. *
  2548. */
  2549. var PosAnimation = Evented.extend({
  2550. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2551. // Run an animation of a given element to a new position, optionally setting
  2552. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2553. // argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1),
  2554. // `0.5` by default).
  2555. run: function (el, newPos, duration, easeLinearity) {
  2556. this.stop();
  2557. this._el = el;
  2558. this._inProgress = true;
  2559. this._duration = duration || 0.25;
  2560. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2561. this._startPos = getPosition(el);
  2562. this._offset = newPos.subtract(this._startPos);
  2563. this._startTime = +new Date();
  2564. // @event start: Event
  2565. // Fired when the animation starts
  2566. this.fire('start');
  2567. this._animate();
  2568. },
  2569. // @method stop()
  2570. // Stops the animation (if currently running).
  2571. stop: function () {
  2572. if (!this._inProgress) { return; }
  2573. this._step(true);
  2574. this._complete();
  2575. },
  2576. _animate: function () {
  2577. // animation loop
  2578. this._animId = requestAnimFrame(this._animate, this);
  2579. this._step();
  2580. },
  2581. _step: function (round) {
  2582. var elapsed = (+new Date()) - this._startTime,
  2583. duration = this._duration * 1000;
  2584. if (elapsed < duration) {
  2585. this._runFrame(this._easeOut(elapsed / duration), round);
  2586. } else {
  2587. this._runFrame(1);
  2588. this._complete();
  2589. }
  2590. },
  2591. _runFrame: function (progress, round) {
  2592. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2593. if (round) {
  2594. pos._round();
  2595. }
  2596. setPosition(this._el, pos);
  2597. // @event step: Event
  2598. // Fired continuously during the animation.
  2599. this.fire('step');
  2600. },
  2601. _complete: function () {
  2602. cancelAnimFrame(this._animId);
  2603. this._inProgress = false;
  2604. // @event end: Event
  2605. // Fired when the animation ends.
  2606. this.fire('end');
  2607. },
  2608. _easeOut: function (t) {
  2609. return 1 - Math.pow(1 - t, this._easeOutPower);
  2610. }
  2611. });
  2612. /*
  2613. * @class Map
  2614. * @aka L.Map
  2615. * @inherits Evented
  2616. *
  2617. * The central class of the API — it is used to create a map on a page and manipulate it.
  2618. *
  2619. * @example
  2620. *
  2621. * ```js
  2622. * // initialize the map on the "map" div with a given center and zoom
  2623. * var map = L.map('map', {
  2624. * center: [51.505, -0.09],
  2625. * zoom: 13
  2626. * });
  2627. * ```
  2628. *
  2629. */
  2630. var Map = Evented.extend({
  2631. options: {
  2632. // @section Map State Options
  2633. // @option crs: CRS = L.CRS.EPSG3857
  2634. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2635. // sure what it means.
  2636. crs: EPSG3857,
  2637. // @option center: LatLng = undefined
  2638. // Initial geographic center of the map
  2639. center: undefined,
  2640. // @option zoom: Number = undefined
  2641. // Initial map zoom level
  2642. zoom: undefined,
  2643. // @option minZoom: Number = *
  2644. // Minimum zoom level of the map.
  2645. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2646. // the lowest of their `minZoom` options will be used instead.
  2647. minZoom: undefined,
  2648. // @option maxZoom: Number = *
  2649. // Maximum zoom level of the map.
  2650. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2651. // the highest of their `maxZoom` options will be used instead.
  2652. maxZoom: undefined,
  2653. // @option layers: Layer[] = []
  2654. // Array of layers that will be added to the map initially
  2655. layers: [],
  2656. // @option maxBounds: LatLngBounds = null
  2657. // When this option is set, the map restricts the view to the given
  2658. // geographical bounds, bouncing the user back if the user tries to pan
  2659. // outside the view. To set the restriction dynamically, use
  2660. // [`setMaxBounds`](#map-setmaxbounds) method.
  2661. maxBounds: undefined,
  2662. // @option renderer: Renderer = *
  2663. // The default method for drawing vector layers on the map. `L.SVG`
  2664. // or `L.Canvas` by default depending on browser support.
  2665. renderer: undefined,
  2666. // @section Animation Options
  2667. // @option zoomAnimation: Boolean = true
  2668. // Whether the map zoom animation is enabled. By default it's enabled
  2669. // in all browsers that support CSS3 Transitions except Android.
  2670. zoomAnimation: true,
  2671. // @option zoomAnimationThreshold: Number = 4
  2672. // Won't animate zoom if the zoom difference exceeds this value.
  2673. zoomAnimationThreshold: 4,
  2674. // @option fadeAnimation: Boolean = true
  2675. // Whether the tile fade animation is enabled. By default it's enabled
  2676. // in all browsers that support CSS3 Transitions except Android.
  2677. fadeAnimation: true,
  2678. // @option markerZoomAnimation: Boolean = true
  2679. // Whether markers animate their zoom with the zoom animation, if disabled
  2680. // they will disappear for the length of the animation. By default it's
  2681. // enabled in all browsers that support CSS3 Transitions except Android.
  2682. markerZoomAnimation: true,
  2683. // @option transform3DLimit: Number = 2^23
  2684. // Defines the maximum size of a CSS translation transform. The default
  2685. // value should not be changed unless a web browser positions layers in
  2686. // the wrong place after doing a large `panBy`.
  2687. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2688. // @section Interaction Options
  2689. // @option zoomSnap: Number = 1
  2690. // Forces the map's zoom level to always be a multiple of this, particularly
  2691. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2692. // By default, the zoom level snaps to the nearest integer; lower values
  2693. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2694. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2695. zoomSnap: 1,
  2696. // @option zoomDelta: Number = 1
  2697. // Controls how much the map's zoom level will change after a
  2698. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2699. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2700. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2701. zoomDelta: 1,
  2702. // @option trackResize: Boolean = true
  2703. // Whether the map automatically handles browser window resize to update itself.
  2704. trackResize: true
  2705. },
  2706. initialize: function (id, options) { // (HTMLElement or String, Object)
  2707. options = setOptions(this, options);
  2708. // Make sure to assign internal flags at the beginning,
  2709. // to avoid inconsistent state in some edge cases.
  2710. this._handlers = [];
  2711. this._layers = {};
  2712. this._zoomBoundLayers = {};
  2713. this._sizeChanged = true;
  2714. this._initContainer(id);
  2715. this._initLayout();
  2716. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2717. this._onResize = bind(this._onResize, this);
  2718. this._initEvents();
  2719. if (options.maxBounds) {
  2720. this.setMaxBounds(options.maxBounds);
  2721. }
  2722. if (options.zoom !== undefined) {
  2723. this._zoom = this._limitZoom(options.zoom);
  2724. }
  2725. if (options.center && options.zoom !== undefined) {
  2726. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2727. }
  2728. this.callInitHooks();
  2729. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2730. this._zoomAnimated = TRANSITION && Browser.any3d && !Browser.mobileOpera &&
  2731. this.options.zoomAnimation;
  2732. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2733. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2734. if (this._zoomAnimated) {
  2735. this._createAnimProxy();
  2736. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2737. }
  2738. this._addLayers(this.options.layers);
  2739. },
  2740. // @section Methods for modifying map state
  2741. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2742. // Sets the view of the map (geographical center and zoom) with the given
  2743. // animation options.
  2744. setView: function (center, zoom, options) {
  2745. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2746. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2747. options = options || {};
  2748. this._stop();
  2749. if (this._loaded && !options.reset && options !== true) {
  2750. if (options.animate !== undefined) {
  2751. options.zoom = extend({animate: options.animate}, options.zoom);
  2752. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2753. }
  2754. // try animating pan or zoom
  2755. var moved = (this._zoom !== zoom) ?
  2756. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2757. this._tryAnimatedPan(center, options.pan);
  2758. if (moved) {
  2759. // prevent resize handler call, the view will refresh after animation anyway
  2760. clearTimeout(this._sizeTimer);
  2761. return this;
  2762. }
  2763. }
  2764. // animation didn't start, just reset the map view
  2765. this._resetView(center, zoom, options.pan && options.pan.noMoveStart);
  2766. return this;
  2767. },
  2768. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2769. // Sets the zoom of the map.
  2770. setZoom: function (zoom, options) {
  2771. if (!this._loaded) {
  2772. this._zoom = zoom;
  2773. return this;
  2774. }
  2775. return this.setView(this.getCenter(), zoom, {zoom: options});
  2776. },
  2777. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2778. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2779. zoomIn: function (delta, options) {
  2780. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  2781. return this.setZoom(this._zoom + delta, options);
  2782. },
  2783. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2784. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2785. zoomOut: function (delta, options) {
  2786. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  2787. return this.setZoom(this._zoom - delta, options);
  2788. },
  2789. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2790. // Zooms the map while keeping a specified geographical point on the map
  2791. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2792. // @alternative
  2793. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2794. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2795. setZoomAround: function (latlng, zoom, options) {
  2796. var scale = this.getZoomScale(zoom),
  2797. viewHalf = this.getSize().divideBy(2),
  2798. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2799. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2800. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2801. return this.setView(newCenter, zoom, {zoom: options});
  2802. },
  2803. _getBoundsCenterZoom: function (bounds, options) {
  2804. options = options || {};
  2805. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2806. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2807. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2808. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2809. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2810. if (zoom === Infinity) {
  2811. return {
  2812. center: bounds.getCenter(),
  2813. zoom: zoom
  2814. };
  2815. }
  2816. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2817. swPoint = this.project(bounds.getSouthWest(), zoom),
  2818. nePoint = this.project(bounds.getNorthEast(), zoom),
  2819. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2820. return {
  2821. center: center,
  2822. zoom: zoom
  2823. };
  2824. },
  2825. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2826. // Sets a map view that contains the given geographical bounds with the
  2827. // maximum zoom level possible.
  2828. fitBounds: function (bounds, options) {
  2829. bounds = toLatLngBounds(bounds);
  2830. if (!bounds.isValid()) {
  2831. throw new Error('Bounds are not valid.');
  2832. }
  2833. var target = this._getBoundsCenterZoom(bounds, options);
  2834. return this.setView(target.center, target.zoom, options);
  2835. },
  2836. // @method fitWorld(options?: fitBounds options): this
  2837. // Sets a map view that mostly contains the whole world with the maximum
  2838. // zoom level possible.
  2839. fitWorld: function (options) {
  2840. return this.fitBounds([[-90, -180], [90, 180]], options);
  2841. },
  2842. // @method panTo(latlng: LatLng, options?: Pan options): this
  2843. // Pans the map to a given center.
  2844. panTo: function (center, options) { // (LatLng)
  2845. return this.setView(center, this._zoom, {pan: options});
  2846. },
  2847. // @method panBy(offset: Point, options?: Pan options): this
  2848. // Pans the map by a given number of pixels (animated).
  2849. panBy: function (offset, options) {
  2850. offset = toPoint(offset).round();
  2851. options = options || {};
  2852. if (!offset.x && !offset.y) {
  2853. return this.fire('moveend');
  2854. }
  2855. // If we pan too far, Chrome gets issues with tiles
  2856. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2857. if (options.animate !== true && !this.getSize().contains(offset)) {
  2858. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2859. return this;
  2860. }
  2861. if (!this._panAnim) {
  2862. this._panAnim = new PosAnimation();
  2863. this._panAnim.on({
  2864. 'step': this._onPanTransitionStep,
  2865. 'end': this._onPanTransitionEnd
  2866. }, this);
  2867. }
  2868. // don't fire movestart if animating inertia
  2869. if (!options.noMoveStart) {
  2870. this.fire('movestart');
  2871. }
  2872. // animate pan unless animate: false specified
  2873. if (options.animate !== false) {
  2874. addClass(this._mapPane, 'leaflet-pan-anim');
  2875. var newPos = this._getMapPanePos().subtract(offset).round();
  2876. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2877. } else {
  2878. this._rawPanBy(offset);
  2879. this.fire('move').fire('moveend');
  2880. }
  2881. return this;
  2882. },
  2883. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2884. // Sets the view of the map (geographical center and zoom) performing a smooth
  2885. // pan-zoom animation.
  2886. flyTo: function (targetCenter, targetZoom, options) {
  2887. options = options || {};
  2888. if (options.animate === false || !Browser.any3d) {
  2889. return this.setView(targetCenter, targetZoom, options);
  2890. }
  2891. this._stop();
  2892. var from = this.project(this.getCenter()),
  2893. to = this.project(targetCenter),
  2894. size = this.getSize(),
  2895. startZoom = this._zoom;
  2896. targetCenter = toLatLng(targetCenter);
  2897. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2898. var w0 = Math.max(size.x, size.y),
  2899. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2900. u1 = (to.distanceTo(from)) || 1,
  2901. rho = 1.42,
  2902. rho2 = rho * rho;
  2903. function r(i) {
  2904. var s1 = i ? -1 : 1,
  2905. s2 = i ? w1 : w0,
  2906. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2907. b1 = 2 * s2 * rho2 * u1,
  2908. b = t1 / b1,
  2909. sq = Math.sqrt(b * b + 1) - b;
  2910. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2911. // thus triggering an infinite loop in flyTo
  2912. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2913. return log;
  2914. }
  2915. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2916. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2917. function tanh(n) { return sinh(n) / cosh(n); }
  2918. var r0 = r(0);
  2919. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2920. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2921. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2922. var start = Date.now(),
  2923. S = (r(1) - r0) / rho,
  2924. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2925. function frame() {
  2926. var t = (Date.now() - start) / duration,
  2927. s = easeOut(t) * S;
  2928. if (t <= 1) {
  2929. this._flyToFrame = requestAnimFrame(frame, this);
  2930. this._move(
  2931. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2932. this.getScaleZoom(w0 / w(s), startZoom),
  2933. {flyTo: true});
  2934. } else {
  2935. this
  2936. ._move(targetCenter, targetZoom)
  2937. ._moveEnd(true);
  2938. }
  2939. }
  2940. this._moveStart(true, options.noMoveStart);
  2941. frame.call(this);
  2942. return this;
  2943. },
  2944. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2945. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2946. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2947. flyToBounds: function (bounds, options) {
  2948. var target = this._getBoundsCenterZoom(bounds, options);
  2949. return this.flyTo(target.center, target.zoom, options);
  2950. },
  2951. // @method setMaxBounds(bounds: LatLngBounds): this
  2952. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2953. setMaxBounds: function (bounds) {
  2954. bounds = toLatLngBounds(bounds);
  2955. if (this.listens('moveend', this._panInsideMaxBounds)) {
  2956. this.off('moveend', this._panInsideMaxBounds);
  2957. }
  2958. if (!bounds.isValid()) {
  2959. this.options.maxBounds = null;
  2960. return this;
  2961. }
  2962. this.options.maxBounds = bounds;
  2963. if (this._loaded) {
  2964. this._panInsideMaxBounds();
  2965. }
  2966. return this.on('moveend', this._panInsideMaxBounds);
  2967. },
  2968. // @method setMinZoom(zoom: Number): this
  2969. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2970. setMinZoom: function (zoom) {
  2971. var oldZoom = this.options.minZoom;
  2972. this.options.minZoom = zoom;
  2973. if (this._loaded && oldZoom !== zoom) {
  2974. this.fire('zoomlevelschange');
  2975. if (this.getZoom() < this.options.minZoom) {
  2976. return this.setZoom(zoom);
  2977. }
  2978. }
  2979. return this;
  2980. },
  2981. // @method setMaxZoom(zoom: Number): this
  2982. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2983. setMaxZoom: function (zoom) {
  2984. var oldZoom = this.options.maxZoom;
  2985. this.options.maxZoom = zoom;
  2986. if (this._loaded && oldZoom !== zoom) {
  2987. this.fire('zoomlevelschange');
  2988. if (this.getZoom() > this.options.maxZoom) {
  2989. return this.setZoom(zoom);
  2990. }
  2991. }
  2992. return this;
  2993. },
  2994. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2995. // 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.
  2996. panInsideBounds: function (bounds, options) {
  2997. this._enforcingBounds = true;
  2998. var center = this.getCenter(),
  2999. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  3000. if (!center.equals(newCenter)) {
  3001. this.panTo(newCenter, options);
  3002. }
  3003. this._enforcingBounds = false;
  3004. return this;
  3005. },
  3006. // @method panInside(latlng: LatLng, options?: padding options): this
  3007. // Pans the map the minimum amount to make the `latlng` visible. Use
  3008. // padding options to fit the display to more restricted bounds.
  3009. // If `latlng` is already within the (optionally padded) display bounds,
  3010. // the map will not be panned.
  3011. panInside: function (latlng, options) {
  3012. options = options || {};
  3013. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  3014. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  3015. pixelCenter = this.project(this.getCenter()),
  3016. pixelPoint = this.project(latlng),
  3017. pixelBounds = this.getPixelBounds(),
  3018. paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]),
  3019. paddedSize = paddedBounds.getSize();
  3020. if (!paddedBounds.contains(pixelPoint)) {
  3021. this._enforcingBounds = true;
  3022. var centerOffset = pixelPoint.subtract(paddedBounds.getCenter());
  3023. var offset = paddedBounds.extend(pixelPoint).getSize().subtract(paddedSize);
  3024. pixelCenter.x += centerOffset.x < 0 ? -offset.x : offset.x;
  3025. pixelCenter.y += centerOffset.y < 0 ? -offset.y : offset.y;
  3026. this.panTo(this.unproject(pixelCenter), options);
  3027. this._enforcingBounds = false;
  3028. }
  3029. return this;
  3030. },
  3031. // @method invalidateSize(options: Zoom/pan options): this
  3032. // Checks if the map container size changed and updates the map if so —
  3033. // call it after you've changed the map size dynamically, also animating
  3034. // pan by default. If `options.pan` is `false`, panning will not occur.
  3035. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  3036. // that it doesn't happen often even if the method is called many
  3037. // times in a row.
  3038. // @alternative
  3039. // @method invalidateSize(animate: Boolean): this
  3040. // Checks if the map container size changed and updates the map if so —
  3041. // call it after you've changed the map size dynamically, also animating
  3042. // pan by default.
  3043. invalidateSize: function (options) {
  3044. if (!this._loaded) { return this; }
  3045. options = extend({
  3046. animate: false,
  3047. pan: true
  3048. }, options === true ? {animate: true} : options);
  3049. var oldSize = this.getSize();
  3050. this._sizeChanged = true;
  3051. this._lastCenter = null;
  3052. var newSize = this.getSize(),
  3053. oldCenter = oldSize.divideBy(2).round(),
  3054. newCenter = newSize.divideBy(2).round(),
  3055. offset = oldCenter.subtract(newCenter);
  3056. if (!offset.x && !offset.y) { return this; }
  3057. if (options.animate && options.pan) {
  3058. this.panBy(offset);
  3059. } else {
  3060. if (options.pan) {
  3061. this._rawPanBy(offset);
  3062. }
  3063. this.fire('move');
  3064. if (options.debounceMoveend) {
  3065. clearTimeout(this._sizeTimer);
  3066. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  3067. } else {
  3068. this.fire('moveend');
  3069. }
  3070. }
  3071. // @section Map state change events
  3072. // @event resize: ResizeEvent
  3073. // Fired when the map is resized.
  3074. return this.fire('resize', {
  3075. oldSize: oldSize,
  3076. newSize: newSize
  3077. });
  3078. },
  3079. // @section Methods for modifying map state
  3080. // @method stop(): this
  3081. // Stops the currently running `panTo` or `flyTo` animation, if any.
  3082. stop: function () {
  3083. this.setZoom(this._limitZoom(this._zoom));
  3084. if (!this.options.zoomSnap) {
  3085. this.fire('viewreset');
  3086. }
  3087. return this._stop();
  3088. },
  3089. // @section Geolocation methods
  3090. // @method locate(options?: Locate options): this
  3091. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  3092. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  3093. // and optionally sets the map view to the user's location with respect to
  3094. // detection accuracy (or to the world view if geolocation failed).
  3095. // Note that, if your page doesn't use HTTPS, this method will fail in
  3096. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  3097. // See `Locate options` for more details.
  3098. locate: function (options) {
  3099. options = this._locateOptions = extend({
  3100. timeout: 10000,
  3101. watch: false
  3102. // setView: false
  3103. // maxZoom: <Number>
  3104. // maximumAge: 0
  3105. // enableHighAccuracy: false
  3106. }, options);
  3107. if (!('geolocation' in navigator)) {
  3108. this._handleGeolocationError({
  3109. code: 0,
  3110. message: 'Geolocation not supported.'
  3111. });
  3112. return this;
  3113. }
  3114. var onResponse = bind(this._handleGeolocationResponse, this),
  3115. onError = bind(this._handleGeolocationError, this);
  3116. if (options.watch) {
  3117. this._locationWatchId =
  3118. navigator.geolocation.watchPosition(onResponse, onError, options);
  3119. } else {
  3120. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  3121. }
  3122. return this;
  3123. },
  3124. // @method stopLocate(): this
  3125. // Stops watching location previously initiated by `map.locate({watch: true})`
  3126. // and aborts resetting the map view if map.locate was called with
  3127. // `{setView: true}`.
  3128. stopLocate: function () {
  3129. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  3130. navigator.geolocation.clearWatch(this._locationWatchId);
  3131. }
  3132. if (this._locateOptions) {
  3133. this._locateOptions.setView = false;
  3134. }
  3135. return this;
  3136. },
  3137. _handleGeolocationError: function (error) {
  3138. if (!this._container._leaflet_id) { return; }
  3139. var c = error.code,
  3140. message = error.message ||
  3141. (c === 1 ? 'permission denied' :
  3142. (c === 2 ? 'position unavailable' : 'timeout'));
  3143. if (this._locateOptions.setView && !this._loaded) {
  3144. this.fitWorld();
  3145. }
  3146. // @section Location events
  3147. // @event locationerror: ErrorEvent
  3148. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  3149. this.fire('locationerror', {
  3150. code: c,
  3151. message: 'Geolocation error: ' + message + '.'
  3152. });
  3153. },
  3154. _handleGeolocationResponse: function (pos) {
  3155. if (!this._container._leaflet_id) { return; }
  3156. var lat = pos.coords.latitude,
  3157. lng = pos.coords.longitude,
  3158. latlng = new LatLng(lat, lng),
  3159. bounds = latlng.toBounds(pos.coords.accuracy * 2),
  3160. options = this._locateOptions;
  3161. if (options.setView) {
  3162. var zoom = this.getBoundsZoom(bounds);
  3163. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  3164. }
  3165. var data = {
  3166. latlng: latlng,
  3167. bounds: bounds,
  3168. timestamp: pos.timestamp
  3169. };
  3170. for (var i in pos.coords) {
  3171. if (typeof pos.coords[i] === 'number') {
  3172. data[i] = pos.coords[i];
  3173. }
  3174. }
  3175. // @event locationfound: LocationEvent
  3176. // Fired when geolocation (using the [`locate`](#map-locate) method)
  3177. // went successfully.
  3178. this.fire('locationfound', data);
  3179. },
  3180. // TODO Appropriate docs section?
  3181. // @section Other Methods
  3182. // @method addHandler(name: String, HandlerClass: Function): this
  3183. // Adds a new `Handler` to the map, given its name and constructor function.
  3184. addHandler: function (name, HandlerClass) {
  3185. if (!HandlerClass) { return this; }
  3186. var handler = this[name] = new HandlerClass(this);
  3187. this._handlers.push(handler);
  3188. if (this.options[name]) {
  3189. handler.enable();
  3190. }
  3191. return this;
  3192. },
  3193. // @method remove(): this
  3194. // Destroys the map and clears all related event listeners.
  3195. remove: function () {
  3196. this._initEvents(true);
  3197. if (this.options.maxBounds) { this.off('moveend', this._panInsideMaxBounds); }
  3198. if (this._containerId !== this._container._leaflet_id) {
  3199. throw new Error('Map container is being reused by another instance');
  3200. }
  3201. try {
  3202. // throws error in IE6-8
  3203. delete this._container._leaflet_id;
  3204. delete this._containerId;
  3205. } catch (e) {
  3206. /*eslint-disable */
  3207. this._container._leaflet_id = undefined;
  3208. /* eslint-enable */
  3209. this._containerId = undefined;
  3210. }
  3211. if (this._locationWatchId !== undefined) {
  3212. this.stopLocate();
  3213. }
  3214. this._stop();
  3215. remove(this._mapPane);
  3216. if (this._clearControlPos) {
  3217. this._clearControlPos();
  3218. }
  3219. if (this._resizeRequest) {
  3220. cancelAnimFrame(this._resizeRequest);
  3221. this._resizeRequest = null;
  3222. }
  3223. this._clearHandlers();
  3224. if (this._loaded) {
  3225. // @section Map state change events
  3226. // @event unload: Event
  3227. // Fired when the map is destroyed with [remove](#map-remove) method.
  3228. this.fire('unload');
  3229. }
  3230. var i;
  3231. for (i in this._layers) {
  3232. this._layers[i].remove();
  3233. }
  3234. for (i in this._panes) {
  3235. remove(this._panes[i]);
  3236. }
  3237. this._layers = [];
  3238. this._panes = [];
  3239. delete this._mapPane;
  3240. delete this._renderer;
  3241. return this;
  3242. },
  3243. // @section Other Methods
  3244. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3245. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3246. // then returns it. The pane is created as a child of `container`, or
  3247. // as a child of the main map pane if not set.
  3248. createPane: function (name, container) {
  3249. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3250. pane = create$1('div', className, container || this._mapPane);
  3251. if (name) {
  3252. this._panes[name] = pane;
  3253. }
  3254. return pane;
  3255. },
  3256. // @section Methods for Getting Map State
  3257. // @method getCenter(): LatLng
  3258. // Returns the geographical center of the map view
  3259. getCenter: function () {
  3260. this._checkIfLoaded();
  3261. if (this._lastCenter && !this._moved()) {
  3262. return this._lastCenter.clone();
  3263. }
  3264. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3265. },
  3266. // @method getZoom(): Number
  3267. // Returns the current zoom level of the map view
  3268. getZoom: function () {
  3269. return this._zoom;
  3270. },
  3271. // @method getBounds(): LatLngBounds
  3272. // Returns the geographical bounds visible in the current map view
  3273. getBounds: function () {
  3274. var bounds = this.getPixelBounds(),
  3275. sw = this.unproject(bounds.getBottomLeft()),
  3276. ne = this.unproject(bounds.getTopRight());
  3277. return new LatLngBounds(sw, ne);
  3278. },
  3279. // @method getMinZoom(): Number
  3280. // 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.
  3281. getMinZoom: function () {
  3282. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3283. },
  3284. // @method getMaxZoom(): Number
  3285. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3286. getMaxZoom: function () {
  3287. return this.options.maxZoom === undefined ?
  3288. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3289. this.options.maxZoom;
  3290. },
  3291. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
  3292. // Returns the maximum zoom level on which the given bounds fit to the map
  3293. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3294. // instead returns the minimum zoom level on which the map view fits into
  3295. // the given bounds in its entirety.
  3296. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3297. bounds = toLatLngBounds(bounds);
  3298. padding = toPoint(padding || [0, 0]);
  3299. var zoom = this.getZoom() || 0,
  3300. min = this.getMinZoom(),
  3301. max = this.getMaxZoom(),
  3302. nw = bounds.getNorthWest(),
  3303. se = bounds.getSouthEast(),
  3304. size = this.getSize().subtract(padding),
  3305. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3306. snap = Browser.any3d ? this.options.zoomSnap : 1,
  3307. scalex = size.x / boundsSize.x,
  3308. scaley = size.y / boundsSize.y,
  3309. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3310. zoom = this.getScaleZoom(scale, zoom);
  3311. if (snap) {
  3312. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3313. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3314. }
  3315. return Math.max(min, Math.min(max, zoom));
  3316. },
  3317. // @method getSize(): Point
  3318. // Returns the current size of the map container (in pixels).
  3319. getSize: function () {
  3320. if (!this._size || this._sizeChanged) {
  3321. this._size = new Point(
  3322. this._container.clientWidth || 0,
  3323. this._container.clientHeight || 0);
  3324. this._sizeChanged = false;
  3325. }
  3326. return this._size.clone();
  3327. },
  3328. // @method getPixelBounds(): Bounds
  3329. // Returns the bounds of the current map view in projected pixel
  3330. // coordinates (sometimes useful in layer and overlay implementations).
  3331. getPixelBounds: function (center, zoom) {
  3332. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3333. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3334. },
  3335. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3336. // the map pane? "left point of the map layer" can be confusing, specially
  3337. // since there can be negative offsets.
  3338. // @method getPixelOrigin(): Point
  3339. // Returns the projected pixel coordinates of the top left point of
  3340. // the map layer (useful in custom layer and overlay implementations).
  3341. getPixelOrigin: function () {
  3342. this._checkIfLoaded();
  3343. return this._pixelOrigin;
  3344. },
  3345. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3346. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3347. // If `zoom` is omitted, the map's current zoom level is used.
  3348. getPixelWorldBounds: function (zoom) {
  3349. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3350. },
  3351. // @section Other Methods
  3352. // @method getPane(pane: String|HTMLElement): HTMLElement
  3353. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3354. getPane: function (pane) {
  3355. return typeof pane === 'string' ? this._panes[pane] : pane;
  3356. },
  3357. // @method getPanes(): Object
  3358. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3359. // the panes as values.
  3360. getPanes: function () {
  3361. return this._panes;
  3362. },
  3363. // @method getContainer: HTMLElement
  3364. // Returns the HTML element that contains the map.
  3365. getContainer: function () {
  3366. return this._container;
  3367. },
  3368. // @section Conversion Methods
  3369. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3370. // Returns the scale factor to be applied to a map transition from zoom level
  3371. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3372. getZoomScale: function (toZoom, fromZoom) {
  3373. // TODO replace with universal implementation after refactoring projections
  3374. var crs = this.options.crs;
  3375. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3376. return crs.scale(toZoom) / crs.scale(fromZoom);
  3377. },
  3378. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3379. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3380. // level and everything is scaled by a factor of `scale`. Inverse of
  3381. // [`getZoomScale`](#map-getZoomScale).
  3382. getScaleZoom: function (scale, fromZoom) {
  3383. var crs = this.options.crs;
  3384. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3385. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3386. return isNaN(zoom) ? Infinity : zoom;
  3387. },
  3388. // @method project(latlng: LatLng, zoom: Number): Point
  3389. // Projects a geographical coordinate `LatLng` according to the projection
  3390. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3391. // `Transformation`. The result is pixel coordinate relative to
  3392. // the CRS origin.
  3393. project: function (latlng, zoom) {
  3394. zoom = zoom === undefined ? this._zoom : zoom;
  3395. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3396. },
  3397. // @method unproject(point: Point, zoom: Number): LatLng
  3398. // Inverse of [`project`](#map-project).
  3399. unproject: function (point, zoom) {
  3400. zoom = zoom === undefined ? this._zoom : zoom;
  3401. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3402. },
  3403. // @method layerPointToLatLng(point: Point): LatLng
  3404. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3405. // returns the corresponding geographical coordinate (for the current zoom level).
  3406. layerPointToLatLng: function (point) {
  3407. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3408. return this.unproject(projectedPoint);
  3409. },
  3410. // @method latLngToLayerPoint(latlng: LatLng): Point
  3411. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3412. // relative to the [origin pixel](#map-getpixelorigin).
  3413. latLngToLayerPoint: function (latlng) {
  3414. var projectedPoint = this.project(toLatLng(latlng))._round();
  3415. return projectedPoint._subtract(this.getPixelOrigin());
  3416. },
  3417. // @method wrapLatLng(latlng: LatLng): LatLng
  3418. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3419. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3420. // CRS's bounds.
  3421. // By default this means longitude is wrapped around the dateline so its
  3422. // value is between -180 and +180 degrees.
  3423. wrapLatLng: function (latlng) {
  3424. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3425. },
  3426. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3427. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3428. // its center is within the CRS's bounds.
  3429. // By default this means the center longitude is wrapped around the dateline so its
  3430. // value is between -180 and +180 degrees, and the majority of the bounds
  3431. // overlaps the CRS's bounds.
  3432. wrapLatLngBounds: function (latlng) {
  3433. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3434. },
  3435. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3436. // Returns the distance between two geographical coordinates according to
  3437. // the map's CRS. By default this measures distance in meters.
  3438. distance: function (latlng1, latlng2) {
  3439. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3440. },
  3441. // @method containerPointToLayerPoint(point: Point): Point
  3442. // Given a pixel coordinate relative to the map container, returns the corresponding
  3443. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3444. containerPointToLayerPoint: function (point) { // (Point)
  3445. return toPoint(point).subtract(this._getMapPanePos());
  3446. },
  3447. // @method layerPointToContainerPoint(point: Point): Point
  3448. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3449. // returns the corresponding pixel coordinate relative to the map container.
  3450. layerPointToContainerPoint: function (point) { // (Point)
  3451. return toPoint(point).add(this._getMapPanePos());
  3452. },
  3453. // @method containerPointToLatLng(point: Point): LatLng
  3454. // Given a pixel coordinate relative to the map container, returns
  3455. // the corresponding geographical coordinate (for the current zoom level).
  3456. containerPointToLatLng: function (point) {
  3457. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3458. return this.layerPointToLatLng(layerPoint);
  3459. },
  3460. // @method latLngToContainerPoint(latlng: LatLng): Point
  3461. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3462. // relative to the map container.
  3463. latLngToContainerPoint: function (latlng) {
  3464. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3465. },
  3466. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3467. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3468. // map container where the event took place.
  3469. mouseEventToContainerPoint: function (e) {
  3470. return getMousePosition(e, this._container);
  3471. },
  3472. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3473. // Given a MouseEvent object, returns the pixel coordinate relative to
  3474. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3475. mouseEventToLayerPoint: function (e) {
  3476. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3477. },
  3478. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3479. // Given a MouseEvent object, returns geographical coordinate where the
  3480. // event took place.
  3481. mouseEventToLatLng: function (e) { // (MouseEvent)
  3482. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3483. },
  3484. // map initialization methods
  3485. _initContainer: function (id) {
  3486. var container = this._container = get(id);
  3487. if (!container) {
  3488. throw new Error('Map container not found.');
  3489. } else if (container._leaflet_id) {
  3490. throw new Error('Map container is already initialized.');
  3491. }
  3492. on(container, 'scroll', this._onScroll, this);
  3493. this._containerId = stamp(container);
  3494. },
  3495. _initLayout: function () {
  3496. var container = this._container;
  3497. this._fadeAnimated = this.options.fadeAnimation && Browser.any3d;
  3498. addClass(container, 'leaflet-container' +
  3499. (Browser.touch ? ' leaflet-touch' : '') +
  3500. (Browser.retina ? ' leaflet-retina' : '') +
  3501. (Browser.ielt9 ? ' leaflet-oldie' : '') +
  3502. (Browser.safari ? ' leaflet-safari' : '') +
  3503. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3504. var position = getStyle(container, 'position');
  3505. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed' && position !== 'sticky') {
  3506. container.style.position = 'relative';
  3507. }
  3508. this._initPanes();
  3509. if (this._initControlPos) {
  3510. this._initControlPos();
  3511. }
  3512. },
  3513. _initPanes: function () {
  3514. var panes = this._panes = {};
  3515. this._paneRenderers = {};
  3516. // @section
  3517. //
  3518. // Panes are DOM elements used to control the ordering of layers on the map. You
  3519. // can access panes with [`map.getPane`](#map-getpane) or
  3520. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3521. // [`map.createPane`](#map-createpane) method.
  3522. //
  3523. // Every map has the following default panes that differ only in zIndex.
  3524. //
  3525. // @pane mapPane: HTMLElement = 'auto'
  3526. // Pane that contains all other map panes
  3527. this._mapPane = this.createPane('mapPane', this._container);
  3528. setPosition(this._mapPane, new Point(0, 0));
  3529. // @pane tilePane: HTMLElement = 200
  3530. // Pane for `GridLayer`s and `TileLayer`s
  3531. this.createPane('tilePane');
  3532. // @pane overlayPane: HTMLElement = 400
  3533. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  3534. this.createPane('overlayPane');
  3535. // @pane shadowPane: HTMLElement = 500
  3536. // Pane for overlay shadows (e.g. `Marker` shadows)
  3537. this.createPane('shadowPane');
  3538. // @pane markerPane: HTMLElement = 600
  3539. // Pane for `Icon`s of `Marker`s
  3540. this.createPane('markerPane');
  3541. // @pane tooltipPane: HTMLElement = 650
  3542. // Pane for `Tooltip`s.
  3543. this.createPane('tooltipPane');
  3544. // @pane popupPane: HTMLElement = 700
  3545. // Pane for `Popup`s.
  3546. this.createPane('popupPane');
  3547. if (!this.options.markerZoomAnimation) {
  3548. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3549. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3550. }
  3551. },
  3552. // private methods that modify map state
  3553. // @section Map state change events
  3554. _resetView: function (center, zoom, noMoveStart) {
  3555. setPosition(this._mapPane, new Point(0, 0));
  3556. var loading = !this._loaded;
  3557. this._loaded = true;
  3558. zoom = this._limitZoom(zoom);
  3559. this.fire('viewprereset');
  3560. var zoomChanged = this._zoom !== zoom;
  3561. this
  3562. ._moveStart(zoomChanged, noMoveStart)
  3563. ._move(center, zoom)
  3564. ._moveEnd(zoomChanged);
  3565. // @event viewreset: Event
  3566. // Fired when the map needs to redraw its content (this usually happens
  3567. // on map zoom or load). Very useful for creating custom overlays.
  3568. this.fire('viewreset');
  3569. // @event load: Event
  3570. // Fired when the map is initialized (when its center and zoom are set
  3571. // for the first time).
  3572. if (loading) {
  3573. this.fire('load');
  3574. }
  3575. },
  3576. _moveStart: function (zoomChanged, noMoveStart) {
  3577. // @event zoomstart: Event
  3578. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3579. // @event movestart: Event
  3580. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3581. if (zoomChanged) {
  3582. this.fire('zoomstart');
  3583. }
  3584. if (!noMoveStart) {
  3585. this.fire('movestart');
  3586. }
  3587. return this;
  3588. },
  3589. _move: function (center, zoom, data, supressEvent) {
  3590. if (zoom === undefined) {
  3591. zoom = this._zoom;
  3592. }
  3593. var zoomChanged = this._zoom !== zoom;
  3594. this._zoom = zoom;
  3595. this._lastCenter = center;
  3596. this._pixelOrigin = this._getNewPixelOrigin(center);
  3597. if (!supressEvent) {
  3598. // @event zoom: Event
  3599. // Fired repeatedly during any change in zoom level,
  3600. // including zoom and fly animations.
  3601. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3602. this.fire('zoom', data);
  3603. }
  3604. // @event move: Event
  3605. // Fired repeatedly during any movement of the map,
  3606. // including pan and fly animations.
  3607. this.fire('move', data);
  3608. } else if (data && data.pinch) { // Always fire 'zoom' if pinching because #3530
  3609. this.fire('zoom', data);
  3610. }
  3611. return this;
  3612. },
  3613. _moveEnd: function (zoomChanged) {
  3614. // @event zoomend: Event
  3615. // Fired when the map zoom changed, after any animations.
  3616. if (zoomChanged) {
  3617. this.fire('zoomend');
  3618. }
  3619. // @event moveend: Event
  3620. // Fired when the center of the map stops changing
  3621. // (e.g. user stopped dragging the map or after non-centered zoom).
  3622. return this.fire('moveend');
  3623. },
  3624. _stop: function () {
  3625. cancelAnimFrame(this._flyToFrame);
  3626. if (this._panAnim) {
  3627. this._panAnim.stop();
  3628. }
  3629. return this;
  3630. },
  3631. _rawPanBy: function (offset) {
  3632. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3633. },
  3634. _getZoomSpan: function () {
  3635. return this.getMaxZoom() - this.getMinZoom();
  3636. },
  3637. _panInsideMaxBounds: function () {
  3638. if (!this._enforcingBounds) {
  3639. this.panInsideBounds(this.options.maxBounds);
  3640. }
  3641. },
  3642. _checkIfLoaded: function () {
  3643. if (!this._loaded) {
  3644. throw new Error('Set map center and zoom first.');
  3645. }
  3646. },
  3647. // DOM event handling
  3648. // @section Interaction events
  3649. _initEvents: function (remove) {
  3650. this._targets = {};
  3651. this._targets[stamp(this._container)] = this;
  3652. var onOff = remove ? off : on;
  3653. // @event click: MouseEvent
  3654. // Fired when the user clicks (or taps) the map.
  3655. // @event dblclick: MouseEvent
  3656. // Fired when the user double-clicks (or double-taps) the map.
  3657. // @event mousedown: MouseEvent
  3658. // Fired when the user pushes the mouse button on the map.
  3659. // @event mouseup: MouseEvent
  3660. // Fired when the user releases the mouse button on the map.
  3661. // @event mouseover: MouseEvent
  3662. // Fired when the mouse enters the map.
  3663. // @event mouseout: MouseEvent
  3664. // Fired when the mouse leaves the map.
  3665. // @event mousemove: MouseEvent
  3666. // Fired while the mouse moves over the map.
  3667. // @event contextmenu: MouseEvent
  3668. // Fired when the user pushes the right mouse button on the map, prevents
  3669. // default browser context menu from showing if there are listeners on
  3670. // this event. Also fired on mobile when the user holds a single touch
  3671. // for a second (also called long press).
  3672. // @event keypress: KeyboardEvent
  3673. // Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
  3674. // @event keydown: KeyboardEvent
  3675. // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
  3676. // the `keydown` event is fired for keys that produce a character value and for keys
  3677. // that do not produce a character value.
  3678. // @event keyup: KeyboardEvent
  3679. // Fired when the user releases a key from the keyboard while the map is focused.
  3680. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3681. 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
  3682. if (this.options.trackResize) {
  3683. onOff(window, 'resize', this._onResize, this);
  3684. }
  3685. if (Browser.any3d && this.options.transform3DLimit) {
  3686. (remove ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3687. }
  3688. },
  3689. _onResize: function () {
  3690. cancelAnimFrame(this._resizeRequest);
  3691. this._resizeRequest = requestAnimFrame(
  3692. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3693. },
  3694. _onScroll: function () {
  3695. this._container.scrollTop = 0;
  3696. this._container.scrollLeft = 0;
  3697. },
  3698. _onMoveEnd: function () {
  3699. var pos = this._getMapPanePos();
  3700. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3701. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3702. // a pixel offset on very high values, see: https://jsfiddle.net/dg6r5hhb/
  3703. this._resetView(this.getCenter(), this.getZoom());
  3704. }
  3705. },
  3706. _findEventTargets: function (e, type) {
  3707. var targets = [],
  3708. target,
  3709. isHover = type === 'mouseout' || type === 'mouseover',
  3710. src = e.target || e.srcElement,
  3711. dragging = false;
  3712. while (src) {
  3713. target = this._targets[stamp(src)];
  3714. if (target && (type === 'click' || type === 'preclick') && this._draggableMoved(target)) {
  3715. // Prevent firing click after you just dragged an object.
  3716. dragging = true;
  3717. break;
  3718. }
  3719. if (target && target.listens(type, true)) {
  3720. if (isHover && !isExternalTarget(src, e)) { break; }
  3721. targets.push(target);
  3722. if (isHover) { break; }
  3723. }
  3724. if (src === this._container) { break; }
  3725. src = src.parentNode;
  3726. }
  3727. if (!targets.length && !dragging && !isHover && this.listens(type, true)) {
  3728. targets = [this];
  3729. }
  3730. return targets;
  3731. },
  3732. _isClickDisabled: function (el) {
  3733. while (el && el !== this._container) {
  3734. if (el['_leaflet_disable_click']) { return true; }
  3735. el = el.parentNode;
  3736. }
  3737. },
  3738. _handleDOMEvent: function (e) {
  3739. var el = (e.target || e.srcElement);
  3740. if (!this._loaded || el['_leaflet_disable_events'] || e.type === 'click' && this._isClickDisabled(el)) {
  3741. return;
  3742. }
  3743. var type = e.type;
  3744. if (type === 'mousedown') {
  3745. // prevents outline when clicking on keyboard-focusable element
  3746. preventOutline(el);
  3747. }
  3748. this._fireDOMEvent(e, type);
  3749. },
  3750. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3751. _fireDOMEvent: function (e, type, canvasTargets) {
  3752. if (e.type === 'click') {
  3753. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3754. // @event preclick: MouseEvent
  3755. // Fired before mouse click on the map (sometimes useful when you
  3756. // want something to happen on click before any existing click
  3757. // handlers start running).
  3758. var synth = extend({}, e);
  3759. synth.type = 'preclick';
  3760. this._fireDOMEvent(synth, synth.type, canvasTargets);
  3761. }
  3762. // Find the layer the event is propagating from and its parents.
  3763. var targets = this._findEventTargets(e, type);
  3764. if (canvasTargets) {
  3765. var filtered = []; // pick only targets with listeners
  3766. for (var i = 0; i < canvasTargets.length; i++) {
  3767. if (canvasTargets[i].listens(type, true)) {
  3768. filtered.push(canvasTargets[i]);
  3769. }
  3770. }
  3771. targets = filtered.concat(targets);
  3772. }
  3773. if (!targets.length) { return; }
  3774. if (type === 'contextmenu') {
  3775. preventDefault(e);
  3776. }
  3777. var target = targets[0];
  3778. var data = {
  3779. originalEvent: e
  3780. };
  3781. if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
  3782. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  3783. data.containerPoint = isMarker ?
  3784. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3785. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3786. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3787. }
  3788. for (i = 0; i < targets.length; i++) {
  3789. targets[i].fire(type, data, true);
  3790. if (data.originalEvent._stopped ||
  3791. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3792. }
  3793. },
  3794. _draggableMoved: function (obj) {
  3795. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3796. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3797. },
  3798. _clearHandlers: function () {
  3799. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3800. this._handlers[i].disable();
  3801. }
  3802. },
  3803. // @section Other Methods
  3804. // @method whenReady(fn: Function, context?: Object): this
  3805. // Runs the given function `fn` when the map gets initialized with
  3806. // a view (center and zoom) and at least one layer, or immediately
  3807. // if it's already initialized, optionally passing a function context.
  3808. whenReady: function (callback, context) {
  3809. if (this._loaded) {
  3810. callback.call(context || this, {target: this});
  3811. } else {
  3812. this.on('load', callback, context);
  3813. }
  3814. return this;
  3815. },
  3816. // private methods for getting map state
  3817. _getMapPanePos: function () {
  3818. return getPosition(this._mapPane) || new Point(0, 0);
  3819. },
  3820. _moved: function () {
  3821. var pos = this._getMapPanePos();
  3822. return pos && !pos.equals([0, 0]);
  3823. },
  3824. _getTopLeftPoint: function (center, zoom) {
  3825. var pixelOrigin = center && zoom !== undefined ?
  3826. this._getNewPixelOrigin(center, zoom) :
  3827. this.getPixelOrigin();
  3828. return pixelOrigin.subtract(this._getMapPanePos());
  3829. },
  3830. _getNewPixelOrigin: function (center, zoom) {
  3831. var viewHalf = this.getSize()._divideBy(2);
  3832. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3833. },
  3834. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3835. var topLeft = this._getNewPixelOrigin(center, zoom);
  3836. return this.project(latlng, zoom)._subtract(topLeft);
  3837. },
  3838. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3839. var topLeft = this._getNewPixelOrigin(center, zoom);
  3840. return toBounds([
  3841. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3842. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3843. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3844. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3845. ]);
  3846. },
  3847. // layer point of the current center
  3848. _getCenterLayerPoint: function () {
  3849. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3850. },
  3851. // offset of the specified place to the current center in pixels
  3852. _getCenterOffset: function (latlng) {
  3853. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3854. },
  3855. // adjust center for view to get inside bounds
  3856. _limitCenter: function (center, zoom, bounds) {
  3857. if (!bounds) { return center; }
  3858. var centerPoint = this.project(center, zoom),
  3859. viewHalf = this.getSize().divideBy(2),
  3860. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3861. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3862. // If offset is less than a pixel, ignore.
  3863. // This prevents unstable projections from getting into
  3864. // an infinite loop of tiny offsets.
  3865. if (Math.abs(offset.x) <= 1 && Math.abs(offset.y) <= 1) {
  3866. return center;
  3867. }
  3868. return this.unproject(centerPoint.add(offset), zoom);
  3869. },
  3870. // adjust offset for view to get inside bounds
  3871. _limitOffset: function (offset, bounds) {
  3872. if (!bounds) { return offset; }
  3873. var viewBounds = this.getPixelBounds(),
  3874. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3875. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3876. },
  3877. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3878. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3879. var projectedMaxBounds = toBounds(
  3880. this.project(maxBounds.getNorthEast(), zoom),
  3881. this.project(maxBounds.getSouthWest(), zoom)
  3882. ),
  3883. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3884. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3885. dx = this._rebound(minOffset.x, -maxOffset.x),
  3886. dy = this._rebound(minOffset.y, -maxOffset.y);
  3887. return new Point(dx, dy);
  3888. },
  3889. _rebound: function (left, right) {
  3890. return left + right > 0 ?
  3891. Math.round(left - right) / 2 :
  3892. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3893. },
  3894. _limitZoom: function (zoom) {
  3895. var min = this.getMinZoom(),
  3896. max = this.getMaxZoom(),
  3897. snap = Browser.any3d ? this.options.zoomSnap : 1;
  3898. if (snap) {
  3899. zoom = Math.round(zoom / snap) * snap;
  3900. }
  3901. return Math.max(min, Math.min(max, zoom));
  3902. },
  3903. _onPanTransitionStep: function () {
  3904. this.fire('move');
  3905. },
  3906. _onPanTransitionEnd: function () {
  3907. removeClass(this._mapPane, 'leaflet-pan-anim');
  3908. this.fire('moveend');
  3909. },
  3910. _tryAnimatedPan: function (center, options) {
  3911. // difference between the new and current centers in pixels
  3912. var offset = this._getCenterOffset(center)._trunc();
  3913. // don't animate too far unless animate: true specified in options
  3914. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3915. this.panBy(offset, options);
  3916. return true;
  3917. },
  3918. _createAnimProxy: function () {
  3919. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3920. this._panes.mapPane.appendChild(proxy);
  3921. this.on('zoomanim', function (e) {
  3922. var prop = TRANSFORM,
  3923. transform = this._proxy.style[prop];
  3924. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3925. // workaround for case when transform is the same and so transitionend event is not fired
  3926. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3927. this._onZoomTransitionEnd();
  3928. }
  3929. }, this);
  3930. this.on('load moveend', this._animMoveEnd, this);
  3931. this._on('unload', this._destroyAnimProxy, this);
  3932. },
  3933. _destroyAnimProxy: function () {
  3934. remove(this._proxy);
  3935. this.off('load moveend', this._animMoveEnd, this);
  3936. delete this._proxy;
  3937. },
  3938. _animMoveEnd: function () {
  3939. var c = this.getCenter(),
  3940. z = this.getZoom();
  3941. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3942. },
  3943. _catchTransitionEnd: function (e) {
  3944. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3945. this._onZoomTransitionEnd();
  3946. }
  3947. },
  3948. _nothingToAnimate: function () {
  3949. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3950. },
  3951. _tryAnimatedZoom: function (center, zoom, options) {
  3952. if (this._animatingZoom) { return true; }
  3953. options = options || {};
  3954. // don't animate if disabled, not supported or zoom difference is too large
  3955. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3956. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3957. // offset is the pixel coords of the zoom origin relative to the current center
  3958. var scale = this.getZoomScale(zoom),
  3959. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3960. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3961. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3962. requestAnimFrame(function () {
  3963. this
  3964. ._moveStart(true, options.noMoveStart || false)
  3965. ._animateZoom(center, zoom, true);
  3966. }, this);
  3967. return true;
  3968. },
  3969. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3970. if (!this._mapPane) { return; }
  3971. if (startAnim) {
  3972. this._animatingZoom = true;
  3973. // remember what center/zoom to set after animation
  3974. this._animateToCenter = center;
  3975. this._animateToZoom = zoom;
  3976. addClass(this._mapPane, 'leaflet-zoom-anim');
  3977. }
  3978. // @section Other Events
  3979. // @event zoomanim: ZoomAnimEvent
  3980. // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
  3981. this.fire('zoomanim', {
  3982. center: center,
  3983. zoom: zoom,
  3984. noUpdate: noUpdate
  3985. });
  3986. if (!this._tempFireZoomEvent) {
  3987. this._tempFireZoomEvent = this._zoom !== this._animateToZoom;
  3988. }
  3989. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  3990. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3991. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3992. },
  3993. _onZoomTransitionEnd: function () {
  3994. if (!this._animatingZoom) { return; }
  3995. if (this._mapPane) {
  3996. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3997. }
  3998. this._animatingZoom = false;
  3999. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  4000. if (this._tempFireZoomEvent) {
  4001. this.fire('zoom');
  4002. }
  4003. delete this._tempFireZoomEvent;
  4004. this.fire('move');
  4005. this._moveEnd(true);
  4006. }
  4007. });
  4008. // @section
  4009. // @factory L.map(id: String, options?: Map options)
  4010. // Instantiates a map object given the DOM ID of a `<div>` element
  4011. // and optionally an object literal with `Map options`.
  4012. //
  4013. // @alternative
  4014. // @factory L.map(el: HTMLElement, options?: Map options)
  4015. // Instantiates a map object given an instance of a `<div>` HTML element
  4016. // and optionally an object literal with `Map options`.
  4017. function createMap(id, options) {
  4018. return new Map(id, options);
  4019. }
  4020. /*
  4021. * @class Control
  4022. * @aka L.Control
  4023. * @inherits Class
  4024. *
  4025. * L.Control is a base class for implementing map controls. Handles positioning.
  4026. * All other controls extend from this class.
  4027. */
  4028. var Control = Class.extend({
  4029. // @section
  4030. // @aka Control Options
  4031. options: {
  4032. // @option position: String = 'topright'
  4033. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  4034. // `'topright'`, `'bottomleft'` or `'bottomright'`
  4035. position: 'topright'
  4036. },
  4037. initialize: function (options) {
  4038. setOptions(this, options);
  4039. },
  4040. /* @section
  4041. * Classes extending L.Control will inherit the following methods:
  4042. *
  4043. * @method getPosition: string
  4044. * Returns the position of the control.
  4045. */
  4046. getPosition: function () {
  4047. return this.options.position;
  4048. },
  4049. // @method setPosition(position: string): this
  4050. // Sets the position of the control.
  4051. setPosition: function (position) {
  4052. var map = this._map;
  4053. if (map) {
  4054. map.removeControl(this);
  4055. }
  4056. this.options.position = position;
  4057. if (map) {
  4058. map.addControl(this);
  4059. }
  4060. return this;
  4061. },
  4062. // @method getContainer: HTMLElement
  4063. // Returns the HTMLElement that contains the control.
  4064. getContainer: function () {
  4065. return this._container;
  4066. },
  4067. // @method addTo(map: Map): this
  4068. // Adds the control to the given map.
  4069. addTo: function (map) {
  4070. this.remove();
  4071. this._map = map;
  4072. var container = this._container = this.onAdd(map),
  4073. pos = this.getPosition(),
  4074. corner = map._controlCorners[pos];
  4075. addClass(container, 'leaflet-control');
  4076. if (pos.indexOf('bottom') !== -1) {
  4077. corner.insertBefore(container, corner.firstChild);
  4078. } else {
  4079. corner.appendChild(container);
  4080. }
  4081. this._map.on('unload', this.remove, this);
  4082. return this;
  4083. },
  4084. // @method remove: this
  4085. // Removes the control from the map it is currently active on.
  4086. remove: function () {
  4087. if (!this._map) {
  4088. return this;
  4089. }
  4090. remove(this._container);
  4091. if (this.onRemove) {
  4092. this.onRemove(this._map);
  4093. }
  4094. this._map.off('unload', this.remove, this);
  4095. this._map = null;
  4096. return this;
  4097. },
  4098. _refocusOnMap: function (e) {
  4099. // if map exists and event is not a keyboard event
  4100. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  4101. this._map.getContainer().focus();
  4102. }
  4103. }
  4104. });
  4105. var control = function (options) {
  4106. return new Control(options);
  4107. };
  4108. /* @section Extension methods
  4109. * @uninheritable
  4110. *
  4111. * Every control should extend from `L.Control` and (re-)implement the following methods.
  4112. *
  4113. * @method onAdd(map: Map): HTMLElement
  4114. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  4115. *
  4116. * @method onRemove(map: Map)
  4117. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  4118. */
  4119. /* @namespace Map
  4120. * @section Methods for Layers and Controls
  4121. */
  4122. Map.include({
  4123. // @method addControl(control: Control): this
  4124. // Adds the given control to the map
  4125. addControl: function (control) {
  4126. control.addTo(this);
  4127. return this;
  4128. },
  4129. // @method removeControl(control: Control): this
  4130. // Removes the given control from the map
  4131. removeControl: function (control) {
  4132. control.remove();
  4133. return this;
  4134. },
  4135. _initControlPos: function () {
  4136. var corners = this._controlCorners = {},
  4137. l = 'leaflet-',
  4138. container = this._controlContainer =
  4139. create$1('div', l + 'control-container', this._container);
  4140. function createCorner(vSide, hSide) {
  4141. var className = l + vSide + ' ' + l + hSide;
  4142. corners[vSide + hSide] = create$1('div', className, container);
  4143. }
  4144. createCorner('top', 'left');
  4145. createCorner('top', 'right');
  4146. createCorner('bottom', 'left');
  4147. createCorner('bottom', 'right');
  4148. },
  4149. _clearControlPos: function () {
  4150. for (var i in this._controlCorners) {
  4151. remove(this._controlCorners[i]);
  4152. }
  4153. remove(this._controlContainer);
  4154. delete this._controlCorners;
  4155. delete this._controlContainer;
  4156. }
  4157. });
  4158. /*
  4159. * @class Control.Layers
  4160. * @aka L.Control.Layers
  4161. * @inherits Control
  4162. *
  4163. * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](https://leafletjs.com/examples/layers-control/)). Extends `Control`.
  4164. *
  4165. * @example
  4166. *
  4167. * ```js
  4168. * var baseLayers = {
  4169. * "Mapbox": mapbox,
  4170. * "OpenStreetMap": osm
  4171. * };
  4172. *
  4173. * var overlays = {
  4174. * "Marker": marker,
  4175. * "Roads": roadsLayer
  4176. * };
  4177. *
  4178. * L.control.layers(baseLayers, overlays).addTo(map);
  4179. * ```
  4180. *
  4181. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  4182. *
  4183. * ```js
  4184. * {
  4185. * "<someName1>": layer1,
  4186. * "<someName2>": layer2
  4187. * }
  4188. * ```
  4189. *
  4190. * The layer names can contain HTML, which allows you to add additional styling to the items:
  4191. *
  4192. * ```js
  4193. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  4194. * ```
  4195. */
  4196. var Layers = Control.extend({
  4197. // @section
  4198. // @aka Control.Layers options
  4199. options: {
  4200. // @option collapsed: Boolean = true
  4201. // If `true`, the control will be collapsed into an icon and expanded on mouse hover, touch, or keyboard activation.
  4202. collapsed: true,
  4203. position: 'topright',
  4204. // @option autoZIndex: Boolean = true
  4205. // 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.
  4206. autoZIndex: true,
  4207. // @option hideSingleBase: Boolean = false
  4208. // If `true`, the base layers in the control will be hidden when there is only one.
  4209. hideSingleBase: false,
  4210. // @option sortLayers: Boolean = false
  4211. // Whether to sort the layers. When `false`, layers will keep the order
  4212. // in which they were added to the control.
  4213. sortLayers: false,
  4214. // @option sortFunction: Function = *
  4215. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  4216. // that will be used for sorting the layers, when `sortLayers` is `true`.
  4217. // The function receives both the `L.Layer` instances and their names, as in
  4218. // `sortFunction(layerA, layerB, nameA, nameB)`.
  4219. // By default, it sorts layers alphabetically by their name.
  4220. sortFunction: function (layerA, layerB, nameA, nameB) {
  4221. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  4222. }
  4223. },
  4224. initialize: function (baseLayers, overlays, options) {
  4225. setOptions(this, options);
  4226. this._layerControlInputs = [];
  4227. this._layers = [];
  4228. this._lastZIndex = 0;
  4229. this._handlingClick = false;
  4230. this._preventClick = false;
  4231. for (var i in baseLayers) {
  4232. this._addLayer(baseLayers[i], i);
  4233. }
  4234. for (i in overlays) {
  4235. this._addLayer(overlays[i], i, true);
  4236. }
  4237. },
  4238. onAdd: function (map) {
  4239. this._initLayout();
  4240. this._update();
  4241. this._map = map;
  4242. map.on('zoomend', this._checkDisabledLayers, this);
  4243. for (var i = 0; i < this._layers.length; i++) {
  4244. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4245. }
  4246. return this._container;
  4247. },
  4248. addTo: function (map) {
  4249. Control.prototype.addTo.call(this, map);
  4250. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4251. return this._expandIfNotCollapsed();
  4252. },
  4253. onRemove: function () {
  4254. this._map.off('zoomend', this._checkDisabledLayers, this);
  4255. for (var i = 0; i < this._layers.length; i++) {
  4256. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4257. }
  4258. },
  4259. // @method addBaseLayer(layer: Layer, name: String): this
  4260. // Adds a base layer (radio button entry) with the given name to the control.
  4261. addBaseLayer: function (layer, name) {
  4262. this._addLayer(layer, name);
  4263. return (this._map) ? this._update() : this;
  4264. },
  4265. // @method addOverlay(layer: Layer, name: String): this
  4266. // Adds an overlay (checkbox entry) with the given name to the control.
  4267. addOverlay: function (layer, name) {
  4268. this._addLayer(layer, name, true);
  4269. return (this._map) ? this._update() : this;
  4270. },
  4271. // @method removeLayer(layer: Layer): this
  4272. // Remove the given layer from the control.
  4273. removeLayer: function (layer) {
  4274. layer.off('add remove', this._onLayerChange, this);
  4275. var obj = this._getLayer(stamp(layer));
  4276. if (obj) {
  4277. this._layers.splice(this._layers.indexOf(obj), 1);
  4278. }
  4279. return (this._map) ? this._update() : this;
  4280. },
  4281. // @method expand(): this
  4282. // Expand the control container if collapsed.
  4283. expand: function () {
  4284. addClass(this._container, 'leaflet-control-layers-expanded');
  4285. this._section.style.height = null;
  4286. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4287. if (acceptableHeight < this._section.clientHeight) {
  4288. addClass(this._section, 'leaflet-control-layers-scrollbar');
  4289. this._section.style.height = acceptableHeight + 'px';
  4290. } else {
  4291. removeClass(this._section, 'leaflet-control-layers-scrollbar');
  4292. }
  4293. this._checkDisabledLayers();
  4294. return this;
  4295. },
  4296. // @method collapse(): this
  4297. // Collapse the control container if expanded.
  4298. collapse: function () {
  4299. removeClass(this._container, 'leaflet-control-layers-expanded');
  4300. return this;
  4301. },
  4302. _initLayout: function () {
  4303. var className = 'leaflet-control-layers',
  4304. container = this._container = create$1('div', className),
  4305. collapsed = this.options.collapsed;
  4306. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4307. container.setAttribute('aria-haspopup', true);
  4308. disableClickPropagation(container);
  4309. disableScrollPropagation(container);
  4310. var section = this._section = create$1('section', className + '-list');
  4311. if (collapsed) {
  4312. this._map.on('click', this.collapse, this);
  4313. on(container, {
  4314. mouseenter: this._expandSafely,
  4315. mouseleave: this.collapse
  4316. }, this);
  4317. }
  4318. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4319. link.href = '#';
  4320. link.title = 'Layers';
  4321. link.setAttribute('role', 'button');
  4322. on(link, {
  4323. keydown: function (e) {
  4324. if (e.keyCode === 13) {
  4325. this._expandSafely();
  4326. }
  4327. },
  4328. // Certain screen readers intercept the key event and instead send a click event
  4329. click: function (e) {
  4330. preventDefault(e);
  4331. this._expandSafely();
  4332. }
  4333. }, this);
  4334. if (!collapsed) {
  4335. this.expand();
  4336. }
  4337. this._baseLayersList = create$1('div', className + '-base', section);
  4338. this._separator = create$1('div', className + '-separator', section);
  4339. this._overlaysList = create$1('div', className + '-overlays', section);
  4340. container.appendChild(section);
  4341. },
  4342. _getLayer: function (id) {
  4343. for (var i = 0; i < this._layers.length; i++) {
  4344. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4345. return this._layers[i];
  4346. }
  4347. }
  4348. },
  4349. _addLayer: function (layer, name, overlay) {
  4350. if (this._map) {
  4351. layer.on('add remove', this._onLayerChange, this);
  4352. }
  4353. this._layers.push({
  4354. layer: layer,
  4355. name: name,
  4356. overlay: overlay
  4357. });
  4358. if (this.options.sortLayers) {
  4359. this._layers.sort(bind(function (a, b) {
  4360. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4361. }, this));
  4362. }
  4363. if (this.options.autoZIndex && layer.setZIndex) {
  4364. this._lastZIndex++;
  4365. layer.setZIndex(this._lastZIndex);
  4366. }
  4367. this._expandIfNotCollapsed();
  4368. },
  4369. _update: function () {
  4370. if (!this._container) { return this; }
  4371. empty(this._baseLayersList);
  4372. empty(this._overlaysList);
  4373. this._layerControlInputs = [];
  4374. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4375. for (i = 0; i < this._layers.length; i++) {
  4376. obj = this._layers[i];
  4377. this._addItem(obj);
  4378. overlaysPresent = overlaysPresent || obj.overlay;
  4379. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4380. baseLayersCount += !obj.overlay ? 1 : 0;
  4381. }
  4382. // Hide base layers section if there's only one layer.
  4383. if (this.options.hideSingleBase) {
  4384. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4385. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4386. }
  4387. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4388. return this;
  4389. },
  4390. _onLayerChange: function (e) {
  4391. if (!this._handlingClick) {
  4392. this._update();
  4393. }
  4394. var obj = this._getLayer(stamp(e.target));
  4395. // @namespace Map
  4396. // @section Layer events
  4397. // @event baselayerchange: LayersControlEvent
  4398. // Fired when the base layer is changed through the [layers control](#control-layers).
  4399. // @event overlayadd: LayersControlEvent
  4400. // Fired when an overlay is selected through the [layers control](#control-layers).
  4401. // @event overlayremove: LayersControlEvent
  4402. // Fired when an overlay is deselected through the [layers control](#control-layers).
  4403. // @namespace Control.Layers
  4404. var type = obj.overlay ?
  4405. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4406. (e.type === 'add' ? 'baselayerchange' : null);
  4407. if (type) {
  4408. this._map.fire(type, obj);
  4409. }
  4410. },
  4411. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see https://stackoverflow.com/a/119079)
  4412. _createRadioElement: function (name, checked) {
  4413. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4414. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4415. var radioFragment = document.createElement('div');
  4416. radioFragment.innerHTML = radioHtml;
  4417. return radioFragment.firstChild;
  4418. },
  4419. _addItem: function (obj) {
  4420. var label = document.createElement('label'),
  4421. checked = this._map.hasLayer(obj.layer),
  4422. input;
  4423. if (obj.overlay) {
  4424. input = document.createElement('input');
  4425. input.type = 'checkbox';
  4426. input.className = 'leaflet-control-layers-selector';
  4427. input.defaultChecked = checked;
  4428. } else {
  4429. input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);
  4430. }
  4431. this._layerControlInputs.push(input);
  4432. input.layerId = stamp(obj.layer);
  4433. on(input, 'click', this._onInputClick, this);
  4434. var name = document.createElement('span');
  4435. name.innerHTML = ' ' + obj.name;
  4436. // Helps from preventing layer control flicker when checkboxes are disabled
  4437. // https://github.com/Leaflet/Leaflet/issues/2771
  4438. var holder = document.createElement('span');
  4439. label.appendChild(holder);
  4440. holder.appendChild(input);
  4441. holder.appendChild(name);
  4442. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4443. container.appendChild(label);
  4444. this._checkDisabledLayers();
  4445. return label;
  4446. },
  4447. _onInputClick: function () {
  4448. // expanding the control on mobile with a click can cause adding a layer - we don't want this
  4449. if (this._preventClick) {
  4450. return;
  4451. }
  4452. var inputs = this._layerControlInputs,
  4453. input, layer;
  4454. var addedLayers = [],
  4455. removedLayers = [];
  4456. this._handlingClick = true;
  4457. for (var i = inputs.length - 1; i >= 0; i--) {
  4458. input = inputs[i];
  4459. layer = this._getLayer(input.layerId).layer;
  4460. if (input.checked) {
  4461. addedLayers.push(layer);
  4462. } else if (!input.checked) {
  4463. removedLayers.push(layer);
  4464. }
  4465. }
  4466. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4467. for (i = 0; i < removedLayers.length; i++) {
  4468. if (this._map.hasLayer(removedLayers[i])) {
  4469. this._map.removeLayer(removedLayers[i]);
  4470. }
  4471. }
  4472. for (i = 0; i < addedLayers.length; i++) {
  4473. if (!this._map.hasLayer(addedLayers[i])) {
  4474. this._map.addLayer(addedLayers[i]);
  4475. }
  4476. }
  4477. this._handlingClick = false;
  4478. this._refocusOnMap();
  4479. },
  4480. _checkDisabledLayers: function () {
  4481. var inputs = this._layerControlInputs,
  4482. input,
  4483. layer,
  4484. zoom = this._map.getZoom();
  4485. for (var i = inputs.length - 1; i >= 0; i--) {
  4486. input = inputs[i];
  4487. layer = this._getLayer(input.layerId).layer;
  4488. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4489. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4490. }
  4491. },
  4492. _expandIfNotCollapsed: function () {
  4493. if (this._map && !this.options.collapsed) {
  4494. this.expand();
  4495. }
  4496. return this;
  4497. },
  4498. _expandSafely: function () {
  4499. var section = this._section;
  4500. this._preventClick = true;
  4501. on(section, 'click', preventDefault);
  4502. this.expand();
  4503. var that = this;
  4504. setTimeout(function () {
  4505. off(section, 'click', preventDefault);
  4506. that._preventClick = false;
  4507. });
  4508. }
  4509. });
  4510. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4511. // Creates a layers control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
  4512. var layers = function (baseLayers, overlays, options) {
  4513. return new Layers(baseLayers, overlays, options);
  4514. };
  4515. /*
  4516. * @class Control.Zoom
  4517. * @aka L.Control.Zoom
  4518. * @inherits Control
  4519. *
  4520. * 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`.
  4521. */
  4522. var Zoom = Control.extend({
  4523. // @section
  4524. // @aka Control.Zoom options
  4525. options: {
  4526. position: 'topleft',
  4527. // @option zoomInText: String = '<span aria-hidden="true">+</span>'
  4528. // The text set on the 'zoom in' button.
  4529. zoomInText: '<span aria-hidden="true">+</span>',
  4530. // @option zoomInTitle: String = 'Zoom in'
  4531. // The title set on the 'zoom in' button.
  4532. zoomInTitle: 'Zoom in',
  4533. // @option zoomOutText: String = '<span aria-hidden="true">&#x2212;</span>'
  4534. // The text set on the 'zoom out' button.
  4535. zoomOutText: '<span aria-hidden="true">&#x2212;</span>',
  4536. // @option zoomOutTitle: String = 'Zoom out'
  4537. // The title set on the 'zoom out' button.
  4538. zoomOutTitle: 'Zoom out'
  4539. },
  4540. onAdd: function (map) {
  4541. var zoomName = 'leaflet-control-zoom',
  4542. container = create$1('div', zoomName + ' leaflet-bar'),
  4543. options = this.options;
  4544. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4545. zoomName + '-in', container, this._zoomIn);
  4546. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4547. zoomName + '-out', container, this._zoomOut);
  4548. this._updateDisabled();
  4549. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4550. return container;
  4551. },
  4552. onRemove: function (map) {
  4553. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4554. },
  4555. disable: function () {
  4556. this._disabled = true;
  4557. this._updateDisabled();
  4558. return this;
  4559. },
  4560. enable: function () {
  4561. this._disabled = false;
  4562. this._updateDisabled();
  4563. return this;
  4564. },
  4565. _zoomIn: function (e) {
  4566. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4567. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4568. }
  4569. },
  4570. _zoomOut: function (e) {
  4571. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4572. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4573. }
  4574. },
  4575. _createButton: function (html, title, className, container, fn) {
  4576. var link = create$1('a', className, container);
  4577. link.innerHTML = html;
  4578. link.href = '#';
  4579. link.title = title;
  4580. /*
  4581. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4582. */
  4583. link.setAttribute('role', 'button');
  4584. link.setAttribute('aria-label', title);
  4585. disableClickPropagation(link);
  4586. on(link, 'click', stop);
  4587. on(link, 'click', fn, this);
  4588. on(link, 'click', this._refocusOnMap, this);
  4589. return link;
  4590. },
  4591. _updateDisabled: function () {
  4592. var map = this._map,
  4593. className = 'leaflet-disabled';
  4594. removeClass(this._zoomInButton, className);
  4595. removeClass(this._zoomOutButton, className);
  4596. this._zoomInButton.setAttribute('aria-disabled', 'false');
  4597. this._zoomOutButton.setAttribute('aria-disabled', 'false');
  4598. if (this._disabled || map._zoom === map.getMinZoom()) {
  4599. addClass(this._zoomOutButton, className);
  4600. this._zoomOutButton.setAttribute('aria-disabled', 'true');
  4601. }
  4602. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4603. addClass(this._zoomInButton, className);
  4604. this._zoomInButton.setAttribute('aria-disabled', 'true');
  4605. }
  4606. }
  4607. });
  4608. // @namespace Map
  4609. // @section Control options
  4610. // @option zoomControl: Boolean = true
  4611. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4612. Map.mergeOptions({
  4613. zoomControl: true
  4614. });
  4615. Map.addInitHook(function () {
  4616. if (this.options.zoomControl) {
  4617. // @section Controls
  4618. // @property zoomControl: Control.Zoom
  4619. // The default zoom control (only available if the
  4620. // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
  4621. this.zoomControl = new Zoom();
  4622. this.addControl(this.zoomControl);
  4623. }
  4624. });
  4625. // @namespace Control.Zoom
  4626. // @factory L.control.zoom(options: Control.Zoom options)
  4627. // Creates a zoom control
  4628. var zoom = function (options) {
  4629. return new Zoom(options);
  4630. };
  4631. /*
  4632. * @class Control.Scale
  4633. * @aka L.Control.Scale
  4634. * @inherits Control
  4635. *
  4636. * 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`.
  4637. *
  4638. * @example
  4639. *
  4640. * ```js
  4641. * L.control.scale().addTo(map);
  4642. * ```
  4643. */
  4644. var Scale = Control.extend({
  4645. // @section
  4646. // @aka Control.Scale options
  4647. options: {
  4648. position: 'bottomleft',
  4649. // @option maxWidth: Number = 100
  4650. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4651. maxWidth: 100,
  4652. // @option metric: Boolean = True
  4653. // Whether to show the metric scale line (m/km).
  4654. metric: true,
  4655. // @option imperial: Boolean = True
  4656. // Whether to show the imperial scale line (mi/ft).
  4657. imperial: true
  4658. // @option updateWhenIdle: Boolean = false
  4659. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4660. },
  4661. onAdd: function (map) {
  4662. var className = 'leaflet-control-scale',
  4663. container = create$1('div', className),
  4664. options = this.options;
  4665. this._addScales(options, className + '-line', container);
  4666. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4667. map.whenReady(this._update, this);
  4668. return container;
  4669. },
  4670. onRemove: function (map) {
  4671. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4672. },
  4673. _addScales: function (options, className, container) {
  4674. if (options.metric) {
  4675. this._mScale = create$1('div', className, container);
  4676. }
  4677. if (options.imperial) {
  4678. this._iScale = create$1('div', className, container);
  4679. }
  4680. },
  4681. _update: function () {
  4682. var map = this._map,
  4683. y = map.getSize().y / 2;
  4684. var maxMeters = map.distance(
  4685. map.containerPointToLatLng([0, y]),
  4686. map.containerPointToLatLng([this.options.maxWidth, y]));
  4687. this._updateScales(maxMeters);
  4688. },
  4689. _updateScales: function (maxMeters) {
  4690. if (this.options.metric && maxMeters) {
  4691. this._updateMetric(maxMeters);
  4692. }
  4693. if (this.options.imperial && maxMeters) {
  4694. this._updateImperial(maxMeters);
  4695. }
  4696. },
  4697. _updateMetric: function (maxMeters) {
  4698. var meters = this._getRoundNum(maxMeters),
  4699. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4700. this._updateScale(this._mScale, label, meters / maxMeters);
  4701. },
  4702. _updateImperial: function (maxMeters) {
  4703. var maxFeet = maxMeters * 3.2808399,
  4704. maxMiles, miles, feet;
  4705. if (maxFeet > 5280) {
  4706. maxMiles = maxFeet / 5280;
  4707. miles = this._getRoundNum(maxMiles);
  4708. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4709. } else {
  4710. feet = this._getRoundNum(maxFeet);
  4711. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4712. }
  4713. },
  4714. _updateScale: function (scale, text, ratio) {
  4715. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4716. scale.innerHTML = text;
  4717. },
  4718. _getRoundNum: function (num) {
  4719. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4720. d = num / pow10;
  4721. d = d >= 10 ? 10 :
  4722. d >= 5 ? 5 :
  4723. d >= 3 ? 3 :
  4724. d >= 2 ? 2 : 1;
  4725. return pow10 * d;
  4726. }
  4727. });
  4728. // @factory L.control.scale(options?: Control.Scale options)
  4729. // Creates an scale control with the given options.
  4730. var scale = function (options) {
  4731. return new Scale(options);
  4732. };
  4733. var ukrainianFlag = '<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="12" height="8" viewBox="0 0 12 8" class="leaflet-attribution-flag"><path fill="#4C7BE1" d="M0 0h12v4H0z"/><path fill="#FFD500" d="M0 4h12v3H0z"/><path fill="#E0BC00" d="M0 7h12v1H0z"/></svg>';
  4734. /*
  4735. * @class Control.Attribution
  4736. * @aka L.Control.Attribution
  4737. * @inherits Control
  4738. *
  4739. * 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.
  4740. */
  4741. var Attribution = Control.extend({
  4742. // @section
  4743. // @aka Control.Attribution options
  4744. options: {
  4745. position: 'bottomright',
  4746. // @option prefix: String|false = 'Leaflet'
  4747. // The HTML text shown before the attributions. Pass `false` to disable.
  4748. prefix: '<a href="https://leafletjs.com" title="A JavaScript library for interactive maps">' + (Browser.inlineSvg ? ukrainianFlag + ' ' : '') + 'Leaflet</a>'
  4749. },
  4750. initialize: function (options) {
  4751. setOptions(this, options);
  4752. this._attributions = {};
  4753. },
  4754. onAdd: function (map) {
  4755. map.attributionControl = this;
  4756. this._container = create$1('div', 'leaflet-control-attribution');
  4757. disableClickPropagation(this._container);
  4758. // TODO ugly, refactor
  4759. for (var i in map._layers) {
  4760. if (map._layers[i].getAttribution) {
  4761. this.addAttribution(map._layers[i].getAttribution());
  4762. }
  4763. }
  4764. this._update();
  4765. map.on('layeradd', this._addAttribution, this);
  4766. return this._container;
  4767. },
  4768. onRemove: function (map) {
  4769. map.off('layeradd', this._addAttribution, this);
  4770. },
  4771. _addAttribution: function (ev) {
  4772. if (ev.layer.getAttribution) {
  4773. this.addAttribution(ev.layer.getAttribution());
  4774. ev.layer.once('remove', function () {
  4775. this.removeAttribution(ev.layer.getAttribution());
  4776. }, this);
  4777. }
  4778. },
  4779. // @method setPrefix(prefix: String|false): this
  4780. // The HTML text shown before the attributions. Pass `false` to disable.
  4781. setPrefix: function (prefix) {
  4782. this.options.prefix = prefix;
  4783. this._update();
  4784. return this;
  4785. },
  4786. // @method addAttribution(text: String): this
  4787. // Adds an attribution text (e.g. `'&copy; OpenStreetMap contributors'`).
  4788. addAttribution: function (text) {
  4789. if (!text) { return this; }
  4790. if (!this._attributions[text]) {
  4791. this._attributions[text] = 0;
  4792. }
  4793. this._attributions[text]++;
  4794. this._update();
  4795. return this;
  4796. },
  4797. // @method removeAttribution(text: String): this
  4798. // Removes an attribution text.
  4799. removeAttribution: function (text) {
  4800. if (!text) { return this; }
  4801. if (this._attributions[text]) {
  4802. this._attributions[text]--;
  4803. this._update();
  4804. }
  4805. return this;
  4806. },
  4807. _update: function () {
  4808. if (!this._map) { return; }
  4809. var attribs = [];
  4810. for (var i in this._attributions) {
  4811. if (this._attributions[i]) {
  4812. attribs.push(i);
  4813. }
  4814. }
  4815. var prefixAndAttribs = [];
  4816. if (this.options.prefix) {
  4817. prefixAndAttribs.push(this.options.prefix);
  4818. }
  4819. if (attribs.length) {
  4820. prefixAndAttribs.push(attribs.join(', '));
  4821. }
  4822. this._container.innerHTML = prefixAndAttribs.join(' <span aria-hidden="true">|</span> ');
  4823. }
  4824. });
  4825. // @namespace Map
  4826. // @section Control options
  4827. // @option attributionControl: Boolean = true
  4828. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4829. Map.mergeOptions({
  4830. attributionControl: true
  4831. });
  4832. Map.addInitHook(function () {
  4833. if (this.options.attributionControl) {
  4834. new Attribution().addTo(this);
  4835. }
  4836. });
  4837. // @namespace Control.Attribution
  4838. // @factory L.control.attribution(options: Control.Attribution options)
  4839. // Creates an attribution control.
  4840. var attribution = function (options) {
  4841. return new Attribution(options);
  4842. };
  4843. Control.Layers = Layers;
  4844. Control.Zoom = Zoom;
  4845. Control.Scale = Scale;
  4846. Control.Attribution = Attribution;
  4847. control.layers = layers;
  4848. control.zoom = zoom;
  4849. control.scale = scale;
  4850. control.attribution = attribution;
  4851. /*
  4852. L.Handler is a base class for handler classes that are used internally to inject
  4853. interaction features like dragging to classes like Map and Marker.
  4854. */
  4855. // @class Handler
  4856. // @aka L.Handler
  4857. // Abstract class for map interaction handlers
  4858. var Handler = Class.extend({
  4859. initialize: function (map) {
  4860. this._map = map;
  4861. },
  4862. // @method enable(): this
  4863. // Enables the handler
  4864. enable: function () {
  4865. if (this._enabled) { return this; }
  4866. this._enabled = true;
  4867. this.addHooks();
  4868. return this;
  4869. },
  4870. // @method disable(): this
  4871. // Disables the handler
  4872. disable: function () {
  4873. if (!this._enabled) { return this; }
  4874. this._enabled = false;
  4875. this.removeHooks();
  4876. return this;
  4877. },
  4878. // @method enabled(): Boolean
  4879. // Returns `true` if the handler is enabled
  4880. enabled: function () {
  4881. return !!this._enabled;
  4882. }
  4883. // @section Extension methods
  4884. // Classes inheriting from `Handler` must implement the two following methods:
  4885. // @method addHooks()
  4886. // Called when the handler is enabled, should add event hooks.
  4887. // @method removeHooks()
  4888. // Called when the handler is disabled, should remove the event hooks added previously.
  4889. });
  4890. // @section There is static function which can be called without instantiating L.Handler:
  4891. // @function addTo(map: Map, name: String): this
  4892. // Adds a new Handler to the given map with the given name.
  4893. Handler.addTo = function (map, name) {
  4894. map.addHandler(name, this);
  4895. return this;
  4896. };
  4897. var Mixin = {Events: Events};
  4898. /*
  4899. * @class Draggable
  4900. * @aka L.Draggable
  4901. * @inherits Evented
  4902. *
  4903. * A class for making DOM elements draggable (including touch support).
  4904. * Used internally for map and marker dragging. Only works for elements
  4905. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4906. *
  4907. * @example
  4908. * ```js
  4909. * var draggable = new L.Draggable(elementToDrag);
  4910. * draggable.enable();
  4911. * ```
  4912. */
  4913. var START = Browser.touch ? 'touchstart mousedown' : 'mousedown';
  4914. var Draggable = Evented.extend({
  4915. options: {
  4916. // @section
  4917. // @aka Draggable options
  4918. // @option clickTolerance: Number = 3
  4919. // The max number of pixels a user can shift the mouse pointer during a click
  4920. // for it to be considered a valid click (as opposed to a mouse drag).
  4921. clickTolerance: 3
  4922. },
  4923. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4924. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4925. initialize: function (element, dragStartTarget, preventOutline, options) {
  4926. setOptions(this, options);
  4927. this._element = element;
  4928. this._dragStartTarget = dragStartTarget || element;
  4929. this._preventOutline = preventOutline;
  4930. },
  4931. // @method enable()
  4932. // Enables the dragging ability
  4933. enable: function () {
  4934. if (this._enabled) { return; }
  4935. on(this._dragStartTarget, START, this._onDown, this);
  4936. this._enabled = true;
  4937. },
  4938. // @method disable()
  4939. // Disables the dragging ability
  4940. disable: function () {
  4941. if (!this._enabled) { return; }
  4942. // If we're currently dragging this draggable,
  4943. // disabling it counts as first ending the drag.
  4944. if (Draggable._dragging === this) {
  4945. this.finishDrag(true);
  4946. }
  4947. off(this._dragStartTarget, START, this._onDown, this);
  4948. this._enabled = false;
  4949. this._moved = false;
  4950. },
  4951. _onDown: function (e) {
  4952. // Ignore the event if disabled; this happens in IE11
  4953. // under some circumstances, see #3666.
  4954. if (!this._enabled) { return; }
  4955. this._moved = false;
  4956. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4957. if (e.touches && e.touches.length !== 1) {
  4958. // Finish dragging to avoid conflict with touchZoom
  4959. if (Draggable._dragging === this) {
  4960. this.finishDrag();
  4961. }
  4962. return;
  4963. }
  4964. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4965. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4966. if (this._preventOutline) {
  4967. preventOutline(this._element);
  4968. }
  4969. disableImageDrag();
  4970. disableTextSelection();
  4971. if (this._moving) { return; }
  4972. // @event down: Event
  4973. // Fired when a drag is about to start.
  4974. this.fire('down');
  4975. var first = e.touches ? e.touches[0] : e,
  4976. sizedParent = getSizedParentNode(this._element);
  4977. this._startPoint = new Point(first.clientX, first.clientY);
  4978. this._startPos = getPosition(this._element);
  4979. // Cache the scale, so that we can continuously compensate for it during drag (_onMove).
  4980. this._parentScale = getScale(sizedParent);
  4981. var mouseevent = e.type === 'mousedown';
  4982. on(document, mouseevent ? 'mousemove' : 'touchmove', this._onMove, this);
  4983. on(document, mouseevent ? 'mouseup' : 'touchend touchcancel', this._onUp, this);
  4984. },
  4985. _onMove: function (e) {
  4986. // Ignore the event if disabled; this happens in IE11
  4987. // under some circumstances, see #3666.
  4988. if (!this._enabled) { return; }
  4989. if (e.touches && e.touches.length > 1) {
  4990. this._moved = true;
  4991. return;
  4992. }
  4993. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4994. offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);
  4995. if (!offset.x && !offset.y) { return; }
  4996. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4997. // We assume that the parent container's position, border and scale do not change for the duration of the drag.
  4998. // Therefore there is no need to account for the position and border (they are eliminated by the subtraction)
  4999. // and we can use the cached value for the scale.
  5000. offset.x /= this._parentScale.x;
  5001. offset.y /= this._parentScale.y;
  5002. preventDefault(e);
  5003. if (!this._moved) {
  5004. // @event dragstart: Event
  5005. // Fired when a drag starts
  5006. this.fire('dragstart');
  5007. this._moved = true;
  5008. addClass(document.body, 'leaflet-dragging');
  5009. this._lastTarget = e.target || e.srcElement;
  5010. // IE and Edge do not give the <use> element, so fetch it
  5011. // if necessary
  5012. if (window.SVGElementInstance && this._lastTarget instanceof window.SVGElementInstance) {
  5013. this._lastTarget = this._lastTarget.correspondingUseElement;
  5014. }
  5015. addClass(this._lastTarget, 'leaflet-drag-target');
  5016. }
  5017. this._newPos = this._startPos.add(offset);
  5018. this._moving = true;
  5019. this._lastEvent = e;
  5020. this._updatePosition();
  5021. },
  5022. _updatePosition: function () {
  5023. var e = {originalEvent: this._lastEvent};
  5024. // @event predrag: Event
  5025. // Fired continuously during dragging *before* each corresponding
  5026. // update of the element's position.
  5027. this.fire('predrag', e);
  5028. setPosition(this._element, this._newPos);
  5029. // @event drag: Event
  5030. // Fired continuously during dragging.
  5031. this.fire('drag', e);
  5032. },
  5033. _onUp: function () {
  5034. // Ignore the event if disabled; this happens in IE11
  5035. // under some circumstances, see #3666.
  5036. if (!this._enabled) { return; }
  5037. this.finishDrag();
  5038. },
  5039. finishDrag: function (noInertia) {
  5040. removeClass(document.body, 'leaflet-dragging');
  5041. if (this._lastTarget) {
  5042. removeClass(this._lastTarget, 'leaflet-drag-target');
  5043. this._lastTarget = null;
  5044. }
  5045. off(document, 'mousemove touchmove', this._onMove, this);
  5046. off(document, 'mouseup touchend touchcancel', this._onUp, this);
  5047. enableImageDrag();
  5048. enableTextSelection();
  5049. var fireDragend = this._moved && this._moving;
  5050. this._moving = false;
  5051. Draggable._dragging = false;
  5052. if (fireDragend) {
  5053. // @event dragend: DragEndEvent
  5054. // Fired when the drag ends.
  5055. this.fire('dragend', {
  5056. noInertia: noInertia,
  5057. distance: this._newPos.distanceTo(this._startPos)
  5058. });
  5059. }
  5060. }
  5061. });
  5062. /*
  5063. * @namespace PolyUtil
  5064. * Various utility functions for polygon geometries.
  5065. */
  5066. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5067. * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).
  5068. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5069. * performance. Note that polygon points needs different algorithm for clipping
  5070. * than polyline, so there's a separate method for it.
  5071. */
  5072. function clipPolygon(points, bounds, round) {
  5073. var clippedPoints,
  5074. edges = [1, 4, 2, 8],
  5075. i, j, k,
  5076. a, b,
  5077. len, edge, p;
  5078. for (i = 0, len = points.length; i < len; i++) {
  5079. points[i]._code = _getBitCode(points[i], bounds);
  5080. }
  5081. // for each edge (left, bottom, right, top)
  5082. for (k = 0; k < 4; k++) {
  5083. edge = edges[k];
  5084. clippedPoints = [];
  5085. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5086. a = points[i];
  5087. b = points[j];
  5088. // if a is inside the clip window
  5089. if (!(a._code & edge)) {
  5090. // if b is outside the clip window (a->b goes out of screen)
  5091. if (b._code & edge) {
  5092. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5093. p._code = _getBitCode(p, bounds);
  5094. clippedPoints.push(p);
  5095. }
  5096. clippedPoints.push(a);
  5097. // else if b is inside the clip window (a->b enters the screen)
  5098. } else if (!(b._code & edge)) {
  5099. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5100. p._code = _getBitCode(p, bounds);
  5101. clippedPoints.push(p);
  5102. }
  5103. }
  5104. points = clippedPoints;
  5105. }
  5106. return points;
  5107. }
  5108. /* @function polygonCenter(latlngs: LatLng[], crs: CRS): LatLng
  5109. * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polygon.
  5110. */
  5111. function polygonCenter(latlngs, crs) {
  5112. var i, j, p1, p2, f, area, x, y, center;
  5113. if (!latlngs || latlngs.length === 0) {
  5114. throw new Error('latlngs not passed');
  5115. }
  5116. if (!isFlat(latlngs)) {
  5117. console.warn('latlngs are not flat! Only the first ring will be used');
  5118. latlngs = latlngs[0];
  5119. }
  5120. var centroidLatLng = toLatLng([0, 0]);
  5121. var bounds = toLatLngBounds(latlngs);
  5122. var areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());
  5123. // tests showed that below 1700 rounding errors are happening
  5124. if (areaBounds < 1700) {
  5125. // getting a inexact center, to move the latlngs near to [0, 0] to prevent rounding errors
  5126. centroidLatLng = centroid(latlngs);
  5127. }
  5128. var len = latlngs.length;
  5129. var points = [];
  5130. for (i = 0; i < len; i++) {
  5131. var latlng = toLatLng(latlngs[i]);
  5132. points.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));
  5133. }
  5134. area = x = y = 0;
  5135. // polygon centroid algorithm;
  5136. for (i = 0, j = len - 1; i < len; j = i++) {
  5137. p1 = points[i];
  5138. p2 = points[j];
  5139. f = p1.y * p2.x - p2.y * p1.x;
  5140. x += (p1.x + p2.x) * f;
  5141. y += (p1.y + p2.y) * f;
  5142. area += f * 3;
  5143. }
  5144. if (area === 0) {
  5145. // Polygon is so small that all points are on same pixel.
  5146. center = points[0];
  5147. } else {
  5148. center = [x / area, y / area];
  5149. }
  5150. var latlngCenter = crs.unproject(toPoint(center));
  5151. return toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);
  5152. }
  5153. /* @function centroid(latlngs: LatLng[]): LatLng
  5154. * Returns the 'center of mass' of the passed LatLngs.
  5155. */
  5156. function centroid(coords) {
  5157. var latSum = 0;
  5158. var lngSum = 0;
  5159. var len = 0;
  5160. for (var i = 0; i < coords.length; i++) {
  5161. var latlng = toLatLng(coords[i]);
  5162. latSum += latlng.lat;
  5163. lngSum += latlng.lng;
  5164. len++;
  5165. }
  5166. return toLatLng([latSum / len, lngSum / len]);
  5167. }
  5168. var PolyUtil = {
  5169. __proto__: null,
  5170. clipPolygon: clipPolygon,
  5171. polygonCenter: polygonCenter,
  5172. centroid: centroid
  5173. };
  5174. /*
  5175. * @namespace LineUtil
  5176. *
  5177. * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
  5178. */
  5179. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  5180. // Improves rendering performance dramatically by lessening the number of points to draw.
  5181. // @function simplify(points: Point[], tolerance: Number): Point[]
  5182. // Dramatically reduces the number of points in a polyline while retaining
  5183. // its shape and returns a new array of simplified points, using the
  5184. // [Ramer-Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm).
  5185. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  5186. // each zoom level and also reducing visual noise. tolerance affects the amount of
  5187. // simplification (lesser value means higher quality but slower and with more points).
  5188. // Also released as a separated micro-library [Simplify.js](https://mourner.github.io/simplify-js/).
  5189. function simplify(points, tolerance) {
  5190. if (!tolerance || !points.length) {
  5191. return points.slice();
  5192. }
  5193. var sqTolerance = tolerance * tolerance;
  5194. // stage 1: vertex reduction
  5195. points = _reducePoints(points, sqTolerance);
  5196. // stage 2: Douglas-Peucker simplification
  5197. points = _simplifyDP(points, sqTolerance);
  5198. return points;
  5199. }
  5200. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  5201. // Returns the distance between point `p` and segment `p1` to `p2`.
  5202. function pointToSegmentDistance(p, p1, p2) {
  5203. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  5204. }
  5205. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  5206. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  5207. function closestPointOnSegment(p, p1, p2) {
  5208. return _sqClosestPointOnSegment(p, p1, p2);
  5209. }
  5210. // Ramer-Douglas-Peucker simplification, see https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
  5211. function _simplifyDP(points, sqTolerance) {
  5212. var len = points.length,
  5213. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  5214. markers = new ArrayConstructor(len);
  5215. markers[0] = markers[len - 1] = 1;
  5216. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  5217. var i,
  5218. newPoints = [];
  5219. for (i = 0; i < len; i++) {
  5220. if (markers[i]) {
  5221. newPoints.push(points[i]);
  5222. }
  5223. }
  5224. return newPoints;
  5225. }
  5226. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  5227. var maxSqDist = 0,
  5228. index, i, sqDist;
  5229. for (i = first + 1; i <= last - 1; i++) {
  5230. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  5231. if (sqDist > maxSqDist) {
  5232. index = i;
  5233. maxSqDist = sqDist;
  5234. }
  5235. }
  5236. if (maxSqDist > sqTolerance) {
  5237. markers[index] = 1;
  5238. _simplifyDPStep(points, markers, sqTolerance, first, index);
  5239. _simplifyDPStep(points, markers, sqTolerance, index, last);
  5240. }
  5241. }
  5242. // reduce points that are too close to each other to a single point
  5243. function _reducePoints(points, sqTolerance) {
  5244. var reducedPoints = [points[0]];
  5245. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  5246. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  5247. reducedPoints.push(points[i]);
  5248. prev = i;
  5249. }
  5250. }
  5251. if (prev < len - 1) {
  5252. reducedPoints.push(points[len - 1]);
  5253. }
  5254. return reducedPoints;
  5255. }
  5256. var _lastCode;
  5257. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  5258. // Clips the segment a to b by rectangular bounds with the
  5259. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  5260. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  5261. // points that are on the screen or near, increasing performance.
  5262. function clipSegment(a, b, bounds, useLastCode, round) {
  5263. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  5264. codeB = _getBitCode(b, bounds),
  5265. codeOut, p, newCode;
  5266. // save 2nd code to avoid calculating it on the next segment
  5267. _lastCode = codeB;
  5268. while (true) {
  5269. // if a,b is inside the clip window (trivial accept)
  5270. if (!(codeA | codeB)) {
  5271. return [a, b];
  5272. }
  5273. // if a,b is outside the clip window (trivial reject)
  5274. if (codeA & codeB) {
  5275. return false;
  5276. }
  5277. // other cases
  5278. codeOut = codeA || codeB;
  5279. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  5280. newCode = _getBitCode(p, bounds);
  5281. if (codeOut === codeA) {
  5282. a = p;
  5283. codeA = newCode;
  5284. } else {
  5285. b = p;
  5286. codeB = newCode;
  5287. }
  5288. }
  5289. }
  5290. function _getEdgeIntersection(a, b, code, bounds, round) {
  5291. var dx = b.x - a.x,
  5292. dy = b.y - a.y,
  5293. min = bounds.min,
  5294. max = bounds.max,
  5295. x, y;
  5296. if (code & 8) { // top
  5297. x = a.x + dx * (max.y - a.y) / dy;
  5298. y = max.y;
  5299. } else if (code & 4) { // bottom
  5300. x = a.x + dx * (min.y - a.y) / dy;
  5301. y = min.y;
  5302. } else if (code & 2) { // right
  5303. x = max.x;
  5304. y = a.y + dy * (max.x - a.x) / dx;
  5305. } else if (code & 1) { // left
  5306. x = min.x;
  5307. y = a.y + dy * (min.x - a.x) / dx;
  5308. }
  5309. return new Point(x, y, round);
  5310. }
  5311. function _getBitCode(p, bounds) {
  5312. var code = 0;
  5313. if (p.x < bounds.min.x) { // left
  5314. code |= 1;
  5315. } else if (p.x > bounds.max.x) { // right
  5316. code |= 2;
  5317. }
  5318. if (p.y < bounds.min.y) { // bottom
  5319. code |= 4;
  5320. } else if (p.y > bounds.max.y) { // top
  5321. code |= 8;
  5322. }
  5323. return code;
  5324. }
  5325. // square distance (to avoid unnecessary Math.sqrt calls)
  5326. function _sqDist(p1, p2) {
  5327. var dx = p2.x - p1.x,
  5328. dy = p2.y - p1.y;
  5329. return dx * dx + dy * dy;
  5330. }
  5331. // return closest point on segment or distance to that point
  5332. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  5333. var x = p1.x,
  5334. y = p1.y,
  5335. dx = p2.x - x,
  5336. dy = p2.y - y,
  5337. dot = dx * dx + dy * dy,
  5338. t;
  5339. if (dot > 0) {
  5340. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  5341. if (t > 1) {
  5342. x = p2.x;
  5343. y = p2.y;
  5344. } else if (t > 0) {
  5345. x += dx * t;
  5346. y += dy * t;
  5347. }
  5348. }
  5349. dx = p.x - x;
  5350. dy = p.y - y;
  5351. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  5352. }
  5353. // @function isFlat(latlngs: LatLng[]): Boolean
  5354. // Returns true if `latlngs` is a flat array, false is nested.
  5355. function isFlat(latlngs) {
  5356. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  5357. }
  5358. function _flat(latlngs) {
  5359. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  5360. return isFlat(latlngs);
  5361. }
  5362. /* @function polylineCenter(latlngs: LatLng[], crs: CRS): LatLng
  5363. * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polyline.
  5364. */
  5365. function polylineCenter(latlngs, crs) {
  5366. var i, halfDist, segDist, dist, p1, p2, ratio, center;
  5367. if (!latlngs || latlngs.length === 0) {
  5368. throw new Error('latlngs not passed');
  5369. }
  5370. if (!isFlat(latlngs)) {
  5371. console.warn('latlngs are not flat! Only the first ring will be used');
  5372. latlngs = latlngs[0];
  5373. }
  5374. var centroidLatLng = toLatLng([0, 0]);
  5375. var bounds = toLatLngBounds(latlngs);
  5376. var areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());
  5377. // tests showed that below 1700 rounding errors are happening
  5378. if (areaBounds < 1700) {
  5379. // getting a inexact center, to move the latlngs near to [0, 0] to prevent rounding errors
  5380. centroidLatLng = centroid(latlngs);
  5381. }
  5382. var len = latlngs.length;
  5383. var points = [];
  5384. for (i = 0; i < len; i++) {
  5385. var latlng = toLatLng(latlngs[i]);
  5386. points.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));
  5387. }
  5388. for (i = 0, halfDist = 0; i < len - 1; i++) {
  5389. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  5390. }
  5391. // The line is so small in the current view that all points are on the same pixel.
  5392. if (halfDist === 0) {
  5393. center = points[0];
  5394. } else {
  5395. for (i = 0, dist = 0; i < len - 1; i++) {
  5396. p1 = points[i];
  5397. p2 = points[i + 1];
  5398. segDist = p1.distanceTo(p2);
  5399. dist += segDist;
  5400. if (dist > halfDist) {
  5401. ratio = (dist - halfDist) / segDist;
  5402. center = [
  5403. p2.x - ratio * (p2.x - p1.x),
  5404. p2.y - ratio * (p2.y - p1.y)
  5405. ];
  5406. break;
  5407. }
  5408. }
  5409. }
  5410. var latlngCenter = crs.unproject(toPoint(center));
  5411. return toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);
  5412. }
  5413. var LineUtil = {
  5414. __proto__: null,
  5415. simplify: simplify,
  5416. pointToSegmentDistance: pointToSegmentDistance,
  5417. closestPointOnSegment: closestPointOnSegment,
  5418. clipSegment: clipSegment,
  5419. _getEdgeIntersection: _getEdgeIntersection,
  5420. _getBitCode: _getBitCode,
  5421. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5422. isFlat: isFlat,
  5423. _flat: _flat,
  5424. polylineCenter: polylineCenter
  5425. };
  5426. /*
  5427. * @namespace Projection
  5428. * @section
  5429. * Leaflet comes with a set of already defined Projections out of the box:
  5430. *
  5431. * @projection L.Projection.LonLat
  5432. *
  5433. * Equirectangular, or Plate Carree projection — the most simple projection,
  5434. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5435. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5436. * `EPSG:4326` and `Simple` CRS.
  5437. */
  5438. var LonLat = {
  5439. project: function (latlng) {
  5440. return new Point(latlng.lng, latlng.lat);
  5441. },
  5442. unproject: function (point) {
  5443. return new LatLng(point.y, point.x);
  5444. },
  5445. bounds: new Bounds([-180, -90], [180, 90])
  5446. };
  5447. /*
  5448. * @namespace Projection
  5449. * @projection L.Projection.Mercator
  5450. *
  5451. * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.
  5452. */
  5453. var Mercator = {
  5454. R: 6378137,
  5455. R_MINOR: 6356752.314245179,
  5456. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5457. project: function (latlng) {
  5458. var d = Math.PI / 180,
  5459. r = this.R,
  5460. y = latlng.lat * d,
  5461. tmp = this.R_MINOR / r,
  5462. e = Math.sqrt(1 - tmp * tmp),
  5463. con = e * Math.sin(y);
  5464. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5465. y = -r * Math.log(Math.max(ts, 1E-10));
  5466. return new Point(latlng.lng * d * r, y);
  5467. },
  5468. unproject: function (point) {
  5469. var d = 180 / Math.PI,
  5470. r = this.R,
  5471. tmp = this.R_MINOR / r,
  5472. e = Math.sqrt(1 - tmp * tmp),
  5473. ts = Math.exp(-point.y / r),
  5474. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5475. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5476. con = e * Math.sin(phi);
  5477. con = Math.pow((1 - con) / (1 + con), e / 2);
  5478. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5479. phi += dphi;
  5480. }
  5481. return new LatLng(phi * d, point.x * d / r);
  5482. }
  5483. };
  5484. /*
  5485. * @class Projection
  5486. * An object with methods for projecting geographical coordinates of the world onto
  5487. * a flat surface (and back). See [Map projection](https://en.wikipedia.org/wiki/Map_projection).
  5488. * @property bounds: Bounds
  5489. * The bounds (specified in CRS units) where the projection is valid
  5490. * @method project(latlng: LatLng): Point
  5491. * Projects geographical coordinates into a 2D point.
  5492. * Only accepts actual `L.LatLng` instances, not arrays.
  5493. * @method unproject(point: Point): LatLng
  5494. * The inverse of `project`. Projects a 2D point into a geographical location.
  5495. * Only accepts actual `L.Point` instances, not arrays.
  5496. * Note that the projection instances do not inherit from Leaflet's `Class` object,
  5497. * and can't be instantiated. Also, new classes can't inherit from them,
  5498. * and methods can't be added to them with the `include` function.
  5499. */
  5500. var index = {
  5501. __proto__: null,
  5502. LonLat: LonLat,
  5503. Mercator: Mercator,
  5504. SphericalMercator: SphericalMercator
  5505. };
  5506. /*
  5507. * @namespace CRS
  5508. * @crs L.CRS.EPSG3395
  5509. *
  5510. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5511. */
  5512. var EPSG3395 = extend({}, Earth, {
  5513. code: 'EPSG:3395',
  5514. projection: Mercator,
  5515. transformation: (function () {
  5516. var scale = 0.5 / (Math.PI * Mercator.R);
  5517. return toTransformation(scale, 0.5, -scale, 0.5);
  5518. }())
  5519. });
  5520. /*
  5521. * @namespace CRS
  5522. * @crs L.CRS.EPSG4326
  5523. *
  5524. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5525. *
  5526. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5527. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5528. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5529. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5530. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5531. */
  5532. var EPSG4326 = extend({}, Earth, {
  5533. code: 'EPSG:4326',
  5534. projection: LonLat,
  5535. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5536. });
  5537. /*
  5538. * @namespace CRS
  5539. * @crs L.CRS.Simple
  5540. *
  5541. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5542. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5543. * axis should still be inverted (going from bottom to top). `distance()` returns
  5544. * simple euclidean distance.
  5545. */
  5546. var Simple = extend({}, CRS, {
  5547. projection: LonLat,
  5548. transformation: toTransformation(1, 0, -1, 0),
  5549. scale: function (zoom) {
  5550. return Math.pow(2, zoom);
  5551. },
  5552. zoom: function (scale) {
  5553. return Math.log(scale) / Math.LN2;
  5554. },
  5555. distance: function (latlng1, latlng2) {
  5556. var dx = latlng2.lng - latlng1.lng,
  5557. dy = latlng2.lat - latlng1.lat;
  5558. return Math.sqrt(dx * dx + dy * dy);
  5559. },
  5560. infinite: true
  5561. });
  5562. CRS.Earth = Earth;
  5563. CRS.EPSG3395 = EPSG3395;
  5564. CRS.EPSG3857 = EPSG3857;
  5565. CRS.EPSG900913 = EPSG900913;
  5566. CRS.EPSG4326 = EPSG4326;
  5567. CRS.Simple = Simple;
  5568. /*
  5569. * @class Layer
  5570. * @inherits Evented
  5571. * @aka L.Layer
  5572. * @aka ILayer
  5573. *
  5574. * A set of methods from the Layer base class that all Leaflet layers use.
  5575. * Inherits all methods, options and events from `L.Evented`.
  5576. *
  5577. * @example
  5578. *
  5579. * ```js
  5580. * var layer = L.marker(latlng).addTo(map);
  5581. * layer.addTo(map);
  5582. * layer.remove();
  5583. * ```
  5584. *
  5585. * @event add: Event
  5586. * Fired after the layer is added to a map
  5587. *
  5588. * @event remove: Event
  5589. * Fired after the layer is removed from a map
  5590. */
  5591. var Layer = Evented.extend({
  5592. // Classes extending `L.Layer` will inherit the following options:
  5593. options: {
  5594. // @option pane: String = 'overlayPane'
  5595. // 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.
  5596. pane: 'overlayPane',
  5597. // @option attribution: String = null
  5598. // String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.
  5599. attribution: null,
  5600. bubblingMouseEvents: true
  5601. },
  5602. /* @section
  5603. * Classes extending `L.Layer` will inherit the following methods:
  5604. *
  5605. * @method addTo(map: Map|LayerGroup): this
  5606. * Adds the layer to the given map or layer group.
  5607. */
  5608. addTo: function (map) {
  5609. map.addLayer(this);
  5610. return this;
  5611. },
  5612. // @method remove: this
  5613. // Removes the layer from the map it is currently active on.
  5614. remove: function () {
  5615. return this.removeFrom(this._map || this._mapToAdd);
  5616. },
  5617. // @method removeFrom(map: Map): this
  5618. // Removes the layer from the given map
  5619. //
  5620. // @alternative
  5621. // @method removeFrom(group: LayerGroup): this
  5622. // Removes the layer from the given `LayerGroup`
  5623. removeFrom: function (obj) {
  5624. if (obj) {
  5625. obj.removeLayer(this);
  5626. }
  5627. return this;
  5628. },
  5629. // @method getPane(name? : String): HTMLElement
  5630. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5631. getPane: function (name) {
  5632. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5633. },
  5634. addInteractiveTarget: function (targetEl) {
  5635. this._map._targets[stamp(targetEl)] = this;
  5636. return this;
  5637. },
  5638. removeInteractiveTarget: function (targetEl) {
  5639. delete this._map._targets[stamp(targetEl)];
  5640. return this;
  5641. },
  5642. // @method getAttribution: String
  5643. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5644. getAttribution: function () {
  5645. return this.options.attribution;
  5646. },
  5647. _layerAdd: function (e) {
  5648. var map = e.target;
  5649. // check in case layer gets added and then removed before the map is ready
  5650. if (!map.hasLayer(this)) { return; }
  5651. this._map = map;
  5652. this._zoomAnimated = map._zoomAnimated;
  5653. if (this.getEvents) {
  5654. var events = this.getEvents();
  5655. map.on(events, this);
  5656. this.once('remove', function () {
  5657. map.off(events, this);
  5658. }, this);
  5659. }
  5660. this.onAdd(map);
  5661. this.fire('add');
  5662. map.fire('layeradd', {layer: this});
  5663. }
  5664. });
  5665. /* @section Extension methods
  5666. * @uninheritable
  5667. *
  5668. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5669. *
  5670. * @method onAdd(map: Map): this
  5671. * 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).
  5672. *
  5673. * @method onRemove(map: Map): this
  5674. * 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).
  5675. *
  5676. * @method getEvents(): Object
  5677. * 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.
  5678. *
  5679. * @method getAttribution(): String
  5680. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5681. *
  5682. * @method beforeAdd(map: Map): this
  5683. * 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.
  5684. */
  5685. /* @namespace Map
  5686. * @section Layer events
  5687. *
  5688. * @event layeradd: LayerEvent
  5689. * Fired when a new layer is added to the map.
  5690. *
  5691. * @event layerremove: LayerEvent
  5692. * Fired when some layer is removed from the map
  5693. *
  5694. * @section Methods for Layers and Controls
  5695. */
  5696. Map.include({
  5697. // @method addLayer(layer: Layer): this
  5698. // Adds the given layer to the map
  5699. addLayer: function (layer) {
  5700. if (!layer._layerAdd) {
  5701. throw new Error('The provided object is not a Layer.');
  5702. }
  5703. var id = stamp(layer);
  5704. if (this._layers[id]) { return this; }
  5705. this._layers[id] = layer;
  5706. layer._mapToAdd = this;
  5707. if (layer.beforeAdd) {
  5708. layer.beforeAdd(this);
  5709. }
  5710. this.whenReady(layer._layerAdd, layer);
  5711. return this;
  5712. },
  5713. // @method removeLayer(layer: Layer): this
  5714. // Removes the given layer from the map.
  5715. removeLayer: function (layer) {
  5716. var id = stamp(layer);
  5717. if (!this._layers[id]) { return this; }
  5718. if (this._loaded) {
  5719. layer.onRemove(this);
  5720. }
  5721. delete this._layers[id];
  5722. if (this._loaded) {
  5723. this.fire('layerremove', {layer: layer});
  5724. layer.fire('remove');
  5725. }
  5726. layer._map = layer._mapToAdd = null;
  5727. return this;
  5728. },
  5729. // @method hasLayer(layer: Layer): Boolean
  5730. // Returns `true` if the given layer is currently added to the map
  5731. hasLayer: function (layer) {
  5732. return stamp(layer) in this._layers;
  5733. },
  5734. /* @method eachLayer(fn: Function, context?: Object): this
  5735. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5736. * ```
  5737. * map.eachLayer(function(layer){
  5738. * layer.bindPopup('Hello');
  5739. * });
  5740. * ```
  5741. */
  5742. eachLayer: function (method, context) {
  5743. for (var i in this._layers) {
  5744. method.call(context, this._layers[i]);
  5745. }
  5746. return this;
  5747. },
  5748. _addLayers: function (layers) {
  5749. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5750. for (var i = 0, len = layers.length; i < len; i++) {
  5751. this.addLayer(layers[i]);
  5752. }
  5753. },
  5754. _addZoomLimit: function (layer) {
  5755. if (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5756. this._zoomBoundLayers[stamp(layer)] = layer;
  5757. this._updateZoomLevels();
  5758. }
  5759. },
  5760. _removeZoomLimit: function (layer) {
  5761. var id = stamp(layer);
  5762. if (this._zoomBoundLayers[id]) {
  5763. delete this._zoomBoundLayers[id];
  5764. this._updateZoomLevels();
  5765. }
  5766. },
  5767. _updateZoomLevels: function () {
  5768. var minZoom = Infinity,
  5769. maxZoom = -Infinity,
  5770. oldZoomSpan = this._getZoomSpan();
  5771. for (var i in this._zoomBoundLayers) {
  5772. var options = this._zoomBoundLayers[i].options;
  5773. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5774. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5775. }
  5776. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5777. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5778. // @section Map state change events
  5779. // @event zoomlevelschange: Event
  5780. // Fired when the number of zoomlevels on the map is changed due
  5781. // to adding or removing a layer.
  5782. if (oldZoomSpan !== this._getZoomSpan()) {
  5783. this.fire('zoomlevelschange');
  5784. }
  5785. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5786. this.setZoom(this._layersMaxZoom);
  5787. }
  5788. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5789. this.setZoom(this._layersMinZoom);
  5790. }
  5791. }
  5792. });
  5793. /*
  5794. * @class LayerGroup
  5795. * @aka L.LayerGroup
  5796. * @inherits Interactive layer
  5797. *
  5798. * Used to group several layers and handle them as one. If you add it to the map,
  5799. * any layers added or removed from the group will be added/removed on the map as
  5800. * well. Extends `Layer`.
  5801. *
  5802. * @example
  5803. *
  5804. * ```js
  5805. * L.layerGroup([marker1, marker2])
  5806. * .addLayer(polyline)
  5807. * .addTo(map);
  5808. * ```
  5809. */
  5810. var LayerGroup = Layer.extend({
  5811. initialize: function (layers, options) {
  5812. setOptions(this, options);
  5813. this._layers = {};
  5814. var i, len;
  5815. if (layers) {
  5816. for (i = 0, len = layers.length; i < len; i++) {
  5817. this.addLayer(layers[i]);
  5818. }
  5819. }
  5820. },
  5821. // @method addLayer(layer: Layer): this
  5822. // Adds the given layer to the group.
  5823. addLayer: function (layer) {
  5824. var id = this.getLayerId(layer);
  5825. this._layers[id] = layer;
  5826. if (this._map) {
  5827. this._map.addLayer(layer);
  5828. }
  5829. return this;
  5830. },
  5831. // @method removeLayer(layer: Layer): this
  5832. // Removes the given layer from the group.
  5833. // @alternative
  5834. // @method removeLayer(id: Number): this
  5835. // Removes the layer with the given internal ID from the group.
  5836. removeLayer: function (layer) {
  5837. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5838. if (this._map && this._layers[id]) {
  5839. this._map.removeLayer(this._layers[id]);
  5840. }
  5841. delete this._layers[id];
  5842. return this;
  5843. },
  5844. // @method hasLayer(layer: Layer): Boolean
  5845. // Returns `true` if the given layer is currently added to the group.
  5846. // @alternative
  5847. // @method hasLayer(id: Number): Boolean
  5848. // Returns `true` if the given internal ID is currently added to the group.
  5849. hasLayer: function (layer) {
  5850. var layerId = typeof layer === 'number' ? layer : this.getLayerId(layer);
  5851. return layerId in this._layers;
  5852. },
  5853. // @method clearLayers(): this
  5854. // Removes all the layers from the group.
  5855. clearLayers: function () {
  5856. return this.eachLayer(this.removeLayer, this);
  5857. },
  5858. // @method invoke(methodName: String, …): this
  5859. // Calls `methodName` on every layer contained in this group, passing any
  5860. // additional parameters. Has no effect if the layers contained do not
  5861. // implement `methodName`.
  5862. invoke: function (methodName) {
  5863. var args = Array.prototype.slice.call(arguments, 1),
  5864. i, layer;
  5865. for (i in this._layers) {
  5866. layer = this._layers[i];
  5867. if (layer[methodName]) {
  5868. layer[methodName].apply(layer, args);
  5869. }
  5870. }
  5871. return this;
  5872. },
  5873. onAdd: function (map) {
  5874. this.eachLayer(map.addLayer, map);
  5875. },
  5876. onRemove: function (map) {
  5877. this.eachLayer(map.removeLayer, map);
  5878. },
  5879. // @method eachLayer(fn: Function, context?: Object): this
  5880. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5881. // ```js
  5882. // group.eachLayer(function (layer) {
  5883. // layer.bindPopup('Hello');
  5884. // });
  5885. // ```
  5886. eachLayer: function (method, context) {
  5887. for (var i in this._layers) {
  5888. method.call(context, this._layers[i]);
  5889. }
  5890. return this;
  5891. },
  5892. // @method getLayer(id: Number): Layer
  5893. // Returns the layer with the given internal ID.
  5894. getLayer: function (id) {
  5895. return this._layers[id];
  5896. },
  5897. // @method getLayers(): Layer[]
  5898. // Returns an array of all the layers added to the group.
  5899. getLayers: function () {
  5900. var layers = [];
  5901. this.eachLayer(layers.push, layers);
  5902. return layers;
  5903. },
  5904. // @method setZIndex(zIndex: Number): this
  5905. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5906. setZIndex: function (zIndex) {
  5907. return this.invoke('setZIndex', zIndex);
  5908. },
  5909. // @method getLayerId(layer: Layer): Number
  5910. // Returns the internal ID for a layer
  5911. getLayerId: function (layer) {
  5912. return stamp(layer);
  5913. }
  5914. });
  5915. // @factory L.layerGroup(layers?: Layer[], options?: Object)
  5916. // Create a layer group, optionally given an initial set of layers and an `options` object.
  5917. var layerGroup = function (layers, options) {
  5918. return new LayerGroup(layers, options);
  5919. };
  5920. /*
  5921. * @class FeatureGroup
  5922. * @aka L.FeatureGroup
  5923. * @inherits LayerGroup
  5924. *
  5925. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5926. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5927. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5928. * handler, it will handle events from any of the layers. This includes mouse events
  5929. * and custom events.
  5930. * * Has `layeradd` and `layerremove` events
  5931. *
  5932. * @example
  5933. *
  5934. * ```js
  5935. * L.featureGroup([marker1, marker2, polyline])
  5936. * .bindPopup('Hello world!')
  5937. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5938. * .addTo(map);
  5939. * ```
  5940. */
  5941. var FeatureGroup = LayerGroup.extend({
  5942. addLayer: function (layer) {
  5943. if (this.hasLayer(layer)) {
  5944. return this;
  5945. }
  5946. layer.addEventParent(this);
  5947. LayerGroup.prototype.addLayer.call(this, layer);
  5948. // @event layeradd: LayerEvent
  5949. // Fired when a layer is added to this `FeatureGroup`
  5950. return this.fire('layeradd', {layer: layer});
  5951. },
  5952. removeLayer: function (layer) {
  5953. if (!this.hasLayer(layer)) {
  5954. return this;
  5955. }
  5956. if (layer in this._layers) {
  5957. layer = this._layers[layer];
  5958. }
  5959. layer.removeEventParent(this);
  5960. LayerGroup.prototype.removeLayer.call(this, layer);
  5961. // @event layerremove: LayerEvent
  5962. // Fired when a layer is removed from this `FeatureGroup`
  5963. return this.fire('layerremove', {layer: layer});
  5964. },
  5965. // @method setStyle(style: Path options): this
  5966. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5967. setStyle: function (style) {
  5968. return this.invoke('setStyle', style);
  5969. },
  5970. // @method bringToFront(): this
  5971. // Brings the layer group to the top of all other layers
  5972. bringToFront: function () {
  5973. return this.invoke('bringToFront');
  5974. },
  5975. // @method bringToBack(): this
  5976. // Brings the layer group to the back of all other layers
  5977. bringToBack: function () {
  5978. return this.invoke('bringToBack');
  5979. },
  5980. // @method getBounds(): LatLngBounds
  5981. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5982. getBounds: function () {
  5983. var bounds = new LatLngBounds();
  5984. for (var id in this._layers) {
  5985. var layer = this._layers[id];
  5986. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5987. }
  5988. return bounds;
  5989. }
  5990. });
  5991. // @factory L.featureGroup(layers?: Layer[], options?: Object)
  5992. // Create a feature group, optionally given an initial set of layers and an `options` object.
  5993. var featureGroup = function (layers, options) {
  5994. return new FeatureGroup(layers, options);
  5995. };
  5996. /*
  5997. * @class Icon
  5998. * @aka L.Icon
  5999. *
  6000. * Represents an icon to provide when creating a marker.
  6001. *
  6002. * @example
  6003. *
  6004. * ```js
  6005. * var myIcon = L.icon({
  6006. * iconUrl: 'my-icon.png',
  6007. * iconRetinaUrl: 'my-icon@2x.png',
  6008. * iconSize: [38, 95],
  6009. * iconAnchor: [22, 94],
  6010. * popupAnchor: [-3, -76],
  6011. * shadowUrl: 'my-icon-shadow.png',
  6012. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  6013. * shadowSize: [68, 95],
  6014. * shadowAnchor: [22, 94]
  6015. * });
  6016. *
  6017. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  6018. * ```
  6019. *
  6020. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  6021. *
  6022. */
  6023. var Icon = Class.extend({
  6024. /* @section
  6025. * @aka Icon options
  6026. *
  6027. * @option iconUrl: String = null
  6028. * **(required)** The URL to the icon image (absolute or relative to your script path).
  6029. *
  6030. * @option iconRetinaUrl: String = null
  6031. * The URL to a retina sized version of the icon image (absolute or relative to your
  6032. * script path). Used for Retina screen devices.
  6033. *
  6034. * @option iconSize: Point = null
  6035. * Size of the icon image in pixels.
  6036. *
  6037. * @option iconAnchor: Point = null
  6038. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  6039. * will be aligned so that this point is at the marker's geographical location. Centered
  6040. * by default if size is specified, also can be set in CSS with negative margins.
  6041. *
  6042. * @option popupAnchor: Point = [0, 0]
  6043. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  6044. *
  6045. * @option tooltipAnchor: Point = [0, 0]
  6046. * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
  6047. *
  6048. * @option shadowUrl: String = null
  6049. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  6050. *
  6051. * @option shadowRetinaUrl: String = null
  6052. *
  6053. * @option shadowSize: Point = null
  6054. * Size of the shadow image in pixels.
  6055. *
  6056. * @option shadowAnchor: Point = null
  6057. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  6058. * as iconAnchor if not specified).
  6059. *
  6060. * @option className: String = ''
  6061. * A custom class name to assign to both icon and shadow images. Empty by default.
  6062. */
  6063. options: {
  6064. popupAnchor: [0, 0],
  6065. tooltipAnchor: [0, 0],
  6066. // @option crossOrigin: Boolean|String = false
  6067. // Whether the crossOrigin attribute will be added to the tiles.
  6068. // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
  6069. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  6070. crossOrigin: false
  6071. },
  6072. initialize: function (options) {
  6073. setOptions(this, options);
  6074. },
  6075. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  6076. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  6077. // styled according to the options.
  6078. createIcon: function (oldIcon) {
  6079. return this._createIcon('icon', oldIcon);
  6080. },
  6081. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  6082. // As `createIcon`, but for the shadow beneath it.
  6083. createShadow: function (oldIcon) {
  6084. return this._createIcon('shadow', oldIcon);
  6085. },
  6086. _createIcon: function (name, oldIcon) {
  6087. var src = this._getIconUrl(name);
  6088. if (!src) {
  6089. if (name === 'icon') {
  6090. throw new Error('iconUrl not set in Icon options (see the docs).');
  6091. }
  6092. return null;
  6093. }
  6094. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  6095. this._setIconStyles(img, name);
  6096. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  6097. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  6098. }
  6099. return img;
  6100. },
  6101. _setIconStyles: function (img, name) {
  6102. var options = this.options;
  6103. var sizeOption = options[name + 'Size'];
  6104. if (typeof sizeOption === 'number') {
  6105. sizeOption = [sizeOption, sizeOption];
  6106. }
  6107. var size = toPoint(sizeOption),
  6108. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  6109. size && size.divideBy(2, true));
  6110. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  6111. if (anchor) {
  6112. img.style.marginLeft = (-anchor.x) + 'px';
  6113. img.style.marginTop = (-anchor.y) + 'px';
  6114. }
  6115. if (size) {
  6116. img.style.width = size.x + 'px';
  6117. img.style.height = size.y + 'px';
  6118. }
  6119. },
  6120. _createImg: function (src, el) {
  6121. el = el || document.createElement('img');
  6122. el.src = src;
  6123. return el;
  6124. },
  6125. _getIconUrl: function (name) {
  6126. return Browser.retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  6127. }
  6128. });
  6129. // @factory L.icon(options: Icon options)
  6130. // Creates an icon instance with the given options.
  6131. function icon(options) {
  6132. return new Icon(options);
  6133. }
  6134. /*
  6135. * @miniclass Icon.Default (Icon)
  6136. * @aka L.Icon.Default
  6137. * @section
  6138. *
  6139. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  6140. * no icon is specified. Points to the blue marker image distributed with Leaflet
  6141. * releases.
  6142. *
  6143. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  6144. * (which is a set of `Icon options`).
  6145. *
  6146. * If you want to _completely_ replace the default icon, override the
  6147. * `L.Marker.prototype.options.icon` with your own icon instead.
  6148. */
  6149. var IconDefault = Icon.extend({
  6150. options: {
  6151. iconUrl: 'marker-icon.png',
  6152. iconRetinaUrl: 'marker-icon-2x.png',
  6153. shadowUrl: 'marker-shadow.png',
  6154. iconSize: [25, 41],
  6155. iconAnchor: [12, 41],
  6156. popupAnchor: [1, -34],
  6157. tooltipAnchor: [16, -28],
  6158. shadowSize: [41, 41]
  6159. },
  6160. _getIconUrl: function (name) {
  6161. if (typeof IconDefault.imagePath !== 'string') { // Deprecated, backwards-compatibility only
  6162. IconDefault.imagePath = this._detectIconPath();
  6163. }
  6164. // @option imagePath: String
  6165. // `Icon.Default` will try to auto-detect the location of the
  6166. // blue icon images. If you are placing these images in a non-standard
  6167. // way, set this option to point to the right path.
  6168. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  6169. },
  6170. _stripUrl: function (path) { // separate function to use in tests
  6171. var strip = function (str, re, idx) {
  6172. var match = re.exec(str);
  6173. return match && match[idx];
  6174. };
  6175. path = strip(path, /^url\((['"])?(.+)\1\)$/, 2);
  6176. return path && strip(path, /^(.*)marker-icon\.png$/, 1);
  6177. },
  6178. _detectIconPath: function () {
  6179. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  6180. var path = getStyle(el, 'background-image') ||
  6181. getStyle(el, 'backgroundImage'); // IE8
  6182. document.body.removeChild(el);
  6183. path = this._stripUrl(path);
  6184. if (path) { return path; }
  6185. var link = document.querySelector('link[href$="leaflet.css"]');
  6186. if (!link) { return ''; }
  6187. return link.href.substring(0, link.href.length - 'leaflet.css'.length - 1);
  6188. }
  6189. });
  6190. /*
  6191. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  6192. */
  6193. /* @namespace Marker
  6194. * @section Interaction handlers
  6195. *
  6196. * 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:
  6197. *
  6198. * ```js
  6199. * marker.dragging.disable();
  6200. * ```
  6201. *
  6202. * @property dragging: Handler
  6203. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  6204. */
  6205. var MarkerDrag = Handler.extend({
  6206. initialize: function (marker) {
  6207. this._marker = marker;
  6208. },
  6209. addHooks: function () {
  6210. var icon = this._marker._icon;
  6211. if (!this._draggable) {
  6212. this._draggable = new Draggable(icon, icon, true);
  6213. }
  6214. this._draggable.on({
  6215. dragstart: this._onDragStart,
  6216. predrag: this._onPreDrag,
  6217. drag: this._onDrag,
  6218. dragend: this._onDragEnd
  6219. }, this).enable();
  6220. addClass(icon, 'leaflet-marker-draggable');
  6221. },
  6222. removeHooks: function () {
  6223. this._draggable.off({
  6224. dragstart: this._onDragStart,
  6225. predrag: this._onPreDrag,
  6226. drag: this._onDrag,
  6227. dragend: this._onDragEnd
  6228. }, this).disable();
  6229. if (this._marker._icon) {
  6230. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  6231. }
  6232. },
  6233. moved: function () {
  6234. return this._draggable && this._draggable._moved;
  6235. },
  6236. _adjustPan: function (e) {
  6237. var marker = this._marker,
  6238. map = marker._map,
  6239. speed = this._marker.options.autoPanSpeed,
  6240. padding = this._marker.options.autoPanPadding,
  6241. iconPos = getPosition(marker._icon),
  6242. bounds = map.getPixelBounds(),
  6243. origin = map.getPixelOrigin();
  6244. var panBounds = toBounds(
  6245. bounds.min._subtract(origin).add(padding),
  6246. bounds.max._subtract(origin).subtract(padding)
  6247. );
  6248. if (!panBounds.contains(iconPos)) {
  6249. // Compute incremental movement
  6250. var movement = toPoint(
  6251. (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
  6252. (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
  6253. (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
  6254. (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
  6255. ).multiplyBy(speed);
  6256. map.panBy(movement, {animate: false});
  6257. this._draggable._newPos._add(movement);
  6258. this._draggable._startPos._add(movement);
  6259. setPosition(marker._icon, this._draggable._newPos);
  6260. this._onDrag(e);
  6261. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  6262. }
  6263. },
  6264. _onDragStart: function () {
  6265. // @section Dragging events
  6266. // @event dragstart: Event
  6267. // Fired when the user starts dragging the marker.
  6268. // @event movestart: Event
  6269. // Fired when the marker starts moving (because of dragging).
  6270. this._oldLatLng = this._marker.getLatLng();
  6271. // When using ES6 imports it could not be set when `Popup` was not imported as well
  6272. this._marker.closePopup && this._marker.closePopup();
  6273. this._marker
  6274. .fire('movestart')
  6275. .fire('dragstart');
  6276. },
  6277. _onPreDrag: function (e) {
  6278. if (this._marker.options.autoPan) {
  6279. cancelAnimFrame(this._panRequest);
  6280. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  6281. }
  6282. },
  6283. _onDrag: function (e) {
  6284. var marker = this._marker,
  6285. shadow = marker._shadow,
  6286. iconPos = getPosition(marker._icon),
  6287. latlng = marker._map.layerPointToLatLng(iconPos);
  6288. // update shadow position
  6289. if (shadow) {
  6290. setPosition(shadow, iconPos);
  6291. }
  6292. marker._latlng = latlng;
  6293. e.latlng = latlng;
  6294. e.oldLatLng = this._oldLatLng;
  6295. // @event drag: Event
  6296. // Fired repeatedly while the user drags the marker.
  6297. marker
  6298. .fire('move', e)
  6299. .fire('drag', e);
  6300. },
  6301. _onDragEnd: function (e) {
  6302. // @event dragend: DragEndEvent
  6303. // Fired when the user stops dragging the marker.
  6304. cancelAnimFrame(this._panRequest);
  6305. // @event moveend: Event
  6306. // Fired when the marker stops moving (because of dragging).
  6307. delete this._oldLatLng;
  6308. this._marker
  6309. .fire('moveend')
  6310. .fire('dragend', e);
  6311. }
  6312. });
  6313. /*
  6314. * @class Marker
  6315. * @inherits Interactive layer
  6316. * @aka L.Marker
  6317. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  6318. *
  6319. * @example
  6320. *
  6321. * ```js
  6322. * L.marker([50.5, 30.5]).addTo(map);
  6323. * ```
  6324. */
  6325. var Marker = Layer.extend({
  6326. // @section
  6327. // @aka Marker options
  6328. options: {
  6329. // @option icon: Icon = *
  6330. // Icon instance to use for rendering the marker.
  6331. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  6332. // If not specified, a common instance of `L.Icon.Default` is used.
  6333. icon: new IconDefault(),
  6334. // Option inherited from "Interactive layer" abstract class
  6335. interactive: true,
  6336. // @option keyboard: Boolean = true
  6337. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  6338. keyboard: true,
  6339. // @option title: String = ''
  6340. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  6341. // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
  6342. title: '',
  6343. // @option alt: String = 'Marker'
  6344. // Text for the `alt` attribute of the icon image.
  6345. // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
  6346. alt: 'Marker',
  6347. // @option zIndexOffset: Number = 0
  6348. // 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).
  6349. zIndexOffset: 0,
  6350. // @option opacity: Number = 1.0
  6351. // The opacity of the marker.
  6352. opacity: 1,
  6353. // @option riseOnHover: Boolean = false
  6354. // If `true`, the marker will get on top of others when you hover the mouse over it.
  6355. riseOnHover: false,
  6356. // @option riseOffset: Number = 250
  6357. // The z-index offset used for the `riseOnHover` feature.
  6358. riseOffset: 250,
  6359. // @option pane: String = 'markerPane'
  6360. // `Map pane` where the markers icon will be added.
  6361. pane: 'markerPane',
  6362. // @option shadowPane: String = 'shadowPane'
  6363. // `Map pane` where the markers shadow will be added.
  6364. shadowPane: 'shadowPane',
  6365. // @option bubblingMouseEvents: Boolean = false
  6366. // When `true`, a mouse event on this marker will trigger the same event on the map
  6367. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6368. bubblingMouseEvents: false,
  6369. // @option autoPanOnFocus: Boolean = true
  6370. // When `true`, the map will pan whenever the marker is focused (via
  6371. // e.g. pressing `tab` on the keyboard) to ensure the marker is
  6372. // visible within the map's bounds
  6373. autoPanOnFocus: true,
  6374. // @section Draggable marker options
  6375. // @option draggable: Boolean = false
  6376. // Whether the marker is draggable with mouse/touch or not.
  6377. draggable: false,
  6378. // @option autoPan: Boolean = false
  6379. // Whether to pan the map when dragging this marker near its edge or not.
  6380. autoPan: false,
  6381. // @option autoPanPadding: Point = Point(50, 50)
  6382. // Distance (in pixels to the left/right and to the top/bottom) of the
  6383. // map edge to start panning the map.
  6384. autoPanPadding: [50, 50],
  6385. // @option autoPanSpeed: Number = 10
  6386. // Number of pixels the map should pan by.
  6387. autoPanSpeed: 10
  6388. },
  6389. /* @section
  6390. *
  6391. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  6392. */
  6393. initialize: function (latlng, options) {
  6394. setOptions(this, options);
  6395. this._latlng = toLatLng(latlng);
  6396. },
  6397. onAdd: function (map) {
  6398. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  6399. if (this._zoomAnimated) {
  6400. map.on('zoomanim', this._animateZoom, this);
  6401. }
  6402. this._initIcon();
  6403. this.update();
  6404. },
  6405. onRemove: function (map) {
  6406. if (this.dragging && this.dragging.enabled()) {
  6407. this.options.draggable = true;
  6408. this.dragging.removeHooks();
  6409. }
  6410. delete this.dragging;
  6411. if (this._zoomAnimated) {
  6412. map.off('zoomanim', this._animateZoom, this);
  6413. }
  6414. this._removeIcon();
  6415. this._removeShadow();
  6416. },
  6417. getEvents: function () {
  6418. return {
  6419. zoom: this.update,
  6420. viewreset: this.update
  6421. };
  6422. },
  6423. // @method getLatLng: LatLng
  6424. // Returns the current geographical position of the marker.
  6425. getLatLng: function () {
  6426. return this._latlng;
  6427. },
  6428. // @method setLatLng(latlng: LatLng): this
  6429. // Changes the marker position to the given point.
  6430. setLatLng: function (latlng) {
  6431. var oldLatLng = this._latlng;
  6432. this._latlng = toLatLng(latlng);
  6433. this.update();
  6434. // @event move: Event
  6435. // 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`.
  6436. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6437. },
  6438. // @method setZIndexOffset(offset: Number): this
  6439. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6440. setZIndexOffset: function (offset) {
  6441. this.options.zIndexOffset = offset;
  6442. return this.update();
  6443. },
  6444. // @method getIcon: Icon
  6445. // Returns the current icon used by the marker
  6446. getIcon: function () {
  6447. return this.options.icon;
  6448. },
  6449. // @method setIcon(icon: Icon): this
  6450. // Changes the marker icon.
  6451. setIcon: function (icon) {
  6452. this.options.icon = icon;
  6453. if (this._map) {
  6454. this._initIcon();
  6455. this.update();
  6456. }
  6457. if (this._popup) {
  6458. this.bindPopup(this._popup, this._popup.options);
  6459. }
  6460. return this;
  6461. },
  6462. getElement: function () {
  6463. return this._icon;
  6464. },
  6465. update: function () {
  6466. if (this._icon && this._map) {
  6467. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6468. this._setPos(pos);
  6469. }
  6470. return this;
  6471. },
  6472. _initIcon: function () {
  6473. var options = this.options,
  6474. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6475. var icon = options.icon.createIcon(this._icon),
  6476. addIcon = false;
  6477. // if we're not reusing the icon, remove the old one and init new one
  6478. if (icon !== this._icon) {
  6479. if (this._icon) {
  6480. this._removeIcon();
  6481. }
  6482. addIcon = true;
  6483. if (options.title) {
  6484. icon.title = options.title;
  6485. }
  6486. if (icon.tagName === 'IMG') {
  6487. icon.alt = options.alt || '';
  6488. }
  6489. }
  6490. addClass(icon, classToAdd);
  6491. if (options.keyboard) {
  6492. icon.tabIndex = '0';
  6493. icon.setAttribute('role', 'button');
  6494. }
  6495. this._icon = icon;
  6496. if (options.riseOnHover) {
  6497. this.on({
  6498. mouseover: this._bringToFront,
  6499. mouseout: this._resetZIndex
  6500. });
  6501. }
  6502. if (this.options.autoPanOnFocus) {
  6503. on(icon, 'focus', this._panOnFocus, this);
  6504. }
  6505. var newShadow = options.icon.createShadow(this._shadow),
  6506. addShadow = false;
  6507. if (newShadow !== this._shadow) {
  6508. this._removeShadow();
  6509. addShadow = true;
  6510. }
  6511. if (newShadow) {
  6512. addClass(newShadow, classToAdd);
  6513. newShadow.alt = '';
  6514. }
  6515. this._shadow = newShadow;
  6516. if (options.opacity < 1) {
  6517. this._updateOpacity();
  6518. }
  6519. if (addIcon) {
  6520. this.getPane().appendChild(this._icon);
  6521. }
  6522. this._initInteraction();
  6523. if (newShadow && addShadow) {
  6524. this.getPane(options.shadowPane).appendChild(this._shadow);
  6525. }
  6526. },
  6527. _removeIcon: function () {
  6528. if (this.options.riseOnHover) {
  6529. this.off({
  6530. mouseover: this._bringToFront,
  6531. mouseout: this._resetZIndex
  6532. });
  6533. }
  6534. if (this.options.autoPanOnFocus) {
  6535. off(this._icon, 'focus', this._panOnFocus, this);
  6536. }
  6537. remove(this._icon);
  6538. this.removeInteractiveTarget(this._icon);
  6539. this._icon = null;
  6540. },
  6541. _removeShadow: function () {
  6542. if (this._shadow) {
  6543. remove(this._shadow);
  6544. }
  6545. this._shadow = null;
  6546. },
  6547. _setPos: function (pos) {
  6548. if (this._icon) {
  6549. setPosition(this._icon, pos);
  6550. }
  6551. if (this._shadow) {
  6552. setPosition(this._shadow, pos);
  6553. }
  6554. this._zIndex = pos.y + this.options.zIndexOffset;
  6555. this._resetZIndex();
  6556. },
  6557. _updateZIndex: function (offset) {
  6558. if (this._icon) {
  6559. this._icon.style.zIndex = this._zIndex + offset;
  6560. }
  6561. },
  6562. _animateZoom: function (opt) {
  6563. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6564. this._setPos(pos);
  6565. },
  6566. _initInteraction: function () {
  6567. if (!this.options.interactive) { return; }
  6568. addClass(this._icon, 'leaflet-interactive');
  6569. this.addInteractiveTarget(this._icon);
  6570. if (MarkerDrag) {
  6571. var draggable = this.options.draggable;
  6572. if (this.dragging) {
  6573. draggable = this.dragging.enabled();
  6574. this.dragging.disable();
  6575. }
  6576. this.dragging = new MarkerDrag(this);
  6577. if (draggable) {
  6578. this.dragging.enable();
  6579. }
  6580. }
  6581. },
  6582. // @method setOpacity(opacity: Number): this
  6583. // Changes the opacity of the marker.
  6584. setOpacity: function (opacity) {
  6585. this.options.opacity = opacity;
  6586. if (this._map) {
  6587. this._updateOpacity();
  6588. }
  6589. return this;
  6590. },
  6591. _updateOpacity: function () {
  6592. var opacity = this.options.opacity;
  6593. if (this._icon) {
  6594. setOpacity(this._icon, opacity);
  6595. }
  6596. if (this._shadow) {
  6597. setOpacity(this._shadow, opacity);
  6598. }
  6599. },
  6600. _bringToFront: function () {
  6601. this._updateZIndex(this.options.riseOffset);
  6602. },
  6603. _resetZIndex: function () {
  6604. this._updateZIndex(0);
  6605. },
  6606. _panOnFocus: function () {
  6607. var map = this._map;
  6608. if (!map) { return; }
  6609. var iconOpts = this.options.icon.options;
  6610. var size = iconOpts.iconSize ? toPoint(iconOpts.iconSize) : toPoint(0, 0);
  6611. var anchor = iconOpts.iconAnchor ? toPoint(iconOpts.iconAnchor) : toPoint(0, 0);
  6612. map.panInside(this._latlng, {
  6613. paddingTopLeft: anchor,
  6614. paddingBottomRight: size.subtract(anchor)
  6615. });
  6616. },
  6617. _getPopupAnchor: function () {
  6618. return this.options.icon.options.popupAnchor;
  6619. },
  6620. _getTooltipAnchor: function () {
  6621. return this.options.icon.options.tooltipAnchor;
  6622. }
  6623. });
  6624. // factory L.marker(latlng: LatLng, options? : Marker options)
  6625. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6626. // Instantiates a Marker object given a geographical point and optionally an options object.
  6627. function marker(latlng, options) {
  6628. return new Marker(latlng, options);
  6629. }
  6630. /*
  6631. * @class Path
  6632. * @aka L.Path
  6633. * @inherits Interactive layer
  6634. *
  6635. * An abstract class that contains options and constants shared between vector
  6636. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6637. */
  6638. var Path = Layer.extend({
  6639. // @section
  6640. // @aka Path options
  6641. options: {
  6642. // @option stroke: Boolean = true
  6643. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6644. stroke: true,
  6645. // @option color: String = '#3388ff'
  6646. // Stroke color
  6647. color: '#3388ff',
  6648. // @option weight: Number = 3
  6649. // Stroke width in pixels
  6650. weight: 3,
  6651. // @option opacity: Number = 1.0
  6652. // Stroke opacity
  6653. opacity: 1,
  6654. // @option lineCap: String= 'round'
  6655. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6656. lineCap: 'round',
  6657. // @option lineJoin: String = 'round'
  6658. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6659. lineJoin: 'round',
  6660. // @option dashArray: String = null
  6661. // 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).
  6662. dashArray: null,
  6663. // @option dashOffset: String = null
  6664. // 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).
  6665. dashOffset: null,
  6666. // @option fill: Boolean = depends
  6667. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6668. fill: false,
  6669. // @option fillColor: String = *
  6670. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6671. fillColor: null,
  6672. // @option fillOpacity: Number = 0.2
  6673. // Fill opacity.
  6674. fillOpacity: 0.2,
  6675. // @option fillRule: String = 'evenodd'
  6676. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6677. fillRule: 'evenodd',
  6678. // className: '',
  6679. // Option inherited from "Interactive layer" abstract class
  6680. interactive: true,
  6681. // @option bubblingMouseEvents: Boolean = true
  6682. // When `true`, a mouse event on this path will trigger the same event on the map
  6683. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6684. bubblingMouseEvents: true
  6685. },
  6686. beforeAdd: function (map) {
  6687. // Renderer is set here because we need to call renderer.getEvents
  6688. // before this.getEvents.
  6689. this._renderer = map.getRenderer(this);
  6690. },
  6691. onAdd: function () {
  6692. this._renderer._initPath(this);
  6693. this._reset();
  6694. this._renderer._addPath(this);
  6695. },
  6696. onRemove: function () {
  6697. this._renderer._removePath(this);
  6698. },
  6699. // @method redraw(): this
  6700. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6701. redraw: function () {
  6702. if (this._map) {
  6703. this._renderer._updatePath(this);
  6704. }
  6705. return this;
  6706. },
  6707. // @method setStyle(style: Path options): this
  6708. // Changes the appearance of a Path based on the options in the `Path options` object.
  6709. setStyle: function (style) {
  6710. setOptions(this, style);
  6711. if (this._renderer) {
  6712. this._renderer._updateStyle(this);
  6713. if (this.options.stroke && style && Object.prototype.hasOwnProperty.call(style, 'weight')) {
  6714. this._updateBounds();
  6715. }
  6716. }
  6717. return this;
  6718. },
  6719. // @method bringToFront(): this
  6720. // Brings the layer to the top of all path layers.
  6721. bringToFront: function () {
  6722. if (this._renderer) {
  6723. this._renderer._bringToFront(this);
  6724. }
  6725. return this;
  6726. },
  6727. // @method bringToBack(): this
  6728. // Brings the layer to the bottom of all path layers.
  6729. bringToBack: function () {
  6730. if (this._renderer) {
  6731. this._renderer._bringToBack(this);
  6732. }
  6733. return this;
  6734. },
  6735. getElement: function () {
  6736. return this._path;
  6737. },
  6738. _reset: function () {
  6739. // defined in child classes
  6740. this._project();
  6741. this._update();
  6742. },
  6743. _clickTolerance: function () {
  6744. // used when doing hit detection for Canvas layers
  6745. return (this.options.stroke ? this.options.weight / 2 : 0) +
  6746. (this._renderer.options.tolerance || 0);
  6747. }
  6748. });
  6749. /*
  6750. * @class CircleMarker
  6751. * @aka L.CircleMarker
  6752. * @inherits Path
  6753. *
  6754. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6755. */
  6756. var CircleMarker = Path.extend({
  6757. // @section
  6758. // @aka CircleMarker options
  6759. options: {
  6760. fill: true,
  6761. // @option radius: Number = 10
  6762. // Radius of the circle marker, in pixels
  6763. radius: 10
  6764. },
  6765. initialize: function (latlng, options) {
  6766. setOptions(this, options);
  6767. this._latlng = toLatLng(latlng);
  6768. this._radius = this.options.radius;
  6769. },
  6770. // @method setLatLng(latLng: LatLng): this
  6771. // Sets the position of a circle marker to a new location.
  6772. setLatLng: function (latlng) {
  6773. var oldLatLng = this._latlng;
  6774. this._latlng = toLatLng(latlng);
  6775. this.redraw();
  6776. // @event move: Event
  6777. // Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
  6778. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6779. },
  6780. // @method getLatLng(): LatLng
  6781. // Returns the current geographical position of the circle marker
  6782. getLatLng: function () {
  6783. return this._latlng;
  6784. },
  6785. // @method setRadius(radius: Number): this
  6786. // Sets the radius of a circle marker. Units are in pixels.
  6787. setRadius: function (radius) {
  6788. this.options.radius = this._radius = radius;
  6789. return this.redraw();
  6790. },
  6791. // @method getRadius(): Number
  6792. // Returns the current radius of the circle
  6793. getRadius: function () {
  6794. return this._radius;
  6795. },
  6796. setStyle : function (options) {
  6797. var radius = options && options.radius || this._radius;
  6798. Path.prototype.setStyle.call(this, options);
  6799. this.setRadius(radius);
  6800. return this;
  6801. },
  6802. _project: function () {
  6803. this._point = this._map.latLngToLayerPoint(this._latlng);
  6804. this._updateBounds();
  6805. },
  6806. _updateBounds: function () {
  6807. var r = this._radius,
  6808. r2 = this._radiusY || r,
  6809. w = this._clickTolerance(),
  6810. p = [r + w, r2 + w];
  6811. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6812. },
  6813. _update: function () {
  6814. if (this._map) {
  6815. this._updatePath();
  6816. }
  6817. },
  6818. _updatePath: function () {
  6819. this._renderer._updateCircle(this);
  6820. },
  6821. _empty: function () {
  6822. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6823. },
  6824. // Needed by the `Canvas` renderer for interactivity
  6825. _containsPoint: function (p) {
  6826. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6827. }
  6828. });
  6829. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6830. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6831. function circleMarker(latlng, options) {
  6832. return new CircleMarker(latlng, options);
  6833. }
  6834. /*
  6835. * @class Circle
  6836. * @aka L.Circle
  6837. * @inherits CircleMarker
  6838. *
  6839. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6840. *
  6841. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6842. *
  6843. * @example
  6844. *
  6845. * ```js
  6846. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6847. * ```
  6848. */
  6849. var Circle = CircleMarker.extend({
  6850. initialize: function (latlng, options, legacyOptions) {
  6851. if (typeof options === 'number') {
  6852. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6853. options = extend({}, legacyOptions, {radius: options});
  6854. }
  6855. setOptions(this, options);
  6856. this._latlng = toLatLng(latlng);
  6857. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6858. // @section
  6859. // @aka Circle options
  6860. // @option radius: Number; Radius of the circle, in meters.
  6861. this._mRadius = this.options.radius;
  6862. },
  6863. // @method setRadius(radius: Number): this
  6864. // Sets the radius of a circle. Units are in meters.
  6865. setRadius: function (radius) {
  6866. this._mRadius = radius;
  6867. return this.redraw();
  6868. },
  6869. // @method getRadius(): Number
  6870. // Returns the current radius of a circle. Units are in meters.
  6871. getRadius: function () {
  6872. return this._mRadius;
  6873. },
  6874. // @method getBounds(): LatLngBounds
  6875. // Returns the `LatLngBounds` of the path.
  6876. getBounds: function () {
  6877. var half = [this._radius, this._radiusY || this._radius];
  6878. return new LatLngBounds(
  6879. this._map.layerPointToLatLng(this._point.subtract(half)),
  6880. this._map.layerPointToLatLng(this._point.add(half)));
  6881. },
  6882. setStyle: Path.prototype.setStyle,
  6883. _project: function () {
  6884. var lng = this._latlng.lng,
  6885. lat = this._latlng.lat,
  6886. map = this._map,
  6887. crs = map.options.crs;
  6888. if (crs.distance === Earth.distance) {
  6889. var d = Math.PI / 180,
  6890. latR = (this._mRadius / Earth.R) / d,
  6891. top = map.project([lat + latR, lng]),
  6892. bottom = map.project([lat - latR, lng]),
  6893. p = top.add(bottom).divideBy(2),
  6894. lat2 = map.unproject(p).lat,
  6895. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6896. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6897. if (isNaN(lngR) || lngR === 0) {
  6898. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6899. }
  6900. this._point = p.subtract(map.getPixelOrigin());
  6901. this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
  6902. this._radiusY = p.y - top.y;
  6903. } else {
  6904. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6905. this._point = map.latLngToLayerPoint(this._latlng);
  6906. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6907. }
  6908. this._updateBounds();
  6909. }
  6910. });
  6911. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6912. // Instantiates a circle object given a geographical point, and an options object
  6913. // which contains the circle radius.
  6914. // @alternative
  6915. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6916. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6917. // Do not use in new applications or plugins.
  6918. function circle(latlng, options, legacyOptions) {
  6919. return new Circle(latlng, options, legacyOptions);
  6920. }
  6921. /*
  6922. * @class Polyline
  6923. * @aka L.Polyline
  6924. * @inherits Path
  6925. *
  6926. * A class for drawing polyline overlays on a map. Extends `Path`.
  6927. *
  6928. * @example
  6929. *
  6930. * ```js
  6931. * // create a red polyline from an array of LatLng points
  6932. * var latlngs = [
  6933. * [45.51, -122.68],
  6934. * [37.77, -122.43],
  6935. * [34.04, -118.2]
  6936. * ];
  6937. *
  6938. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6939. *
  6940. * // zoom the map to the polyline
  6941. * map.fitBounds(polyline.getBounds());
  6942. * ```
  6943. *
  6944. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6945. *
  6946. * ```js
  6947. * // create a red polyline from an array of arrays of LatLng points
  6948. * var latlngs = [
  6949. * [[45.51, -122.68],
  6950. * [37.77, -122.43],
  6951. * [34.04, -118.2]],
  6952. * [[40.78, -73.91],
  6953. * [41.83, -87.62],
  6954. * [32.76, -96.72]]
  6955. * ];
  6956. * ```
  6957. */
  6958. var Polyline = Path.extend({
  6959. // @section
  6960. // @aka Polyline options
  6961. options: {
  6962. // @option smoothFactor: Number = 1.0
  6963. // How much to simplify the polyline on each zoom level. More means
  6964. // better performance and smoother look, and less means more accurate representation.
  6965. smoothFactor: 1.0,
  6966. // @option noClip: Boolean = false
  6967. // Disable polyline clipping.
  6968. noClip: false
  6969. },
  6970. initialize: function (latlngs, options) {
  6971. setOptions(this, options);
  6972. this._setLatLngs(latlngs);
  6973. },
  6974. // @method getLatLngs(): LatLng[]
  6975. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6976. getLatLngs: function () {
  6977. return this._latlngs;
  6978. },
  6979. // @method setLatLngs(latlngs: LatLng[]): this
  6980. // Replaces all the points in the polyline with the given array of geographical points.
  6981. setLatLngs: function (latlngs) {
  6982. this._setLatLngs(latlngs);
  6983. return this.redraw();
  6984. },
  6985. // @method isEmpty(): Boolean
  6986. // Returns `true` if the Polyline has no LatLngs.
  6987. isEmpty: function () {
  6988. return !this._latlngs.length;
  6989. },
  6990. // @method closestLayerPoint(p: Point): Point
  6991. // Returns the point closest to `p` on the Polyline.
  6992. closestLayerPoint: function (p) {
  6993. var minDistance = Infinity,
  6994. minPoint = null,
  6995. closest = _sqClosestPointOnSegment,
  6996. p1, p2;
  6997. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6998. var points = this._parts[j];
  6999. for (var i = 1, len = points.length; i < len; i++) {
  7000. p1 = points[i - 1];
  7001. p2 = points[i];
  7002. var sqDist = closest(p, p1, p2, true);
  7003. if (sqDist < minDistance) {
  7004. minDistance = sqDist;
  7005. minPoint = closest(p, p1, p2);
  7006. }
  7007. }
  7008. }
  7009. if (minPoint) {
  7010. minPoint.distance = Math.sqrt(minDistance);
  7011. }
  7012. return minPoint;
  7013. },
  7014. // @method getCenter(): LatLng
  7015. // Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline.
  7016. getCenter: function () {
  7017. // throws error when not yet added to map as this center calculation requires projected coordinates
  7018. if (!this._map) {
  7019. throw new Error('Must add layer to map before using getCenter()');
  7020. }
  7021. return polylineCenter(this._defaultShape(), this._map.options.crs);
  7022. },
  7023. // @method getBounds(): LatLngBounds
  7024. // Returns the `LatLngBounds` of the path.
  7025. getBounds: function () {
  7026. return this._bounds;
  7027. },
  7028. // @method addLatLng(latlng: LatLng, latlngs?: LatLng[]): this
  7029. // Adds a given point to the polyline. By default, adds to the first ring of
  7030. // the polyline in case of a multi-polyline, but can be overridden by passing
  7031. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  7032. addLatLng: function (latlng, latlngs) {
  7033. latlngs = latlngs || this._defaultShape();
  7034. latlng = toLatLng(latlng);
  7035. latlngs.push(latlng);
  7036. this._bounds.extend(latlng);
  7037. return this.redraw();
  7038. },
  7039. _setLatLngs: function (latlngs) {
  7040. this._bounds = new LatLngBounds();
  7041. this._latlngs = this._convertLatLngs(latlngs);
  7042. },
  7043. _defaultShape: function () {
  7044. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  7045. },
  7046. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  7047. _convertLatLngs: function (latlngs) {
  7048. var result = [],
  7049. flat = isFlat(latlngs);
  7050. for (var i = 0, len = latlngs.length; i < len; i++) {
  7051. if (flat) {
  7052. result[i] = toLatLng(latlngs[i]);
  7053. this._bounds.extend(result[i]);
  7054. } else {
  7055. result[i] = this._convertLatLngs(latlngs[i]);
  7056. }
  7057. }
  7058. return result;
  7059. },
  7060. _project: function () {
  7061. var pxBounds = new Bounds();
  7062. this._rings = [];
  7063. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  7064. if (this._bounds.isValid() && pxBounds.isValid()) {
  7065. this._rawPxBounds = pxBounds;
  7066. this._updateBounds();
  7067. }
  7068. },
  7069. _updateBounds: function () {
  7070. var w = this._clickTolerance(),
  7071. p = new Point(w, w);
  7072. if (!this._rawPxBounds) {
  7073. return;
  7074. }
  7075. this._pxBounds = new Bounds([
  7076. this._rawPxBounds.min.subtract(p),
  7077. this._rawPxBounds.max.add(p)
  7078. ]);
  7079. },
  7080. // recursively turns latlngs into a set of rings with projected coordinates
  7081. _projectLatlngs: function (latlngs, result, projectedBounds) {
  7082. var flat = latlngs[0] instanceof LatLng,
  7083. len = latlngs.length,
  7084. i, ring;
  7085. if (flat) {
  7086. ring = [];
  7087. for (i = 0; i < len; i++) {
  7088. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  7089. projectedBounds.extend(ring[i]);
  7090. }
  7091. result.push(ring);
  7092. } else {
  7093. for (i = 0; i < len; i++) {
  7094. this._projectLatlngs(latlngs[i], result, projectedBounds);
  7095. }
  7096. }
  7097. },
  7098. // clip polyline by renderer bounds so that we have less to render for performance
  7099. _clipPoints: function () {
  7100. var bounds = this._renderer._bounds;
  7101. this._parts = [];
  7102. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7103. return;
  7104. }
  7105. if (this.options.noClip) {
  7106. this._parts = this._rings;
  7107. return;
  7108. }
  7109. var parts = this._parts,
  7110. i, j, k, len, len2, segment, points;
  7111. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  7112. points = this._rings[i];
  7113. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  7114. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  7115. if (!segment) { continue; }
  7116. parts[k] = parts[k] || [];
  7117. parts[k].push(segment[0]);
  7118. // if segment goes out of screen, or it's the last one, it's the end of the line part
  7119. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  7120. parts[k].push(segment[1]);
  7121. k++;
  7122. }
  7123. }
  7124. }
  7125. },
  7126. // simplify each clipped part of the polyline for performance
  7127. _simplifyPoints: function () {
  7128. var parts = this._parts,
  7129. tolerance = this.options.smoothFactor;
  7130. for (var i = 0, len = parts.length; i < len; i++) {
  7131. parts[i] = simplify(parts[i], tolerance);
  7132. }
  7133. },
  7134. _update: function () {
  7135. if (!this._map) { return; }
  7136. this._clipPoints();
  7137. this._simplifyPoints();
  7138. this._updatePath();
  7139. },
  7140. _updatePath: function () {
  7141. this._renderer._updatePoly(this);
  7142. },
  7143. // Needed by the `Canvas` renderer for interactivity
  7144. _containsPoint: function (p, closed) {
  7145. var i, j, k, len, len2, part,
  7146. w = this._clickTolerance();
  7147. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  7148. // hit detection for polylines
  7149. for (i = 0, len = this._parts.length; i < len; i++) {
  7150. part = this._parts[i];
  7151. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7152. if (!closed && (j === 0)) { continue; }
  7153. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  7154. return true;
  7155. }
  7156. }
  7157. }
  7158. return false;
  7159. }
  7160. });
  7161. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  7162. // Instantiates a polyline object given an array of geographical points and
  7163. // optionally an options object. You can create a `Polyline` object with
  7164. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  7165. // of geographic points.
  7166. function polyline(latlngs, options) {
  7167. return new Polyline(latlngs, options);
  7168. }
  7169. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  7170. Polyline._flat = _flat;
  7171. /*
  7172. * @class Polygon
  7173. * @aka L.Polygon
  7174. * @inherits Polyline
  7175. *
  7176. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  7177. *
  7178. * 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.
  7179. *
  7180. *
  7181. * @example
  7182. *
  7183. * ```js
  7184. * // create a red polygon from an array of LatLng points
  7185. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  7186. *
  7187. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  7188. *
  7189. * // zoom the map to the polygon
  7190. * map.fitBounds(polygon.getBounds());
  7191. * ```
  7192. *
  7193. * 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:
  7194. *
  7195. * ```js
  7196. * var latlngs = [
  7197. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7198. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7199. * ];
  7200. * ```
  7201. *
  7202. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  7203. *
  7204. * ```js
  7205. * var latlngs = [
  7206. * [ // first polygon
  7207. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7208. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7209. * ],
  7210. * [ // second polygon
  7211. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  7212. * ]
  7213. * ];
  7214. * ```
  7215. */
  7216. var Polygon = Polyline.extend({
  7217. options: {
  7218. fill: true
  7219. },
  7220. isEmpty: function () {
  7221. return !this._latlngs.length || !this._latlngs[0].length;
  7222. },
  7223. // @method getCenter(): LatLng
  7224. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the Polygon.
  7225. getCenter: function () {
  7226. // throws error when not yet added to map as this center calculation requires projected coordinates
  7227. if (!this._map) {
  7228. throw new Error('Must add layer to map before using getCenter()');
  7229. }
  7230. return polygonCenter(this._defaultShape(), this._map.options.crs);
  7231. },
  7232. _convertLatLngs: function (latlngs) {
  7233. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  7234. len = result.length;
  7235. // remove last point if it equals first one
  7236. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  7237. result.pop();
  7238. }
  7239. return result;
  7240. },
  7241. _setLatLngs: function (latlngs) {
  7242. Polyline.prototype._setLatLngs.call(this, latlngs);
  7243. if (isFlat(this._latlngs)) {
  7244. this._latlngs = [this._latlngs];
  7245. }
  7246. },
  7247. _defaultShape: function () {
  7248. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  7249. },
  7250. _clipPoints: function () {
  7251. // polygons need a different clipping algorithm so we redefine that
  7252. var bounds = this._renderer._bounds,
  7253. w = this.options.weight,
  7254. p = new Point(w, w);
  7255. // increase clip padding by stroke width to avoid stroke on clip edges
  7256. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  7257. this._parts = [];
  7258. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7259. return;
  7260. }
  7261. if (this.options.noClip) {
  7262. this._parts = this._rings;
  7263. return;
  7264. }
  7265. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  7266. clipped = clipPolygon(this._rings[i], bounds, true);
  7267. if (clipped.length) {
  7268. this._parts.push(clipped);
  7269. }
  7270. }
  7271. },
  7272. _updatePath: function () {
  7273. this._renderer._updatePoly(this, true);
  7274. },
  7275. // Needed by the `Canvas` renderer for interactivity
  7276. _containsPoint: function (p) {
  7277. var inside = false,
  7278. part, p1, p2, i, j, k, len, len2;
  7279. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  7280. // ray casting algorithm for detecting if point is in polygon
  7281. for (i = 0, len = this._parts.length; i < len; i++) {
  7282. part = this._parts[i];
  7283. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7284. p1 = part[j];
  7285. p2 = part[k];
  7286. 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)) {
  7287. inside = !inside;
  7288. }
  7289. }
  7290. }
  7291. // also check if it's on polygon stroke
  7292. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  7293. }
  7294. });
  7295. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  7296. function polygon(latlngs, options) {
  7297. return new Polygon(latlngs, options);
  7298. }
  7299. /*
  7300. * @class GeoJSON
  7301. * @aka L.GeoJSON
  7302. * @inherits FeatureGroup
  7303. *
  7304. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  7305. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  7306. *
  7307. * @example
  7308. *
  7309. * ```js
  7310. * L.geoJSON(data, {
  7311. * style: function (feature) {
  7312. * return {color: feature.properties.color};
  7313. * }
  7314. * }).bindPopup(function (layer) {
  7315. * return layer.feature.properties.description;
  7316. * }).addTo(map);
  7317. * ```
  7318. */
  7319. var GeoJSON = FeatureGroup.extend({
  7320. /* @section
  7321. * @aka GeoJSON options
  7322. *
  7323. * @option pointToLayer: Function = *
  7324. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  7325. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  7326. * The default is to spawn a default `Marker`:
  7327. * ```js
  7328. * function(geoJsonPoint, latlng) {
  7329. * return L.marker(latlng);
  7330. * }
  7331. * ```
  7332. *
  7333. * @option style: Function = *
  7334. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  7335. * called internally when data is added.
  7336. * The default value is to not override any defaults:
  7337. * ```js
  7338. * function (geoJsonFeature) {
  7339. * return {}
  7340. * }
  7341. * ```
  7342. *
  7343. * @option onEachFeature: Function = *
  7344. * A `Function` that will be called once for each created `Feature`, after it has
  7345. * been created and styled. Useful for attaching events and popups to features.
  7346. * The default is to do nothing with the newly created layers:
  7347. * ```js
  7348. * function (feature, layer) {}
  7349. * ```
  7350. *
  7351. * @option filter: Function = *
  7352. * A `Function` that will be used to decide whether to include a feature or not.
  7353. * The default is to include all features:
  7354. * ```js
  7355. * function (geoJsonFeature) {
  7356. * return true;
  7357. * }
  7358. * ```
  7359. * Note: dynamically changing the `filter` option will have effect only on newly
  7360. * added data. It will _not_ re-evaluate already included features.
  7361. *
  7362. * @option coordsToLatLng: Function = *
  7363. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  7364. * The default is the `coordsToLatLng` static method.
  7365. *
  7366. * @option markersInheritOptions: Boolean = false
  7367. * Whether default Markers for "Point" type Features inherit from group options.
  7368. */
  7369. initialize: function (geojson, options) {
  7370. setOptions(this, options);
  7371. this._layers = {};
  7372. if (geojson) {
  7373. this.addData(geojson);
  7374. }
  7375. },
  7376. // @method addData( <GeoJSON> data ): this
  7377. // Adds a GeoJSON object to the layer.
  7378. addData: function (geojson) {
  7379. var features = isArray(geojson) ? geojson : geojson.features,
  7380. i, len, feature;
  7381. if (features) {
  7382. for (i = 0, len = features.length; i < len; i++) {
  7383. // only add this if geometry or geometries are set and not null
  7384. feature = features[i];
  7385. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  7386. this.addData(feature);
  7387. }
  7388. }
  7389. return this;
  7390. }
  7391. var options = this.options;
  7392. if (options.filter && !options.filter(geojson)) { return this; }
  7393. var layer = geometryToLayer(geojson, options);
  7394. if (!layer) {
  7395. return this;
  7396. }
  7397. layer.feature = asFeature(geojson);
  7398. layer.defaultOptions = layer.options;
  7399. this.resetStyle(layer);
  7400. if (options.onEachFeature) {
  7401. options.onEachFeature(geojson, layer);
  7402. }
  7403. return this.addLayer(layer);
  7404. },
  7405. // @method resetStyle( <Path> layer? ): this
  7406. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7407. // If `layer` is omitted, the style of all features in the current layer is reset.
  7408. resetStyle: function (layer) {
  7409. if (layer === undefined) {
  7410. return this.eachLayer(this.resetStyle, this);
  7411. }
  7412. // reset any custom styles
  7413. layer.options = extend({}, layer.defaultOptions);
  7414. this._setLayerStyle(layer, this.options.style);
  7415. return this;
  7416. },
  7417. // @method setStyle( <Function> style ): this
  7418. // Changes styles of GeoJSON vector layers with the given style function.
  7419. setStyle: function (style) {
  7420. return this.eachLayer(function (layer) {
  7421. this._setLayerStyle(layer, style);
  7422. }, this);
  7423. },
  7424. _setLayerStyle: function (layer, style) {
  7425. if (layer.setStyle) {
  7426. if (typeof style === 'function') {
  7427. style = style(layer.feature);
  7428. }
  7429. layer.setStyle(style);
  7430. }
  7431. }
  7432. });
  7433. // @section
  7434. // There are several static functions which can be called without instantiating L.GeoJSON:
  7435. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7436. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7437. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7438. // functions if provided as options.
  7439. function geometryToLayer(geojson, options) {
  7440. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7441. coords = geometry ? geometry.coordinates : null,
  7442. layers = [],
  7443. pointToLayer = options && options.pointToLayer,
  7444. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7445. latlng, latlngs, i, len;
  7446. if (!coords && !geometry) {
  7447. return null;
  7448. }
  7449. switch (geometry.type) {
  7450. case 'Point':
  7451. latlng = _coordsToLatLng(coords);
  7452. return _pointToLayer(pointToLayer, geojson, latlng, options);
  7453. case 'MultiPoint':
  7454. for (i = 0, len = coords.length; i < len; i++) {
  7455. latlng = _coordsToLatLng(coords[i]);
  7456. layers.push(_pointToLayer(pointToLayer, geojson, latlng, options));
  7457. }
  7458. return new FeatureGroup(layers);
  7459. case 'LineString':
  7460. case 'MultiLineString':
  7461. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7462. return new Polyline(latlngs, options);
  7463. case 'Polygon':
  7464. case 'MultiPolygon':
  7465. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7466. return new Polygon(latlngs, options);
  7467. case 'GeometryCollection':
  7468. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7469. var geoLayer = geometryToLayer({
  7470. geometry: geometry.geometries[i],
  7471. type: 'Feature',
  7472. properties: geojson.properties
  7473. }, options);
  7474. if (geoLayer) {
  7475. layers.push(geoLayer);
  7476. }
  7477. }
  7478. return new FeatureGroup(layers);
  7479. case 'FeatureCollection':
  7480. for (i = 0, len = geometry.features.length; i < len; i++) {
  7481. var featureLayer = geometryToLayer(geometry.features[i], options);
  7482. if (featureLayer) {
  7483. layers.push(featureLayer);
  7484. }
  7485. }
  7486. return new FeatureGroup(layers);
  7487. default:
  7488. throw new Error('Invalid GeoJSON object.');
  7489. }
  7490. }
  7491. function _pointToLayer(pointToLayerFn, geojson, latlng, options) {
  7492. return pointToLayerFn ?
  7493. pointToLayerFn(geojson, latlng) :
  7494. new Marker(latlng, options && options.markersInheritOptions && options);
  7495. }
  7496. // @function coordsToLatLng(coords: Array): LatLng
  7497. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7498. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7499. function coordsToLatLng(coords) {
  7500. return new LatLng(coords[1], coords[0], coords[2]);
  7501. }
  7502. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7503. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7504. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7505. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7506. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7507. var latlngs = [];
  7508. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7509. latlng = levelsDeep ?
  7510. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7511. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7512. latlngs.push(latlng);
  7513. }
  7514. return latlngs;
  7515. }
  7516. // @function latLngToCoords(latlng: LatLng, precision?: Number|false): Array
  7517. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7518. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function.
  7519. function latLngToCoords(latlng, precision) {
  7520. latlng = toLatLng(latlng);
  7521. return latlng.alt !== undefined ?
  7522. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7523. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7524. }
  7525. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean, precision?: Number|false): Array
  7526. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7527. // `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.
  7528. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function.
  7529. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7530. var coords = [];
  7531. for (var i = 0, len = latlngs.length; i < len; i++) {
  7532. // Check for flat arrays required to ensure unbalanced arrays are correctly converted in recursion
  7533. coords.push(levelsDeep ?
  7534. latLngsToCoords(latlngs[i], isFlat(latlngs[i]) ? 0 : levelsDeep - 1, closed, precision) :
  7535. latLngToCoords(latlngs[i], precision));
  7536. }
  7537. if (!levelsDeep && closed && coords.length > 0) {
  7538. coords.push(coords[0].slice());
  7539. }
  7540. return coords;
  7541. }
  7542. function getFeature(layer, newGeometry) {
  7543. return layer.feature ?
  7544. extend({}, layer.feature, {geometry: newGeometry}) :
  7545. asFeature(newGeometry);
  7546. }
  7547. // @function asFeature(geojson: Object): Object
  7548. // Normalize GeoJSON geometries/features into GeoJSON features.
  7549. function asFeature(geojson) {
  7550. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7551. return geojson;
  7552. }
  7553. return {
  7554. type: 'Feature',
  7555. properties: {},
  7556. geometry: geojson
  7557. };
  7558. }
  7559. var PointToGeoJSON = {
  7560. toGeoJSON: function (precision) {
  7561. return getFeature(this, {
  7562. type: 'Point',
  7563. coordinates: latLngToCoords(this.getLatLng(), precision)
  7564. });
  7565. }
  7566. };
  7567. // @namespace Marker
  7568. // @section Other methods
  7569. // @method toGeoJSON(precision?: Number|false): Object
  7570. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7571. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7572. Marker.include(PointToGeoJSON);
  7573. // @namespace CircleMarker
  7574. // @method toGeoJSON(precision?: Number|false): Object
  7575. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7576. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7577. Circle.include(PointToGeoJSON);
  7578. CircleMarker.include(PointToGeoJSON);
  7579. // @namespace Polyline
  7580. // @method toGeoJSON(precision?: Number|false): Object
  7581. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7582. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7583. Polyline.include({
  7584. toGeoJSON: function (precision) {
  7585. var multi = !isFlat(this._latlngs);
  7586. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7587. return getFeature(this, {
  7588. type: (multi ? 'Multi' : '') + 'LineString',
  7589. coordinates: coords
  7590. });
  7591. }
  7592. });
  7593. // @namespace Polygon
  7594. // @method toGeoJSON(precision?: Number|false): Object
  7595. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7596. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7597. Polygon.include({
  7598. toGeoJSON: function (precision) {
  7599. var holes = !isFlat(this._latlngs),
  7600. multi = holes && !isFlat(this._latlngs[0]);
  7601. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7602. if (!holes) {
  7603. coords = [coords];
  7604. }
  7605. return getFeature(this, {
  7606. type: (multi ? 'Multi' : '') + 'Polygon',
  7607. coordinates: coords
  7608. });
  7609. }
  7610. });
  7611. // @namespace LayerGroup
  7612. LayerGroup.include({
  7613. toMultiPoint: function (precision) {
  7614. var coords = [];
  7615. this.eachLayer(function (layer) {
  7616. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7617. });
  7618. return getFeature(this, {
  7619. type: 'MultiPoint',
  7620. coordinates: coords
  7621. });
  7622. },
  7623. // @method toGeoJSON(precision?: Number|false): Object
  7624. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7625. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7626. toGeoJSON: function (precision) {
  7627. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7628. if (type === 'MultiPoint') {
  7629. return this.toMultiPoint(precision);
  7630. }
  7631. var isGeometryCollection = type === 'GeometryCollection',
  7632. jsons = [];
  7633. this.eachLayer(function (layer) {
  7634. if (layer.toGeoJSON) {
  7635. var json = layer.toGeoJSON(precision);
  7636. if (isGeometryCollection) {
  7637. jsons.push(json.geometry);
  7638. } else {
  7639. var feature = asFeature(json);
  7640. // Squash nested feature collections
  7641. if (feature.type === 'FeatureCollection') {
  7642. jsons.push.apply(jsons, feature.features);
  7643. } else {
  7644. jsons.push(feature);
  7645. }
  7646. }
  7647. }
  7648. });
  7649. if (isGeometryCollection) {
  7650. return getFeature(this, {
  7651. geometries: jsons,
  7652. type: 'GeometryCollection'
  7653. });
  7654. }
  7655. return {
  7656. type: 'FeatureCollection',
  7657. features: jsons
  7658. };
  7659. }
  7660. });
  7661. // @namespace GeoJSON
  7662. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7663. // Creates a GeoJSON layer. Optionally accepts an object in
  7664. // [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map
  7665. // (you can alternatively add it later with `addData` method) and an `options` object.
  7666. function geoJSON(geojson, options) {
  7667. return new GeoJSON(geojson, options);
  7668. }
  7669. // Backward compatibility.
  7670. var geoJson = geoJSON;
  7671. /*
  7672. * @class ImageOverlay
  7673. * @aka L.ImageOverlay
  7674. * @inherits Interactive layer
  7675. *
  7676. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7677. *
  7678. * @example
  7679. *
  7680. * ```js
  7681. * var imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7682. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7683. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7684. * ```
  7685. */
  7686. var ImageOverlay = Layer.extend({
  7687. // @section
  7688. // @aka ImageOverlay options
  7689. options: {
  7690. // @option opacity: Number = 1.0
  7691. // The opacity of the image overlay.
  7692. opacity: 1,
  7693. // @option alt: String = ''
  7694. // Text for the `alt` attribute of the image (useful for accessibility).
  7695. alt: '',
  7696. // @option interactive: Boolean = false
  7697. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7698. interactive: false,
  7699. // @option crossOrigin: Boolean|String = false
  7700. // Whether the crossOrigin attribute will be added to the image.
  7701. // If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data.
  7702. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  7703. crossOrigin: false,
  7704. // @option errorOverlayUrl: String = ''
  7705. // URL to the overlay image to show in place of the overlay that failed to load.
  7706. errorOverlayUrl: '',
  7707. // @option zIndex: Number = 1
  7708. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
  7709. zIndex: 1,
  7710. // @option className: String = ''
  7711. // A custom class name to assign to the image. Empty by default.
  7712. className: ''
  7713. },
  7714. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7715. this._url = url;
  7716. this._bounds = toLatLngBounds(bounds);
  7717. setOptions(this, options);
  7718. },
  7719. onAdd: function () {
  7720. if (!this._image) {
  7721. this._initImage();
  7722. if (this.options.opacity < 1) {
  7723. this._updateOpacity();
  7724. }
  7725. }
  7726. if (this.options.interactive) {
  7727. addClass(this._image, 'leaflet-interactive');
  7728. this.addInteractiveTarget(this._image);
  7729. }
  7730. this.getPane().appendChild(this._image);
  7731. this._reset();
  7732. },
  7733. onRemove: function () {
  7734. remove(this._image);
  7735. if (this.options.interactive) {
  7736. this.removeInteractiveTarget(this._image);
  7737. }
  7738. },
  7739. // @method setOpacity(opacity: Number): this
  7740. // Sets the opacity of the overlay.
  7741. setOpacity: function (opacity) {
  7742. this.options.opacity = opacity;
  7743. if (this._image) {
  7744. this._updateOpacity();
  7745. }
  7746. return this;
  7747. },
  7748. setStyle: function (styleOpts) {
  7749. if (styleOpts.opacity) {
  7750. this.setOpacity(styleOpts.opacity);
  7751. }
  7752. return this;
  7753. },
  7754. // @method bringToFront(): this
  7755. // Brings the layer to the top of all overlays.
  7756. bringToFront: function () {
  7757. if (this._map) {
  7758. toFront(this._image);
  7759. }
  7760. return this;
  7761. },
  7762. // @method bringToBack(): this
  7763. // Brings the layer to the bottom of all overlays.
  7764. bringToBack: function () {
  7765. if (this._map) {
  7766. toBack(this._image);
  7767. }
  7768. return this;
  7769. },
  7770. // @method setUrl(url: String): this
  7771. // Changes the URL of the image.
  7772. setUrl: function (url) {
  7773. this._url = url;
  7774. if (this._image) {
  7775. this._image.src = url;
  7776. }
  7777. return this;
  7778. },
  7779. // @method setBounds(bounds: LatLngBounds): this
  7780. // Update the bounds that this ImageOverlay covers
  7781. setBounds: function (bounds) {
  7782. this._bounds = toLatLngBounds(bounds);
  7783. if (this._map) {
  7784. this._reset();
  7785. }
  7786. return this;
  7787. },
  7788. getEvents: function () {
  7789. var events = {
  7790. zoom: this._reset,
  7791. viewreset: this._reset
  7792. };
  7793. if (this._zoomAnimated) {
  7794. events.zoomanim = this._animateZoom;
  7795. }
  7796. return events;
  7797. },
  7798. // @method setZIndex(value: Number): this
  7799. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7800. setZIndex: function (value) {
  7801. this.options.zIndex = value;
  7802. this._updateZIndex();
  7803. return this;
  7804. },
  7805. // @method getBounds(): LatLngBounds
  7806. // Get the bounds that this ImageOverlay covers
  7807. getBounds: function () {
  7808. return this._bounds;
  7809. },
  7810. // @method getElement(): HTMLElement
  7811. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7812. // used by this overlay.
  7813. getElement: function () {
  7814. return this._image;
  7815. },
  7816. _initImage: function () {
  7817. var wasElementSupplied = this._url.tagName === 'IMG';
  7818. var img = this._image = wasElementSupplied ? this._url : create$1('img');
  7819. addClass(img, 'leaflet-image-layer');
  7820. if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
  7821. if (this.options.className) { addClass(img, this.options.className); }
  7822. img.onselectstart = falseFn;
  7823. img.onmousemove = falseFn;
  7824. // @event load: Event
  7825. // Fired when the ImageOverlay layer has loaded its image
  7826. img.onload = bind(this.fire, this, 'load');
  7827. img.onerror = bind(this._overlayOnError, this, 'error');
  7828. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  7829. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  7830. }
  7831. if (this.options.zIndex) {
  7832. this._updateZIndex();
  7833. }
  7834. if (wasElementSupplied) {
  7835. this._url = img.src;
  7836. return;
  7837. }
  7838. img.src = this._url;
  7839. img.alt = this.options.alt;
  7840. },
  7841. _animateZoom: function (e) {
  7842. var scale = this._map.getZoomScale(e.zoom),
  7843. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7844. setTransform(this._image, offset, scale);
  7845. },
  7846. _reset: function () {
  7847. var image = this._image,
  7848. bounds = new Bounds(
  7849. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7850. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7851. size = bounds.getSize();
  7852. setPosition(image, bounds.min);
  7853. image.style.width = size.x + 'px';
  7854. image.style.height = size.y + 'px';
  7855. },
  7856. _updateOpacity: function () {
  7857. setOpacity(this._image, this.options.opacity);
  7858. },
  7859. _updateZIndex: function () {
  7860. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7861. this._image.style.zIndex = this.options.zIndex;
  7862. }
  7863. },
  7864. _overlayOnError: function () {
  7865. // @event error: Event
  7866. // Fired when the ImageOverlay layer fails to load its image
  7867. this.fire('error');
  7868. var errorUrl = this.options.errorOverlayUrl;
  7869. if (errorUrl && this._url !== errorUrl) {
  7870. this._url = errorUrl;
  7871. this._image.src = errorUrl;
  7872. }
  7873. },
  7874. // @method getCenter(): LatLng
  7875. // Returns the center of the ImageOverlay.
  7876. getCenter: function () {
  7877. return this._bounds.getCenter();
  7878. }
  7879. });
  7880. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7881. // Instantiates an image overlay object given the URL of the image and the
  7882. // geographical bounds it is tied to.
  7883. var imageOverlay = function (url, bounds, options) {
  7884. return new ImageOverlay(url, bounds, options);
  7885. };
  7886. /*
  7887. * @class VideoOverlay
  7888. * @aka L.VideoOverlay
  7889. * @inherits ImageOverlay
  7890. *
  7891. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7892. *
  7893. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7894. * HTML5 element.
  7895. *
  7896. * @example
  7897. *
  7898. * ```js
  7899. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7900. * videoBounds = [[ 32, -130], [ 13, -100]];
  7901. * L.videoOverlay(videoUrl, videoBounds ).addTo(map);
  7902. * ```
  7903. */
  7904. var VideoOverlay = ImageOverlay.extend({
  7905. // @section
  7906. // @aka VideoOverlay options
  7907. options: {
  7908. // @option autoplay: Boolean = true
  7909. // Whether the video starts playing automatically when loaded.
  7910. // On some browsers autoplay will only work with `muted: true`
  7911. autoplay: true,
  7912. // @option loop: Boolean = true
  7913. // Whether the video will loop back to the beginning when played.
  7914. loop: true,
  7915. // @option keepAspectRatio: Boolean = true
  7916. // Whether the video will save aspect ratio after the projection.
  7917. // Relevant for supported browsers. See [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
  7918. keepAspectRatio: true,
  7919. // @option muted: Boolean = false
  7920. // Whether the video starts on mute when loaded.
  7921. muted: false,
  7922. // @option playsInline: Boolean = true
  7923. // Mobile browsers will play the video right where it is instead of open it up in fullscreen mode.
  7924. playsInline: true
  7925. },
  7926. _initImage: function () {
  7927. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7928. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7929. addClass(vid, 'leaflet-image-layer');
  7930. if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
  7931. if (this.options.className) { addClass(vid, this.options.className); }
  7932. vid.onselectstart = falseFn;
  7933. vid.onmousemove = falseFn;
  7934. // @event load: Event
  7935. // Fired when the video has finished loading the first frame
  7936. vid.onloadeddata = bind(this.fire, this, 'load');
  7937. if (wasElementSupplied) {
  7938. var sourceElements = vid.getElementsByTagName('source');
  7939. var sources = [];
  7940. for (var j = 0; j < sourceElements.length; j++) {
  7941. sources.push(sourceElements[j].src);
  7942. }
  7943. this._url = (sourceElements.length > 0) ? sources : [vid.src];
  7944. return;
  7945. }
  7946. if (!isArray(this._url)) { this._url = [this._url]; }
  7947. if (!this.options.keepAspectRatio && Object.prototype.hasOwnProperty.call(vid.style, 'objectFit')) {
  7948. vid.style['objectFit'] = 'fill';
  7949. }
  7950. vid.autoplay = !!this.options.autoplay;
  7951. vid.loop = !!this.options.loop;
  7952. vid.muted = !!this.options.muted;
  7953. vid.playsInline = !!this.options.playsInline;
  7954. for (var i = 0; i < this._url.length; i++) {
  7955. var source = create$1('source');
  7956. source.src = this._url[i];
  7957. vid.appendChild(source);
  7958. }
  7959. }
  7960. // @method getElement(): HTMLVideoElement
  7961. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7962. // used by this overlay.
  7963. });
  7964. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7965. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7966. // geographical bounds it is tied to.
  7967. function videoOverlay(video, bounds, options) {
  7968. return new VideoOverlay(video, bounds, options);
  7969. }
  7970. /*
  7971. * @class SVGOverlay
  7972. * @aka L.SVGOverlay
  7973. * @inherits ImageOverlay
  7974. *
  7975. * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.
  7976. *
  7977. * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.
  7978. *
  7979. * @example
  7980. *
  7981. * ```js
  7982. * var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  7983. * svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
  7984. * svgElement.setAttribute('viewBox', "0 0 200 200");
  7985. * svgElement.innerHTML = '<rect width="200" height="200"/><rect x="75" y="23" width="50" height="50" style="fill:red"/><rect x="75" y="123" width="50" height="50" style="fill:#0013ff"/>';
  7986. * var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
  7987. * L.svgOverlay(svgElement, svgElementBounds).addTo(map);
  7988. * ```
  7989. */
  7990. var SVGOverlay = ImageOverlay.extend({
  7991. _initImage: function () {
  7992. var el = this._image = this._url;
  7993. addClass(el, 'leaflet-image-layer');
  7994. if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); }
  7995. if (this.options.className) { addClass(el, this.options.className); }
  7996. el.onselectstart = falseFn;
  7997. el.onmousemove = falseFn;
  7998. }
  7999. // @method getElement(): SVGElement
  8000. // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
  8001. // used by this overlay.
  8002. });
  8003. // @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)
  8004. // Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.
  8005. // A viewBox attribute is required on the SVG element to zoom in and out properly.
  8006. function svgOverlay(el, bounds, options) {
  8007. return new SVGOverlay(el, bounds, options);
  8008. }
  8009. /*
  8010. * @class DivOverlay
  8011. * @inherits Interactive layer
  8012. * @aka L.DivOverlay
  8013. * Base model for L.Popup and L.Tooltip. Inherit from it for custom overlays like plugins.
  8014. */
  8015. // @namespace DivOverlay
  8016. var DivOverlay = Layer.extend({
  8017. // @section
  8018. // @aka DivOverlay options
  8019. options: {
  8020. // @option interactive: Boolean = false
  8021. // If true, the popup/tooltip will listen to the mouse events.
  8022. interactive: false,
  8023. // @option offset: Point = Point(0, 0)
  8024. // The offset of the overlay position.
  8025. offset: [0, 0],
  8026. // @option className: String = ''
  8027. // A custom CSS class name to assign to the overlay.
  8028. className: '',
  8029. // @option pane: String = undefined
  8030. // `Map pane` where the overlay will be added.
  8031. pane: undefined,
  8032. // @option content: String|HTMLElement|Function = ''
  8033. // Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be
  8034. // passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay.
  8035. content: ''
  8036. },
  8037. initialize: function (options, source) {
  8038. if (options && (options instanceof LatLng || isArray(options))) {
  8039. this._latlng = toLatLng(options);
  8040. setOptions(this, source);
  8041. } else {
  8042. setOptions(this, options);
  8043. this._source = source;
  8044. }
  8045. if (this.options.content) {
  8046. this._content = this.options.content;
  8047. }
  8048. },
  8049. // @method openOn(map: Map): this
  8050. // Adds the overlay to the map.
  8051. // Alternative to `map.openPopup(popup)`/`.openTooltip(tooltip)`.
  8052. openOn: function (map) {
  8053. map = arguments.length ? map : this._source._map; // experimental, not the part of public api
  8054. if (!map.hasLayer(this)) {
  8055. map.addLayer(this);
  8056. }
  8057. return this;
  8058. },
  8059. // @method close(): this
  8060. // Closes the overlay.
  8061. // Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)`
  8062. // and `layer.closePopup()`/`.closeTooltip()`.
  8063. close: function () {
  8064. if (this._map) {
  8065. this._map.removeLayer(this);
  8066. }
  8067. return this;
  8068. },
  8069. // @method toggle(layer?: Layer): this
  8070. // Opens or closes the overlay bound to layer depending on its current state.
  8071. // Argument may be omitted only for overlay bound to layer.
  8072. // Alternative to `layer.togglePopup()`/`.toggleTooltip()`.
  8073. toggle: function (layer) {
  8074. if (this._map) {
  8075. this.close();
  8076. } else {
  8077. if (arguments.length) {
  8078. this._source = layer;
  8079. } else {
  8080. layer = this._source;
  8081. }
  8082. this._prepareOpen();
  8083. // open the overlay on the map
  8084. this.openOn(layer._map);
  8085. }
  8086. return this;
  8087. },
  8088. onAdd: function (map) {
  8089. this._zoomAnimated = map._zoomAnimated;
  8090. if (!this._container) {
  8091. this._initLayout();
  8092. }
  8093. if (map._fadeAnimated) {
  8094. setOpacity(this._container, 0);
  8095. }
  8096. clearTimeout(this._removeTimeout);
  8097. this.getPane().appendChild(this._container);
  8098. this.update();
  8099. if (map._fadeAnimated) {
  8100. setOpacity(this._container, 1);
  8101. }
  8102. this.bringToFront();
  8103. if (this.options.interactive) {
  8104. addClass(this._container, 'leaflet-interactive');
  8105. this.addInteractiveTarget(this._container);
  8106. }
  8107. },
  8108. onRemove: function (map) {
  8109. if (map._fadeAnimated) {
  8110. setOpacity(this._container, 0);
  8111. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  8112. } else {
  8113. remove(this._container);
  8114. }
  8115. if (this.options.interactive) {
  8116. removeClass(this._container, 'leaflet-interactive');
  8117. this.removeInteractiveTarget(this._container);
  8118. }
  8119. },
  8120. // @namespace DivOverlay
  8121. // @method getLatLng: LatLng
  8122. // Returns the geographical point of the overlay.
  8123. getLatLng: function () {
  8124. return this._latlng;
  8125. },
  8126. // @method setLatLng(latlng: LatLng): this
  8127. // Sets the geographical point where the overlay will open.
  8128. setLatLng: function (latlng) {
  8129. this._latlng = toLatLng(latlng);
  8130. if (this._map) {
  8131. this._updatePosition();
  8132. this._adjustPan();
  8133. }
  8134. return this;
  8135. },
  8136. // @method getContent: String|HTMLElement
  8137. // Returns the content of the overlay.
  8138. getContent: function () {
  8139. return this._content;
  8140. },
  8141. // @method setContent(htmlContent: String|HTMLElement|Function): this
  8142. // Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function.
  8143. // The function should return a `String` or `HTMLElement` to be used in the overlay.
  8144. setContent: function (content) {
  8145. this._content = content;
  8146. this.update();
  8147. return this;
  8148. },
  8149. // @method getElement: String|HTMLElement
  8150. // Returns the HTML container of the overlay.
  8151. getElement: function () {
  8152. return this._container;
  8153. },
  8154. // @method update: null
  8155. // Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded.
  8156. update: function () {
  8157. if (!this._map) { return; }
  8158. this._container.style.visibility = 'hidden';
  8159. this._updateContent();
  8160. this._updateLayout();
  8161. this._updatePosition();
  8162. this._container.style.visibility = '';
  8163. this._adjustPan();
  8164. },
  8165. getEvents: function () {
  8166. var events = {
  8167. zoom: this._updatePosition,
  8168. viewreset: this._updatePosition
  8169. };
  8170. if (this._zoomAnimated) {
  8171. events.zoomanim = this._animateZoom;
  8172. }
  8173. return events;
  8174. },
  8175. // @method isOpen: Boolean
  8176. // Returns `true` when the overlay is visible on the map.
  8177. isOpen: function () {
  8178. return !!this._map && this._map.hasLayer(this);
  8179. },
  8180. // @method bringToFront: this
  8181. // Brings this overlay in front of other overlays (in the same map pane).
  8182. bringToFront: function () {
  8183. if (this._map) {
  8184. toFront(this._container);
  8185. }
  8186. return this;
  8187. },
  8188. // @method bringToBack: this
  8189. // Brings this overlay to the back of other overlays (in the same map pane).
  8190. bringToBack: function () {
  8191. if (this._map) {
  8192. toBack(this._container);
  8193. }
  8194. return this;
  8195. },
  8196. // prepare bound overlay to open: update latlng pos / content source (for FeatureGroup)
  8197. _prepareOpen: function (latlng) {
  8198. var source = this._source;
  8199. if (!source._map) { return false; }
  8200. if (source instanceof FeatureGroup) {
  8201. source = null;
  8202. var layers = this._source._layers;
  8203. for (var id in layers) {
  8204. if (layers[id]._map) {
  8205. source = layers[id];
  8206. break;
  8207. }
  8208. }
  8209. if (!source) { return false; } // Unable to get source layer.
  8210. // set overlay source to this layer
  8211. this._source = source;
  8212. }
  8213. if (!latlng) {
  8214. if (source.getCenter) {
  8215. latlng = source.getCenter();
  8216. } else if (source.getLatLng) {
  8217. latlng = source.getLatLng();
  8218. } else if (source.getBounds) {
  8219. latlng = source.getBounds().getCenter();
  8220. } else {
  8221. throw new Error('Unable to get source layer LatLng.');
  8222. }
  8223. }
  8224. this.setLatLng(latlng);
  8225. if (this._map) {
  8226. // update the overlay (content, layout, etc...)
  8227. this.update();
  8228. }
  8229. return true;
  8230. },
  8231. _updateContent: function () {
  8232. if (!this._content) { return; }
  8233. var node = this._contentNode;
  8234. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  8235. if (typeof content === 'string') {
  8236. node.innerHTML = content;
  8237. } else {
  8238. while (node.hasChildNodes()) {
  8239. node.removeChild(node.firstChild);
  8240. }
  8241. node.appendChild(content);
  8242. }
  8243. // @namespace DivOverlay
  8244. // @section DivOverlay events
  8245. // @event contentupdate: Event
  8246. // Fired when the content of the overlay is updated
  8247. this.fire('contentupdate');
  8248. },
  8249. _updatePosition: function () {
  8250. if (!this._map) { return; }
  8251. var pos = this._map.latLngToLayerPoint(this._latlng),
  8252. offset = toPoint(this.options.offset),
  8253. anchor = this._getAnchor();
  8254. if (this._zoomAnimated) {
  8255. setPosition(this._container, pos.add(anchor));
  8256. } else {
  8257. offset = offset.add(pos).add(anchor);
  8258. }
  8259. var bottom = this._containerBottom = -offset.y,
  8260. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  8261. // bottom position the overlay in case the height of the overlay changes (images loading etc)
  8262. this._container.style.bottom = bottom + 'px';
  8263. this._container.style.left = left + 'px';
  8264. },
  8265. _getAnchor: function () {
  8266. return [0, 0];
  8267. }
  8268. });
  8269. Map.include({
  8270. _initOverlay: function (OverlayClass, content, latlng, options) {
  8271. var overlay = content;
  8272. if (!(overlay instanceof OverlayClass)) {
  8273. overlay = new OverlayClass(options).setContent(content);
  8274. }
  8275. if (latlng) {
  8276. overlay.setLatLng(latlng);
  8277. }
  8278. return overlay;
  8279. }
  8280. });
  8281. Layer.include({
  8282. _initOverlay: function (OverlayClass, old, content, options) {
  8283. var overlay = content;
  8284. if (overlay instanceof OverlayClass) {
  8285. setOptions(overlay, options);
  8286. overlay._source = this;
  8287. } else {
  8288. overlay = (old && !options) ? old : new OverlayClass(options, this);
  8289. overlay.setContent(content);
  8290. }
  8291. return overlay;
  8292. }
  8293. });
  8294. /*
  8295. * @class Popup
  8296. * @inherits DivOverlay
  8297. * @aka L.Popup
  8298. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  8299. * open popups while making sure that only one popup is open at one time
  8300. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  8301. *
  8302. * @example
  8303. *
  8304. * If you want to just bind a popup to marker click and then open it, it's really easy:
  8305. *
  8306. * ```js
  8307. * marker.bindPopup(popupContent).openPopup();
  8308. * ```
  8309. * Path overlays like polylines also have a `bindPopup` method.
  8310. *
  8311. * A popup can be also standalone:
  8312. *
  8313. * ```js
  8314. * var popup = L.popup()
  8315. * .setLatLng(latlng)
  8316. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  8317. * .openOn(map);
  8318. * ```
  8319. * or
  8320. * ```js
  8321. * var popup = L.popup(latlng, {content: '<p>Hello world!<br />This is a nice popup.</p>')
  8322. * .openOn(map);
  8323. * ```
  8324. */
  8325. // @namespace Popup
  8326. var Popup = DivOverlay.extend({
  8327. // @section
  8328. // @aka Popup options
  8329. options: {
  8330. // @option pane: String = 'popupPane'
  8331. // `Map pane` where the popup will be added.
  8332. pane: 'popupPane',
  8333. // @option offset: Point = Point(0, 7)
  8334. // The offset of the popup position.
  8335. offset: [0, 7],
  8336. // @option maxWidth: Number = 300
  8337. // Max width of the popup, in pixels.
  8338. maxWidth: 300,
  8339. // @option minWidth: Number = 50
  8340. // Min width of the popup, in pixels.
  8341. minWidth: 50,
  8342. // @option maxHeight: Number = null
  8343. // If set, creates a scrollable container of the given height
  8344. // inside a popup if its content exceeds it.
  8345. // The scrollable container can be styled using the
  8346. // `leaflet-popup-scrolled` CSS class selector.
  8347. maxHeight: null,
  8348. // @option autoPan: Boolean = true
  8349. // Set it to `false` if you don't want the map to do panning animation
  8350. // to fit the opened popup.
  8351. autoPan: true,
  8352. // @option autoPanPaddingTopLeft: Point = null
  8353. // The margin between the popup and the top left corner of the map
  8354. // view after autopanning was performed.
  8355. autoPanPaddingTopLeft: null,
  8356. // @option autoPanPaddingBottomRight: Point = null
  8357. // The margin between the popup and the bottom right corner of the map
  8358. // view after autopanning was performed.
  8359. autoPanPaddingBottomRight: null,
  8360. // @option autoPanPadding: Point = Point(5, 5)
  8361. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  8362. autoPanPadding: [5, 5],
  8363. // @option keepInView: Boolean = false
  8364. // Set it to `true` if you want to prevent users from panning the popup
  8365. // off of the screen while it is open.
  8366. keepInView: false,
  8367. // @option closeButton: Boolean = true
  8368. // Controls the presence of a close button in the popup.
  8369. closeButton: true,
  8370. // @option autoClose: Boolean = true
  8371. // Set it to `false` if you want to override the default behavior of
  8372. // the popup closing when another popup is opened.
  8373. autoClose: true,
  8374. // @option closeOnEscapeKey: Boolean = true
  8375. // Set it to `false` if you want to override the default behavior of
  8376. // the ESC key for closing of the popup.
  8377. closeOnEscapeKey: true,
  8378. // @option closeOnClick: Boolean = *
  8379. // Set it if you want to override the default behavior of the popup closing when user clicks
  8380. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  8381. // @option className: String = ''
  8382. // A custom CSS class name to assign to the popup.
  8383. className: ''
  8384. },
  8385. // @namespace Popup
  8386. // @method openOn(map: Map): this
  8387. // Alternative to `map.openPopup(popup)`.
  8388. // Adds the popup to the map and closes the previous one.
  8389. openOn: function (map) {
  8390. map = arguments.length ? map : this._source._map; // experimental, not the part of public api
  8391. if (!map.hasLayer(this) && map._popup && map._popup.options.autoClose) {
  8392. map.removeLayer(map._popup);
  8393. }
  8394. map._popup = this;
  8395. return DivOverlay.prototype.openOn.call(this, map);
  8396. },
  8397. onAdd: function (map) {
  8398. DivOverlay.prototype.onAdd.call(this, map);
  8399. // @namespace Map
  8400. // @section Popup events
  8401. // @event popupopen: PopupEvent
  8402. // Fired when a popup is opened in the map
  8403. map.fire('popupopen', {popup: this});
  8404. if (this._source) {
  8405. // @namespace Layer
  8406. // @section Popup events
  8407. // @event popupopen: PopupEvent
  8408. // Fired when a popup bound to this layer is opened
  8409. this._source.fire('popupopen', {popup: this}, true);
  8410. // For non-path layers, we toggle the popup when clicking
  8411. // again the layer, so prevent the map to reopen it.
  8412. if (!(this._source instanceof Path)) {
  8413. this._source.on('preclick', stopPropagation);
  8414. }
  8415. }
  8416. },
  8417. onRemove: function (map) {
  8418. DivOverlay.prototype.onRemove.call(this, map);
  8419. // @namespace Map
  8420. // @section Popup events
  8421. // @event popupclose: PopupEvent
  8422. // Fired when a popup in the map is closed
  8423. map.fire('popupclose', {popup: this});
  8424. if (this._source) {
  8425. // @namespace Layer
  8426. // @section Popup events
  8427. // @event popupclose: PopupEvent
  8428. // Fired when a popup bound to this layer is closed
  8429. this._source.fire('popupclose', {popup: this}, true);
  8430. if (!(this._source instanceof Path)) {
  8431. this._source.off('preclick', stopPropagation);
  8432. }
  8433. }
  8434. },
  8435. getEvents: function () {
  8436. var events = DivOverlay.prototype.getEvents.call(this);
  8437. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  8438. events.preclick = this.close;
  8439. }
  8440. if (this.options.keepInView) {
  8441. events.moveend = this._adjustPan;
  8442. }
  8443. return events;
  8444. },
  8445. _initLayout: function () {
  8446. var prefix = 'leaflet-popup',
  8447. container = this._container = create$1('div',
  8448. prefix + ' ' + (this.options.className || '') +
  8449. ' leaflet-zoom-animated');
  8450. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  8451. this._contentNode = create$1('div', prefix + '-content', wrapper);
  8452. disableClickPropagation(container);
  8453. disableScrollPropagation(this._contentNode);
  8454. on(container, 'contextmenu', stopPropagation);
  8455. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  8456. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  8457. if (this.options.closeButton) {
  8458. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  8459. closeButton.setAttribute('role', 'button'); // overrides the implicit role=link of <a> elements #7399
  8460. closeButton.setAttribute('aria-label', 'Close popup');
  8461. closeButton.href = '#close';
  8462. closeButton.innerHTML = '<span aria-hidden="true">&#215;</span>';
  8463. on(closeButton, 'click', function (ev) {
  8464. preventDefault(ev);
  8465. this.close();
  8466. }, this);
  8467. }
  8468. },
  8469. _updateLayout: function () {
  8470. var container = this._contentNode,
  8471. style = container.style;
  8472. style.width = '';
  8473. style.whiteSpace = 'nowrap';
  8474. var width = container.offsetWidth;
  8475. width = Math.min(width, this.options.maxWidth);
  8476. width = Math.max(width, this.options.minWidth);
  8477. style.width = (width + 1) + 'px';
  8478. style.whiteSpace = '';
  8479. style.height = '';
  8480. var height = container.offsetHeight,
  8481. maxHeight = this.options.maxHeight,
  8482. scrolledClass = 'leaflet-popup-scrolled';
  8483. if (maxHeight && height > maxHeight) {
  8484. style.height = maxHeight + 'px';
  8485. addClass(container, scrolledClass);
  8486. } else {
  8487. removeClass(container, scrolledClass);
  8488. }
  8489. this._containerWidth = this._container.offsetWidth;
  8490. },
  8491. _animateZoom: function (e) {
  8492. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  8493. anchor = this._getAnchor();
  8494. setPosition(this._container, pos.add(anchor));
  8495. },
  8496. _adjustPan: function () {
  8497. if (!this.options.autoPan) { return; }
  8498. if (this._map._panAnim) { this._map._panAnim.stop(); }
  8499. // We can endlessly recurse if keepInView is set and the view resets.
  8500. // Let's guard against that by exiting early if we're responding to our own autopan.
  8501. if (this._autopanning) {
  8502. this._autopanning = false;
  8503. return;
  8504. }
  8505. var map = this._map,
  8506. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  8507. containerHeight = this._container.offsetHeight + marginBottom,
  8508. containerWidth = this._containerWidth,
  8509. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  8510. layerPos._add(getPosition(this._container));
  8511. var containerPos = map.layerPointToContainerPoint(layerPos),
  8512. padding = toPoint(this.options.autoPanPadding),
  8513. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  8514. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  8515. size = map.getSize(),
  8516. dx = 0,
  8517. dy = 0;
  8518. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  8519. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  8520. }
  8521. if (containerPos.x - dx - paddingTL.x < 0) { // left
  8522. dx = containerPos.x - paddingTL.x;
  8523. }
  8524. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  8525. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  8526. }
  8527. if (containerPos.y - dy - paddingTL.y < 0) { // top
  8528. dy = containerPos.y - paddingTL.y;
  8529. }
  8530. // @namespace Map
  8531. // @section Popup events
  8532. // @event autopanstart: Event
  8533. // Fired when the map starts autopanning when opening a popup.
  8534. if (dx || dy) {
  8535. // Track that we're autopanning, as this function will be re-ran on moveend
  8536. if (this.options.keepInView) {
  8537. this._autopanning = true;
  8538. }
  8539. map
  8540. .fire('autopanstart')
  8541. .panBy([dx, dy]);
  8542. }
  8543. },
  8544. _getAnchor: function () {
  8545. // Where should we anchor the popup on the source layer?
  8546. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  8547. }
  8548. });
  8549. // @namespace Popup
  8550. // @factory L.popup(options?: Popup options, source?: Layer)
  8551. // 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.
  8552. // @alternative
  8553. // @factory L.popup(latlng: LatLng, options?: Popup options)
  8554. // Instantiates a `Popup` object given `latlng` where the popup will open and an optional `options` object that describes its appearance and location.
  8555. var popup = function (options, source) {
  8556. return new Popup(options, source);
  8557. };
  8558. /* @namespace Map
  8559. * @section Interaction Options
  8560. * @option closePopupOnClick: Boolean = true
  8561. * Set it to `false` if you don't want popups to close when user clicks the map.
  8562. */
  8563. Map.mergeOptions({
  8564. closePopupOnClick: true
  8565. });
  8566. // @namespace Map
  8567. // @section Methods for Layers and Controls
  8568. Map.include({
  8569. // @method openPopup(popup: Popup): this
  8570. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  8571. // @alternative
  8572. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  8573. // Creates a popup with the specified content and options and opens it in the given point on a map.
  8574. openPopup: function (popup, latlng, options) {
  8575. this._initOverlay(Popup, popup, latlng, options)
  8576. .openOn(this);
  8577. return this;
  8578. },
  8579. // @method closePopup(popup?: Popup): this
  8580. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  8581. closePopup: function (popup) {
  8582. popup = arguments.length ? popup : this._popup;
  8583. if (popup) {
  8584. popup.close();
  8585. }
  8586. return this;
  8587. }
  8588. });
  8589. /*
  8590. * @namespace Layer
  8591. * @section Popup methods example
  8592. *
  8593. * All layers share a set of methods convenient for binding popups to it.
  8594. *
  8595. * ```js
  8596. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  8597. * layer.openPopup();
  8598. * layer.closePopup();
  8599. * ```
  8600. *
  8601. * 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.
  8602. */
  8603. // @section Popup methods
  8604. Layer.include({
  8605. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  8606. // Binds a popup to the layer with the passed `content` and sets up the
  8607. // necessary event listeners. If a `Function` is passed it will receive
  8608. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8609. bindPopup: function (content, options) {
  8610. this._popup = this._initOverlay(Popup, this._popup, content, options);
  8611. if (!this._popupHandlersAdded) {
  8612. this.on({
  8613. click: this._openPopup,
  8614. keypress: this._onKeyPress,
  8615. remove: this.closePopup,
  8616. move: this._movePopup
  8617. });
  8618. this._popupHandlersAdded = true;
  8619. }
  8620. return this;
  8621. },
  8622. // @method unbindPopup(): this
  8623. // Removes the popup previously bound with `bindPopup`.
  8624. unbindPopup: function () {
  8625. if (this._popup) {
  8626. this.off({
  8627. click: this._openPopup,
  8628. keypress: this._onKeyPress,
  8629. remove: this.closePopup,
  8630. move: this._movePopup
  8631. });
  8632. this._popupHandlersAdded = false;
  8633. this._popup = null;
  8634. }
  8635. return this;
  8636. },
  8637. // @method openPopup(latlng?: LatLng): this
  8638. // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
  8639. openPopup: function (latlng) {
  8640. if (this._popup) {
  8641. if (!(this instanceof FeatureGroup)) {
  8642. this._popup._source = this;
  8643. }
  8644. if (this._popup._prepareOpen(latlng || this._latlng)) {
  8645. // open the popup on the map
  8646. this._popup.openOn(this._map);
  8647. }
  8648. }
  8649. return this;
  8650. },
  8651. // @method closePopup(): this
  8652. // Closes the popup bound to this layer if it is open.
  8653. closePopup: function () {
  8654. if (this._popup) {
  8655. this._popup.close();
  8656. }
  8657. return this;
  8658. },
  8659. // @method togglePopup(): this
  8660. // Opens or closes the popup bound to this layer depending on its current state.
  8661. togglePopup: function () {
  8662. if (this._popup) {
  8663. this._popup.toggle(this);
  8664. }
  8665. return this;
  8666. },
  8667. // @method isPopupOpen(): boolean
  8668. // Returns `true` if the popup bound to this layer is currently open.
  8669. isPopupOpen: function () {
  8670. return (this._popup ? this._popup.isOpen() : false);
  8671. },
  8672. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8673. // Sets the content of the popup bound to this layer.
  8674. setPopupContent: function (content) {
  8675. if (this._popup) {
  8676. this._popup.setContent(content);
  8677. }
  8678. return this;
  8679. },
  8680. // @method getPopup(): Popup
  8681. // Returns the popup bound to this layer.
  8682. getPopup: function () {
  8683. return this._popup;
  8684. },
  8685. _openPopup: function (e) {
  8686. if (!this._popup || !this._map) {
  8687. return;
  8688. }
  8689. // prevent map click
  8690. stop(e);
  8691. var target = e.layer || e.target;
  8692. if (this._popup._source === target && !(target instanceof Path)) {
  8693. // treat it like a marker and figure out
  8694. // if we should toggle it open/closed
  8695. if (this._map.hasLayer(this._popup)) {
  8696. this.closePopup();
  8697. } else {
  8698. this.openPopup(e.latlng);
  8699. }
  8700. return;
  8701. }
  8702. this._popup._source = target;
  8703. this.openPopup(e.latlng);
  8704. },
  8705. _movePopup: function (e) {
  8706. this._popup.setLatLng(e.latlng);
  8707. },
  8708. _onKeyPress: function (e) {
  8709. if (e.originalEvent.keyCode === 13) {
  8710. this._openPopup(e);
  8711. }
  8712. }
  8713. });
  8714. /*
  8715. * @class Tooltip
  8716. * @inherits DivOverlay
  8717. * @aka L.Tooltip
  8718. * Used to display small texts on top of map layers.
  8719. *
  8720. * @example
  8721. * If you want to just bind a tooltip to marker:
  8722. *
  8723. * ```js
  8724. * marker.bindTooltip("my tooltip text").openTooltip();
  8725. * ```
  8726. * Path overlays like polylines also have a `bindTooltip` method.
  8727. *
  8728. * A tooltip can be also standalone:
  8729. *
  8730. * ```js
  8731. * var tooltip = L.tooltip()
  8732. * .setLatLng(latlng)
  8733. * .setContent('Hello world!<br />This is a nice tooltip.')
  8734. * .addTo(map);
  8735. * ```
  8736. * or
  8737. * ```js
  8738. * var tooltip = L.tooltip(latlng, {content: 'Hello world!<br />This is a nice tooltip.'})
  8739. * .addTo(map);
  8740. * ```
  8741. *
  8742. *
  8743. * Note about tooltip offset. Leaflet takes two options in consideration
  8744. * for computing tooltip offsetting:
  8745. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8746. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8747. * move it to the bottom. Negatives will move to the left and top.
  8748. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8749. * should adapt this value if you use a custom icon.
  8750. */
  8751. // @namespace Tooltip
  8752. var Tooltip = DivOverlay.extend({
  8753. // @section
  8754. // @aka Tooltip options
  8755. options: {
  8756. // @option pane: String = 'tooltipPane'
  8757. // `Map pane` where the tooltip will be added.
  8758. pane: 'tooltipPane',
  8759. // @option offset: Point = Point(0, 0)
  8760. // Optional offset of the tooltip position.
  8761. offset: [0, 0],
  8762. // @option direction: String = 'auto'
  8763. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8764. // `top`, `bottom`, `center`, `auto`.
  8765. // `auto` will dynamically switch between `right` and `left` according to the tooltip
  8766. // position on the map.
  8767. direction: 'auto',
  8768. // @option permanent: Boolean = false
  8769. // Whether to open the tooltip permanently or only on mouseover.
  8770. permanent: false,
  8771. // @option sticky: Boolean = false
  8772. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8773. sticky: false,
  8774. // @option opacity: Number = 0.9
  8775. // Tooltip container opacity.
  8776. opacity: 0.9
  8777. },
  8778. onAdd: function (map) {
  8779. DivOverlay.prototype.onAdd.call(this, map);
  8780. this.setOpacity(this.options.opacity);
  8781. // @namespace Map
  8782. // @section Tooltip events
  8783. // @event tooltipopen: TooltipEvent
  8784. // Fired when a tooltip is opened in the map.
  8785. map.fire('tooltipopen', {tooltip: this});
  8786. if (this._source) {
  8787. this.addEventParent(this._source);
  8788. // @namespace Layer
  8789. // @section Tooltip events
  8790. // @event tooltipopen: TooltipEvent
  8791. // Fired when a tooltip bound to this layer is opened.
  8792. this._source.fire('tooltipopen', {tooltip: this}, true);
  8793. }
  8794. },
  8795. onRemove: function (map) {
  8796. DivOverlay.prototype.onRemove.call(this, map);
  8797. // @namespace Map
  8798. // @section Tooltip events
  8799. // @event tooltipclose: TooltipEvent
  8800. // Fired when a tooltip in the map is closed.
  8801. map.fire('tooltipclose', {tooltip: this});
  8802. if (this._source) {
  8803. this.removeEventParent(this._source);
  8804. // @namespace Layer
  8805. // @section Tooltip events
  8806. // @event tooltipclose: TooltipEvent
  8807. // Fired when a tooltip bound to this layer is closed.
  8808. this._source.fire('tooltipclose', {tooltip: this}, true);
  8809. }
  8810. },
  8811. getEvents: function () {
  8812. var events = DivOverlay.prototype.getEvents.call(this);
  8813. if (!this.options.permanent) {
  8814. events.preclick = this.close;
  8815. }
  8816. return events;
  8817. },
  8818. _initLayout: function () {
  8819. var prefix = 'leaflet-tooltip',
  8820. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8821. this._contentNode = this._container = create$1('div', className);
  8822. this._container.setAttribute('role', 'tooltip');
  8823. this._container.setAttribute('id', 'leaflet-tooltip-' + stamp(this));
  8824. },
  8825. _updateLayout: function () {},
  8826. _adjustPan: function () {},
  8827. _setPosition: function (pos) {
  8828. var subX, subY,
  8829. map = this._map,
  8830. container = this._container,
  8831. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8832. tooltipPoint = map.layerPointToContainerPoint(pos),
  8833. direction = this.options.direction,
  8834. tooltipWidth = container.offsetWidth,
  8835. tooltipHeight = container.offsetHeight,
  8836. offset = toPoint(this.options.offset),
  8837. anchor = this._getAnchor();
  8838. if (direction === 'top') {
  8839. subX = tooltipWidth / 2;
  8840. subY = tooltipHeight;
  8841. } else if (direction === 'bottom') {
  8842. subX = tooltipWidth / 2;
  8843. subY = 0;
  8844. } else if (direction === 'center') {
  8845. subX = tooltipWidth / 2;
  8846. subY = tooltipHeight / 2;
  8847. } else if (direction === 'right') {
  8848. subX = 0;
  8849. subY = tooltipHeight / 2;
  8850. } else if (direction === 'left') {
  8851. subX = tooltipWidth;
  8852. subY = tooltipHeight / 2;
  8853. } else if (tooltipPoint.x < centerPoint.x) {
  8854. direction = 'right';
  8855. subX = 0;
  8856. subY = tooltipHeight / 2;
  8857. } else {
  8858. direction = 'left';
  8859. subX = tooltipWidth + (offset.x + anchor.x) * 2;
  8860. subY = tooltipHeight / 2;
  8861. }
  8862. pos = pos.subtract(toPoint(subX, subY, true)).add(offset).add(anchor);
  8863. removeClass(container, 'leaflet-tooltip-right');
  8864. removeClass(container, 'leaflet-tooltip-left');
  8865. removeClass(container, 'leaflet-tooltip-top');
  8866. removeClass(container, 'leaflet-tooltip-bottom');
  8867. addClass(container, 'leaflet-tooltip-' + direction);
  8868. setPosition(container, pos);
  8869. },
  8870. _updatePosition: function () {
  8871. var pos = this._map.latLngToLayerPoint(this._latlng);
  8872. this._setPosition(pos);
  8873. },
  8874. setOpacity: function (opacity) {
  8875. this.options.opacity = opacity;
  8876. if (this._container) {
  8877. setOpacity(this._container, opacity);
  8878. }
  8879. },
  8880. _animateZoom: function (e) {
  8881. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8882. this._setPosition(pos);
  8883. },
  8884. _getAnchor: function () {
  8885. // Where should we anchor the tooltip on the source layer?
  8886. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8887. }
  8888. });
  8889. // @namespace Tooltip
  8890. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8891. // 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.
  8892. // @alternative
  8893. // @factory L.tooltip(latlng: LatLng, options?: Tooltip options)
  8894. // Instantiates a `Tooltip` object given `latlng` where the tooltip will open and an optional `options` object that describes its appearance and location.
  8895. var tooltip = function (options, source) {
  8896. return new Tooltip(options, source);
  8897. };
  8898. // @namespace Map
  8899. // @section Methods for Layers and Controls
  8900. Map.include({
  8901. // @method openTooltip(tooltip: Tooltip): this
  8902. // Opens the specified tooltip.
  8903. // @alternative
  8904. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8905. // Creates a tooltip with the specified content and options and open it.
  8906. openTooltip: function (tooltip, latlng, options) {
  8907. this._initOverlay(Tooltip, tooltip, latlng, options)
  8908. .openOn(this);
  8909. return this;
  8910. },
  8911. // @method closeTooltip(tooltip: Tooltip): this
  8912. // Closes the tooltip given as parameter.
  8913. closeTooltip: function (tooltip) {
  8914. tooltip.close();
  8915. return this;
  8916. }
  8917. });
  8918. /*
  8919. * @namespace Layer
  8920. * @section Tooltip methods example
  8921. *
  8922. * All layers share a set of methods convenient for binding tooltips to it.
  8923. *
  8924. * ```js
  8925. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8926. * layer.openTooltip();
  8927. * layer.closeTooltip();
  8928. * ```
  8929. */
  8930. // @section Tooltip methods
  8931. Layer.include({
  8932. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8933. // Binds a tooltip to the layer with the passed `content` and sets up the
  8934. // necessary event listeners. If a `Function` is passed it will receive
  8935. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8936. bindTooltip: function (content, options) {
  8937. if (this._tooltip && this.isTooltipOpen()) {
  8938. this.unbindTooltip();
  8939. }
  8940. this._tooltip = this._initOverlay(Tooltip, this._tooltip, content, options);
  8941. this._initTooltipInteractions();
  8942. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8943. this.openTooltip();
  8944. }
  8945. return this;
  8946. },
  8947. // @method unbindTooltip(): this
  8948. // Removes the tooltip previously bound with `bindTooltip`.
  8949. unbindTooltip: function () {
  8950. if (this._tooltip) {
  8951. this._initTooltipInteractions(true);
  8952. this.closeTooltip();
  8953. this._tooltip = null;
  8954. }
  8955. return this;
  8956. },
  8957. _initTooltipInteractions: function (remove) {
  8958. if (!remove && this._tooltipHandlersAdded) { return; }
  8959. var onOff = remove ? 'off' : 'on',
  8960. events = {
  8961. remove: this.closeTooltip,
  8962. move: this._moveTooltip
  8963. };
  8964. if (!this._tooltip.options.permanent) {
  8965. events.mouseover = this._openTooltip;
  8966. events.mouseout = this.closeTooltip;
  8967. events.click = this._openTooltip;
  8968. if (this._map) {
  8969. this._addFocusListeners();
  8970. } else {
  8971. events.add = this._addFocusListeners;
  8972. }
  8973. } else {
  8974. events.add = this._openTooltip;
  8975. }
  8976. if (this._tooltip.options.sticky) {
  8977. events.mousemove = this._moveTooltip;
  8978. }
  8979. this[onOff](events);
  8980. this._tooltipHandlersAdded = !remove;
  8981. },
  8982. // @method openTooltip(latlng?: LatLng): this
  8983. // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8984. openTooltip: function (latlng) {
  8985. if (this._tooltip) {
  8986. if (!(this instanceof FeatureGroup)) {
  8987. this._tooltip._source = this;
  8988. }
  8989. if (this._tooltip._prepareOpen(latlng)) {
  8990. // open the tooltip on the map
  8991. this._tooltip.openOn(this._map);
  8992. if (this.getElement) {
  8993. this._setAriaDescribedByOnLayer(this);
  8994. } else if (this.eachLayer) {
  8995. this.eachLayer(this._setAriaDescribedByOnLayer, this);
  8996. }
  8997. }
  8998. }
  8999. return this;
  9000. },
  9001. // @method closeTooltip(): this
  9002. // Closes the tooltip bound to this layer if it is open.
  9003. closeTooltip: function () {
  9004. if (this._tooltip) {
  9005. return this._tooltip.close();
  9006. }
  9007. },
  9008. // @method toggleTooltip(): this
  9009. // Opens or closes the tooltip bound to this layer depending on its current state.
  9010. toggleTooltip: function () {
  9011. if (this._tooltip) {
  9012. this._tooltip.toggle(this);
  9013. }
  9014. return this;
  9015. },
  9016. // @method isTooltipOpen(): boolean
  9017. // Returns `true` if the tooltip bound to this layer is currently open.
  9018. isTooltipOpen: function () {
  9019. return this._tooltip.isOpen();
  9020. },
  9021. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  9022. // Sets the content of the tooltip bound to this layer.
  9023. setTooltipContent: function (content) {
  9024. if (this._tooltip) {
  9025. this._tooltip.setContent(content);
  9026. }
  9027. return this;
  9028. },
  9029. // @method getTooltip(): Tooltip
  9030. // Returns the tooltip bound to this layer.
  9031. getTooltip: function () {
  9032. return this._tooltip;
  9033. },
  9034. _addFocusListeners: function () {
  9035. if (this.getElement) {
  9036. this._addFocusListenersOnLayer(this);
  9037. } else if (this.eachLayer) {
  9038. this.eachLayer(this._addFocusListenersOnLayer, this);
  9039. }
  9040. },
  9041. _addFocusListenersOnLayer: function (layer) {
  9042. var el = typeof layer.getElement === 'function' && layer.getElement();
  9043. if (el) {
  9044. on(el, 'focus', function () {
  9045. this._tooltip._source = layer;
  9046. this.openTooltip();
  9047. }, this);
  9048. on(el, 'blur', this.closeTooltip, this);
  9049. }
  9050. },
  9051. _setAriaDescribedByOnLayer: function (layer) {
  9052. var el = typeof layer.getElement === 'function' && layer.getElement();
  9053. if (el) {
  9054. el.setAttribute('aria-describedby', this._tooltip._container.id);
  9055. }
  9056. },
  9057. _openTooltip: function (e) {
  9058. if (!this._tooltip || !this._map) {
  9059. return;
  9060. }
  9061. // If the map is moving, we will show the tooltip after it's done.
  9062. if (this._map.dragging && this._map.dragging.moving() && !this._openOnceFlag) {
  9063. this._openOnceFlag = true;
  9064. var that = this;
  9065. this._map.once('moveend', function () {
  9066. that._openOnceFlag = false;
  9067. that._openTooltip(e);
  9068. });
  9069. return;
  9070. }
  9071. this._tooltip._source = e.layer || e.target;
  9072. this.openTooltip(this._tooltip.options.sticky ? e.latlng : undefined);
  9073. },
  9074. _moveTooltip: function (e) {
  9075. var latlng = e.latlng, containerPoint, layerPoint;
  9076. if (this._tooltip.options.sticky && e.originalEvent) {
  9077. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  9078. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  9079. latlng = this._map.layerPointToLatLng(layerPoint);
  9080. }
  9081. this._tooltip.setLatLng(latlng);
  9082. }
  9083. });
  9084. /*
  9085. * @class DivIcon
  9086. * @aka L.DivIcon
  9087. * @inherits Icon
  9088. *
  9089. * Represents a lightweight icon for markers that uses a simple `<div>`
  9090. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  9091. *
  9092. * @example
  9093. * ```js
  9094. * var myIcon = L.divIcon({className: 'my-div-icon'});
  9095. * // you can set .my-div-icon styles in CSS
  9096. *
  9097. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  9098. * ```
  9099. *
  9100. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  9101. */
  9102. var DivIcon = Icon.extend({
  9103. options: {
  9104. // @section
  9105. // @aka DivIcon options
  9106. iconSize: [12, 12], // also can be set through CSS
  9107. // iconAnchor: (Point),
  9108. // popupAnchor: (Point),
  9109. // @option html: String|HTMLElement = ''
  9110. // Custom HTML code to put inside the div element, empty by default. Alternatively,
  9111. // an instance of `HTMLElement`.
  9112. html: false,
  9113. // @option bgPos: Point = [0, 0]
  9114. // Optional relative position of the background, in pixels
  9115. bgPos: null,
  9116. className: 'leaflet-div-icon'
  9117. },
  9118. createIcon: function (oldIcon) {
  9119. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  9120. options = this.options;
  9121. if (options.html instanceof Element) {
  9122. empty(div);
  9123. div.appendChild(options.html);
  9124. } else {
  9125. div.innerHTML = options.html !== false ? options.html : '';
  9126. }
  9127. if (options.bgPos) {
  9128. var bgPos = toPoint(options.bgPos);
  9129. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  9130. }
  9131. this._setIconStyles(div, 'icon');
  9132. return div;
  9133. },
  9134. createShadow: function () {
  9135. return null;
  9136. }
  9137. });
  9138. // @factory L.divIcon(options: DivIcon options)
  9139. // Creates a `DivIcon` instance with the given options.
  9140. function divIcon(options) {
  9141. return new DivIcon(options);
  9142. }
  9143. Icon.Default = IconDefault;
  9144. /*
  9145. * @class GridLayer
  9146. * @inherits Layer
  9147. * @aka L.GridLayer
  9148. *
  9149. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  9150. * 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.
  9151. *
  9152. *
  9153. * @section Synchronous usage
  9154. * @example
  9155. *
  9156. * 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.
  9157. *
  9158. * ```js
  9159. * var CanvasLayer = L.GridLayer.extend({
  9160. * createTile: function(coords){
  9161. * // create a <canvas> element for drawing
  9162. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  9163. *
  9164. * // setup tile width and height according to the options
  9165. * var size = this.getTileSize();
  9166. * tile.width = size.x;
  9167. * tile.height = size.y;
  9168. *
  9169. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  9170. * var ctx = tile.getContext('2d');
  9171. *
  9172. * // return the tile so it can be rendered on screen
  9173. * return tile;
  9174. * }
  9175. * });
  9176. * ```
  9177. *
  9178. * @section Asynchronous usage
  9179. * @example
  9180. *
  9181. * 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.
  9182. *
  9183. * ```js
  9184. * var CanvasLayer = L.GridLayer.extend({
  9185. * createTile: function(coords, done){
  9186. * var error;
  9187. *
  9188. * // create a <canvas> element for drawing
  9189. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  9190. *
  9191. * // setup tile width and height according to the options
  9192. * var size = this.getTileSize();
  9193. * tile.width = size.x;
  9194. * tile.height = size.y;
  9195. *
  9196. * // draw something asynchronously and pass the tile to the done() callback
  9197. * setTimeout(function() {
  9198. * done(error, tile);
  9199. * }, 1000);
  9200. *
  9201. * return tile;
  9202. * }
  9203. * });
  9204. * ```
  9205. *
  9206. * @section
  9207. */
  9208. var GridLayer = Layer.extend({
  9209. // @section
  9210. // @aka GridLayer options
  9211. options: {
  9212. // @option tileSize: Number|Point = 256
  9213. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  9214. tileSize: 256,
  9215. // @option opacity: Number = 1.0
  9216. // Opacity of the tiles. Can be used in the `createTile()` function.
  9217. opacity: 1,
  9218. // @option updateWhenIdle: Boolean = (depends)
  9219. // Load new tiles only when panning ends.
  9220. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  9221. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  9222. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  9223. updateWhenIdle: Browser.mobile,
  9224. // @option updateWhenZooming: Boolean = true
  9225. // 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.
  9226. updateWhenZooming: true,
  9227. // @option updateInterval: Number = 200
  9228. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  9229. updateInterval: 200,
  9230. // @option zIndex: Number = 1
  9231. // The explicit zIndex of the tile layer.
  9232. zIndex: 1,
  9233. // @option bounds: LatLngBounds = undefined
  9234. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  9235. bounds: null,
  9236. // @option minZoom: Number = 0
  9237. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9238. minZoom: 0,
  9239. // @option maxZoom: Number = undefined
  9240. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9241. maxZoom: undefined,
  9242. // @option maxNativeZoom: Number = undefined
  9243. // Maximum zoom number the tile source has available. If it is specified,
  9244. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  9245. // from `maxNativeZoom` level and auto-scaled.
  9246. maxNativeZoom: undefined,
  9247. // @option minNativeZoom: Number = undefined
  9248. // Minimum zoom number the tile source has available. If it is specified,
  9249. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  9250. // from `minNativeZoom` level and auto-scaled.
  9251. minNativeZoom: undefined,
  9252. // @option noWrap: Boolean = false
  9253. // Whether the layer is wrapped around the antimeridian. If `true`, the
  9254. // GridLayer will only be displayed once at low zoom levels. Has no
  9255. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  9256. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  9257. // tiles outside the CRS limits.
  9258. noWrap: false,
  9259. // @option pane: String = 'tilePane'
  9260. // `Map pane` where the grid layer will be added.
  9261. pane: 'tilePane',
  9262. // @option className: String = ''
  9263. // A custom class name to assign to the tile layer. Empty by default.
  9264. className: '',
  9265. // @option keepBuffer: Number = 2
  9266. // When panning the map, keep this many rows and columns of tiles before unloading them.
  9267. keepBuffer: 2
  9268. },
  9269. initialize: function (options) {
  9270. setOptions(this, options);
  9271. },
  9272. onAdd: function () {
  9273. this._initContainer();
  9274. this._levels = {};
  9275. this._tiles = {};
  9276. this._resetView(); // implicit _update() call
  9277. },
  9278. beforeAdd: function (map) {
  9279. map._addZoomLimit(this);
  9280. },
  9281. onRemove: function (map) {
  9282. this._removeAllTiles();
  9283. remove(this._container);
  9284. map._removeZoomLimit(this);
  9285. this._container = null;
  9286. this._tileZoom = undefined;
  9287. },
  9288. // @method bringToFront: this
  9289. // Brings the tile layer to the top of all tile layers.
  9290. bringToFront: function () {
  9291. if (this._map) {
  9292. toFront(this._container);
  9293. this._setAutoZIndex(Math.max);
  9294. }
  9295. return this;
  9296. },
  9297. // @method bringToBack: this
  9298. // Brings the tile layer to the bottom of all tile layers.
  9299. bringToBack: function () {
  9300. if (this._map) {
  9301. toBack(this._container);
  9302. this._setAutoZIndex(Math.min);
  9303. }
  9304. return this;
  9305. },
  9306. // @method getContainer: HTMLElement
  9307. // Returns the HTML element that contains the tiles for this layer.
  9308. getContainer: function () {
  9309. return this._container;
  9310. },
  9311. // @method setOpacity(opacity: Number): this
  9312. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  9313. setOpacity: function (opacity) {
  9314. this.options.opacity = opacity;
  9315. this._updateOpacity();
  9316. return this;
  9317. },
  9318. // @method setZIndex(zIndex: Number): this
  9319. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  9320. setZIndex: function (zIndex) {
  9321. this.options.zIndex = zIndex;
  9322. this._updateZIndex();
  9323. return this;
  9324. },
  9325. // @method isLoading: Boolean
  9326. // Returns `true` if any tile in the grid layer has not finished loading.
  9327. isLoading: function () {
  9328. return this._loading;
  9329. },
  9330. // @method redraw: this
  9331. // Causes the layer to clear all the tiles and request them again.
  9332. redraw: function () {
  9333. if (this._map) {
  9334. this._removeAllTiles();
  9335. var tileZoom = this._clampZoom(this._map.getZoom());
  9336. if (tileZoom !== this._tileZoom) {
  9337. this._tileZoom = tileZoom;
  9338. this._updateLevels();
  9339. }
  9340. this._update();
  9341. }
  9342. return this;
  9343. },
  9344. getEvents: function () {
  9345. var events = {
  9346. viewprereset: this._invalidateAll,
  9347. viewreset: this._resetView,
  9348. zoom: this._resetView,
  9349. moveend: this._onMoveEnd
  9350. };
  9351. if (!this.options.updateWhenIdle) {
  9352. // update tiles on move, but not more often than once per given interval
  9353. if (!this._onMove) {
  9354. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  9355. }
  9356. events.move = this._onMove;
  9357. }
  9358. if (this._zoomAnimated) {
  9359. events.zoomanim = this._animateZoom;
  9360. }
  9361. return events;
  9362. },
  9363. // @section Extension methods
  9364. // Layers extending `GridLayer` shall reimplement the following method.
  9365. // @method createTile(coords: Object, done?: Function): HTMLElement
  9366. // Called only internally, must be overridden by classes extending `GridLayer`.
  9367. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  9368. // is specified, it must be called when the tile has finished loading and drawing.
  9369. createTile: function () {
  9370. return document.createElement('div');
  9371. },
  9372. // @section
  9373. // @method getTileSize: Point
  9374. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  9375. getTileSize: function () {
  9376. var s = this.options.tileSize;
  9377. return s instanceof Point ? s : new Point(s, s);
  9378. },
  9379. _updateZIndex: function () {
  9380. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  9381. this._container.style.zIndex = this.options.zIndex;
  9382. }
  9383. },
  9384. _setAutoZIndex: function (compare) {
  9385. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  9386. var layers = this.getPane().children,
  9387. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  9388. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  9389. zIndex = layers[i].style.zIndex;
  9390. if (layers[i] !== this._container && zIndex) {
  9391. edgeZIndex = compare(edgeZIndex, +zIndex);
  9392. }
  9393. }
  9394. if (isFinite(edgeZIndex)) {
  9395. this.options.zIndex = edgeZIndex + compare(-1, 1);
  9396. this._updateZIndex();
  9397. }
  9398. },
  9399. _updateOpacity: function () {
  9400. if (!this._map) { return; }
  9401. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  9402. if (Browser.ielt9) { return; }
  9403. setOpacity(this._container, this.options.opacity);
  9404. var now = +new Date(),
  9405. nextFrame = false,
  9406. willPrune = false;
  9407. for (var key in this._tiles) {
  9408. var tile = this._tiles[key];
  9409. if (!tile.current || !tile.loaded) { continue; }
  9410. var fade = Math.min(1, (now - tile.loaded) / 200);
  9411. setOpacity(tile.el, fade);
  9412. if (fade < 1) {
  9413. nextFrame = true;
  9414. } else {
  9415. if (tile.active) {
  9416. willPrune = true;
  9417. } else {
  9418. this._onOpaqueTile(tile);
  9419. }
  9420. tile.active = true;
  9421. }
  9422. }
  9423. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  9424. if (nextFrame) {
  9425. cancelAnimFrame(this._fadeFrame);
  9426. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9427. }
  9428. },
  9429. _onOpaqueTile: falseFn,
  9430. _initContainer: function () {
  9431. if (this._container) { return; }
  9432. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  9433. this._updateZIndex();
  9434. if (this.options.opacity < 1) {
  9435. this._updateOpacity();
  9436. }
  9437. this.getPane().appendChild(this._container);
  9438. },
  9439. _updateLevels: function () {
  9440. var zoom = this._tileZoom,
  9441. maxZoom = this.options.maxZoom;
  9442. if (zoom === undefined) { return undefined; }
  9443. for (var z in this._levels) {
  9444. z = Number(z);
  9445. if (this._levels[z].el.children.length || z === zoom) {
  9446. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  9447. this._onUpdateLevel(z);
  9448. } else {
  9449. remove(this._levels[z].el);
  9450. this._removeTilesAtZoom(z);
  9451. this._onRemoveLevel(z);
  9452. delete this._levels[z];
  9453. }
  9454. }
  9455. var level = this._levels[zoom],
  9456. map = this._map;
  9457. if (!level) {
  9458. level = this._levels[zoom] = {};
  9459. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  9460. level.el.style.zIndex = maxZoom;
  9461. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  9462. level.zoom = zoom;
  9463. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  9464. // force the browser to consider the newly added element for transition
  9465. falseFn(level.el.offsetWidth);
  9466. this._onCreateLevel(level);
  9467. }
  9468. this._level = level;
  9469. return level;
  9470. },
  9471. _onUpdateLevel: falseFn,
  9472. _onRemoveLevel: falseFn,
  9473. _onCreateLevel: falseFn,
  9474. _pruneTiles: function () {
  9475. if (!this._map) {
  9476. return;
  9477. }
  9478. var key, tile;
  9479. var zoom = this._map.getZoom();
  9480. if (zoom > this.options.maxZoom ||
  9481. zoom < this.options.minZoom) {
  9482. this._removeAllTiles();
  9483. return;
  9484. }
  9485. for (key in this._tiles) {
  9486. tile = this._tiles[key];
  9487. tile.retain = tile.current;
  9488. }
  9489. for (key in this._tiles) {
  9490. tile = this._tiles[key];
  9491. if (tile.current && !tile.active) {
  9492. var coords = tile.coords;
  9493. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  9494. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  9495. }
  9496. }
  9497. }
  9498. for (key in this._tiles) {
  9499. if (!this._tiles[key].retain) {
  9500. this._removeTile(key);
  9501. }
  9502. }
  9503. },
  9504. _removeTilesAtZoom: function (zoom) {
  9505. for (var key in this._tiles) {
  9506. if (this._tiles[key].coords.z !== zoom) {
  9507. continue;
  9508. }
  9509. this._removeTile(key);
  9510. }
  9511. },
  9512. _removeAllTiles: function () {
  9513. for (var key in this._tiles) {
  9514. this._removeTile(key);
  9515. }
  9516. },
  9517. _invalidateAll: function () {
  9518. for (var z in this._levels) {
  9519. remove(this._levels[z].el);
  9520. this._onRemoveLevel(Number(z));
  9521. delete this._levels[z];
  9522. }
  9523. this._removeAllTiles();
  9524. this._tileZoom = undefined;
  9525. },
  9526. _retainParent: function (x, y, z, minZoom) {
  9527. var x2 = Math.floor(x / 2),
  9528. y2 = Math.floor(y / 2),
  9529. z2 = z - 1,
  9530. coords2 = new Point(+x2, +y2);
  9531. coords2.z = +z2;
  9532. var key = this._tileCoordsToKey(coords2),
  9533. tile = this._tiles[key];
  9534. if (tile && tile.active) {
  9535. tile.retain = true;
  9536. return true;
  9537. } else if (tile && tile.loaded) {
  9538. tile.retain = true;
  9539. }
  9540. if (z2 > minZoom) {
  9541. return this._retainParent(x2, y2, z2, minZoom);
  9542. }
  9543. return false;
  9544. },
  9545. _retainChildren: function (x, y, z, maxZoom) {
  9546. for (var i = 2 * x; i < 2 * x + 2; i++) {
  9547. for (var j = 2 * y; j < 2 * y + 2; j++) {
  9548. var coords = new Point(i, j);
  9549. coords.z = z + 1;
  9550. var key = this._tileCoordsToKey(coords),
  9551. tile = this._tiles[key];
  9552. if (tile && tile.active) {
  9553. tile.retain = true;
  9554. continue;
  9555. } else if (tile && tile.loaded) {
  9556. tile.retain = true;
  9557. }
  9558. if (z + 1 < maxZoom) {
  9559. this._retainChildren(i, j, z + 1, maxZoom);
  9560. }
  9561. }
  9562. }
  9563. },
  9564. _resetView: function (e) {
  9565. var animating = e && (e.pinch || e.flyTo);
  9566. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  9567. },
  9568. _animateZoom: function (e) {
  9569. this._setView(e.center, e.zoom, true, e.noUpdate);
  9570. },
  9571. _clampZoom: function (zoom) {
  9572. var options = this.options;
  9573. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  9574. return options.minNativeZoom;
  9575. }
  9576. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  9577. return options.maxNativeZoom;
  9578. }
  9579. return zoom;
  9580. },
  9581. _setView: function (center, zoom, noPrune, noUpdate) {
  9582. var tileZoom = Math.round(zoom);
  9583. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  9584. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  9585. tileZoom = undefined;
  9586. } else {
  9587. tileZoom = this._clampZoom(tileZoom);
  9588. }
  9589. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  9590. if (!noUpdate || tileZoomChanged) {
  9591. this._tileZoom = tileZoom;
  9592. if (this._abortLoading) {
  9593. this._abortLoading();
  9594. }
  9595. this._updateLevels();
  9596. this._resetGrid();
  9597. if (tileZoom !== undefined) {
  9598. this._update(center);
  9599. }
  9600. if (!noPrune) {
  9601. this._pruneTiles();
  9602. }
  9603. // Flag to prevent _updateOpacity from pruning tiles during
  9604. // a zoom anim or a pinch gesture
  9605. this._noPrune = !!noPrune;
  9606. }
  9607. this._setZoomTransforms(center, zoom);
  9608. },
  9609. _setZoomTransforms: function (center, zoom) {
  9610. for (var i in this._levels) {
  9611. this._setZoomTransform(this._levels[i], center, zoom);
  9612. }
  9613. },
  9614. _setZoomTransform: function (level, center, zoom) {
  9615. var scale = this._map.getZoomScale(zoom, level.zoom),
  9616. translate = level.origin.multiplyBy(scale)
  9617. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  9618. if (Browser.any3d) {
  9619. setTransform(level.el, translate, scale);
  9620. } else {
  9621. setPosition(level.el, translate);
  9622. }
  9623. },
  9624. _resetGrid: function () {
  9625. var map = this._map,
  9626. crs = map.options.crs,
  9627. tileSize = this._tileSize = this.getTileSize(),
  9628. tileZoom = this._tileZoom;
  9629. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  9630. if (bounds) {
  9631. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  9632. }
  9633. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  9634. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  9635. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  9636. ];
  9637. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  9638. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  9639. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  9640. ];
  9641. },
  9642. _onMoveEnd: function () {
  9643. if (!this._map || this._map._animatingZoom) { return; }
  9644. this._update();
  9645. },
  9646. _getTiledPixelBounds: function (center) {
  9647. var map = this._map,
  9648. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9649. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9650. pixelCenter = map.project(center, this._tileZoom).floor(),
  9651. halfSize = map.getSize().divideBy(scale * 2);
  9652. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9653. },
  9654. // Private method to load tiles in the grid's active zoom level according to map bounds
  9655. _update: function (center) {
  9656. var map = this._map;
  9657. if (!map) { return; }
  9658. var zoom = this._clampZoom(map.getZoom());
  9659. if (center === undefined) { center = map.getCenter(); }
  9660. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  9661. var pixelBounds = this._getTiledPixelBounds(center),
  9662. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9663. tileCenter = tileRange.getCenter(),
  9664. queue = [],
  9665. margin = this.options.keepBuffer,
  9666. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9667. tileRange.getTopRight().add([margin, -margin]));
  9668. // Sanity check: panic if the tile range contains Infinity somewhere.
  9669. if (!(isFinite(tileRange.min.x) &&
  9670. isFinite(tileRange.min.y) &&
  9671. isFinite(tileRange.max.x) &&
  9672. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  9673. for (var key in this._tiles) {
  9674. var c = this._tiles[key].coords;
  9675. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9676. this._tiles[key].current = false;
  9677. }
  9678. }
  9679. // _update just loads more tiles. If the tile zoom level differs too much
  9680. // from the map's, let _setView reset levels and prune old tiles.
  9681. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  9682. // create a queue of coordinates to load tiles from
  9683. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9684. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9685. var coords = new Point(i, j);
  9686. coords.z = this._tileZoom;
  9687. if (!this._isValidTile(coords)) { continue; }
  9688. var tile = this._tiles[this._tileCoordsToKey(coords)];
  9689. if (tile) {
  9690. tile.current = true;
  9691. } else {
  9692. queue.push(coords);
  9693. }
  9694. }
  9695. }
  9696. // sort tile queue to load tiles in order of their distance to center
  9697. queue.sort(function (a, b) {
  9698. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9699. });
  9700. if (queue.length !== 0) {
  9701. // if it's the first batch of tiles to load
  9702. if (!this._loading) {
  9703. this._loading = true;
  9704. // @event loading: Event
  9705. // Fired when the grid layer starts loading tiles.
  9706. this.fire('loading');
  9707. }
  9708. // create DOM fragment to append tiles in one batch
  9709. var fragment = document.createDocumentFragment();
  9710. for (i = 0; i < queue.length; i++) {
  9711. this._addTile(queue[i], fragment);
  9712. }
  9713. this._level.el.appendChild(fragment);
  9714. }
  9715. },
  9716. _isValidTile: function (coords) {
  9717. var crs = this._map.options.crs;
  9718. if (!crs.infinite) {
  9719. // don't load tile if it's out of bounds and not wrapped
  9720. var bounds = this._globalTileRange;
  9721. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9722. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  9723. }
  9724. if (!this.options.bounds) { return true; }
  9725. // don't load tile if it doesn't intersect the bounds in options
  9726. var tileBounds = this._tileCoordsToBounds(coords);
  9727. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9728. },
  9729. _keyToBounds: function (key) {
  9730. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9731. },
  9732. _tileCoordsToNwSe: function (coords) {
  9733. var map = this._map,
  9734. tileSize = this.getTileSize(),
  9735. nwPoint = coords.scaleBy(tileSize),
  9736. sePoint = nwPoint.add(tileSize),
  9737. nw = map.unproject(nwPoint, coords.z),
  9738. se = map.unproject(sePoint, coords.z);
  9739. return [nw, se];
  9740. },
  9741. // converts tile coordinates to its geographical bounds
  9742. _tileCoordsToBounds: function (coords) {
  9743. var bp = this._tileCoordsToNwSe(coords),
  9744. bounds = new LatLngBounds(bp[0], bp[1]);
  9745. if (!this.options.noWrap) {
  9746. bounds = this._map.wrapLatLngBounds(bounds);
  9747. }
  9748. return bounds;
  9749. },
  9750. // converts tile coordinates to key for the tile cache
  9751. _tileCoordsToKey: function (coords) {
  9752. return coords.x + ':' + coords.y + ':' + coords.z;
  9753. },
  9754. // converts tile cache key to coordinates
  9755. _keyToTileCoords: function (key) {
  9756. var k = key.split(':'),
  9757. coords = new Point(+k[0], +k[1]);
  9758. coords.z = +k[2];
  9759. return coords;
  9760. },
  9761. _removeTile: function (key) {
  9762. var tile = this._tiles[key];
  9763. if (!tile) { return; }
  9764. remove(tile.el);
  9765. delete this._tiles[key];
  9766. // @event tileunload: TileEvent
  9767. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9768. this.fire('tileunload', {
  9769. tile: tile.el,
  9770. coords: this._keyToTileCoords(key)
  9771. });
  9772. },
  9773. _initTile: function (tile) {
  9774. addClass(tile, 'leaflet-tile');
  9775. var tileSize = this.getTileSize();
  9776. tile.style.width = tileSize.x + 'px';
  9777. tile.style.height = tileSize.y + 'px';
  9778. tile.onselectstart = falseFn;
  9779. tile.onmousemove = falseFn;
  9780. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9781. if (Browser.ielt9 && this.options.opacity < 1) {
  9782. setOpacity(tile, this.options.opacity);
  9783. }
  9784. },
  9785. _addTile: function (coords, container) {
  9786. var tilePos = this._getTilePos(coords),
  9787. key = this._tileCoordsToKey(coords);
  9788. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9789. this._initTile(tile);
  9790. // if createTile is defined with a second argument ("done" callback),
  9791. // we know that tile is async and will be ready later; otherwise
  9792. if (this.createTile.length < 2) {
  9793. // mark tile as ready, but delay one frame for opacity animation to happen
  9794. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9795. }
  9796. setPosition(tile, tilePos);
  9797. // save tile in cache
  9798. this._tiles[key] = {
  9799. el: tile,
  9800. coords: coords,
  9801. current: true
  9802. };
  9803. container.appendChild(tile);
  9804. // @event tileloadstart: TileEvent
  9805. // Fired when a tile is requested and starts loading.
  9806. this.fire('tileloadstart', {
  9807. tile: tile,
  9808. coords: coords
  9809. });
  9810. },
  9811. _tileReady: function (coords, err, tile) {
  9812. if (err) {
  9813. // @event tileerror: TileErrorEvent
  9814. // Fired when there is an error loading a tile.
  9815. this.fire('tileerror', {
  9816. error: err,
  9817. tile: tile,
  9818. coords: coords
  9819. });
  9820. }
  9821. var key = this._tileCoordsToKey(coords);
  9822. tile = this._tiles[key];
  9823. if (!tile) { return; }
  9824. tile.loaded = +new Date();
  9825. if (this._map._fadeAnimated) {
  9826. setOpacity(tile.el, 0);
  9827. cancelAnimFrame(this._fadeFrame);
  9828. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9829. } else {
  9830. tile.active = true;
  9831. this._pruneTiles();
  9832. }
  9833. if (!err) {
  9834. addClass(tile.el, 'leaflet-tile-loaded');
  9835. // @event tileload: TileEvent
  9836. // Fired when a tile loads.
  9837. this.fire('tileload', {
  9838. tile: tile.el,
  9839. coords: coords
  9840. });
  9841. }
  9842. if (this._noTilesToLoad()) {
  9843. this._loading = false;
  9844. // @event load: Event
  9845. // Fired when the grid layer loaded all visible tiles.
  9846. this.fire('load');
  9847. if (Browser.ielt9 || !this._map._fadeAnimated) {
  9848. requestAnimFrame(this._pruneTiles, this);
  9849. } else {
  9850. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9851. // to trigger a pruning.
  9852. setTimeout(bind(this._pruneTiles, this), 250);
  9853. }
  9854. }
  9855. },
  9856. _getTilePos: function (coords) {
  9857. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9858. },
  9859. _wrapCoords: function (coords) {
  9860. var newCoords = new Point(
  9861. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9862. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9863. newCoords.z = coords.z;
  9864. return newCoords;
  9865. },
  9866. _pxBoundsToTileRange: function (bounds) {
  9867. var tileSize = this.getTileSize();
  9868. return new Bounds(
  9869. bounds.min.unscaleBy(tileSize).floor(),
  9870. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9871. },
  9872. _noTilesToLoad: function () {
  9873. for (var key in this._tiles) {
  9874. if (!this._tiles[key].loaded) { return false; }
  9875. }
  9876. return true;
  9877. }
  9878. });
  9879. // @factory L.gridLayer(options?: GridLayer options)
  9880. // Creates a new instance of GridLayer with the supplied options.
  9881. function gridLayer(options) {
  9882. return new GridLayer(options);
  9883. }
  9884. /*
  9885. * @class TileLayer
  9886. * @inherits GridLayer
  9887. * @aka L.TileLayer
  9888. * Used to load and display tile layers on the map. Note that most tile servers require attribution, which you can set under `Layer`. Extends `GridLayer`.
  9889. *
  9890. * @example
  9891. *
  9892. * ```js
  9893. * L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);
  9894. * ```
  9895. *
  9896. * @section URL template
  9897. * @example
  9898. *
  9899. * A string of the following form:
  9900. *
  9901. * ```
  9902. * 'https://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9903. * ```
  9904. *
  9905. * `{s}` means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; `a`, `b` or `c` by default, can be omitted), `{z}` — zoom level, `{x}` and `{y}` — tile coordinates. `{r}` can be used to add "&commat;2x" to the URL to load retina tiles.
  9906. *
  9907. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9908. *
  9909. * ```
  9910. * L.tileLayer('https://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9911. * ```
  9912. */
  9913. var TileLayer = GridLayer.extend({
  9914. // @section
  9915. // @aka TileLayer options
  9916. options: {
  9917. // @option minZoom: Number = 0
  9918. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9919. minZoom: 0,
  9920. // @option maxZoom: Number = 18
  9921. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9922. maxZoom: 18,
  9923. // @option subdomains: String|String[] = 'abc'
  9924. // 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.
  9925. subdomains: 'abc',
  9926. // @option errorTileUrl: String = ''
  9927. // URL to the tile image to show in place of the tile that failed to load.
  9928. errorTileUrl: '',
  9929. // @option zoomOffset: Number = 0
  9930. // The zoom number used in tile URLs will be offset with this value.
  9931. zoomOffset: 0,
  9932. // @option tms: Boolean = false
  9933. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9934. tms: false,
  9935. // @option zoomReverse: Boolean = false
  9936. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9937. zoomReverse: false,
  9938. // @option detectRetina: Boolean = false
  9939. // 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.
  9940. detectRetina: false,
  9941. // @option crossOrigin: Boolean|String = false
  9942. // Whether the crossOrigin attribute will be added to the tiles.
  9943. // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
  9944. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  9945. crossOrigin: false,
  9946. // @option referrerPolicy: Boolean|String = false
  9947. // Whether the referrerPolicy attribute will be added to the tiles.
  9948. // If a String is provided, all tiles will have their referrerPolicy attribute set to the String provided.
  9949. // This may be needed if your map's rendering context has a strict default but your tile provider expects a valid referrer
  9950. // (e.g. to validate an API token).
  9951. // Refer to [HTMLImageElement.referrerPolicy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/referrerPolicy) for valid String values.
  9952. referrerPolicy: false
  9953. },
  9954. initialize: function (url, options) {
  9955. this._url = url;
  9956. options = setOptions(this, options);
  9957. // detecting retina displays, adjusting tileSize and zoom levels
  9958. if (options.detectRetina && Browser.retina && options.maxZoom > 0) {
  9959. options.tileSize = Math.floor(options.tileSize / 2);
  9960. if (!options.zoomReverse) {
  9961. options.zoomOffset++;
  9962. options.maxZoom = Math.max(options.minZoom, options.maxZoom - 1);
  9963. } else {
  9964. options.zoomOffset--;
  9965. options.minZoom = Math.min(options.maxZoom, options.minZoom + 1);
  9966. }
  9967. options.minZoom = Math.max(0, options.minZoom);
  9968. } else if (!options.zoomReverse) {
  9969. // make sure maxZoom is gte minZoom
  9970. options.maxZoom = Math.max(options.minZoom, options.maxZoom);
  9971. } else {
  9972. // make sure minZoom is lte maxZoom
  9973. options.minZoom = Math.min(options.maxZoom, options.minZoom);
  9974. }
  9975. if (typeof options.subdomains === 'string') {
  9976. options.subdomains = options.subdomains.split('');
  9977. }
  9978. this.on('tileunload', this._onTileRemove);
  9979. },
  9980. // @method setUrl(url: String, noRedraw?: Boolean): this
  9981. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9982. // If the URL does not change, the layer will not be redrawn unless
  9983. // the noRedraw parameter is set to false.
  9984. setUrl: function (url, noRedraw) {
  9985. if (this._url === url && noRedraw === undefined) {
  9986. noRedraw = true;
  9987. }
  9988. this._url = url;
  9989. if (!noRedraw) {
  9990. this.redraw();
  9991. }
  9992. return this;
  9993. },
  9994. // @method createTile(coords: Object, done?: Function): HTMLElement
  9995. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9996. // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
  9997. // callback is called when the tile has been loaded.
  9998. createTile: function (coords, done) {
  9999. var tile = document.createElement('img');
  10000. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  10001. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  10002. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  10003. tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  10004. }
  10005. // for this new option we follow the documented behavior
  10006. // more closely by only setting the property when string
  10007. if (typeof this.options.referrerPolicy === 'string') {
  10008. tile.referrerPolicy = this.options.referrerPolicy;
  10009. }
  10010. // The alt attribute is set to the empty string,
  10011. // allowing screen readers to ignore the decorative image tiles.
  10012. // https://www.w3.org/WAI/tutorials/images/decorative/
  10013. // https://www.w3.org/TR/html-aria/#el-img-empty-alt
  10014. tile.alt = '';
  10015. tile.src = this.getTileUrl(coords);
  10016. return tile;
  10017. },
  10018. // @section Extension methods
  10019. // @uninheritable
  10020. // Layers extending `TileLayer` might reimplement the following method.
  10021. // @method getTileUrl(coords: Object): String
  10022. // Called only internally, returns the URL for a tile given its coordinates.
  10023. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  10024. getTileUrl: function (coords) {
  10025. var data = {
  10026. r: Browser.retina ? '@2x' : '',
  10027. s: this._getSubdomain(coords),
  10028. x: coords.x,
  10029. y: coords.y,
  10030. z: this._getZoomForUrl()
  10031. };
  10032. if (this._map && !this._map.options.crs.infinite) {
  10033. var invertedY = this._globalTileRange.max.y - coords.y;
  10034. if (this.options.tms) {
  10035. data['y'] = invertedY;
  10036. }
  10037. data['-y'] = invertedY;
  10038. }
  10039. return template(this._url, extend(data, this.options));
  10040. },
  10041. _tileOnLoad: function (done, tile) {
  10042. // For https://github.com/Leaflet/Leaflet/issues/3332
  10043. if (Browser.ielt9) {
  10044. setTimeout(bind(done, this, null, tile), 0);
  10045. } else {
  10046. done(null, tile);
  10047. }
  10048. },
  10049. _tileOnError: function (done, tile, e) {
  10050. var errorUrl = this.options.errorTileUrl;
  10051. if (errorUrl && tile.getAttribute('src') !== errorUrl) {
  10052. tile.src = errorUrl;
  10053. }
  10054. done(e, tile);
  10055. },
  10056. _onTileRemove: function (e) {
  10057. e.tile.onload = null;
  10058. },
  10059. _getZoomForUrl: function () {
  10060. var zoom = this._tileZoom,
  10061. maxZoom = this.options.maxZoom,
  10062. zoomReverse = this.options.zoomReverse,
  10063. zoomOffset = this.options.zoomOffset;
  10064. if (zoomReverse) {
  10065. zoom = maxZoom - zoom;
  10066. }
  10067. return zoom + zoomOffset;
  10068. },
  10069. _getSubdomain: function (tilePoint) {
  10070. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  10071. return this.options.subdomains[index];
  10072. },
  10073. // stops loading all tiles in the background layer
  10074. _abortLoading: function () {
  10075. var i, tile;
  10076. for (i in this._tiles) {
  10077. if (this._tiles[i].coords.z !== this._tileZoom) {
  10078. tile = this._tiles[i].el;
  10079. tile.onload = falseFn;
  10080. tile.onerror = falseFn;
  10081. if (!tile.complete) {
  10082. tile.src = emptyImageUrl;
  10083. var coords = this._tiles[i].coords;
  10084. remove(tile);
  10085. delete this._tiles[i];
  10086. // @event tileabort: TileEvent
  10087. // Fired when a tile was loading but is now not wanted.
  10088. this.fire('tileabort', {
  10089. tile: tile,
  10090. coords: coords
  10091. });
  10092. }
  10093. }
  10094. }
  10095. },
  10096. _removeTile: function (key) {
  10097. var tile = this._tiles[key];
  10098. if (!tile) { return; }
  10099. // Cancels any pending http requests associated with the tile
  10100. tile.el.setAttribute('src', emptyImageUrl);
  10101. return GridLayer.prototype._removeTile.call(this, key);
  10102. },
  10103. _tileReady: function (coords, err, tile) {
  10104. if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) {
  10105. return;
  10106. }
  10107. return GridLayer.prototype._tileReady.call(this, coords, err, tile);
  10108. }
  10109. });
  10110. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  10111. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  10112. function tileLayer(url, options) {
  10113. return new TileLayer(url, options);
  10114. }
  10115. /*
  10116. * @class TileLayer.WMS
  10117. * @inherits TileLayer
  10118. * @aka L.TileLayer.WMS
  10119. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  10120. *
  10121. * @example
  10122. *
  10123. * ```js
  10124. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  10125. * layers: 'nexrad-n0r-900913',
  10126. * format: 'image/png',
  10127. * transparent: true,
  10128. * attribution: "Weather data © 2012 IEM Nexrad"
  10129. * });
  10130. * ```
  10131. */
  10132. var TileLayerWMS = TileLayer.extend({
  10133. // @section
  10134. // @aka TileLayer.WMS options
  10135. // If any custom options not documented here are used, they will be sent to the
  10136. // WMS server as extra parameters in each request URL. This can be useful for
  10137. // [non-standard vendor WMS parameters](https://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  10138. defaultWmsParams: {
  10139. service: 'WMS',
  10140. request: 'GetMap',
  10141. // @option layers: String = ''
  10142. // **(required)** Comma-separated list of WMS layers to show.
  10143. layers: '',
  10144. // @option styles: String = ''
  10145. // Comma-separated list of WMS styles.
  10146. styles: '',
  10147. // @option format: String = 'image/jpeg'
  10148. // WMS image format (use `'image/png'` for layers with transparency).
  10149. format: 'image/jpeg',
  10150. // @option transparent: Boolean = false
  10151. // If `true`, the WMS service will return images with transparency.
  10152. transparent: false,
  10153. // @option version: String = '1.1.1'
  10154. // Version of the WMS service to use
  10155. version: '1.1.1'
  10156. },
  10157. options: {
  10158. // @option crs: CRS = null
  10159. // Coordinate Reference System to use for the WMS requests, defaults to
  10160. // map CRS. Don't change this if you're not sure what it means.
  10161. crs: null,
  10162. // @option uppercase: Boolean = false
  10163. // If `true`, WMS request parameter keys will be uppercase.
  10164. uppercase: false
  10165. },
  10166. initialize: function (url, options) {
  10167. this._url = url;
  10168. var wmsParams = extend({}, this.defaultWmsParams);
  10169. // all keys that are not TileLayer options go to WMS params
  10170. for (var i in options) {
  10171. if (!(i in this.options)) {
  10172. wmsParams[i] = options[i];
  10173. }
  10174. }
  10175. options = setOptions(this, options);
  10176. var realRetina = options.detectRetina && Browser.retina ? 2 : 1;
  10177. var tileSize = this.getTileSize();
  10178. wmsParams.width = tileSize.x * realRetina;
  10179. wmsParams.height = tileSize.y * realRetina;
  10180. this.wmsParams = wmsParams;
  10181. },
  10182. onAdd: function (map) {
  10183. this._crs = this.options.crs || map.options.crs;
  10184. this._wmsVersion = parseFloat(this.wmsParams.version);
  10185. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  10186. this.wmsParams[projectionKey] = this._crs.code;
  10187. TileLayer.prototype.onAdd.call(this, map);
  10188. },
  10189. getTileUrl: function (coords) {
  10190. var tileBounds = this._tileCoordsToNwSe(coords),
  10191. crs = this._crs,
  10192. bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
  10193. min = bounds.min,
  10194. max = bounds.max,
  10195. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  10196. [min.y, min.x, max.y, max.x] :
  10197. [min.x, min.y, max.x, max.y]).join(','),
  10198. url = TileLayer.prototype.getTileUrl.call(this, coords);
  10199. return url +
  10200. getParamString(this.wmsParams, url, this.options.uppercase) +
  10201. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  10202. },
  10203. // @method setParams(params: Object, noRedraw?: Boolean): this
  10204. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  10205. setParams: function (params, noRedraw) {
  10206. extend(this.wmsParams, params);
  10207. if (!noRedraw) {
  10208. this.redraw();
  10209. }
  10210. return this;
  10211. }
  10212. });
  10213. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  10214. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  10215. function tileLayerWMS(url, options) {
  10216. return new TileLayerWMS(url, options);
  10217. }
  10218. TileLayer.WMS = TileLayerWMS;
  10219. tileLayer.wms = tileLayerWMS;
  10220. /*
  10221. * @class Renderer
  10222. * @inherits Layer
  10223. * @aka L.Renderer
  10224. *
  10225. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  10226. * DOM container of the renderer, its bounds, and its zoom animation.
  10227. *
  10228. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  10229. * itself can be added or removed to the map. All paths use a renderer, which can
  10230. * be implicit (the map will decide the type of renderer and use it automatically)
  10231. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  10232. *
  10233. * Do not use this class directly, use `SVG` and `Canvas` instead.
  10234. *
  10235. * @event update: Event
  10236. * Fired when the renderer updates its bounds, center and zoom, for example when
  10237. * its map has moved
  10238. */
  10239. var Renderer = Layer.extend({
  10240. // @section
  10241. // @aka Renderer options
  10242. options: {
  10243. // @option padding: Number = 0.1
  10244. // How much to extend the clip area around the map view (relative to its size)
  10245. // e.g. 0.1 would be 10% of map view in each direction
  10246. padding: 0.1
  10247. },
  10248. initialize: function (options) {
  10249. setOptions(this, options);
  10250. stamp(this);
  10251. this._layers = this._layers || {};
  10252. },
  10253. onAdd: function () {
  10254. if (!this._container) {
  10255. this._initContainer(); // defined by renderer implementations
  10256. // always keep transform-origin as 0 0
  10257. addClass(this._container, 'leaflet-zoom-animated');
  10258. }
  10259. this.getPane().appendChild(this._container);
  10260. this._update();
  10261. this.on('update', this._updatePaths, this);
  10262. },
  10263. onRemove: function () {
  10264. this.off('update', this._updatePaths, this);
  10265. this._destroyContainer();
  10266. },
  10267. getEvents: function () {
  10268. var events = {
  10269. viewreset: this._reset,
  10270. zoom: this._onZoom,
  10271. moveend: this._update,
  10272. zoomend: this._onZoomEnd
  10273. };
  10274. if (this._zoomAnimated) {
  10275. events.zoomanim = this._onAnimZoom;
  10276. }
  10277. return events;
  10278. },
  10279. _onAnimZoom: function (ev) {
  10280. this._updateTransform(ev.center, ev.zoom);
  10281. },
  10282. _onZoom: function () {
  10283. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  10284. },
  10285. _updateTransform: function (center, zoom) {
  10286. var scale = this._map.getZoomScale(zoom, this._zoom),
  10287. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  10288. currentCenterPoint = this._map.project(this._center, zoom),
  10289. topLeftOffset = viewHalf.multiplyBy(-scale).add(currentCenterPoint)
  10290. .subtract(this._map._getNewPixelOrigin(center, zoom));
  10291. if (Browser.any3d) {
  10292. setTransform(this._container, topLeftOffset, scale);
  10293. } else {
  10294. setPosition(this._container, topLeftOffset);
  10295. }
  10296. },
  10297. _reset: function () {
  10298. this._update();
  10299. this._updateTransform(this._center, this._zoom);
  10300. for (var id in this._layers) {
  10301. this._layers[id]._reset();
  10302. }
  10303. },
  10304. _onZoomEnd: function () {
  10305. for (var id in this._layers) {
  10306. this._layers[id]._project();
  10307. }
  10308. },
  10309. _updatePaths: function () {
  10310. for (var id in this._layers) {
  10311. this._layers[id]._update();
  10312. }
  10313. },
  10314. _update: function () {
  10315. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  10316. // Subclasses are responsible of firing the 'update' event.
  10317. var p = this.options.padding,
  10318. size = this._map.getSize(),
  10319. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  10320. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  10321. this._center = this._map.getCenter();
  10322. this._zoom = this._map.getZoom();
  10323. }
  10324. });
  10325. /*
  10326. * @class Canvas
  10327. * @inherits Renderer
  10328. * @aka L.Canvas
  10329. *
  10330. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  10331. * Inherits `Renderer`.
  10332. *
  10333. * Due to [technical limitations](https://caniuse.com/canvas), Canvas is not
  10334. * available in all web browsers, notably IE8, and overlapping geometries might
  10335. * not display properly in some edge cases.
  10336. *
  10337. * @example
  10338. *
  10339. * Use Canvas by default for all paths in the map:
  10340. *
  10341. * ```js
  10342. * var map = L.map('map', {
  10343. * renderer: L.canvas()
  10344. * });
  10345. * ```
  10346. *
  10347. * Use a Canvas renderer with extra padding for specific vector geometries:
  10348. *
  10349. * ```js
  10350. * var map = L.map('map');
  10351. * var myRenderer = L.canvas({ padding: 0.5 });
  10352. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10353. * var circle = L.circle( center, { renderer: myRenderer } );
  10354. * ```
  10355. */
  10356. var Canvas = Renderer.extend({
  10357. // @section
  10358. // @aka Canvas options
  10359. options: {
  10360. // @option tolerance: Number = 0
  10361. // How much to extend the click tolerance around a path/object on the map.
  10362. tolerance: 0
  10363. },
  10364. getEvents: function () {
  10365. var events = Renderer.prototype.getEvents.call(this);
  10366. events.viewprereset = this._onViewPreReset;
  10367. return events;
  10368. },
  10369. _onViewPreReset: function () {
  10370. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  10371. this._postponeUpdatePaths = true;
  10372. },
  10373. onAdd: function () {
  10374. Renderer.prototype.onAdd.call(this);
  10375. // Redraw vectors since canvas is cleared upon removal,
  10376. // in case of removing the renderer itself from the map.
  10377. this._draw();
  10378. },
  10379. _initContainer: function () {
  10380. var container = this._container = document.createElement('canvas');
  10381. on(container, 'mousemove', this._onMouseMove, this);
  10382. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  10383. on(container, 'mouseout', this._handleMouseOut, this);
  10384. container['_leaflet_disable_events'] = true;
  10385. this._ctx = container.getContext('2d');
  10386. },
  10387. _destroyContainer: function () {
  10388. cancelAnimFrame(this._redrawRequest);
  10389. delete this._ctx;
  10390. remove(this._container);
  10391. off(this._container);
  10392. delete this._container;
  10393. },
  10394. _updatePaths: function () {
  10395. if (this._postponeUpdatePaths) { return; }
  10396. var layer;
  10397. this._redrawBounds = null;
  10398. for (var id in this._layers) {
  10399. layer = this._layers[id];
  10400. layer._update();
  10401. }
  10402. this._redraw();
  10403. },
  10404. _update: function () {
  10405. if (this._map._animatingZoom && this._bounds) { return; }
  10406. Renderer.prototype._update.call(this);
  10407. var b = this._bounds,
  10408. container = this._container,
  10409. size = b.getSize(),
  10410. m = Browser.retina ? 2 : 1;
  10411. setPosition(container, b.min);
  10412. // set canvas size (also clearing it); use double size on retina
  10413. container.width = m * size.x;
  10414. container.height = m * size.y;
  10415. container.style.width = size.x + 'px';
  10416. container.style.height = size.y + 'px';
  10417. if (Browser.retina) {
  10418. this._ctx.scale(2, 2);
  10419. }
  10420. // translate so we use the same path coordinates after canvas element moves
  10421. this._ctx.translate(-b.min.x, -b.min.y);
  10422. // Tell paths to redraw themselves
  10423. this.fire('update');
  10424. },
  10425. _reset: function () {
  10426. Renderer.prototype._reset.call(this);
  10427. if (this._postponeUpdatePaths) {
  10428. this._postponeUpdatePaths = false;
  10429. this._updatePaths();
  10430. }
  10431. },
  10432. _initPath: function (layer) {
  10433. this._updateDashArray(layer);
  10434. this._layers[stamp(layer)] = layer;
  10435. var order = layer._order = {
  10436. layer: layer,
  10437. prev: this._drawLast,
  10438. next: null
  10439. };
  10440. if (this._drawLast) { this._drawLast.next = order; }
  10441. this._drawLast = order;
  10442. this._drawFirst = this._drawFirst || this._drawLast;
  10443. },
  10444. _addPath: function (layer) {
  10445. this._requestRedraw(layer);
  10446. },
  10447. _removePath: function (layer) {
  10448. var order = layer._order;
  10449. var next = order.next;
  10450. var prev = order.prev;
  10451. if (next) {
  10452. next.prev = prev;
  10453. } else {
  10454. this._drawLast = prev;
  10455. }
  10456. if (prev) {
  10457. prev.next = next;
  10458. } else {
  10459. this._drawFirst = next;
  10460. }
  10461. delete layer._order;
  10462. delete this._layers[stamp(layer)];
  10463. this._requestRedraw(layer);
  10464. },
  10465. _updatePath: function (layer) {
  10466. // Redraw the union of the layer's old pixel
  10467. // bounds and the new pixel bounds.
  10468. this._extendRedrawBounds(layer);
  10469. layer._project();
  10470. layer._update();
  10471. // The redraw will extend the redraw bounds
  10472. // with the new pixel bounds.
  10473. this._requestRedraw(layer);
  10474. },
  10475. _updateStyle: function (layer) {
  10476. this._updateDashArray(layer);
  10477. this._requestRedraw(layer);
  10478. },
  10479. _updateDashArray: function (layer) {
  10480. if (typeof layer.options.dashArray === 'string') {
  10481. var parts = layer.options.dashArray.split(/[, ]+/),
  10482. dashArray = [],
  10483. dashValue,
  10484. i;
  10485. for (i = 0; i < parts.length; i++) {
  10486. dashValue = Number(parts[i]);
  10487. // Ignore dash array containing invalid lengths
  10488. if (isNaN(dashValue)) { return; }
  10489. dashArray.push(dashValue);
  10490. }
  10491. layer.options._dashArray = dashArray;
  10492. } else {
  10493. layer.options._dashArray = layer.options.dashArray;
  10494. }
  10495. },
  10496. _requestRedraw: function (layer) {
  10497. if (!this._map) { return; }
  10498. this._extendRedrawBounds(layer);
  10499. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  10500. },
  10501. _extendRedrawBounds: function (layer) {
  10502. if (layer._pxBounds) {
  10503. var padding = (layer.options.weight || 0) + 1;
  10504. this._redrawBounds = this._redrawBounds || new Bounds();
  10505. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  10506. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  10507. }
  10508. },
  10509. _redraw: function () {
  10510. this._redrawRequest = null;
  10511. if (this._redrawBounds) {
  10512. this._redrawBounds.min._floor();
  10513. this._redrawBounds.max._ceil();
  10514. }
  10515. this._clear(); // clear layers in redraw bounds
  10516. this._draw(); // draw layers
  10517. this._redrawBounds = null;
  10518. },
  10519. _clear: function () {
  10520. var bounds = this._redrawBounds;
  10521. if (bounds) {
  10522. var size = bounds.getSize();
  10523. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  10524. } else {
  10525. this._ctx.save();
  10526. this._ctx.setTransform(1, 0, 0, 1, 0, 0);
  10527. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  10528. this._ctx.restore();
  10529. }
  10530. },
  10531. _draw: function () {
  10532. var layer, bounds = this._redrawBounds;
  10533. this._ctx.save();
  10534. if (bounds) {
  10535. var size = bounds.getSize();
  10536. this._ctx.beginPath();
  10537. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  10538. this._ctx.clip();
  10539. }
  10540. this._drawing = true;
  10541. for (var order = this._drawFirst; order; order = order.next) {
  10542. layer = order.layer;
  10543. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  10544. layer._updatePath();
  10545. }
  10546. }
  10547. this._drawing = false;
  10548. this._ctx.restore(); // Restore state before clipping.
  10549. },
  10550. _updatePoly: function (layer, closed) {
  10551. if (!this._drawing) { return; }
  10552. var i, j, len2, p,
  10553. parts = layer._parts,
  10554. len = parts.length,
  10555. ctx = this._ctx;
  10556. if (!len) { return; }
  10557. ctx.beginPath();
  10558. for (i = 0; i < len; i++) {
  10559. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  10560. p = parts[i][j];
  10561. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  10562. }
  10563. if (closed) {
  10564. ctx.closePath();
  10565. }
  10566. }
  10567. this._fillStroke(ctx, layer);
  10568. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  10569. },
  10570. _updateCircle: function (layer) {
  10571. if (!this._drawing || layer._empty()) { return; }
  10572. var p = layer._point,
  10573. ctx = this._ctx,
  10574. r = Math.max(Math.round(layer._radius), 1),
  10575. s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
  10576. if (s !== 1) {
  10577. ctx.save();
  10578. ctx.scale(1, s);
  10579. }
  10580. ctx.beginPath();
  10581. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  10582. if (s !== 1) {
  10583. ctx.restore();
  10584. }
  10585. this._fillStroke(ctx, layer);
  10586. },
  10587. _fillStroke: function (ctx, layer) {
  10588. var options = layer.options;
  10589. if (options.fill) {
  10590. ctx.globalAlpha = options.fillOpacity;
  10591. ctx.fillStyle = options.fillColor || options.color;
  10592. ctx.fill(options.fillRule || 'evenodd');
  10593. }
  10594. if (options.stroke && options.weight !== 0) {
  10595. if (ctx.setLineDash) {
  10596. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  10597. }
  10598. ctx.globalAlpha = options.opacity;
  10599. ctx.lineWidth = options.weight;
  10600. ctx.strokeStyle = options.color;
  10601. ctx.lineCap = options.lineCap;
  10602. ctx.lineJoin = options.lineJoin;
  10603. ctx.stroke();
  10604. }
  10605. },
  10606. // Canvas obviously doesn't have mouse events for individual drawn objects,
  10607. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  10608. _onClick: function (e) {
  10609. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  10610. for (var order = this._drawFirst; order; order = order.next) {
  10611. layer = order.layer;
  10612. if (layer.options.interactive && layer._containsPoint(point)) {
  10613. if (!(e.type === 'click' || e.type === 'preclick') || !this._map._draggableMoved(layer)) {
  10614. clickedLayer = layer;
  10615. }
  10616. }
  10617. }
  10618. this._fireEvent(clickedLayer ? [clickedLayer] : false, e);
  10619. },
  10620. _onMouseMove: function (e) {
  10621. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  10622. var point = this._map.mouseEventToLayerPoint(e);
  10623. this._handleMouseHover(e, point);
  10624. },
  10625. _handleMouseOut: function (e) {
  10626. var layer = this._hoveredLayer;
  10627. if (layer) {
  10628. // if we're leaving the layer, fire mouseout
  10629. removeClass(this._container, 'leaflet-interactive');
  10630. this._fireEvent([layer], e, 'mouseout');
  10631. this._hoveredLayer = null;
  10632. this._mouseHoverThrottled = false;
  10633. }
  10634. },
  10635. _handleMouseHover: function (e, point) {
  10636. if (this._mouseHoverThrottled) {
  10637. return;
  10638. }
  10639. var layer, candidateHoveredLayer;
  10640. for (var order = this._drawFirst; order; order = order.next) {
  10641. layer = order.layer;
  10642. if (layer.options.interactive && layer._containsPoint(point)) {
  10643. candidateHoveredLayer = layer;
  10644. }
  10645. }
  10646. if (candidateHoveredLayer !== this._hoveredLayer) {
  10647. this._handleMouseOut(e);
  10648. if (candidateHoveredLayer) {
  10649. addClass(this._container, 'leaflet-interactive'); // change cursor
  10650. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  10651. this._hoveredLayer = candidateHoveredLayer;
  10652. }
  10653. }
  10654. this._fireEvent(this._hoveredLayer ? [this._hoveredLayer] : false, e);
  10655. this._mouseHoverThrottled = true;
  10656. setTimeout(bind(function () {
  10657. this._mouseHoverThrottled = false;
  10658. }, this), 32);
  10659. },
  10660. _fireEvent: function (layers, e, type) {
  10661. this._map._fireDOMEvent(e, type || e.type, layers);
  10662. },
  10663. _bringToFront: function (layer) {
  10664. var order = layer._order;
  10665. if (!order) { return; }
  10666. var next = order.next;
  10667. var prev = order.prev;
  10668. if (next) {
  10669. next.prev = prev;
  10670. } else {
  10671. // Already last
  10672. return;
  10673. }
  10674. if (prev) {
  10675. prev.next = next;
  10676. } else if (next) {
  10677. // Update first entry unless this is the
  10678. // single entry
  10679. this._drawFirst = next;
  10680. }
  10681. order.prev = this._drawLast;
  10682. this._drawLast.next = order;
  10683. order.next = null;
  10684. this._drawLast = order;
  10685. this._requestRedraw(layer);
  10686. },
  10687. _bringToBack: function (layer) {
  10688. var order = layer._order;
  10689. if (!order) { return; }
  10690. var next = order.next;
  10691. var prev = order.prev;
  10692. if (prev) {
  10693. prev.next = next;
  10694. } else {
  10695. // Already first
  10696. return;
  10697. }
  10698. if (next) {
  10699. next.prev = prev;
  10700. } else if (prev) {
  10701. // Update last entry unless this is the
  10702. // single entry
  10703. this._drawLast = prev;
  10704. }
  10705. order.prev = null;
  10706. order.next = this._drawFirst;
  10707. this._drawFirst.prev = order;
  10708. this._drawFirst = order;
  10709. this._requestRedraw(layer);
  10710. }
  10711. });
  10712. // @factory L.canvas(options?: Renderer options)
  10713. // Creates a Canvas renderer with the given options.
  10714. function canvas(options) {
  10715. return Browser.canvas ? new Canvas(options) : null;
  10716. }
  10717. /*
  10718. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10719. */
  10720. var vmlCreate = (function () {
  10721. try {
  10722. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10723. return function (name) {
  10724. return document.createElement('<lvml:' + name + ' class="lvml">');
  10725. };
  10726. } catch (e) {
  10727. // Do not return fn from catch block so `e` can be garbage collected
  10728. // See https://github.com/Leaflet/Leaflet/pull/7279
  10729. }
  10730. return function (name) {
  10731. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10732. };
  10733. })();
  10734. /*
  10735. * @class SVG
  10736. *
  10737. *
  10738. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10739. * with old versions of Internet Explorer.
  10740. */
  10741. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10742. var vmlMixin = {
  10743. _initContainer: function () {
  10744. this._container = create$1('div', 'leaflet-vml-container');
  10745. },
  10746. _update: function () {
  10747. if (this._map._animatingZoom) { return; }
  10748. Renderer.prototype._update.call(this);
  10749. this.fire('update');
  10750. },
  10751. _initPath: function (layer) {
  10752. var container = layer._container = vmlCreate('shape');
  10753. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10754. container.coordsize = '1 1';
  10755. layer._path = vmlCreate('path');
  10756. container.appendChild(layer._path);
  10757. this._updateStyle(layer);
  10758. this._layers[stamp(layer)] = layer;
  10759. },
  10760. _addPath: function (layer) {
  10761. var container = layer._container;
  10762. this._container.appendChild(container);
  10763. if (layer.options.interactive) {
  10764. layer.addInteractiveTarget(container);
  10765. }
  10766. },
  10767. _removePath: function (layer) {
  10768. var container = layer._container;
  10769. remove(container);
  10770. layer.removeInteractiveTarget(container);
  10771. delete this._layers[stamp(layer)];
  10772. },
  10773. _updateStyle: function (layer) {
  10774. var stroke = layer._stroke,
  10775. fill = layer._fill,
  10776. options = layer.options,
  10777. container = layer._container;
  10778. container.stroked = !!options.stroke;
  10779. container.filled = !!options.fill;
  10780. if (options.stroke) {
  10781. if (!stroke) {
  10782. stroke = layer._stroke = vmlCreate('stroke');
  10783. }
  10784. container.appendChild(stroke);
  10785. stroke.weight = options.weight + 'px';
  10786. stroke.color = options.color;
  10787. stroke.opacity = options.opacity;
  10788. if (options.dashArray) {
  10789. stroke.dashStyle = isArray(options.dashArray) ?
  10790. options.dashArray.join(' ') :
  10791. options.dashArray.replace(/( *, *)/g, ' ');
  10792. } else {
  10793. stroke.dashStyle = '';
  10794. }
  10795. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10796. stroke.joinstyle = options.lineJoin;
  10797. } else if (stroke) {
  10798. container.removeChild(stroke);
  10799. layer._stroke = null;
  10800. }
  10801. if (options.fill) {
  10802. if (!fill) {
  10803. fill = layer._fill = vmlCreate('fill');
  10804. }
  10805. container.appendChild(fill);
  10806. fill.color = options.fillColor || options.color;
  10807. fill.opacity = options.fillOpacity;
  10808. } else if (fill) {
  10809. container.removeChild(fill);
  10810. layer._fill = null;
  10811. }
  10812. },
  10813. _updateCircle: function (layer) {
  10814. var p = layer._point.round(),
  10815. r = Math.round(layer._radius),
  10816. r2 = Math.round(layer._radiusY || r);
  10817. this._setPath(layer, layer._empty() ? 'M0 0' :
  10818. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10819. },
  10820. _setPath: function (layer, path) {
  10821. layer._path.v = path;
  10822. },
  10823. _bringToFront: function (layer) {
  10824. toFront(layer._container);
  10825. },
  10826. _bringToBack: function (layer) {
  10827. toBack(layer._container);
  10828. }
  10829. };
  10830. var create = Browser.vml ? vmlCreate : svgCreate;
  10831. /*
  10832. * @class SVG
  10833. * @inherits Renderer
  10834. * @aka L.SVG
  10835. *
  10836. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10837. * Inherits `Renderer`.
  10838. *
  10839. * Due to [technical limitations](https://caniuse.com/svg), SVG is not
  10840. * available in all web browsers, notably Android 2.x and 3.x.
  10841. *
  10842. * Although SVG is not available on IE7 and IE8, these browsers support
  10843. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10844. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10845. * this case.
  10846. *
  10847. * @example
  10848. *
  10849. * Use SVG by default for all paths in the map:
  10850. *
  10851. * ```js
  10852. * var map = L.map('map', {
  10853. * renderer: L.svg()
  10854. * });
  10855. * ```
  10856. *
  10857. * Use a SVG renderer with extra padding for specific vector geometries:
  10858. *
  10859. * ```js
  10860. * var map = L.map('map');
  10861. * var myRenderer = L.svg({ padding: 0.5 });
  10862. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10863. * var circle = L.circle( center, { renderer: myRenderer } );
  10864. * ```
  10865. */
  10866. var SVG = Renderer.extend({
  10867. _initContainer: function () {
  10868. this._container = create('svg');
  10869. // makes it possible to click through svg root; we'll reset it back in individual paths
  10870. this._container.setAttribute('pointer-events', 'none');
  10871. this._rootGroup = create('g');
  10872. this._container.appendChild(this._rootGroup);
  10873. },
  10874. _destroyContainer: function () {
  10875. remove(this._container);
  10876. off(this._container);
  10877. delete this._container;
  10878. delete this._rootGroup;
  10879. delete this._svgSize;
  10880. },
  10881. _update: function () {
  10882. if (this._map._animatingZoom && this._bounds) { return; }
  10883. Renderer.prototype._update.call(this);
  10884. var b = this._bounds,
  10885. size = b.getSize(),
  10886. container = this._container;
  10887. // set size of svg-container if changed
  10888. if (!this._svgSize || !this._svgSize.equals(size)) {
  10889. this._svgSize = size;
  10890. container.setAttribute('width', size.x);
  10891. container.setAttribute('height', size.y);
  10892. }
  10893. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10894. setPosition(container, b.min);
  10895. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10896. this.fire('update');
  10897. },
  10898. // methods below are called by vector layers implementations
  10899. _initPath: function (layer) {
  10900. var path = layer._path = create('path');
  10901. // @namespace Path
  10902. // @option className: String = null
  10903. // Custom class name set on an element. Only for SVG renderer.
  10904. if (layer.options.className) {
  10905. addClass(path, layer.options.className);
  10906. }
  10907. if (layer.options.interactive) {
  10908. addClass(path, 'leaflet-interactive');
  10909. }
  10910. this._updateStyle(layer);
  10911. this._layers[stamp(layer)] = layer;
  10912. },
  10913. _addPath: function (layer) {
  10914. if (!this._rootGroup) { this._initContainer(); }
  10915. this._rootGroup.appendChild(layer._path);
  10916. layer.addInteractiveTarget(layer._path);
  10917. },
  10918. _removePath: function (layer) {
  10919. remove(layer._path);
  10920. layer.removeInteractiveTarget(layer._path);
  10921. delete this._layers[stamp(layer)];
  10922. },
  10923. _updatePath: function (layer) {
  10924. layer._project();
  10925. layer._update();
  10926. },
  10927. _updateStyle: function (layer) {
  10928. var path = layer._path,
  10929. options = layer.options;
  10930. if (!path) { return; }
  10931. if (options.stroke) {
  10932. path.setAttribute('stroke', options.color);
  10933. path.setAttribute('stroke-opacity', options.opacity);
  10934. path.setAttribute('stroke-width', options.weight);
  10935. path.setAttribute('stroke-linecap', options.lineCap);
  10936. path.setAttribute('stroke-linejoin', options.lineJoin);
  10937. if (options.dashArray) {
  10938. path.setAttribute('stroke-dasharray', options.dashArray);
  10939. } else {
  10940. path.removeAttribute('stroke-dasharray');
  10941. }
  10942. if (options.dashOffset) {
  10943. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10944. } else {
  10945. path.removeAttribute('stroke-dashoffset');
  10946. }
  10947. } else {
  10948. path.setAttribute('stroke', 'none');
  10949. }
  10950. if (options.fill) {
  10951. path.setAttribute('fill', options.fillColor || options.color);
  10952. path.setAttribute('fill-opacity', options.fillOpacity);
  10953. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10954. } else {
  10955. path.setAttribute('fill', 'none');
  10956. }
  10957. },
  10958. _updatePoly: function (layer, closed) {
  10959. this._setPath(layer, pointsToPath(layer._parts, closed));
  10960. },
  10961. _updateCircle: function (layer) {
  10962. var p = layer._point,
  10963. r = Math.max(Math.round(layer._radius), 1),
  10964. r2 = Math.max(Math.round(layer._radiusY), 1) || r,
  10965. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10966. // drawing a circle with two half-arcs
  10967. var d = layer._empty() ? 'M0 0' :
  10968. 'M' + (p.x - r) + ',' + p.y +
  10969. arc + (r * 2) + ',0 ' +
  10970. arc + (-r * 2) + ',0 ';
  10971. this._setPath(layer, d);
  10972. },
  10973. _setPath: function (layer, path) {
  10974. layer._path.setAttribute('d', path);
  10975. },
  10976. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10977. _bringToFront: function (layer) {
  10978. toFront(layer._path);
  10979. },
  10980. _bringToBack: function (layer) {
  10981. toBack(layer._path);
  10982. }
  10983. });
  10984. if (Browser.vml) {
  10985. SVG.include(vmlMixin);
  10986. }
  10987. // @namespace SVG
  10988. // @factory L.svg(options?: Renderer options)
  10989. // Creates a SVG renderer with the given options.
  10990. function svg(options) {
  10991. return Browser.svg || Browser.vml ? new SVG(options) : null;
  10992. }
  10993. Map.include({
  10994. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10995. // Returns the instance of `Renderer` that should be used to render the given
  10996. // `Path`. It will ensure that the `renderer` options of the map and paths
  10997. // are respected, and that the renderers do exist on the map.
  10998. getRenderer: function (layer) {
  10999. // @namespace Path; @option renderer: Renderer
  11000. // Use this specific instance of `Renderer` for this path. Takes
  11001. // precedence over the map's [default renderer](#map-renderer).
  11002. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  11003. if (!renderer) {
  11004. renderer = this._renderer = this._createRenderer();
  11005. }
  11006. if (!this.hasLayer(renderer)) {
  11007. this.addLayer(renderer);
  11008. }
  11009. return renderer;
  11010. },
  11011. _getPaneRenderer: function (name) {
  11012. if (name === 'overlayPane' || name === undefined) {
  11013. return false;
  11014. }
  11015. var renderer = this._paneRenderers[name];
  11016. if (renderer === undefined) {
  11017. renderer = this._createRenderer({pane: name});
  11018. this._paneRenderers[name] = renderer;
  11019. }
  11020. return renderer;
  11021. },
  11022. _createRenderer: function (options) {
  11023. // @namespace Map; @option preferCanvas: Boolean = false
  11024. // Whether `Path`s should be rendered on a `Canvas` renderer.
  11025. // By default, all `Path`s are rendered in a `SVG` renderer.
  11026. return (this.options.preferCanvas && canvas(options)) || svg(options);
  11027. }
  11028. });
  11029. /*
  11030. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  11031. */
  11032. /*
  11033. * @class Rectangle
  11034. * @aka L.Rectangle
  11035. * @inherits Polygon
  11036. *
  11037. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  11038. *
  11039. * @example
  11040. *
  11041. * ```js
  11042. * // define rectangle geographical bounds
  11043. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  11044. *
  11045. * // create an orange rectangle
  11046. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  11047. *
  11048. * // zoom the map to the rectangle bounds
  11049. * map.fitBounds(bounds);
  11050. * ```
  11051. *
  11052. */
  11053. var Rectangle = Polygon.extend({
  11054. initialize: function (latLngBounds, options) {
  11055. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  11056. },
  11057. // @method setBounds(latLngBounds: LatLngBounds): this
  11058. // Redraws the rectangle with the passed bounds.
  11059. setBounds: function (latLngBounds) {
  11060. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  11061. },
  11062. _boundsToLatLngs: function (latLngBounds) {
  11063. latLngBounds = toLatLngBounds(latLngBounds);
  11064. return [
  11065. latLngBounds.getSouthWest(),
  11066. latLngBounds.getNorthWest(),
  11067. latLngBounds.getNorthEast(),
  11068. latLngBounds.getSouthEast()
  11069. ];
  11070. }
  11071. });
  11072. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  11073. function rectangle(latLngBounds, options) {
  11074. return new Rectangle(latLngBounds, options);
  11075. }
  11076. SVG.create = create;
  11077. SVG.pointsToPath = pointsToPath;
  11078. GeoJSON.geometryToLayer = geometryToLayer;
  11079. GeoJSON.coordsToLatLng = coordsToLatLng;
  11080. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  11081. GeoJSON.latLngToCoords = latLngToCoords;
  11082. GeoJSON.latLngsToCoords = latLngsToCoords;
  11083. GeoJSON.getFeature = getFeature;
  11084. GeoJSON.asFeature = asFeature;
  11085. /*
  11086. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  11087. * (zoom to a selected bounding box), enabled by default.
  11088. */
  11089. // @namespace Map
  11090. // @section Interaction Options
  11091. Map.mergeOptions({
  11092. // @option boxZoom: Boolean = true
  11093. // Whether the map can be zoomed to a rectangular area specified by
  11094. // dragging the mouse while pressing the shift key.
  11095. boxZoom: true
  11096. });
  11097. var BoxZoom = Handler.extend({
  11098. initialize: function (map) {
  11099. this._map = map;
  11100. this._container = map._container;
  11101. this._pane = map._panes.overlayPane;
  11102. this._resetStateTimeout = 0;
  11103. map.on('unload', this._destroy, this);
  11104. },
  11105. addHooks: function () {
  11106. on(this._container, 'mousedown', this._onMouseDown, this);
  11107. },
  11108. removeHooks: function () {
  11109. off(this._container, 'mousedown', this._onMouseDown, this);
  11110. },
  11111. moved: function () {
  11112. return this._moved;
  11113. },
  11114. _destroy: function () {
  11115. remove(this._pane);
  11116. delete this._pane;
  11117. },
  11118. _resetState: function () {
  11119. this._resetStateTimeout = 0;
  11120. this._moved = false;
  11121. },
  11122. _clearDeferredResetState: function () {
  11123. if (this._resetStateTimeout !== 0) {
  11124. clearTimeout(this._resetStateTimeout);
  11125. this._resetStateTimeout = 0;
  11126. }
  11127. },
  11128. _onMouseDown: function (e) {
  11129. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  11130. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  11131. // will interrupt the interaction and orphan a box element in the container.
  11132. this._clearDeferredResetState();
  11133. this._resetState();
  11134. disableTextSelection();
  11135. disableImageDrag();
  11136. this._startPoint = this._map.mouseEventToContainerPoint(e);
  11137. on(document, {
  11138. contextmenu: stop,
  11139. mousemove: this._onMouseMove,
  11140. mouseup: this._onMouseUp,
  11141. keydown: this._onKeyDown
  11142. }, this);
  11143. },
  11144. _onMouseMove: function (e) {
  11145. if (!this._moved) {
  11146. this._moved = true;
  11147. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  11148. addClass(this._container, 'leaflet-crosshair');
  11149. this._map.fire('boxzoomstart');
  11150. }
  11151. this._point = this._map.mouseEventToContainerPoint(e);
  11152. var bounds = new Bounds(this._point, this._startPoint),
  11153. size = bounds.getSize();
  11154. setPosition(this._box, bounds.min);
  11155. this._box.style.width = size.x + 'px';
  11156. this._box.style.height = size.y + 'px';
  11157. },
  11158. _finish: function () {
  11159. if (this._moved) {
  11160. remove(this._box);
  11161. removeClass(this._container, 'leaflet-crosshair');
  11162. }
  11163. enableTextSelection();
  11164. enableImageDrag();
  11165. off(document, {
  11166. contextmenu: stop,
  11167. mousemove: this._onMouseMove,
  11168. mouseup: this._onMouseUp,
  11169. keydown: this._onKeyDown
  11170. }, this);
  11171. },
  11172. _onMouseUp: function (e) {
  11173. if ((e.which !== 1) && (e.button !== 1)) { return; }
  11174. this._finish();
  11175. if (!this._moved) { return; }
  11176. // Postpone to next JS tick so internal click event handling
  11177. // still see it as "moved".
  11178. this._clearDeferredResetState();
  11179. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  11180. var bounds = new LatLngBounds(
  11181. this._map.containerPointToLatLng(this._startPoint),
  11182. this._map.containerPointToLatLng(this._point));
  11183. this._map
  11184. .fitBounds(bounds)
  11185. .fire('boxzoomend', {boxZoomBounds: bounds});
  11186. },
  11187. _onKeyDown: function (e) {
  11188. if (e.keyCode === 27) {
  11189. this._finish();
  11190. this._clearDeferredResetState();
  11191. this._resetState();
  11192. }
  11193. }
  11194. });
  11195. // @section Handlers
  11196. // @property boxZoom: Handler
  11197. // Box (shift-drag with mouse) zoom handler.
  11198. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  11199. /*
  11200. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  11201. */
  11202. // @namespace Map
  11203. // @section Interaction Options
  11204. Map.mergeOptions({
  11205. // @option doubleClickZoom: Boolean|String = true
  11206. // Whether the map can be zoomed in by double clicking on it and
  11207. // zoomed out by double clicking while holding shift. If passed
  11208. // `'center'`, double-click zoom will zoom to the center of the
  11209. // view regardless of where the mouse was.
  11210. doubleClickZoom: true
  11211. });
  11212. var DoubleClickZoom = Handler.extend({
  11213. addHooks: function () {
  11214. this._map.on('dblclick', this._onDoubleClick, this);
  11215. },
  11216. removeHooks: function () {
  11217. this._map.off('dblclick', this._onDoubleClick, this);
  11218. },
  11219. _onDoubleClick: function (e) {
  11220. var map = this._map,
  11221. oldZoom = map.getZoom(),
  11222. delta = map.options.zoomDelta,
  11223. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  11224. if (map.options.doubleClickZoom === 'center') {
  11225. map.setZoom(zoom);
  11226. } else {
  11227. map.setZoomAround(e.containerPoint, zoom);
  11228. }
  11229. }
  11230. });
  11231. // @section Handlers
  11232. //
  11233. // Map properties include interaction handlers that allow you to control
  11234. // interaction behavior in runtime, enabling or disabling certain features such
  11235. // as dragging or touch zoom (see `Handler` methods). For example:
  11236. //
  11237. // ```js
  11238. // map.doubleClickZoom.disable();
  11239. // ```
  11240. //
  11241. // @property doubleClickZoom: Handler
  11242. // Double click zoom handler.
  11243. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  11244. /*
  11245. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  11246. */
  11247. // @namespace Map
  11248. // @section Interaction Options
  11249. Map.mergeOptions({
  11250. // @option dragging: Boolean = true
  11251. // Whether the map is draggable with mouse/touch or not.
  11252. dragging: true,
  11253. // @section Panning Inertia Options
  11254. // @option inertia: Boolean = *
  11255. // If enabled, panning of the map will have an inertia effect where
  11256. // the map builds momentum while dragging and continues moving in
  11257. // the same direction for some time. Feels especially nice on touch
  11258. // devices. Enabled by default.
  11259. inertia: true,
  11260. // @option inertiaDeceleration: Number = 3000
  11261. // The rate with which the inertial movement slows down, in pixels/second².
  11262. inertiaDeceleration: 3400, // px/s^2
  11263. // @option inertiaMaxSpeed: Number = Infinity
  11264. // Max speed of the inertial movement, in pixels/second.
  11265. inertiaMaxSpeed: Infinity, // px/s
  11266. // @option easeLinearity: Number = 0.2
  11267. easeLinearity: 0.2,
  11268. // TODO refactor, move to CRS
  11269. // @option worldCopyJump: Boolean = false
  11270. // With this option enabled, the map tracks when you pan to another "copy"
  11271. // of the world and seamlessly jumps to the original one so that all overlays
  11272. // like markers and vector layers are still visible.
  11273. worldCopyJump: false,
  11274. // @option maxBoundsViscosity: Number = 0.0
  11275. // If `maxBounds` is set, this option will control how solid the bounds
  11276. // are when dragging the map around. The default value of `0.0` allows the
  11277. // user to drag outside the bounds at normal speed, higher values will
  11278. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  11279. // solid, preventing the user from dragging outside the bounds.
  11280. maxBoundsViscosity: 0.0
  11281. });
  11282. var Drag = Handler.extend({
  11283. addHooks: function () {
  11284. if (!this._draggable) {
  11285. var map = this._map;
  11286. this._draggable = new Draggable(map._mapPane, map._container);
  11287. this._draggable.on({
  11288. dragstart: this._onDragStart,
  11289. drag: this._onDrag,
  11290. dragend: this._onDragEnd
  11291. }, this);
  11292. this._draggable.on('predrag', this._onPreDragLimit, this);
  11293. if (map.options.worldCopyJump) {
  11294. this._draggable.on('predrag', this._onPreDragWrap, this);
  11295. map.on('zoomend', this._onZoomEnd, this);
  11296. map.whenReady(this._onZoomEnd, this);
  11297. }
  11298. }
  11299. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  11300. this._draggable.enable();
  11301. this._positions = [];
  11302. this._times = [];
  11303. },
  11304. removeHooks: function () {
  11305. removeClass(this._map._container, 'leaflet-grab');
  11306. removeClass(this._map._container, 'leaflet-touch-drag');
  11307. this._draggable.disable();
  11308. },
  11309. moved: function () {
  11310. return this._draggable && this._draggable._moved;
  11311. },
  11312. moving: function () {
  11313. return this._draggable && this._draggable._moving;
  11314. },
  11315. _onDragStart: function () {
  11316. var map = this._map;
  11317. map._stop();
  11318. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  11319. var bounds = toLatLngBounds(this._map.options.maxBounds);
  11320. this._offsetLimit = toBounds(
  11321. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  11322. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  11323. .add(this._map.getSize()));
  11324. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  11325. } else {
  11326. this._offsetLimit = null;
  11327. }
  11328. map
  11329. .fire('movestart')
  11330. .fire('dragstart');
  11331. if (map.options.inertia) {
  11332. this._positions = [];
  11333. this._times = [];
  11334. }
  11335. },
  11336. _onDrag: function (e) {
  11337. if (this._map.options.inertia) {
  11338. var time = this._lastTime = +new Date(),
  11339. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  11340. this._positions.push(pos);
  11341. this._times.push(time);
  11342. this._prunePositions(time);
  11343. }
  11344. this._map
  11345. .fire('move', e)
  11346. .fire('drag', e);
  11347. },
  11348. _prunePositions: function (time) {
  11349. while (this._positions.length > 1 && time - this._times[0] > 50) {
  11350. this._positions.shift();
  11351. this._times.shift();
  11352. }
  11353. },
  11354. _onZoomEnd: function () {
  11355. var pxCenter = this._map.getSize().divideBy(2),
  11356. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  11357. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  11358. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  11359. },
  11360. _viscousLimit: function (value, threshold) {
  11361. return value - (value - threshold) * this._viscosity;
  11362. },
  11363. _onPreDragLimit: function () {
  11364. if (!this._viscosity || !this._offsetLimit) { return; }
  11365. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  11366. var limit = this._offsetLimit;
  11367. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  11368. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  11369. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  11370. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  11371. this._draggable._newPos = this._draggable._startPos.add(offset);
  11372. },
  11373. _onPreDragWrap: function () {
  11374. // TODO refactor to be able to adjust map pane position after zoom
  11375. var worldWidth = this._worldWidth,
  11376. halfWidth = Math.round(worldWidth / 2),
  11377. dx = this._initialWorldOffset,
  11378. x = this._draggable._newPos.x,
  11379. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  11380. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  11381. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  11382. this._draggable._absPos = this._draggable._newPos.clone();
  11383. this._draggable._newPos.x = newX;
  11384. },
  11385. _onDragEnd: function (e) {
  11386. var map = this._map,
  11387. options = map.options,
  11388. noInertia = !options.inertia || e.noInertia || this._times.length < 2;
  11389. map.fire('dragend', e);
  11390. if (noInertia) {
  11391. map.fire('moveend');
  11392. } else {
  11393. this._prunePositions(+new Date());
  11394. var direction = this._lastPos.subtract(this._positions[0]),
  11395. duration = (this._lastTime - this._times[0]) / 1000,
  11396. ease = options.easeLinearity,
  11397. speedVector = direction.multiplyBy(ease / duration),
  11398. speed = speedVector.distanceTo([0, 0]),
  11399. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  11400. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  11401. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  11402. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  11403. if (!offset.x && !offset.y) {
  11404. map.fire('moveend');
  11405. } else {
  11406. offset = map._limitOffset(offset, map.options.maxBounds);
  11407. requestAnimFrame(function () {
  11408. map.panBy(offset, {
  11409. duration: decelerationDuration,
  11410. easeLinearity: ease,
  11411. noMoveStart: true,
  11412. animate: true
  11413. });
  11414. });
  11415. }
  11416. }
  11417. }
  11418. });
  11419. // @section Handlers
  11420. // @property dragging: Handler
  11421. // Map dragging handler (by both mouse and touch).
  11422. Map.addInitHook('addHandler', 'dragging', Drag);
  11423. /*
  11424. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  11425. */
  11426. // @namespace Map
  11427. // @section Keyboard Navigation Options
  11428. Map.mergeOptions({
  11429. // @option keyboard: Boolean = true
  11430. // Makes the map focusable and allows users to navigate the map with keyboard
  11431. // arrows and `+`/`-` keys.
  11432. keyboard: true,
  11433. // @option keyboardPanDelta: Number = 80
  11434. // Amount of pixels to pan when pressing an arrow key.
  11435. keyboardPanDelta: 80
  11436. });
  11437. var Keyboard = Handler.extend({
  11438. keyCodes: {
  11439. left: [37],
  11440. right: [39],
  11441. down: [40],
  11442. up: [38],
  11443. zoomIn: [187, 107, 61, 171],
  11444. zoomOut: [189, 109, 54, 173]
  11445. },
  11446. initialize: function (map) {
  11447. this._map = map;
  11448. this._setPanDelta(map.options.keyboardPanDelta);
  11449. this._setZoomDelta(map.options.zoomDelta);
  11450. },
  11451. addHooks: function () {
  11452. var container = this._map._container;
  11453. // make the container focusable by tabbing
  11454. if (container.tabIndex <= 0) {
  11455. container.tabIndex = '0';
  11456. }
  11457. on(container, {
  11458. focus: this._onFocus,
  11459. blur: this._onBlur,
  11460. mousedown: this._onMouseDown
  11461. }, this);
  11462. this._map.on({
  11463. focus: this._addHooks,
  11464. blur: this._removeHooks
  11465. }, this);
  11466. },
  11467. removeHooks: function () {
  11468. this._removeHooks();
  11469. off(this._map._container, {
  11470. focus: this._onFocus,
  11471. blur: this._onBlur,
  11472. mousedown: this._onMouseDown
  11473. }, this);
  11474. this._map.off({
  11475. focus: this._addHooks,
  11476. blur: this._removeHooks
  11477. }, this);
  11478. },
  11479. _onMouseDown: function () {
  11480. if (this._focused) { return; }
  11481. var body = document.body,
  11482. docEl = document.documentElement,
  11483. top = body.scrollTop || docEl.scrollTop,
  11484. left = body.scrollLeft || docEl.scrollLeft;
  11485. this._map._container.focus();
  11486. window.scrollTo(left, top);
  11487. },
  11488. _onFocus: function () {
  11489. this._focused = true;
  11490. this._map.fire('focus');
  11491. },
  11492. _onBlur: function () {
  11493. this._focused = false;
  11494. this._map.fire('blur');
  11495. },
  11496. _setPanDelta: function (panDelta) {
  11497. var keys = this._panKeys = {},
  11498. codes = this.keyCodes,
  11499. i, len;
  11500. for (i = 0, len = codes.left.length; i < len; i++) {
  11501. keys[codes.left[i]] = [-1 * panDelta, 0];
  11502. }
  11503. for (i = 0, len = codes.right.length; i < len; i++) {
  11504. keys[codes.right[i]] = [panDelta, 0];
  11505. }
  11506. for (i = 0, len = codes.down.length; i < len; i++) {
  11507. keys[codes.down[i]] = [0, panDelta];
  11508. }
  11509. for (i = 0, len = codes.up.length; i < len; i++) {
  11510. keys[codes.up[i]] = [0, -1 * panDelta];
  11511. }
  11512. },
  11513. _setZoomDelta: function (zoomDelta) {
  11514. var keys = this._zoomKeys = {},
  11515. codes = this.keyCodes,
  11516. i, len;
  11517. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  11518. keys[codes.zoomIn[i]] = zoomDelta;
  11519. }
  11520. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  11521. keys[codes.zoomOut[i]] = -zoomDelta;
  11522. }
  11523. },
  11524. _addHooks: function () {
  11525. on(document, 'keydown', this._onKeyDown, this);
  11526. },
  11527. _removeHooks: function () {
  11528. off(document, 'keydown', this._onKeyDown, this);
  11529. },
  11530. _onKeyDown: function (e) {
  11531. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  11532. var key = e.keyCode,
  11533. map = this._map,
  11534. offset;
  11535. if (key in this._panKeys) {
  11536. if (!map._panAnim || !map._panAnim._inProgress) {
  11537. offset = this._panKeys[key];
  11538. if (e.shiftKey) {
  11539. offset = toPoint(offset).multiplyBy(3);
  11540. }
  11541. if (map.options.maxBounds) {
  11542. offset = map._limitOffset(toPoint(offset), map.options.maxBounds);
  11543. }
  11544. if (map.options.worldCopyJump) {
  11545. var newLatLng = map.wrapLatLng(map.unproject(map.project(map.getCenter()).add(offset)));
  11546. map.panTo(newLatLng);
  11547. } else {
  11548. map.panBy(offset);
  11549. }
  11550. }
  11551. } else if (key in this._zoomKeys) {
  11552. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  11553. } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
  11554. map.closePopup();
  11555. } else {
  11556. return;
  11557. }
  11558. stop(e);
  11559. }
  11560. });
  11561. // @section Handlers
  11562. // @section Handlers
  11563. // @property keyboard: Handler
  11564. // Keyboard navigation handler.
  11565. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  11566. /*
  11567. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  11568. */
  11569. // @namespace Map
  11570. // @section Interaction Options
  11571. Map.mergeOptions({
  11572. // @section Mouse wheel options
  11573. // @option scrollWheelZoom: Boolean|String = true
  11574. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  11575. // it will zoom to the center of the view regardless of where the mouse was.
  11576. scrollWheelZoom: true,
  11577. // @option wheelDebounceTime: Number = 40
  11578. // Limits the rate at which a wheel can fire (in milliseconds). By default
  11579. // user can't zoom via wheel more often than once per 40 ms.
  11580. wheelDebounceTime: 40,
  11581. // @option wheelPxPerZoomLevel: Number = 60
  11582. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  11583. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  11584. // faster (and vice versa).
  11585. wheelPxPerZoomLevel: 60
  11586. });
  11587. var ScrollWheelZoom = Handler.extend({
  11588. addHooks: function () {
  11589. on(this._map._container, 'wheel', this._onWheelScroll, this);
  11590. this._delta = 0;
  11591. },
  11592. removeHooks: function () {
  11593. off(this._map._container, 'wheel', this._onWheelScroll, this);
  11594. },
  11595. _onWheelScroll: function (e) {
  11596. var delta = getWheelDelta(e);
  11597. var debounce = this._map.options.wheelDebounceTime;
  11598. this._delta += delta;
  11599. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  11600. if (!this._startTime) {
  11601. this._startTime = +new Date();
  11602. }
  11603. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  11604. clearTimeout(this._timer);
  11605. this._timer = setTimeout(bind(this._performZoom, this), left);
  11606. stop(e);
  11607. },
  11608. _performZoom: function () {
  11609. var map = this._map,
  11610. zoom = map.getZoom(),
  11611. snap = this._map.options.zoomSnap || 0;
  11612. map._stop(); // stop panning and fly animations if any
  11613. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  11614. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  11615. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  11616. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  11617. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  11618. this._delta = 0;
  11619. this._startTime = null;
  11620. if (!delta) { return; }
  11621. if (map.options.scrollWheelZoom === 'center') {
  11622. map.setZoom(zoom + delta);
  11623. } else {
  11624. map.setZoomAround(this._lastMousePos, zoom + delta);
  11625. }
  11626. }
  11627. });
  11628. // @section Handlers
  11629. // @property scrollWheelZoom: Handler
  11630. // Scroll wheel zoom handler.
  11631. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  11632. /*
  11633. * L.Map.TapHold is used to simulate `contextmenu` event on long hold,
  11634. * which otherwise is not fired by mobile Safari.
  11635. */
  11636. var tapHoldDelay = 600;
  11637. // @namespace Map
  11638. // @section Interaction Options
  11639. Map.mergeOptions({
  11640. // @section Touch interaction options
  11641. // @option tapHold: Boolean
  11642. // Enables simulation of `contextmenu` event, default is `true` for mobile Safari.
  11643. tapHold: Browser.touchNative && Browser.safari && Browser.mobile,
  11644. // @option tapTolerance: Number = 15
  11645. // The max number of pixels a user can shift his finger during touch
  11646. // for it to be considered a valid tap.
  11647. tapTolerance: 15
  11648. });
  11649. var TapHold = Handler.extend({
  11650. addHooks: function () {
  11651. on(this._map._container, 'touchstart', this._onDown, this);
  11652. },
  11653. removeHooks: function () {
  11654. off(this._map._container, 'touchstart', this._onDown, this);
  11655. },
  11656. _onDown: function (e) {
  11657. clearTimeout(this._holdTimeout);
  11658. if (e.touches.length !== 1) { return; }
  11659. var first = e.touches[0];
  11660. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  11661. this._holdTimeout = setTimeout(bind(function () {
  11662. this._cancel();
  11663. if (!this._isTapValid()) { return; }
  11664. // prevent simulated mouse events https://w3c.github.io/touch-events/#mouse-events
  11665. on(document, 'touchend', preventDefault);
  11666. on(document, 'touchend touchcancel', this._cancelClickPrevent);
  11667. this._simulateEvent('contextmenu', first);
  11668. }, this), tapHoldDelay);
  11669. on(document, 'touchend touchcancel contextmenu', this._cancel, this);
  11670. on(document, 'touchmove', this._onMove, this);
  11671. },
  11672. _cancelClickPrevent: function cancelClickPrevent() {
  11673. off(document, 'touchend', preventDefault);
  11674. off(document, 'touchend touchcancel', cancelClickPrevent);
  11675. },
  11676. _cancel: function () {
  11677. clearTimeout(this._holdTimeout);
  11678. off(document, 'touchend touchcancel contextmenu', this._cancel, this);
  11679. off(document, 'touchmove', this._onMove, this);
  11680. },
  11681. _onMove: function (e) {
  11682. var first = e.touches[0];
  11683. this._newPos = new Point(first.clientX, first.clientY);
  11684. },
  11685. _isTapValid: function () {
  11686. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11687. },
  11688. _simulateEvent: function (type, e) {
  11689. var simulatedEvent = new MouseEvent(type, {
  11690. bubbles: true,
  11691. cancelable: true,
  11692. view: window,
  11693. // detail: 1,
  11694. screenX: e.screenX,
  11695. screenY: e.screenY,
  11696. clientX: e.clientX,
  11697. clientY: e.clientY,
  11698. // button: 2,
  11699. // buttons: 2
  11700. });
  11701. simulatedEvent._simulated = true;
  11702. e.target.dispatchEvent(simulatedEvent);
  11703. }
  11704. });
  11705. // @section Handlers
  11706. // @property tapHold: Handler
  11707. // Long tap handler to simulate `contextmenu` event (useful in mobile Safari).
  11708. Map.addInitHook('addHandler', 'tapHold', TapHold);
  11709. /*
  11710. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11711. */
  11712. // @namespace Map
  11713. // @section Interaction Options
  11714. Map.mergeOptions({
  11715. // @section Touch interaction options
  11716. // @option touchZoom: Boolean|String = *
  11717. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11718. // passed `'center'`, it will zoom to the center of the view regardless of
  11719. // where the touch events (fingers) were. Enabled for touch-capable web
  11720. // browsers.
  11721. touchZoom: Browser.touch,
  11722. // @option bounceAtZoomLimits: Boolean = true
  11723. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11724. // and then bounce back when pinch-zooming.
  11725. bounceAtZoomLimits: true
  11726. });
  11727. var TouchZoom = Handler.extend({
  11728. addHooks: function () {
  11729. addClass(this._map._container, 'leaflet-touch-zoom');
  11730. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11731. },
  11732. removeHooks: function () {
  11733. removeClass(this._map._container, 'leaflet-touch-zoom');
  11734. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11735. },
  11736. _onTouchStart: function (e) {
  11737. var map = this._map;
  11738. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  11739. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11740. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11741. this._centerPoint = map.getSize()._divideBy(2);
  11742. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11743. if (map.options.touchZoom !== 'center') {
  11744. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11745. }
  11746. this._startDist = p1.distanceTo(p2);
  11747. this._startZoom = map.getZoom();
  11748. this._moved = false;
  11749. this._zooming = true;
  11750. map._stop();
  11751. on(document, 'touchmove', this._onTouchMove, this);
  11752. on(document, 'touchend touchcancel', this._onTouchEnd, this);
  11753. preventDefault(e);
  11754. },
  11755. _onTouchMove: function (e) {
  11756. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  11757. var map = this._map,
  11758. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11759. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11760. scale = p1.distanceTo(p2) / this._startDist;
  11761. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11762. if (!map.options.bounceAtZoomLimits && (
  11763. (this._zoom < map.getMinZoom() && scale < 1) ||
  11764. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11765. this._zoom = map._limitZoom(this._zoom);
  11766. }
  11767. if (map.options.touchZoom === 'center') {
  11768. this._center = this._startLatLng;
  11769. if (scale === 1) { return; }
  11770. } else {
  11771. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11772. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11773. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  11774. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11775. }
  11776. if (!this._moved) {
  11777. map._moveStart(true, false);
  11778. this._moved = true;
  11779. }
  11780. cancelAnimFrame(this._animRequest);
  11781. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false}, undefined);
  11782. this._animRequest = requestAnimFrame(moveFn, this, true);
  11783. preventDefault(e);
  11784. },
  11785. _onTouchEnd: function () {
  11786. if (!this._moved || !this._zooming) {
  11787. this._zooming = false;
  11788. return;
  11789. }
  11790. this._zooming = false;
  11791. cancelAnimFrame(this._animRequest);
  11792. off(document, 'touchmove', this._onTouchMove, this);
  11793. off(document, 'touchend touchcancel', this._onTouchEnd, this);
  11794. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11795. if (this._map.options.zoomAnimation) {
  11796. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11797. } else {
  11798. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11799. }
  11800. }
  11801. });
  11802. // @section Handlers
  11803. // @property touchZoom: Handler
  11804. // Touch zoom handler.
  11805. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11806. Map.BoxZoom = BoxZoom;
  11807. Map.DoubleClickZoom = DoubleClickZoom;
  11808. Map.Drag = Drag;
  11809. Map.Keyboard = Keyboard;
  11810. Map.ScrollWheelZoom = ScrollWheelZoom;
  11811. Map.TapHold = TapHold;
  11812. Map.TouchZoom = TouchZoom;
  11813. exports.Bounds = Bounds;
  11814. exports.Browser = Browser;
  11815. exports.CRS = CRS;
  11816. exports.Canvas = Canvas;
  11817. exports.Circle = Circle;
  11818. exports.CircleMarker = CircleMarker;
  11819. exports.Class = Class;
  11820. exports.Control = Control;
  11821. exports.DivIcon = DivIcon;
  11822. exports.DivOverlay = DivOverlay;
  11823. exports.DomEvent = DomEvent;
  11824. exports.DomUtil = DomUtil;
  11825. exports.Draggable = Draggable;
  11826. exports.Evented = Evented;
  11827. exports.FeatureGroup = FeatureGroup;
  11828. exports.GeoJSON = GeoJSON;
  11829. exports.GridLayer = GridLayer;
  11830. exports.Handler = Handler;
  11831. exports.Icon = Icon;
  11832. exports.ImageOverlay = ImageOverlay;
  11833. exports.LatLng = LatLng;
  11834. exports.LatLngBounds = LatLngBounds;
  11835. exports.Layer = Layer;
  11836. exports.LayerGroup = LayerGroup;
  11837. exports.LineUtil = LineUtil;
  11838. exports.Map = Map;
  11839. exports.Marker = Marker;
  11840. exports.Mixin = Mixin;
  11841. exports.Path = Path;
  11842. exports.Point = Point;
  11843. exports.PolyUtil = PolyUtil;
  11844. exports.Polygon = Polygon;
  11845. exports.Polyline = Polyline;
  11846. exports.Popup = Popup;
  11847. exports.PosAnimation = PosAnimation;
  11848. exports.Projection = index;
  11849. exports.Rectangle = Rectangle;
  11850. exports.Renderer = Renderer;
  11851. exports.SVG = SVG;
  11852. exports.SVGOverlay = SVGOverlay;
  11853. exports.TileLayer = TileLayer;
  11854. exports.Tooltip = Tooltip;
  11855. exports.Transformation = Transformation;
  11856. exports.Util = Util;
  11857. exports.VideoOverlay = VideoOverlay;
  11858. exports.bind = bind;
  11859. exports.bounds = toBounds;
  11860. exports.canvas = canvas;
  11861. exports.circle = circle;
  11862. exports.circleMarker = circleMarker;
  11863. exports.control = control;
  11864. exports.divIcon = divIcon;
  11865. exports.extend = extend;
  11866. exports.featureGroup = featureGroup;
  11867. exports.geoJSON = geoJSON;
  11868. exports.geoJson = geoJson;
  11869. exports.gridLayer = gridLayer;
  11870. exports.icon = icon;
  11871. exports.imageOverlay = imageOverlay;
  11872. exports.latLng = toLatLng;
  11873. exports.latLngBounds = toLatLngBounds;
  11874. exports.layerGroup = layerGroup;
  11875. exports.map = createMap;
  11876. exports.marker = marker;
  11877. exports.point = toPoint;
  11878. exports.polygon = polygon;
  11879. exports.polyline = polyline;
  11880. exports.popup = popup;
  11881. exports.rectangle = rectangle;
  11882. exports.setOptions = setOptions;
  11883. exports.stamp = stamp;
  11884. exports.svg = svg;
  11885. exports.svgOverlay = svgOverlay;
  11886. exports.tileLayer = tileLayer;
  11887. exports.tooltip = tooltip;
  11888. exports.transformation = toTransformation;
  11889. exports.version = version;
  11890. exports.videoOverlay = videoOverlay;
  11891. var oldL = window.L;
  11892. exports.noConflict = function() {
  11893. window.L = oldL;
  11894. return this;
  11895. }
  11896. // Always export us to window global (see #2364)
  11897. window.L = exports;
  11898. }));
  11899. //# sourceMappingURL=leaflet-src.js.map