leaflet-src.esm.js 406 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420
  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. var version = "1.9.4";
  6. /*
  7. * @namespace Util
  8. *
  9. * Various utility functions, used by Leaflet internally.
  10. */
  11. // @function extend(dest: Object, src?: Object): Object
  12. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  13. function extend(dest) {
  14. var i, j, len, src;
  15. for (j = 1, len = arguments.length; j < len; j++) {
  16. src = arguments[j];
  17. for (i in src) {
  18. dest[i] = src[i];
  19. }
  20. }
  21. return dest;
  22. }
  23. // @function create(proto: Object, properties?: Object): Object
  24. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  25. var create$2 = Object.create || (function () {
  26. function F() {}
  27. return function (proto) {
  28. F.prototype = proto;
  29. return new F();
  30. };
  31. })();
  32. // @function bind(fn: Function, …): Function
  33. // 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).
  34. // Has a `L.bind()` shortcut.
  35. function bind(fn, obj) {
  36. var slice = Array.prototype.slice;
  37. if (fn.bind) {
  38. return fn.bind.apply(fn, slice.call(arguments, 1));
  39. }
  40. var args = slice.call(arguments, 2);
  41. return function () {
  42. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  43. };
  44. }
  45. // @property lastId: Number
  46. // Last unique ID used by [`stamp()`](#util-stamp)
  47. var lastId = 0;
  48. // @function stamp(obj: Object): Number
  49. // Returns the unique ID of an object, assigning it one if it doesn't have it.
  50. function stamp(obj) {
  51. if (!('_leaflet_id' in obj)) {
  52. obj['_leaflet_id'] = ++lastId;
  53. }
  54. return obj._leaflet_id;
  55. }
  56. // @function throttle(fn: Function, time: Number, context: Object): Function
  57. // Returns a function which executes function `fn` with the given scope `context`
  58. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  59. // `fn` will be called no more than one time per given amount of `time`. The arguments
  60. // received by the bound function will be any arguments passed when binding the
  61. // function, followed by any arguments passed when invoking the bound function.
  62. // Has an `L.throttle` shortcut.
  63. function throttle(fn, time, context) {
  64. var lock, args, wrapperFn, later;
  65. later = function () {
  66. // reset lock and call if queued
  67. lock = false;
  68. if (args) {
  69. wrapperFn.apply(context, args);
  70. args = false;
  71. }
  72. };
  73. wrapperFn = function () {
  74. if (lock) {
  75. // called too soon, queue to call later
  76. args = arguments;
  77. } else {
  78. // call and lock until later
  79. fn.apply(context, arguments);
  80. setTimeout(later, time);
  81. lock = true;
  82. }
  83. };
  84. return wrapperFn;
  85. }
  86. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  87. // Returns the number `num` modulo `range` in such a way so it lies within
  88. // `range[0]` and `range[1]`. The returned value will be always smaller than
  89. // `range[1]` unless `includeMax` is set to `true`.
  90. function wrapNum(x, range, includeMax) {
  91. var max = range[1],
  92. min = range[0],
  93. d = max - min;
  94. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  95. }
  96. // @function falseFn(): Function
  97. // Returns a function which always returns `false`.
  98. function falseFn() { return false; }
  99. // @function formatNum(num: Number, precision?: Number|false): Number
  100. // Returns the number `num` rounded with specified `precision`.
  101. // The default `precision` value is 6 decimal places.
  102. // `false` can be passed to skip any processing (can be useful to avoid round-off errors).
  103. function formatNum(num, precision) {
  104. if (precision === false) { return num; }
  105. var pow = Math.pow(10, precision === undefined ? 6 : precision);
  106. return Math.round(num * pow) / pow;
  107. }
  108. // @function trim(str: String): String
  109. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  110. function trim(str) {
  111. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  112. }
  113. // @function splitWords(str: String): String[]
  114. // Trims and splits the string on whitespace and returns the array of parts.
  115. function splitWords(str) {
  116. return trim(str).split(/\s+/);
  117. }
  118. // @function setOptions(obj: Object, options: Object): Object
  119. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  120. function setOptions(obj, options) {
  121. if (!Object.prototype.hasOwnProperty.call(obj, 'options')) {
  122. obj.options = obj.options ? create$2(obj.options) : {};
  123. }
  124. for (var i in options) {
  125. obj.options[i] = options[i];
  126. }
  127. return obj.options;
  128. }
  129. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  130. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  131. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  132. // be appended at the end. If `uppercase` is `true`, the parameter names will
  133. // be uppercased (e.g. `'?A=foo&B=bar'`)
  134. function getParamString(obj, existingUrl, uppercase) {
  135. var params = [];
  136. for (var i in obj) {
  137. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  138. }
  139. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  140. }
  141. var templateRe = /\{ *([\w_ -]+) *\}/g;
  142. // @function template(str: String, data: Object): String
  143. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  144. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  145. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  146. // data values — they will be evaluated passing `data` as an argument.
  147. function template(str, data) {
  148. return str.replace(templateRe, function (str, key) {
  149. var value = data[key];
  150. if (value === undefined) {
  151. throw new Error('No value provided for variable ' + str);
  152. } else if (typeof value === 'function') {
  153. value = value(data);
  154. }
  155. return value;
  156. });
  157. }
  158. // @function isArray(obj): Boolean
  159. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  160. var isArray = Array.isArray || function (obj) {
  161. return (Object.prototype.toString.call(obj) === '[object Array]');
  162. };
  163. // @function indexOf(array: Array, el: Object): Number
  164. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  165. function indexOf(array, el) {
  166. for (var i = 0; i < array.length; i++) {
  167. if (array[i] === el) { return i; }
  168. }
  169. return -1;
  170. }
  171. // @property emptyImageUrl: String
  172. // Data URI string containing a base64-encoded empty GIF image.
  173. // Used as a hack to free memory from unused images on WebKit-powered
  174. // mobile devices (by setting image `src` to this string).
  175. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  176. // inspired by https://paulirish.com/2011/requestanimationframe-for-smart-animating/
  177. function getPrefixed(name) {
  178. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  179. }
  180. var lastTime = 0;
  181. // fallback for IE 7-8
  182. function timeoutDefer(fn) {
  183. var time = +new Date(),
  184. timeToCall = Math.max(0, 16 - (time - lastTime));
  185. lastTime = time + timeToCall;
  186. return window.setTimeout(fn, timeToCall);
  187. }
  188. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  189. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  190. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  191. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  192. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  193. // `context` if given. When `immediate` is set, `fn` is called immediately if
  194. // the browser doesn't have native support for
  195. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  196. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  197. function requestAnimFrame(fn, context, immediate) {
  198. if (immediate && requestFn === timeoutDefer) {
  199. fn.call(context);
  200. } else {
  201. return requestFn.call(window, bind(fn, context));
  202. }
  203. }
  204. // @function cancelAnimFrame(id: Number): undefined
  205. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  206. function cancelAnimFrame(id) {
  207. if (id) {
  208. cancelFn.call(window, id);
  209. }
  210. }
  211. var Util = {
  212. __proto__: null,
  213. extend: extend,
  214. create: create$2,
  215. bind: bind,
  216. get lastId () { return lastId; },
  217. stamp: stamp,
  218. throttle: throttle,
  219. wrapNum: wrapNum,
  220. falseFn: falseFn,
  221. formatNum: formatNum,
  222. trim: trim,
  223. splitWords: splitWords,
  224. setOptions: setOptions,
  225. getParamString: getParamString,
  226. template: template,
  227. isArray: isArray,
  228. indexOf: indexOf,
  229. emptyImageUrl: emptyImageUrl,
  230. requestFn: requestFn,
  231. cancelFn: cancelFn,
  232. requestAnimFrame: requestAnimFrame,
  233. cancelAnimFrame: cancelAnimFrame
  234. };
  235. // @class Class
  236. // @aka L.Class
  237. // @section
  238. // @uninheritable
  239. // Thanks to John Resig and Dean Edwards for inspiration!
  240. function Class() {}
  241. Class.extend = function (props) {
  242. // @function extend(props: Object): Function
  243. // [Extends the current class](#class-inheritance) given the properties to be included.
  244. // Returns a Javascript function that is a class constructor (to be called with `new`).
  245. var NewClass = function () {
  246. setOptions(this);
  247. // call the constructor
  248. if (this.initialize) {
  249. this.initialize.apply(this, arguments);
  250. }
  251. // call all constructor hooks
  252. this.callInitHooks();
  253. };
  254. var parentProto = NewClass.__super__ = this.prototype;
  255. var proto = create$2(parentProto);
  256. proto.constructor = NewClass;
  257. NewClass.prototype = proto;
  258. // inherit parent's statics
  259. for (var i in this) {
  260. if (Object.prototype.hasOwnProperty.call(this, i) && i !== 'prototype' && i !== '__super__') {
  261. NewClass[i] = this[i];
  262. }
  263. }
  264. // mix static properties into the class
  265. if (props.statics) {
  266. extend(NewClass, props.statics);
  267. }
  268. // mix includes into the prototype
  269. if (props.includes) {
  270. checkDeprecatedMixinEvents(props.includes);
  271. extend.apply(null, [proto].concat(props.includes));
  272. }
  273. // mix given properties into the prototype
  274. extend(proto, props);
  275. delete proto.statics;
  276. delete proto.includes;
  277. // merge options
  278. if (proto.options) {
  279. proto.options = parentProto.options ? create$2(parentProto.options) : {};
  280. extend(proto.options, props.options);
  281. }
  282. proto._initHooks = [];
  283. // add method for calling all hooks
  284. proto.callInitHooks = function () {
  285. if (this._initHooksCalled) { return; }
  286. if (parentProto.callInitHooks) {
  287. parentProto.callInitHooks.call(this);
  288. }
  289. this._initHooksCalled = true;
  290. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  291. proto._initHooks[i].call(this);
  292. }
  293. };
  294. return NewClass;
  295. };
  296. // @function include(properties: Object): this
  297. // [Includes a mixin](#class-includes) into the current class.
  298. Class.include = function (props) {
  299. var parentOptions = this.prototype.options;
  300. extend(this.prototype, props);
  301. if (props.options) {
  302. this.prototype.options = parentOptions;
  303. this.mergeOptions(props.options);
  304. }
  305. return this;
  306. };
  307. // @function mergeOptions(options: Object): this
  308. // [Merges `options`](#class-options) into the defaults of the class.
  309. Class.mergeOptions = function (options) {
  310. extend(this.prototype.options, options);
  311. return this;
  312. };
  313. // @function addInitHook(fn: Function): this
  314. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  315. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  316. var args = Array.prototype.slice.call(arguments, 1);
  317. var init = typeof fn === 'function' ? fn : function () {
  318. this[fn].apply(this, args);
  319. };
  320. this.prototype._initHooks = this.prototype._initHooks || [];
  321. this.prototype._initHooks.push(init);
  322. return this;
  323. };
  324. function checkDeprecatedMixinEvents(includes) {
  325. /* global L: true */
  326. if (typeof L === 'undefined' || !L || !L.Mixin) { return; }
  327. includes = isArray(includes) ? includes : [includes];
  328. for (var i = 0; i < includes.length; i++) {
  329. if (includes[i] === L.Mixin.Events) {
  330. console.warn('Deprecated include of L.Mixin.Events: ' +
  331. 'this property will be removed in future releases, ' +
  332. 'please inherit from L.Evented instead.', new Error().stack);
  333. }
  334. }
  335. }
  336. /*
  337. * @class Evented
  338. * @aka L.Evented
  339. * @inherits Class
  340. *
  341. * 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).
  342. *
  343. * @example
  344. *
  345. * ```js
  346. * map.on('click', function(e) {
  347. * alert(e.latlng);
  348. * } );
  349. * ```
  350. *
  351. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  352. *
  353. * ```js
  354. * function onClick(e) { ... }
  355. *
  356. * map.on('click', onClick);
  357. * map.off('click', onClick);
  358. * ```
  359. */
  360. var Events = {
  361. /* @method on(type: String, fn: Function, context?: Object): this
  362. * 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'`).
  363. *
  364. * @alternative
  365. * @method on(eventMap: Object): this
  366. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  367. */
  368. on: function (types, fn, context) {
  369. // types can be a map of types/handlers
  370. if (typeof types === 'object') {
  371. for (var type in types) {
  372. // we don't process space-separated events here for performance;
  373. // it's a hot path since Layer uses the on(obj) syntax
  374. this._on(type, types[type], fn);
  375. }
  376. } else {
  377. // types can be a string of space-separated words
  378. types = splitWords(types);
  379. for (var i = 0, len = types.length; i < len; i++) {
  380. this._on(types[i], fn, context);
  381. }
  382. }
  383. return this;
  384. },
  385. /* @method off(type: String, fn?: Function, context?: Object): this
  386. * 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.
  387. *
  388. * @alternative
  389. * @method off(eventMap: Object): this
  390. * Removes a set of type/listener pairs.
  391. *
  392. * @alternative
  393. * @method off: this
  394. * Removes all listeners to all events on the object. This includes implicitly attached events.
  395. */
  396. off: function (types, fn, context) {
  397. if (!arguments.length) {
  398. // clear all listeners if called without arguments
  399. delete this._events;
  400. } else if (typeof types === 'object') {
  401. for (var type in types) {
  402. this._off(type, types[type], fn);
  403. }
  404. } else {
  405. types = splitWords(types);
  406. var removeAll = arguments.length === 1;
  407. for (var i = 0, len = types.length; i < len; i++) {
  408. if (removeAll) {
  409. this._off(types[i]);
  410. } else {
  411. this._off(types[i], fn, context);
  412. }
  413. }
  414. }
  415. return this;
  416. },
  417. // attach listener (without syntactic sugar now)
  418. _on: function (type, fn, context, _once) {
  419. if (typeof fn !== 'function') {
  420. console.warn('wrong listener type: ' + typeof fn);
  421. return;
  422. }
  423. // check if fn already there
  424. if (this._listens(type, fn, context) !== false) {
  425. return;
  426. }
  427. if (context === this) {
  428. // Less memory footprint.
  429. context = undefined;
  430. }
  431. var newListener = {fn: fn, ctx: context};
  432. if (_once) {
  433. newListener.once = true;
  434. }
  435. this._events = this._events || {};
  436. this._events[type] = this._events[type] || [];
  437. this._events[type].push(newListener);
  438. },
  439. _off: function (type, fn, context) {
  440. var listeners,
  441. i,
  442. len;
  443. if (!this._events) {
  444. return;
  445. }
  446. listeners = this._events[type];
  447. if (!listeners) {
  448. return;
  449. }
  450. if (arguments.length === 1) { // remove all
  451. if (this._firingCount) {
  452. // Set all removed listeners to noop
  453. // so they are not called if remove happens in fire
  454. for (i = 0, len = listeners.length; i < len; i++) {
  455. listeners[i].fn = falseFn;
  456. }
  457. }
  458. // clear all listeners for a type if function isn't specified
  459. delete this._events[type];
  460. return;
  461. }
  462. if (typeof fn !== 'function') {
  463. console.warn('wrong listener type: ' + typeof fn);
  464. return;
  465. }
  466. // find fn and remove it
  467. var index = this._listens(type, fn, context);
  468. if (index !== false) {
  469. var listener = listeners[index];
  470. if (this._firingCount) {
  471. // set the removed listener to noop so that's not called if remove happens in fire
  472. listener.fn = falseFn;
  473. /* copy array in case events are being fired */
  474. this._events[type] = listeners = listeners.slice();
  475. }
  476. listeners.splice(index, 1);
  477. }
  478. },
  479. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  480. // Fires an event of the specified type. You can optionally provide a data
  481. // object — the first argument of the listener function will contain its
  482. // properties. The event can optionally be propagated to event parents.
  483. fire: function (type, data, propagate) {
  484. if (!this.listens(type, propagate)) { return this; }
  485. var event = extend({}, data, {
  486. type: type,
  487. target: this,
  488. sourceTarget: data && data.sourceTarget || this
  489. });
  490. if (this._events) {
  491. var listeners = this._events[type];
  492. if (listeners) {
  493. this._firingCount = (this._firingCount + 1) || 1;
  494. for (var i = 0, len = listeners.length; i < len; i++) {
  495. var l = listeners[i];
  496. // off overwrites l.fn, so we need to copy fn to a var
  497. var fn = l.fn;
  498. if (l.once) {
  499. this.off(type, fn, l.ctx);
  500. }
  501. fn.call(l.ctx || this, event);
  502. }
  503. this._firingCount--;
  504. }
  505. }
  506. if (propagate) {
  507. // propagate the event to parents (set with addEventParent)
  508. this._propagateEvent(event);
  509. }
  510. return this;
  511. },
  512. // @method listens(type: String, propagate?: Boolean): Boolean
  513. // @method listens(type: String, fn: Function, context?: Object, propagate?: Boolean): Boolean
  514. // Returns `true` if a particular event type has any listeners attached to it.
  515. // The verification can optionally be propagated, it will return `true` if parents have the listener attached to it.
  516. listens: function (type, fn, context, propagate) {
  517. if (typeof type !== 'string') {
  518. console.warn('"string" type argument expected');
  519. }
  520. // we don't overwrite the input `fn` value, because we need to use it for propagation
  521. var _fn = fn;
  522. if (typeof fn !== 'function') {
  523. propagate = !!fn;
  524. _fn = undefined;
  525. context = undefined;
  526. }
  527. var listeners = this._events && this._events[type];
  528. if (listeners && listeners.length) {
  529. if (this._listens(type, _fn, context) !== false) {
  530. return true;
  531. }
  532. }
  533. if (propagate) {
  534. // also check parents for listeners if event propagates
  535. for (var id in this._eventParents) {
  536. if (this._eventParents[id].listens(type, fn, context, propagate)) { return true; }
  537. }
  538. }
  539. return false;
  540. },
  541. // returns the index (number) or false
  542. _listens: function (type, fn, context) {
  543. if (!this._events) {
  544. return false;
  545. }
  546. var listeners = this._events[type] || [];
  547. if (!fn) {
  548. return !!listeners.length;
  549. }
  550. if (context === this) {
  551. // Less memory footprint.
  552. context = undefined;
  553. }
  554. for (var i = 0, len = listeners.length; i < len; i++) {
  555. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  556. return i;
  557. }
  558. }
  559. return false;
  560. },
  561. // @method once(…): this
  562. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  563. once: function (types, fn, context) {
  564. // types can be a map of types/handlers
  565. if (typeof types === 'object') {
  566. for (var type in types) {
  567. // we don't process space-separated events here for performance;
  568. // it's a hot path since Layer uses the on(obj) syntax
  569. this._on(type, types[type], fn, true);
  570. }
  571. } else {
  572. // types can be a string of space-separated words
  573. types = splitWords(types);
  574. for (var i = 0, len = types.length; i < len; i++) {
  575. this._on(types[i], fn, context, true);
  576. }
  577. }
  578. return this;
  579. },
  580. // @method addEventParent(obj: Evented): this
  581. // Adds an event parent - an `Evented` that will receive propagated events
  582. addEventParent: function (obj) {
  583. this._eventParents = this._eventParents || {};
  584. this._eventParents[stamp(obj)] = obj;
  585. return this;
  586. },
  587. // @method removeEventParent(obj: Evented): this
  588. // Removes an event parent, so it will stop receiving propagated events
  589. removeEventParent: function (obj) {
  590. if (this._eventParents) {
  591. delete this._eventParents[stamp(obj)];
  592. }
  593. return this;
  594. },
  595. _propagateEvent: function (e) {
  596. for (var id in this._eventParents) {
  597. this._eventParents[id].fire(e.type, extend({
  598. layer: e.target,
  599. propagatedFrom: e.target
  600. }, e), true);
  601. }
  602. }
  603. };
  604. // aliases; we should ditch those eventually
  605. // @method addEventListener(…): this
  606. // Alias to [`on(…)`](#evented-on)
  607. Events.addEventListener = Events.on;
  608. // @method removeEventListener(…): this
  609. // Alias to [`off(…)`](#evented-off)
  610. // @method clearAllEventListeners(…): this
  611. // Alias to [`off()`](#evented-off)
  612. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  613. // @method addOneTimeEventListener(…): this
  614. // Alias to [`once(…)`](#evented-once)
  615. Events.addOneTimeEventListener = Events.once;
  616. // @method fireEvent(…): this
  617. // Alias to [`fire(…)`](#evented-fire)
  618. Events.fireEvent = Events.fire;
  619. // @method hasEventListeners(…): Boolean
  620. // Alias to [`listens(…)`](#evented-listens)
  621. Events.hasEventListeners = Events.listens;
  622. var Evented = Class.extend(Events);
  623. /*
  624. * @class Point
  625. * @aka L.Point
  626. *
  627. * Represents a point with `x` and `y` coordinates in pixels.
  628. *
  629. * @example
  630. *
  631. * ```js
  632. * var point = L.point(200, 300);
  633. * ```
  634. *
  635. * 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:
  636. *
  637. * ```js
  638. * map.panBy([200, 300]);
  639. * map.panBy(L.point(200, 300));
  640. * ```
  641. *
  642. * Note that `Point` does not inherit from Leaflet's `Class` object,
  643. * which means new classes can't inherit from it, and new methods
  644. * can't be added to it with the `include` function.
  645. */
  646. function Point(x, y, round) {
  647. // @property x: Number; The `x` coordinate of the point
  648. this.x = (round ? Math.round(x) : x);
  649. // @property y: Number; The `y` coordinate of the point
  650. this.y = (round ? Math.round(y) : y);
  651. }
  652. var trunc = Math.trunc || function (v) {
  653. return v > 0 ? Math.floor(v) : Math.ceil(v);
  654. };
  655. Point.prototype = {
  656. // @method clone(): Point
  657. // Returns a copy of the current point.
  658. clone: function () {
  659. return new Point(this.x, this.y);
  660. },
  661. // @method add(otherPoint: Point): Point
  662. // Returns the result of addition of the current and the given points.
  663. add: function (point) {
  664. // non-destructive, returns a new point
  665. return this.clone()._add(toPoint(point));
  666. },
  667. _add: function (point) {
  668. // destructive, used directly for performance in situations where it's safe to modify existing point
  669. this.x += point.x;
  670. this.y += point.y;
  671. return this;
  672. },
  673. // @method subtract(otherPoint: Point): Point
  674. // Returns the result of subtraction of the given point from the current.
  675. subtract: function (point) {
  676. return this.clone()._subtract(toPoint(point));
  677. },
  678. _subtract: function (point) {
  679. this.x -= point.x;
  680. this.y -= point.y;
  681. return this;
  682. },
  683. // @method divideBy(num: Number): Point
  684. // Returns the result of division of the current point by the given number.
  685. divideBy: function (num) {
  686. return this.clone()._divideBy(num);
  687. },
  688. _divideBy: function (num) {
  689. this.x /= num;
  690. this.y /= num;
  691. return this;
  692. },
  693. // @method multiplyBy(num: Number): Point
  694. // Returns the result of multiplication of the current point by the given number.
  695. multiplyBy: function (num) {
  696. return this.clone()._multiplyBy(num);
  697. },
  698. _multiplyBy: function (num) {
  699. this.x *= num;
  700. this.y *= num;
  701. return this;
  702. },
  703. // @method scaleBy(scale: Point): Point
  704. // Multiply each coordinate of the current point by each coordinate of
  705. // `scale`. In linear algebra terms, multiply the point by the
  706. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  707. // defined by `scale`.
  708. scaleBy: function (point) {
  709. return new Point(this.x * point.x, this.y * point.y);
  710. },
  711. // @method unscaleBy(scale: Point): Point
  712. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  713. // each coordinate of `scale`.
  714. unscaleBy: function (point) {
  715. return new Point(this.x / point.x, this.y / point.y);
  716. },
  717. // @method round(): Point
  718. // Returns a copy of the current point with rounded coordinates.
  719. round: function () {
  720. return this.clone()._round();
  721. },
  722. _round: function () {
  723. this.x = Math.round(this.x);
  724. this.y = Math.round(this.y);
  725. return this;
  726. },
  727. // @method floor(): Point
  728. // Returns a copy of the current point with floored coordinates (rounded down).
  729. floor: function () {
  730. return this.clone()._floor();
  731. },
  732. _floor: function () {
  733. this.x = Math.floor(this.x);
  734. this.y = Math.floor(this.y);
  735. return this;
  736. },
  737. // @method ceil(): Point
  738. // Returns a copy of the current point with ceiled coordinates (rounded up).
  739. ceil: function () {
  740. return this.clone()._ceil();
  741. },
  742. _ceil: function () {
  743. this.x = Math.ceil(this.x);
  744. this.y = Math.ceil(this.y);
  745. return this;
  746. },
  747. // @method trunc(): Point
  748. // Returns a copy of the current point with truncated coordinates (rounded towards zero).
  749. trunc: function () {
  750. return this.clone()._trunc();
  751. },
  752. _trunc: function () {
  753. this.x = trunc(this.x);
  754. this.y = trunc(this.y);
  755. return this;
  756. },
  757. // @method distanceTo(otherPoint: Point): Number
  758. // Returns the cartesian distance between the current and the given points.
  759. distanceTo: function (point) {
  760. point = toPoint(point);
  761. var x = point.x - this.x,
  762. y = point.y - this.y;
  763. return Math.sqrt(x * x + y * y);
  764. },
  765. // @method equals(otherPoint: Point): Boolean
  766. // Returns `true` if the given point has the same coordinates.
  767. equals: function (point) {
  768. point = toPoint(point);
  769. return point.x === this.x &&
  770. point.y === this.y;
  771. },
  772. // @method contains(otherPoint: Point): Boolean
  773. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  774. contains: function (point) {
  775. point = toPoint(point);
  776. return Math.abs(point.x) <= Math.abs(this.x) &&
  777. Math.abs(point.y) <= Math.abs(this.y);
  778. },
  779. // @method toString(): String
  780. // Returns a string representation of the point for debugging purposes.
  781. toString: function () {
  782. return 'Point(' +
  783. formatNum(this.x) + ', ' +
  784. formatNum(this.y) + ')';
  785. }
  786. };
  787. // @factory L.point(x: Number, y: Number, round?: Boolean)
  788. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  789. // @alternative
  790. // @factory L.point(coords: Number[])
  791. // Expects an array of the form `[x, y]` instead.
  792. // @alternative
  793. // @factory L.point(coords: Object)
  794. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  795. function toPoint(x, y, round) {
  796. if (x instanceof Point) {
  797. return x;
  798. }
  799. if (isArray(x)) {
  800. return new Point(x[0], x[1]);
  801. }
  802. if (x === undefined || x === null) {
  803. return x;
  804. }
  805. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  806. return new Point(x.x, x.y);
  807. }
  808. return new Point(x, y, round);
  809. }
  810. /*
  811. * @class Bounds
  812. * @aka L.Bounds
  813. *
  814. * Represents a rectangular area in pixel coordinates.
  815. *
  816. * @example
  817. *
  818. * ```js
  819. * var p1 = L.point(10, 10),
  820. * p2 = L.point(40, 60),
  821. * bounds = L.bounds(p1, p2);
  822. * ```
  823. *
  824. * 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:
  825. *
  826. * ```js
  827. * otherBounds.intersects([[10, 10], [40, 60]]);
  828. * ```
  829. *
  830. * Note that `Bounds` does not inherit from Leaflet's `Class` object,
  831. * which means new classes can't inherit from it, and new methods
  832. * can't be added to it with the `include` function.
  833. */
  834. function Bounds(a, b) {
  835. if (!a) { return; }
  836. var points = b ? [a, b] : a;
  837. for (var i = 0, len = points.length; i < len; i++) {
  838. this.extend(points[i]);
  839. }
  840. }
  841. Bounds.prototype = {
  842. // @method extend(point: Point): this
  843. // Extends the bounds to contain the given point.
  844. // @alternative
  845. // @method extend(otherBounds: Bounds): this
  846. // Extend the bounds to contain the given bounds
  847. extend: function (obj) {
  848. var min2, max2;
  849. if (!obj) { return this; }
  850. if (obj instanceof Point || typeof obj[0] === 'number' || 'x' in obj) {
  851. min2 = max2 = toPoint(obj);
  852. } else {
  853. obj = toBounds(obj);
  854. min2 = obj.min;
  855. max2 = obj.max;
  856. if (!min2 || !max2) { return this; }
  857. }
  858. // @property min: Point
  859. // The top left corner of the rectangle.
  860. // @property max: Point
  861. // The bottom right corner of the rectangle.
  862. if (!this.min && !this.max) {
  863. this.min = min2.clone();
  864. this.max = max2.clone();
  865. } else {
  866. this.min.x = Math.min(min2.x, this.min.x);
  867. this.max.x = Math.max(max2.x, this.max.x);
  868. this.min.y = Math.min(min2.y, this.min.y);
  869. this.max.y = Math.max(max2.y, this.max.y);
  870. }
  871. return this;
  872. },
  873. // @method getCenter(round?: Boolean): Point
  874. // Returns the center point of the bounds.
  875. getCenter: function (round) {
  876. return toPoint(
  877. (this.min.x + this.max.x) / 2,
  878. (this.min.y + this.max.y) / 2, round);
  879. },
  880. // @method getBottomLeft(): Point
  881. // Returns the bottom-left point of the bounds.
  882. getBottomLeft: function () {
  883. return toPoint(this.min.x, this.max.y);
  884. },
  885. // @method getTopRight(): Point
  886. // Returns the top-right point of the bounds.
  887. getTopRight: function () { // -> Point
  888. return toPoint(this.max.x, this.min.y);
  889. },
  890. // @method getTopLeft(): Point
  891. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  892. getTopLeft: function () {
  893. return this.min; // left, top
  894. },
  895. // @method getBottomRight(): Point
  896. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  897. getBottomRight: function () {
  898. return this.max; // right, bottom
  899. },
  900. // @method getSize(): Point
  901. // Returns the size of the given bounds
  902. getSize: function () {
  903. return this.max.subtract(this.min);
  904. },
  905. // @method contains(otherBounds: Bounds): Boolean
  906. // Returns `true` if the rectangle contains the given one.
  907. // @alternative
  908. // @method contains(point: Point): Boolean
  909. // Returns `true` if the rectangle contains the given point.
  910. contains: function (obj) {
  911. var min, max;
  912. if (typeof obj[0] === 'number' || obj instanceof Point) {
  913. obj = toPoint(obj);
  914. } else {
  915. obj = toBounds(obj);
  916. }
  917. if (obj instanceof Bounds) {
  918. min = obj.min;
  919. max = obj.max;
  920. } else {
  921. min = max = obj;
  922. }
  923. return (min.x >= this.min.x) &&
  924. (max.x <= this.max.x) &&
  925. (min.y >= this.min.y) &&
  926. (max.y <= this.max.y);
  927. },
  928. // @method intersects(otherBounds: Bounds): Boolean
  929. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  930. // intersect if they have at least one point in common.
  931. intersects: function (bounds) { // (Bounds) -> Boolean
  932. bounds = toBounds(bounds);
  933. var min = this.min,
  934. max = this.max,
  935. min2 = bounds.min,
  936. max2 = bounds.max,
  937. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  938. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  939. return xIntersects && yIntersects;
  940. },
  941. // @method overlaps(otherBounds: Bounds): Boolean
  942. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  943. // overlap if their intersection is an area.
  944. overlaps: function (bounds) { // (Bounds) -> Boolean
  945. bounds = toBounds(bounds);
  946. var min = this.min,
  947. max = this.max,
  948. min2 = bounds.min,
  949. max2 = bounds.max,
  950. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  951. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  952. return xOverlaps && yOverlaps;
  953. },
  954. // @method isValid(): Boolean
  955. // Returns `true` if the bounds are properly initialized.
  956. isValid: function () {
  957. return !!(this.min && this.max);
  958. },
  959. // @method pad(bufferRatio: Number): Bounds
  960. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  961. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  962. // Negative values will retract the bounds.
  963. pad: function (bufferRatio) {
  964. var min = this.min,
  965. max = this.max,
  966. heightBuffer = Math.abs(min.x - max.x) * bufferRatio,
  967. widthBuffer = Math.abs(min.y - max.y) * bufferRatio;
  968. return toBounds(
  969. toPoint(min.x - heightBuffer, min.y - widthBuffer),
  970. toPoint(max.x + heightBuffer, max.y + widthBuffer));
  971. },
  972. // @method equals(otherBounds: Bounds): Boolean
  973. // Returns `true` if the rectangle is equivalent to the given bounds.
  974. equals: function (bounds) {
  975. if (!bounds) { return false; }
  976. bounds = toBounds(bounds);
  977. return this.min.equals(bounds.getTopLeft()) &&
  978. this.max.equals(bounds.getBottomRight());
  979. },
  980. };
  981. // @factory L.bounds(corner1: Point, corner2: Point)
  982. // Creates a Bounds object from two corners coordinate pairs.
  983. // @alternative
  984. // @factory L.bounds(points: Point[])
  985. // Creates a Bounds object from the given array of points.
  986. function toBounds(a, b) {
  987. if (!a || a instanceof Bounds) {
  988. return a;
  989. }
  990. return new Bounds(a, b);
  991. }
  992. /*
  993. * @class LatLngBounds
  994. * @aka L.LatLngBounds
  995. *
  996. * Represents a rectangular geographical area on a map.
  997. *
  998. * @example
  999. *
  1000. * ```js
  1001. * var corner1 = L.latLng(40.712, -74.227),
  1002. * corner2 = L.latLng(40.774, -74.125),
  1003. * bounds = L.latLngBounds(corner1, corner2);
  1004. * ```
  1005. *
  1006. * 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:
  1007. *
  1008. * ```js
  1009. * map.fitBounds([
  1010. * [40.712, -74.227],
  1011. * [40.774, -74.125]
  1012. * ]);
  1013. * ```
  1014. *
  1015. * 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.
  1016. *
  1017. * Note that `LatLngBounds` does not inherit from Leaflet's `Class` object,
  1018. * which means new classes can't inherit from it, and new methods
  1019. * can't be added to it with the `include` function.
  1020. */
  1021. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  1022. if (!corner1) { return; }
  1023. var latlngs = corner2 ? [corner1, corner2] : corner1;
  1024. for (var i = 0, len = latlngs.length; i < len; i++) {
  1025. this.extend(latlngs[i]);
  1026. }
  1027. }
  1028. LatLngBounds.prototype = {
  1029. // @method extend(latlng: LatLng): this
  1030. // Extend the bounds to contain the given point
  1031. // @alternative
  1032. // @method extend(otherBounds: LatLngBounds): this
  1033. // Extend the bounds to contain the given bounds
  1034. extend: function (obj) {
  1035. var sw = this._southWest,
  1036. ne = this._northEast,
  1037. sw2, ne2;
  1038. if (obj instanceof LatLng) {
  1039. sw2 = obj;
  1040. ne2 = obj;
  1041. } else if (obj instanceof LatLngBounds) {
  1042. sw2 = obj._southWest;
  1043. ne2 = obj._northEast;
  1044. if (!sw2 || !ne2) { return this; }
  1045. } else {
  1046. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  1047. }
  1048. if (!sw && !ne) {
  1049. this._southWest = new LatLng(sw2.lat, sw2.lng);
  1050. this._northEast = new LatLng(ne2.lat, ne2.lng);
  1051. } else {
  1052. sw.lat = Math.min(sw2.lat, sw.lat);
  1053. sw.lng = Math.min(sw2.lng, sw.lng);
  1054. ne.lat = Math.max(ne2.lat, ne.lat);
  1055. ne.lng = Math.max(ne2.lng, ne.lng);
  1056. }
  1057. return this;
  1058. },
  1059. // @method pad(bufferRatio: Number): LatLngBounds
  1060. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  1061. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  1062. // Negative values will retract the bounds.
  1063. pad: function (bufferRatio) {
  1064. var sw = this._southWest,
  1065. ne = this._northEast,
  1066. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  1067. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  1068. return new LatLngBounds(
  1069. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  1070. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  1071. },
  1072. // @method getCenter(): LatLng
  1073. // Returns the center point of the bounds.
  1074. getCenter: function () {
  1075. return new LatLng(
  1076. (this._southWest.lat + this._northEast.lat) / 2,
  1077. (this._southWest.lng + this._northEast.lng) / 2);
  1078. },
  1079. // @method getSouthWest(): LatLng
  1080. // Returns the south-west point of the bounds.
  1081. getSouthWest: function () {
  1082. return this._southWest;
  1083. },
  1084. // @method getNorthEast(): LatLng
  1085. // Returns the north-east point of the bounds.
  1086. getNorthEast: function () {
  1087. return this._northEast;
  1088. },
  1089. // @method getNorthWest(): LatLng
  1090. // Returns the north-west point of the bounds.
  1091. getNorthWest: function () {
  1092. return new LatLng(this.getNorth(), this.getWest());
  1093. },
  1094. // @method getSouthEast(): LatLng
  1095. // Returns the south-east point of the bounds.
  1096. getSouthEast: function () {
  1097. return new LatLng(this.getSouth(), this.getEast());
  1098. },
  1099. // @method getWest(): Number
  1100. // Returns the west longitude of the bounds
  1101. getWest: function () {
  1102. return this._southWest.lng;
  1103. },
  1104. // @method getSouth(): Number
  1105. // Returns the south latitude of the bounds
  1106. getSouth: function () {
  1107. return this._southWest.lat;
  1108. },
  1109. // @method getEast(): Number
  1110. // Returns the east longitude of the bounds
  1111. getEast: function () {
  1112. return this._northEast.lng;
  1113. },
  1114. // @method getNorth(): Number
  1115. // Returns the north latitude of the bounds
  1116. getNorth: function () {
  1117. return this._northEast.lat;
  1118. },
  1119. // @method contains(otherBounds: LatLngBounds): Boolean
  1120. // Returns `true` if the rectangle contains the given one.
  1121. // @alternative
  1122. // @method contains (latlng: LatLng): Boolean
  1123. // Returns `true` if the rectangle contains the given point.
  1124. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1125. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1126. obj = toLatLng(obj);
  1127. } else {
  1128. obj = toLatLngBounds(obj);
  1129. }
  1130. var sw = this._southWest,
  1131. ne = this._northEast,
  1132. sw2, ne2;
  1133. if (obj instanceof LatLngBounds) {
  1134. sw2 = obj.getSouthWest();
  1135. ne2 = obj.getNorthEast();
  1136. } else {
  1137. sw2 = ne2 = obj;
  1138. }
  1139. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1140. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1141. },
  1142. // @method intersects(otherBounds: LatLngBounds): Boolean
  1143. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1144. intersects: function (bounds) {
  1145. bounds = toLatLngBounds(bounds);
  1146. var sw = this._southWest,
  1147. ne = this._northEast,
  1148. sw2 = bounds.getSouthWest(),
  1149. ne2 = bounds.getNorthEast(),
  1150. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1151. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1152. return latIntersects && lngIntersects;
  1153. },
  1154. // @method overlaps(otherBounds: LatLngBounds): Boolean
  1155. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1156. overlaps: function (bounds) {
  1157. bounds = toLatLngBounds(bounds);
  1158. var sw = this._southWest,
  1159. ne = this._northEast,
  1160. sw2 = bounds.getSouthWest(),
  1161. ne2 = bounds.getNorthEast(),
  1162. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1163. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1164. return latOverlaps && lngOverlaps;
  1165. },
  1166. // @method toBBoxString(): String
  1167. // 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.
  1168. toBBoxString: function () {
  1169. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1170. },
  1171. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1172. // 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.
  1173. equals: function (bounds, maxMargin) {
  1174. if (!bounds) { return false; }
  1175. bounds = toLatLngBounds(bounds);
  1176. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1177. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1178. },
  1179. // @method isValid(): Boolean
  1180. // Returns `true` if the bounds are properly initialized.
  1181. isValid: function () {
  1182. return !!(this._southWest && this._northEast);
  1183. }
  1184. };
  1185. // TODO International date line?
  1186. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1187. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1188. // @alternative
  1189. // @factory L.latLngBounds(latlngs: LatLng[])
  1190. // 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).
  1191. function toLatLngBounds(a, b) {
  1192. if (a instanceof LatLngBounds) {
  1193. return a;
  1194. }
  1195. return new LatLngBounds(a, b);
  1196. }
  1197. /* @class LatLng
  1198. * @aka L.LatLng
  1199. *
  1200. * Represents a geographical point with a certain latitude and longitude.
  1201. *
  1202. * @example
  1203. *
  1204. * ```
  1205. * var latlng = L.latLng(50.5, 30.5);
  1206. * ```
  1207. *
  1208. * 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:
  1209. *
  1210. * ```
  1211. * map.panTo([50, 30]);
  1212. * map.panTo({lon: 30, lat: 50});
  1213. * map.panTo({lat: 50, lng: 30});
  1214. * map.panTo(L.latLng(50, 30));
  1215. * ```
  1216. *
  1217. * Note that `LatLng` does not inherit from Leaflet's `Class` object,
  1218. * which means new classes can't inherit from it, and new methods
  1219. * can't be added to it with the `include` function.
  1220. */
  1221. function LatLng(lat, lng, alt) {
  1222. if (isNaN(lat) || isNaN(lng)) {
  1223. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1224. }
  1225. // @property lat: Number
  1226. // Latitude in degrees
  1227. this.lat = +lat;
  1228. // @property lng: Number
  1229. // Longitude in degrees
  1230. this.lng = +lng;
  1231. // @property alt: Number
  1232. // Altitude in meters (optional)
  1233. if (alt !== undefined) {
  1234. this.alt = +alt;
  1235. }
  1236. }
  1237. LatLng.prototype = {
  1238. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1239. // 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.
  1240. equals: function (obj, maxMargin) {
  1241. if (!obj) { return false; }
  1242. obj = toLatLng(obj);
  1243. var margin = Math.max(
  1244. Math.abs(this.lat - obj.lat),
  1245. Math.abs(this.lng - obj.lng));
  1246. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1247. },
  1248. // @method toString(): String
  1249. // Returns a string representation of the point (for debugging purposes).
  1250. toString: function (precision) {
  1251. return 'LatLng(' +
  1252. formatNum(this.lat, precision) + ', ' +
  1253. formatNum(this.lng, precision) + ')';
  1254. },
  1255. // @method distanceTo(otherLatLng: LatLng): Number
  1256. // 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).
  1257. distanceTo: function (other) {
  1258. return Earth.distance(this, toLatLng(other));
  1259. },
  1260. // @method wrap(): LatLng
  1261. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1262. wrap: function () {
  1263. return Earth.wrapLatLng(this);
  1264. },
  1265. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1266. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1267. toBounds: function (sizeInMeters) {
  1268. var latAccuracy = 180 * sizeInMeters / 40075017,
  1269. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1270. return toLatLngBounds(
  1271. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1272. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1273. },
  1274. clone: function () {
  1275. return new LatLng(this.lat, this.lng, this.alt);
  1276. }
  1277. };
  1278. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1279. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1280. // @alternative
  1281. // @factory L.latLng(coords: Array): LatLng
  1282. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1283. // @alternative
  1284. // @factory L.latLng(coords: Object): LatLng
  1285. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1286. function toLatLng(a, b, c) {
  1287. if (a instanceof LatLng) {
  1288. return a;
  1289. }
  1290. if (isArray(a) && typeof a[0] !== 'object') {
  1291. if (a.length === 3) {
  1292. return new LatLng(a[0], a[1], a[2]);
  1293. }
  1294. if (a.length === 2) {
  1295. return new LatLng(a[0], a[1]);
  1296. }
  1297. return null;
  1298. }
  1299. if (a === undefined || a === null) {
  1300. return a;
  1301. }
  1302. if (typeof a === 'object' && 'lat' in a) {
  1303. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1304. }
  1305. if (b === undefined) {
  1306. return null;
  1307. }
  1308. return new LatLng(a, b, c);
  1309. }
  1310. /*
  1311. * @namespace CRS
  1312. * @crs L.CRS.Base
  1313. * Object that defines coordinate reference systems for projecting
  1314. * geographical points into pixel (screen) coordinates and back (and to
  1315. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1316. * [spatial reference system](https://en.wikipedia.org/wiki/Spatial_reference_system).
  1317. *
  1318. * Leaflet defines the most usual CRSs by default. If you want to use a
  1319. * CRS not defined by default, take a look at the
  1320. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1321. *
  1322. * Note that the CRS instances do not inherit from Leaflet's `Class` object,
  1323. * and can't be instantiated. Also, new classes can't inherit from them,
  1324. * and methods can't be added to them with the `include` function.
  1325. */
  1326. var CRS = {
  1327. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1328. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1329. latLngToPoint: function (latlng, zoom) {
  1330. var projectedPoint = this.projection.project(latlng),
  1331. scale = this.scale(zoom);
  1332. return this.transformation._transform(projectedPoint, scale);
  1333. },
  1334. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1335. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1336. // zoom into geographical coordinates.
  1337. pointToLatLng: function (point, zoom) {
  1338. var scale = this.scale(zoom),
  1339. untransformedPoint = this.transformation.untransform(point, scale);
  1340. return this.projection.unproject(untransformedPoint);
  1341. },
  1342. // @method project(latlng: LatLng): Point
  1343. // Projects geographical coordinates into coordinates in units accepted for
  1344. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1345. project: function (latlng) {
  1346. return this.projection.project(latlng);
  1347. },
  1348. // @method unproject(point: Point): LatLng
  1349. // Given a projected coordinate returns the corresponding LatLng.
  1350. // The inverse of `project`.
  1351. unproject: function (point) {
  1352. return this.projection.unproject(point);
  1353. },
  1354. // @method scale(zoom: Number): Number
  1355. // Returns the scale used when transforming projected coordinates into
  1356. // pixel coordinates for a particular zoom. For example, it returns
  1357. // `256 * 2^zoom` for Mercator-based CRS.
  1358. scale: function (zoom) {
  1359. return 256 * Math.pow(2, zoom);
  1360. },
  1361. // @method zoom(scale: Number): Number
  1362. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1363. // factor of `scale`.
  1364. zoom: function (scale) {
  1365. return Math.log(scale / 256) / Math.LN2;
  1366. },
  1367. // @method getProjectedBounds(zoom: Number): Bounds
  1368. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1369. getProjectedBounds: function (zoom) {
  1370. if (this.infinite) { return null; }
  1371. var b = this.projection.bounds,
  1372. s = this.scale(zoom),
  1373. min = this.transformation.transform(b.min, s),
  1374. max = this.transformation.transform(b.max, s);
  1375. return new Bounds(min, max);
  1376. },
  1377. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1378. // Returns the distance between two geographical coordinates.
  1379. // @property code: String
  1380. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1381. //
  1382. // @property wrapLng: Number[]
  1383. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1384. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1385. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1386. //
  1387. // @property wrapLat: Number[]
  1388. // Like `wrapLng`, but for the latitude (vertical) axis.
  1389. // wrapLng: [min, max],
  1390. // wrapLat: [min, max],
  1391. // @property infinite: Boolean
  1392. // If true, the coordinate space will be unbounded (infinite in both axes)
  1393. infinite: false,
  1394. // @method wrapLatLng(latlng: LatLng): LatLng
  1395. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1396. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1397. wrapLatLng: function (latlng) {
  1398. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1399. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1400. alt = latlng.alt;
  1401. return new LatLng(lat, lng, alt);
  1402. },
  1403. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1404. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1405. // that its center is within the CRS's bounds.
  1406. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1407. wrapLatLngBounds: function (bounds) {
  1408. var center = bounds.getCenter(),
  1409. newCenter = this.wrapLatLng(center),
  1410. latShift = center.lat - newCenter.lat,
  1411. lngShift = center.lng - newCenter.lng;
  1412. if (latShift === 0 && lngShift === 0) {
  1413. return bounds;
  1414. }
  1415. var sw = bounds.getSouthWest(),
  1416. ne = bounds.getNorthEast(),
  1417. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1418. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1419. return new LatLngBounds(newSw, newNe);
  1420. }
  1421. };
  1422. /*
  1423. * @namespace CRS
  1424. * @crs L.CRS.Earth
  1425. *
  1426. * Serves as the base for CRS that are global such that they cover the earth.
  1427. * Can only be used as the base for other CRS and cannot be used directly,
  1428. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1429. * meters.
  1430. */
  1431. var Earth = extend({}, CRS, {
  1432. wrapLng: [-180, 180],
  1433. // Mean Earth Radius, as recommended for use by
  1434. // the International Union of Geodesy and Geophysics,
  1435. // see https://rosettacode.org/wiki/Haversine_formula
  1436. R: 6371000,
  1437. // distance between two geographical points using spherical law of cosines approximation
  1438. distance: function (latlng1, latlng2) {
  1439. var rad = Math.PI / 180,
  1440. lat1 = latlng1.lat * rad,
  1441. lat2 = latlng2.lat * rad,
  1442. sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
  1443. sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
  1444. a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
  1445. c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1446. return this.R * c;
  1447. }
  1448. });
  1449. /*
  1450. * @namespace Projection
  1451. * @projection L.Projection.SphericalMercator
  1452. *
  1453. * Spherical Mercator projection — the most common projection for online maps,
  1454. * used by almost all free and commercial tile providers. Assumes that Earth is
  1455. * a sphere. Used by the `EPSG:3857` CRS.
  1456. */
  1457. var earthRadius = 6378137;
  1458. var SphericalMercator = {
  1459. R: earthRadius,
  1460. MAX_LATITUDE: 85.0511287798,
  1461. project: function (latlng) {
  1462. var d = Math.PI / 180,
  1463. max = this.MAX_LATITUDE,
  1464. lat = Math.max(Math.min(max, latlng.lat), -max),
  1465. sin = Math.sin(lat * d);
  1466. return new Point(
  1467. this.R * latlng.lng * d,
  1468. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1469. },
  1470. unproject: function (point) {
  1471. var d = 180 / Math.PI;
  1472. return new LatLng(
  1473. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1474. point.x * d / this.R);
  1475. },
  1476. bounds: (function () {
  1477. var d = earthRadius * Math.PI;
  1478. return new Bounds([-d, -d], [d, d]);
  1479. })()
  1480. };
  1481. /*
  1482. * @class Transformation
  1483. * @aka L.Transformation
  1484. *
  1485. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1486. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1487. * the reverse. Used by Leaflet in its projections code.
  1488. *
  1489. * @example
  1490. *
  1491. * ```js
  1492. * var transformation = L.transformation(2, 5, -1, 10),
  1493. * p = L.point(1, 2),
  1494. * p2 = transformation.transform(p), // L.point(7, 8)
  1495. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1496. * ```
  1497. */
  1498. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1499. // Creates a `Transformation` object with the given coefficients.
  1500. function Transformation(a, b, c, d) {
  1501. if (isArray(a)) {
  1502. // use array properties
  1503. this._a = a[0];
  1504. this._b = a[1];
  1505. this._c = a[2];
  1506. this._d = a[3];
  1507. return;
  1508. }
  1509. this._a = a;
  1510. this._b = b;
  1511. this._c = c;
  1512. this._d = d;
  1513. }
  1514. Transformation.prototype = {
  1515. // @method transform(point: Point, scale?: Number): Point
  1516. // Returns a transformed point, optionally multiplied by the given scale.
  1517. // Only accepts actual `L.Point` instances, not arrays.
  1518. transform: function (point, scale) { // (Point, Number) -> Point
  1519. return this._transform(point.clone(), scale);
  1520. },
  1521. // destructive transform (faster)
  1522. _transform: function (point, scale) {
  1523. scale = scale || 1;
  1524. point.x = scale * (this._a * point.x + this._b);
  1525. point.y = scale * (this._c * point.y + this._d);
  1526. return point;
  1527. },
  1528. // @method untransform(point: Point, scale?: Number): Point
  1529. // Returns the reverse transformation of the given point, optionally divided
  1530. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1531. untransform: function (point, scale) {
  1532. scale = scale || 1;
  1533. return new Point(
  1534. (point.x / scale - this._b) / this._a,
  1535. (point.y / scale - this._d) / this._c);
  1536. }
  1537. };
  1538. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1539. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1540. // Instantiates a Transformation object with the given coefficients.
  1541. // @alternative
  1542. // @factory L.transformation(coefficients: Array): Transformation
  1543. // Expects an coefficients array of the form
  1544. // `[a: Number, b: Number, c: Number, d: Number]`.
  1545. function toTransformation(a, b, c, d) {
  1546. return new Transformation(a, b, c, d);
  1547. }
  1548. /*
  1549. * @namespace CRS
  1550. * @crs L.CRS.EPSG3857
  1551. *
  1552. * The most common CRS for online maps, used by almost all free and commercial
  1553. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1554. * Map's `crs` option.
  1555. */
  1556. var EPSG3857 = extend({}, Earth, {
  1557. code: 'EPSG:3857',
  1558. projection: SphericalMercator,
  1559. transformation: (function () {
  1560. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1561. return toTransformation(scale, 0.5, -scale, 0.5);
  1562. }())
  1563. });
  1564. var EPSG900913 = extend({}, EPSG3857, {
  1565. code: 'EPSG:900913'
  1566. });
  1567. // @namespace SVG; @section
  1568. // There are several static functions which can be called without instantiating L.SVG:
  1569. // @function create(name: String): SVGElement
  1570. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1571. // corresponding to the class name passed. For example, using 'line' will return
  1572. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1573. function svgCreate(name) {
  1574. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1575. }
  1576. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1577. // Generates a SVG path string for multiple rings, with each ring turning
  1578. // into "M..L..L.." instructions
  1579. function pointsToPath(rings, closed) {
  1580. var str = '',
  1581. i, j, len, len2, points, p;
  1582. for (i = 0, len = rings.length; i < len; i++) {
  1583. points = rings[i];
  1584. for (j = 0, len2 = points.length; j < len2; j++) {
  1585. p = points[j];
  1586. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1587. }
  1588. // closes the ring for polygons; "x" is VML syntax
  1589. str += closed ? (Browser.svg ? 'z' : 'x') : '';
  1590. }
  1591. // SVG complains about empty path strings
  1592. return str || 'M0 0';
  1593. }
  1594. /*
  1595. * @namespace Browser
  1596. * @aka L.Browser
  1597. *
  1598. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1599. *
  1600. * @example
  1601. *
  1602. * ```js
  1603. * if (L.Browser.ielt9) {
  1604. * alert('Upgrade your browser, dude!');
  1605. * }
  1606. * ```
  1607. */
  1608. var style = document.documentElement.style;
  1609. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1610. var ie = 'ActiveXObject' in window;
  1611. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1612. var ielt9 = ie && !document.addEventListener;
  1613. // @property edge: Boolean; `true` for the Edge web browser.
  1614. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1615. // @property webkit: Boolean;
  1616. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1617. var webkit = userAgentContains('webkit');
  1618. // @property android: Boolean
  1619. // **Deprecated.** `true` for any browser running on an Android platform.
  1620. var android = userAgentContains('android');
  1621. // @property android23: Boolean; **Deprecated.** `true` for browsers running on Android 2 or Android 3.
  1622. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1623. /* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */
  1624. var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit
  1625. // @property androidStock: Boolean; **Deprecated.** `true` for the Android stock browser (i.e. not Chrome)
  1626. var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);
  1627. // @property opera: Boolean; `true` for the Opera browser
  1628. var opera = !!window.opera;
  1629. // @property chrome: Boolean; `true` for the Chrome browser.
  1630. var chrome = !edge && userAgentContains('chrome');
  1631. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1632. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1633. // @property safari: Boolean; `true` for the Safari browser.
  1634. var safari = !chrome && userAgentContains('safari');
  1635. var phantom = userAgentContains('phantom');
  1636. // @property opera12: Boolean
  1637. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1638. var opera12 = 'OTransition' in style;
  1639. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1640. var win = navigator.platform.indexOf('Win') === 0;
  1641. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1642. var ie3d = ie && ('transition' in style);
  1643. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1644. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1645. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1646. var gecko3d = 'MozPerspective' in style;
  1647. // @property any3d: Boolean
  1648. // `true` for all browsers supporting CSS transforms.
  1649. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1650. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1651. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1652. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1653. var mobileWebkit = mobile && webkit;
  1654. // @property mobileWebkit3d: Boolean
  1655. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1656. var mobileWebkit3d = mobile && webkit3d;
  1657. // @property msPointer: Boolean
  1658. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1659. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1660. // @property pointer: Boolean
  1661. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1662. var pointer = !!(window.PointerEvent || msPointer);
  1663. // @property touchNative: Boolean
  1664. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1665. // **This does not necessarily mean** that the browser is running in a computer with
  1666. // a touchscreen, it only means that the browser is capable of understanding
  1667. // touch events.
  1668. var touchNative = 'ontouchstart' in window || !!window.TouchEvent;
  1669. // @property touch: Boolean
  1670. // `true` for all browsers supporting either [touch](#browser-touch) or [pointer](#browser-pointer) events.
  1671. // Note: pointer events will be preferred (if available), and processed for all `touch*` listeners.
  1672. var touch = !window.L_NO_TOUCH && (touchNative || pointer);
  1673. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1674. var mobileOpera = mobile && opera;
  1675. // @property mobileGecko: Boolean
  1676. // `true` for gecko-based browsers running in a mobile device.
  1677. var mobileGecko = mobile && gecko;
  1678. // @property retina: Boolean
  1679. // `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%.
  1680. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1681. // @property passiveEvents: Boolean
  1682. // `true` for browsers that support passive events.
  1683. var passiveEvents = (function () {
  1684. var supportsPassiveOption = false;
  1685. try {
  1686. var opts = Object.defineProperty({}, 'passive', {
  1687. get: function () { // eslint-disable-line getter-return
  1688. supportsPassiveOption = true;
  1689. }
  1690. });
  1691. window.addEventListener('testPassiveEventSupport', falseFn, opts);
  1692. window.removeEventListener('testPassiveEventSupport', falseFn, opts);
  1693. } catch (e) {
  1694. // Errors can safely be ignored since this is only a browser support test.
  1695. }
  1696. return supportsPassiveOption;
  1697. }());
  1698. // @property canvas: Boolean
  1699. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1700. var canvas$1 = (function () {
  1701. return !!document.createElement('canvas').getContext;
  1702. }());
  1703. // @property svg: Boolean
  1704. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1705. var svg$1 = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1706. var inlineSvg = !!svg$1 && (function () {
  1707. var div = document.createElement('div');
  1708. div.innerHTML = '<svg/>';
  1709. return (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg';
  1710. })();
  1711. // @property vml: Boolean
  1712. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1713. var vml = !svg$1 && (function () {
  1714. try {
  1715. var div = document.createElement('div');
  1716. div.innerHTML = '<v:shape adj="1"/>';
  1717. var shape = div.firstChild;
  1718. shape.style.behavior = 'url(#default#VML)';
  1719. return shape && (typeof shape.adj === 'object');
  1720. } catch (e) {
  1721. return false;
  1722. }
  1723. }());
  1724. // @property mac: Boolean; `true` when the browser is running in a Mac platform
  1725. var mac = navigator.platform.indexOf('Mac') === 0;
  1726. // @property mac: Boolean; `true` when the browser is running in a Linux platform
  1727. var linux = navigator.platform.indexOf('Linux') === 0;
  1728. function userAgentContains(str) {
  1729. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1730. }
  1731. var Browser = {
  1732. ie: ie,
  1733. ielt9: ielt9,
  1734. edge: edge,
  1735. webkit: webkit,
  1736. android: android,
  1737. android23: android23,
  1738. androidStock: androidStock,
  1739. opera: opera,
  1740. chrome: chrome,
  1741. gecko: gecko,
  1742. safari: safari,
  1743. phantom: phantom,
  1744. opera12: opera12,
  1745. win: win,
  1746. ie3d: ie3d,
  1747. webkit3d: webkit3d,
  1748. gecko3d: gecko3d,
  1749. any3d: any3d,
  1750. mobile: mobile,
  1751. mobileWebkit: mobileWebkit,
  1752. mobileWebkit3d: mobileWebkit3d,
  1753. msPointer: msPointer,
  1754. pointer: pointer,
  1755. touch: touch,
  1756. touchNative: touchNative,
  1757. mobileOpera: mobileOpera,
  1758. mobileGecko: mobileGecko,
  1759. retina: retina,
  1760. passiveEvents: passiveEvents,
  1761. canvas: canvas$1,
  1762. svg: svg$1,
  1763. vml: vml,
  1764. inlineSvg: inlineSvg,
  1765. mac: mac,
  1766. linux: linux
  1767. };
  1768. /*
  1769. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1770. */
  1771. var POINTER_DOWN = Browser.msPointer ? 'MSPointerDown' : 'pointerdown';
  1772. var POINTER_MOVE = Browser.msPointer ? 'MSPointerMove' : 'pointermove';
  1773. var POINTER_UP = Browser.msPointer ? 'MSPointerUp' : 'pointerup';
  1774. var POINTER_CANCEL = Browser.msPointer ? 'MSPointerCancel' : 'pointercancel';
  1775. var pEvent = {
  1776. touchstart : POINTER_DOWN,
  1777. touchmove : POINTER_MOVE,
  1778. touchend : POINTER_UP,
  1779. touchcancel : POINTER_CANCEL
  1780. };
  1781. var handle = {
  1782. touchstart : _onPointerStart,
  1783. touchmove : _handlePointer,
  1784. touchend : _handlePointer,
  1785. touchcancel : _handlePointer
  1786. };
  1787. var _pointers = {};
  1788. var _pointerDocListener = false;
  1789. // Provides a touch events wrapper for (ms)pointer events.
  1790. // ref https://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1791. function addPointerListener(obj, type, handler) {
  1792. if (type === 'touchstart') {
  1793. _addPointerDocListener();
  1794. }
  1795. if (!handle[type]) {
  1796. console.warn('wrong event specified:', type);
  1797. return falseFn;
  1798. }
  1799. handler = handle[type].bind(this, handler);
  1800. obj.addEventListener(pEvent[type], handler, false);
  1801. return handler;
  1802. }
  1803. function removePointerListener(obj, type, handler) {
  1804. if (!pEvent[type]) {
  1805. console.warn('wrong event specified:', type);
  1806. return;
  1807. }
  1808. obj.removeEventListener(pEvent[type], handler, false);
  1809. }
  1810. function _globalPointerDown(e) {
  1811. _pointers[e.pointerId] = e;
  1812. }
  1813. function _globalPointerMove(e) {
  1814. if (_pointers[e.pointerId]) {
  1815. _pointers[e.pointerId] = e;
  1816. }
  1817. }
  1818. function _globalPointerUp(e) {
  1819. delete _pointers[e.pointerId];
  1820. }
  1821. function _addPointerDocListener() {
  1822. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1823. if (!_pointerDocListener) {
  1824. // we listen document as any drags that end by moving the touch off the screen get fired there
  1825. document.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1826. document.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1827. document.addEventListener(POINTER_UP, _globalPointerUp, true);
  1828. document.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1829. _pointerDocListener = true;
  1830. }
  1831. }
  1832. function _handlePointer(handler, e) {
  1833. if (e.pointerType === (e.MSPOINTER_TYPE_MOUSE || 'mouse')) { return; }
  1834. e.touches = [];
  1835. for (var i in _pointers) {
  1836. e.touches.push(_pointers[i]);
  1837. }
  1838. e.changedTouches = [e];
  1839. handler(e);
  1840. }
  1841. function _onPointerStart(handler, e) {
  1842. // IE10 specific: MsTouch needs preventDefault. See #2000
  1843. if (e.MSPOINTER_TYPE_TOUCH && e.pointerType === e.MSPOINTER_TYPE_TOUCH) {
  1844. preventDefault(e);
  1845. }
  1846. _handlePointer(handler, e);
  1847. }
  1848. /*
  1849. * Extends the event handling code with double tap support for mobile browsers.
  1850. *
  1851. * Note: currently most browsers fire native dblclick, with only a few exceptions
  1852. * (see https://github.com/Leaflet/Leaflet/issues/7012#issuecomment-595087386)
  1853. */
  1854. function makeDblclick(event) {
  1855. // in modern browsers `type` cannot be just overridden:
  1856. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only
  1857. var newEvent = {},
  1858. prop, i;
  1859. for (i in event) {
  1860. prop = event[i];
  1861. newEvent[i] = prop && prop.bind ? prop.bind(event) : prop;
  1862. }
  1863. event = newEvent;
  1864. newEvent.type = 'dblclick';
  1865. newEvent.detail = 2;
  1866. newEvent.isTrusted = false;
  1867. newEvent._simulated = true; // for debug purposes
  1868. return newEvent;
  1869. }
  1870. var delay = 200;
  1871. function addDoubleTapListener(obj, handler) {
  1872. // Most browsers handle double tap natively
  1873. obj.addEventListener('dblclick', handler);
  1874. // On some platforms the browser doesn't fire native dblclicks for touch events.
  1875. // It seems that in all such cases `detail` property of `click` event is always `1`.
  1876. // So here we rely on that fact to avoid excessive 'dblclick' simulation when not needed.
  1877. var last = 0,
  1878. detail;
  1879. function simDblclick(e) {
  1880. if (e.detail !== 1) {
  1881. detail = e.detail; // keep in sync to avoid false dblclick in some cases
  1882. return;
  1883. }
  1884. if (e.pointerType === 'mouse' ||
  1885. (e.sourceCapabilities && !e.sourceCapabilities.firesTouchEvents)) {
  1886. return;
  1887. }
  1888. // When clicking on an <input>, the browser generates a click on its
  1889. // <label> (and vice versa) triggering two clicks in quick succession.
  1890. // This ignores clicks on elements which are a label with a 'for'
  1891. // attribute (or children of such a label), but not children of
  1892. // a <input>.
  1893. var path = getPropagationPath(e);
  1894. if (path.some(function (el) {
  1895. return el instanceof HTMLLabelElement && el.attributes.for;
  1896. }) &&
  1897. !path.some(function (el) {
  1898. return (
  1899. el instanceof HTMLInputElement ||
  1900. el instanceof HTMLSelectElement
  1901. );
  1902. })
  1903. ) {
  1904. return;
  1905. }
  1906. var now = Date.now();
  1907. if (now - last <= delay) {
  1908. detail++;
  1909. if (detail === 2) {
  1910. handler(makeDblclick(e));
  1911. }
  1912. } else {
  1913. detail = 1;
  1914. }
  1915. last = now;
  1916. }
  1917. obj.addEventListener('click', simDblclick);
  1918. return {
  1919. dblclick: handler,
  1920. simDblclick: simDblclick
  1921. };
  1922. }
  1923. function removeDoubleTapListener(obj, handlers) {
  1924. obj.removeEventListener('dblclick', handlers.dblclick);
  1925. obj.removeEventListener('click', handlers.simDblclick);
  1926. }
  1927. /*
  1928. * @namespace DomUtil
  1929. *
  1930. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  1931. * tree, used by Leaflet internally.
  1932. *
  1933. * Most functions expecting or returning a `HTMLElement` also work for
  1934. * SVG elements. The only difference is that classes refer to CSS classes
  1935. * in HTML and SVG classes in SVG.
  1936. */
  1937. // @property TRANSFORM: String
  1938. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  1939. var TRANSFORM = testProp(
  1940. ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  1941. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  1942. // the same for the transitionend event, in particular the Android 4.1 stock browser
  1943. // @property TRANSITION: String
  1944. // Vendor-prefixed transition style name.
  1945. var TRANSITION = testProp(
  1946. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  1947. // @property TRANSITION_END: String
  1948. // Vendor-prefixed transitionend event name.
  1949. var TRANSITION_END =
  1950. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  1951. // @function get(id: String|HTMLElement): HTMLElement
  1952. // Returns an element given its DOM id, or returns the element itself
  1953. // if it was passed directly.
  1954. function get(id) {
  1955. return typeof id === 'string' ? document.getElementById(id) : id;
  1956. }
  1957. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  1958. // Returns the value for a certain style attribute on an element,
  1959. // including computed values or values set through CSS.
  1960. function getStyle(el, style) {
  1961. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  1962. if ((!value || value === 'auto') && document.defaultView) {
  1963. var css = document.defaultView.getComputedStyle(el, null);
  1964. value = css ? css[style] : null;
  1965. }
  1966. return value === 'auto' ? null : value;
  1967. }
  1968. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  1969. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  1970. function create$1(tagName, className, container) {
  1971. var el = document.createElement(tagName);
  1972. el.className = className || '';
  1973. if (container) {
  1974. container.appendChild(el);
  1975. }
  1976. return el;
  1977. }
  1978. // @function remove(el: HTMLElement)
  1979. // Removes `el` from its parent element
  1980. function remove(el) {
  1981. var parent = el.parentNode;
  1982. if (parent) {
  1983. parent.removeChild(el);
  1984. }
  1985. }
  1986. // @function empty(el: HTMLElement)
  1987. // Removes all of `el`'s children elements from `el`
  1988. function empty(el) {
  1989. while (el.firstChild) {
  1990. el.removeChild(el.firstChild);
  1991. }
  1992. }
  1993. // @function toFront(el: HTMLElement)
  1994. // Makes `el` the last child of its parent, so it renders in front of the other children.
  1995. function toFront(el) {
  1996. var parent = el.parentNode;
  1997. if (parent && parent.lastChild !== el) {
  1998. parent.appendChild(el);
  1999. }
  2000. }
  2001. // @function toBack(el: HTMLElement)
  2002. // Makes `el` the first child of its parent, so it renders behind the other children.
  2003. function toBack(el) {
  2004. var parent = el.parentNode;
  2005. if (parent && parent.firstChild !== el) {
  2006. parent.insertBefore(el, parent.firstChild);
  2007. }
  2008. }
  2009. // @function hasClass(el: HTMLElement, name: String): Boolean
  2010. // Returns `true` if the element's class attribute contains `name`.
  2011. function hasClass(el, name) {
  2012. if (el.classList !== undefined) {
  2013. return el.classList.contains(name);
  2014. }
  2015. var className = getClass(el);
  2016. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  2017. }
  2018. // @function addClass(el: HTMLElement, name: String)
  2019. // Adds `name` to the element's class attribute.
  2020. function addClass(el, name) {
  2021. if (el.classList !== undefined) {
  2022. var classes = splitWords(name);
  2023. for (var i = 0, len = classes.length; i < len; i++) {
  2024. el.classList.add(classes[i]);
  2025. }
  2026. } else if (!hasClass(el, name)) {
  2027. var className = getClass(el);
  2028. setClass(el, (className ? className + ' ' : '') + name);
  2029. }
  2030. }
  2031. // @function removeClass(el: HTMLElement, name: String)
  2032. // Removes `name` from the element's class attribute.
  2033. function removeClass(el, name) {
  2034. if (el.classList !== undefined) {
  2035. el.classList.remove(name);
  2036. } else {
  2037. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  2038. }
  2039. }
  2040. // @function setClass(el: HTMLElement, name: String)
  2041. // Sets the element's class.
  2042. function setClass(el, name) {
  2043. if (el.className.baseVal === undefined) {
  2044. el.className = name;
  2045. } else {
  2046. // in case of SVG element
  2047. el.className.baseVal = name;
  2048. }
  2049. }
  2050. // @function getClass(el: HTMLElement): String
  2051. // Returns the element's class.
  2052. function getClass(el) {
  2053. // Check if the element is an SVGElementInstance and use the correspondingElement instead
  2054. // (Required for linked SVG elements in IE11.)
  2055. if (el.correspondingElement) {
  2056. el = el.correspondingElement;
  2057. }
  2058. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  2059. }
  2060. // @function setOpacity(el: HTMLElement, opacity: Number)
  2061. // Set the opacity of an element (including old IE support).
  2062. // `opacity` must be a number from `0` to `1`.
  2063. function setOpacity(el, value) {
  2064. if ('opacity' in el.style) {
  2065. el.style.opacity = value;
  2066. } else if ('filter' in el.style) {
  2067. _setOpacityIE(el, value);
  2068. }
  2069. }
  2070. function _setOpacityIE(el, value) {
  2071. var filter = false,
  2072. filterName = 'DXImageTransform.Microsoft.Alpha';
  2073. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  2074. try {
  2075. filter = el.filters.item(filterName);
  2076. } catch (e) {
  2077. // don't set opacity to 1 if we haven't already set an opacity,
  2078. // it isn't needed and breaks transparent pngs.
  2079. if (value === 1) { return; }
  2080. }
  2081. value = Math.round(value * 100);
  2082. if (filter) {
  2083. filter.Enabled = (value !== 100);
  2084. filter.Opacity = value;
  2085. } else {
  2086. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  2087. }
  2088. }
  2089. // @function testProp(props: String[]): String|false
  2090. // Goes through the array of style names and returns the first name
  2091. // that is a valid style name for an element. If no such name is found,
  2092. // it returns false. Useful for vendor-prefixed styles like `transform`.
  2093. function testProp(props) {
  2094. var style = document.documentElement.style;
  2095. for (var i = 0; i < props.length; i++) {
  2096. if (props[i] in style) {
  2097. return props[i];
  2098. }
  2099. }
  2100. return false;
  2101. }
  2102. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  2103. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  2104. // and optionally scaled by `scale`. Does not have an effect if the
  2105. // browser doesn't support 3D CSS transforms.
  2106. function setTransform(el, offset, scale) {
  2107. var pos = offset || new Point(0, 0);
  2108. el.style[TRANSFORM] =
  2109. (Browser.ie3d ?
  2110. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2111. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2112. (scale ? ' scale(' + scale + ')' : '');
  2113. }
  2114. // @function setPosition(el: HTMLElement, position: Point)
  2115. // Sets the position of `el` to coordinates specified by `position`,
  2116. // using CSS translate or top/left positioning depending on the browser
  2117. // (used by Leaflet internally to position its layers).
  2118. function setPosition(el, point) {
  2119. /*eslint-disable */
  2120. el._leaflet_pos = point;
  2121. /* eslint-enable */
  2122. if (Browser.any3d) {
  2123. setTransform(el, point);
  2124. } else {
  2125. el.style.left = point.x + 'px';
  2126. el.style.top = point.y + 'px';
  2127. }
  2128. }
  2129. // @function getPosition(el: HTMLElement): Point
  2130. // Returns the coordinates of an element previously positioned with setPosition.
  2131. function getPosition(el) {
  2132. // this method is only used for elements previously positioned using setPosition,
  2133. // so it's safe to cache the position for performance
  2134. return el._leaflet_pos || new Point(0, 0);
  2135. }
  2136. // @function disableTextSelection()
  2137. // Prevents the user from generating `selectstart` DOM events, usually generated
  2138. // when the user drags the mouse through a page with text. Used internally
  2139. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2140. // the map. Affects drag interactions on the whole document.
  2141. // @function enableTextSelection()
  2142. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2143. var disableTextSelection;
  2144. var enableTextSelection;
  2145. var _userSelect;
  2146. if ('onselectstart' in document) {
  2147. disableTextSelection = function () {
  2148. on(window, 'selectstart', preventDefault);
  2149. };
  2150. enableTextSelection = function () {
  2151. off(window, 'selectstart', preventDefault);
  2152. };
  2153. } else {
  2154. var userSelectProperty = testProp(
  2155. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2156. disableTextSelection = function () {
  2157. if (userSelectProperty) {
  2158. var style = document.documentElement.style;
  2159. _userSelect = style[userSelectProperty];
  2160. style[userSelectProperty] = 'none';
  2161. }
  2162. };
  2163. enableTextSelection = function () {
  2164. if (userSelectProperty) {
  2165. document.documentElement.style[userSelectProperty] = _userSelect;
  2166. _userSelect = undefined;
  2167. }
  2168. };
  2169. }
  2170. // @function disableImageDrag()
  2171. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2172. // for `dragstart` DOM events, usually generated when the user drags an image.
  2173. function disableImageDrag() {
  2174. on(window, 'dragstart', preventDefault);
  2175. }
  2176. // @function enableImageDrag()
  2177. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2178. function enableImageDrag() {
  2179. off(window, 'dragstart', preventDefault);
  2180. }
  2181. var _outlineElement, _outlineStyle;
  2182. // @function preventOutline(el: HTMLElement)
  2183. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2184. // of the element `el` invisible. Used internally by Leaflet to prevent
  2185. // focusable elements from displaying an outline when the user performs a
  2186. // drag interaction on them.
  2187. function preventOutline(element) {
  2188. while (element.tabIndex === -1) {
  2189. element = element.parentNode;
  2190. }
  2191. if (!element.style) { return; }
  2192. restoreOutline();
  2193. _outlineElement = element;
  2194. _outlineStyle = element.style.outlineStyle;
  2195. element.style.outlineStyle = 'none';
  2196. on(window, 'keydown', restoreOutline);
  2197. }
  2198. // @function restoreOutline()
  2199. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2200. function restoreOutline() {
  2201. if (!_outlineElement) { return; }
  2202. _outlineElement.style.outlineStyle = _outlineStyle;
  2203. _outlineElement = undefined;
  2204. _outlineStyle = undefined;
  2205. off(window, 'keydown', restoreOutline);
  2206. }
  2207. // @function getSizedParentNode(el: HTMLElement): HTMLElement
  2208. // Finds the closest parent node which size (width and height) is not null.
  2209. function getSizedParentNode(element) {
  2210. do {
  2211. element = element.parentNode;
  2212. } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);
  2213. return element;
  2214. }
  2215. // @function getScale(el: HTMLElement): Object
  2216. // Computes the CSS scale currently applied on the element.
  2217. // Returns an object with `x` and `y` members as horizontal and vertical scales respectively,
  2218. // and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
  2219. function getScale(element) {
  2220. var rect = element.getBoundingClientRect(); // Read-only in old browsers.
  2221. return {
  2222. x: rect.width / element.offsetWidth || 1,
  2223. y: rect.height / element.offsetHeight || 1,
  2224. boundingClientRect: rect
  2225. };
  2226. }
  2227. var DomUtil = {
  2228. __proto__: null,
  2229. TRANSFORM: TRANSFORM,
  2230. TRANSITION: TRANSITION,
  2231. TRANSITION_END: TRANSITION_END,
  2232. get: get,
  2233. getStyle: getStyle,
  2234. create: create$1,
  2235. remove: remove,
  2236. empty: empty,
  2237. toFront: toFront,
  2238. toBack: toBack,
  2239. hasClass: hasClass,
  2240. addClass: addClass,
  2241. removeClass: removeClass,
  2242. setClass: setClass,
  2243. getClass: getClass,
  2244. setOpacity: setOpacity,
  2245. testProp: testProp,
  2246. setTransform: setTransform,
  2247. setPosition: setPosition,
  2248. getPosition: getPosition,
  2249. get disableTextSelection () { return disableTextSelection; },
  2250. get enableTextSelection () { return enableTextSelection; },
  2251. disableImageDrag: disableImageDrag,
  2252. enableImageDrag: enableImageDrag,
  2253. preventOutline: preventOutline,
  2254. restoreOutline: restoreOutline,
  2255. getSizedParentNode: getSizedParentNode,
  2256. getScale: getScale
  2257. };
  2258. /*
  2259. * @namespace DomEvent
  2260. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  2261. */
  2262. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  2263. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2264. // Adds a listener function (`fn`) to a particular DOM event type of the
  2265. // element `el`. You can optionally specify the context of the listener
  2266. // (object the `this` keyword will point to). You can also pass several
  2267. // space-separated types (e.g. `'click dblclick'`).
  2268. // @alternative
  2269. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  2270. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2271. function on(obj, types, fn, context) {
  2272. if (types && typeof types === 'object') {
  2273. for (var type in types) {
  2274. addOne(obj, type, types[type], fn);
  2275. }
  2276. } else {
  2277. types = splitWords(types);
  2278. for (var i = 0, len = types.length; i < len; i++) {
  2279. addOne(obj, types[i], fn, context);
  2280. }
  2281. }
  2282. return this;
  2283. }
  2284. var eventsKey = '_leaflet_events';
  2285. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  2286. // Removes a previously added listener function.
  2287. // Note that if you passed a custom context to on, you must pass the same
  2288. // context to `off` in order to remove the listener.
  2289. // @alternative
  2290. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  2291. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  2292. // @alternative
  2293. // @function off(el: HTMLElement, types: String): this
  2294. // Removes all previously added listeners of given types.
  2295. // @alternative
  2296. // @function off(el: HTMLElement): this
  2297. // Removes all previously added listeners from given HTMLElement
  2298. function off(obj, types, fn, context) {
  2299. if (arguments.length === 1) {
  2300. batchRemove(obj);
  2301. delete obj[eventsKey];
  2302. } else if (types && typeof types === 'object') {
  2303. for (var type in types) {
  2304. removeOne(obj, type, types[type], fn);
  2305. }
  2306. } else {
  2307. types = splitWords(types);
  2308. if (arguments.length === 2) {
  2309. batchRemove(obj, function (type) {
  2310. return indexOf(types, type) !== -1;
  2311. });
  2312. } else {
  2313. for (var i = 0, len = types.length; i < len; i++) {
  2314. removeOne(obj, types[i], fn, context);
  2315. }
  2316. }
  2317. }
  2318. return this;
  2319. }
  2320. function batchRemove(obj, filterFn) {
  2321. for (var id in obj[eventsKey]) {
  2322. var type = id.split(/\d/)[0];
  2323. if (!filterFn || filterFn(type)) {
  2324. removeOne(obj, type, null, null, id);
  2325. }
  2326. }
  2327. }
  2328. var mouseSubst = {
  2329. mouseenter: 'mouseover',
  2330. mouseleave: 'mouseout',
  2331. wheel: !('onwheel' in window) && 'mousewheel'
  2332. };
  2333. function addOne(obj, type, fn, context) {
  2334. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2335. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  2336. var handler = function (e) {
  2337. return fn.call(context || obj, e || window.event);
  2338. };
  2339. var originalHandler = handler;
  2340. if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {
  2341. // Needs DomEvent.Pointer.js
  2342. handler = addPointerListener(obj, type, handler);
  2343. } else if (Browser.touch && (type === 'dblclick')) {
  2344. handler = addDoubleTapListener(obj, handler);
  2345. } else if ('addEventListener' in obj) {
  2346. if (type === 'touchstart' || type === 'touchmove' || type === 'wheel' || type === 'mousewheel') {
  2347. obj.addEventListener(mouseSubst[type] || type, handler, Browser.passiveEvents ? {passive: false} : false);
  2348. } else if (type === 'mouseenter' || type === 'mouseleave') {
  2349. handler = function (e) {
  2350. e = e || window.event;
  2351. if (isExternalTarget(obj, e)) {
  2352. originalHandler(e);
  2353. }
  2354. };
  2355. obj.addEventListener(mouseSubst[type], handler, false);
  2356. } else {
  2357. obj.addEventListener(type, originalHandler, false);
  2358. }
  2359. } else {
  2360. obj.attachEvent('on' + type, handler);
  2361. }
  2362. obj[eventsKey] = obj[eventsKey] || {};
  2363. obj[eventsKey][id] = handler;
  2364. }
  2365. function removeOne(obj, type, fn, context, id) {
  2366. id = id || type + stamp(fn) + (context ? '_' + stamp(context) : '');
  2367. var handler = obj[eventsKey] && obj[eventsKey][id];
  2368. if (!handler) { return this; }
  2369. if (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {
  2370. removePointerListener(obj, type, handler);
  2371. } else if (Browser.touch && (type === 'dblclick')) {
  2372. removeDoubleTapListener(obj, handler);
  2373. } else if ('removeEventListener' in obj) {
  2374. obj.removeEventListener(mouseSubst[type] || type, handler, false);
  2375. } else {
  2376. obj.detachEvent('on' + type, handler);
  2377. }
  2378. obj[eventsKey][id] = null;
  2379. }
  2380. // @function stopPropagation(ev: DOMEvent): this
  2381. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  2382. // ```js
  2383. // L.DomEvent.on(div, 'click', function (ev) {
  2384. // L.DomEvent.stopPropagation(ev);
  2385. // });
  2386. // ```
  2387. function stopPropagation(e) {
  2388. if (e.stopPropagation) {
  2389. e.stopPropagation();
  2390. } else if (e.originalEvent) { // In case of Leaflet event.
  2391. e.originalEvent._stopped = true;
  2392. } else {
  2393. e.cancelBubble = true;
  2394. }
  2395. return this;
  2396. }
  2397. // @function disableScrollPropagation(el: HTMLElement): this
  2398. // Adds `stopPropagation` to the element's `'wheel'` events (plus browser variants).
  2399. function disableScrollPropagation(el) {
  2400. addOne(el, 'wheel', stopPropagation);
  2401. return this;
  2402. }
  2403. // @function disableClickPropagation(el: HTMLElement): this
  2404. // Adds `stopPropagation` to the element's `'click'`, `'dblclick'`, `'contextmenu'`,
  2405. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  2406. function disableClickPropagation(el) {
  2407. on(el, 'mousedown touchstart dblclick contextmenu', stopPropagation);
  2408. el['_leaflet_disable_click'] = true;
  2409. return this;
  2410. }
  2411. // @function preventDefault(ev: DOMEvent): this
  2412. // Prevents the default action of the DOM Event `ev` from happening (such as
  2413. // following a link in the href of the a element, or doing a POST request
  2414. // with page reload when a `<form>` is submitted).
  2415. // Use it inside listener functions.
  2416. function preventDefault(e) {
  2417. if (e.preventDefault) {
  2418. e.preventDefault();
  2419. } else {
  2420. e.returnValue = false;
  2421. }
  2422. return this;
  2423. }
  2424. // @function stop(ev: DOMEvent): this
  2425. // Does `stopPropagation` and `preventDefault` at the same time.
  2426. function stop(e) {
  2427. preventDefault(e);
  2428. stopPropagation(e);
  2429. return this;
  2430. }
  2431. // @function getPropagationPath(ev: DOMEvent): Array
  2432. // Compatibility polyfill for [`Event.composedPath()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath).
  2433. // Returns an array containing the `HTMLElement`s that the given DOM event
  2434. // should propagate to (if not stopped).
  2435. function getPropagationPath(ev) {
  2436. if (ev.composedPath) {
  2437. return ev.composedPath();
  2438. }
  2439. var path = [];
  2440. var el = ev.target;
  2441. while (el) {
  2442. path.push(el);
  2443. el = el.parentNode;
  2444. }
  2445. return path;
  2446. }
  2447. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  2448. // Gets normalized mouse position from a DOM event relative to the
  2449. // `container` (border excluded) or to the whole page if not specified.
  2450. function getMousePosition(e, container) {
  2451. if (!container) {
  2452. return new Point(e.clientX, e.clientY);
  2453. }
  2454. var scale = getScale(container),
  2455. offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)
  2456. return new Point(
  2457. // offset.left/top values are in page scale (like clientX/Y),
  2458. // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
  2459. (e.clientX - offset.left) / scale.x - container.clientLeft,
  2460. (e.clientY - offset.top) / scale.y - container.clientTop
  2461. );
  2462. }
  2463. // except , Safari and
  2464. // We need double the scroll pixels (see #7403 and #4538) for all Browsers
  2465. // except OSX (Mac) -> 3x, Chrome running on Linux 1x
  2466. var wheelPxFactor =
  2467. (Browser.linux && Browser.chrome) ? window.devicePixelRatio :
  2468. Browser.mac ? window.devicePixelRatio * 3 :
  2469. window.devicePixelRatio > 0 ? 2 * window.devicePixelRatio : 1;
  2470. // @function getWheelDelta(ev: DOMEvent): Number
  2471. // Gets normalized wheel delta from a wheel DOM event, in vertical
  2472. // pixels scrolled (negative if scrolling down).
  2473. // Events from pointing devices without precise scrolling are mapped to
  2474. // a best guess of 60 pixels.
  2475. function getWheelDelta(e) {
  2476. return (Browser.edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2477. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2478. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2479. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2480. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2481. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2482. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2483. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2484. 0;
  2485. }
  2486. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2487. function isExternalTarget(el, e) {
  2488. var related = e.relatedTarget;
  2489. if (!related) { return true; }
  2490. try {
  2491. while (related && (related !== el)) {
  2492. related = related.parentNode;
  2493. }
  2494. } catch (err) {
  2495. return false;
  2496. }
  2497. return (related !== el);
  2498. }
  2499. var DomEvent = {
  2500. __proto__: null,
  2501. on: on,
  2502. off: off,
  2503. stopPropagation: stopPropagation,
  2504. disableScrollPropagation: disableScrollPropagation,
  2505. disableClickPropagation: disableClickPropagation,
  2506. preventDefault: preventDefault,
  2507. stop: stop,
  2508. getPropagationPath: getPropagationPath,
  2509. getMousePosition: getMousePosition,
  2510. getWheelDelta: getWheelDelta,
  2511. isExternalTarget: isExternalTarget,
  2512. addListener: on,
  2513. removeListener: off
  2514. };
  2515. /*
  2516. * @class PosAnimation
  2517. * @aka L.PosAnimation
  2518. * @inherits Evented
  2519. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2520. *
  2521. * @example
  2522. * ```js
  2523. * var myPositionMarker = L.marker([48.864716, 2.294694]).addTo(map);
  2524. *
  2525. * myPositionMarker.on("click", function() {
  2526. * var pos = map.latLngToLayerPoint(myPositionMarker.getLatLng());
  2527. * pos.y -= 25;
  2528. * var fx = new L.PosAnimation();
  2529. *
  2530. * fx.once('end',function() {
  2531. * pos.y += 25;
  2532. * fx.run(myPositionMarker._icon, pos, 0.8);
  2533. * });
  2534. *
  2535. * fx.run(myPositionMarker._icon, pos, 0.3);
  2536. * });
  2537. *
  2538. * ```
  2539. *
  2540. * @constructor L.PosAnimation()
  2541. * Creates a `PosAnimation` object.
  2542. *
  2543. */
  2544. var PosAnimation = Evented.extend({
  2545. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2546. // Run an animation of a given element to a new position, optionally setting
  2547. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2548. // argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1),
  2549. // `0.5` by default).
  2550. run: function (el, newPos, duration, easeLinearity) {
  2551. this.stop();
  2552. this._el = el;
  2553. this._inProgress = true;
  2554. this._duration = duration || 0.25;
  2555. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2556. this._startPos = getPosition(el);
  2557. this._offset = newPos.subtract(this._startPos);
  2558. this._startTime = +new Date();
  2559. // @event start: Event
  2560. // Fired when the animation starts
  2561. this.fire('start');
  2562. this._animate();
  2563. },
  2564. // @method stop()
  2565. // Stops the animation (if currently running).
  2566. stop: function () {
  2567. if (!this._inProgress) { return; }
  2568. this._step(true);
  2569. this._complete();
  2570. },
  2571. _animate: function () {
  2572. // animation loop
  2573. this._animId = requestAnimFrame(this._animate, this);
  2574. this._step();
  2575. },
  2576. _step: function (round) {
  2577. var elapsed = (+new Date()) - this._startTime,
  2578. duration = this._duration * 1000;
  2579. if (elapsed < duration) {
  2580. this._runFrame(this._easeOut(elapsed / duration), round);
  2581. } else {
  2582. this._runFrame(1);
  2583. this._complete();
  2584. }
  2585. },
  2586. _runFrame: function (progress, round) {
  2587. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2588. if (round) {
  2589. pos._round();
  2590. }
  2591. setPosition(this._el, pos);
  2592. // @event step: Event
  2593. // Fired continuously during the animation.
  2594. this.fire('step');
  2595. },
  2596. _complete: function () {
  2597. cancelAnimFrame(this._animId);
  2598. this._inProgress = false;
  2599. // @event end: Event
  2600. // Fired when the animation ends.
  2601. this.fire('end');
  2602. },
  2603. _easeOut: function (t) {
  2604. return 1 - Math.pow(1 - t, this._easeOutPower);
  2605. }
  2606. });
  2607. /*
  2608. * @class Map
  2609. * @aka L.Map
  2610. * @inherits Evented
  2611. *
  2612. * The central class of the API — it is used to create a map on a page and manipulate it.
  2613. *
  2614. * @example
  2615. *
  2616. * ```js
  2617. * // initialize the map on the "map" div with a given center and zoom
  2618. * var map = L.map('map', {
  2619. * center: [51.505, -0.09],
  2620. * zoom: 13
  2621. * });
  2622. * ```
  2623. *
  2624. */
  2625. var Map = Evented.extend({
  2626. options: {
  2627. // @section Map State Options
  2628. // @option crs: CRS = L.CRS.EPSG3857
  2629. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2630. // sure what it means.
  2631. crs: EPSG3857,
  2632. // @option center: LatLng = undefined
  2633. // Initial geographic center of the map
  2634. center: undefined,
  2635. // @option zoom: Number = undefined
  2636. // Initial map zoom level
  2637. zoom: undefined,
  2638. // @option minZoom: Number = *
  2639. // Minimum zoom level of the map.
  2640. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2641. // the lowest of their `minZoom` options will be used instead.
  2642. minZoom: undefined,
  2643. // @option maxZoom: Number = *
  2644. // Maximum zoom level of the map.
  2645. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2646. // the highest of their `maxZoom` options will be used instead.
  2647. maxZoom: undefined,
  2648. // @option layers: Layer[] = []
  2649. // Array of layers that will be added to the map initially
  2650. layers: [],
  2651. // @option maxBounds: LatLngBounds = null
  2652. // When this option is set, the map restricts the view to the given
  2653. // geographical bounds, bouncing the user back if the user tries to pan
  2654. // outside the view. To set the restriction dynamically, use
  2655. // [`setMaxBounds`](#map-setmaxbounds) method.
  2656. maxBounds: undefined,
  2657. // @option renderer: Renderer = *
  2658. // The default method for drawing vector layers on the map. `L.SVG`
  2659. // or `L.Canvas` by default depending on browser support.
  2660. renderer: undefined,
  2661. // @section Animation Options
  2662. // @option zoomAnimation: Boolean = true
  2663. // Whether the map zoom animation is enabled. By default it's enabled
  2664. // in all browsers that support CSS3 Transitions except Android.
  2665. zoomAnimation: true,
  2666. // @option zoomAnimationThreshold: Number = 4
  2667. // Won't animate zoom if the zoom difference exceeds this value.
  2668. zoomAnimationThreshold: 4,
  2669. // @option fadeAnimation: Boolean = true
  2670. // Whether the tile fade animation is enabled. By default it's enabled
  2671. // in all browsers that support CSS3 Transitions except Android.
  2672. fadeAnimation: true,
  2673. // @option markerZoomAnimation: Boolean = true
  2674. // Whether markers animate their zoom with the zoom animation, if disabled
  2675. // they will disappear for the length of the animation. By default it's
  2676. // enabled in all browsers that support CSS3 Transitions except Android.
  2677. markerZoomAnimation: true,
  2678. // @option transform3DLimit: Number = 2^23
  2679. // Defines the maximum size of a CSS translation transform. The default
  2680. // value should not be changed unless a web browser positions layers in
  2681. // the wrong place after doing a large `panBy`.
  2682. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2683. // @section Interaction Options
  2684. // @option zoomSnap: Number = 1
  2685. // Forces the map's zoom level to always be a multiple of this, particularly
  2686. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2687. // By default, the zoom level snaps to the nearest integer; lower values
  2688. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2689. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2690. zoomSnap: 1,
  2691. // @option zoomDelta: Number = 1
  2692. // Controls how much the map's zoom level will change after a
  2693. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2694. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2695. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2696. zoomDelta: 1,
  2697. // @option trackResize: Boolean = true
  2698. // Whether the map automatically handles browser window resize to update itself.
  2699. trackResize: true
  2700. },
  2701. initialize: function (id, options) { // (HTMLElement or String, Object)
  2702. options = setOptions(this, options);
  2703. // Make sure to assign internal flags at the beginning,
  2704. // to avoid inconsistent state in some edge cases.
  2705. this._handlers = [];
  2706. this._layers = {};
  2707. this._zoomBoundLayers = {};
  2708. this._sizeChanged = true;
  2709. this._initContainer(id);
  2710. this._initLayout();
  2711. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2712. this._onResize = bind(this._onResize, this);
  2713. this._initEvents();
  2714. if (options.maxBounds) {
  2715. this.setMaxBounds(options.maxBounds);
  2716. }
  2717. if (options.zoom !== undefined) {
  2718. this._zoom = this._limitZoom(options.zoom);
  2719. }
  2720. if (options.center && options.zoom !== undefined) {
  2721. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2722. }
  2723. this.callInitHooks();
  2724. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2725. this._zoomAnimated = TRANSITION && Browser.any3d && !Browser.mobileOpera &&
  2726. this.options.zoomAnimation;
  2727. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2728. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2729. if (this._zoomAnimated) {
  2730. this._createAnimProxy();
  2731. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2732. }
  2733. this._addLayers(this.options.layers);
  2734. },
  2735. // @section Methods for modifying map state
  2736. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2737. // Sets the view of the map (geographical center and zoom) with the given
  2738. // animation options.
  2739. setView: function (center, zoom, options) {
  2740. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2741. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2742. options = options || {};
  2743. this._stop();
  2744. if (this._loaded && !options.reset && options !== true) {
  2745. if (options.animate !== undefined) {
  2746. options.zoom = extend({animate: options.animate}, options.zoom);
  2747. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2748. }
  2749. // try animating pan or zoom
  2750. var moved = (this._zoom !== zoom) ?
  2751. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2752. this._tryAnimatedPan(center, options.pan);
  2753. if (moved) {
  2754. // prevent resize handler call, the view will refresh after animation anyway
  2755. clearTimeout(this._sizeTimer);
  2756. return this;
  2757. }
  2758. }
  2759. // animation didn't start, just reset the map view
  2760. this._resetView(center, zoom, options.pan && options.pan.noMoveStart);
  2761. return this;
  2762. },
  2763. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2764. // Sets the zoom of the map.
  2765. setZoom: function (zoom, options) {
  2766. if (!this._loaded) {
  2767. this._zoom = zoom;
  2768. return this;
  2769. }
  2770. return this.setView(this.getCenter(), zoom, {zoom: options});
  2771. },
  2772. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2773. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2774. zoomIn: function (delta, options) {
  2775. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  2776. return this.setZoom(this._zoom + delta, options);
  2777. },
  2778. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2779. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2780. zoomOut: function (delta, options) {
  2781. delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
  2782. return this.setZoom(this._zoom - delta, options);
  2783. },
  2784. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2785. // Zooms the map while keeping a specified geographical point on the map
  2786. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2787. // @alternative
  2788. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2789. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2790. setZoomAround: function (latlng, zoom, options) {
  2791. var scale = this.getZoomScale(zoom),
  2792. viewHalf = this.getSize().divideBy(2),
  2793. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2794. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2795. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2796. return this.setView(newCenter, zoom, {zoom: options});
  2797. },
  2798. _getBoundsCenterZoom: function (bounds, options) {
  2799. options = options || {};
  2800. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2801. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2802. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2803. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2804. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2805. if (zoom === Infinity) {
  2806. return {
  2807. center: bounds.getCenter(),
  2808. zoom: zoom
  2809. };
  2810. }
  2811. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2812. swPoint = this.project(bounds.getSouthWest(), zoom),
  2813. nePoint = this.project(bounds.getNorthEast(), zoom),
  2814. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2815. return {
  2816. center: center,
  2817. zoom: zoom
  2818. };
  2819. },
  2820. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2821. // Sets a map view that contains the given geographical bounds with the
  2822. // maximum zoom level possible.
  2823. fitBounds: function (bounds, options) {
  2824. bounds = toLatLngBounds(bounds);
  2825. if (!bounds.isValid()) {
  2826. throw new Error('Bounds are not valid.');
  2827. }
  2828. var target = this._getBoundsCenterZoom(bounds, options);
  2829. return this.setView(target.center, target.zoom, options);
  2830. },
  2831. // @method fitWorld(options?: fitBounds options): this
  2832. // Sets a map view that mostly contains the whole world with the maximum
  2833. // zoom level possible.
  2834. fitWorld: function (options) {
  2835. return this.fitBounds([[-90, -180], [90, 180]], options);
  2836. },
  2837. // @method panTo(latlng: LatLng, options?: Pan options): this
  2838. // Pans the map to a given center.
  2839. panTo: function (center, options) { // (LatLng)
  2840. return this.setView(center, this._zoom, {pan: options});
  2841. },
  2842. // @method panBy(offset: Point, options?: Pan options): this
  2843. // Pans the map by a given number of pixels (animated).
  2844. panBy: function (offset, options) {
  2845. offset = toPoint(offset).round();
  2846. options = options || {};
  2847. if (!offset.x && !offset.y) {
  2848. return this.fire('moveend');
  2849. }
  2850. // If we pan too far, Chrome gets issues with tiles
  2851. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2852. if (options.animate !== true && !this.getSize().contains(offset)) {
  2853. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2854. return this;
  2855. }
  2856. if (!this._panAnim) {
  2857. this._panAnim = new PosAnimation();
  2858. this._panAnim.on({
  2859. 'step': this._onPanTransitionStep,
  2860. 'end': this._onPanTransitionEnd
  2861. }, this);
  2862. }
  2863. // don't fire movestart if animating inertia
  2864. if (!options.noMoveStart) {
  2865. this.fire('movestart');
  2866. }
  2867. // animate pan unless animate: false specified
  2868. if (options.animate !== false) {
  2869. addClass(this._mapPane, 'leaflet-pan-anim');
  2870. var newPos = this._getMapPanePos().subtract(offset).round();
  2871. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2872. } else {
  2873. this._rawPanBy(offset);
  2874. this.fire('move').fire('moveend');
  2875. }
  2876. return this;
  2877. },
  2878. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2879. // Sets the view of the map (geographical center and zoom) performing a smooth
  2880. // pan-zoom animation.
  2881. flyTo: function (targetCenter, targetZoom, options) {
  2882. options = options || {};
  2883. if (options.animate === false || !Browser.any3d) {
  2884. return this.setView(targetCenter, targetZoom, options);
  2885. }
  2886. this._stop();
  2887. var from = this.project(this.getCenter()),
  2888. to = this.project(targetCenter),
  2889. size = this.getSize(),
  2890. startZoom = this._zoom;
  2891. targetCenter = toLatLng(targetCenter);
  2892. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2893. var w0 = Math.max(size.x, size.y),
  2894. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2895. u1 = (to.distanceTo(from)) || 1,
  2896. rho = 1.42,
  2897. rho2 = rho * rho;
  2898. function r(i) {
  2899. var s1 = i ? -1 : 1,
  2900. s2 = i ? w1 : w0,
  2901. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2902. b1 = 2 * s2 * rho2 * u1,
  2903. b = t1 / b1,
  2904. sq = Math.sqrt(b * b + 1) - b;
  2905. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2906. // thus triggering an infinite loop in flyTo
  2907. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2908. return log;
  2909. }
  2910. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2911. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2912. function tanh(n) { return sinh(n) / cosh(n); }
  2913. var r0 = r(0);
  2914. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2915. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2916. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2917. var start = Date.now(),
  2918. S = (r(1) - r0) / rho,
  2919. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2920. function frame() {
  2921. var t = (Date.now() - start) / duration,
  2922. s = easeOut(t) * S;
  2923. if (t <= 1) {
  2924. this._flyToFrame = requestAnimFrame(frame, this);
  2925. this._move(
  2926. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2927. this.getScaleZoom(w0 / w(s), startZoom),
  2928. {flyTo: true});
  2929. } else {
  2930. this
  2931. ._move(targetCenter, targetZoom)
  2932. ._moveEnd(true);
  2933. }
  2934. }
  2935. this._moveStart(true, options.noMoveStart);
  2936. frame.call(this);
  2937. return this;
  2938. },
  2939. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2940. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2941. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2942. flyToBounds: function (bounds, options) {
  2943. var target = this._getBoundsCenterZoom(bounds, options);
  2944. return this.flyTo(target.center, target.zoom, options);
  2945. },
  2946. // @method setMaxBounds(bounds: LatLngBounds): this
  2947. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2948. setMaxBounds: function (bounds) {
  2949. bounds = toLatLngBounds(bounds);
  2950. if (this.listens('moveend', this._panInsideMaxBounds)) {
  2951. this.off('moveend', this._panInsideMaxBounds);
  2952. }
  2953. if (!bounds.isValid()) {
  2954. this.options.maxBounds = null;
  2955. return this;
  2956. }
  2957. this.options.maxBounds = bounds;
  2958. if (this._loaded) {
  2959. this._panInsideMaxBounds();
  2960. }
  2961. return this.on('moveend', this._panInsideMaxBounds);
  2962. },
  2963. // @method setMinZoom(zoom: Number): this
  2964. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2965. setMinZoom: function (zoom) {
  2966. var oldZoom = this.options.minZoom;
  2967. this.options.minZoom = zoom;
  2968. if (this._loaded && oldZoom !== zoom) {
  2969. this.fire('zoomlevelschange');
  2970. if (this.getZoom() < this.options.minZoom) {
  2971. return this.setZoom(zoom);
  2972. }
  2973. }
  2974. return this;
  2975. },
  2976. // @method setMaxZoom(zoom: Number): this
  2977. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2978. setMaxZoom: function (zoom) {
  2979. var oldZoom = this.options.maxZoom;
  2980. this.options.maxZoom = zoom;
  2981. if (this._loaded && oldZoom !== zoom) {
  2982. this.fire('zoomlevelschange');
  2983. if (this.getZoom() > this.options.maxZoom) {
  2984. return this.setZoom(zoom);
  2985. }
  2986. }
  2987. return this;
  2988. },
  2989. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2990. // 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.
  2991. panInsideBounds: function (bounds, options) {
  2992. this._enforcingBounds = true;
  2993. var center = this.getCenter(),
  2994. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2995. if (!center.equals(newCenter)) {
  2996. this.panTo(newCenter, options);
  2997. }
  2998. this._enforcingBounds = false;
  2999. return this;
  3000. },
  3001. // @method panInside(latlng: LatLng, options?: padding options): this
  3002. // Pans the map the minimum amount to make the `latlng` visible. Use
  3003. // padding options to fit the display to more restricted bounds.
  3004. // If `latlng` is already within the (optionally padded) display bounds,
  3005. // the map will not be panned.
  3006. panInside: function (latlng, options) {
  3007. options = options || {};
  3008. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  3009. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  3010. pixelCenter = this.project(this.getCenter()),
  3011. pixelPoint = this.project(latlng),
  3012. pixelBounds = this.getPixelBounds(),
  3013. paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]),
  3014. paddedSize = paddedBounds.getSize();
  3015. if (!paddedBounds.contains(pixelPoint)) {
  3016. this._enforcingBounds = true;
  3017. var centerOffset = pixelPoint.subtract(paddedBounds.getCenter());
  3018. var offset = paddedBounds.extend(pixelPoint).getSize().subtract(paddedSize);
  3019. pixelCenter.x += centerOffset.x < 0 ? -offset.x : offset.x;
  3020. pixelCenter.y += centerOffset.y < 0 ? -offset.y : offset.y;
  3021. this.panTo(this.unproject(pixelCenter), options);
  3022. this._enforcingBounds = false;
  3023. }
  3024. return this;
  3025. },
  3026. // @method invalidateSize(options: Zoom/pan options): this
  3027. // Checks if the map container size changed and updates the map if so —
  3028. // call it after you've changed the map size dynamically, also animating
  3029. // pan by default. If `options.pan` is `false`, panning will not occur.
  3030. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  3031. // that it doesn't happen often even if the method is called many
  3032. // times in a row.
  3033. // @alternative
  3034. // @method invalidateSize(animate: Boolean): this
  3035. // Checks if the map container size changed and updates the map if so —
  3036. // call it after you've changed the map size dynamically, also animating
  3037. // pan by default.
  3038. invalidateSize: function (options) {
  3039. if (!this._loaded) { return this; }
  3040. options = extend({
  3041. animate: false,
  3042. pan: true
  3043. }, options === true ? {animate: true} : options);
  3044. var oldSize = this.getSize();
  3045. this._sizeChanged = true;
  3046. this._lastCenter = null;
  3047. var newSize = this.getSize(),
  3048. oldCenter = oldSize.divideBy(2).round(),
  3049. newCenter = newSize.divideBy(2).round(),
  3050. offset = oldCenter.subtract(newCenter);
  3051. if (!offset.x && !offset.y) { return this; }
  3052. if (options.animate && options.pan) {
  3053. this.panBy(offset);
  3054. } else {
  3055. if (options.pan) {
  3056. this._rawPanBy(offset);
  3057. }
  3058. this.fire('move');
  3059. if (options.debounceMoveend) {
  3060. clearTimeout(this._sizeTimer);
  3061. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  3062. } else {
  3063. this.fire('moveend');
  3064. }
  3065. }
  3066. // @section Map state change events
  3067. // @event resize: ResizeEvent
  3068. // Fired when the map is resized.
  3069. return this.fire('resize', {
  3070. oldSize: oldSize,
  3071. newSize: newSize
  3072. });
  3073. },
  3074. // @section Methods for modifying map state
  3075. // @method stop(): this
  3076. // Stops the currently running `panTo` or `flyTo` animation, if any.
  3077. stop: function () {
  3078. this.setZoom(this._limitZoom(this._zoom));
  3079. if (!this.options.zoomSnap) {
  3080. this.fire('viewreset');
  3081. }
  3082. return this._stop();
  3083. },
  3084. // @section Geolocation methods
  3085. // @method locate(options?: Locate options): this
  3086. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  3087. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  3088. // and optionally sets the map view to the user's location with respect to
  3089. // detection accuracy (or to the world view if geolocation failed).
  3090. // Note that, if your page doesn't use HTTPS, this method will fail in
  3091. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  3092. // See `Locate options` for more details.
  3093. locate: function (options) {
  3094. options = this._locateOptions = extend({
  3095. timeout: 10000,
  3096. watch: false
  3097. // setView: false
  3098. // maxZoom: <Number>
  3099. // maximumAge: 0
  3100. // enableHighAccuracy: false
  3101. }, options);
  3102. if (!('geolocation' in navigator)) {
  3103. this._handleGeolocationError({
  3104. code: 0,
  3105. message: 'Geolocation not supported.'
  3106. });
  3107. return this;
  3108. }
  3109. var onResponse = bind(this._handleGeolocationResponse, this),
  3110. onError = bind(this._handleGeolocationError, this);
  3111. if (options.watch) {
  3112. this._locationWatchId =
  3113. navigator.geolocation.watchPosition(onResponse, onError, options);
  3114. } else {
  3115. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  3116. }
  3117. return this;
  3118. },
  3119. // @method stopLocate(): this
  3120. // Stops watching location previously initiated by `map.locate({watch: true})`
  3121. // and aborts resetting the map view if map.locate was called with
  3122. // `{setView: true}`.
  3123. stopLocate: function () {
  3124. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  3125. navigator.geolocation.clearWatch(this._locationWatchId);
  3126. }
  3127. if (this._locateOptions) {
  3128. this._locateOptions.setView = false;
  3129. }
  3130. return this;
  3131. },
  3132. _handleGeolocationError: function (error) {
  3133. if (!this._container._leaflet_id) { return; }
  3134. var c = error.code,
  3135. message = error.message ||
  3136. (c === 1 ? 'permission denied' :
  3137. (c === 2 ? 'position unavailable' : 'timeout'));
  3138. if (this._locateOptions.setView && !this._loaded) {
  3139. this.fitWorld();
  3140. }
  3141. // @section Location events
  3142. // @event locationerror: ErrorEvent
  3143. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  3144. this.fire('locationerror', {
  3145. code: c,
  3146. message: 'Geolocation error: ' + message + '.'
  3147. });
  3148. },
  3149. _handleGeolocationResponse: function (pos) {
  3150. if (!this._container._leaflet_id) { return; }
  3151. var lat = pos.coords.latitude,
  3152. lng = pos.coords.longitude,
  3153. latlng = new LatLng(lat, lng),
  3154. bounds = latlng.toBounds(pos.coords.accuracy * 2),
  3155. options = this._locateOptions;
  3156. if (options.setView) {
  3157. var zoom = this.getBoundsZoom(bounds);
  3158. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  3159. }
  3160. var data = {
  3161. latlng: latlng,
  3162. bounds: bounds,
  3163. timestamp: pos.timestamp
  3164. };
  3165. for (var i in pos.coords) {
  3166. if (typeof pos.coords[i] === 'number') {
  3167. data[i] = pos.coords[i];
  3168. }
  3169. }
  3170. // @event locationfound: LocationEvent
  3171. // Fired when geolocation (using the [`locate`](#map-locate) method)
  3172. // went successfully.
  3173. this.fire('locationfound', data);
  3174. },
  3175. // TODO Appropriate docs section?
  3176. // @section Other Methods
  3177. // @method addHandler(name: String, HandlerClass: Function): this
  3178. // Adds a new `Handler` to the map, given its name and constructor function.
  3179. addHandler: function (name, HandlerClass) {
  3180. if (!HandlerClass) { return this; }
  3181. var handler = this[name] = new HandlerClass(this);
  3182. this._handlers.push(handler);
  3183. if (this.options[name]) {
  3184. handler.enable();
  3185. }
  3186. return this;
  3187. },
  3188. // @method remove(): this
  3189. // Destroys the map and clears all related event listeners.
  3190. remove: function () {
  3191. this._initEvents(true);
  3192. if (this.options.maxBounds) { this.off('moveend', this._panInsideMaxBounds); }
  3193. if (this._containerId !== this._container._leaflet_id) {
  3194. throw new Error('Map container is being reused by another instance');
  3195. }
  3196. try {
  3197. // throws error in IE6-8
  3198. delete this._container._leaflet_id;
  3199. delete this._containerId;
  3200. } catch (e) {
  3201. /*eslint-disable */
  3202. this._container._leaflet_id = undefined;
  3203. /* eslint-enable */
  3204. this._containerId = undefined;
  3205. }
  3206. if (this._locationWatchId !== undefined) {
  3207. this.stopLocate();
  3208. }
  3209. this._stop();
  3210. remove(this._mapPane);
  3211. if (this._clearControlPos) {
  3212. this._clearControlPos();
  3213. }
  3214. if (this._resizeRequest) {
  3215. cancelAnimFrame(this._resizeRequest);
  3216. this._resizeRequest = null;
  3217. }
  3218. this._clearHandlers();
  3219. if (this._loaded) {
  3220. // @section Map state change events
  3221. // @event unload: Event
  3222. // Fired when the map is destroyed with [remove](#map-remove) method.
  3223. this.fire('unload');
  3224. }
  3225. var i;
  3226. for (i in this._layers) {
  3227. this._layers[i].remove();
  3228. }
  3229. for (i in this._panes) {
  3230. remove(this._panes[i]);
  3231. }
  3232. this._layers = [];
  3233. this._panes = [];
  3234. delete this._mapPane;
  3235. delete this._renderer;
  3236. return this;
  3237. },
  3238. // @section Other Methods
  3239. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3240. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3241. // then returns it. The pane is created as a child of `container`, or
  3242. // as a child of the main map pane if not set.
  3243. createPane: function (name, container) {
  3244. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3245. pane = create$1('div', className, container || this._mapPane);
  3246. if (name) {
  3247. this._panes[name] = pane;
  3248. }
  3249. return pane;
  3250. },
  3251. // @section Methods for Getting Map State
  3252. // @method getCenter(): LatLng
  3253. // Returns the geographical center of the map view
  3254. getCenter: function () {
  3255. this._checkIfLoaded();
  3256. if (this._lastCenter && !this._moved()) {
  3257. return this._lastCenter.clone();
  3258. }
  3259. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3260. },
  3261. // @method getZoom(): Number
  3262. // Returns the current zoom level of the map view
  3263. getZoom: function () {
  3264. return this._zoom;
  3265. },
  3266. // @method getBounds(): LatLngBounds
  3267. // Returns the geographical bounds visible in the current map view
  3268. getBounds: function () {
  3269. var bounds = this.getPixelBounds(),
  3270. sw = this.unproject(bounds.getBottomLeft()),
  3271. ne = this.unproject(bounds.getTopRight());
  3272. return new LatLngBounds(sw, ne);
  3273. },
  3274. // @method getMinZoom(): Number
  3275. // 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.
  3276. getMinZoom: function () {
  3277. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3278. },
  3279. // @method getMaxZoom(): Number
  3280. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3281. getMaxZoom: function () {
  3282. return this.options.maxZoom === undefined ?
  3283. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3284. this.options.maxZoom;
  3285. },
  3286. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
  3287. // Returns the maximum zoom level on which the given bounds fit to the map
  3288. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3289. // instead returns the minimum zoom level on which the map view fits into
  3290. // the given bounds in its entirety.
  3291. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3292. bounds = toLatLngBounds(bounds);
  3293. padding = toPoint(padding || [0, 0]);
  3294. var zoom = this.getZoom() || 0,
  3295. min = this.getMinZoom(),
  3296. max = this.getMaxZoom(),
  3297. nw = bounds.getNorthWest(),
  3298. se = bounds.getSouthEast(),
  3299. size = this.getSize().subtract(padding),
  3300. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3301. snap = Browser.any3d ? this.options.zoomSnap : 1,
  3302. scalex = size.x / boundsSize.x,
  3303. scaley = size.y / boundsSize.y,
  3304. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3305. zoom = this.getScaleZoom(scale, zoom);
  3306. if (snap) {
  3307. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3308. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3309. }
  3310. return Math.max(min, Math.min(max, zoom));
  3311. },
  3312. // @method getSize(): Point
  3313. // Returns the current size of the map container (in pixels).
  3314. getSize: function () {
  3315. if (!this._size || this._sizeChanged) {
  3316. this._size = new Point(
  3317. this._container.clientWidth || 0,
  3318. this._container.clientHeight || 0);
  3319. this._sizeChanged = false;
  3320. }
  3321. return this._size.clone();
  3322. },
  3323. // @method getPixelBounds(): Bounds
  3324. // Returns the bounds of the current map view in projected pixel
  3325. // coordinates (sometimes useful in layer and overlay implementations).
  3326. getPixelBounds: function (center, zoom) {
  3327. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3328. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3329. },
  3330. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3331. // the map pane? "left point of the map layer" can be confusing, specially
  3332. // since there can be negative offsets.
  3333. // @method getPixelOrigin(): Point
  3334. // Returns the projected pixel coordinates of the top left point of
  3335. // the map layer (useful in custom layer and overlay implementations).
  3336. getPixelOrigin: function () {
  3337. this._checkIfLoaded();
  3338. return this._pixelOrigin;
  3339. },
  3340. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3341. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3342. // If `zoom` is omitted, the map's current zoom level is used.
  3343. getPixelWorldBounds: function (zoom) {
  3344. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3345. },
  3346. // @section Other Methods
  3347. // @method getPane(pane: String|HTMLElement): HTMLElement
  3348. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3349. getPane: function (pane) {
  3350. return typeof pane === 'string' ? this._panes[pane] : pane;
  3351. },
  3352. // @method getPanes(): Object
  3353. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3354. // the panes as values.
  3355. getPanes: function () {
  3356. return this._panes;
  3357. },
  3358. // @method getContainer: HTMLElement
  3359. // Returns the HTML element that contains the map.
  3360. getContainer: function () {
  3361. return this._container;
  3362. },
  3363. // @section Conversion Methods
  3364. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3365. // Returns the scale factor to be applied to a map transition from zoom level
  3366. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3367. getZoomScale: function (toZoom, fromZoom) {
  3368. // TODO replace with universal implementation after refactoring projections
  3369. var crs = this.options.crs;
  3370. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3371. return crs.scale(toZoom) / crs.scale(fromZoom);
  3372. },
  3373. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3374. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3375. // level and everything is scaled by a factor of `scale`. Inverse of
  3376. // [`getZoomScale`](#map-getZoomScale).
  3377. getScaleZoom: function (scale, fromZoom) {
  3378. var crs = this.options.crs;
  3379. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3380. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3381. return isNaN(zoom) ? Infinity : zoom;
  3382. },
  3383. // @method project(latlng: LatLng, zoom: Number): Point
  3384. // Projects a geographical coordinate `LatLng` according to the projection
  3385. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3386. // `Transformation`. The result is pixel coordinate relative to
  3387. // the CRS origin.
  3388. project: function (latlng, zoom) {
  3389. zoom = zoom === undefined ? this._zoom : zoom;
  3390. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3391. },
  3392. // @method unproject(point: Point, zoom: Number): LatLng
  3393. // Inverse of [`project`](#map-project).
  3394. unproject: function (point, zoom) {
  3395. zoom = zoom === undefined ? this._zoom : zoom;
  3396. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3397. },
  3398. // @method layerPointToLatLng(point: Point): LatLng
  3399. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3400. // returns the corresponding geographical coordinate (for the current zoom level).
  3401. layerPointToLatLng: function (point) {
  3402. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3403. return this.unproject(projectedPoint);
  3404. },
  3405. // @method latLngToLayerPoint(latlng: LatLng): Point
  3406. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3407. // relative to the [origin pixel](#map-getpixelorigin).
  3408. latLngToLayerPoint: function (latlng) {
  3409. var projectedPoint = this.project(toLatLng(latlng))._round();
  3410. return projectedPoint._subtract(this.getPixelOrigin());
  3411. },
  3412. // @method wrapLatLng(latlng: LatLng): LatLng
  3413. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3414. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3415. // CRS's bounds.
  3416. // By default this means longitude is wrapped around the dateline so its
  3417. // value is between -180 and +180 degrees.
  3418. wrapLatLng: function (latlng) {
  3419. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3420. },
  3421. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3422. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3423. // its center is within the CRS's bounds.
  3424. // By default this means the center longitude is wrapped around the dateline so its
  3425. // value is between -180 and +180 degrees, and the majority of the bounds
  3426. // overlaps the CRS's bounds.
  3427. wrapLatLngBounds: function (latlng) {
  3428. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3429. },
  3430. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3431. // Returns the distance between two geographical coordinates according to
  3432. // the map's CRS. By default this measures distance in meters.
  3433. distance: function (latlng1, latlng2) {
  3434. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3435. },
  3436. // @method containerPointToLayerPoint(point: Point): Point
  3437. // Given a pixel coordinate relative to the map container, returns the corresponding
  3438. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3439. containerPointToLayerPoint: function (point) { // (Point)
  3440. return toPoint(point).subtract(this._getMapPanePos());
  3441. },
  3442. // @method layerPointToContainerPoint(point: Point): Point
  3443. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3444. // returns the corresponding pixel coordinate relative to the map container.
  3445. layerPointToContainerPoint: function (point) { // (Point)
  3446. return toPoint(point).add(this._getMapPanePos());
  3447. },
  3448. // @method containerPointToLatLng(point: Point): LatLng
  3449. // Given a pixel coordinate relative to the map container, returns
  3450. // the corresponding geographical coordinate (for the current zoom level).
  3451. containerPointToLatLng: function (point) {
  3452. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3453. return this.layerPointToLatLng(layerPoint);
  3454. },
  3455. // @method latLngToContainerPoint(latlng: LatLng): Point
  3456. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3457. // relative to the map container.
  3458. latLngToContainerPoint: function (latlng) {
  3459. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3460. },
  3461. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3462. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3463. // map container where the event took place.
  3464. mouseEventToContainerPoint: function (e) {
  3465. return getMousePosition(e, this._container);
  3466. },
  3467. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3468. // Given a MouseEvent object, returns the pixel coordinate relative to
  3469. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3470. mouseEventToLayerPoint: function (e) {
  3471. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3472. },
  3473. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3474. // Given a MouseEvent object, returns geographical coordinate where the
  3475. // event took place.
  3476. mouseEventToLatLng: function (e) { // (MouseEvent)
  3477. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3478. },
  3479. // map initialization methods
  3480. _initContainer: function (id) {
  3481. var container = this._container = get(id);
  3482. if (!container) {
  3483. throw new Error('Map container not found.');
  3484. } else if (container._leaflet_id) {
  3485. throw new Error('Map container is already initialized.');
  3486. }
  3487. on(container, 'scroll', this._onScroll, this);
  3488. this._containerId = stamp(container);
  3489. },
  3490. _initLayout: function () {
  3491. var container = this._container;
  3492. this._fadeAnimated = this.options.fadeAnimation && Browser.any3d;
  3493. addClass(container, 'leaflet-container' +
  3494. (Browser.touch ? ' leaflet-touch' : '') +
  3495. (Browser.retina ? ' leaflet-retina' : '') +
  3496. (Browser.ielt9 ? ' leaflet-oldie' : '') +
  3497. (Browser.safari ? ' leaflet-safari' : '') +
  3498. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3499. var position = getStyle(container, 'position');
  3500. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed' && position !== 'sticky') {
  3501. container.style.position = 'relative';
  3502. }
  3503. this._initPanes();
  3504. if (this._initControlPos) {
  3505. this._initControlPos();
  3506. }
  3507. },
  3508. _initPanes: function () {
  3509. var panes = this._panes = {};
  3510. this._paneRenderers = {};
  3511. // @section
  3512. //
  3513. // Panes are DOM elements used to control the ordering of layers on the map. You
  3514. // can access panes with [`map.getPane`](#map-getpane) or
  3515. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3516. // [`map.createPane`](#map-createpane) method.
  3517. //
  3518. // Every map has the following default panes that differ only in zIndex.
  3519. //
  3520. // @pane mapPane: HTMLElement = 'auto'
  3521. // Pane that contains all other map panes
  3522. this._mapPane = this.createPane('mapPane', this._container);
  3523. setPosition(this._mapPane, new Point(0, 0));
  3524. // @pane tilePane: HTMLElement = 200
  3525. // Pane for `GridLayer`s and `TileLayer`s
  3526. this.createPane('tilePane');
  3527. // @pane overlayPane: HTMLElement = 400
  3528. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  3529. this.createPane('overlayPane');
  3530. // @pane shadowPane: HTMLElement = 500
  3531. // Pane for overlay shadows (e.g. `Marker` shadows)
  3532. this.createPane('shadowPane');
  3533. // @pane markerPane: HTMLElement = 600
  3534. // Pane for `Icon`s of `Marker`s
  3535. this.createPane('markerPane');
  3536. // @pane tooltipPane: HTMLElement = 650
  3537. // Pane for `Tooltip`s.
  3538. this.createPane('tooltipPane');
  3539. // @pane popupPane: HTMLElement = 700
  3540. // Pane for `Popup`s.
  3541. this.createPane('popupPane');
  3542. if (!this.options.markerZoomAnimation) {
  3543. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3544. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3545. }
  3546. },
  3547. // private methods that modify map state
  3548. // @section Map state change events
  3549. _resetView: function (center, zoom, noMoveStart) {
  3550. setPosition(this._mapPane, new Point(0, 0));
  3551. var loading = !this._loaded;
  3552. this._loaded = true;
  3553. zoom = this._limitZoom(zoom);
  3554. this.fire('viewprereset');
  3555. var zoomChanged = this._zoom !== zoom;
  3556. this
  3557. ._moveStart(zoomChanged, noMoveStart)
  3558. ._move(center, zoom)
  3559. ._moveEnd(zoomChanged);
  3560. // @event viewreset: Event
  3561. // Fired when the map needs to redraw its content (this usually happens
  3562. // on map zoom or load). Very useful for creating custom overlays.
  3563. this.fire('viewreset');
  3564. // @event load: Event
  3565. // Fired when the map is initialized (when its center and zoom are set
  3566. // for the first time).
  3567. if (loading) {
  3568. this.fire('load');
  3569. }
  3570. },
  3571. _moveStart: function (zoomChanged, noMoveStart) {
  3572. // @event zoomstart: Event
  3573. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3574. // @event movestart: Event
  3575. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3576. if (zoomChanged) {
  3577. this.fire('zoomstart');
  3578. }
  3579. if (!noMoveStart) {
  3580. this.fire('movestart');
  3581. }
  3582. return this;
  3583. },
  3584. _move: function (center, zoom, data, supressEvent) {
  3585. if (zoom === undefined) {
  3586. zoom = this._zoom;
  3587. }
  3588. var zoomChanged = this._zoom !== zoom;
  3589. this._zoom = zoom;
  3590. this._lastCenter = center;
  3591. this._pixelOrigin = this._getNewPixelOrigin(center);
  3592. if (!supressEvent) {
  3593. // @event zoom: Event
  3594. // Fired repeatedly during any change in zoom level,
  3595. // including zoom and fly animations.
  3596. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3597. this.fire('zoom', data);
  3598. }
  3599. // @event move: Event
  3600. // Fired repeatedly during any movement of the map,
  3601. // including pan and fly animations.
  3602. this.fire('move', data);
  3603. } else if (data && data.pinch) { // Always fire 'zoom' if pinching because #3530
  3604. this.fire('zoom', data);
  3605. }
  3606. return this;
  3607. },
  3608. _moveEnd: function (zoomChanged) {
  3609. // @event zoomend: Event
  3610. // Fired when the map zoom changed, after any animations.
  3611. if (zoomChanged) {
  3612. this.fire('zoomend');
  3613. }
  3614. // @event moveend: Event
  3615. // Fired when the center of the map stops changing
  3616. // (e.g. user stopped dragging the map or after non-centered zoom).
  3617. return this.fire('moveend');
  3618. },
  3619. _stop: function () {
  3620. cancelAnimFrame(this._flyToFrame);
  3621. if (this._panAnim) {
  3622. this._panAnim.stop();
  3623. }
  3624. return this;
  3625. },
  3626. _rawPanBy: function (offset) {
  3627. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3628. },
  3629. _getZoomSpan: function () {
  3630. return this.getMaxZoom() - this.getMinZoom();
  3631. },
  3632. _panInsideMaxBounds: function () {
  3633. if (!this._enforcingBounds) {
  3634. this.panInsideBounds(this.options.maxBounds);
  3635. }
  3636. },
  3637. _checkIfLoaded: function () {
  3638. if (!this._loaded) {
  3639. throw new Error('Set map center and zoom first.');
  3640. }
  3641. },
  3642. // DOM event handling
  3643. // @section Interaction events
  3644. _initEvents: function (remove) {
  3645. this._targets = {};
  3646. this._targets[stamp(this._container)] = this;
  3647. var onOff = remove ? off : on;
  3648. // @event click: MouseEvent
  3649. // Fired when the user clicks (or taps) the map.
  3650. // @event dblclick: MouseEvent
  3651. // Fired when the user double-clicks (or double-taps) the map.
  3652. // @event mousedown: MouseEvent
  3653. // Fired when the user pushes the mouse button on the map.
  3654. // @event mouseup: MouseEvent
  3655. // Fired when the user releases the mouse button on the map.
  3656. // @event mouseover: MouseEvent
  3657. // Fired when the mouse enters the map.
  3658. // @event mouseout: MouseEvent
  3659. // Fired when the mouse leaves the map.
  3660. // @event mousemove: MouseEvent
  3661. // Fired while the mouse moves over the map.
  3662. // @event contextmenu: MouseEvent
  3663. // Fired when the user pushes the right mouse button on the map, prevents
  3664. // default browser context menu from showing if there are listeners on
  3665. // this event. Also fired on mobile when the user holds a single touch
  3666. // for a second (also called long press).
  3667. // @event keypress: KeyboardEvent
  3668. // Fired when the user presses a key from the keyboard that produces a character value while the map is focused.
  3669. // @event keydown: KeyboardEvent
  3670. // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,
  3671. // the `keydown` event is fired for keys that produce a character value and for keys
  3672. // that do not produce a character value.
  3673. // @event keyup: KeyboardEvent
  3674. // Fired when the user releases a key from the keyboard while the map is focused.
  3675. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3676. 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);
  3677. if (this.options.trackResize) {
  3678. onOff(window, 'resize', this._onResize, this);
  3679. }
  3680. if (Browser.any3d && this.options.transform3DLimit) {
  3681. (remove ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3682. }
  3683. },
  3684. _onResize: function () {
  3685. cancelAnimFrame(this._resizeRequest);
  3686. this._resizeRequest = requestAnimFrame(
  3687. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3688. },
  3689. _onScroll: function () {
  3690. this._container.scrollTop = 0;
  3691. this._container.scrollLeft = 0;
  3692. },
  3693. _onMoveEnd: function () {
  3694. var pos = this._getMapPanePos();
  3695. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3696. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3697. // a pixel offset on very high values, see: https://jsfiddle.net/dg6r5hhb/
  3698. this._resetView(this.getCenter(), this.getZoom());
  3699. }
  3700. },
  3701. _findEventTargets: function (e, type) {
  3702. var targets = [],
  3703. target,
  3704. isHover = type === 'mouseout' || type === 'mouseover',
  3705. src = e.target || e.srcElement,
  3706. dragging = false;
  3707. while (src) {
  3708. target = this._targets[stamp(src)];
  3709. if (target && (type === 'click' || type === 'preclick') && this._draggableMoved(target)) {
  3710. // Prevent firing click after you just dragged an object.
  3711. dragging = true;
  3712. break;
  3713. }
  3714. if (target && target.listens(type, true)) {
  3715. if (isHover && !isExternalTarget(src, e)) { break; }
  3716. targets.push(target);
  3717. if (isHover) { break; }
  3718. }
  3719. if (src === this._container) { break; }
  3720. src = src.parentNode;
  3721. }
  3722. if (!targets.length && !dragging && !isHover && this.listens(type, true)) {
  3723. targets = [this];
  3724. }
  3725. return targets;
  3726. },
  3727. _isClickDisabled: function (el) {
  3728. while (el && el !== this._container) {
  3729. if (el['_leaflet_disable_click']) { return true; }
  3730. el = el.parentNode;
  3731. }
  3732. },
  3733. _handleDOMEvent: function (e) {
  3734. var el = (e.target || e.srcElement);
  3735. if (!this._loaded || el['_leaflet_disable_events'] || e.type === 'click' && this._isClickDisabled(el)) {
  3736. return;
  3737. }
  3738. var type = e.type;
  3739. if (type === 'mousedown') {
  3740. // prevents outline when clicking on keyboard-focusable element
  3741. preventOutline(el);
  3742. }
  3743. this._fireDOMEvent(e, type);
  3744. },
  3745. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3746. _fireDOMEvent: function (e, type, canvasTargets) {
  3747. if (e.type === 'click') {
  3748. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3749. // @event preclick: MouseEvent
  3750. // Fired before mouse click on the map (sometimes useful when you
  3751. // want something to happen on click before any existing click
  3752. // handlers start running).
  3753. var synth = extend({}, e);
  3754. synth.type = 'preclick';
  3755. this._fireDOMEvent(synth, synth.type, canvasTargets);
  3756. }
  3757. // Find the layer the event is propagating from and its parents.
  3758. var targets = this._findEventTargets(e, type);
  3759. if (canvasTargets) {
  3760. var filtered = []; // pick only targets with listeners
  3761. for (var i = 0; i < canvasTargets.length; i++) {
  3762. if (canvasTargets[i].listens(type, true)) {
  3763. filtered.push(canvasTargets[i]);
  3764. }
  3765. }
  3766. targets = filtered.concat(targets);
  3767. }
  3768. if (!targets.length) { return; }
  3769. if (type === 'contextmenu') {
  3770. preventDefault(e);
  3771. }
  3772. var target = targets[0];
  3773. var data = {
  3774. originalEvent: e
  3775. };
  3776. if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {
  3777. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  3778. data.containerPoint = isMarker ?
  3779. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3780. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3781. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3782. }
  3783. for (i = 0; i < targets.length; i++) {
  3784. targets[i].fire(type, data, true);
  3785. if (data.originalEvent._stopped ||
  3786. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3787. }
  3788. },
  3789. _draggableMoved: function (obj) {
  3790. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3791. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3792. },
  3793. _clearHandlers: function () {
  3794. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3795. this._handlers[i].disable();
  3796. }
  3797. },
  3798. // @section Other Methods
  3799. // @method whenReady(fn: Function, context?: Object): this
  3800. // Runs the given function `fn` when the map gets initialized with
  3801. // a view (center and zoom) and at least one layer, or immediately
  3802. // if it's already initialized, optionally passing a function context.
  3803. whenReady: function (callback, context) {
  3804. if (this._loaded) {
  3805. callback.call(context || this, {target: this});
  3806. } else {
  3807. this.on('load', callback, context);
  3808. }
  3809. return this;
  3810. },
  3811. // private methods for getting map state
  3812. _getMapPanePos: function () {
  3813. return getPosition(this._mapPane) || new Point(0, 0);
  3814. },
  3815. _moved: function () {
  3816. var pos = this._getMapPanePos();
  3817. return pos && !pos.equals([0, 0]);
  3818. },
  3819. _getTopLeftPoint: function (center, zoom) {
  3820. var pixelOrigin = center && zoom !== undefined ?
  3821. this._getNewPixelOrigin(center, zoom) :
  3822. this.getPixelOrigin();
  3823. return pixelOrigin.subtract(this._getMapPanePos());
  3824. },
  3825. _getNewPixelOrigin: function (center, zoom) {
  3826. var viewHalf = this.getSize()._divideBy(2);
  3827. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3828. },
  3829. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3830. var topLeft = this._getNewPixelOrigin(center, zoom);
  3831. return this.project(latlng, zoom)._subtract(topLeft);
  3832. },
  3833. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3834. var topLeft = this._getNewPixelOrigin(center, zoom);
  3835. return toBounds([
  3836. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3837. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3838. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3839. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3840. ]);
  3841. },
  3842. // layer point of the current center
  3843. _getCenterLayerPoint: function () {
  3844. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3845. },
  3846. // offset of the specified place to the current center in pixels
  3847. _getCenterOffset: function (latlng) {
  3848. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3849. },
  3850. // adjust center for view to get inside bounds
  3851. _limitCenter: function (center, zoom, bounds) {
  3852. if (!bounds) { return center; }
  3853. var centerPoint = this.project(center, zoom),
  3854. viewHalf = this.getSize().divideBy(2),
  3855. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3856. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3857. // If offset is less than a pixel, ignore.
  3858. // This prevents unstable projections from getting into
  3859. // an infinite loop of tiny offsets.
  3860. if (Math.abs(offset.x) <= 1 && Math.abs(offset.y) <= 1) {
  3861. return center;
  3862. }
  3863. return this.unproject(centerPoint.add(offset), zoom);
  3864. },
  3865. // adjust offset for view to get inside bounds
  3866. _limitOffset: function (offset, bounds) {
  3867. if (!bounds) { return offset; }
  3868. var viewBounds = this.getPixelBounds(),
  3869. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3870. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3871. },
  3872. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3873. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3874. var projectedMaxBounds = toBounds(
  3875. this.project(maxBounds.getNorthEast(), zoom),
  3876. this.project(maxBounds.getSouthWest(), zoom)
  3877. ),
  3878. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3879. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3880. dx = this._rebound(minOffset.x, -maxOffset.x),
  3881. dy = this._rebound(minOffset.y, -maxOffset.y);
  3882. return new Point(dx, dy);
  3883. },
  3884. _rebound: function (left, right) {
  3885. return left + right > 0 ?
  3886. Math.round(left - right) / 2 :
  3887. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3888. },
  3889. _limitZoom: function (zoom) {
  3890. var min = this.getMinZoom(),
  3891. max = this.getMaxZoom(),
  3892. snap = Browser.any3d ? this.options.zoomSnap : 1;
  3893. if (snap) {
  3894. zoom = Math.round(zoom / snap) * snap;
  3895. }
  3896. return Math.max(min, Math.min(max, zoom));
  3897. },
  3898. _onPanTransitionStep: function () {
  3899. this.fire('move');
  3900. },
  3901. _onPanTransitionEnd: function () {
  3902. removeClass(this._mapPane, 'leaflet-pan-anim');
  3903. this.fire('moveend');
  3904. },
  3905. _tryAnimatedPan: function (center, options) {
  3906. // difference between the new and current centers in pixels
  3907. var offset = this._getCenterOffset(center)._trunc();
  3908. // don't animate too far unless animate: true specified in options
  3909. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3910. this.panBy(offset, options);
  3911. return true;
  3912. },
  3913. _createAnimProxy: function () {
  3914. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3915. this._panes.mapPane.appendChild(proxy);
  3916. this.on('zoomanim', function (e) {
  3917. var prop = TRANSFORM,
  3918. transform = this._proxy.style[prop];
  3919. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3920. // workaround for case when transform is the same and so transitionend event is not fired
  3921. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3922. this._onZoomTransitionEnd();
  3923. }
  3924. }, this);
  3925. this.on('load moveend', this._animMoveEnd, this);
  3926. this._on('unload', this._destroyAnimProxy, this);
  3927. },
  3928. _destroyAnimProxy: function () {
  3929. remove(this._proxy);
  3930. this.off('load moveend', this._animMoveEnd, this);
  3931. delete this._proxy;
  3932. },
  3933. _animMoveEnd: function () {
  3934. var c = this.getCenter(),
  3935. z = this.getZoom();
  3936. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3937. },
  3938. _catchTransitionEnd: function (e) {
  3939. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3940. this._onZoomTransitionEnd();
  3941. }
  3942. },
  3943. _nothingToAnimate: function () {
  3944. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3945. },
  3946. _tryAnimatedZoom: function (center, zoom, options) {
  3947. if (this._animatingZoom) { return true; }
  3948. options = options || {};
  3949. // don't animate if disabled, not supported or zoom difference is too large
  3950. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3951. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3952. // offset is the pixel coords of the zoom origin relative to the current center
  3953. var scale = this.getZoomScale(zoom),
  3954. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3955. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3956. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3957. requestAnimFrame(function () {
  3958. this
  3959. ._moveStart(true, options.noMoveStart || false)
  3960. ._animateZoom(center, zoom, true);
  3961. }, this);
  3962. return true;
  3963. },
  3964. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3965. if (!this._mapPane) { return; }
  3966. if (startAnim) {
  3967. this._animatingZoom = true;
  3968. // remember what center/zoom to set after animation
  3969. this._animateToCenter = center;
  3970. this._animateToZoom = zoom;
  3971. addClass(this._mapPane, 'leaflet-zoom-anim');
  3972. }
  3973. // @section Other Events
  3974. // @event zoomanim: ZoomAnimEvent
  3975. // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
  3976. this.fire('zoomanim', {
  3977. center: center,
  3978. zoom: zoom,
  3979. noUpdate: noUpdate
  3980. });
  3981. if (!this._tempFireZoomEvent) {
  3982. this._tempFireZoomEvent = this._zoom !== this._animateToZoom;
  3983. }
  3984. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  3985. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3986. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3987. },
  3988. _onZoomTransitionEnd: function () {
  3989. if (!this._animatingZoom) { return; }
  3990. if (this._mapPane) {
  3991. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3992. }
  3993. this._animatingZoom = false;
  3994. this._move(this._animateToCenter, this._animateToZoom, undefined, true);
  3995. if (this._tempFireZoomEvent) {
  3996. this.fire('zoom');
  3997. }
  3998. delete this._tempFireZoomEvent;
  3999. this.fire('move');
  4000. this._moveEnd(true);
  4001. }
  4002. });
  4003. // @section
  4004. // @factory L.map(id: String, options?: Map options)
  4005. // Instantiates a map object given the DOM ID of a `<div>` element
  4006. // and optionally an object literal with `Map options`.
  4007. //
  4008. // @alternative
  4009. // @factory L.map(el: HTMLElement, options?: Map options)
  4010. // Instantiates a map object given an instance of a `<div>` HTML element
  4011. // and optionally an object literal with `Map options`.
  4012. function createMap(id, options) {
  4013. return new Map(id, options);
  4014. }
  4015. /*
  4016. * @class Control
  4017. * @aka L.Control
  4018. * @inherits Class
  4019. *
  4020. * L.Control is a base class for implementing map controls. Handles positioning.
  4021. * All other controls extend from this class.
  4022. */
  4023. var Control = Class.extend({
  4024. // @section
  4025. // @aka Control Options
  4026. options: {
  4027. // @option position: String = 'topright'
  4028. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  4029. // `'topright'`, `'bottomleft'` or `'bottomright'`
  4030. position: 'topright'
  4031. },
  4032. initialize: function (options) {
  4033. setOptions(this, options);
  4034. },
  4035. /* @section
  4036. * Classes extending L.Control will inherit the following methods:
  4037. *
  4038. * @method getPosition: string
  4039. * Returns the position of the control.
  4040. */
  4041. getPosition: function () {
  4042. return this.options.position;
  4043. },
  4044. // @method setPosition(position: string): this
  4045. // Sets the position of the control.
  4046. setPosition: function (position) {
  4047. var map = this._map;
  4048. if (map) {
  4049. map.removeControl(this);
  4050. }
  4051. this.options.position = position;
  4052. if (map) {
  4053. map.addControl(this);
  4054. }
  4055. return this;
  4056. },
  4057. // @method getContainer: HTMLElement
  4058. // Returns the HTMLElement that contains the control.
  4059. getContainer: function () {
  4060. return this._container;
  4061. },
  4062. // @method addTo(map: Map): this
  4063. // Adds the control to the given map.
  4064. addTo: function (map) {
  4065. this.remove();
  4066. this._map = map;
  4067. var container = this._container = this.onAdd(map),
  4068. pos = this.getPosition(),
  4069. corner = map._controlCorners[pos];
  4070. addClass(container, 'leaflet-control');
  4071. if (pos.indexOf('bottom') !== -1) {
  4072. corner.insertBefore(container, corner.firstChild);
  4073. } else {
  4074. corner.appendChild(container);
  4075. }
  4076. this._map.on('unload', this.remove, this);
  4077. return this;
  4078. },
  4079. // @method remove: this
  4080. // Removes the control from the map it is currently active on.
  4081. remove: function () {
  4082. if (!this._map) {
  4083. return this;
  4084. }
  4085. remove(this._container);
  4086. if (this.onRemove) {
  4087. this.onRemove(this._map);
  4088. }
  4089. this._map.off('unload', this.remove, this);
  4090. this._map = null;
  4091. return this;
  4092. },
  4093. _refocusOnMap: function (e) {
  4094. // if map exists and event is not a keyboard event
  4095. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  4096. this._map.getContainer().focus();
  4097. }
  4098. }
  4099. });
  4100. var control = function (options) {
  4101. return new Control(options);
  4102. };
  4103. /* @section Extension methods
  4104. * @uninheritable
  4105. *
  4106. * Every control should extend from `L.Control` and (re-)implement the following methods.
  4107. *
  4108. * @method onAdd(map: Map): HTMLElement
  4109. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  4110. *
  4111. * @method onRemove(map: Map)
  4112. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  4113. */
  4114. /* @namespace Map
  4115. * @section Methods for Layers and Controls
  4116. */
  4117. Map.include({
  4118. // @method addControl(control: Control): this
  4119. // Adds the given control to the map
  4120. addControl: function (control) {
  4121. control.addTo(this);
  4122. return this;
  4123. },
  4124. // @method removeControl(control: Control): this
  4125. // Removes the given control from the map
  4126. removeControl: function (control) {
  4127. control.remove();
  4128. return this;
  4129. },
  4130. _initControlPos: function () {
  4131. var corners = this._controlCorners = {},
  4132. l = 'leaflet-',
  4133. container = this._controlContainer =
  4134. create$1('div', l + 'control-container', this._container);
  4135. function createCorner(vSide, hSide) {
  4136. var className = l + vSide + ' ' + l + hSide;
  4137. corners[vSide + hSide] = create$1('div', className, container);
  4138. }
  4139. createCorner('top', 'left');
  4140. createCorner('top', 'right');
  4141. createCorner('bottom', 'left');
  4142. createCorner('bottom', 'right');
  4143. },
  4144. _clearControlPos: function () {
  4145. for (var i in this._controlCorners) {
  4146. remove(this._controlCorners[i]);
  4147. }
  4148. remove(this._controlContainer);
  4149. delete this._controlCorners;
  4150. delete this._controlContainer;
  4151. }
  4152. });
  4153. /*
  4154. * @class Control.Layers
  4155. * @aka L.Control.Layers
  4156. * @inherits Control
  4157. *
  4158. * 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`.
  4159. *
  4160. * @example
  4161. *
  4162. * ```js
  4163. * var baseLayers = {
  4164. * "Mapbox": mapbox,
  4165. * "OpenStreetMap": osm
  4166. * };
  4167. *
  4168. * var overlays = {
  4169. * "Marker": marker,
  4170. * "Roads": roadsLayer
  4171. * };
  4172. *
  4173. * L.control.layers(baseLayers, overlays).addTo(map);
  4174. * ```
  4175. *
  4176. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  4177. *
  4178. * ```js
  4179. * {
  4180. * "<someName1>": layer1,
  4181. * "<someName2>": layer2
  4182. * }
  4183. * ```
  4184. *
  4185. * The layer names can contain HTML, which allows you to add additional styling to the items:
  4186. *
  4187. * ```js
  4188. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  4189. * ```
  4190. */
  4191. var Layers = Control.extend({
  4192. // @section
  4193. // @aka Control.Layers options
  4194. options: {
  4195. // @option collapsed: Boolean = true
  4196. // If `true`, the control will be collapsed into an icon and expanded on mouse hover, touch, or keyboard activation.
  4197. collapsed: true,
  4198. position: 'topright',
  4199. // @option autoZIndex: Boolean = true
  4200. // 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.
  4201. autoZIndex: true,
  4202. // @option hideSingleBase: Boolean = false
  4203. // If `true`, the base layers in the control will be hidden when there is only one.
  4204. hideSingleBase: false,
  4205. // @option sortLayers: Boolean = false
  4206. // Whether to sort the layers. When `false`, layers will keep the order
  4207. // in which they were added to the control.
  4208. sortLayers: false,
  4209. // @option sortFunction: Function = *
  4210. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  4211. // that will be used for sorting the layers, when `sortLayers` is `true`.
  4212. // The function receives both the `L.Layer` instances and their names, as in
  4213. // `sortFunction(layerA, layerB, nameA, nameB)`.
  4214. // By default, it sorts layers alphabetically by their name.
  4215. sortFunction: function (layerA, layerB, nameA, nameB) {
  4216. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  4217. }
  4218. },
  4219. initialize: function (baseLayers, overlays, options) {
  4220. setOptions(this, options);
  4221. this._layerControlInputs = [];
  4222. this._layers = [];
  4223. this._lastZIndex = 0;
  4224. this._handlingClick = false;
  4225. this._preventClick = false;
  4226. for (var i in baseLayers) {
  4227. this._addLayer(baseLayers[i], i);
  4228. }
  4229. for (i in overlays) {
  4230. this._addLayer(overlays[i], i, true);
  4231. }
  4232. },
  4233. onAdd: function (map) {
  4234. this._initLayout();
  4235. this._update();
  4236. this._map = map;
  4237. map.on('zoomend', this._checkDisabledLayers, this);
  4238. for (var i = 0; i < this._layers.length; i++) {
  4239. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4240. }
  4241. return this._container;
  4242. },
  4243. addTo: function (map) {
  4244. Control.prototype.addTo.call(this, map);
  4245. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4246. return this._expandIfNotCollapsed();
  4247. },
  4248. onRemove: function () {
  4249. this._map.off('zoomend', this._checkDisabledLayers, this);
  4250. for (var i = 0; i < this._layers.length; i++) {
  4251. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4252. }
  4253. },
  4254. // @method addBaseLayer(layer: Layer, name: String): this
  4255. // Adds a base layer (radio button entry) with the given name to the control.
  4256. addBaseLayer: function (layer, name) {
  4257. this._addLayer(layer, name);
  4258. return (this._map) ? this._update() : this;
  4259. },
  4260. // @method addOverlay(layer: Layer, name: String): this
  4261. // Adds an overlay (checkbox entry) with the given name to the control.
  4262. addOverlay: function (layer, name) {
  4263. this._addLayer(layer, name, true);
  4264. return (this._map) ? this._update() : this;
  4265. },
  4266. // @method removeLayer(layer: Layer): this
  4267. // Remove the given layer from the control.
  4268. removeLayer: function (layer) {
  4269. layer.off('add remove', this._onLayerChange, this);
  4270. var obj = this._getLayer(stamp(layer));
  4271. if (obj) {
  4272. this._layers.splice(this._layers.indexOf(obj), 1);
  4273. }
  4274. return (this._map) ? this._update() : this;
  4275. },
  4276. // @method expand(): this
  4277. // Expand the control container if collapsed.
  4278. expand: function () {
  4279. addClass(this._container, 'leaflet-control-layers-expanded');
  4280. this._section.style.height = null;
  4281. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4282. if (acceptableHeight < this._section.clientHeight) {
  4283. addClass(this._section, 'leaflet-control-layers-scrollbar');
  4284. this._section.style.height = acceptableHeight + 'px';
  4285. } else {
  4286. removeClass(this._section, 'leaflet-control-layers-scrollbar');
  4287. }
  4288. this._checkDisabledLayers();
  4289. return this;
  4290. },
  4291. // @method collapse(): this
  4292. // Collapse the control container if expanded.
  4293. collapse: function () {
  4294. removeClass(this._container, 'leaflet-control-layers-expanded');
  4295. return this;
  4296. },
  4297. _initLayout: function () {
  4298. var className = 'leaflet-control-layers',
  4299. container = this._container = create$1('div', className),
  4300. collapsed = this.options.collapsed;
  4301. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4302. container.setAttribute('aria-haspopup', true);
  4303. disableClickPropagation(container);
  4304. disableScrollPropagation(container);
  4305. var section = this._section = create$1('section', className + '-list');
  4306. if (collapsed) {
  4307. this._map.on('click', this.collapse, this);
  4308. on(container, {
  4309. mouseenter: this._expandSafely,
  4310. mouseleave: this.collapse
  4311. }, this);
  4312. }
  4313. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4314. link.href = '#';
  4315. link.title = 'Layers';
  4316. link.setAttribute('role', 'button');
  4317. on(link, {
  4318. keydown: function (e) {
  4319. if (e.keyCode === 13) {
  4320. this._expandSafely();
  4321. }
  4322. },
  4323. // Certain screen readers intercept the key event and instead send a click event
  4324. click: function (e) {
  4325. preventDefault(e);
  4326. this._expandSafely();
  4327. }
  4328. }, this);
  4329. if (!collapsed) {
  4330. this.expand();
  4331. }
  4332. this._baseLayersList = create$1('div', className + '-base', section);
  4333. this._separator = create$1('div', className + '-separator', section);
  4334. this._overlaysList = create$1('div', className + '-overlays', section);
  4335. container.appendChild(section);
  4336. },
  4337. _getLayer: function (id) {
  4338. for (var i = 0; i < this._layers.length; i++) {
  4339. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4340. return this._layers[i];
  4341. }
  4342. }
  4343. },
  4344. _addLayer: function (layer, name, overlay) {
  4345. if (this._map) {
  4346. layer.on('add remove', this._onLayerChange, this);
  4347. }
  4348. this._layers.push({
  4349. layer: layer,
  4350. name: name,
  4351. overlay: overlay
  4352. });
  4353. if (this.options.sortLayers) {
  4354. this._layers.sort(bind(function (a, b) {
  4355. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4356. }, this));
  4357. }
  4358. if (this.options.autoZIndex && layer.setZIndex) {
  4359. this._lastZIndex++;
  4360. layer.setZIndex(this._lastZIndex);
  4361. }
  4362. this._expandIfNotCollapsed();
  4363. },
  4364. _update: function () {
  4365. if (!this._container) { return this; }
  4366. empty(this._baseLayersList);
  4367. empty(this._overlaysList);
  4368. this._layerControlInputs = [];
  4369. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4370. for (i = 0; i < this._layers.length; i++) {
  4371. obj = this._layers[i];
  4372. this._addItem(obj);
  4373. overlaysPresent = overlaysPresent || obj.overlay;
  4374. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4375. baseLayersCount += !obj.overlay ? 1 : 0;
  4376. }
  4377. // Hide base layers section if there's only one layer.
  4378. if (this.options.hideSingleBase) {
  4379. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4380. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4381. }
  4382. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4383. return this;
  4384. },
  4385. _onLayerChange: function (e) {
  4386. if (!this._handlingClick) {
  4387. this._update();
  4388. }
  4389. var obj = this._getLayer(stamp(e.target));
  4390. // @namespace Map
  4391. // @section Layer events
  4392. // @event baselayerchange: LayersControlEvent
  4393. // Fired when the base layer is changed through the [layers control](#control-layers).
  4394. // @event overlayadd: LayersControlEvent
  4395. // Fired when an overlay is selected through the [layers control](#control-layers).
  4396. // @event overlayremove: LayersControlEvent
  4397. // Fired when an overlay is deselected through the [layers control](#control-layers).
  4398. // @namespace Control.Layers
  4399. var type = obj.overlay ?
  4400. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4401. (e.type === 'add' ? 'baselayerchange' : null);
  4402. if (type) {
  4403. this._map.fire(type, obj);
  4404. }
  4405. },
  4406. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see https://stackoverflow.com/a/119079)
  4407. _createRadioElement: function (name, checked) {
  4408. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4409. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4410. var radioFragment = document.createElement('div');
  4411. radioFragment.innerHTML = radioHtml;
  4412. return radioFragment.firstChild;
  4413. },
  4414. _addItem: function (obj) {
  4415. var label = document.createElement('label'),
  4416. checked = this._map.hasLayer(obj.layer),
  4417. input;
  4418. if (obj.overlay) {
  4419. input = document.createElement('input');
  4420. input.type = 'checkbox';
  4421. input.className = 'leaflet-control-layers-selector';
  4422. input.defaultChecked = checked;
  4423. } else {
  4424. input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);
  4425. }
  4426. this._layerControlInputs.push(input);
  4427. input.layerId = stamp(obj.layer);
  4428. on(input, 'click', this._onInputClick, this);
  4429. var name = document.createElement('span');
  4430. name.innerHTML = ' ' + obj.name;
  4431. // Helps from preventing layer control flicker when checkboxes are disabled
  4432. // https://github.com/Leaflet/Leaflet/issues/2771
  4433. var holder = document.createElement('span');
  4434. label.appendChild(holder);
  4435. holder.appendChild(input);
  4436. holder.appendChild(name);
  4437. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4438. container.appendChild(label);
  4439. this._checkDisabledLayers();
  4440. return label;
  4441. },
  4442. _onInputClick: function () {
  4443. // expanding the control on mobile with a click can cause adding a layer - we don't want this
  4444. if (this._preventClick) {
  4445. return;
  4446. }
  4447. var inputs = this._layerControlInputs,
  4448. input, layer;
  4449. var addedLayers = [],
  4450. removedLayers = [];
  4451. this._handlingClick = true;
  4452. for (var i = inputs.length - 1; i >= 0; i--) {
  4453. input = inputs[i];
  4454. layer = this._getLayer(input.layerId).layer;
  4455. if (input.checked) {
  4456. addedLayers.push(layer);
  4457. } else if (!input.checked) {
  4458. removedLayers.push(layer);
  4459. }
  4460. }
  4461. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4462. for (i = 0; i < removedLayers.length; i++) {
  4463. if (this._map.hasLayer(removedLayers[i])) {
  4464. this._map.removeLayer(removedLayers[i]);
  4465. }
  4466. }
  4467. for (i = 0; i < addedLayers.length; i++) {
  4468. if (!this._map.hasLayer(addedLayers[i])) {
  4469. this._map.addLayer(addedLayers[i]);
  4470. }
  4471. }
  4472. this._handlingClick = false;
  4473. this._refocusOnMap();
  4474. },
  4475. _checkDisabledLayers: function () {
  4476. var inputs = this._layerControlInputs,
  4477. input,
  4478. layer,
  4479. zoom = this._map.getZoom();
  4480. for (var i = inputs.length - 1; i >= 0; i--) {
  4481. input = inputs[i];
  4482. layer = this._getLayer(input.layerId).layer;
  4483. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4484. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4485. }
  4486. },
  4487. _expandIfNotCollapsed: function () {
  4488. if (this._map && !this.options.collapsed) {
  4489. this.expand();
  4490. }
  4491. return this;
  4492. },
  4493. _expandSafely: function () {
  4494. var section = this._section;
  4495. this._preventClick = true;
  4496. on(section, 'click', preventDefault);
  4497. this.expand();
  4498. var that = this;
  4499. setTimeout(function () {
  4500. off(section, 'click', preventDefault);
  4501. that._preventClick = false;
  4502. });
  4503. }
  4504. });
  4505. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4506. // 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.
  4507. var layers = function (baseLayers, overlays, options) {
  4508. return new Layers(baseLayers, overlays, options);
  4509. };
  4510. /*
  4511. * @class Control.Zoom
  4512. * @aka L.Control.Zoom
  4513. * @inherits Control
  4514. *
  4515. * 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`.
  4516. */
  4517. var Zoom = Control.extend({
  4518. // @section
  4519. // @aka Control.Zoom options
  4520. options: {
  4521. position: 'topleft',
  4522. // @option zoomInText: String = '<span aria-hidden="true">+</span>'
  4523. // The text set on the 'zoom in' button.
  4524. zoomInText: '<span aria-hidden="true">+</span>',
  4525. // @option zoomInTitle: String = 'Zoom in'
  4526. // The title set on the 'zoom in' button.
  4527. zoomInTitle: 'Zoom in',
  4528. // @option zoomOutText: String = '<span aria-hidden="true">&#x2212;</span>'
  4529. // The text set on the 'zoom out' button.
  4530. zoomOutText: '<span aria-hidden="true">&#x2212;</span>',
  4531. // @option zoomOutTitle: String = 'Zoom out'
  4532. // The title set on the 'zoom out' button.
  4533. zoomOutTitle: 'Zoom out'
  4534. },
  4535. onAdd: function (map) {
  4536. var zoomName = 'leaflet-control-zoom',
  4537. container = create$1('div', zoomName + ' leaflet-bar'),
  4538. options = this.options;
  4539. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4540. zoomName + '-in', container, this._zoomIn);
  4541. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4542. zoomName + '-out', container, this._zoomOut);
  4543. this._updateDisabled();
  4544. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4545. return container;
  4546. },
  4547. onRemove: function (map) {
  4548. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4549. },
  4550. disable: function () {
  4551. this._disabled = true;
  4552. this._updateDisabled();
  4553. return this;
  4554. },
  4555. enable: function () {
  4556. this._disabled = false;
  4557. this._updateDisabled();
  4558. return this;
  4559. },
  4560. _zoomIn: function (e) {
  4561. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4562. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4563. }
  4564. },
  4565. _zoomOut: function (e) {
  4566. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4567. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4568. }
  4569. },
  4570. _createButton: function (html, title, className, container, fn) {
  4571. var link = create$1('a', className, container);
  4572. link.innerHTML = html;
  4573. link.href = '#';
  4574. link.title = title;
  4575. /*
  4576. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4577. */
  4578. link.setAttribute('role', 'button');
  4579. link.setAttribute('aria-label', title);
  4580. disableClickPropagation(link);
  4581. on(link, 'click', stop);
  4582. on(link, 'click', fn, this);
  4583. on(link, 'click', this._refocusOnMap, this);
  4584. return link;
  4585. },
  4586. _updateDisabled: function () {
  4587. var map = this._map,
  4588. className = 'leaflet-disabled';
  4589. removeClass(this._zoomInButton, className);
  4590. removeClass(this._zoomOutButton, className);
  4591. this._zoomInButton.setAttribute('aria-disabled', 'false');
  4592. this._zoomOutButton.setAttribute('aria-disabled', 'false');
  4593. if (this._disabled || map._zoom === map.getMinZoom()) {
  4594. addClass(this._zoomOutButton, className);
  4595. this._zoomOutButton.setAttribute('aria-disabled', 'true');
  4596. }
  4597. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4598. addClass(this._zoomInButton, className);
  4599. this._zoomInButton.setAttribute('aria-disabled', 'true');
  4600. }
  4601. }
  4602. });
  4603. // @namespace Map
  4604. // @section Control options
  4605. // @option zoomControl: Boolean = true
  4606. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4607. Map.mergeOptions({
  4608. zoomControl: true
  4609. });
  4610. Map.addInitHook(function () {
  4611. if (this.options.zoomControl) {
  4612. // @section Controls
  4613. // @property zoomControl: Control.Zoom
  4614. // The default zoom control (only available if the
  4615. // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
  4616. this.zoomControl = new Zoom();
  4617. this.addControl(this.zoomControl);
  4618. }
  4619. });
  4620. // @namespace Control.Zoom
  4621. // @factory L.control.zoom(options: Control.Zoom options)
  4622. // Creates a zoom control
  4623. var zoom = function (options) {
  4624. return new Zoom(options);
  4625. };
  4626. /*
  4627. * @class Control.Scale
  4628. * @aka L.Control.Scale
  4629. * @inherits Control
  4630. *
  4631. * 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`.
  4632. *
  4633. * @example
  4634. *
  4635. * ```js
  4636. * L.control.scale().addTo(map);
  4637. * ```
  4638. */
  4639. var Scale = Control.extend({
  4640. // @section
  4641. // @aka Control.Scale options
  4642. options: {
  4643. position: 'bottomleft',
  4644. // @option maxWidth: Number = 100
  4645. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4646. maxWidth: 100,
  4647. // @option metric: Boolean = True
  4648. // Whether to show the metric scale line (m/km).
  4649. metric: true,
  4650. // @option imperial: Boolean = True
  4651. // Whether to show the imperial scale line (mi/ft).
  4652. imperial: true
  4653. // @option updateWhenIdle: Boolean = false
  4654. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4655. },
  4656. onAdd: function (map) {
  4657. var className = 'leaflet-control-scale',
  4658. container = create$1('div', className),
  4659. options = this.options;
  4660. this._addScales(options, className + '-line', container);
  4661. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4662. map.whenReady(this._update, this);
  4663. return container;
  4664. },
  4665. onRemove: function (map) {
  4666. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4667. },
  4668. _addScales: function (options, className, container) {
  4669. if (options.metric) {
  4670. this._mScale = create$1('div', className, container);
  4671. }
  4672. if (options.imperial) {
  4673. this._iScale = create$1('div', className, container);
  4674. }
  4675. },
  4676. _update: function () {
  4677. var map = this._map,
  4678. y = map.getSize().y / 2;
  4679. var maxMeters = map.distance(
  4680. map.containerPointToLatLng([0, y]),
  4681. map.containerPointToLatLng([this.options.maxWidth, y]));
  4682. this._updateScales(maxMeters);
  4683. },
  4684. _updateScales: function (maxMeters) {
  4685. if (this.options.metric && maxMeters) {
  4686. this._updateMetric(maxMeters);
  4687. }
  4688. if (this.options.imperial && maxMeters) {
  4689. this._updateImperial(maxMeters);
  4690. }
  4691. },
  4692. _updateMetric: function (maxMeters) {
  4693. var meters = this._getRoundNum(maxMeters),
  4694. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4695. this._updateScale(this._mScale, label, meters / maxMeters);
  4696. },
  4697. _updateImperial: function (maxMeters) {
  4698. var maxFeet = maxMeters * 3.2808399,
  4699. maxMiles, miles, feet;
  4700. if (maxFeet > 5280) {
  4701. maxMiles = maxFeet / 5280;
  4702. miles = this._getRoundNum(maxMiles);
  4703. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4704. } else {
  4705. feet = this._getRoundNum(maxFeet);
  4706. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4707. }
  4708. },
  4709. _updateScale: function (scale, text, ratio) {
  4710. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4711. scale.innerHTML = text;
  4712. },
  4713. _getRoundNum: function (num) {
  4714. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4715. d = num / pow10;
  4716. d = d >= 10 ? 10 :
  4717. d >= 5 ? 5 :
  4718. d >= 3 ? 3 :
  4719. d >= 2 ? 2 : 1;
  4720. return pow10 * d;
  4721. }
  4722. });
  4723. // @factory L.control.scale(options?: Control.Scale options)
  4724. // Creates an scale control with the given options.
  4725. var scale = function (options) {
  4726. return new Scale(options);
  4727. };
  4728. 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>';
  4729. /*
  4730. * @class Control.Attribution
  4731. * @aka L.Control.Attribution
  4732. * @inherits Control
  4733. *
  4734. * 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.
  4735. */
  4736. var Attribution = Control.extend({
  4737. // @section
  4738. // @aka Control.Attribution options
  4739. options: {
  4740. position: 'bottomright',
  4741. // @option prefix: String|false = 'Leaflet'
  4742. // The HTML text shown before the attributions. Pass `false` to disable.
  4743. prefix: '<a href="https://leafletjs.com" title="A JavaScript library for interactive maps">' + (Browser.inlineSvg ? ukrainianFlag + ' ' : '') + 'Leaflet</a>'
  4744. },
  4745. initialize: function (options) {
  4746. setOptions(this, options);
  4747. this._attributions = {};
  4748. },
  4749. onAdd: function (map) {
  4750. map.attributionControl = this;
  4751. this._container = create$1('div', 'leaflet-control-attribution');
  4752. disableClickPropagation(this._container);
  4753. // TODO ugly, refactor
  4754. for (var i in map._layers) {
  4755. if (map._layers[i].getAttribution) {
  4756. this.addAttribution(map._layers[i].getAttribution());
  4757. }
  4758. }
  4759. this._update();
  4760. map.on('layeradd', this._addAttribution, this);
  4761. return this._container;
  4762. },
  4763. onRemove: function (map) {
  4764. map.off('layeradd', this._addAttribution, this);
  4765. },
  4766. _addAttribution: function (ev) {
  4767. if (ev.layer.getAttribution) {
  4768. this.addAttribution(ev.layer.getAttribution());
  4769. ev.layer.once('remove', function () {
  4770. this.removeAttribution(ev.layer.getAttribution());
  4771. }, this);
  4772. }
  4773. },
  4774. // @method setPrefix(prefix: String|false): this
  4775. // The HTML text shown before the attributions. Pass `false` to disable.
  4776. setPrefix: function (prefix) {
  4777. this.options.prefix = prefix;
  4778. this._update();
  4779. return this;
  4780. },
  4781. // @method addAttribution(text: String): this
  4782. // Adds an attribution text (e.g. `'&copy; OpenStreetMap contributors'`).
  4783. addAttribution: function (text) {
  4784. if (!text) { return this; }
  4785. if (!this._attributions[text]) {
  4786. this._attributions[text] = 0;
  4787. }
  4788. this._attributions[text]++;
  4789. this._update();
  4790. return this;
  4791. },
  4792. // @method removeAttribution(text: String): this
  4793. // Removes an attribution text.
  4794. removeAttribution: function (text) {
  4795. if (!text) { return this; }
  4796. if (this._attributions[text]) {
  4797. this._attributions[text]--;
  4798. this._update();
  4799. }
  4800. return this;
  4801. },
  4802. _update: function () {
  4803. if (!this._map) { return; }
  4804. var attribs = [];
  4805. for (var i in this._attributions) {
  4806. if (this._attributions[i]) {
  4807. attribs.push(i);
  4808. }
  4809. }
  4810. var prefixAndAttribs = [];
  4811. if (this.options.prefix) {
  4812. prefixAndAttribs.push(this.options.prefix);
  4813. }
  4814. if (attribs.length) {
  4815. prefixAndAttribs.push(attribs.join(', '));
  4816. }
  4817. this._container.innerHTML = prefixAndAttribs.join(' <span aria-hidden="true">|</span> ');
  4818. }
  4819. });
  4820. // @namespace Map
  4821. // @section Control options
  4822. // @option attributionControl: Boolean = true
  4823. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4824. Map.mergeOptions({
  4825. attributionControl: true
  4826. });
  4827. Map.addInitHook(function () {
  4828. if (this.options.attributionControl) {
  4829. new Attribution().addTo(this);
  4830. }
  4831. });
  4832. // @namespace Control.Attribution
  4833. // @factory L.control.attribution(options: Control.Attribution options)
  4834. // Creates an attribution control.
  4835. var attribution = function (options) {
  4836. return new Attribution(options);
  4837. };
  4838. Control.Layers = Layers;
  4839. Control.Zoom = Zoom;
  4840. Control.Scale = Scale;
  4841. Control.Attribution = Attribution;
  4842. control.layers = layers;
  4843. control.zoom = zoom;
  4844. control.scale = scale;
  4845. control.attribution = attribution;
  4846. /*
  4847. L.Handler is a base class for handler classes that are used internally to inject
  4848. interaction features like dragging to classes like Map and Marker.
  4849. */
  4850. // @class Handler
  4851. // @aka L.Handler
  4852. // Abstract class for map interaction handlers
  4853. var Handler = Class.extend({
  4854. initialize: function (map) {
  4855. this._map = map;
  4856. },
  4857. // @method enable(): this
  4858. // Enables the handler
  4859. enable: function () {
  4860. if (this._enabled) { return this; }
  4861. this._enabled = true;
  4862. this.addHooks();
  4863. return this;
  4864. },
  4865. // @method disable(): this
  4866. // Disables the handler
  4867. disable: function () {
  4868. if (!this._enabled) { return this; }
  4869. this._enabled = false;
  4870. this.removeHooks();
  4871. return this;
  4872. },
  4873. // @method enabled(): Boolean
  4874. // Returns `true` if the handler is enabled
  4875. enabled: function () {
  4876. return !!this._enabled;
  4877. }
  4878. // @section Extension methods
  4879. // Classes inheriting from `Handler` must implement the two following methods:
  4880. // @method addHooks()
  4881. // Called when the handler is enabled, should add event hooks.
  4882. // @method removeHooks()
  4883. // Called when the handler is disabled, should remove the event hooks added previously.
  4884. });
  4885. // @section There is static function which can be called without instantiating L.Handler:
  4886. // @function addTo(map: Map, name: String): this
  4887. // Adds a new Handler to the given map with the given name.
  4888. Handler.addTo = function (map, name) {
  4889. map.addHandler(name, this);
  4890. return this;
  4891. };
  4892. var Mixin = {Events: Events};
  4893. /*
  4894. * @class Draggable
  4895. * @aka L.Draggable
  4896. * @inherits Evented
  4897. *
  4898. * A class for making DOM elements draggable (including touch support).
  4899. * Used internally for map and marker dragging. Only works for elements
  4900. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4901. *
  4902. * @example
  4903. * ```js
  4904. * var draggable = new L.Draggable(elementToDrag);
  4905. * draggable.enable();
  4906. * ```
  4907. */
  4908. var START = Browser.touch ? 'touchstart mousedown' : 'mousedown';
  4909. var Draggable = Evented.extend({
  4910. options: {
  4911. // @section
  4912. // @aka Draggable options
  4913. // @option clickTolerance: Number = 3
  4914. // The max number of pixels a user can shift the mouse pointer during a click
  4915. // for it to be considered a valid click (as opposed to a mouse drag).
  4916. clickTolerance: 3
  4917. },
  4918. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4919. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4920. initialize: function (element, dragStartTarget, preventOutline, options) {
  4921. setOptions(this, options);
  4922. this._element = element;
  4923. this._dragStartTarget = dragStartTarget || element;
  4924. this._preventOutline = preventOutline;
  4925. },
  4926. // @method enable()
  4927. // Enables the dragging ability
  4928. enable: function () {
  4929. if (this._enabled) { return; }
  4930. on(this._dragStartTarget, START, this._onDown, this);
  4931. this._enabled = true;
  4932. },
  4933. // @method disable()
  4934. // Disables the dragging ability
  4935. disable: function () {
  4936. if (!this._enabled) { return; }
  4937. // If we're currently dragging this draggable,
  4938. // disabling it counts as first ending the drag.
  4939. if (Draggable._dragging === this) {
  4940. this.finishDrag(true);
  4941. }
  4942. off(this._dragStartTarget, START, this._onDown, this);
  4943. this._enabled = false;
  4944. this._moved = false;
  4945. },
  4946. _onDown: function (e) {
  4947. // Ignore the event if disabled; this happens in IE11
  4948. // under some circumstances, see #3666.
  4949. if (!this._enabled) { return; }
  4950. this._moved = false;
  4951. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4952. if (e.touches && e.touches.length !== 1) {
  4953. // Finish dragging to avoid conflict with touchZoom
  4954. if (Draggable._dragging === this) {
  4955. this.finishDrag();
  4956. }
  4957. return;
  4958. }
  4959. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4960. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4961. if (this._preventOutline) {
  4962. preventOutline(this._element);
  4963. }
  4964. disableImageDrag();
  4965. disableTextSelection();
  4966. if (this._moving) { return; }
  4967. // @event down: Event
  4968. // Fired when a drag is about to start.
  4969. this.fire('down');
  4970. var first = e.touches ? e.touches[0] : e,
  4971. sizedParent = getSizedParentNode(this._element);
  4972. this._startPoint = new Point(first.clientX, first.clientY);
  4973. this._startPos = getPosition(this._element);
  4974. // Cache the scale, so that we can continuously compensate for it during drag (_onMove).
  4975. this._parentScale = getScale(sizedParent);
  4976. var mouseevent = e.type === 'mousedown';
  4977. on(document, mouseevent ? 'mousemove' : 'touchmove', this._onMove, this);
  4978. on(document, mouseevent ? 'mouseup' : 'touchend touchcancel', this._onUp, this);
  4979. },
  4980. _onMove: function (e) {
  4981. // Ignore the event if disabled; this happens in IE11
  4982. // under some circumstances, see #3666.
  4983. if (!this._enabled) { return; }
  4984. if (e.touches && e.touches.length > 1) {
  4985. this._moved = true;
  4986. return;
  4987. }
  4988. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4989. offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);
  4990. if (!offset.x && !offset.y) { return; }
  4991. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4992. // We assume that the parent container's position, border and scale do not change for the duration of the drag.
  4993. // Therefore there is no need to account for the position and border (they are eliminated by the subtraction)
  4994. // and we can use the cached value for the scale.
  4995. offset.x /= this._parentScale.x;
  4996. offset.y /= this._parentScale.y;
  4997. preventDefault(e);
  4998. if (!this._moved) {
  4999. // @event dragstart: Event
  5000. // Fired when a drag starts
  5001. this.fire('dragstart');
  5002. this._moved = true;
  5003. addClass(document.body, 'leaflet-dragging');
  5004. this._lastTarget = e.target || e.srcElement;
  5005. // IE and Edge do not give the <use> element, so fetch it
  5006. // if necessary
  5007. if (window.SVGElementInstance && this._lastTarget instanceof window.SVGElementInstance) {
  5008. this._lastTarget = this._lastTarget.correspondingUseElement;
  5009. }
  5010. addClass(this._lastTarget, 'leaflet-drag-target');
  5011. }
  5012. this._newPos = this._startPos.add(offset);
  5013. this._moving = true;
  5014. this._lastEvent = e;
  5015. this._updatePosition();
  5016. },
  5017. _updatePosition: function () {
  5018. var e = {originalEvent: this._lastEvent};
  5019. // @event predrag: Event
  5020. // Fired continuously during dragging *before* each corresponding
  5021. // update of the element's position.
  5022. this.fire('predrag', e);
  5023. setPosition(this._element, this._newPos);
  5024. // @event drag: Event
  5025. // Fired continuously during dragging.
  5026. this.fire('drag', e);
  5027. },
  5028. _onUp: function () {
  5029. // Ignore the event if disabled; this happens in IE11
  5030. // under some circumstances, see #3666.
  5031. if (!this._enabled) { return; }
  5032. this.finishDrag();
  5033. },
  5034. finishDrag: function (noInertia) {
  5035. removeClass(document.body, 'leaflet-dragging');
  5036. if (this._lastTarget) {
  5037. removeClass(this._lastTarget, 'leaflet-drag-target');
  5038. this._lastTarget = null;
  5039. }
  5040. off(document, 'mousemove touchmove', this._onMove, this);
  5041. off(document, 'mouseup touchend touchcancel', this._onUp, this);
  5042. enableImageDrag();
  5043. enableTextSelection();
  5044. var fireDragend = this._moved && this._moving;
  5045. this._moving = false;
  5046. Draggable._dragging = false;
  5047. if (fireDragend) {
  5048. // @event dragend: DragEndEvent
  5049. // Fired when the drag ends.
  5050. this.fire('dragend', {
  5051. noInertia: noInertia,
  5052. distance: this._newPos.distanceTo(this._startPos)
  5053. });
  5054. }
  5055. }
  5056. });
  5057. /*
  5058. * @namespace PolyUtil
  5059. * Various utility functions for polygon geometries.
  5060. */
  5061. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5062. * 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)).
  5063. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5064. * performance. Note that polygon points needs different algorithm for clipping
  5065. * than polyline, so there's a separate method for it.
  5066. */
  5067. function clipPolygon(points, bounds, round) {
  5068. var clippedPoints,
  5069. edges = [1, 4, 2, 8],
  5070. i, j, k,
  5071. a, b,
  5072. len, edge, p;
  5073. for (i = 0, len = points.length; i < len; i++) {
  5074. points[i]._code = _getBitCode(points[i], bounds);
  5075. }
  5076. // for each edge (left, bottom, right, top)
  5077. for (k = 0; k < 4; k++) {
  5078. edge = edges[k];
  5079. clippedPoints = [];
  5080. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5081. a = points[i];
  5082. b = points[j];
  5083. // if a is inside the clip window
  5084. if (!(a._code & edge)) {
  5085. // if b is outside the clip window (a->b goes out of screen)
  5086. if (b._code & edge) {
  5087. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5088. p._code = _getBitCode(p, bounds);
  5089. clippedPoints.push(p);
  5090. }
  5091. clippedPoints.push(a);
  5092. // else if b is inside the clip window (a->b enters the screen)
  5093. } else if (!(b._code & edge)) {
  5094. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5095. p._code = _getBitCode(p, bounds);
  5096. clippedPoints.push(p);
  5097. }
  5098. }
  5099. points = clippedPoints;
  5100. }
  5101. return points;
  5102. }
  5103. /* @function polygonCenter(latlngs: LatLng[], crs: CRS): LatLng
  5104. * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polygon.
  5105. */
  5106. function polygonCenter(latlngs, crs) {
  5107. var i, j, p1, p2, f, area, x, y, center;
  5108. if (!latlngs || latlngs.length === 0) {
  5109. throw new Error('latlngs not passed');
  5110. }
  5111. if (!isFlat(latlngs)) {
  5112. console.warn('latlngs are not flat! Only the first ring will be used');
  5113. latlngs = latlngs[0];
  5114. }
  5115. var centroidLatLng = toLatLng([0, 0]);
  5116. var bounds = toLatLngBounds(latlngs);
  5117. var areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());
  5118. // tests showed that below 1700 rounding errors are happening
  5119. if (areaBounds < 1700) {
  5120. // getting a inexact center, to move the latlngs near to [0, 0] to prevent rounding errors
  5121. centroidLatLng = centroid(latlngs);
  5122. }
  5123. var len = latlngs.length;
  5124. var points = [];
  5125. for (i = 0; i < len; i++) {
  5126. var latlng = toLatLng(latlngs[i]);
  5127. points.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));
  5128. }
  5129. area = x = y = 0;
  5130. // polygon centroid algorithm;
  5131. for (i = 0, j = len - 1; i < len; j = i++) {
  5132. p1 = points[i];
  5133. p2 = points[j];
  5134. f = p1.y * p2.x - p2.y * p1.x;
  5135. x += (p1.x + p2.x) * f;
  5136. y += (p1.y + p2.y) * f;
  5137. area += f * 3;
  5138. }
  5139. if (area === 0) {
  5140. // Polygon is so small that all points are on same pixel.
  5141. center = points[0];
  5142. } else {
  5143. center = [x / area, y / area];
  5144. }
  5145. var latlngCenter = crs.unproject(toPoint(center));
  5146. return toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);
  5147. }
  5148. /* @function centroid(latlngs: LatLng[]): LatLng
  5149. * Returns the 'center of mass' of the passed LatLngs.
  5150. */
  5151. function centroid(coords) {
  5152. var latSum = 0;
  5153. var lngSum = 0;
  5154. var len = 0;
  5155. for (var i = 0; i < coords.length; i++) {
  5156. var latlng = toLatLng(coords[i]);
  5157. latSum += latlng.lat;
  5158. lngSum += latlng.lng;
  5159. len++;
  5160. }
  5161. return toLatLng([latSum / len, lngSum / len]);
  5162. }
  5163. var PolyUtil = {
  5164. __proto__: null,
  5165. clipPolygon: clipPolygon,
  5166. polygonCenter: polygonCenter,
  5167. centroid: centroid
  5168. };
  5169. /*
  5170. * @namespace LineUtil
  5171. *
  5172. * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
  5173. */
  5174. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  5175. // Improves rendering performance dramatically by lessening the number of points to draw.
  5176. // @function simplify(points: Point[], tolerance: Number): Point[]
  5177. // Dramatically reduces the number of points in a polyline while retaining
  5178. // its shape and returns a new array of simplified points, using the
  5179. // [Ramer-Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm).
  5180. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  5181. // each zoom level and also reducing visual noise. tolerance affects the amount of
  5182. // simplification (lesser value means higher quality but slower and with more points).
  5183. // Also released as a separated micro-library [Simplify.js](https://mourner.github.io/simplify-js/).
  5184. function simplify(points, tolerance) {
  5185. if (!tolerance || !points.length) {
  5186. return points.slice();
  5187. }
  5188. var sqTolerance = tolerance * tolerance;
  5189. // stage 1: vertex reduction
  5190. points = _reducePoints(points, sqTolerance);
  5191. // stage 2: Douglas-Peucker simplification
  5192. points = _simplifyDP(points, sqTolerance);
  5193. return points;
  5194. }
  5195. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  5196. // Returns the distance between point `p` and segment `p1` to `p2`.
  5197. function pointToSegmentDistance(p, p1, p2) {
  5198. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  5199. }
  5200. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  5201. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  5202. function closestPointOnSegment(p, p1, p2) {
  5203. return _sqClosestPointOnSegment(p, p1, p2);
  5204. }
  5205. // Ramer-Douglas-Peucker simplification, see https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
  5206. function _simplifyDP(points, sqTolerance) {
  5207. var len = points.length,
  5208. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  5209. markers = new ArrayConstructor(len);
  5210. markers[0] = markers[len - 1] = 1;
  5211. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  5212. var i,
  5213. newPoints = [];
  5214. for (i = 0; i < len; i++) {
  5215. if (markers[i]) {
  5216. newPoints.push(points[i]);
  5217. }
  5218. }
  5219. return newPoints;
  5220. }
  5221. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  5222. var maxSqDist = 0,
  5223. index, i, sqDist;
  5224. for (i = first + 1; i <= last - 1; i++) {
  5225. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  5226. if (sqDist > maxSqDist) {
  5227. index = i;
  5228. maxSqDist = sqDist;
  5229. }
  5230. }
  5231. if (maxSqDist > sqTolerance) {
  5232. markers[index] = 1;
  5233. _simplifyDPStep(points, markers, sqTolerance, first, index);
  5234. _simplifyDPStep(points, markers, sqTolerance, index, last);
  5235. }
  5236. }
  5237. // reduce points that are too close to each other to a single point
  5238. function _reducePoints(points, sqTolerance) {
  5239. var reducedPoints = [points[0]];
  5240. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  5241. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  5242. reducedPoints.push(points[i]);
  5243. prev = i;
  5244. }
  5245. }
  5246. if (prev < len - 1) {
  5247. reducedPoints.push(points[len - 1]);
  5248. }
  5249. return reducedPoints;
  5250. }
  5251. var _lastCode;
  5252. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  5253. // Clips the segment a to b by rectangular bounds with the
  5254. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  5255. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  5256. // points that are on the screen or near, increasing performance.
  5257. function clipSegment(a, b, bounds, useLastCode, round) {
  5258. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  5259. codeB = _getBitCode(b, bounds),
  5260. codeOut, p, newCode;
  5261. // save 2nd code to avoid calculating it on the next segment
  5262. _lastCode = codeB;
  5263. while (true) {
  5264. // if a,b is inside the clip window (trivial accept)
  5265. if (!(codeA | codeB)) {
  5266. return [a, b];
  5267. }
  5268. // if a,b is outside the clip window (trivial reject)
  5269. if (codeA & codeB) {
  5270. return false;
  5271. }
  5272. // other cases
  5273. codeOut = codeA || codeB;
  5274. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  5275. newCode = _getBitCode(p, bounds);
  5276. if (codeOut === codeA) {
  5277. a = p;
  5278. codeA = newCode;
  5279. } else {
  5280. b = p;
  5281. codeB = newCode;
  5282. }
  5283. }
  5284. }
  5285. function _getEdgeIntersection(a, b, code, bounds, round) {
  5286. var dx = b.x - a.x,
  5287. dy = b.y - a.y,
  5288. min = bounds.min,
  5289. max = bounds.max,
  5290. x, y;
  5291. if (code & 8) { // top
  5292. x = a.x + dx * (max.y - a.y) / dy;
  5293. y = max.y;
  5294. } else if (code & 4) { // bottom
  5295. x = a.x + dx * (min.y - a.y) / dy;
  5296. y = min.y;
  5297. } else if (code & 2) { // right
  5298. x = max.x;
  5299. y = a.y + dy * (max.x - a.x) / dx;
  5300. } else if (code & 1) { // left
  5301. x = min.x;
  5302. y = a.y + dy * (min.x - a.x) / dx;
  5303. }
  5304. return new Point(x, y, round);
  5305. }
  5306. function _getBitCode(p, bounds) {
  5307. var code = 0;
  5308. if (p.x < bounds.min.x) { // left
  5309. code |= 1;
  5310. } else if (p.x > bounds.max.x) { // right
  5311. code |= 2;
  5312. }
  5313. if (p.y < bounds.min.y) { // bottom
  5314. code |= 4;
  5315. } else if (p.y > bounds.max.y) { // top
  5316. code |= 8;
  5317. }
  5318. return code;
  5319. }
  5320. // square distance (to avoid unnecessary Math.sqrt calls)
  5321. function _sqDist(p1, p2) {
  5322. var dx = p2.x - p1.x,
  5323. dy = p2.y - p1.y;
  5324. return dx * dx + dy * dy;
  5325. }
  5326. // return closest point on segment or distance to that point
  5327. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  5328. var x = p1.x,
  5329. y = p1.y,
  5330. dx = p2.x - x,
  5331. dy = p2.y - y,
  5332. dot = dx * dx + dy * dy,
  5333. t;
  5334. if (dot > 0) {
  5335. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  5336. if (t > 1) {
  5337. x = p2.x;
  5338. y = p2.y;
  5339. } else if (t > 0) {
  5340. x += dx * t;
  5341. y += dy * t;
  5342. }
  5343. }
  5344. dx = p.x - x;
  5345. dy = p.y - y;
  5346. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  5347. }
  5348. // @function isFlat(latlngs: LatLng[]): Boolean
  5349. // Returns true if `latlngs` is a flat array, false is nested.
  5350. function isFlat(latlngs) {
  5351. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  5352. }
  5353. function _flat(latlngs) {
  5354. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  5355. return isFlat(latlngs);
  5356. }
  5357. /* @function polylineCenter(latlngs: LatLng[], crs: CRS): LatLng
  5358. * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polyline.
  5359. */
  5360. function polylineCenter(latlngs, crs) {
  5361. var i, halfDist, segDist, dist, p1, p2, ratio, center;
  5362. if (!latlngs || latlngs.length === 0) {
  5363. throw new Error('latlngs not passed');
  5364. }
  5365. if (!isFlat(latlngs)) {
  5366. console.warn('latlngs are not flat! Only the first ring will be used');
  5367. latlngs = latlngs[0];
  5368. }
  5369. var centroidLatLng = toLatLng([0, 0]);
  5370. var bounds = toLatLngBounds(latlngs);
  5371. var areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());
  5372. // tests showed that below 1700 rounding errors are happening
  5373. if (areaBounds < 1700) {
  5374. // getting a inexact center, to move the latlngs near to [0, 0] to prevent rounding errors
  5375. centroidLatLng = centroid(latlngs);
  5376. }
  5377. var len = latlngs.length;
  5378. var points = [];
  5379. for (i = 0; i < len; i++) {
  5380. var latlng = toLatLng(latlngs[i]);
  5381. points.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));
  5382. }
  5383. for (i = 0, halfDist = 0; i < len - 1; i++) {
  5384. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  5385. }
  5386. // The line is so small in the current view that all points are on the same pixel.
  5387. if (halfDist === 0) {
  5388. center = points[0];
  5389. } else {
  5390. for (i = 0, dist = 0; i < len - 1; i++) {
  5391. p1 = points[i];
  5392. p2 = points[i + 1];
  5393. segDist = p1.distanceTo(p2);
  5394. dist += segDist;
  5395. if (dist > halfDist) {
  5396. ratio = (dist - halfDist) / segDist;
  5397. center = [
  5398. p2.x - ratio * (p2.x - p1.x),
  5399. p2.y - ratio * (p2.y - p1.y)
  5400. ];
  5401. break;
  5402. }
  5403. }
  5404. }
  5405. var latlngCenter = crs.unproject(toPoint(center));
  5406. return toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);
  5407. }
  5408. var LineUtil = {
  5409. __proto__: null,
  5410. simplify: simplify,
  5411. pointToSegmentDistance: pointToSegmentDistance,
  5412. closestPointOnSegment: closestPointOnSegment,
  5413. clipSegment: clipSegment,
  5414. _getEdgeIntersection: _getEdgeIntersection,
  5415. _getBitCode: _getBitCode,
  5416. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5417. isFlat: isFlat,
  5418. _flat: _flat,
  5419. polylineCenter: polylineCenter
  5420. };
  5421. /*
  5422. * @namespace Projection
  5423. * @section
  5424. * Leaflet comes with a set of already defined Projections out of the box:
  5425. *
  5426. * @projection L.Projection.LonLat
  5427. *
  5428. * Equirectangular, or Plate Carree projection — the most simple projection,
  5429. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5430. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5431. * `EPSG:4326` and `Simple` CRS.
  5432. */
  5433. var LonLat = {
  5434. project: function (latlng) {
  5435. return new Point(latlng.lng, latlng.lat);
  5436. },
  5437. unproject: function (point) {
  5438. return new LatLng(point.y, point.x);
  5439. },
  5440. bounds: new Bounds([-180, -90], [180, 90])
  5441. };
  5442. /*
  5443. * @namespace Projection
  5444. * @projection L.Projection.Mercator
  5445. *
  5446. * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.
  5447. */
  5448. var Mercator = {
  5449. R: 6378137,
  5450. R_MINOR: 6356752.314245179,
  5451. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5452. project: function (latlng) {
  5453. var d = Math.PI / 180,
  5454. r = this.R,
  5455. y = latlng.lat * d,
  5456. tmp = this.R_MINOR / r,
  5457. e = Math.sqrt(1 - tmp * tmp),
  5458. con = e * Math.sin(y);
  5459. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5460. y = -r * Math.log(Math.max(ts, 1E-10));
  5461. return new Point(latlng.lng * d * r, y);
  5462. },
  5463. unproject: function (point) {
  5464. var d = 180 / Math.PI,
  5465. r = this.R,
  5466. tmp = this.R_MINOR / r,
  5467. e = Math.sqrt(1 - tmp * tmp),
  5468. ts = Math.exp(-point.y / r),
  5469. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5470. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5471. con = e * Math.sin(phi);
  5472. con = Math.pow((1 - con) / (1 + con), e / 2);
  5473. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5474. phi += dphi;
  5475. }
  5476. return new LatLng(phi * d, point.x * d / r);
  5477. }
  5478. };
  5479. /*
  5480. * @class Projection
  5481. * An object with methods for projecting geographical coordinates of the world onto
  5482. * a flat surface (and back). See [Map projection](https://en.wikipedia.org/wiki/Map_projection).
  5483. * @property bounds: Bounds
  5484. * The bounds (specified in CRS units) where the projection is valid
  5485. * @method project(latlng: LatLng): Point
  5486. * Projects geographical coordinates into a 2D point.
  5487. * Only accepts actual `L.LatLng` instances, not arrays.
  5488. * @method unproject(point: Point): LatLng
  5489. * The inverse of `project`. Projects a 2D point into a geographical location.
  5490. * Only accepts actual `L.Point` instances, not arrays.
  5491. * Note that the projection instances do not inherit from Leaflet's `Class` object,
  5492. * and can't be instantiated. Also, new classes can't inherit from them,
  5493. * and methods can't be added to them with the `include` function.
  5494. */
  5495. var index = {
  5496. __proto__: null,
  5497. LonLat: LonLat,
  5498. Mercator: Mercator,
  5499. SphericalMercator: SphericalMercator
  5500. };
  5501. /*
  5502. * @namespace CRS
  5503. * @crs L.CRS.EPSG3395
  5504. *
  5505. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5506. */
  5507. var EPSG3395 = extend({}, Earth, {
  5508. code: 'EPSG:3395',
  5509. projection: Mercator,
  5510. transformation: (function () {
  5511. var scale = 0.5 / (Math.PI * Mercator.R);
  5512. return toTransformation(scale, 0.5, -scale, 0.5);
  5513. }())
  5514. });
  5515. /*
  5516. * @namespace CRS
  5517. * @crs L.CRS.EPSG4326
  5518. *
  5519. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5520. *
  5521. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5522. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5523. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5524. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5525. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5526. */
  5527. var EPSG4326 = extend({}, Earth, {
  5528. code: 'EPSG:4326',
  5529. projection: LonLat,
  5530. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5531. });
  5532. /*
  5533. * @namespace CRS
  5534. * @crs L.CRS.Simple
  5535. *
  5536. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5537. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5538. * axis should still be inverted (going from bottom to top). `distance()` returns
  5539. * simple euclidean distance.
  5540. */
  5541. var Simple = extend({}, CRS, {
  5542. projection: LonLat,
  5543. transformation: toTransformation(1, 0, -1, 0),
  5544. scale: function (zoom) {
  5545. return Math.pow(2, zoom);
  5546. },
  5547. zoom: function (scale) {
  5548. return Math.log(scale) / Math.LN2;
  5549. },
  5550. distance: function (latlng1, latlng2) {
  5551. var dx = latlng2.lng - latlng1.lng,
  5552. dy = latlng2.lat - latlng1.lat;
  5553. return Math.sqrt(dx * dx + dy * dy);
  5554. },
  5555. infinite: true
  5556. });
  5557. CRS.Earth = Earth;
  5558. CRS.EPSG3395 = EPSG3395;
  5559. CRS.EPSG3857 = EPSG3857;
  5560. CRS.EPSG900913 = EPSG900913;
  5561. CRS.EPSG4326 = EPSG4326;
  5562. CRS.Simple = Simple;
  5563. /*
  5564. * @class Layer
  5565. * @inherits Evented
  5566. * @aka L.Layer
  5567. * @aka ILayer
  5568. *
  5569. * A set of methods from the Layer base class that all Leaflet layers use.
  5570. * Inherits all methods, options and events from `L.Evented`.
  5571. *
  5572. * @example
  5573. *
  5574. * ```js
  5575. * var layer = L.marker(latlng).addTo(map);
  5576. * layer.addTo(map);
  5577. * layer.remove();
  5578. * ```
  5579. *
  5580. * @event add: Event
  5581. * Fired after the layer is added to a map
  5582. *
  5583. * @event remove: Event
  5584. * Fired after the layer is removed from a map
  5585. */
  5586. var Layer = Evented.extend({
  5587. // Classes extending `L.Layer` will inherit the following options:
  5588. options: {
  5589. // @option pane: String = 'overlayPane'
  5590. // 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.
  5591. pane: 'overlayPane',
  5592. // @option attribution: String = null
  5593. // 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.
  5594. attribution: null,
  5595. bubblingMouseEvents: true
  5596. },
  5597. /* @section
  5598. * Classes extending `L.Layer` will inherit the following methods:
  5599. *
  5600. * @method addTo(map: Map|LayerGroup): this
  5601. * Adds the layer to the given map or layer group.
  5602. */
  5603. addTo: function (map) {
  5604. map.addLayer(this);
  5605. return this;
  5606. },
  5607. // @method remove: this
  5608. // Removes the layer from the map it is currently active on.
  5609. remove: function () {
  5610. return this.removeFrom(this._map || this._mapToAdd);
  5611. },
  5612. // @method removeFrom(map: Map): this
  5613. // Removes the layer from the given map
  5614. //
  5615. // @alternative
  5616. // @method removeFrom(group: LayerGroup): this
  5617. // Removes the layer from the given `LayerGroup`
  5618. removeFrom: function (obj) {
  5619. if (obj) {
  5620. obj.removeLayer(this);
  5621. }
  5622. return this;
  5623. },
  5624. // @method getPane(name? : String): HTMLElement
  5625. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5626. getPane: function (name) {
  5627. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5628. },
  5629. addInteractiveTarget: function (targetEl) {
  5630. this._map._targets[stamp(targetEl)] = this;
  5631. return this;
  5632. },
  5633. removeInteractiveTarget: function (targetEl) {
  5634. delete this._map._targets[stamp(targetEl)];
  5635. return this;
  5636. },
  5637. // @method getAttribution: String
  5638. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5639. getAttribution: function () {
  5640. return this.options.attribution;
  5641. },
  5642. _layerAdd: function (e) {
  5643. var map = e.target;
  5644. // check in case layer gets added and then removed before the map is ready
  5645. if (!map.hasLayer(this)) { return; }
  5646. this._map = map;
  5647. this._zoomAnimated = map._zoomAnimated;
  5648. if (this.getEvents) {
  5649. var events = this.getEvents();
  5650. map.on(events, this);
  5651. this.once('remove', function () {
  5652. map.off(events, this);
  5653. }, this);
  5654. }
  5655. this.onAdd(map);
  5656. this.fire('add');
  5657. map.fire('layeradd', {layer: this});
  5658. }
  5659. });
  5660. /* @section Extension methods
  5661. * @uninheritable
  5662. *
  5663. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5664. *
  5665. * @method onAdd(map: Map): this
  5666. * 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).
  5667. *
  5668. * @method onRemove(map: Map): this
  5669. * 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).
  5670. *
  5671. * @method getEvents(): Object
  5672. * 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.
  5673. *
  5674. * @method getAttribution(): String
  5675. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5676. *
  5677. * @method beforeAdd(map: Map): this
  5678. * 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.
  5679. */
  5680. /* @namespace Map
  5681. * @section Layer events
  5682. *
  5683. * @event layeradd: LayerEvent
  5684. * Fired when a new layer is added to the map.
  5685. *
  5686. * @event layerremove: LayerEvent
  5687. * Fired when some layer is removed from the map
  5688. *
  5689. * @section Methods for Layers and Controls
  5690. */
  5691. Map.include({
  5692. // @method addLayer(layer: Layer): this
  5693. // Adds the given layer to the map
  5694. addLayer: function (layer) {
  5695. if (!layer._layerAdd) {
  5696. throw new Error('The provided object is not a Layer.');
  5697. }
  5698. var id = stamp(layer);
  5699. if (this._layers[id]) { return this; }
  5700. this._layers[id] = layer;
  5701. layer._mapToAdd = this;
  5702. if (layer.beforeAdd) {
  5703. layer.beforeAdd(this);
  5704. }
  5705. this.whenReady(layer._layerAdd, layer);
  5706. return this;
  5707. },
  5708. // @method removeLayer(layer: Layer): this
  5709. // Removes the given layer from the map.
  5710. removeLayer: function (layer) {
  5711. var id = stamp(layer);
  5712. if (!this._layers[id]) { return this; }
  5713. if (this._loaded) {
  5714. layer.onRemove(this);
  5715. }
  5716. delete this._layers[id];
  5717. if (this._loaded) {
  5718. this.fire('layerremove', {layer: layer});
  5719. layer.fire('remove');
  5720. }
  5721. layer._map = layer._mapToAdd = null;
  5722. return this;
  5723. },
  5724. // @method hasLayer(layer: Layer): Boolean
  5725. // Returns `true` if the given layer is currently added to the map
  5726. hasLayer: function (layer) {
  5727. return stamp(layer) in this._layers;
  5728. },
  5729. /* @method eachLayer(fn: Function, context?: Object): this
  5730. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5731. * ```
  5732. * map.eachLayer(function(layer){
  5733. * layer.bindPopup('Hello');
  5734. * });
  5735. * ```
  5736. */
  5737. eachLayer: function (method, context) {
  5738. for (var i in this._layers) {
  5739. method.call(context, this._layers[i]);
  5740. }
  5741. return this;
  5742. },
  5743. _addLayers: function (layers) {
  5744. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5745. for (var i = 0, len = layers.length; i < len; i++) {
  5746. this.addLayer(layers[i]);
  5747. }
  5748. },
  5749. _addZoomLimit: function (layer) {
  5750. if (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5751. this._zoomBoundLayers[stamp(layer)] = layer;
  5752. this._updateZoomLevels();
  5753. }
  5754. },
  5755. _removeZoomLimit: function (layer) {
  5756. var id = stamp(layer);
  5757. if (this._zoomBoundLayers[id]) {
  5758. delete this._zoomBoundLayers[id];
  5759. this._updateZoomLevels();
  5760. }
  5761. },
  5762. _updateZoomLevels: function () {
  5763. var minZoom = Infinity,
  5764. maxZoom = -Infinity,
  5765. oldZoomSpan = this._getZoomSpan();
  5766. for (var i in this._zoomBoundLayers) {
  5767. var options = this._zoomBoundLayers[i].options;
  5768. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5769. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5770. }
  5771. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5772. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5773. // @section Map state change events
  5774. // @event zoomlevelschange: Event
  5775. // Fired when the number of zoomlevels on the map is changed due
  5776. // to adding or removing a layer.
  5777. if (oldZoomSpan !== this._getZoomSpan()) {
  5778. this.fire('zoomlevelschange');
  5779. }
  5780. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5781. this.setZoom(this._layersMaxZoom);
  5782. }
  5783. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5784. this.setZoom(this._layersMinZoom);
  5785. }
  5786. }
  5787. });
  5788. /*
  5789. * @class LayerGroup
  5790. * @aka L.LayerGroup
  5791. * @inherits Interactive layer
  5792. *
  5793. * Used to group several layers and handle them as one. If you add it to the map,
  5794. * any layers added or removed from the group will be added/removed on the map as
  5795. * well. Extends `Layer`.
  5796. *
  5797. * @example
  5798. *
  5799. * ```js
  5800. * L.layerGroup([marker1, marker2])
  5801. * .addLayer(polyline)
  5802. * .addTo(map);
  5803. * ```
  5804. */
  5805. var LayerGroup = Layer.extend({
  5806. initialize: function (layers, options) {
  5807. setOptions(this, options);
  5808. this._layers = {};
  5809. var i, len;
  5810. if (layers) {
  5811. for (i = 0, len = layers.length; i < len; i++) {
  5812. this.addLayer(layers[i]);
  5813. }
  5814. }
  5815. },
  5816. // @method addLayer(layer: Layer): this
  5817. // Adds the given layer to the group.
  5818. addLayer: function (layer) {
  5819. var id = this.getLayerId(layer);
  5820. this._layers[id] = layer;
  5821. if (this._map) {
  5822. this._map.addLayer(layer);
  5823. }
  5824. return this;
  5825. },
  5826. // @method removeLayer(layer: Layer): this
  5827. // Removes the given layer from the group.
  5828. // @alternative
  5829. // @method removeLayer(id: Number): this
  5830. // Removes the layer with the given internal ID from the group.
  5831. removeLayer: function (layer) {
  5832. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5833. if (this._map && this._layers[id]) {
  5834. this._map.removeLayer(this._layers[id]);
  5835. }
  5836. delete this._layers[id];
  5837. return this;
  5838. },
  5839. // @method hasLayer(layer: Layer): Boolean
  5840. // Returns `true` if the given layer is currently added to the group.
  5841. // @alternative
  5842. // @method hasLayer(id: Number): Boolean
  5843. // Returns `true` if the given internal ID is currently added to the group.
  5844. hasLayer: function (layer) {
  5845. var layerId = typeof layer === 'number' ? layer : this.getLayerId(layer);
  5846. return layerId in this._layers;
  5847. },
  5848. // @method clearLayers(): this
  5849. // Removes all the layers from the group.
  5850. clearLayers: function () {
  5851. return this.eachLayer(this.removeLayer, this);
  5852. },
  5853. // @method invoke(methodName: String, …): this
  5854. // Calls `methodName` on every layer contained in this group, passing any
  5855. // additional parameters. Has no effect if the layers contained do not
  5856. // implement `methodName`.
  5857. invoke: function (methodName) {
  5858. var args = Array.prototype.slice.call(arguments, 1),
  5859. i, layer;
  5860. for (i in this._layers) {
  5861. layer = this._layers[i];
  5862. if (layer[methodName]) {
  5863. layer[methodName].apply(layer, args);
  5864. }
  5865. }
  5866. return this;
  5867. },
  5868. onAdd: function (map) {
  5869. this.eachLayer(map.addLayer, map);
  5870. },
  5871. onRemove: function (map) {
  5872. this.eachLayer(map.removeLayer, map);
  5873. },
  5874. // @method eachLayer(fn: Function, context?: Object): this
  5875. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5876. // ```js
  5877. // group.eachLayer(function (layer) {
  5878. // layer.bindPopup('Hello');
  5879. // });
  5880. // ```
  5881. eachLayer: function (method, context) {
  5882. for (var i in this._layers) {
  5883. method.call(context, this._layers[i]);
  5884. }
  5885. return this;
  5886. },
  5887. // @method getLayer(id: Number): Layer
  5888. // Returns the layer with the given internal ID.
  5889. getLayer: function (id) {
  5890. return this._layers[id];
  5891. },
  5892. // @method getLayers(): Layer[]
  5893. // Returns an array of all the layers added to the group.
  5894. getLayers: function () {
  5895. var layers = [];
  5896. this.eachLayer(layers.push, layers);
  5897. return layers;
  5898. },
  5899. // @method setZIndex(zIndex: Number): this
  5900. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5901. setZIndex: function (zIndex) {
  5902. return this.invoke('setZIndex', zIndex);
  5903. },
  5904. // @method getLayerId(layer: Layer): Number
  5905. // Returns the internal ID for a layer
  5906. getLayerId: function (layer) {
  5907. return stamp(layer);
  5908. }
  5909. });
  5910. // @factory L.layerGroup(layers?: Layer[], options?: Object)
  5911. // Create a layer group, optionally given an initial set of layers and an `options` object.
  5912. var layerGroup = function (layers, options) {
  5913. return new LayerGroup(layers, options);
  5914. };
  5915. /*
  5916. * @class FeatureGroup
  5917. * @aka L.FeatureGroup
  5918. * @inherits LayerGroup
  5919. *
  5920. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5921. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5922. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5923. * handler, it will handle events from any of the layers. This includes mouse events
  5924. * and custom events.
  5925. * * Has `layeradd` and `layerremove` events
  5926. *
  5927. * @example
  5928. *
  5929. * ```js
  5930. * L.featureGroup([marker1, marker2, polyline])
  5931. * .bindPopup('Hello world!')
  5932. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5933. * .addTo(map);
  5934. * ```
  5935. */
  5936. var FeatureGroup = LayerGroup.extend({
  5937. addLayer: function (layer) {
  5938. if (this.hasLayer(layer)) {
  5939. return this;
  5940. }
  5941. layer.addEventParent(this);
  5942. LayerGroup.prototype.addLayer.call(this, layer);
  5943. // @event layeradd: LayerEvent
  5944. // Fired when a layer is added to this `FeatureGroup`
  5945. return this.fire('layeradd', {layer: layer});
  5946. },
  5947. removeLayer: function (layer) {
  5948. if (!this.hasLayer(layer)) {
  5949. return this;
  5950. }
  5951. if (layer in this._layers) {
  5952. layer = this._layers[layer];
  5953. }
  5954. layer.removeEventParent(this);
  5955. LayerGroup.prototype.removeLayer.call(this, layer);
  5956. // @event layerremove: LayerEvent
  5957. // Fired when a layer is removed from this `FeatureGroup`
  5958. return this.fire('layerremove', {layer: layer});
  5959. },
  5960. // @method setStyle(style: Path options): this
  5961. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5962. setStyle: function (style) {
  5963. return this.invoke('setStyle', style);
  5964. },
  5965. // @method bringToFront(): this
  5966. // Brings the layer group to the top of all other layers
  5967. bringToFront: function () {
  5968. return this.invoke('bringToFront');
  5969. },
  5970. // @method bringToBack(): this
  5971. // Brings the layer group to the back of all other layers
  5972. bringToBack: function () {
  5973. return this.invoke('bringToBack');
  5974. },
  5975. // @method getBounds(): LatLngBounds
  5976. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5977. getBounds: function () {
  5978. var bounds = new LatLngBounds();
  5979. for (var id in this._layers) {
  5980. var layer = this._layers[id];
  5981. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5982. }
  5983. return bounds;
  5984. }
  5985. });
  5986. // @factory L.featureGroup(layers?: Layer[], options?: Object)
  5987. // Create a feature group, optionally given an initial set of layers and an `options` object.
  5988. var featureGroup = function (layers, options) {
  5989. return new FeatureGroup(layers, options);
  5990. };
  5991. /*
  5992. * @class Icon
  5993. * @aka L.Icon
  5994. *
  5995. * Represents an icon to provide when creating a marker.
  5996. *
  5997. * @example
  5998. *
  5999. * ```js
  6000. * var myIcon = L.icon({
  6001. * iconUrl: 'my-icon.png',
  6002. * iconRetinaUrl: 'my-icon@2x.png',
  6003. * iconSize: [38, 95],
  6004. * iconAnchor: [22, 94],
  6005. * popupAnchor: [-3, -76],
  6006. * shadowUrl: 'my-icon-shadow.png',
  6007. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  6008. * shadowSize: [68, 95],
  6009. * shadowAnchor: [22, 94]
  6010. * });
  6011. *
  6012. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  6013. * ```
  6014. *
  6015. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  6016. *
  6017. */
  6018. var Icon = Class.extend({
  6019. /* @section
  6020. * @aka Icon options
  6021. *
  6022. * @option iconUrl: String = null
  6023. * **(required)** The URL to the icon image (absolute or relative to your script path).
  6024. *
  6025. * @option iconRetinaUrl: String = null
  6026. * The URL to a retina sized version of the icon image (absolute or relative to your
  6027. * script path). Used for Retina screen devices.
  6028. *
  6029. * @option iconSize: Point = null
  6030. * Size of the icon image in pixels.
  6031. *
  6032. * @option iconAnchor: Point = null
  6033. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  6034. * will be aligned so that this point is at the marker's geographical location. Centered
  6035. * by default if size is specified, also can be set in CSS with negative margins.
  6036. *
  6037. * @option popupAnchor: Point = [0, 0]
  6038. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  6039. *
  6040. * @option tooltipAnchor: Point = [0, 0]
  6041. * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
  6042. *
  6043. * @option shadowUrl: String = null
  6044. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  6045. *
  6046. * @option shadowRetinaUrl: String = null
  6047. *
  6048. * @option shadowSize: Point = null
  6049. * Size of the shadow image in pixels.
  6050. *
  6051. * @option shadowAnchor: Point = null
  6052. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  6053. * as iconAnchor if not specified).
  6054. *
  6055. * @option className: String = ''
  6056. * A custom class name to assign to both icon and shadow images. Empty by default.
  6057. */
  6058. options: {
  6059. popupAnchor: [0, 0],
  6060. tooltipAnchor: [0, 0],
  6061. // @option crossOrigin: Boolean|String = false
  6062. // Whether the crossOrigin attribute will be added to the tiles.
  6063. // 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.
  6064. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  6065. crossOrigin: false
  6066. },
  6067. initialize: function (options) {
  6068. setOptions(this, options);
  6069. },
  6070. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  6071. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  6072. // styled according to the options.
  6073. createIcon: function (oldIcon) {
  6074. return this._createIcon('icon', oldIcon);
  6075. },
  6076. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  6077. // As `createIcon`, but for the shadow beneath it.
  6078. createShadow: function (oldIcon) {
  6079. return this._createIcon('shadow', oldIcon);
  6080. },
  6081. _createIcon: function (name, oldIcon) {
  6082. var src = this._getIconUrl(name);
  6083. if (!src) {
  6084. if (name === 'icon') {
  6085. throw new Error('iconUrl not set in Icon options (see the docs).');
  6086. }
  6087. return null;
  6088. }
  6089. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  6090. this._setIconStyles(img, name);
  6091. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  6092. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  6093. }
  6094. return img;
  6095. },
  6096. _setIconStyles: function (img, name) {
  6097. var options = this.options;
  6098. var sizeOption = options[name + 'Size'];
  6099. if (typeof sizeOption === 'number') {
  6100. sizeOption = [sizeOption, sizeOption];
  6101. }
  6102. var size = toPoint(sizeOption),
  6103. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  6104. size && size.divideBy(2, true));
  6105. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  6106. if (anchor) {
  6107. img.style.marginLeft = (-anchor.x) + 'px';
  6108. img.style.marginTop = (-anchor.y) + 'px';
  6109. }
  6110. if (size) {
  6111. img.style.width = size.x + 'px';
  6112. img.style.height = size.y + 'px';
  6113. }
  6114. },
  6115. _createImg: function (src, el) {
  6116. el = el || document.createElement('img');
  6117. el.src = src;
  6118. return el;
  6119. },
  6120. _getIconUrl: function (name) {
  6121. return Browser.retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  6122. }
  6123. });
  6124. // @factory L.icon(options: Icon options)
  6125. // Creates an icon instance with the given options.
  6126. function icon(options) {
  6127. return new Icon(options);
  6128. }
  6129. /*
  6130. * @miniclass Icon.Default (Icon)
  6131. * @aka L.Icon.Default
  6132. * @section
  6133. *
  6134. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  6135. * no icon is specified. Points to the blue marker image distributed with Leaflet
  6136. * releases.
  6137. *
  6138. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  6139. * (which is a set of `Icon options`).
  6140. *
  6141. * If you want to _completely_ replace the default icon, override the
  6142. * `L.Marker.prototype.options.icon` with your own icon instead.
  6143. */
  6144. var IconDefault = Icon.extend({
  6145. options: {
  6146. iconUrl: 'marker-icon.png',
  6147. iconRetinaUrl: 'marker-icon-2x.png',
  6148. shadowUrl: 'marker-shadow.png',
  6149. iconSize: [25, 41],
  6150. iconAnchor: [12, 41],
  6151. popupAnchor: [1, -34],
  6152. tooltipAnchor: [16, -28],
  6153. shadowSize: [41, 41]
  6154. },
  6155. _getIconUrl: function (name) {
  6156. if (typeof IconDefault.imagePath !== 'string') { // Deprecated, backwards-compatibility only
  6157. IconDefault.imagePath = this._detectIconPath();
  6158. }
  6159. // @option imagePath: String
  6160. // `Icon.Default` will try to auto-detect the location of the
  6161. // blue icon images. If you are placing these images in a non-standard
  6162. // way, set this option to point to the right path.
  6163. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  6164. },
  6165. _stripUrl: function (path) { // separate function to use in tests
  6166. var strip = function (str, re, idx) {
  6167. var match = re.exec(str);
  6168. return match && match[idx];
  6169. };
  6170. path = strip(path, /^url\((['"])?(.+)\1\)$/, 2);
  6171. return path && strip(path, /^(.*)marker-icon\.png$/, 1);
  6172. },
  6173. _detectIconPath: function () {
  6174. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  6175. var path = getStyle(el, 'background-image') ||
  6176. getStyle(el, 'backgroundImage'); // IE8
  6177. document.body.removeChild(el);
  6178. path = this._stripUrl(path);
  6179. if (path) { return path; }
  6180. var link = document.querySelector('link[href$="leaflet.css"]');
  6181. if (!link) { return ''; }
  6182. return link.href.substring(0, link.href.length - 'leaflet.css'.length - 1);
  6183. }
  6184. });
  6185. /*
  6186. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  6187. */
  6188. /* @namespace Marker
  6189. * @section Interaction handlers
  6190. *
  6191. * 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:
  6192. *
  6193. * ```js
  6194. * marker.dragging.disable();
  6195. * ```
  6196. *
  6197. * @property dragging: Handler
  6198. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  6199. */
  6200. var MarkerDrag = Handler.extend({
  6201. initialize: function (marker) {
  6202. this._marker = marker;
  6203. },
  6204. addHooks: function () {
  6205. var icon = this._marker._icon;
  6206. if (!this._draggable) {
  6207. this._draggable = new Draggable(icon, icon, true);
  6208. }
  6209. this._draggable.on({
  6210. dragstart: this._onDragStart,
  6211. predrag: this._onPreDrag,
  6212. drag: this._onDrag,
  6213. dragend: this._onDragEnd
  6214. }, this).enable();
  6215. addClass(icon, 'leaflet-marker-draggable');
  6216. },
  6217. removeHooks: function () {
  6218. this._draggable.off({
  6219. dragstart: this._onDragStart,
  6220. predrag: this._onPreDrag,
  6221. drag: this._onDrag,
  6222. dragend: this._onDragEnd
  6223. }, this).disable();
  6224. if (this._marker._icon) {
  6225. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  6226. }
  6227. },
  6228. moved: function () {
  6229. return this._draggable && this._draggable._moved;
  6230. },
  6231. _adjustPan: function (e) {
  6232. var marker = this._marker,
  6233. map = marker._map,
  6234. speed = this._marker.options.autoPanSpeed,
  6235. padding = this._marker.options.autoPanPadding,
  6236. iconPos = getPosition(marker._icon),
  6237. bounds = map.getPixelBounds(),
  6238. origin = map.getPixelOrigin();
  6239. var panBounds = toBounds(
  6240. bounds.min._subtract(origin).add(padding),
  6241. bounds.max._subtract(origin).subtract(padding)
  6242. );
  6243. if (!panBounds.contains(iconPos)) {
  6244. // Compute incremental movement
  6245. var movement = toPoint(
  6246. (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
  6247. (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
  6248. (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
  6249. (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
  6250. ).multiplyBy(speed);
  6251. map.panBy(movement, {animate: false});
  6252. this._draggable._newPos._add(movement);
  6253. this._draggable._startPos._add(movement);
  6254. setPosition(marker._icon, this._draggable._newPos);
  6255. this._onDrag(e);
  6256. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  6257. }
  6258. },
  6259. _onDragStart: function () {
  6260. // @section Dragging events
  6261. // @event dragstart: Event
  6262. // Fired when the user starts dragging the marker.
  6263. // @event movestart: Event
  6264. // Fired when the marker starts moving (because of dragging).
  6265. this._oldLatLng = this._marker.getLatLng();
  6266. // When using ES6 imports it could not be set when `Popup` was not imported as well
  6267. this._marker.closePopup && this._marker.closePopup();
  6268. this._marker
  6269. .fire('movestart')
  6270. .fire('dragstart');
  6271. },
  6272. _onPreDrag: function (e) {
  6273. if (this._marker.options.autoPan) {
  6274. cancelAnimFrame(this._panRequest);
  6275. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  6276. }
  6277. },
  6278. _onDrag: function (e) {
  6279. var marker = this._marker,
  6280. shadow = marker._shadow,
  6281. iconPos = getPosition(marker._icon),
  6282. latlng = marker._map.layerPointToLatLng(iconPos);
  6283. // update shadow position
  6284. if (shadow) {
  6285. setPosition(shadow, iconPos);
  6286. }
  6287. marker._latlng = latlng;
  6288. e.latlng = latlng;
  6289. e.oldLatLng = this._oldLatLng;
  6290. // @event drag: Event
  6291. // Fired repeatedly while the user drags the marker.
  6292. marker
  6293. .fire('move', e)
  6294. .fire('drag', e);
  6295. },
  6296. _onDragEnd: function (e) {
  6297. // @event dragend: DragEndEvent
  6298. // Fired when the user stops dragging the marker.
  6299. cancelAnimFrame(this._panRequest);
  6300. // @event moveend: Event
  6301. // Fired when the marker stops moving (because of dragging).
  6302. delete this._oldLatLng;
  6303. this._marker
  6304. .fire('moveend')
  6305. .fire('dragend', e);
  6306. }
  6307. });
  6308. /*
  6309. * @class Marker
  6310. * @inherits Interactive layer
  6311. * @aka L.Marker
  6312. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  6313. *
  6314. * @example
  6315. *
  6316. * ```js
  6317. * L.marker([50.5, 30.5]).addTo(map);
  6318. * ```
  6319. */
  6320. var Marker = Layer.extend({
  6321. // @section
  6322. // @aka Marker options
  6323. options: {
  6324. // @option icon: Icon = *
  6325. // Icon instance to use for rendering the marker.
  6326. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  6327. // If not specified, a common instance of `L.Icon.Default` is used.
  6328. icon: new IconDefault(),
  6329. // Option inherited from "Interactive layer" abstract class
  6330. interactive: true,
  6331. // @option keyboard: Boolean = true
  6332. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  6333. keyboard: true,
  6334. // @option title: String = ''
  6335. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  6336. // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
  6337. title: '',
  6338. // @option alt: String = 'Marker'
  6339. // Text for the `alt` attribute of the icon image.
  6340. // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
  6341. alt: 'Marker',
  6342. // @option zIndexOffset: Number = 0
  6343. // 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).
  6344. zIndexOffset: 0,
  6345. // @option opacity: Number = 1.0
  6346. // The opacity of the marker.
  6347. opacity: 1,
  6348. // @option riseOnHover: Boolean = false
  6349. // If `true`, the marker will get on top of others when you hover the mouse over it.
  6350. riseOnHover: false,
  6351. // @option riseOffset: Number = 250
  6352. // The z-index offset used for the `riseOnHover` feature.
  6353. riseOffset: 250,
  6354. // @option pane: String = 'markerPane'
  6355. // `Map pane` where the markers icon will be added.
  6356. pane: 'markerPane',
  6357. // @option shadowPane: String = 'shadowPane'
  6358. // `Map pane` where the markers shadow will be added.
  6359. shadowPane: 'shadowPane',
  6360. // @option bubblingMouseEvents: Boolean = false
  6361. // When `true`, a mouse event on this marker will trigger the same event on the map
  6362. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6363. bubblingMouseEvents: false,
  6364. // @option autoPanOnFocus: Boolean = true
  6365. // When `true`, the map will pan whenever the marker is focused (via
  6366. // e.g. pressing `tab` on the keyboard) to ensure the marker is
  6367. // visible within the map's bounds
  6368. autoPanOnFocus: true,
  6369. // @section Draggable marker options
  6370. // @option draggable: Boolean = false
  6371. // Whether the marker is draggable with mouse/touch or not.
  6372. draggable: false,
  6373. // @option autoPan: Boolean = false
  6374. // Whether to pan the map when dragging this marker near its edge or not.
  6375. autoPan: false,
  6376. // @option autoPanPadding: Point = Point(50, 50)
  6377. // Distance (in pixels to the left/right and to the top/bottom) of the
  6378. // map edge to start panning the map.
  6379. autoPanPadding: [50, 50],
  6380. // @option autoPanSpeed: Number = 10
  6381. // Number of pixels the map should pan by.
  6382. autoPanSpeed: 10
  6383. },
  6384. /* @section
  6385. *
  6386. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  6387. */
  6388. initialize: function (latlng, options) {
  6389. setOptions(this, options);
  6390. this._latlng = toLatLng(latlng);
  6391. },
  6392. onAdd: function (map) {
  6393. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  6394. if (this._zoomAnimated) {
  6395. map.on('zoomanim', this._animateZoom, this);
  6396. }
  6397. this._initIcon();
  6398. this.update();
  6399. },
  6400. onRemove: function (map) {
  6401. if (this.dragging && this.dragging.enabled()) {
  6402. this.options.draggable = true;
  6403. this.dragging.removeHooks();
  6404. }
  6405. delete this.dragging;
  6406. if (this._zoomAnimated) {
  6407. map.off('zoomanim', this._animateZoom, this);
  6408. }
  6409. this._removeIcon();
  6410. this._removeShadow();
  6411. },
  6412. getEvents: function () {
  6413. return {
  6414. zoom: this.update,
  6415. viewreset: this.update
  6416. };
  6417. },
  6418. // @method getLatLng: LatLng
  6419. // Returns the current geographical position of the marker.
  6420. getLatLng: function () {
  6421. return this._latlng;
  6422. },
  6423. // @method setLatLng(latlng: LatLng): this
  6424. // Changes the marker position to the given point.
  6425. setLatLng: function (latlng) {
  6426. var oldLatLng = this._latlng;
  6427. this._latlng = toLatLng(latlng);
  6428. this.update();
  6429. // @event move: Event
  6430. // 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`.
  6431. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6432. },
  6433. // @method setZIndexOffset(offset: Number): this
  6434. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6435. setZIndexOffset: function (offset) {
  6436. this.options.zIndexOffset = offset;
  6437. return this.update();
  6438. },
  6439. // @method getIcon: Icon
  6440. // Returns the current icon used by the marker
  6441. getIcon: function () {
  6442. return this.options.icon;
  6443. },
  6444. // @method setIcon(icon: Icon): this
  6445. // Changes the marker icon.
  6446. setIcon: function (icon) {
  6447. this.options.icon = icon;
  6448. if (this._map) {
  6449. this._initIcon();
  6450. this.update();
  6451. }
  6452. if (this._popup) {
  6453. this.bindPopup(this._popup, this._popup.options);
  6454. }
  6455. return this;
  6456. },
  6457. getElement: function () {
  6458. return this._icon;
  6459. },
  6460. update: function () {
  6461. if (this._icon && this._map) {
  6462. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6463. this._setPos(pos);
  6464. }
  6465. return this;
  6466. },
  6467. _initIcon: function () {
  6468. var options = this.options,
  6469. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6470. var icon = options.icon.createIcon(this._icon),
  6471. addIcon = false;
  6472. // if we're not reusing the icon, remove the old one and init new one
  6473. if (icon !== this._icon) {
  6474. if (this._icon) {
  6475. this._removeIcon();
  6476. }
  6477. addIcon = true;
  6478. if (options.title) {
  6479. icon.title = options.title;
  6480. }
  6481. if (icon.tagName === 'IMG') {
  6482. icon.alt = options.alt || '';
  6483. }
  6484. }
  6485. addClass(icon, classToAdd);
  6486. if (options.keyboard) {
  6487. icon.tabIndex = '0';
  6488. icon.setAttribute('role', 'button');
  6489. }
  6490. this._icon = icon;
  6491. if (options.riseOnHover) {
  6492. this.on({
  6493. mouseover: this._bringToFront,
  6494. mouseout: this._resetZIndex
  6495. });
  6496. }
  6497. if (this.options.autoPanOnFocus) {
  6498. on(icon, 'focus', this._panOnFocus, this);
  6499. }
  6500. var newShadow = options.icon.createShadow(this._shadow),
  6501. addShadow = false;
  6502. if (newShadow !== this._shadow) {
  6503. this._removeShadow();
  6504. addShadow = true;
  6505. }
  6506. if (newShadow) {
  6507. addClass(newShadow, classToAdd);
  6508. newShadow.alt = '';
  6509. }
  6510. this._shadow = newShadow;
  6511. if (options.opacity < 1) {
  6512. this._updateOpacity();
  6513. }
  6514. if (addIcon) {
  6515. this.getPane().appendChild(this._icon);
  6516. }
  6517. this._initInteraction();
  6518. if (newShadow && addShadow) {
  6519. this.getPane(options.shadowPane).appendChild(this._shadow);
  6520. }
  6521. },
  6522. _removeIcon: function () {
  6523. if (this.options.riseOnHover) {
  6524. this.off({
  6525. mouseover: this._bringToFront,
  6526. mouseout: this._resetZIndex
  6527. });
  6528. }
  6529. if (this.options.autoPanOnFocus) {
  6530. off(this._icon, 'focus', this._panOnFocus, this);
  6531. }
  6532. remove(this._icon);
  6533. this.removeInteractiveTarget(this._icon);
  6534. this._icon = null;
  6535. },
  6536. _removeShadow: function () {
  6537. if (this._shadow) {
  6538. remove(this._shadow);
  6539. }
  6540. this._shadow = null;
  6541. },
  6542. _setPos: function (pos) {
  6543. if (this._icon) {
  6544. setPosition(this._icon, pos);
  6545. }
  6546. if (this._shadow) {
  6547. setPosition(this._shadow, pos);
  6548. }
  6549. this._zIndex = pos.y + this.options.zIndexOffset;
  6550. this._resetZIndex();
  6551. },
  6552. _updateZIndex: function (offset) {
  6553. if (this._icon) {
  6554. this._icon.style.zIndex = this._zIndex + offset;
  6555. }
  6556. },
  6557. _animateZoom: function (opt) {
  6558. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6559. this._setPos(pos);
  6560. },
  6561. _initInteraction: function () {
  6562. if (!this.options.interactive) { return; }
  6563. addClass(this._icon, 'leaflet-interactive');
  6564. this.addInteractiveTarget(this._icon);
  6565. if (MarkerDrag) {
  6566. var draggable = this.options.draggable;
  6567. if (this.dragging) {
  6568. draggable = this.dragging.enabled();
  6569. this.dragging.disable();
  6570. }
  6571. this.dragging = new MarkerDrag(this);
  6572. if (draggable) {
  6573. this.dragging.enable();
  6574. }
  6575. }
  6576. },
  6577. // @method setOpacity(opacity: Number): this
  6578. // Changes the opacity of the marker.
  6579. setOpacity: function (opacity) {
  6580. this.options.opacity = opacity;
  6581. if (this._map) {
  6582. this._updateOpacity();
  6583. }
  6584. return this;
  6585. },
  6586. _updateOpacity: function () {
  6587. var opacity = this.options.opacity;
  6588. if (this._icon) {
  6589. setOpacity(this._icon, opacity);
  6590. }
  6591. if (this._shadow) {
  6592. setOpacity(this._shadow, opacity);
  6593. }
  6594. },
  6595. _bringToFront: function () {
  6596. this._updateZIndex(this.options.riseOffset);
  6597. },
  6598. _resetZIndex: function () {
  6599. this._updateZIndex(0);
  6600. },
  6601. _panOnFocus: function () {
  6602. var map = this._map;
  6603. if (!map) { return; }
  6604. var iconOpts = this.options.icon.options;
  6605. var size = iconOpts.iconSize ? toPoint(iconOpts.iconSize) : toPoint(0, 0);
  6606. var anchor = iconOpts.iconAnchor ? toPoint(iconOpts.iconAnchor) : toPoint(0, 0);
  6607. map.panInside(this._latlng, {
  6608. paddingTopLeft: anchor,
  6609. paddingBottomRight: size.subtract(anchor)
  6610. });
  6611. },
  6612. _getPopupAnchor: function () {
  6613. return this.options.icon.options.popupAnchor;
  6614. },
  6615. _getTooltipAnchor: function () {
  6616. return this.options.icon.options.tooltipAnchor;
  6617. }
  6618. });
  6619. // factory L.marker(latlng: LatLng, options? : Marker options)
  6620. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6621. // Instantiates a Marker object given a geographical point and optionally an options object.
  6622. function marker(latlng, options) {
  6623. return new Marker(latlng, options);
  6624. }
  6625. /*
  6626. * @class Path
  6627. * @aka L.Path
  6628. * @inherits Interactive layer
  6629. *
  6630. * An abstract class that contains options and constants shared between vector
  6631. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6632. */
  6633. var Path = Layer.extend({
  6634. // @section
  6635. // @aka Path options
  6636. options: {
  6637. // @option stroke: Boolean = true
  6638. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6639. stroke: true,
  6640. // @option color: String = '#3388ff'
  6641. // Stroke color
  6642. color: '#3388ff',
  6643. // @option weight: Number = 3
  6644. // Stroke width in pixels
  6645. weight: 3,
  6646. // @option opacity: Number = 1.0
  6647. // Stroke opacity
  6648. opacity: 1,
  6649. // @option lineCap: String= 'round'
  6650. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6651. lineCap: 'round',
  6652. // @option lineJoin: String = 'round'
  6653. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6654. lineJoin: 'round',
  6655. // @option dashArray: String = null
  6656. // 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).
  6657. dashArray: null,
  6658. // @option dashOffset: String = null
  6659. // 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).
  6660. dashOffset: null,
  6661. // @option fill: Boolean = depends
  6662. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6663. fill: false,
  6664. // @option fillColor: String = *
  6665. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6666. fillColor: null,
  6667. // @option fillOpacity: Number = 0.2
  6668. // Fill opacity.
  6669. fillOpacity: 0.2,
  6670. // @option fillRule: String = 'evenodd'
  6671. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6672. fillRule: 'evenodd',
  6673. // className: '',
  6674. // Option inherited from "Interactive layer" abstract class
  6675. interactive: true,
  6676. // @option bubblingMouseEvents: Boolean = true
  6677. // When `true`, a mouse event on this path will trigger the same event on the map
  6678. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6679. bubblingMouseEvents: true
  6680. },
  6681. beforeAdd: function (map) {
  6682. // Renderer is set here because we need to call renderer.getEvents
  6683. // before this.getEvents.
  6684. this._renderer = map.getRenderer(this);
  6685. },
  6686. onAdd: function () {
  6687. this._renderer._initPath(this);
  6688. this._reset();
  6689. this._renderer._addPath(this);
  6690. },
  6691. onRemove: function () {
  6692. this._renderer._removePath(this);
  6693. },
  6694. // @method redraw(): this
  6695. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6696. redraw: function () {
  6697. if (this._map) {
  6698. this._renderer._updatePath(this);
  6699. }
  6700. return this;
  6701. },
  6702. // @method setStyle(style: Path options): this
  6703. // Changes the appearance of a Path based on the options in the `Path options` object.
  6704. setStyle: function (style) {
  6705. setOptions(this, style);
  6706. if (this._renderer) {
  6707. this._renderer._updateStyle(this);
  6708. if (this.options.stroke && style && Object.prototype.hasOwnProperty.call(style, 'weight')) {
  6709. this._updateBounds();
  6710. }
  6711. }
  6712. return this;
  6713. },
  6714. // @method bringToFront(): this
  6715. // Brings the layer to the top of all path layers.
  6716. bringToFront: function () {
  6717. if (this._renderer) {
  6718. this._renderer._bringToFront(this);
  6719. }
  6720. return this;
  6721. },
  6722. // @method bringToBack(): this
  6723. // Brings the layer to the bottom of all path layers.
  6724. bringToBack: function () {
  6725. if (this._renderer) {
  6726. this._renderer._bringToBack(this);
  6727. }
  6728. return this;
  6729. },
  6730. getElement: function () {
  6731. return this._path;
  6732. },
  6733. _reset: function () {
  6734. // defined in child classes
  6735. this._project();
  6736. this._update();
  6737. },
  6738. _clickTolerance: function () {
  6739. // used when doing hit detection for Canvas layers
  6740. return (this.options.stroke ? this.options.weight / 2 : 0) +
  6741. (this._renderer.options.tolerance || 0);
  6742. }
  6743. });
  6744. /*
  6745. * @class CircleMarker
  6746. * @aka L.CircleMarker
  6747. * @inherits Path
  6748. *
  6749. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6750. */
  6751. var CircleMarker = Path.extend({
  6752. // @section
  6753. // @aka CircleMarker options
  6754. options: {
  6755. fill: true,
  6756. // @option radius: Number = 10
  6757. // Radius of the circle marker, in pixels
  6758. radius: 10
  6759. },
  6760. initialize: function (latlng, options) {
  6761. setOptions(this, options);
  6762. this._latlng = toLatLng(latlng);
  6763. this._radius = this.options.radius;
  6764. },
  6765. // @method setLatLng(latLng: LatLng): this
  6766. // Sets the position of a circle marker to a new location.
  6767. setLatLng: function (latlng) {
  6768. var oldLatLng = this._latlng;
  6769. this._latlng = toLatLng(latlng);
  6770. this.redraw();
  6771. // @event move: Event
  6772. // Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.
  6773. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6774. },
  6775. // @method getLatLng(): LatLng
  6776. // Returns the current geographical position of the circle marker
  6777. getLatLng: function () {
  6778. return this._latlng;
  6779. },
  6780. // @method setRadius(radius: Number): this
  6781. // Sets the radius of a circle marker. Units are in pixels.
  6782. setRadius: function (radius) {
  6783. this.options.radius = this._radius = radius;
  6784. return this.redraw();
  6785. },
  6786. // @method getRadius(): Number
  6787. // Returns the current radius of the circle
  6788. getRadius: function () {
  6789. return this._radius;
  6790. },
  6791. setStyle : function (options) {
  6792. var radius = options && options.radius || this._radius;
  6793. Path.prototype.setStyle.call(this, options);
  6794. this.setRadius(radius);
  6795. return this;
  6796. },
  6797. _project: function () {
  6798. this._point = this._map.latLngToLayerPoint(this._latlng);
  6799. this._updateBounds();
  6800. },
  6801. _updateBounds: function () {
  6802. var r = this._radius,
  6803. r2 = this._radiusY || r,
  6804. w = this._clickTolerance(),
  6805. p = [r + w, r2 + w];
  6806. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6807. },
  6808. _update: function () {
  6809. if (this._map) {
  6810. this._updatePath();
  6811. }
  6812. },
  6813. _updatePath: function () {
  6814. this._renderer._updateCircle(this);
  6815. },
  6816. _empty: function () {
  6817. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6818. },
  6819. // Needed by the `Canvas` renderer for interactivity
  6820. _containsPoint: function (p) {
  6821. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6822. }
  6823. });
  6824. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6825. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6826. function circleMarker(latlng, options) {
  6827. return new CircleMarker(latlng, options);
  6828. }
  6829. /*
  6830. * @class Circle
  6831. * @aka L.Circle
  6832. * @inherits CircleMarker
  6833. *
  6834. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6835. *
  6836. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6837. *
  6838. * @example
  6839. *
  6840. * ```js
  6841. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6842. * ```
  6843. */
  6844. var Circle = CircleMarker.extend({
  6845. initialize: function (latlng, options, legacyOptions) {
  6846. if (typeof options === 'number') {
  6847. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6848. options = extend({}, legacyOptions, {radius: options});
  6849. }
  6850. setOptions(this, options);
  6851. this._latlng = toLatLng(latlng);
  6852. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6853. // @section
  6854. // @aka Circle options
  6855. // @option radius: Number; Radius of the circle, in meters.
  6856. this._mRadius = this.options.radius;
  6857. },
  6858. // @method setRadius(radius: Number): this
  6859. // Sets the radius of a circle. Units are in meters.
  6860. setRadius: function (radius) {
  6861. this._mRadius = radius;
  6862. return this.redraw();
  6863. },
  6864. // @method getRadius(): Number
  6865. // Returns the current radius of a circle. Units are in meters.
  6866. getRadius: function () {
  6867. return this._mRadius;
  6868. },
  6869. // @method getBounds(): LatLngBounds
  6870. // Returns the `LatLngBounds` of the path.
  6871. getBounds: function () {
  6872. var half = [this._radius, this._radiusY || this._radius];
  6873. return new LatLngBounds(
  6874. this._map.layerPointToLatLng(this._point.subtract(half)),
  6875. this._map.layerPointToLatLng(this._point.add(half)));
  6876. },
  6877. setStyle: Path.prototype.setStyle,
  6878. _project: function () {
  6879. var lng = this._latlng.lng,
  6880. lat = this._latlng.lat,
  6881. map = this._map,
  6882. crs = map.options.crs;
  6883. if (crs.distance === Earth.distance) {
  6884. var d = Math.PI / 180,
  6885. latR = (this._mRadius / Earth.R) / d,
  6886. top = map.project([lat + latR, lng]),
  6887. bottom = map.project([lat - latR, lng]),
  6888. p = top.add(bottom).divideBy(2),
  6889. lat2 = map.unproject(p).lat,
  6890. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6891. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6892. if (isNaN(lngR) || lngR === 0) {
  6893. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6894. }
  6895. this._point = p.subtract(map.getPixelOrigin());
  6896. this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
  6897. this._radiusY = p.y - top.y;
  6898. } else {
  6899. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6900. this._point = map.latLngToLayerPoint(this._latlng);
  6901. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6902. }
  6903. this._updateBounds();
  6904. }
  6905. });
  6906. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6907. // Instantiates a circle object given a geographical point, and an options object
  6908. // which contains the circle radius.
  6909. // @alternative
  6910. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6911. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6912. // Do not use in new applications or plugins.
  6913. function circle(latlng, options, legacyOptions) {
  6914. return new Circle(latlng, options, legacyOptions);
  6915. }
  6916. /*
  6917. * @class Polyline
  6918. * @aka L.Polyline
  6919. * @inherits Path
  6920. *
  6921. * A class for drawing polyline overlays on a map. Extends `Path`.
  6922. *
  6923. * @example
  6924. *
  6925. * ```js
  6926. * // create a red polyline from an array of LatLng points
  6927. * var latlngs = [
  6928. * [45.51, -122.68],
  6929. * [37.77, -122.43],
  6930. * [34.04, -118.2]
  6931. * ];
  6932. *
  6933. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6934. *
  6935. * // zoom the map to the polyline
  6936. * map.fitBounds(polyline.getBounds());
  6937. * ```
  6938. *
  6939. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6940. *
  6941. * ```js
  6942. * // create a red polyline from an array of arrays of LatLng points
  6943. * var latlngs = [
  6944. * [[45.51, -122.68],
  6945. * [37.77, -122.43],
  6946. * [34.04, -118.2]],
  6947. * [[40.78, -73.91],
  6948. * [41.83, -87.62],
  6949. * [32.76, -96.72]]
  6950. * ];
  6951. * ```
  6952. */
  6953. var Polyline = Path.extend({
  6954. // @section
  6955. // @aka Polyline options
  6956. options: {
  6957. // @option smoothFactor: Number = 1.0
  6958. // How much to simplify the polyline on each zoom level. More means
  6959. // better performance and smoother look, and less means more accurate representation.
  6960. smoothFactor: 1.0,
  6961. // @option noClip: Boolean = false
  6962. // Disable polyline clipping.
  6963. noClip: false
  6964. },
  6965. initialize: function (latlngs, options) {
  6966. setOptions(this, options);
  6967. this._setLatLngs(latlngs);
  6968. },
  6969. // @method getLatLngs(): LatLng[]
  6970. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6971. getLatLngs: function () {
  6972. return this._latlngs;
  6973. },
  6974. // @method setLatLngs(latlngs: LatLng[]): this
  6975. // Replaces all the points in the polyline with the given array of geographical points.
  6976. setLatLngs: function (latlngs) {
  6977. this._setLatLngs(latlngs);
  6978. return this.redraw();
  6979. },
  6980. // @method isEmpty(): Boolean
  6981. // Returns `true` if the Polyline has no LatLngs.
  6982. isEmpty: function () {
  6983. return !this._latlngs.length;
  6984. },
  6985. // @method closestLayerPoint(p: Point): Point
  6986. // Returns the point closest to `p` on the Polyline.
  6987. closestLayerPoint: function (p) {
  6988. var minDistance = Infinity,
  6989. minPoint = null,
  6990. closest = _sqClosestPointOnSegment,
  6991. p1, p2;
  6992. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6993. var points = this._parts[j];
  6994. for (var i = 1, len = points.length; i < len; i++) {
  6995. p1 = points[i - 1];
  6996. p2 = points[i];
  6997. var sqDist = closest(p, p1, p2, true);
  6998. if (sqDist < minDistance) {
  6999. minDistance = sqDist;
  7000. minPoint = closest(p, p1, p2);
  7001. }
  7002. }
  7003. }
  7004. if (minPoint) {
  7005. minPoint.distance = Math.sqrt(minDistance);
  7006. }
  7007. return minPoint;
  7008. },
  7009. // @method getCenter(): LatLng
  7010. // Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline.
  7011. getCenter: function () {
  7012. // throws error when not yet added to map as this center calculation requires projected coordinates
  7013. if (!this._map) {
  7014. throw new Error('Must add layer to map before using getCenter()');
  7015. }
  7016. return polylineCenter(this._defaultShape(), this._map.options.crs);
  7017. },
  7018. // @method getBounds(): LatLngBounds
  7019. // Returns the `LatLngBounds` of the path.
  7020. getBounds: function () {
  7021. return this._bounds;
  7022. },
  7023. // @method addLatLng(latlng: LatLng, latlngs?: LatLng[]): this
  7024. // Adds a given point to the polyline. By default, adds to the first ring of
  7025. // the polyline in case of a multi-polyline, but can be overridden by passing
  7026. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  7027. addLatLng: function (latlng, latlngs) {
  7028. latlngs = latlngs || this._defaultShape();
  7029. latlng = toLatLng(latlng);
  7030. latlngs.push(latlng);
  7031. this._bounds.extend(latlng);
  7032. return this.redraw();
  7033. },
  7034. _setLatLngs: function (latlngs) {
  7035. this._bounds = new LatLngBounds();
  7036. this._latlngs = this._convertLatLngs(latlngs);
  7037. },
  7038. _defaultShape: function () {
  7039. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  7040. },
  7041. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  7042. _convertLatLngs: function (latlngs) {
  7043. var result = [],
  7044. flat = isFlat(latlngs);
  7045. for (var i = 0, len = latlngs.length; i < len; i++) {
  7046. if (flat) {
  7047. result[i] = toLatLng(latlngs[i]);
  7048. this._bounds.extend(result[i]);
  7049. } else {
  7050. result[i] = this._convertLatLngs(latlngs[i]);
  7051. }
  7052. }
  7053. return result;
  7054. },
  7055. _project: function () {
  7056. var pxBounds = new Bounds();
  7057. this._rings = [];
  7058. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  7059. if (this._bounds.isValid() && pxBounds.isValid()) {
  7060. this._rawPxBounds = pxBounds;
  7061. this._updateBounds();
  7062. }
  7063. },
  7064. _updateBounds: function () {
  7065. var w = this._clickTolerance(),
  7066. p = new Point(w, w);
  7067. if (!this._rawPxBounds) {
  7068. return;
  7069. }
  7070. this._pxBounds = new Bounds([
  7071. this._rawPxBounds.min.subtract(p),
  7072. this._rawPxBounds.max.add(p)
  7073. ]);
  7074. },
  7075. // recursively turns latlngs into a set of rings with projected coordinates
  7076. _projectLatlngs: function (latlngs, result, projectedBounds) {
  7077. var flat = latlngs[0] instanceof LatLng,
  7078. len = latlngs.length,
  7079. i, ring;
  7080. if (flat) {
  7081. ring = [];
  7082. for (i = 0; i < len; i++) {
  7083. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  7084. projectedBounds.extend(ring[i]);
  7085. }
  7086. result.push(ring);
  7087. } else {
  7088. for (i = 0; i < len; i++) {
  7089. this._projectLatlngs(latlngs[i], result, projectedBounds);
  7090. }
  7091. }
  7092. },
  7093. // clip polyline by renderer bounds so that we have less to render for performance
  7094. _clipPoints: function () {
  7095. var bounds = this._renderer._bounds;
  7096. this._parts = [];
  7097. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7098. return;
  7099. }
  7100. if (this.options.noClip) {
  7101. this._parts = this._rings;
  7102. return;
  7103. }
  7104. var parts = this._parts,
  7105. i, j, k, len, len2, segment, points;
  7106. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  7107. points = this._rings[i];
  7108. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  7109. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  7110. if (!segment) { continue; }
  7111. parts[k] = parts[k] || [];
  7112. parts[k].push(segment[0]);
  7113. // if segment goes out of screen, or it's the last one, it's the end of the line part
  7114. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  7115. parts[k].push(segment[1]);
  7116. k++;
  7117. }
  7118. }
  7119. }
  7120. },
  7121. // simplify each clipped part of the polyline for performance
  7122. _simplifyPoints: function () {
  7123. var parts = this._parts,
  7124. tolerance = this.options.smoothFactor;
  7125. for (var i = 0, len = parts.length; i < len; i++) {
  7126. parts[i] = simplify(parts[i], tolerance);
  7127. }
  7128. },
  7129. _update: function () {
  7130. if (!this._map) { return; }
  7131. this._clipPoints();
  7132. this._simplifyPoints();
  7133. this._updatePath();
  7134. },
  7135. _updatePath: function () {
  7136. this._renderer._updatePoly(this);
  7137. },
  7138. // Needed by the `Canvas` renderer for interactivity
  7139. _containsPoint: function (p, closed) {
  7140. var i, j, k, len, len2, part,
  7141. w = this._clickTolerance();
  7142. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  7143. // hit detection for polylines
  7144. for (i = 0, len = this._parts.length; i < len; i++) {
  7145. part = this._parts[i];
  7146. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7147. if (!closed && (j === 0)) { continue; }
  7148. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  7149. return true;
  7150. }
  7151. }
  7152. }
  7153. return false;
  7154. }
  7155. });
  7156. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  7157. // Instantiates a polyline object given an array of geographical points and
  7158. // optionally an options object. You can create a `Polyline` object with
  7159. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  7160. // of geographic points.
  7161. function polyline(latlngs, options) {
  7162. return new Polyline(latlngs, options);
  7163. }
  7164. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  7165. Polyline._flat = _flat;
  7166. /*
  7167. * @class Polygon
  7168. * @aka L.Polygon
  7169. * @inherits Polyline
  7170. *
  7171. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  7172. *
  7173. * 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.
  7174. *
  7175. *
  7176. * @example
  7177. *
  7178. * ```js
  7179. * // create a red polygon from an array of LatLng points
  7180. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  7181. *
  7182. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  7183. *
  7184. * // zoom the map to the polygon
  7185. * map.fitBounds(polygon.getBounds());
  7186. * ```
  7187. *
  7188. * 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:
  7189. *
  7190. * ```js
  7191. * var latlngs = [
  7192. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7193. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7194. * ];
  7195. * ```
  7196. *
  7197. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  7198. *
  7199. * ```js
  7200. * var latlngs = [
  7201. * [ // first polygon
  7202. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  7203. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  7204. * ],
  7205. * [ // second polygon
  7206. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  7207. * ]
  7208. * ];
  7209. * ```
  7210. */
  7211. var Polygon = Polyline.extend({
  7212. options: {
  7213. fill: true
  7214. },
  7215. isEmpty: function () {
  7216. return !this._latlngs.length || !this._latlngs[0].length;
  7217. },
  7218. // @method getCenter(): LatLng
  7219. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the Polygon.
  7220. getCenter: function () {
  7221. // throws error when not yet added to map as this center calculation requires projected coordinates
  7222. if (!this._map) {
  7223. throw new Error('Must add layer to map before using getCenter()');
  7224. }
  7225. return polygonCenter(this._defaultShape(), this._map.options.crs);
  7226. },
  7227. _convertLatLngs: function (latlngs) {
  7228. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  7229. len = result.length;
  7230. // remove last point if it equals first one
  7231. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  7232. result.pop();
  7233. }
  7234. return result;
  7235. },
  7236. _setLatLngs: function (latlngs) {
  7237. Polyline.prototype._setLatLngs.call(this, latlngs);
  7238. if (isFlat(this._latlngs)) {
  7239. this._latlngs = [this._latlngs];
  7240. }
  7241. },
  7242. _defaultShape: function () {
  7243. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  7244. },
  7245. _clipPoints: function () {
  7246. // polygons need a different clipping algorithm so we redefine that
  7247. var bounds = this._renderer._bounds,
  7248. w = this.options.weight,
  7249. p = new Point(w, w);
  7250. // increase clip padding by stroke width to avoid stroke on clip edges
  7251. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  7252. this._parts = [];
  7253. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  7254. return;
  7255. }
  7256. if (this.options.noClip) {
  7257. this._parts = this._rings;
  7258. return;
  7259. }
  7260. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  7261. clipped = clipPolygon(this._rings[i], bounds, true);
  7262. if (clipped.length) {
  7263. this._parts.push(clipped);
  7264. }
  7265. }
  7266. },
  7267. _updatePath: function () {
  7268. this._renderer._updatePoly(this, true);
  7269. },
  7270. // Needed by the `Canvas` renderer for interactivity
  7271. _containsPoint: function (p) {
  7272. var inside = false,
  7273. part, p1, p2, i, j, k, len, len2;
  7274. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  7275. // ray casting algorithm for detecting if point is in polygon
  7276. for (i = 0, len = this._parts.length; i < len; i++) {
  7277. part = this._parts[i];
  7278. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  7279. p1 = part[j];
  7280. p2 = part[k];
  7281. 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)) {
  7282. inside = !inside;
  7283. }
  7284. }
  7285. }
  7286. // also check if it's on polygon stroke
  7287. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  7288. }
  7289. });
  7290. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  7291. function polygon(latlngs, options) {
  7292. return new Polygon(latlngs, options);
  7293. }
  7294. /*
  7295. * @class GeoJSON
  7296. * @aka L.GeoJSON
  7297. * @inherits FeatureGroup
  7298. *
  7299. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  7300. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  7301. *
  7302. * @example
  7303. *
  7304. * ```js
  7305. * L.geoJSON(data, {
  7306. * style: function (feature) {
  7307. * return {color: feature.properties.color};
  7308. * }
  7309. * }).bindPopup(function (layer) {
  7310. * return layer.feature.properties.description;
  7311. * }).addTo(map);
  7312. * ```
  7313. */
  7314. var GeoJSON = FeatureGroup.extend({
  7315. /* @section
  7316. * @aka GeoJSON options
  7317. *
  7318. * @option pointToLayer: Function = *
  7319. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  7320. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  7321. * The default is to spawn a default `Marker`:
  7322. * ```js
  7323. * function(geoJsonPoint, latlng) {
  7324. * return L.marker(latlng);
  7325. * }
  7326. * ```
  7327. *
  7328. * @option style: Function = *
  7329. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  7330. * called internally when data is added.
  7331. * The default value is to not override any defaults:
  7332. * ```js
  7333. * function (geoJsonFeature) {
  7334. * return {}
  7335. * }
  7336. * ```
  7337. *
  7338. * @option onEachFeature: Function = *
  7339. * A `Function` that will be called once for each created `Feature`, after it has
  7340. * been created and styled. Useful for attaching events and popups to features.
  7341. * The default is to do nothing with the newly created layers:
  7342. * ```js
  7343. * function (feature, layer) {}
  7344. * ```
  7345. *
  7346. * @option filter: Function = *
  7347. * A `Function` that will be used to decide whether to include a feature or not.
  7348. * The default is to include all features:
  7349. * ```js
  7350. * function (geoJsonFeature) {
  7351. * return true;
  7352. * }
  7353. * ```
  7354. * Note: dynamically changing the `filter` option will have effect only on newly
  7355. * added data. It will _not_ re-evaluate already included features.
  7356. *
  7357. * @option coordsToLatLng: Function = *
  7358. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  7359. * The default is the `coordsToLatLng` static method.
  7360. *
  7361. * @option markersInheritOptions: Boolean = false
  7362. * Whether default Markers for "Point" type Features inherit from group options.
  7363. */
  7364. initialize: function (geojson, options) {
  7365. setOptions(this, options);
  7366. this._layers = {};
  7367. if (geojson) {
  7368. this.addData(geojson);
  7369. }
  7370. },
  7371. // @method addData( <GeoJSON> data ): this
  7372. // Adds a GeoJSON object to the layer.
  7373. addData: function (geojson) {
  7374. var features = isArray(geojson) ? geojson : geojson.features,
  7375. i, len, feature;
  7376. if (features) {
  7377. for (i = 0, len = features.length; i < len; i++) {
  7378. // only add this if geometry or geometries are set and not null
  7379. feature = features[i];
  7380. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  7381. this.addData(feature);
  7382. }
  7383. }
  7384. return this;
  7385. }
  7386. var options = this.options;
  7387. if (options.filter && !options.filter(geojson)) { return this; }
  7388. var layer = geometryToLayer(geojson, options);
  7389. if (!layer) {
  7390. return this;
  7391. }
  7392. layer.feature = asFeature(geojson);
  7393. layer.defaultOptions = layer.options;
  7394. this.resetStyle(layer);
  7395. if (options.onEachFeature) {
  7396. options.onEachFeature(geojson, layer);
  7397. }
  7398. return this.addLayer(layer);
  7399. },
  7400. // @method resetStyle( <Path> layer? ): this
  7401. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7402. // If `layer` is omitted, the style of all features in the current layer is reset.
  7403. resetStyle: function (layer) {
  7404. if (layer === undefined) {
  7405. return this.eachLayer(this.resetStyle, this);
  7406. }
  7407. // reset any custom styles
  7408. layer.options = extend({}, layer.defaultOptions);
  7409. this._setLayerStyle(layer, this.options.style);
  7410. return this;
  7411. },
  7412. // @method setStyle( <Function> style ): this
  7413. // Changes styles of GeoJSON vector layers with the given style function.
  7414. setStyle: function (style) {
  7415. return this.eachLayer(function (layer) {
  7416. this._setLayerStyle(layer, style);
  7417. }, this);
  7418. },
  7419. _setLayerStyle: function (layer, style) {
  7420. if (layer.setStyle) {
  7421. if (typeof style === 'function') {
  7422. style = style(layer.feature);
  7423. }
  7424. layer.setStyle(style);
  7425. }
  7426. }
  7427. });
  7428. // @section
  7429. // There are several static functions which can be called without instantiating L.GeoJSON:
  7430. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7431. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7432. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7433. // functions if provided as options.
  7434. function geometryToLayer(geojson, options) {
  7435. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7436. coords = geometry ? geometry.coordinates : null,
  7437. layers = [],
  7438. pointToLayer = options && options.pointToLayer,
  7439. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7440. latlng, latlngs, i, len;
  7441. if (!coords && !geometry) {
  7442. return null;
  7443. }
  7444. switch (geometry.type) {
  7445. case 'Point':
  7446. latlng = _coordsToLatLng(coords);
  7447. return _pointToLayer(pointToLayer, geojson, latlng, options);
  7448. case 'MultiPoint':
  7449. for (i = 0, len = coords.length; i < len; i++) {
  7450. latlng = _coordsToLatLng(coords[i]);
  7451. layers.push(_pointToLayer(pointToLayer, geojson, latlng, options));
  7452. }
  7453. return new FeatureGroup(layers);
  7454. case 'LineString':
  7455. case 'MultiLineString':
  7456. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7457. return new Polyline(latlngs, options);
  7458. case 'Polygon':
  7459. case 'MultiPolygon':
  7460. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7461. return new Polygon(latlngs, options);
  7462. case 'GeometryCollection':
  7463. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7464. var geoLayer = geometryToLayer({
  7465. geometry: geometry.geometries[i],
  7466. type: 'Feature',
  7467. properties: geojson.properties
  7468. }, options);
  7469. if (geoLayer) {
  7470. layers.push(geoLayer);
  7471. }
  7472. }
  7473. return new FeatureGroup(layers);
  7474. case 'FeatureCollection':
  7475. for (i = 0, len = geometry.features.length; i < len; i++) {
  7476. var featureLayer = geometryToLayer(geometry.features[i], options);
  7477. if (featureLayer) {
  7478. layers.push(featureLayer);
  7479. }
  7480. }
  7481. return new FeatureGroup(layers);
  7482. default:
  7483. throw new Error('Invalid GeoJSON object.');
  7484. }
  7485. }
  7486. function _pointToLayer(pointToLayerFn, geojson, latlng, options) {
  7487. return pointToLayerFn ?
  7488. pointToLayerFn(geojson, latlng) :
  7489. new Marker(latlng, options && options.markersInheritOptions && options);
  7490. }
  7491. // @function coordsToLatLng(coords: Array): LatLng
  7492. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7493. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7494. function coordsToLatLng(coords) {
  7495. return new LatLng(coords[1], coords[0], coords[2]);
  7496. }
  7497. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7498. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7499. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7500. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7501. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7502. var latlngs = [];
  7503. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7504. latlng = levelsDeep ?
  7505. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7506. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7507. latlngs.push(latlng);
  7508. }
  7509. return latlngs;
  7510. }
  7511. // @function latLngToCoords(latlng: LatLng, precision?: Number|false): Array
  7512. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7513. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function.
  7514. function latLngToCoords(latlng, precision) {
  7515. latlng = toLatLng(latlng);
  7516. return latlng.alt !== undefined ?
  7517. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7518. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7519. }
  7520. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean, precision?: Number|false): Array
  7521. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7522. // `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.
  7523. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function.
  7524. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7525. var coords = [];
  7526. for (var i = 0, len = latlngs.length; i < len; i++) {
  7527. // Check for flat arrays required to ensure unbalanced arrays are correctly converted in recursion
  7528. coords.push(levelsDeep ?
  7529. latLngsToCoords(latlngs[i], isFlat(latlngs[i]) ? 0 : levelsDeep - 1, closed, precision) :
  7530. latLngToCoords(latlngs[i], precision));
  7531. }
  7532. if (!levelsDeep && closed && coords.length > 0) {
  7533. coords.push(coords[0].slice());
  7534. }
  7535. return coords;
  7536. }
  7537. function getFeature(layer, newGeometry) {
  7538. return layer.feature ?
  7539. extend({}, layer.feature, {geometry: newGeometry}) :
  7540. asFeature(newGeometry);
  7541. }
  7542. // @function asFeature(geojson: Object): Object
  7543. // Normalize GeoJSON geometries/features into GeoJSON features.
  7544. function asFeature(geojson) {
  7545. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7546. return geojson;
  7547. }
  7548. return {
  7549. type: 'Feature',
  7550. properties: {},
  7551. geometry: geojson
  7552. };
  7553. }
  7554. var PointToGeoJSON = {
  7555. toGeoJSON: function (precision) {
  7556. return getFeature(this, {
  7557. type: 'Point',
  7558. coordinates: latLngToCoords(this.getLatLng(), precision)
  7559. });
  7560. }
  7561. };
  7562. // @namespace Marker
  7563. // @section Other methods
  7564. // @method toGeoJSON(precision?: Number|false): Object
  7565. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7566. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7567. Marker.include(PointToGeoJSON);
  7568. // @namespace CircleMarker
  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 circle marker (as a GeoJSON `Point` Feature).
  7572. Circle.include(PointToGeoJSON);
  7573. CircleMarker.include(PointToGeoJSON);
  7574. // @namespace Polyline
  7575. // @method toGeoJSON(precision?: Number|false): Object
  7576. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7577. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7578. Polyline.include({
  7579. toGeoJSON: function (precision) {
  7580. var multi = !isFlat(this._latlngs);
  7581. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7582. return getFeature(this, {
  7583. type: (multi ? 'Multi' : '') + 'LineString',
  7584. coordinates: coords
  7585. });
  7586. }
  7587. });
  7588. // @namespace Polygon
  7589. // @method toGeoJSON(precision?: Number|false): Object
  7590. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7591. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7592. Polygon.include({
  7593. toGeoJSON: function (precision) {
  7594. var holes = !isFlat(this._latlngs),
  7595. multi = holes && !isFlat(this._latlngs[0]);
  7596. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7597. if (!holes) {
  7598. coords = [coords];
  7599. }
  7600. return getFeature(this, {
  7601. type: (multi ? 'Multi' : '') + 'Polygon',
  7602. coordinates: coords
  7603. });
  7604. }
  7605. });
  7606. // @namespace LayerGroup
  7607. LayerGroup.include({
  7608. toMultiPoint: function (precision) {
  7609. var coords = [];
  7610. this.eachLayer(function (layer) {
  7611. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7612. });
  7613. return getFeature(this, {
  7614. type: 'MultiPoint',
  7615. coordinates: coords
  7616. });
  7617. },
  7618. // @method toGeoJSON(precision?: Number|false): Object
  7619. // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
  7620. // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7621. toGeoJSON: function (precision) {
  7622. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7623. if (type === 'MultiPoint') {
  7624. return this.toMultiPoint(precision);
  7625. }
  7626. var isGeometryCollection = type === 'GeometryCollection',
  7627. jsons = [];
  7628. this.eachLayer(function (layer) {
  7629. if (layer.toGeoJSON) {
  7630. var json = layer.toGeoJSON(precision);
  7631. if (isGeometryCollection) {
  7632. jsons.push(json.geometry);
  7633. } else {
  7634. var feature = asFeature(json);
  7635. // Squash nested feature collections
  7636. if (feature.type === 'FeatureCollection') {
  7637. jsons.push.apply(jsons, feature.features);
  7638. } else {
  7639. jsons.push(feature);
  7640. }
  7641. }
  7642. }
  7643. });
  7644. if (isGeometryCollection) {
  7645. return getFeature(this, {
  7646. geometries: jsons,
  7647. type: 'GeometryCollection'
  7648. });
  7649. }
  7650. return {
  7651. type: 'FeatureCollection',
  7652. features: jsons
  7653. };
  7654. }
  7655. });
  7656. // @namespace GeoJSON
  7657. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7658. // Creates a GeoJSON layer. Optionally accepts an object in
  7659. // [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map
  7660. // (you can alternatively add it later with `addData` method) and an `options` object.
  7661. function geoJSON(geojson, options) {
  7662. return new GeoJSON(geojson, options);
  7663. }
  7664. // Backward compatibility.
  7665. var geoJson = geoJSON;
  7666. /*
  7667. * @class ImageOverlay
  7668. * @aka L.ImageOverlay
  7669. * @inherits Interactive layer
  7670. *
  7671. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7672. *
  7673. * @example
  7674. *
  7675. * ```js
  7676. * var imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7677. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7678. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7679. * ```
  7680. */
  7681. var ImageOverlay = Layer.extend({
  7682. // @section
  7683. // @aka ImageOverlay options
  7684. options: {
  7685. // @option opacity: Number = 1.0
  7686. // The opacity of the image overlay.
  7687. opacity: 1,
  7688. // @option alt: String = ''
  7689. // Text for the `alt` attribute of the image (useful for accessibility).
  7690. alt: '',
  7691. // @option interactive: Boolean = false
  7692. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7693. interactive: false,
  7694. // @option crossOrigin: Boolean|String = false
  7695. // Whether the crossOrigin attribute will be added to the image.
  7696. // 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.
  7697. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  7698. crossOrigin: false,
  7699. // @option errorOverlayUrl: String = ''
  7700. // URL to the overlay image to show in place of the overlay that failed to load.
  7701. errorOverlayUrl: '',
  7702. // @option zIndex: Number = 1
  7703. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
  7704. zIndex: 1,
  7705. // @option className: String = ''
  7706. // A custom class name to assign to the image. Empty by default.
  7707. className: ''
  7708. },
  7709. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7710. this._url = url;
  7711. this._bounds = toLatLngBounds(bounds);
  7712. setOptions(this, options);
  7713. },
  7714. onAdd: function () {
  7715. if (!this._image) {
  7716. this._initImage();
  7717. if (this.options.opacity < 1) {
  7718. this._updateOpacity();
  7719. }
  7720. }
  7721. if (this.options.interactive) {
  7722. addClass(this._image, 'leaflet-interactive');
  7723. this.addInteractiveTarget(this._image);
  7724. }
  7725. this.getPane().appendChild(this._image);
  7726. this._reset();
  7727. },
  7728. onRemove: function () {
  7729. remove(this._image);
  7730. if (this.options.interactive) {
  7731. this.removeInteractiveTarget(this._image);
  7732. }
  7733. },
  7734. // @method setOpacity(opacity: Number): this
  7735. // Sets the opacity of the overlay.
  7736. setOpacity: function (opacity) {
  7737. this.options.opacity = opacity;
  7738. if (this._image) {
  7739. this._updateOpacity();
  7740. }
  7741. return this;
  7742. },
  7743. setStyle: function (styleOpts) {
  7744. if (styleOpts.opacity) {
  7745. this.setOpacity(styleOpts.opacity);
  7746. }
  7747. return this;
  7748. },
  7749. // @method bringToFront(): this
  7750. // Brings the layer to the top of all overlays.
  7751. bringToFront: function () {
  7752. if (this._map) {
  7753. toFront(this._image);
  7754. }
  7755. return this;
  7756. },
  7757. // @method bringToBack(): this
  7758. // Brings the layer to the bottom of all overlays.
  7759. bringToBack: function () {
  7760. if (this._map) {
  7761. toBack(this._image);
  7762. }
  7763. return this;
  7764. },
  7765. // @method setUrl(url: String): this
  7766. // Changes the URL of the image.
  7767. setUrl: function (url) {
  7768. this._url = url;
  7769. if (this._image) {
  7770. this._image.src = url;
  7771. }
  7772. return this;
  7773. },
  7774. // @method setBounds(bounds: LatLngBounds): this
  7775. // Update the bounds that this ImageOverlay covers
  7776. setBounds: function (bounds) {
  7777. this._bounds = toLatLngBounds(bounds);
  7778. if (this._map) {
  7779. this._reset();
  7780. }
  7781. return this;
  7782. },
  7783. getEvents: function () {
  7784. var events = {
  7785. zoom: this._reset,
  7786. viewreset: this._reset
  7787. };
  7788. if (this._zoomAnimated) {
  7789. events.zoomanim = this._animateZoom;
  7790. }
  7791. return events;
  7792. },
  7793. // @method setZIndex(value: Number): this
  7794. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7795. setZIndex: function (value) {
  7796. this.options.zIndex = value;
  7797. this._updateZIndex();
  7798. return this;
  7799. },
  7800. // @method getBounds(): LatLngBounds
  7801. // Get the bounds that this ImageOverlay covers
  7802. getBounds: function () {
  7803. return this._bounds;
  7804. },
  7805. // @method getElement(): HTMLElement
  7806. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7807. // used by this overlay.
  7808. getElement: function () {
  7809. return this._image;
  7810. },
  7811. _initImage: function () {
  7812. var wasElementSupplied = this._url.tagName === 'IMG';
  7813. var img = this._image = wasElementSupplied ? this._url : create$1('img');
  7814. addClass(img, 'leaflet-image-layer');
  7815. if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
  7816. if (this.options.className) { addClass(img, this.options.className); }
  7817. img.onselectstart = falseFn;
  7818. img.onmousemove = falseFn;
  7819. // @event load: Event
  7820. // Fired when the ImageOverlay layer has loaded its image
  7821. img.onload = bind(this.fire, this, 'load');
  7822. img.onerror = bind(this._overlayOnError, this, 'error');
  7823. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  7824. img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  7825. }
  7826. if (this.options.zIndex) {
  7827. this._updateZIndex();
  7828. }
  7829. if (wasElementSupplied) {
  7830. this._url = img.src;
  7831. return;
  7832. }
  7833. img.src = this._url;
  7834. img.alt = this.options.alt;
  7835. },
  7836. _animateZoom: function (e) {
  7837. var scale = this._map.getZoomScale(e.zoom),
  7838. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7839. setTransform(this._image, offset, scale);
  7840. },
  7841. _reset: function () {
  7842. var image = this._image,
  7843. bounds = new Bounds(
  7844. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7845. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7846. size = bounds.getSize();
  7847. setPosition(image, bounds.min);
  7848. image.style.width = size.x + 'px';
  7849. image.style.height = size.y + 'px';
  7850. },
  7851. _updateOpacity: function () {
  7852. setOpacity(this._image, this.options.opacity);
  7853. },
  7854. _updateZIndex: function () {
  7855. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7856. this._image.style.zIndex = this.options.zIndex;
  7857. }
  7858. },
  7859. _overlayOnError: function () {
  7860. // @event error: Event
  7861. // Fired when the ImageOverlay layer fails to load its image
  7862. this.fire('error');
  7863. var errorUrl = this.options.errorOverlayUrl;
  7864. if (errorUrl && this._url !== errorUrl) {
  7865. this._url = errorUrl;
  7866. this._image.src = errorUrl;
  7867. }
  7868. },
  7869. // @method getCenter(): LatLng
  7870. // Returns the center of the ImageOverlay.
  7871. getCenter: function () {
  7872. return this._bounds.getCenter();
  7873. }
  7874. });
  7875. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7876. // Instantiates an image overlay object given the URL of the image and the
  7877. // geographical bounds it is tied to.
  7878. var imageOverlay = function (url, bounds, options) {
  7879. return new ImageOverlay(url, bounds, options);
  7880. };
  7881. /*
  7882. * @class VideoOverlay
  7883. * @aka L.VideoOverlay
  7884. * @inherits ImageOverlay
  7885. *
  7886. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7887. *
  7888. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7889. * HTML5 element.
  7890. *
  7891. * @example
  7892. *
  7893. * ```js
  7894. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7895. * videoBounds = [[ 32, -130], [ 13, -100]];
  7896. * L.videoOverlay(videoUrl, videoBounds ).addTo(map);
  7897. * ```
  7898. */
  7899. var VideoOverlay = ImageOverlay.extend({
  7900. // @section
  7901. // @aka VideoOverlay options
  7902. options: {
  7903. // @option autoplay: Boolean = true
  7904. // Whether the video starts playing automatically when loaded.
  7905. // On some browsers autoplay will only work with `muted: true`
  7906. autoplay: true,
  7907. // @option loop: Boolean = true
  7908. // Whether the video will loop back to the beginning when played.
  7909. loop: true,
  7910. // @option keepAspectRatio: Boolean = true
  7911. // Whether the video will save aspect ratio after the projection.
  7912. // Relevant for supported browsers. See [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
  7913. keepAspectRatio: true,
  7914. // @option muted: Boolean = false
  7915. // Whether the video starts on mute when loaded.
  7916. muted: false,
  7917. // @option playsInline: Boolean = true
  7918. // Mobile browsers will play the video right where it is instead of open it up in fullscreen mode.
  7919. playsInline: true
  7920. },
  7921. _initImage: function () {
  7922. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7923. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7924. addClass(vid, 'leaflet-image-layer');
  7925. if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
  7926. if (this.options.className) { addClass(vid, this.options.className); }
  7927. vid.onselectstart = falseFn;
  7928. vid.onmousemove = falseFn;
  7929. // @event load: Event
  7930. // Fired when the video has finished loading the first frame
  7931. vid.onloadeddata = bind(this.fire, this, 'load');
  7932. if (wasElementSupplied) {
  7933. var sourceElements = vid.getElementsByTagName('source');
  7934. var sources = [];
  7935. for (var j = 0; j < sourceElements.length; j++) {
  7936. sources.push(sourceElements[j].src);
  7937. }
  7938. this._url = (sourceElements.length > 0) ? sources : [vid.src];
  7939. return;
  7940. }
  7941. if (!isArray(this._url)) { this._url = [this._url]; }
  7942. if (!this.options.keepAspectRatio && Object.prototype.hasOwnProperty.call(vid.style, 'objectFit')) {
  7943. vid.style['objectFit'] = 'fill';
  7944. }
  7945. vid.autoplay = !!this.options.autoplay;
  7946. vid.loop = !!this.options.loop;
  7947. vid.muted = !!this.options.muted;
  7948. vid.playsInline = !!this.options.playsInline;
  7949. for (var i = 0; i < this._url.length; i++) {
  7950. var source = create$1('source');
  7951. source.src = this._url[i];
  7952. vid.appendChild(source);
  7953. }
  7954. }
  7955. // @method getElement(): HTMLVideoElement
  7956. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7957. // used by this overlay.
  7958. });
  7959. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7960. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7961. // geographical bounds it is tied to.
  7962. function videoOverlay(video, bounds, options) {
  7963. return new VideoOverlay(video, bounds, options);
  7964. }
  7965. /*
  7966. * @class SVGOverlay
  7967. * @aka L.SVGOverlay
  7968. * @inherits ImageOverlay
  7969. *
  7970. * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.
  7971. *
  7972. * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.
  7973. *
  7974. * @example
  7975. *
  7976. * ```js
  7977. * var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  7978. * svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
  7979. * svgElement.setAttribute('viewBox', "0 0 200 200");
  7980. * 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"/>';
  7981. * var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
  7982. * L.svgOverlay(svgElement, svgElementBounds).addTo(map);
  7983. * ```
  7984. */
  7985. var SVGOverlay = ImageOverlay.extend({
  7986. _initImage: function () {
  7987. var el = this._image = this._url;
  7988. addClass(el, 'leaflet-image-layer');
  7989. if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); }
  7990. if (this.options.className) { addClass(el, this.options.className); }
  7991. el.onselectstart = falseFn;
  7992. el.onmousemove = falseFn;
  7993. }
  7994. // @method getElement(): SVGElement
  7995. // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
  7996. // used by this overlay.
  7997. });
  7998. // @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)
  7999. // Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.
  8000. // A viewBox attribute is required on the SVG element to zoom in and out properly.
  8001. function svgOverlay(el, bounds, options) {
  8002. return new SVGOverlay(el, bounds, options);
  8003. }
  8004. /*
  8005. * @class DivOverlay
  8006. * @inherits Interactive layer
  8007. * @aka L.DivOverlay
  8008. * Base model for L.Popup and L.Tooltip. Inherit from it for custom overlays like plugins.
  8009. */
  8010. // @namespace DivOverlay
  8011. var DivOverlay = Layer.extend({
  8012. // @section
  8013. // @aka DivOverlay options
  8014. options: {
  8015. // @option interactive: Boolean = false
  8016. // If true, the popup/tooltip will listen to the mouse events.
  8017. interactive: false,
  8018. // @option offset: Point = Point(0, 0)
  8019. // The offset of the overlay position.
  8020. offset: [0, 0],
  8021. // @option className: String = ''
  8022. // A custom CSS class name to assign to the overlay.
  8023. className: '',
  8024. // @option pane: String = undefined
  8025. // `Map pane` where the overlay will be added.
  8026. pane: undefined,
  8027. // @option content: String|HTMLElement|Function = ''
  8028. // Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be
  8029. // passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay.
  8030. content: ''
  8031. },
  8032. initialize: function (options, source) {
  8033. if (options && (options instanceof LatLng || isArray(options))) {
  8034. this._latlng = toLatLng(options);
  8035. setOptions(this, source);
  8036. } else {
  8037. setOptions(this, options);
  8038. this._source = source;
  8039. }
  8040. if (this.options.content) {
  8041. this._content = this.options.content;
  8042. }
  8043. },
  8044. // @method openOn(map: Map): this
  8045. // Adds the overlay to the map.
  8046. // Alternative to `map.openPopup(popup)`/`.openTooltip(tooltip)`.
  8047. openOn: function (map) {
  8048. map = arguments.length ? map : this._source._map; // experimental, not the part of public api
  8049. if (!map.hasLayer(this)) {
  8050. map.addLayer(this);
  8051. }
  8052. return this;
  8053. },
  8054. // @method close(): this
  8055. // Closes the overlay.
  8056. // Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)`
  8057. // and `layer.closePopup()`/`.closeTooltip()`.
  8058. close: function () {
  8059. if (this._map) {
  8060. this._map.removeLayer(this);
  8061. }
  8062. return this;
  8063. },
  8064. // @method toggle(layer?: Layer): this
  8065. // Opens or closes the overlay bound to layer depending on its current state.
  8066. // Argument may be omitted only for overlay bound to layer.
  8067. // Alternative to `layer.togglePopup()`/`.toggleTooltip()`.
  8068. toggle: function (layer) {
  8069. if (this._map) {
  8070. this.close();
  8071. } else {
  8072. if (arguments.length) {
  8073. this._source = layer;
  8074. } else {
  8075. layer = this._source;
  8076. }
  8077. this._prepareOpen();
  8078. // open the overlay on the map
  8079. this.openOn(layer._map);
  8080. }
  8081. return this;
  8082. },
  8083. onAdd: function (map) {
  8084. this._zoomAnimated = map._zoomAnimated;
  8085. if (!this._container) {
  8086. this._initLayout();
  8087. }
  8088. if (map._fadeAnimated) {
  8089. setOpacity(this._container, 0);
  8090. }
  8091. clearTimeout(this._removeTimeout);
  8092. this.getPane().appendChild(this._container);
  8093. this.update();
  8094. if (map._fadeAnimated) {
  8095. setOpacity(this._container, 1);
  8096. }
  8097. this.bringToFront();
  8098. if (this.options.interactive) {
  8099. addClass(this._container, 'leaflet-interactive');
  8100. this.addInteractiveTarget(this._container);
  8101. }
  8102. },
  8103. onRemove: function (map) {
  8104. if (map._fadeAnimated) {
  8105. setOpacity(this._container, 0);
  8106. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  8107. } else {
  8108. remove(this._container);
  8109. }
  8110. if (this.options.interactive) {
  8111. removeClass(this._container, 'leaflet-interactive');
  8112. this.removeInteractiveTarget(this._container);
  8113. }
  8114. },
  8115. // @namespace DivOverlay
  8116. // @method getLatLng: LatLng
  8117. // Returns the geographical point of the overlay.
  8118. getLatLng: function () {
  8119. return this._latlng;
  8120. },
  8121. // @method setLatLng(latlng: LatLng): this
  8122. // Sets the geographical point where the overlay will open.
  8123. setLatLng: function (latlng) {
  8124. this._latlng = toLatLng(latlng);
  8125. if (this._map) {
  8126. this._updatePosition();
  8127. this._adjustPan();
  8128. }
  8129. return this;
  8130. },
  8131. // @method getContent: String|HTMLElement
  8132. // Returns the content of the overlay.
  8133. getContent: function () {
  8134. return this._content;
  8135. },
  8136. // @method setContent(htmlContent: String|HTMLElement|Function): this
  8137. // Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function.
  8138. // The function should return a `String` or `HTMLElement` to be used in the overlay.
  8139. setContent: function (content) {
  8140. this._content = content;
  8141. this.update();
  8142. return this;
  8143. },
  8144. // @method getElement: String|HTMLElement
  8145. // Returns the HTML container of the overlay.
  8146. getElement: function () {
  8147. return this._container;
  8148. },
  8149. // @method update: null
  8150. // Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded.
  8151. update: function () {
  8152. if (!this._map) { return; }
  8153. this._container.style.visibility = 'hidden';
  8154. this._updateContent();
  8155. this._updateLayout();
  8156. this._updatePosition();
  8157. this._container.style.visibility = '';
  8158. this._adjustPan();
  8159. },
  8160. getEvents: function () {
  8161. var events = {
  8162. zoom: this._updatePosition,
  8163. viewreset: this._updatePosition
  8164. };
  8165. if (this._zoomAnimated) {
  8166. events.zoomanim = this._animateZoom;
  8167. }
  8168. return events;
  8169. },
  8170. // @method isOpen: Boolean
  8171. // Returns `true` when the overlay is visible on the map.
  8172. isOpen: function () {
  8173. return !!this._map && this._map.hasLayer(this);
  8174. },
  8175. // @method bringToFront: this
  8176. // Brings this overlay in front of other overlays (in the same map pane).
  8177. bringToFront: function () {
  8178. if (this._map) {
  8179. toFront(this._container);
  8180. }
  8181. return this;
  8182. },
  8183. // @method bringToBack: this
  8184. // Brings this overlay to the back of other overlays (in the same map pane).
  8185. bringToBack: function () {
  8186. if (this._map) {
  8187. toBack(this._container);
  8188. }
  8189. return this;
  8190. },
  8191. // prepare bound overlay to open: update latlng pos / content source (for FeatureGroup)
  8192. _prepareOpen: function (latlng) {
  8193. var source = this._source;
  8194. if (!source._map) { return false; }
  8195. if (source instanceof FeatureGroup) {
  8196. source = null;
  8197. var layers = this._source._layers;
  8198. for (var id in layers) {
  8199. if (layers[id]._map) {
  8200. source = layers[id];
  8201. break;
  8202. }
  8203. }
  8204. if (!source) { return false; } // Unable to get source layer.
  8205. // set overlay source to this layer
  8206. this._source = source;
  8207. }
  8208. if (!latlng) {
  8209. if (source.getCenter) {
  8210. latlng = source.getCenter();
  8211. } else if (source.getLatLng) {
  8212. latlng = source.getLatLng();
  8213. } else if (source.getBounds) {
  8214. latlng = source.getBounds().getCenter();
  8215. } else {
  8216. throw new Error('Unable to get source layer LatLng.');
  8217. }
  8218. }
  8219. this.setLatLng(latlng);
  8220. if (this._map) {
  8221. // update the overlay (content, layout, etc...)
  8222. this.update();
  8223. }
  8224. return true;
  8225. },
  8226. _updateContent: function () {
  8227. if (!this._content) { return; }
  8228. var node = this._contentNode;
  8229. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  8230. if (typeof content === 'string') {
  8231. node.innerHTML = content;
  8232. } else {
  8233. while (node.hasChildNodes()) {
  8234. node.removeChild(node.firstChild);
  8235. }
  8236. node.appendChild(content);
  8237. }
  8238. // @namespace DivOverlay
  8239. // @section DivOverlay events
  8240. // @event contentupdate: Event
  8241. // Fired when the content of the overlay is updated
  8242. this.fire('contentupdate');
  8243. },
  8244. _updatePosition: function () {
  8245. if (!this._map) { return; }
  8246. var pos = this._map.latLngToLayerPoint(this._latlng),
  8247. offset = toPoint(this.options.offset),
  8248. anchor = this._getAnchor();
  8249. if (this._zoomAnimated) {
  8250. setPosition(this._container, pos.add(anchor));
  8251. } else {
  8252. offset = offset.add(pos).add(anchor);
  8253. }
  8254. var bottom = this._containerBottom = -offset.y,
  8255. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  8256. // bottom position the overlay in case the height of the overlay changes (images loading etc)
  8257. this._container.style.bottom = bottom + 'px';
  8258. this._container.style.left = left + 'px';
  8259. },
  8260. _getAnchor: function () {
  8261. return [0, 0];
  8262. }
  8263. });
  8264. Map.include({
  8265. _initOverlay: function (OverlayClass, content, latlng, options) {
  8266. var overlay = content;
  8267. if (!(overlay instanceof OverlayClass)) {
  8268. overlay = new OverlayClass(options).setContent(content);
  8269. }
  8270. if (latlng) {
  8271. overlay.setLatLng(latlng);
  8272. }
  8273. return overlay;
  8274. }
  8275. });
  8276. Layer.include({
  8277. _initOverlay: function (OverlayClass, old, content, options) {
  8278. var overlay = content;
  8279. if (overlay instanceof OverlayClass) {
  8280. setOptions(overlay, options);
  8281. overlay._source = this;
  8282. } else {
  8283. overlay = (old && !options) ? old : new OverlayClass(options, this);
  8284. overlay.setContent(content);
  8285. }
  8286. return overlay;
  8287. }
  8288. });
  8289. /*
  8290. * @class Popup
  8291. * @inherits DivOverlay
  8292. * @aka L.Popup
  8293. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  8294. * open popups while making sure that only one popup is open at one time
  8295. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  8296. *
  8297. * @example
  8298. *
  8299. * If you want to just bind a popup to marker click and then open it, it's really easy:
  8300. *
  8301. * ```js
  8302. * marker.bindPopup(popupContent).openPopup();
  8303. * ```
  8304. * Path overlays like polylines also have a `bindPopup` method.
  8305. *
  8306. * A popup can be also standalone:
  8307. *
  8308. * ```js
  8309. * var popup = L.popup()
  8310. * .setLatLng(latlng)
  8311. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  8312. * .openOn(map);
  8313. * ```
  8314. * or
  8315. * ```js
  8316. * var popup = L.popup(latlng, {content: '<p>Hello world!<br />This is a nice popup.</p>')
  8317. * .openOn(map);
  8318. * ```
  8319. */
  8320. // @namespace Popup
  8321. var Popup = DivOverlay.extend({
  8322. // @section
  8323. // @aka Popup options
  8324. options: {
  8325. // @option pane: String = 'popupPane'
  8326. // `Map pane` where the popup will be added.
  8327. pane: 'popupPane',
  8328. // @option offset: Point = Point(0, 7)
  8329. // The offset of the popup position.
  8330. offset: [0, 7],
  8331. // @option maxWidth: Number = 300
  8332. // Max width of the popup, in pixels.
  8333. maxWidth: 300,
  8334. // @option minWidth: Number = 50
  8335. // Min width of the popup, in pixels.
  8336. minWidth: 50,
  8337. // @option maxHeight: Number = null
  8338. // If set, creates a scrollable container of the given height
  8339. // inside a popup if its content exceeds it.
  8340. // The scrollable container can be styled using the
  8341. // `leaflet-popup-scrolled` CSS class selector.
  8342. maxHeight: null,
  8343. // @option autoPan: Boolean = true
  8344. // Set it to `false` if you don't want the map to do panning animation
  8345. // to fit the opened popup.
  8346. autoPan: true,
  8347. // @option autoPanPaddingTopLeft: Point = null
  8348. // The margin between the popup and the top left corner of the map
  8349. // view after autopanning was performed.
  8350. autoPanPaddingTopLeft: null,
  8351. // @option autoPanPaddingBottomRight: Point = null
  8352. // The margin between the popup and the bottom right corner of the map
  8353. // view after autopanning was performed.
  8354. autoPanPaddingBottomRight: null,
  8355. // @option autoPanPadding: Point = Point(5, 5)
  8356. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  8357. autoPanPadding: [5, 5],
  8358. // @option keepInView: Boolean = false
  8359. // Set it to `true` if you want to prevent users from panning the popup
  8360. // off of the screen while it is open.
  8361. keepInView: false,
  8362. // @option closeButton: Boolean = true
  8363. // Controls the presence of a close button in the popup.
  8364. closeButton: true,
  8365. // @option autoClose: Boolean = true
  8366. // Set it to `false` if you want to override the default behavior of
  8367. // the popup closing when another popup is opened.
  8368. autoClose: true,
  8369. // @option closeOnEscapeKey: Boolean = true
  8370. // Set it to `false` if you want to override the default behavior of
  8371. // the ESC key for closing of the popup.
  8372. closeOnEscapeKey: true,
  8373. // @option closeOnClick: Boolean = *
  8374. // Set it if you want to override the default behavior of the popup closing when user clicks
  8375. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  8376. // @option className: String = ''
  8377. // A custom CSS class name to assign to the popup.
  8378. className: ''
  8379. },
  8380. // @namespace Popup
  8381. // @method openOn(map: Map): this
  8382. // Alternative to `map.openPopup(popup)`.
  8383. // Adds the popup to the map and closes the previous one.
  8384. openOn: function (map) {
  8385. map = arguments.length ? map : this._source._map; // experimental, not the part of public api
  8386. if (!map.hasLayer(this) && map._popup && map._popup.options.autoClose) {
  8387. map.removeLayer(map._popup);
  8388. }
  8389. map._popup = this;
  8390. return DivOverlay.prototype.openOn.call(this, map);
  8391. },
  8392. onAdd: function (map) {
  8393. DivOverlay.prototype.onAdd.call(this, map);
  8394. // @namespace Map
  8395. // @section Popup events
  8396. // @event popupopen: PopupEvent
  8397. // Fired when a popup is opened in the map
  8398. map.fire('popupopen', {popup: this});
  8399. if (this._source) {
  8400. // @namespace Layer
  8401. // @section Popup events
  8402. // @event popupopen: PopupEvent
  8403. // Fired when a popup bound to this layer is opened
  8404. this._source.fire('popupopen', {popup: this}, true);
  8405. // For non-path layers, we toggle the popup when clicking
  8406. // again the layer, so prevent the map to reopen it.
  8407. if (!(this._source instanceof Path)) {
  8408. this._source.on('preclick', stopPropagation);
  8409. }
  8410. }
  8411. },
  8412. onRemove: function (map) {
  8413. DivOverlay.prototype.onRemove.call(this, map);
  8414. // @namespace Map
  8415. // @section Popup events
  8416. // @event popupclose: PopupEvent
  8417. // Fired when a popup in the map is closed
  8418. map.fire('popupclose', {popup: this});
  8419. if (this._source) {
  8420. // @namespace Layer
  8421. // @section Popup events
  8422. // @event popupclose: PopupEvent
  8423. // Fired when a popup bound to this layer is closed
  8424. this._source.fire('popupclose', {popup: this}, true);
  8425. if (!(this._source instanceof Path)) {
  8426. this._source.off('preclick', stopPropagation);
  8427. }
  8428. }
  8429. },
  8430. getEvents: function () {
  8431. var events = DivOverlay.prototype.getEvents.call(this);
  8432. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  8433. events.preclick = this.close;
  8434. }
  8435. if (this.options.keepInView) {
  8436. events.moveend = this._adjustPan;
  8437. }
  8438. return events;
  8439. },
  8440. _initLayout: function () {
  8441. var prefix = 'leaflet-popup',
  8442. container = this._container = create$1('div',
  8443. prefix + ' ' + (this.options.className || '') +
  8444. ' leaflet-zoom-animated');
  8445. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  8446. this._contentNode = create$1('div', prefix + '-content', wrapper);
  8447. disableClickPropagation(container);
  8448. disableScrollPropagation(this._contentNode);
  8449. on(container, 'contextmenu', stopPropagation);
  8450. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  8451. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  8452. if (this.options.closeButton) {
  8453. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  8454. closeButton.setAttribute('role', 'button'); // overrides the implicit role=link of <a> elements #7399
  8455. closeButton.setAttribute('aria-label', 'Close popup');
  8456. closeButton.href = '#close';
  8457. closeButton.innerHTML = '<span aria-hidden="true">&#215;</span>';
  8458. on(closeButton, 'click', function (ev) {
  8459. preventDefault(ev);
  8460. this.close();
  8461. }, this);
  8462. }
  8463. },
  8464. _updateLayout: function () {
  8465. var container = this._contentNode,
  8466. style = container.style;
  8467. style.width = '';
  8468. style.whiteSpace = 'nowrap';
  8469. var width = container.offsetWidth;
  8470. width = Math.min(width, this.options.maxWidth);
  8471. width = Math.max(width, this.options.minWidth);
  8472. style.width = (width + 1) + 'px';
  8473. style.whiteSpace = '';
  8474. style.height = '';
  8475. var height = container.offsetHeight,
  8476. maxHeight = this.options.maxHeight,
  8477. scrolledClass = 'leaflet-popup-scrolled';
  8478. if (maxHeight && height > maxHeight) {
  8479. style.height = maxHeight + 'px';
  8480. addClass(container, scrolledClass);
  8481. } else {
  8482. removeClass(container, scrolledClass);
  8483. }
  8484. this._containerWidth = this._container.offsetWidth;
  8485. },
  8486. _animateZoom: function (e) {
  8487. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  8488. anchor = this._getAnchor();
  8489. setPosition(this._container, pos.add(anchor));
  8490. },
  8491. _adjustPan: function () {
  8492. if (!this.options.autoPan) { return; }
  8493. if (this._map._panAnim) { this._map._panAnim.stop(); }
  8494. // We can endlessly recurse if keepInView is set and the view resets.
  8495. // Let's guard against that by exiting early if we're responding to our own autopan.
  8496. if (this._autopanning) {
  8497. this._autopanning = false;
  8498. return;
  8499. }
  8500. var map = this._map,
  8501. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  8502. containerHeight = this._container.offsetHeight + marginBottom,
  8503. containerWidth = this._containerWidth,
  8504. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  8505. layerPos._add(getPosition(this._container));
  8506. var containerPos = map.layerPointToContainerPoint(layerPos),
  8507. padding = toPoint(this.options.autoPanPadding),
  8508. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  8509. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  8510. size = map.getSize(),
  8511. dx = 0,
  8512. dy = 0;
  8513. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  8514. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  8515. }
  8516. if (containerPos.x - dx - paddingTL.x < 0) { // left
  8517. dx = containerPos.x - paddingTL.x;
  8518. }
  8519. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  8520. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  8521. }
  8522. if (containerPos.y - dy - paddingTL.y < 0) { // top
  8523. dy = containerPos.y - paddingTL.y;
  8524. }
  8525. // @namespace Map
  8526. // @section Popup events
  8527. // @event autopanstart: Event
  8528. // Fired when the map starts autopanning when opening a popup.
  8529. if (dx || dy) {
  8530. // Track that we're autopanning, as this function will be re-ran on moveend
  8531. if (this.options.keepInView) {
  8532. this._autopanning = true;
  8533. }
  8534. map
  8535. .fire('autopanstart')
  8536. .panBy([dx, dy]);
  8537. }
  8538. },
  8539. _getAnchor: function () {
  8540. // Where should we anchor the popup on the source layer?
  8541. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  8542. }
  8543. });
  8544. // @namespace Popup
  8545. // @factory L.popup(options?: Popup options, source?: Layer)
  8546. // 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.
  8547. // @alternative
  8548. // @factory L.popup(latlng: LatLng, options?: Popup options)
  8549. // Instantiates a `Popup` object given `latlng` where the popup will open and an optional `options` object that describes its appearance and location.
  8550. var popup = function (options, source) {
  8551. return new Popup(options, source);
  8552. };
  8553. /* @namespace Map
  8554. * @section Interaction Options
  8555. * @option closePopupOnClick: Boolean = true
  8556. * Set it to `false` if you don't want popups to close when user clicks the map.
  8557. */
  8558. Map.mergeOptions({
  8559. closePopupOnClick: true
  8560. });
  8561. // @namespace Map
  8562. // @section Methods for Layers and Controls
  8563. Map.include({
  8564. // @method openPopup(popup: Popup): this
  8565. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  8566. // @alternative
  8567. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  8568. // Creates a popup with the specified content and options and opens it in the given point on a map.
  8569. openPopup: function (popup, latlng, options) {
  8570. this._initOverlay(Popup, popup, latlng, options)
  8571. .openOn(this);
  8572. return this;
  8573. },
  8574. // @method closePopup(popup?: Popup): this
  8575. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  8576. closePopup: function (popup) {
  8577. popup = arguments.length ? popup : this._popup;
  8578. if (popup) {
  8579. popup.close();
  8580. }
  8581. return this;
  8582. }
  8583. });
  8584. /*
  8585. * @namespace Layer
  8586. * @section Popup methods example
  8587. *
  8588. * All layers share a set of methods convenient for binding popups to it.
  8589. *
  8590. * ```js
  8591. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  8592. * layer.openPopup();
  8593. * layer.closePopup();
  8594. * ```
  8595. *
  8596. * 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.
  8597. */
  8598. // @section Popup methods
  8599. Layer.include({
  8600. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  8601. // Binds a popup to the layer with the passed `content` and sets up the
  8602. // necessary event listeners. If a `Function` is passed it will receive
  8603. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8604. bindPopup: function (content, options) {
  8605. this._popup = this._initOverlay(Popup, this._popup, content, options);
  8606. if (!this._popupHandlersAdded) {
  8607. this.on({
  8608. click: this._openPopup,
  8609. keypress: this._onKeyPress,
  8610. remove: this.closePopup,
  8611. move: this._movePopup
  8612. });
  8613. this._popupHandlersAdded = true;
  8614. }
  8615. return this;
  8616. },
  8617. // @method unbindPopup(): this
  8618. // Removes the popup previously bound with `bindPopup`.
  8619. unbindPopup: function () {
  8620. if (this._popup) {
  8621. this.off({
  8622. click: this._openPopup,
  8623. keypress: this._onKeyPress,
  8624. remove: this.closePopup,
  8625. move: this._movePopup
  8626. });
  8627. this._popupHandlersAdded = false;
  8628. this._popup = null;
  8629. }
  8630. return this;
  8631. },
  8632. // @method openPopup(latlng?: LatLng): this
  8633. // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
  8634. openPopup: function (latlng) {
  8635. if (this._popup) {
  8636. if (!(this instanceof FeatureGroup)) {
  8637. this._popup._source = this;
  8638. }
  8639. if (this._popup._prepareOpen(latlng || this._latlng)) {
  8640. // open the popup on the map
  8641. this._popup.openOn(this._map);
  8642. }
  8643. }
  8644. return this;
  8645. },
  8646. // @method closePopup(): this
  8647. // Closes the popup bound to this layer if it is open.
  8648. closePopup: function () {
  8649. if (this._popup) {
  8650. this._popup.close();
  8651. }
  8652. return this;
  8653. },
  8654. // @method togglePopup(): this
  8655. // Opens or closes the popup bound to this layer depending on its current state.
  8656. togglePopup: function () {
  8657. if (this._popup) {
  8658. this._popup.toggle(this);
  8659. }
  8660. return this;
  8661. },
  8662. // @method isPopupOpen(): boolean
  8663. // Returns `true` if the popup bound to this layer is currently open.
  8664. isPopupOpen: function () {
  8665. return (this._popup ? this._popup.isOpen() : false);
  8666. },
  8667. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8668. // Sets the content of the popup bound to this layer.
  8669. setPopupContent: function (content) {
  8670. if (this._popup) {
  8671. this._popup.setContent(content);
  8672. }
  8673. return this;
  8674. },
  8675. // @method getPopup(): Popup
  8676. // Returns the popup bound to this layer.
  8677. getPopup: function () {
  8678. return this._popup;
  8679. },
  8680. _openPopup: function (e) {
  8681. if (!this._popup || !this._map) {
  8682. return;
  8683. }
  8684. // prevent map click
  8685. stop(e);
  8686. var target = e.layer || e.target;
  8687. if (this._popup._source === target && !(target instanceof Path)) {
  8688. // treat it like a marker and figure out
  8689. // if we should toggle it open/closed
  8690. if (this._map.hasLayer(this._popup)) {
  8691. this.closePopup();
  8692. } else {
  8693. this.openPopup(e.latlng);
  8694. }
  8695. return;
  8696. }
  8697. this._popup._source = target;
  8698. this.openPopup(e.latlng);
  8699. },
  8700. _movePopup: function (e) {
  8701. this._popup.setLatLng(e.latlng);
  8702. },
  8703. _onKeyPress: function (e) {
  8704. if (e.originalEvent.keyCode === 13) {
  8705. this._openPopup(e);
  8706. }
  8707. }
  8708. });
  8709. /*
  8710. * @class Tooltip
  8711. * @inherits DivOverlay
  8712. * @aka L.Tooltip
  8713. * Used to display small texts on top of map layers.
  8714. *
  8715. * @example
  8716. * If you want to just bind a tooltip to marker:
  8717. *
  8718. * ```js
  8719. * marker.bindTooltip("my tooltip text").openTooltip();
  8720. * ```
  8721. * Path overlays like polylines also have a `bindTooltip` method.
  8722. *
  8723. * A tooltip can be also standalone:
  8724. *
  8725. * ```js
  8726. * var tooltip = L.tooltip()
  8727. * .setLatLng(latlng)
  8728. * .setContent('Hello world!<br />This is a nice tooltip.')
  8729. * .addTo(map);
  8730. * ```
  8731. * or
  8732. * ```js
  8733. * var tooltip = L.tooltip(latlng, {content: 'Hello world!<br />This is a nice tooltip.'})
  8734. * .addTo(map);
  8735. * ```
  8736. *
  8737. *
  8738. * Note about tooltip offset. Leaflet takes two options in consideration
  8739. * for computing tooltip offsetting:
  8740. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8741. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8742. * move it to the bottom. Negatives will move to the left and top.
  8743. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8744. * should adapt this value if you use a custom icon.
  8745. */
  8746. // @namespace Tooltip
  8747. var Tooltip = DivOverlay.extend({
  8748. // @section
  8749. // @aka Tooltip options
  8750. options: {
  8751. // @option pane: String = 'tooltipPane'
  8752. // `Map pane` where the tooltip will be added.
  8753. pane: 'tooltipPane',
  8754. // @option offset: Point = Point(0, 0)
  8755. // Optional offset of the tooltip position.
  8756. offset: [0, 0],
  8757. // @option direction: String = 'auto'
  8758. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8759. // `top`, `bottom`, `center`, `auto`.
  8760. // `auto` will dynamically switch between `right` and `left` according to the tooltip
  8761. // position on the map.
  8762. direction: 'auto',
  8763. // @option permanent: Boolean = false
  8764. // Whether to open the tooltip permanently or only on mouseover.
  8765. permanent: false,
  8766. // @option sticky: Boolean = false
  8767. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8768. sticky: false,
  8769. // @option opacity: Number = 0.9
  8770. // Tooltip container opacity.
  8771. opacity: 0.9
  8772. },
  8773. onAdd: function (map) {
  8774. DivOverlay.prototype.onAdd.call(this, map);
  8775. this.setOpacity(this.options.opacity);
  8776. // @namespace Map
  8777. // @section Tooltip events
  8778. // @event tooltipopen: TooltipEvent
  8779. // Fired when a tooltip is opened in the map.
  8780. map.fire('tooltipopen', {tooltip: this});
  8781. if (this._source) {
  8782. this.addEventParent(this._source);
  8783. // @namespace Layer
  8784. // @section Tooltip events
  8785. // @event tooltipopen: TooltipEvent
  8786. // Fired when a tooltip bound to this layer is opened.
  8787. this._source.fire('tooltipopen', {tooltip: this}, true);
  8788. }
  8789. },
  8790. onRemove: function (map) {
  8791. DivOverlay.prototype.onRemove.call(this, map);
  8792. // @namespace Map
  8793. // @section Tooltip events
  8794. // @event tooltipclose: TooltipEvent
  8795. // Fired when a tooltip in the map is closed.
  8796. map.fire('tooltipclose', {tooltip: this});
  8797. if (this._source) {
  8798. this.removeEventParent(this._source);
  8799. // @namespace Layer
  8800. // @section Tooltip events
  8801. // @event tooltipclose: TooltipEvent
  8802. // Fired when a tooltip bound to this layer is closed.
  8803. this._source.fire('tooltipclose', {tooltip: this}, true);
  8804. }
  8805. },
  8806. getEvents: function () {
  8807. var events = DivOverlay.prototype.getEvents.call(this);
  8808. if (!this.options.permanent) {
  8809. events.preclick = this.close;
  8810. }
  8811. return events;
  8812. },
  8813. _initLayout: function () {
  8814. var prefix = 'leaflet-tooltip',
  8815. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8816. this._contentNode = this._container = create$1('div', className);
  8817. this._container.setAttribute('role', 'tooltip');
  8818. this._container.setAttribute('id', 'leaflet-tooltip-' + stamp(this));
  8819. },
  8820. _updateLayout: function () {},
  8821. _adjustPan: function () {},
  8822. _setPosition: function (pos) {
  8823. var subX, subY,
  8824. map = this._map,
  8825. container = this._container,
  8826. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8827. tooltipPoint = map.layerPointToContainerPoint(pos),
  8828. direction = this.options.direction,
  8829. tooltipWidth = container.offsetWidth,
  8830. tooltipHeight = container.offsetHeight,
  8831. offset = toPoint(this.options.offset),
  8832. anchor = this._getAnchor();
  8833. if (direction === 'top') {
  8834. subX = tooltipWidth / 2;
  8835. subY = tooltipHeight;
  8836. } else if (direction === 'bottom') {
  8837. subX = tooltipWidth / 2;
  8838. subY = 0;
  8839. } else if (direction === 'center') {
  8840. subX = tooltipWidth / 2;
  8841. subY = tooltipHeight / 2;
  8842. } else if (direction === 'right') {
  8843. subX = 0;
  8844. subY = tooltipHeight / 2;
  8845. } else if (direction === 'left') {
  8846. subX = tooltipWidth;
  8847. subY = tooltipHeight / 2;
  8848. } else if (tooltipPoint.x < centerPoint.x) {
  8849. direction = 'right';
  8850. subX = 0;
  8851. subY = tooltipHeight / 2;
  8852. } else {
  8853. direction = 'left';
  8854. subX = tooltipWidth + (offset.x + anchor.x) * 2;
  8855. subY = tooltipHeight / 2;
  8856. }
  8857. pos = pos.subtract(toPoint(subX, subY, true)).add(offset).add(anchor);
  8858. removeClass(container, 'leaflet-tooltip-right');
  8859. removeClass(container, 'leaflet-tooltip-left');
  8860. removeClass(container, 'leaflet-tooltip-top');
  8861. removeClass(container, 'leaflet-tooltip-bottom');
  8862. addClass(container, 'leaflet-tooltip-' + direction);
  8863. setPosition(container, pos);
  8864. },
  8865. _updatePosition: function () {
  8866. var pos = this._map.latLngToLayerPoint(this._latlng);
  8867. this._setPosition(pos);
  8868. },
  8869. setOpacity: function (opacity) {
  8870. this.options.opacity = opacity;
  8871. if (this._container) {
  8872. setOpacity(this._container, opacity);
  8873. }
  8874. },
  8875. _animateZoom: function (e) {
  8876. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8877. this._setPosition(pos);
  8878. },
  8879. _getAnchor: function () {
  8880. // Where should we anchor the tooltip on the source layer?
  8881. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8882. }
  8883. });
  8884. // @namespace Tooltip
  8885. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8886. // 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.
  8887. // @alternative
  8888. // @factory L.tooltip(latlng: LatLng, options?: Tooltip options)
  8889. // Instantiates a `Tooltip` object given `latlng` where the tooltip will open and an optional `options` object that describes its appearance and location.
  8890. var tooltip = function (options, source) {
  8891. return new Tooltip(options, source);
  8892. };
  8893. // @namespace Map
  8894. // @section Methods for Layers and Controls
  8895. Map.include({
  8896. // @method openTooltip(tooltip: Tooltip): this
  8897. // Opens the specified tooltip.
  8898. // @alternative
  8899. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8900. // Creates a tooltip with the specified content and options and open it.
  8901. openTooltip: function (tooltip, latlng, options) {
  8902. this._initOverlay(Tooltip, tooltip, latlng, options)
  8903. .openOn(this);
  8904. return this;
  8905. },
  8906. // @method closeTooltip(tooltip: Tooltip): this
  8907. // Closes the tooltip given as parameter.
  8908. closeTooltip: function (tooltip) {
  8909. tooltip.close();
  8910. return this;
  8911. }
  8912. });
  8913. /*
  8914. * @namespace Layer
  8915. * @section Tooltip methods example
  8916. *
  8917. * All layers share a set of methods convenient for binding tooltips to it.
  8918. *
  8919. * ```js
  8920. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8921. * layer.openTooltip();
  8922. * layer.closeTooltip();
  8923. * ```
  8924. */
  8925. // @section Tooltip methods
  8926. Layer.include({
  8927. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8928. // Binds a tooltip to the layer with the passed `content` and sets up the
  8929. // necessary event listeners. If a `Function` is passed it will receive
  8930. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8931. bindTooltip: function (content, options) {
  8932. if (this._tooltip && this.isTooltipOpen()) {
  8933. this.unbindTooltip();
  8934. }
  8935. this._tooltip = this._initOverlay(Tooltip, this._tooltip, content, options);
  8936. this._initTooltipInteractions();
  8937. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8938. this.openTooltip();
  8939. }
  8940. return this;
  8941. },
  8942. // @method unbindTooltip(): this
  8943. // Removes the tooltip previously bound with `bindTooltip`.
  8944. unbindTooltip: function () {
  8945. if (this._tooltip) {
  8946. this._initTooltipInteractions(true);
  8947. this.closeTooltip();
  8948. this._tooltip = null;
  8949. }
  8950. return this;
  8951. },
  8952. _initTooltipInteractions: function (remove) {
  8953. if (!remove && this._tooltipHandlersAdded) { return; }
  8954. var onOff = remove ? 'off' : 'on',
  8955. events = {
  8956. remove: this.closeTooltip,
  8957. move: this._moveTooltip
  8958. };
  8959. if (!this._tooltip.options.permanent) {
  8960. events.mouseover = this._openTooltip;
  8961. events.mouseout = this.closeTooltip;
  8962. events.click = this._openTooltip;
  8963. if (this._map) {
  8964. this._addFocusListeners();
  8965. } else {
  8966. events.add = this._addFocusListeners;
  8967. }
  8968. } else {
  8969. events.add = this._openTooltip;
  8970. }
  8971. if (this._tooltip.options.sticky) {
  8972. events.mousemove = this._moveTooltip;
  8973. }
  8974. this[onOff](events);
  8975. this._tooltipHandlersAdded = !remove;
  8976. },
  8977. // @method openTooltip(latlng?: LatLng): this
  8978. // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8979. openTooltip: function (latlng) {
  8980. if (this._tooltip) {
  8981. if (!(this instanceof FeatureGroup)) {
  8982. this._tooltip._source = this;
  8983. }
  8984. if (this._tooltip._prepareOpen(latlng)) {
  8985. // open the tooltip on the map
  8986. this._tooltip.openOn(this._map);
  8987. if (this.getElement) {
  8988. this._setAriaDescribedByOnLayer(this);
  8989. } else if (this.eachLayer) {
  8990. this.eachLayer(this._setAriaDescribedByOnLayer, this);
  8991. }
  8992. }
  8993. }
  8994. return this;
  8995. },
  8996. // @method closeTooltip(): this
  8997. // Closes the tooltip bound to this layer if it is open.
  8998. closeTooltip: function () {
  8999. if (this._tooltip) {
  9000. return this._tooltip.close();
  9001. }
  9002. },
  9003. // @method toggleTooltip(): this
  9004. // Opens or closes the tooltip bound to this layer depending on its current state.
  9005. toggleTooltip: function () {
  9006. if (this._tooltip) {
  9007. this._tooltip.toggle(this);
  9008. }
  9009. return this;
  9010. },
  9011. // @method isTooltipOpen(): boolean
  9012. // Returns `true` if the tooltip bound to this layer is currently open.
  9013. isTooltipOpen: function () {
  9014. return this._tooltip.isOpen();
  9015. },
  9016. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  9017. // Sets the content of the tooltip bound to this layer.
  9018. setTooltipContent: function (content) {
  9019. if (this._tooltip) {
  9020. this._tooltip.setContent(content);
  9021. }
  9022. return this;
  9023. },
  9024. // @method getTooltip(): Tooltip
  9025. // Returns the tooltip bound to this layer.
  9026. getTooltip: function () {
  9027. return this._tooltip;
  9028. },
  9029. _addFocusListeners: function () {
  9030. if (this.getElement) {
  9031. this._addFocusListenersOnLayer(this);
  9032. } else if (this.eachLayer) {
  9033. this.eachLayer(this._addFocusListenersOnLayer, this);
  9034. }
  9035. },
  9036. _addFocusListenersOnLayer: function (layer) {
  9037. var el = typeof layer.getElement === 'function' && layer.getElement();
  9038. if (el) {
  9039. on(el, 'focus', function () {
  9040. this._tooltip._source = layer;
  9041. this.openTooltip();
  9042. }, this);
  9043. on(el, 'blur', this.closeTooltip, this);
  9044. }
  9045. },
  9046. _setAriaDescribedByOnLayer: function (layer) {
  9047. var el = typeof layer.getElement === 'function' && layer.getElement();
  9048. if (el) {
  9049. el.setAttribute('aria-describedby', this._tooltip._container.id);
  9050. }
  9051. },
  9052. _openTooltip: function (e) {
  9053. if (!this._tooltip || !this._map) {
  9054. return;
  9055. }
  9056. // If the map is moving, we will show the tooltip after it's done.
  9057. if (this._map.dragging && this._map.dragging.moving() && !this._openOnceFlag) {
  9058. this._openOnceFlag = true;
  9059. var that = this;
  9060. this._map.once('moveend', function () {
  9061. that._openOnceFlag = false;
  9062. that._openTooltip(e);
  9063. });
  9064. return;
  9065. }
  9066. this._tooltip._source = e.layer || e.target;
  9067. this.openTooltip(this._tooltip.options.sticky ? e.latlng : undefined);
  9068. },
  9069. _moveTooltip: function (e) {
  9070. var latlng = e.latlng, containerPoint, layerPoint;
  9071. if (this._tooltip.options.sticky && e.originalEvent) {
  9072. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  9073. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  9074. latlng = this._map.layerPointToLatLng(layerPoint);
  9075. }
  9076. this._tooltip.setLatLng(latlng);
  9077. }
  9078. });
  9079. /*
  9080. * @class DivIcon
  9081. * @aka L.DivIcon
  9082. * @inherits Icon
  9083. *
  9084. * Represents a lightweight icon for markers that uses a simple `<div>`
  9085. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  9086. *
  9087. * @example
  9088. * ```js
  9089. * var myIcon = L.divIcon({className: 'my-div-icon'});
  9090. * // you can set .my-div-icon styles in CSS
  9091. *
  9092. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  9093. * ```
  9094. *
  9095. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  9096. */
  9097. var DivIcon = Icon.extend({
  9098. options: {
  9099. // @section
  9100. // @aka DivIcon options
  9101. iconSize: [12, 12], // also can be set through CSS
  9102. // iconAnchor: (Point),
  9103. // popupAnchor: (Point),
  9104. // @option html: String|HTMLElement = ''
  9105. // Custom HTML code to put inside the div element, empty by default. Alternatively,
  9106. // an instance of `HTMLElement`.
  9107. html: false,
  9108. // @option bgPos: Point = [0, 0]
  9109. // Optional relative position of the background, in pixels
  9110. bgPos: null,
  9111. className: 'leaflet-div-icon'
  9112. },
  9113. createIcon: function (oldIcon) {
  9114. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  9115. options = this.options;
  9116. if (options.html instanceof Element) {
  9117. empty(div);
  9118. div.appendChild(options.html);
  9119. } else {
  9120. div.innerHTML = options.html !== false ? options.html : '';
  9121. }
  9122. if (options.bgPos) {
  9123. var bgPos = toPoint(options.bgPos);
  9124. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  9125. }
  9126. this._setIconStyles(div, 'icon');
  9127. return div;
  9128. },
  9129. createShadow: function () {
  9130. return null;
  9131. }
  9132. });
  9133. // @factory L.divIcon(options: DivIcon options)
  9134. // Creates a `DivIcon` instance with the given options.
  9135. function divIcon(options) {
  9136. return new DivIcon(options);
  9137. }
  9138. Icon.Default = IconDefault;
  9139. /*
  9140. * @class GridLayer
  9141. * @inherits Layer
  9142. * @aka L.GridLayer
  9143. *
  9144. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  9145. * 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.
  9146. *
  9147. *
  9148. * @section Synchronous usage
  9149. * @example
  9150. *
  9151. * 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.
  9152. *
  9153. * ```js
  9154. * var CanvasLayer = L.GridLayer.extend({
  9155. * createTile: function(coords){
  9156. * // create a <canvas> element for drawing
  9157. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  9158. *
  9159. * // setup tile width and height according to the options
  9160. * var size = this.getTileSize();
  9161. * tile.width = size.x;
  9162. * tile.height = size.y;
  9163. *
  9164. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  9165. * var ctx = tile.getContext('2d');
  9166. *
  9167. * // return the tile so it can be rendered on screen
  9168. * return tile;
  9169. * }
  9170. * });
  9171. * ```
  9172. *
  9173. * @section Asynchronous usage
  9174. * @example
  9175. *
  9176. * 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.
  9177. *
  9178. * ```js
  9179. * var CanvasLayer = L.GridLayer.extend({
  9180. * createTile: function(coords, done){
  9181. * var error;
  9182. *
  9183. * // create a <canvas> element for drawing
  9184. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  9185. *
  9186. * // setup tile width and height according to the options
  9187. * var size = this.getTileSize();
  9188. * tile.width = size.x;
  9189. * tile.height = size.y;
  9190. *
  9191. * // draw something asynchronously and pass the tile to the done() callback
  9192. * setTimeout(function() {
  9193. * done(error, tile);
  9194. * }, 1000);
  9195. *
  9196. * return tile;
  9197. * }
  9198. * });
  9199. * ```
  9200. *
  9201. * @section
  9202. */
  9203. var GridLayer = Layer.extend({
  9204. // @section
  9205. // @aka GridLayer options
  9206. options: {
  9207. // @option tileSize: Number|Point = 256
  9208. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  9209. tileSize: 256,
  9210. // @option opacity: Number = 1.0
  9211. // Opacity of the tiles. Can be used in the `createTile()` function.
  9212. opacity: 1,
  9213. // @option updateWhenIdle: Boolean = (depends)
  9214. // Load new tiles only when panning ends.
  9215. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  9216. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  9217. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  9218. updateWhenIdle: Browser.mobile,
  9219. // @option updateWhenZooming: Boolean = true
  9220. // 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.
  9221. updateWhenZooming: true,
  9222. // @option updateInterval: Number = 200
  9223. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  9224. updateInterval: 200,
  9225. // @option zIndex: Number = 1
  9226. // The explicit zIndex of the tile layer.
  9227. zIndex: 1,
  9228. // @option bounds: LatLngBounds = undefined
  9229. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  9230. bounds: null,
  9231. // @option minZoom: Number = 0
  9232. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9233. minZoom: 0,
  9234. // @option maxZoom: Number = undefined
  9235. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9236. maxZoom: undefined,
  9237. // @option maxNativeZoom: Number = undefined
  9238. // Maximum zoom number the tile source has available. If it is specified,
  9239. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  9240. // from `maxNativeZoom` level and auto-scaled.
  9241. maxNativeZoom: undefined,
  9242. // @option minNativeZoom: Number = undefined
  9243. // Minimum zoom number the tile source has available. If it is specified,
  9244. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  9245. // from `minNativeZoom` level and auto-scaled.
  9246. minNativeZoom: undefined,
  9247. // @option noWrap: Boolean = false
  9248. // Whether the layer is wrapped around the antimeridian. If `true`, the
  9249. // GridLayer will only be displayed once at low zoom levels. Has no
  9250. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  9251. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  9252. // tiles outside the CRS limits.
  9253. noWrap: false,
  9254. // @option pane: String = 'tilePane'
  9255. // `Map pane` where the grid layer will be added.
  9256. pane: 'tilePane',
  9257. // @option className: String = ''
  9258. // A custom class name to assign to the tile layer. Empty by default.
  9259. className: '',
  9260. // @option keepBuffer: Number = 2
  9261. // When panning the map, keep this many rows and columns of tiles before unloading them.
  9262. keepBuffer: 2
  9263. },
  9264. initialize: function (options) {
  9265. setOptions(this, options);
  9266. },
  9267. onAdd: function () {
  9268. this._initContainer();
  9269. this._levels = {};
  9270. this._tiles = {};
  9271. this._resetView(); // implicit _update() call
  9272. },
  9273. beforeAdd: function (map) {
  9274. map._addZoomLimit(this);
  9275. },
  9276. onRemove: function (map) {
  9277. this._removeAllTiles();
  9278. remove(this._container);
  9279. map._removeZoomLimit(this);
  9280. this._container = null;
  9281. this._tileZoom = undefined;
  9282. },
  9283. // @method bringToFront: this
  9284. // Brings the tile layer to the top of all tile layers.
  9285. bringToFront: function () {
  9286. if (this._map) {
  9287. toFront(this._container);
  9288. this._setAutoZIndex(Math.max);
  9289. }
  9290. return this;
  9291. },
  9292. // @method bringToBack: this
  9293. // Brings the tile layer to the bottom of all tile layers.
  9294. bringToBack: function () {
  9295. if (this._map) {
  9296. toBack(this._container);
  9297. this._setAutoZIndex(Math.min);
  9298. }
  9299. return this;
  9300. },
  9301. // @method getContainer: HTMLElement
  9302. // Returns the HTML element that contains the tiles for this layer.
  9303. getContainer: function () {
  9304. return this._container;
  9305. },
  9306. // @method setOpacity(opacity: Number): this
  9307. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  9308. setOpacity: function (opacity) {
  9309. this.options.opacity = opacity;
  9310. this._updateOpacity();
  9311. return this;
  9312. },
  9313. // @method setZIndex(zIndex: Number): this
  9314. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  9315. setZIndex: function (zIndex) {
  9316. this.options.zIndex = zIndex;
  9317. this._updateZIndex();
  9318. return this;
  9319. },
  9320. // @method isLoading: Boolean
  9321. // Returns `true` if any tile in the grid layer has not finished loading.
  9322. isLoading: function () {
  9323. return this._loading;
  9324. },
  9325. // @method redraw: this
  9326. // Causes the layer to clear all the tiles and request them again.
  9327. redraw: function () {
  9328. if (this._map) {
  9329. this._removeAllTiles();
  9330. var tileZoom = this._clampZoom(this._map.getZoom());
  9331. if (tileZoom !== this._tileZoom) {
  9332. this._tileZoom = tileZoom;
  9333. this._updateLevels();
  9334. }
  9335. this._update();
  9336. }
  9337. return this;
  9338. },
  9339. getEvents: function () {
  9340. var events = {
  9341. viewprereset: this._invalidateAll,
  9342. viewreset: this._resetView,
  9343. zoom: this._resetView,
  9344. moveend: this._onMoveEnd
  9345. };
  9346. if (!this.options.updateWhenIdle) {
  9347. // update tiles on move, but not more often than once per given interval
  9348. if (!this._onMove) {
  9349. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  9350. }
  9351. events.move = this._onMove;
  9352. }
  9353. if (this._zoomAnimated) {
  9354. events.zoomanim = this._animateZoom;
  9355. }
  9356. return events;
  9357. },
  9358. // @section Extension methods
  9359. // Layers extending `GridLayer` shall reimplement the following method.
  9360. // @method createTile(coords: Object, done?: Function): HTMLElement
  9361. // Called only internally, must be overridden by classes extending `GridLayer`.
  9362. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  9363. // is specified, it must be called when the tile has finished loading and drawing.
  9364. createTile: function () {
  9365. return document.createElement('div');
  9366. },
  9367. // @section
  9368. // @method getTileSize: Point
  9369. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  9370. getTileSize: function () {
  9371. var s = this.options.tileSize;
  9372. return s instanceof Point ? s : new Point(s, s);
  9373. },
  9374. _updateZIndex: function () {
  9375. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  9376. this._container.style.zIndex = this.options.zIndex;
  9377. }
  9378. },
  9379. _setAutoZIndex: function (compare) {
  9380. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  9381. var layers = this.getPane().children,
  9382. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  9383. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  9384. zIndex = layers[i].style.zIndex;
  9385. if (layers[i] !== this._container && zIndex) {
  9386. edgeZIndex = compare(edgeZIndex, +zIndex);
  9387. }
  9388. }
  9389. if (isFinite(edgeZIndex)) {
  9390. this.options.zIndex = edgeZIndex + compare(-1, 1);
  9391. this._updateZIndex();
  9392. }
  9393. },
  9394. _updateOpacity: function () {
  9395. if (!this._map) { return; }
  9396. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  9397. if (Browser.ielt9) { return; }
  9398. setOpacity(this._container, this.options.opacity);
  9399. var now = +new Date(),
  9400. nextFrame = false,
  9401. willPrune = false;
  9402. for (var key in this._tiles) {
  9403. var tile = this._tiles[key];
  9404. if (!tile.current || !tile.loaded) { continue; }
  9405. var fade = Math.min(1, (now - tile.loaded) / 200);
  9406. setOpacity(tile.el, fade);
  9407. if (fade < 1) {
  9408. nextFrame = true;
  9409. } else {
  9410. if (tile.active) {
  9411. willPrune = true;
  9412. } else {
  9413. this._onOpaqueTile(tile);
  9414. }
  9415. tile.active = true;
  9416. }
  9417. }
  9418. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  9419. if (nextFrame) {
  9420. cancelAnimFrame(this._fadeFrame);
  9421. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9422. }
  9423. },
  9424. _onOpaqueTile: falseFn,
  9425. _initContainer: function () {
  9426. if (this._container) { return; }
  9427. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  9428. this._updateZIndex();
  9429. if (this.options.opacity < 1) {
  9430. this._updateOpacity();
  9431. }
  9432. this.getPane().appendChild(this._container);
  9433. },
  9434. _updateLevels: function () {
  9435. var zoom = this._tileZoom,
  9436. maxZoom = this.options.maxZoom;
  9437. if (zoom === undefined) { return undefined; }
  9438. for (var z in this._levels) {
  9439. z = Number(z);
  9440. if (this._levels[z].el.children.length || z === zoom) {
  9441. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  9442. this._onUpdateLevel(z);
  9443. } else {
  9444. remove(this._levels[z].el);
  9445. this._removeTilesAtZoom(z);
  9446. this._onRemoveLevel(z);
  9447. delete this._levels[z];
  9448. }
  9449. }
  9450. var level = this._levels[zoom],
  9451. map = this._map;
  9452. if (!level) {
  9453. level = this._levels[zoom] = {};
  9454. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  9455. level.el.style.zIndex = maxZoom;
  9456. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  9457. level.zoom = zoom;
  9458. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  9459. // force the browser to consider the newly added element for transition
  9460. falseFn(level.el.offsetWidth);
  9461. this._onCreateLevel(level);
  9462. }
  9463. this._level = level;
  9464. return level;
  9465. },
  9466. _onUpdateLevel: falseFn,
  9467. _onRemoveLevel: falseFn,
  9468. _onCreateLevel: falseFn,
  9469. _pruneTiles: function () {
  9470. if (!this._map) {
  9471. return;
  9472. }
  9473. var key, tile;
  9474. var zoom = this._map.getZoom();
  9475. if (zoom > this.options.maxZoom ||
  9476. zoom < this.options.minZoom) {
  9477. this._removeAllTiles();
  9478. return;
  9479. }
  9480. for (key in this._tiles) {
  9481. tile = this._tiles[key];
  9482. tile.retain = tile.current;
  9483. }
  9484. for (key in this._tiles) {
  9485. tile = this._tiles[key];
  9486. if (tile.current && !tile.active) {
  9487. var coords = tile.coords;
  9488. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  9489. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  9490. }
  9491. }
  9492. }
  9493. for (key in this._tiles) {
  9494. if (!this._tiles[key].retain) {
  9495. this._removeTile(key);
  9496. }
  9497. }
  9498. },
  9499. _removeTilesAtZoom: function (zoom) {
  9500. for (var key in this._tiles) {
  9501. if (this._tiles[key].coords.z !== zoom) {
  9502. continue;
  9503. }
  9504. this._removeTile(key);
  9505. }
  9506. },
  9507. _removeAllTiles: function () {
  9508. for (var key in this._tiles) {
  9509. this._removeTile(key);
  9510. }
  9511. },
  9512. _invalidateAll: function () {
  9513. for (var z in this._levels) {
  9514. remove(this._levels[z].el);
  9515. this._onRemoveLevel(Number(z));
  9516. delete this._levels[z];
  9517. }
  9518. this._removeAllTiles();
  9519. this._tileZoom = undefined;
  9520. },
  9521. _retainParent: function (x, y, z, minZoom) {
  9522. var x2 = Math.floor(x / 2),
  9523. y2 = Math.floor(y / 2),
  9524. z2 = z - 1,
  9525. coords2 = new Point(+x2, +y2);
  9526. coords2.z = +z2;
  9527. var key = this._tileCoordsToKey(coords2),
  9528. tile = this._tiles[key];
  9529. if (tile && tile.active) {
  9530. tile.retain = true;
  9531. return true;
  9532. } else if (tile && tile.loaded) {
  9533. tile.retain = true;
  9534. }
  9535. if (z2 > minZoom) {
  9536. return this._retainParent(x2, y2, z2, minZoom);
  9537. }
  9538. return false;
  9539. },
  9540. _retainChildren: function (x, y, z, maxZoom) {
  9541. for (var i = 2 * x; i < 2 * x + 2; i++) {
  9542. for (var j = 2 * y; j < 2 * y + 2; j++) {
  9543. var coords = new Point(i, j);
  9544. coords.z = z + 1;
  9545. var key = this._tileCoordsToKey(coords),
  9546. tile = this._tiles[key];
  9547. if (tile && tile.active) {
  9548. tile.retain = true;
  9549. continue;
  9550. } else if (tile && tile.loaded) {
  9551. tile.retain = true;
  9552. }
  9553. if (z + 1 < maxZoom) {
  9554. this._retainChildren(i, j, z + 1, maxZoom);
  9555. }
  9556. }
  9557. }
  9558. },
  9559. _resetView: function (e) {
  9560. var animating = e && (e.pinch || e.flyTo);
  9561. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  9562. },
  9563. _animateZoom: function (e) {
  9564. this._setView(e.center, e.zoom, true, e.noUpdate);
  9565. },
  9566. _clampZoom: function (zoom) {
  9567. var options = this.options;
  9568. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  9569. return options.minNativeZoom;
  9570. }
  9571. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  9572. return options.maxNativeZoom;
  9573. }
  9574. return zoom;
  9575. },
  9576. _setView: function (center, zoom, noPrune, noUpdate) {
  9577. var tileZoom = Math.round(zoom);
  9578. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  9579. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  9580. tileZoom = undefined;
  9581. } else {
  9582. tileZoom = this._clampZoom(tileZoom);
  9583. }
  9584. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  9585. if (!noUpdate || tileZoomChanged) {
  9586. this._tileZoom = tileZoom;
  9587. if (this._abortLoading) {
  9588. this._abortLoading();
  9589. }
  9590. this._updateLevels();
  9591. this._resetGrid();
  9592. if (tileZoom !== undefined) {
  9593. this._update(center);
  9594. }
  9595. if (!noPrune) {
  9596. this._pruneTiles();
  9597. }
  9598. // Flag to prevent _updateOpacity from pruning tiles during
  9599. // a zoom anim or a pinch gesture
  9600. this._noPrune = !!noPrune;
  9601. }
  9602. this._setZoomTransforms(center, zoom);
  9603. },
  9604. _setZoomTransforms: function (center, zoom) {
  9605. for (var i in this._levels) {
  9606. this._setZoomTransform(this._levels[i], center, zoom);
  9607. }
  9608. },
  9609. _setZoomTransform: function (level, center, zoom) {
  9610. var scale = this._map.getZoomScale(zoom, level.zoom),
  9611. translate = level.origin.multiplyBy(scale)
  9612. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  9613. if (Browser.any3d) {
  9614. setTransform(level.el, translate, scale);
  9615. } else {
  9616. setPosition(level.el, translate);
  9617. }
  9618. },
  9619. _resetGrid: function () {
  9620. var map = this._map,
  9621. crs = map.options.crs,
  9622. tileSize = this._tileSize = this.getTileSize(),
  9623. tileZoom = this._tileZoom;
  9624. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  9625. if (bounds) {
  9626. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  9627. }
  9628. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  9629. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  9630. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  9631. ];
  9632. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  9633. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  9634. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  9635. ];
  9636. },
  9637. _onMoveEnd: function () {
  9638. if (!this._map || this._map._animatingZoom) { return; }
  9639. this._update();
  9640. },
  9641. _getTiledPixelBounds: function (center) {
  9642. var map = this._map,
  9643. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9644. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9645. pixelCenter = map.project(center, this._tileZoom).floor(),
  9646. halfSize = map.getSize().divideBy(scale * 2);
  9647. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9648. },
  9649. // Private method to load tiles in the grid's active zoom level according to map bounds
  9650. _update: function (center) {
  9651. var map = this._map;
  9652. if (!map) { return; }
  9653. var zoom = this._clampZoom(map.getZoom());
  9654. if (center === undefined) { center = map.getCenter(); }
  9655. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  9656. var pixelBounds = this._getTiledPixelBounds(center),
  9657. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9658. tileCenter = tileRange.getCenter(),
  9659. queue = [],
  9660. margin = this.options.keepBuffer,
  9661. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9662. tileRange.getTopRight().add([margin, -margin]));
  9663. // Sanity check: panic if the tile range contains Infinity somewhere.
  9664. if (!(isFinite(tileRange.min.x) &&
  9665. isFinite(tileRange.min.y) &&
  9666. isFinite(tileRange.max.x) &&
  9667. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  9668. for (var key in this._tiles) {
  9669. var c = this._tiles[key].coords;
  9670. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9671. this._tiles[key].current = false;
  9672. }
  9673. }
  9674. // _update just loads more tiles. If the tile zoom level differs too much
  9675. // from the map's, let _setView reset levels and prune old tiles.
  9676. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  9677. // create a queue of coordinates to load tiles from
  9678. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9679. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9680. var coords = new Point(i, j);
  9681. coords.z = this._tileZoom;
  9682. if (!this._isValidTile(coords)) { continue; }
  9683. var tile = this._tiles[this._tileCoordsToKey(coords)];
  9684. if (tile) {
  9685. tile.current = true;
  9686. } else {
  9687. queue.push(coords);
  9688. }
  9689. }
  9690. }
  9691. // sort tile queue to load tiles in order of their distance to center
  9692. queue.sort(function (a, b) {
  9693. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9694. });
  9695. if (queue.length !== 0) {
  9696. // if it's the first batch of tiles to load
  9697. if (!this._loading) {
  9698. this._loading = true;
  9699. // @event loading: Event
  9700. // Fired when the grid layer starts loading tiles.
  9701. this.fire('loading');
  9702. }
  9703. // create DOM fragment to append tiles in one batch
  9704. var fragment = document.createDocumentFragment();
  9705. for (i = 0; i < queue.length; i++) {
  9706. this._addTile(queue[i], fragment);
  9707. }
  9708. this._level.el.appendChild(fragment);
  9709. }
  9710. },
  9711. _isValidTile: function (coords) {
  9712. var crs = this._map.options.crs;
  9713. if (!crs.infinite) {
  9714. // don't load tile if it's out of bounds and not wrapped
  9715. var bounds = this._globalTileRange;
  9716. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9717. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  9718. }
  9719. if (!this.options.bounds) { return true; }
  9720. // don't load tile if it doesn't intersect the bounds in options
  9721. var tileBounds = this._tileCoordsToBounds(coords);
  9722. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9723. },
  9724. _keyToBounds: function (key) {
  9725. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9726. },
  9727. _tileCoordsToNwSe: function (coords) {
  9728. var map = this._map,
  9729. tileSize = this.getTileSize(),
  9730. nwPoint = coords.scaleBy(tileSize),
  9731. sePoint = nwPoint.add(tileSize),
  9732. nw = map.unproject(nwPoint, coords.z),
  9733. se = map.unproject(sePoint, coords.z);
  9734. return [nw, se];
  9735. },
  9736. // converts tile coordinates to its geographical bounds
  9737. _tileCoordsToBounds: function (coords) {
  9738. var bp = this._tileCoordsToNwSe(coords),
  9739. bounds = new LatLngBounds(bp[0], bp[1]);
  9740. if (!this.options.noWrap) {
  9741. bounds = this._map.wrapLatLngBounds(bounds);
  9742. }
  9743. return bounds;
  9744. },
  9745. // converts tile coordinates to key for the tile cache
  9746. _tileCoordsToKey: function (coords) {
  9747. return coords.x + ':' + coords.y + ':' + coords.z;
  9748. },
  9749. // converts tile cache key to coordinates
  9750. _keyToTileCoords: function (key) {
  9751. var k = key.split(':'),
  9752. coords = new Point(+k[0], +k[1]);
  9753. coords.z = +k[2];
  9754. return coords;
  9755. },
  9756. _removeTile: function (key) {
  9757. var tile = this._tiles[key];
  9758. if (!tile) { return; }
  9759. remove(tile.el);
  9760. delete this._tiles[key];
  9761. // @event tileunload: TileEvent
  9762. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9763. this.fire('tileunload', {
  9764. tile: tile.el,
  9765. coords: this._keyToTileCoords(key)
  9766. });
  9767. },
  9768. _initTile: function (tile) {
  9769. addClass(tile, 'leaflet-tile');
  9770. var tileSize = this.getTileSize();
  9771. tile.style.width = tileSize.x + 'px';
  9772. tile.style.height = tileSize.y + 'px';
  9773. tile.onselectstart = falseFn;
  9774. tile.onmousemove = falseFn;
  9775. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9776. if (Browser.ielt9 && this.options.opacity < 1) {
  9777. setOpacity(tile, this.options.opacity);
  9778. }
  9779. },
  9780. _addTile: function (coords, container) {
  9781. var tilePos = this._getTilePos(coords),
  9782. key = this._tileCoordsToKey(coords);
  9783. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9784. this._initTile(tile);
  9785. // if createTile is defined with a second argument ("done" callback),
  9786. // we know that tile is async and will be ready later; otherwise
  9787. if (this.createTile.length < 2) {
  9788. // mark tile as ready, but delay one frame for opacity animation to happen
  9789. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9790. }
  9791. setPosition(tile, tilePos);
  9792. // save tile in cache
  9793. this._tiles[key] = {
  9794. el: tile,
  9795. coords: coords,
  9796. current: true
  9797. };
  9798. container.appendChild(tile);
  9799. // @event tileloadstart: TileEvent
  9800. // Fired when a tile is requested and starts loading.
  9801. this.fire('tileloadstart', {
  9802. tile: tile,
  9803. coords: coords
  9804. });
  9805. },
  9806. _tileReady: function (coords, err, tile) {
  9807. if (err) {
  9808. // @event tileerror: TileErrorEvent
  9809. // Fired when there is an error loading a tile.
  9810. this.fire('tileerror', {
  9811. error: err,
  9812. tile: tile,
  9813. coords: coords
  9814. });
  9815. }
  9816. var key = this._tileCoordsToKey(coords);
  9817. tile = this._tiles[key];
  9818. if (!tile) { return; }
  9819. tile.loaded = +new Date();
  9820. if (this._map._fadeAnimated) {
  9821. setOpacity(tile.el, 0);
  9822. cancelAnimFrame(this._fadeFrame);
  9823. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9824. } else {
  9825. tile.active = true;
  9826. this._pruneTiles();
  9827. }
  9828. if (!err) {
  9829. addClass(tile.el, 'leaflet-tile-loaded');
  9830. // @event tileload: TileEvent
  9831. // Fired when a tile loads.
  9832. this.fire('tileload', {
  9833. tile: tile.el,
  9834. coords: coords
  9835. });
  9836. }
  9837. if (this._noTilesToLoad()) {
  9838. this._loading = false;
  9839. // @event load: Event
  9840. // Fired when the grid layer loaded all visible tiles.
  9841. this.fire('load');
  9842. if (Browser.ielt9 || !this._map._fadeAnimated) {
  9843. requestAnimFrame(this._pruneTiles, this);
  9844. } else {
  9845. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9846. // to trigger a pruning.
  9847. setTimeout(bind(this._pruneTiles, this), 250);
  9848. }
  9849. }
  9850. },
  9851. _getTilePos: function (coords) {
  9852. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9853. },
  9854. _wrapCoords: function (coords) {
  9855. var newCoords = new Point(
  9856. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9857. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9858. newCoords.z = coords.z;
  9859. return newCoords;
  9860. },
  9861. _pxBoundsToTileRange: function (bounds) {
  9862. var tileSize = this.getTileSize();
  9863. return new Bounds(
  9864. bounds.min.unscaleBy(tileSize).floor(),
  9865. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9866. },
  9867. _noTilesToLoad: function () {
  9868. for (var key in this._tiles) {
  9869. if (!this._tiles[key].loaded) { return false; }
  9870. }
  9871. return true;
  9872. }
  9873. });
  9874. // @factory L.gridLayer(options?: GridLayer options)
  9875. // Creates a new instance of GridLayer with the supplied options.
  9876. function gridLayer(options) {
  9877. return new GridLayer(options);
  9878. }
  9879. /*
  9880. * @class TileLayer
  9881. * @inherits GridLayer
  9882. * @aka L.TileLayer
  9883. * 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`.
  9884. *
  9885. * @example
  9886. *
  9887. * ```js
  9888. * 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);
  9889. * ```
  9890. *
  9891. * @section URL template
  9892. * @example
  9893. *
  9894. * A string of the following form:
  9895. *
  9896. * ```
  9897. * 'https://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9898. * ```
  9899. *
  9900. * `{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.
  9901. *
  9902. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9903. *
  9904. * ```
  9905. * L.tileLayer('https://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9906. * ```
  9907. */
  9908. var TileLayer = GridLayer.extend({
  9909. // @section
  9910. // @aka TileLayer options
  9911. options: {
  9912. // @option minZoom: Number = 0
  9913. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9914. minZoom: 0,
  9915. // @option maxZoom: Number = 18
  9916. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9917. maxZoom: 18,
  9918. // @option subdomains: String|String[] = 'abc'
  9919. // 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.
  9920. subdomains: 'abc',
  9921. // @option errorTileUrl: String = ''
  9922. // URL to the tile image to show in place of the tile that failed to load.
  9923. errorTileUrl: '',
  9924. // @option zoomOffset: Number = 0
  9925. // The zoom number used in tile URLs will be offset with this value.
  9926. zoomOffset: 0,
  9927. // @option tms: Boolean = false
  9928. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9929. tms: false,
  9930. // @option zoomReverse: Boolean = false
  9931. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9932. zoomReverse: false,
  9933. // @option detectRetina: Boolean = false
  9934. // 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.
  9935. detectRetina: false,
  9936. // @option crossOrigin: Boolean|String = false
  9937. // Whether the crossOrigin attribute will be added to the tiles.
  9938. // 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.
  9939. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
  9940. crossOrigin: false,
  9941. // @option referrerPolicy: Boolean|String = false
  9942. // Whether the referrerPolicy attribute will be added to the tiles.
  9943. // If a String is provided, all tiles will have their referrerPolicy attribute set to the String provided.
  9944. // This may be needed if your map's rendering context has a strict default but your tile provider expects a valid referrer
  9945. // (e.g. to validate an API token).
  9946. // Refer to [HTMLImageElement.referrerPolicy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/referrerPolicy) for valid String values.
  9947. referrerPolicy: false
  9948. },
  9949. initialize: function (url, options) {
  9950. this._url = url;
  9951. options = setOptions(this, options);
  9952. // detecting retina displays, adjusting tileSize and zoom levels
  9953. if (options.detectRetina && Browser.retina && options.maxZoom > 0) {
  9954. options.tileSize = Math.floor(options.tileSize / 2);
  9955. if (!options.zoomReverse) {
  9956. options.zoomOffset++;
  9957. options.maxZoom = Math.max(options.minZoom, options.maxZoom - 1);
  9958. } else {
  9959. options.zoomOffset--;
  9960. options.minZoom = Math.min(options.maxZoom, options.minZoom + 1);
  9961. }
  9962. options.minZoom = Math.max(0, options.minZoom);
  9963. } else if (!options.zoomReverse) {
  9964. // make sure maxZoom is gte minZoom
  9965. options.maxZoom = Math.max(options.minZoom, options.maxZoom);
  9966. } else {
  9967. // make sure minZoom is lte maxZoom
  9968. options.minZoom = Math.min(options.maxZoom, options.minZoom);
  9969. }
  9970. if (typeof options.subdomains === 'string') {
  9971. options.subdomains = options.subdomains.split('');
  9972. }
  9973. this.on('tileunload', this._onTileRemove);
  9974. },
  9975. // @method setUrl(url: String, noRedraw?: Boolean): this
  9976. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9977. // If the URL does not change, the layer will not be redrawn unless
  9978. // the noRedraw parameter is set to false.
  9979. setUrl: function (url, noRedraw) {
  9980. if (this._url === url && noRedraw === undefined) {
  9981. noRedraw = true;
  9982. }
  9983. this._url = url;
  9984. if (!noRedraw) {
  9985. this.redraw();
  9986. }
  9987. return this;
  9988. },
  9989. // @method createTile(coords: Object, done?: Function): HTMLElement
  9990. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9991. // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
  9992. // callback is called when the tile has been loaded.
  9993. createTile: function (coords, done) {
  9994. var tile = document.createElement('img');
  9995. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9996. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9997. if (this.options.crossOrigin || this.options.crossOrigin === '') {
  9998. tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
  9999. }
  10000. // for this new option we follow the documented behavior
  10001. // more closely by only setting the property when string
  10002. if (typeof this.options.referrerPolicy === 'string') {
  10003. tile.referrerPolicy = this.options.referrerPolicy;
  10004. }
  10005. // The alt attribute is set to the empty string,
  10006. // allowing screen readers to ignore the decorative image tiles.
  10007. // https://www.w3.org/WAI/tutorials/images/decorative/
  10008. // https://www.w3.org/TR/html-aria/#el-img-empty-alt
  10009. tile.alt = '';
  10010. tile.src = this.getTileUrl(coords);
  10011. return tile;
  10012. },
  10013. // @section Extension methods
  10014. // @uninheritable
  10015. // Layers extending `TileLayer` might reimplement the following method.
  10016. // @method getTileUrl(coords: Object): String
  10017. // Called only internally, returns the URL for a tile given its coordinates.
  10018. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  10019. getTileUrl: function (coords) {
  10020. var data = {
  10021. r: Browser.retina ? '@2x' : '',
  10022. s: this._getSubdomain(coords),
  10023. x: coords.x,
  10024. y: coords.y,
  10025. z: this._getZoomForUrl()
  10026. };
  10027. if (this._map && !this._map.options.crs.infinite) {
  10028. var invertedY = this._globalTileRange.max.y - coords.y;
  10029. if (this.options.tms) {
  10030. data['y'] = invertedY;
  10031. }
  10032. data['-y'] = invertedY;
  10033. }
  10034. return template(this._url, extend(data, this.options));
  10035. },
  10036. _tileOnLoad: function (done, tile) {
  10037. // For https://github.com/Leaflet/Leaflet/issues/3332
  10038. if (Browser.ielt9) {
  10039. setTimeout(bind(done, this, null, tile), 0);
  10040. } else {
  10041. done(null, tile);
  10042. }
  10043. },
  10044. _tileOnError: function (done, tile, e) {
  10045. var errorUrl = this.options.errorTileUrl;
  10046. if (errorUrl && tile.getAttribute('src') !== errorUrl) {
  10047. tile.src = errorUrl;
  10048. }
  10049. done(e, tile);
  10050. },
  10051. _onTileRemove: function (e) {
  10052. e.tile.onload = null;
  10053. },
  10054. _getZoomForUrl: function () {
  10055. var zoom = this._tileZoom,
  10056. maxZoom = this.options.maxZoom,
  10057. zoomReverse = this.options.zoomReverse,
  10058. zoomOffset = this.options.zoomOffset;
  10059. if (zoomReverse) {
  10060. zoom = maxZoom - zoom;
  10061. }
  10062. return zoom + zoomOffset;
  10063. },
  10064. _getSubdomain: function (tilePoint) {
  10065. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  10066. return this.options.subdomains[index];
  10067. },
  10068. // stops loading all tiles in the background layer
  10069. _abortLoading: function () {
  10070. var i, tile;
  10071. for (i in this._tiles) {
  10072. if (this._tiles[i].coords.z !== this._tileZoom) {
  10073. tile = this._tiles[i].el;
  10074. tile.onload = falseFn;
  10075. tile.onerror = falseFn;
  10076. if (!tile.complete) {
  10077. tile.src = emptyImageUrl;
  10078. var coords = this._tiles[i].coords;
  10079. remove(tile);
  10080. delete this._tiles[i];
  10081. // @event tileabort: TileEvent
  10082. // Fired when a tile was loading but is now not wanted.
  10083. this.fire('tileabort', {
  10084. tile: tile,
  10085. coords: coords
  10086. });
  10087. }
  10088. }
  10089. }
  10090. },
  10091. _removeTile: function (key) {
  10092. var tile = this._tiles[key];
  10093. if (!tile) { return; }
  10094. // Cancels any pending http requests associated with the tile
  10095. tile.el.setAttribute('src', emptyImageUrl);
  10096. return GridLayer.prototype._removeTile.call(this, key);
  10097. },
  10098. _tileReady: function (coords, err, tile) {
  10099. if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) {
  10100. return;
  10101. }
  10102. return GridLayer.prototype._tileReady.call(this, coords, err, tile);
  10103. }
  10104. });
  10105. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  10106. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  10107. function tileLayer(url, options) {
  10108. return new TileLayer(url, options);
  10109. }
  10110. /*
  10111. * @class TileLayer.WMS
  10112. * @inherits TileLayer
  10113. * @aka L.TileLayer.WMS
  10114. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  10115. *
  10116. * @example
  10117. *
  10118. * ```js
  10119. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  10120. * layers: 'nexrad-n0r-900913',
  10121. * format: 'image/png',
  10122. * transparent: true,
  10123. * attribution: "Weather data © 2012 IEM Nexrad"
  10124. * });
  10125. * ```
  10126. */
  10127. var TileLayerWMS = TileLayer.extend({
  10128. // @section
  10129. // @aka TileLayer.WMS options
  10130. // If any custom options not documented here are used, they will be sent to the
  10131. // WMS server as extra parameters in each request URL. This can be useful for
  10132. // [non-standard vendor WMS parameters](https://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  10133. defaultWmsParams: {
  10134. service: 'WMS',
  10135. request: 'GetMap',
  10136. // @option layers: String = ''
  10137. // **(required)** Comma-separated list of WMS layers to show.
  10138. layers: '',
  10139. // @option styles: String = ''
  10140. // Comma-separated list of WMS styles.
  10141. styles: '',
  10142. // @option format: String = 'image/jpeg'
  10143. // WMS image format (use `'image/png'` for layers with transparency).
  10144. format: 'image/jpeg',
  10145. // @option transparent: Boolean = false
  10146. // If `true`, the WMS service will return images with transparency.
  10147. transparent: false,
  10148. // @option version: String = '1.1.1'
  10149. // Version of the WMS service to use
  10150. version: '1.1.1'
  10151. },
  10152. options: {
  10153. // @option crs: CRS = null
  10154. // Coordinate Reference System to use for the WMS requests, defaults to
  10155. // map CRS. Don't change this if you're not sure what it means.
  10156. crs: null,
  10157. // @option uppercase: Boolean = false
  10158. // If `true`, WMS request parameter keys will be uppercase.
  10159. uppercase: false
  10160. },
  10161. initialize: function (url, options) {
  10162. this._url = url;
  10163. var wmsParams = extend({}, this.defaultWmsParams);
  10164. // all keys that are not TileLayer options go to WMS params
  10165. for (var i in options) {
  10166. if (!(i in this.options)) {
  10167. wmsParams[i] = options[i];
  10168. }
  10169. }
  10170. options = setOptions(this, options);
  10171. var realRetina = options.detectRetina && Browser.retina ? 2 : 1;
  10172. var tileSize = this.getTileSize();
  10173. wmsParams.width = tileSize.x * realRetina;
  10174. wmsParams.height = tileSize.y * realRetina;
  10175. this.wmsParams = wmsParams;
  10176. },
  10177. onAdd: function (map) {
  10178. this._crs = this.options.crs || map.options.crs;
  10179. this._wmsVersion = parseFloat(this.wmsParams.version);
  10180. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  10181. this.wmsParams[projectionKey] = this._crs.code;
  10182. TileLayer.prototype.onAdd.call(this, map);
  10183. },
  10184. getTileUrl: function (coords) {
  10185. var tileBounds = this._tileCoordsToNwSe(coords),
  10186. crs = this._crs,
  10187. bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
  10188. min = bounds.min,
  10189. max = bounds.max,
  10190. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  10191. [min.y, min.x, max.y, max.x] :
  10192. [min.x, min.y, max.x, max.y]).join(','),
  10193. url = TileLayer.prototype.getTileUrl.call(this, coords);
  10194. return url +
  10195. getParamString(this.wmsParams, url, this.options.uppercase) +
  10196. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  10197. },
  10198. // @method setParams(params: Object, noRedraw?: Boolean): this
  10199. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  10200. setParams: function (params, noRedraw) {
  10201. extend(this.wmsParams, params);
  10202. if (!noRedraw) {
  10203. this.redraw();
  10204. }
  10205. return this;
  10206. }
  10207. });
  10208. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  10209. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  10210. function tileLayerWMS(url, options) {
  10211. return new TileLayerWMS(url, options);
  10212. }
  10213. TileLayer.WMS = TileLayerWMS;
  10214. tileLayer.wms = tileLayerWMS;
  10215. /*
  10216. * @class Renderer
  10217. * @inherits Layer
  10218. * @aka L.Renderer
  10219. *
  10220. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  10221. * DOM container of the renderer, its bounds, and its zoom animation.
  10222. *
  10223. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  10224. * itself can be added or removed to the map. All paths use a renderer, which can
  10225. * be implicit (the map will decide the type of renderer and use it automatically)
  10226. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  10227. *
  10228. * Do not use this class directly, use `SVG` and `Canvas` instead.
  10229. *
  10230. * @event update: Event
  10231. * Fired when the renderer updates its bounds, center and zoom, for example when
  10232. * its map has moved
  10233. */
  10234. var Renderer = Layer.extend({
  10235. // @section
  10236. // @aka Renderer options
  10237. options: {
  10238. // @option padding: Number = 0.1
  10239. // How much to extend the clip area around the map view (relative to its size)
  10240. // e.g. 0.1 would be 10% of map view in each direction
  10241. padding: 0.1
  10242. },
  10243. initialize: function (options) {
  10244. setOptions(this, options);
  10245. stamp(this);
  10246. this._layers = this._layers || {};
  10247. },
  10248. onAdd: function () {
  10249. if (!this._container) {
  10250. this._initContainer(); // defined by renderer implementations
  10251. // always keep transform-origin as 0 0
  10252. addClass(this._container, 'leaflet-zoom-animated');
  10253. }
  10254. this.getPane().appendChild(this._container);
  10255. this._update();
  10256. this.on('update', this._updatePaths, this);
  10257. },
  10258. onRemove: function () {
  10259. this.off('update', this._updatePaths, this);
  10260. this._destroyContainer();
  10261. },
  10262. getEvents: function () {
  10263. var events = {
  10264. viewreset: this._reset,
  10265. zoom: this._onZoom,
  10266. moveend: this._update,
  10267. zoomend: this._onZoomEnd
  10268. };
  10269. if (this._zoomAnimated) {
  10270. events.zoomanim = this._onAnimZoom;
  10271. }
  10272. return events;
  10273. },
  10274. _onAnimZoom: function (ev) {
  10275. this._updateTransform(ev.center, ev.zoom);
  10276. },
  10277. _onZoom: function () {
  10278. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  10279. },
  10280. _updateTransform: function (center, zoom) {
  10281. var scale = this._map.getZoomScale(zoom, this._zoom),
  10282. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  10283. currentCenterPoint = this._map.project(this._center, zoom),
  10284. topLeftOffset = viewHalf.multiplyBy(-scale).add(currentCenterPoint)
  10285. .subtract(this._map._getNewPixelOrigin(center, zoom));
  10286. if (Browser.any3d) {
  10287. setTransform(this._container, topLeftOffset, scale);
  10288. } else {
  10289. setPosition(this._container, topLeftOffset);
  10290. }
  10291. },
  10292. _reset: function () {
  10293. this._update();
  10294. this._updateTransform(this._center, this._zoom);
  10295. for (var id in this._layers) {
  10296. this._layers[id]._reset();
  10297. }
  10298. },
  10299. _onZoomEnd: function () {
  10300. for (var id in this._layers) {
  10301. this._layers[id]._project();
  10302. }
  10303. },
  10304. _updatePaths: function () {
  10305. for (var id in this._layers) {
  10306. this._layers[id]._update();
  10307. }
  10308. },
  10309. _update: function () {
  10310. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  10311. // Subclasses are responsible of firing the 'update' event.
  10312. var p = this.options.padding,
  10313. size = this._map.getSize(),
  10314. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  10315. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  10316. this._center = this._map.getCenter();
  10317. this._zoom = this._map.getZoom();
  10318. }
  10319. });
  10320. /*
  10321. * @class Canvas
  10322. * @inherits Renderer
  10323. * @aka L.Canvas
  10324. *
  10325. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  10326. * Inherits `Renderer`.
  10327. *
  10328. * Due to [technical limitations](https://caniuse.com/canvas), Canvas is not
  10329. * available in all web browsers, notably IE8, and overlapping geometries might
  10330. * not display properly in some edge cases.
  10331. *
  10332. * @example
  10333. *
  10334. * Use Canvas by default for all paths in the map:
  10335. *
  10336. * ```js
  10337. * var map = L.map('map', {
  10338. * renderer: L.canvas()
  10339. * });
  10340. * ```
  10341. *
  10342. * Use a Canvas renderer with extra padding for specific vector geometries:
  10343. *
  10344. * ```js
  10345. * var map = L.map('map');
  10346. * var myRenderer = L.canvas({ padding: 0.5 });
  10347. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10348. * var circle = L.circle( center, { renderer: myRenderer } );
  10349. * ```
  10350. */
  10351. var Canvas = Renderer.extend({
  10352. // @section
  10353. // @aka Canvas options
  10354. options: {
  10355. // @option tolerance: Number = 0
  10356. // How much to extend the click tolerance around a path/object on the map.
  10357. tolerance: 0
  10358. },
  10359. getEvents: function () {
  10360. var events = Renderer.prototype.getEvents.call(this);
  10361. events.viewprereset = this._onViewPreReset;
  10362. return events;
  10363. },
  10364. _onViewPreReset: function () {
  10365. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  10366. this._postponeUpdatePaths = true;
  10367. },
  10368. onAdd: function () {
  10369. Renderer.prototype.onAdd.call(this);
  10370. // Redraw vectors since canvas is cleared upon removal,
  10371. // in case of removing the renderer itself from the map.
  10372. this._draw();
  10373. },
  10374. _initContainer: function () {
  10375. var container = this._container = document.createElement('canvas');
  10376. on(container, 'mousemove', this._onMouseMove, this);
  10377. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  10378. on(container, 'mouseout', this._handleMouseOut, this);
  10379. container['_leaflet_disable_events'] = true;
  10380. this._ctx = container.getContext('2d');
  10381. },
  10382. _destroyContainer: function () {
  10383. cancelAnimFrame(this._redrawRequest);
  10384. delete this._ctx;
  10385. remove(this._container);
  10386. off(this._container);
  10387. delete this._container;
  10388. },
  10389. _updatePaths: function () {
  10390. if (this._postponeUpdatePaths) { return; }
  10391. var layer;
  10392. this._redrawBounds = null;
  10393. for (var id in this._layers) {
  10394. layer = this._layers[id];
  10395. layer._update();
  10396. }
  10397. this._redraw();
  10398. },
  10399. _update: function () {
  10400. if (this._map._animatingZoom && this._bounds) { return; }
  10401. Renderer.prototype._update.call(this);
  10402. var b = this._bounds,
  10403. container = this._container,
  10404. size = b.getSize(),
  10405. m = Browser.retina ? 2 : 1;
  10406. setPosition(container, b.min);
  10407. // set canvas size (also clearing it); use double size on retina
  10408. container.width = m * size.x;
  10409. container.height = m * size.y;
  10410. container.style.width = size.x + 'px';
  10411. container.style.height = size.y + 'px';
  10412. if (Browser.retina) {
  10413. this._ctx.scale(2, 2);
  10414. }
  10415. // translate so we use the same path coordinates after canvas element moves
  10416. this._ctx.translate(-b.min.x, -b.min.y);
  10417. // Tell paths to redraw themselves
  10418. this.fire('update');
  10419. },
  10420. _reset: function () {
  10421. Renderer.prototype._reset.call(this);
  10422. if (this._postponeUpdatePaths) {
  10423. this._postponeUpdatePaths = false;
  10424. this._updatePaths();
  10425. }
  10426. },
  10427. _initPath: function (layer) {
  10428. this._updateDashArray(layer);
  10429. this._layers[stamp(layer)] = layer;
  10430. var order = layer._order = {
  10431. layer: layer,
  10432. prev: this._drawLast,
  10433. next: null
  10434. };
  10435. if (this._drawLast) { this._drawLast.next = order; }
  10436. this._drawLast = order;
  10437. this._drawFirst = this._drawFirst || this._drawLast;
  10438. },
  10439. _addPath: function (layer) {
  10440. this._requestRedraw(layer);
  10441. },
  10442. _removePath: function (layer) {
  10443. var order = layer._order;
  10444. var next = order.next;
  10445. var prev = order.prev;
  10446. if (next) {
  10447. next.prev = prev;
  10448. } else {
  10449. this._drawLast = prev;
  10450. }
  10451. if (prev) {
  10452. prev.next = next;
  10453. } else {
  10454. this._drawFirst = next;
  10455. }
  10456. delete layer._order;
  10457. delete this._layers[stamp(layer)];
  10458. this._requestRedraw(layer);
  10459. },
  10460. _updatePath: function (layer) {
  10461. // Redraw the union of the layer's old pixel
  10462. // bounds and the new pixel bounds.
  10463. this._extendRedrawBounds(layer);
  10464. layer._project();
  10465. layer._update();
  10466. // The redraw will extend the redraw bounds
  10467. // with the new pixel bounds.
  10468. this._requestRedraw(layer);
  10469. },
  10470. _updateStyle: function (layer) {
  10471. this._updateDashArray(layer);
  10472. this._requestRedraw(layer);
  10473. },
  10474. _updateDashArray: function (layer) {
  10475. if (typeof layer.options.dashArray === 'string') {
  10476. var parts = layer.options.dashArray.split(/[, ]+/),
  10477. dashArray = [],
  10478. dashValue,
  10479. i;
  10480. for (i = 0; i < parts.length; i++) {
  10481. dashValue = Number(parts[i]);
  10482. // Ignore dash array containing invalid lengths
  10483. if (isNaN(dashValue)) { return; }
  10484. dashArray.push(dashValue);
  10485. }
  10486. layer.options._dashArray = dashArray;
  10487. } else {
  10488. layer.options._dashArray = layer.options.dashArray;
  10489. }
  10490. },
  10491. _requestRedraw: function (layer) {
  10492. if (!this._map) { return; }
  10493. this._extendRedrawBounds(layer);
  10494. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  10495. },
  10496. _extendRedrawBounds: function (layer) {
  10497. if (layer._pxBounds) {
  10498. var padding = (layer.options.weight || 0) + 1;
  10499. this._redrawBounds = this._redrawBounds || new Bounds();
  10500. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  10501. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  10502. }
  10503. },
  10504. _redraw: function () {
  10505. this._redrawRequest = null;
  10506. if (this._redrawBounds) {
  10507. this._redrawBounds.min._floor();
  10508. this._redrawBounds.max._ceil();
  10509. }
  10510. this._clear(); // clear layers in redraw bounds
  10511. this._draw(); // draw layers
  10512. this._redrawBounds = null;
  10513. },
  10514. _clear: function () {
  10515. var bounds = this._redrawBounds;
  10516. if (bounds) {
  10517. var size = bounds.getSize();
  10518. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  10519. } else {
  10520. this._ctx.save();
  10521. this._ctx.setTransform(1, 0, 0, 1, 0, 0);
  10522. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  10523. this._ctx.restore();
  10524. }
  10525. },
  10526. _draw: function () {
  10527. var layer, bounds = this._redrawBounds;
  10528. this._ctx.save();
  10529. if (bounds) {
  10530. var size = bounds.getSize();
  10531. this._ctx.beginPath();
  10532. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  10533. this._ctx.clip();
  10534. }
  10535. this._drawing = true;
  10536. for (var order = this._drawFirst; order; order = order.next) {
  10537. layer = order.layer;
  10538. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  10539. layer._updatePath();
  10540. }
  10541. }
  10542. this._drawing = false;
  10543. this._ctx.restore(); // Restore state before clipping.
  10544. },
  10545. _updatePoly: function (layer, closed) {
  10546. if (!this._drawing) { return; }
  10547. var i, j, len2, p,
  10548. parts = layer._parts,
  10549. len = parts.length,
  10550. ctx = this._ctx;
  10551. if (!len) { return; }
  10552. ctx.beginPath();
  10553. for (i = 0; i < len; i++) {
  10554. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  10555. p = parts[i][j];
  10556. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  10557. }
  10558. if (closed) {
  10559. ctx.closePath();
  10560. }
  10561. }
  10562. this._fillStroke(ctx, layer);
  10563. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  10564. },
  10565. _updateCircle: function (layer) {
  10566. if (!this._drawing || layer._empty()) { return; }
  10567. var p = layer._point,
  10568. ctx = this._ctx,
  10569. r = Math.max(Math.round(layer._radius), 1),
  10570. s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
  10571. if (s !== 1) {
  10572. ctx.save();
  10573. ctx.scale(1, s);
  10574. }
  10575. ctx.beginPath();
  10576. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  10577. if (s !== 1) {
  10578. ctx.restore();
  10579. }
  10580. this._fillStroke(ctx, layer);
  10581. },
  10582. _fillStroke: function (ctx, layer) {
  10583. var options = layer.options;
  10584. if (options.fill) {
  10585. ctx.globalAlpha = options.fillOpacity;
  10586. ctx.fillStyle = options.fillColor || options.color;
  10587. ctx.fill(options.fillRule || 'evenodd');
  10588. }
  10589. if (options.stroke && options.weight !== 0) {
  10590. if (ctx.setLineDash) {
  10591. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  10592. }
  10593. ctx.globalAlpha = options.opacity;
  10594. ctx.lineWidth = options.weight;
  10595. ctx.strokeStyle = options.color;
  10596. ctx.lineCap = options.lineCap;
  10597. ctx.lineJoin = options.lineJoin;
  10598. ctx.stroke();
  10599. }
  10600. },
  10601. // Canvas obviously doesn't have mouse events for individual drawn objects,
  10602. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  10603. _onClick: function (e) {
  10604. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  10605. for (var order = this._drawFirst; order; order = order.next) {
  10606. layer = order.layer;
  10607. if (layer.options.interactive && layer._containsPoint(point)) {
  10608. if (!(e.type === 'click' || e.type === 'preclick') || !this._map._draggableMoved(layer)) {
  10609. clickedLayer = layer;
  10610. }
  10611. }
  10612. }
  10613. this._fireEvent(clickedLayer ? [clickedLayer] : false, e);
  10614. },
  10615. _onMouseMove: function (e) {
  10616. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  10617. var point = this._map.mouseEventToLayerPoint(e);
  10618. this._handleMouseHover(e, point);
  10619. },
  10620. _handleMouseOut: function (e) {
  10621. var layer = this._hoveredLayer;
  10622. if (layer) {
  10623. // if we're leaving the layer, fire mouseout
  10624. removeClass(this._container, 'leaflet-interactive');
  10625. this._fireEvent([layer], e, 'mouseout');
  10626. this._hoveredLayer = null;
  10627. this._mouseHoverThrottled = false;
  10628. }
  10629. },
  10630. _handleMouseHover: function (e, point) {
  10631. if (this._mouseHoverThrottled) {
  10632. return;
  10633. }
  10634. var layer, candidateHoveredLayer;
  10635. for (var order = this._drawFirst; order; order = order.next) {
  10636. layer = order.layer;
  10637. if (layer.options.interactive && layer._containsPoint(point)) {
  10638. candidateHoveredLayer = layer;
  10639. }
  10640. }
  10641. if (candidateHoveredLayer !== this._hoveredLayer) {
  10642. this._handleMouseOut(e);
  10643. if (candidateHoveredLayer) {
  10644. addClass(this._container, 'leaflet-interactive'); // change cursor
  10645. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  10646. this._hoveredLayer = candidateHoveredLayer;
  10647. }
  10648. }
  10649. this._fireEvent(this._hoveredLayer ? [this._hoveredLayer] : false, e);
  10650. this._mouseHoverThrottled = true;
  10651. setTimeout(bind(function () {
  10652. this._mouseHoverThrottled = false;
  10653. }, this), 32);
  10654. },
  10655. _fireEvent: function (layers, e, type) {
  10656. this._map._fireDOMEvent(e, type || e.type, layers);
  10657. },
  10658. _bringToFront: function (layer) {
  10659. var order = layer._order;
  10660. if (!order) { return; }
  10661. var next = order.next;
  10662. var prev = order.prev;
  10663. if (next) {
  10664. next.prev = prev;
  10665. } else {
  10666. // Already last
  10667. return;
  10668. }
  10669. if (prev) {
  10670. prev.next = next;
  10671. } else if (next) {
  10672. // Update first entry unless this is the
  10673. // single entry
  10674. this._drawFirst = next;
  10675. }
  10676. order.prev = this._drawLast;
  10677. this._drawLast.next = order;
  10678. order.next = null;
  10679. this._drawLast = order;
  10680. this._requestRedraw(layer);
  10681. },
  10682. _bringToBack: function (layer) {
  10683. var order = layer._order;
  10684. if (!order) { return; }
  10685. var next = order.next;
  10686. var prev = order.prev;
  10687. if (prev) {
  10688. prev.next = next;
  10689. } else {
  10690. // Already first
  10691. return;
  10692. }
  10693. if (next) {
  10694. next.prev = prev;
  10695. } else if (prev) {
  10696. // Update last entry unless this is the
  10697. // single entry
  10698. this._drawLast = prev;
  10699. }
  10700. order.prev = null;
  10701. order.next = this._drawFirst;
  10702. this._drawFirst.prev = order;
  10703. this._drawFirst = order;
  10704. this._requestRedraw(layer);
  10705. }
  10706. });
  10707. // @factory L.canvas(options?: Renderer options)
  10708. // Creates a Canvas renderer with the given options.
  10709. function canvas(options) {
  10710. return Browser.canvas ? new Canvas(options) : null;
  10711. }
  10712. /*
  10713. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10714. */
  10715. var vmlCreate = (function () {
  10716. try {
  10717. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10718. return function (name) {
  10719. return document.createElement('<lvml:' + name + ' class="lvml">');
  10720. };
  10721. } catch (e) {
  10722. // Do not return fn from catch block so `e` can be garbage collected
  10723. // See https://github.com/Leaflet/Leaflet/pull/7279
  10724. }
  10725. return function (name) {
  10726. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10727. };
  10728. })();
  10729. /*
  10730. * @class SVG
  10731. *
  10732. *
  10733. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10734. * with old versions of Internet Explorer.
  10735. */
  10736. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10737. var vmlMixin = {
  10738. _initContainer: function () {
  10739. this._container = create$1('div', 'leaflet-vml-container');
  10740. },
  10741. _update: function () {
  10742. if (this._map._animatingZoom) { return; }
  10743. Renderer.prototype._update.call(this);
  10744. this.fire('update');
  10745. },
  10746. _initPath: function (layer) {
  10747. var container = layer._container = vmlCreate('shape');
  10748. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10749. container.coordsize = '1 1';
  10750. layer._path = vmlCreate('path');
  10751. container.appendChild(layer._path);
  10752. this._updateStyle(layer);
  10753. this._layers[stamp(layer)] = layer;
  10754. },
  10755. _addPath: function (layer) {
  10756. var container = layer._container;
  10757. this._container.appendChild(container);
  10758. if (layer.options.interactive) {
  10759. layer.addInteractiveTarget(container);
  10760. }
  10761. },
  10762. _removePath: function (layer) {
  10763. var container = layer._container;
  10764. remove(container);
  10765. layer.removeInteractiveTarget(container);
  10766. delete this._layers[stamp(layer)];
  10767. },
  10768. _updateStyle: function (layer) {
  10769. var stroke = layer._stroke,
  10770. fill = layer._fill,
  10771. options = layer.options,
  10772. container = layer._container;
  10773. container.stroked = !!options.stroke;
  10774. container.filled = !!options.fill;
  10775. if (options.stroke) {
  10776. if (!stroke) {
  10777. stroke = layer._stroke = vmlCreate('stroke');
  10778. }
  10779. container.appendChild(stroke);
  10780. stroke.weight = options.weight + 'px';
  10781. stroke.color = options.color;
  10782. stroke.opacity = options.opacity;
  10783. if (options.dashArray) {
  10784. stroke.dashStyle = isArray(options.dashArray) ?
  10785. options.dashArray.join(' ') :
  10786. options.dashArray.replace(/( *, *)/g, ' ');
  10787. } else {
  10788. stroke.dashStyle = '';
  10789. }
  10790. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10791. stroke.joinstyle = options.lineJoin;
  10792. } else if (stroke) {
  10793. container.removeChild(stroke);
  10794. layer._stroke = null;
  10795. }
  10796. if (options.fill) {
  10797. if (!fill) {
  10798. fill = layer._fill = vmlCreate('fill');
  10799. }
  10800. container.appendChild(fill);
  10801. fill.color = options.fillColor || options.color;
  10802. fill.opacity = options.fillOpacity;
  10803. } else if (fill) {
  10804. container.removeChild(fill);
  10805. layer._fill = null;
  10806. }
  10807. },
  10808. _updateCircle: function (layer) {
  10809. var p = layer._point.round(),
  10810. r = Math.round(layer._radius),
  10811. r2 = Math.round(layer._radiusY || r);
  10812. this._setPath(layer, layer._empty() ? 'M0 0' :
  10813. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10814. },
  10815. _setPath: function (layer, path) {
  10816. layer._path.v = path;
  10817. },
  10818. _bringToFront: function (layer) {
  10819. toFront(layer._container);
  10820. },
  10821. _bringToBack: function (layer) {
  10822. toBack(layer._container);
  10823. }
  10824. };
  10825. var create = Browser.vml ? vmlCreate : svgCreate;
  10826. /*
  10827. * @class SVG
  10828. * @inherits Renderer
  10829. * @aka L.SVG
  10830. *
  10831. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10832. * Inherits `Renderer`.
  10833. *
  10834. * Due to [technical limitations](https://caniuse.com/svg), SVG is not
  10835. * available in all web browsers, notably Android 2.x and 3.x.
  10836. *
  10837. * Although SVG is not available on IE7 and IE8, these browsers support
  10838. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10839. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10840. * this case.
  10841. *
  10842. * @example
  10843. *
  10844. * Use SVG by default for all paths in the map:
  10845. *
  10846. * ```js
  10847. * var map = L.map('map', {
  10848. * renderer: L.svg()
  10849. * });
  10850. * ```
  10851. *
  10852. * Use a SVG renderer with extra padding for specific vector geometries:
  10853. *
  10854. * ```js
  10855. * var map = L.map('map');
  10856. * var myRenderer = L.svg({ padding: 0.5 });
  10857. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10858. * var circle = L.circle( center, { renderer: myRenderer } );
  10859. * ```
  10860. */
  10861. var SVG = Renderer.extend({
  10862. _initContainer: function () {
  10863. this._container = create('svg');
  10864. // makes it possible to click through svg root; we'll reset it back in individual paths
  10865. this._container.setAttribute('pointer-events', 'none');
  10866. this._rootGroup = create('g');
  10867. this._container.appendChild(this._rootGroup);
  10868. },
  10869. _destroyContainer: function () {
  10870. remove(this._container);
  10871. off(this._container);
  10872. delete this._container;
  10873. delete this._rootGroup;
  10874. delete this._svgSize;
  10875. },
  10876. _update: function () {
  10877. if (this._map._animatingZoom && this._bounds) { return; }
  10878. Renderer.prototype._update.call(this);
  10879. var b = this._bounds,
  10880. size = b.getSize(),
  10881. container = this._container;
  10882. // set size of svg-container if changed
  10883. if (!this._svgSize || !this._svgSize.equals(size)) {
  10884. this._svgSize = size;
  10885. container.setAttribute('width', size.x);
  10886. container.setAttribute('height', size.y);
  10887. }
  10888. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10889. setPosition(container, b.min);
  10890. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10891. this.fire('update');
  10892. },
  10893. // methods below are called by vector layers implementations
  10894. _initPath: function (layer) {
  10895. var path = layer._path = create('path');
  10896. // @namespace Path
  10897. // @option className: String = null
  10898. // Custom class name set on an element. Only for SVG renderer.
  10899. if (layer.options.className) {
  10900. addClass(path, layer.options.className);
  10901. }
  10902. if (layer.options.interactive) {
  10903. addClass(path, 'leaflet-interactive');
  10904. }
  10905. this._updateStyle(layer);
  10906. this._layers[stamp(layer)] = layer;
  10907. },
  10908. _addPath: function (layer) {
  10909. if (!this._rootGroup) { this._initContainer(); }
  10910. this._rootGroup.appendChild(layer._path);
  10911. layer.addInteractiveTarget(layer._path);
  10912. },
  10913. _removePath: function (layer) {
  10914. remove(layer._path);
  10915. layer.removeInteractiveTarget(layer._path);
  10916. delete this._layers[stamp(layer)];
  10917. },
  10918. _updatePath: function (layer) {
  10919. layer._project();
  10920. layer._update();
  10921. },
  10922. _updateStyle: function (layer) {
  10923. var path = layer._path,
  10924. options = layer.options;
  10925. if (!path) { return; }
  10926. if (options.stroke) {
  10927. path.setAttribute('stroke', options.color);
  10928. path.setAttribute('stroke-opacity', options.opacity);
  10929. path.setAttribute('stroke-width', options.weight);
  10930. path.setAttribute('stroke-linecap', options.lineCap);
  10931. path.setAttribute('stroke-linejoin', options.lineJoin);
  10932. if (options.dashArray) {
  10933. path.setAttribute('stroke-dasharray', options.dashArray);
  10934. } else {
  10935. path.removeAttribute('stroke-dasharray');
  10936. }
  10937. if (options.dashOffset) {
  10938. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10939. } else {
  10940. path.removeAttribute('stroke-dashoffset');
  10941. }
  10942. } else {
  10943. path.setAttribute('stroke', 'none');
  10944. }
  10945. if (options.fill) {
  10946. path.setAttribute('fill', options.fillColor || options.color);
  10947. path.setAttribute('fill-opacity', options.fillOpacity);
  10948. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10949. } else {
  10950. path.setAttribute('fill', 'none');
  10951. }
  10952. },
  10953. _updatePoly: function (layer, closed) {
  10954. this._setPath(layer, pointsToPath(layer._parts, closed));
  10955. },
  10956. _updateCircle: function (layer) {
  10957. var p = layer._point,
  10958. r = Math.max(Math.round(layer._radius), 1),
  10959. r2 = Math.max(Math.round(layer._radiusY), 1) || r,
  10960. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10961. // drawing a circle with two half-arcs
  10962. var d = layer._empty() ? 'M0 0' :
  10963. 'M' + (p.x - r) + ',' + p.y +
  10964. arc + (r * 2) + ',0 ' +
  10965. arc + (-r * 2) + ',0 ';
  10966. this._setPath(layer, d);
  10967. },
  10968. _setPath: function (layer, path) {
  10969. layer._path.setAttribute('d', path);
  10970. },
  10971. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10972. _bringToFront: function (layer) {
  10973. toFront(layer._path);
  10974. },
  10975. _bringToBack: function (layer) {
  10976. toBack(layer._path);
  10977. }
  10978. });
  10979. if (Browser.vml) {
  10980. SVG.include(vmlMixin);
  10981. }
  10982. // @namespace SVG
  10983. // @factory L.svg(options?: Renderer options)
  10984. // Creates a SVG renderer with the given options.
  10985. function svg(options) {
  10986. return Browser.svg || Browser.vml ? new SVG(options) : null;
  10987. }
  10988. Map.include({
  10989. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10990. // Returns the instance of `Renderer` that should be used to render the given
  10991. // `Path`. It will ensure that the `renderer` options of the map and paths
  10992. // are respected, and that the renderers do exist on the map.
  10993. getRenderer: function (layer) {
  10994. // @namespace Path; @option renderer: Renderer
  10995. // Use this specific instance of `Renderer` for this path. Takes
  10996. // precedence over the map's [default renderer](#map-renderer).
  10997. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10998. if (!renderer) {
  10999. renderer = this._renderer = this._createRenderer();
  11000. }
  11001. if (!this.hasLayer(renderer)) {
  11002. this.addLayer(renderer);
  11003. }
  11004. return renderer;
  11005. },
  11006. _getPaneRenderer: function (name) {
  11007. if (name === 'overlayPane' || name === undefined) {
  11008. return false;
  11009. }
  11010. var renderer = this._paneRenderers[name];
  11011. if (renderer === undefined) {
  11012. renderer = this._createRenderer({pane: name});
  11013. this._paneRenderers[name] = renderer;
  11014. }
  11015. return renderer;
  11016. },
  11017. _createRenderer: function (options) {
  11018. // @namespace Map; @option preferCanvas: Boolean = false
  11019. // Whether `Path`s should be rendered on a `Canvas` renderer.
  11020. // By default, all `Path`s are rendered in a `SVG` renderer.
  11021. return (this.options.preferCanvas && canvas(options)) || svg(options);
  11022. }
  11023. });
  11024. /*
  11025. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  11026. */
  11027. /*
  11028. * @class Rectangle
  11029. * @aka L.Rectangle
  11030. * @inherits Polygon
  11031. *
  11032. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  11033. *
  11034. * @example
  11035. *
  11036. * ```js
  11037. * // define rectangle geographical bounds
  11038. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  11039. *
  11040. * // create an orange rectangle
  11041. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  11042. *
  11043. * // zoom the map to the rectangle bounds
  11044. * map.fitBounds(bounds);
  11045. * ```
  11046. *
  11047. */
  11048. var Rectangle = Polygon.extend({
  11049. initialize: function (latLngBounds, options) {
  11050. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  11051. },
  11052. // @method setBounds(latLngBounds: LatLngBounds): this
  11053. // Redraws the rectangle with the passed bounds.
  11054. setBounds: function (latLngBounds) {
  11055. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  11056. },
  11057. _boundsToLatLngs: function (latLngBounds) {
  11058. latLngBounds = toLatLngBounds(latLngBounds);
  11059. return [
  11060. latLngBounds.getSouthWest(),
  11061. latLngBounds.getNorthWest(),
  11062. latLngBounds.getNorthEast(),
  11063. latLngBounds.getSouthEast()
  11064. ];
  11065. }
  11066. });
  11067. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  11068. function rectangle(latLngBounds, options) {
  11069. return new Rectangle(latLngBounds, options);
  11070. }
  11071. SVG.create = create;
  11072. SVG.pointsToPath = pointsToPath;
  11073. GeoJSON.geometryToLayer = geometryToLayer;
  11074. GeoJSON.coordsToLatLng = coordsToLatLng;
  11075. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  11076. GeoJSON.latLngToCoords = latLngToCoords;
  11077. GeoJSON.latLngsToCoords = latLngsToCoords;
  11078. GeoJSON.getFeature = getFeature;
  11079. GeoJSON.asFeature = asFeature;
  11080. /*
  11081. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  11082. * (zoom to a selected bounding box), enabled by default.
  11083. */
  11084. // @namespace Map
  11085. // @section Interaction Options
  11086. Map.mergeOptions({
  11087. // @option boxZoom: Boolean = true
  11088. // Whether the map can be zoomed to a rectangular area specified by
  11089. // dragging the mouse while pressing the shift key.
  11090. boxZoom: true
  11091. });
  11092. var BoxZoom = Handler.extend({
  11093. initialize: function (map) {
  11094. this._map = map;
  11095. this._container = map._container;
  11096. this._pane = map._panes.overlayPane;
  11097. this._resetStateTimeout = 0;
  11098. map.on('unload', this._destroy, this);
  11099. },
  11100. addHooks: function () {
  11101. on(this._container, 'mousedown', this._onMouseDown, this);
  11102. },
  11103. removeHooks: function () {
  11104. off(this._container, 'mousedown', this._onMouseDown, this);
  11105. },
  11106. moved: function () {
  11107. return this._moved;
  11108. },
  11109. _destroy: function () {
  11110. remove(this._pane);
  11111. delete this._pane;
  11112. },
  11113. _resetState: function () {
  11114. this._resetStateTimeout = 0;
  11115. this._moved = false;
  11116. },
  11117. _clearDeferredResetState: function () {
  11118. if (this._resetStateTimeout !== 0) {
  11119. clearTimeout(this._resetStateTimeout);
  11120. this._resetStateTimeout = 0;
  11121. }
  11122. },
  11123. _onMouseDown: function (e) {
  11124. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  11125. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  11126. // will interrupt the interaction and orphan a box element in the container.
  11127. this._clearDeferredResetState();
  11128. this._resetState();
  11129. disableTextSelection();
  11130. disableImageDrag();
  11131. this._startPoint = this._map.mouseEventToContainerPoint(e);
  11132. on(document, {
  11133. contextmenu: stop,
  11134. mousemove: this._onMouseMove,
  11135. mouseup: this._onMouseUp,
  11136. keydown: this._onKeyDown
  11137. }, this);
  11138. },
  11139. _onMouseMove: function (e) {
  11140. if (!this._moved) {
  11141. this._moved = true;
  11142. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  11143. addClass(this._container, 'leaflet-crosshair');
  11144. this._map.fire('boxzoomstart');
  11145. }
  11146. this._point = this._map.mouseEventToContainerPoint(e);
  11147. var bounds = new Bounds(this._point, this._startPoint),
  11148. size = bounds.getSize();
  11149. setPosition(this._box, bounds.min);
  11150. this._box.style.width = size.x + 'px';
  11151. this._box.style.height = size.y + 'px';
  11152. },
  11153. _finish: function () {
  11154. if (this._moved) {
  11155. remove(this._box);
  11156. removeClass(this._container, 'leaflet-crosshair');
  11157. }
  11158. enableTextSelection();
  11159. enableImageDrag();
  11160. off(document, {
  11161. contextmenu: stop,
  11162. mousemove: this._onMouseMove,
  11163. mouseup: this._onMouseUp,
  11164. keydown: this._onKeyDown
  11165. }, this);
  11166. },
  11167. _onMouseUp: function (e) {
  11168. if ((e.which !== 1) && (e.button !== 1)) { return; }
  11169. this._finish();
  11170. if (!this._moved) { return; }
  11171. // Postpone to next JS tick so internal click event handling
  11172. // still see it as "moved".
  11173. this._clearDeferredResetState();
  11174. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  11175. var bounds = new LatLngBounds(
  11176. this._map.containerPointToLatLng(this._startPoint),
  11177. this._map.containerPointToLatLng(this._point));
  11178. this._map
  11179. .fitBounds(bounds)
  11180. .fire('boxzoomend', {boxZoomBounds: bounds});
  11181. },
  11182. _onKeyDown: function (e) {
  11183. if (e.keyCode === 27) {
  11184. this._finish();
  11185. this._clearDeferredResetState();
  11186. this._resetState();
  11187. }
  11188. }
  11189. });
  11190. // @section Handlers
  11191. // @property boxZoom: Handler
  11192. // Box (shift-drag with mouse) zoom handler.
  11193. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  11194. /*
  11195. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  11196. */
  11197. // @namespace Map
  11198. // @section Interaction Options
  11199. Map.mergeOptions({
  11200. // @option doubleClickZoom: Boolean|String = true
  11201. // Whether the map can be zoomed in by double clicking on it and
  11202. // zoomed out by double clicking while holding shift. If passed
  11203. // `'center'`, double-click zoom will zoom to the center of the
  11204. // view regardless of where the mouse was.
  11205. doubleClickZoom: true
  11206. });
  11207. var DoubleClickZoom = Handler.extend({
  11208. addHooks: function () {
  11209. this._map.on('dblclick', this._onDoubleClick, this);
  11210. },
  11211. removeHooks: function () {
  11212. this._map.off('dblclick', this._onDoubleClick, this);
  11213. },
  11214. _onDoubleClick: function (e) {
  11215. var map = this._map,
  11216. oldZoom = map.getZoom(),
  11217. delta = map.options.zoomDelta,
  11218. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  11219. if (map.options.doubleClickZoom === 'center') {
  11220. map.setZoom(zoom);
  11221. } else {
  11222. map.setZoomAround(e.containerPoint, zoom);
  11223. }
  11224. }
  11225. });
  11226. // @section Handlers
  11227. //
  11228. // Map properties include interaction handlers that allow you to control
  11229. // interaction behavior in runtime, enabling or disabling certain features such
  11230. // as dragging or touch zoom (see `Handler` methods). For example:
  11231. //
  11232. // ```js
  11233. // map.doubleClickZoom.disable();
  11234. // ```
  11235. //
  11236. // @property doubleClickZoom: Handler
  11237. // Double click zoom handler.
  11238. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  11239. /*
  11240. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  11241. */
  11242. // @namespace Map
  11243. // @section Interaction Options
  11244. Map.mergeOptions({
  11245. // @option dragging: Boolean = true
  11246. // Whether the map is draggable with mouse/touch or not.
  11247. dragging: true,
  11248. // @section Panning Inertia Options
  11249. // @option inertia: Boolean = *
  11250. // If enabled, panning of the map will have an inertia effect where
  11251. // the map builds momentum while dragging and continues moving in
  11252. // the same direction for some time. Feels especially nice on touch
  11253. // devices. Enabled by default.
  11254. inertia: true,
  11255. // @option inertiaDeceleration: Number = 3000
  11256. // The rate with which the inertial movement slows down, in pixels/second².
  11257. inertiaDeceleration: 3400, // px/s^2
  11258. // @option inertiaMaxSpeed: Number = Infinity
  11259. // Max speed of the inertial movement, in pixels/second.
  11260. inertiaMaxSpeed: Infinity, // px/s
  11261. // @option easeLinearity: Number = 0.2
  11262. easeLinearity: 0.2,
  11263. // TODO refactor, move to CRS
  11264. // @option worldCopyJump: Boolean = false
  11265. // With this option enabled, the map tracks when you pan to another "copy"
  11266. // of the world and seamlessly jumps to the original one so that all overlays
  11267. // like markers and vector layers are still visible.
  11268. worldCopyJump: false,
  11269. // @option maxBoundsViscosity: Number = 0.0
  11270. // If `maxBounds` is set, this option will control how solid the bounds
  11271. // are when dragging the map around. The default value of `0.0` allows the
  11272. // user to drag outside the bounds at normal speed, higher values will
  11273. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  11274. // solid, preventing the user from dragging outside the bounds.
  11275. maxBoundsViscosity: 0.0
  11276. });
  11277. var Drag = Handler.extend({
  11278. addHooks: function () {
  11279. if (!this._draggable) {
  11280. var map = this._map;
  11281. this._draggable = new Draggable(map._mapPane, map._container);
  11282. this._draggable.on({
  11283. dragstart: this._onDragStart,
  11284. drag: this._onDrag,
  11285. dragend: this._onDragEnd
  11286. }, this);
  11287. this._draggable.on('predrag', this._onPreDragLimit, this);
  11288. if (map.options.worldCopyJump) {
  11289. this._draggable.on('predrag', this._onPreDragWrap, this);
  11290. map.on('zoomend', this._onZoomEnd, this);
  11291. map.whenReady(this._onZoomEnd, this);
  11292. }
  11293. }
  11294. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  11295. this._draggable.enable();
  11296. this._positions = [];
  11297. this._times = [];
  11298. },
  11299. removeHooks: function () {
  11300. removeClass(this._map._container, 'leaflet-grab');
  11301. removeClass(this._map._container, 'leaflet-touch-drag');
  11302. this._draggable.disable();
  11303. },
  11304. moved: function () {
  11305. return this._draggable && this._draggable._moved;
  11306. },
  11307. moving: function () {
  11308. return this._draggable && this._draggable._moving;
  11309. },
  11310. _onDragStart: function () {
  11311. var map = this._map;
  11312. map._stop();
  11313. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  11314. var bounds = toLatLngBounds(this._map.options.maxBounds);
  11315. this._offsetLimit = toBounds(
  11316. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  11317. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  11318. .add(this._map.getSize()));
  11319. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  11320. } else {
  11321. this._offsetLimit = null;
  11322. }
  11323. map
  11324. .fire('movestart')
  11325. .fire('dragstart');
  11326. if (map.options.inertia) {
  11327. this._positions = [];
  11328. this._times = [];
  11329. }
  11330. },
  11331. _onDrag: function (e) {
  11332. if (this._map.options.inertia) {
  11333. var time = this._lastTime = +new Date(),
  11334. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  11335. this._positions.push(pos);
  11336. this._times.push(time);
  11337. this._prunePositions(time);
  11338. }
  11339. this._map
  11340. .fire('move', e)
  11341. .fire('drag', e);
  11342. },
  11343. _prunePositions: function (time) {
  11344. while (this._positions.length > 1 && time - this._times[0] > 50) {
  11345. this._positions.shift();
  11346. this._times.shift();
  11347. }
  11348. },
  11349. _onZoomEnd: function () {
  11350. var pxCenter = this._map.getSize().divideBy(2),
  11351. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  11352. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  11353. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  11354. },
  11355. _viscousLimit: function (value, threshold) {
  11356. return value - (value - threshold) * this._viscosity;
  11357. },
  11358. _onPreDragLimit: function () {
  11359. if (!this._viscosity || !this._offsetLimit) { return; }
  11360. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  11361. var limit = this._offsetLimit;
  11362. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  11363. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  11364. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  11365. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  11366. this._draggable._newPos = this._draggable._startPos.add(offset);
  11367. },
  11368. _onPreDragWrap: function () {
  11369. // TODO refactor to be able to adjust map pane position after zoom
  11370. var worldWidth = this._worldWidth,
  11371. halfWidth = Math.round(worldWidth / 2),
  11372. dx = this._initialWorldOffset,
  11373. x = this._draggable._newPos.x,
  11374. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  11375. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  11376. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  11377. this._draggable._absPos = this._draggable._newPos.clone();
  11378. this._draggable._newPos.x = newX;
  11379. },
  11380. _onDragEnd: function (e) {
  11381. var map = this._map,
  11382. options = map.options,
  11383. noInertia = !options.inertia || e.noInertia || this._times.length < 2;
  11384. map.fire('dragend', e);
  11385. if (noInertia) {
  11386. map.fire('moveend');
  11387. } else {
  11388. this._prunePositions(+new Date());
  11389. var direction = this._lastPos.subtract(this._positions[0]),
  11390. duration = (this._lastTime - this._times[0]) / 1000,
  11391. ease = options.easeLinearity,
  11392. speedVector = direction.multiplyBy(ease / duration),
  11393. speed = speedVector.distanceTo([0, 0]),
  11394. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  11395. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  11396. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  11397. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  11398. if (!offset.x && !offset.y) {
  11399. map.fire('moveend');
  11400. } else {
  11401. offset = map._limitOffset(offset, map.options.maxBounds);
  11402. requestAnimFrame(function () {
  11403. map.panBy(offset, {
  11404. duration: decelerationDuration,
  11405. easeLinearity: ease,
  11406. noMoveStart: true,
  11407. animate: true
  11408. });
  11409. });
  11410. }
  11411. }
  11412. }
  11413. });
  11414. // @section Handlers
  11415. // @property dragging: Handler
  11416. // Map dragging handler (by both mouse and touch).
  11417. Map.addInitHook('addHandler', 'dragging', Drag);
  11418. /*
  11419. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  11420. */
  11421. // @namespace Map
  11422. // @section Keyboard Navigation Options
  11423. Map.mergeOptions({
  11424. // @option keyboard: Boolean = true
  11425. // Makes the map focusable and allows users to navigate the map with keyboard
  11426. // arrows and `+`/`-` keys.
  11427. keyboard: true,
  11428. // @option keyboardPanDelta: Number = 80
  11429. // Amount of pixels to pan when pressing an arrow key.
  11430. keyboardPanDelta: 80
  11431. });
  11432. var Keyboard = Handler.extend({
  11433. keyCodes: {
  11434. left: [37],
  11435. right: [39],
  11436. down: [40],
  11437. up: [38],
  11438. zoomIn: [187, 107, 61, 171],
  11439. zoomOut: [189, 109, 54, 173]
  11440. },
  11441. initialize: function (map) {
  11442. this._map = map;
  11443. this._setPanDelta(map.options.keyboardPanDelta);
  11444. this._setZoomDelta(map.options.zoomDelta);
  11445. },
  11446. addHooks: function () {
  11447. var container = this._map._container;
  11448. // make the container focusable by tabbing
  11449. if (container.tabIndex <= 0) {
  11450. container.tabIndex = '0';
  11451. }
  11452. on(container, {
  11453. focus: this._onFocus,
  11454. blur: this._onBlur,
  11455. mousedown: this._onMouseDown
  11456. }, this);
  11457. this._map.on({
  11458. focus: this._addHooks,
  11459. blur: this._removeHooks
  11460. }, this);
  11461. },
  11462. removeHooks: function () {
  11463. this._removeHooks();
  11464. off(this._map._container, {
  11465. focus: this._onFocus,
  11466. blur: this._onBlur,
  11467. mousedown: this._onMouseDown
  11468. }, this);
  11469. this._map.off({
  11470. focus: this._addHooks,
  11471. blur: this._removeHooks
  11472. }, this);
  11473. },
  11474. _onMouseDown: function () {
  11475. if (this._focused) { return; }
  11476. var body = document.body,
  11477. docEl = document.documentElement,
  11478. top = body.scrollTop || docEl.scrollTop,
  11479. left = body.scrollLeft || docEl.scrollLeft;
  11480. this._map._container.focus();
  11481. window.scrollTo(left, top);
  11482. },
  11483. _onFocus: function () {
  11484. this._focused = true;
  11485. this._map.fire('focus');
  11486. },
  11487. _onBlur: function () {
  11488. this._focused = false;
  11489. this._map.fire('blur');
  11490. },
  11491. _setPanDelta: function (panDelta) {
  11492. var keys = this._panKeys = {},
  11493. codes = this.keyCodes,
  11494. i, len;
  11495. for (i = 0, len = codes.left.length; i < len; i++) {
  11496. keys[codes.left[i]] = [-1 * panDelta, 0];
  11497. }
  11498. for (i = 0, len = codes.right.length; i < len; i++) {
  11499. keys[codes.right[i]] = [panDelta, 0];
  11500. }
  11501. for (i = 0, len = codes.down.length; i < len; i++) {
  11502. keys[codes.down[i]] = [0, panDelta];
  11503. }
  11504. for (i = 0, len = codes.up.length; i < len; i++) {
  11505. keys[codes.up[i]] = [0, -1 * panDelta];
  11506. }
  11507. },
  11508. _setZoomDelta: function (zoomDelta) {
  11509. var keys = this._zoomKeys = {},
  11510. codes = this.keyCodes,
  11511. i, len;
  11512. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  11513. keys[codes.zoomIn[i]] = zoomDelta;
  11514. }
  11515. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  11516. keys[codes.zoomOut[i]] = -zoomDelta;
  11517. }
  11518. },
  11519. _addHooks: function () {
  11520. on(document, 'keydown', this._onKeyDown, this);
  11521. },
  11522. _removeHooks: function () {
  11523. off(document, 'keydown', this._onKeyDown, this);
  11524. },
  11525. _onKeyDown: function (e) {
  11526. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  11527. var key = e.keyCode,
  11528. map = this._map,
  11529. offset;
  11530. if (key in this._panKeys) {
  11531. if (!map._panAnim || !map._panAnim._inProgress) {
  11532. offset = this._panKeys[key];
  11533. if (e.shiftKey) {
  11534. offset = toPoint(offset).multiplyBy(3);
  11535. }
  11536. if (map.options.maxBounds) {
  11537. offset = map._limitOffset(toPoint(offset), map.options.maxBounds);
  11538. }
  11539. if (map.options.worldCopyJump) {
  11540. var newLatLng = map.wrapLatLng(map.unproject(map.project(map.getCenter()).add(offset)));
  11541. map.panTo(newLatLng);
  11542. } else {
  11543. map.panBy(offset);
  11544. }
  11545. }
  11546. } else if (key in this._zoomKeys) {
  11547. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  11548. } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
  11549. map.closePopup();
  11550. } else {
  11551. return;
  11552. }
  11553. stop(e);
  11554. }
  11555. });
  11556. // @section Handlers
  11557. // @section Handlers
  11558. // @property keyboard: Handler
  11559. // Keyboard navigation handler.
  11560. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  11561. /*
  11562. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  11563. */
  11564. // @namespace Map
  11565. // @section Interaction Options
  11566. Map.mergeOptions({
  11567. // @section Mouse wheel options
  11568. // @option scrollWheelZoom: Boolean|String = true
  11569. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  11570. // it will zoom to the center of the view regardless of where the mouse was.
  11571. scrollWheelZoom: true,
  11572. // @option wheelDebounceTime: Number = 40
  11573. // Limits the rate at which a wheel can fire (in milliseconds). By default
  11574. // user can't zoom via wheel more often than once per 40 ms.
  11575. wheelDebounceTime: 40,
  11576. // @option wheelPxPerZoomLevel: Number = 60
  11577. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  11578. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  11579. // faster (and vice versa).
  11580. wheelPxPerZoomLevel: 60
  11581. });
  11582. var ScrollWheelZoom = Handler.extend({
  11583. addHooks: function () {
  11584. on(this._map._container, 'wheel', this._onWheelScroll, this);
  11585. this._delta = 0;
  11586. },
  11587. removeHooks: function () {
  11588. off(this._map._container, 'wheel', this._onWheelScroll, this);
  11589. },
  11590. _onWheelScroll: function (e) {
  11591. var delta = getWheelDelta(e);
  11592. var debounce = this._map.options.wheelDebounceTime;
  11593. this._delta += delta;
  11594. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  11595. if (!this._startTime) {
  11596. this._startTime = +new Date();
  11597. }
  11598. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  11599. clearTimeout(this._timer);
  11600. this._timer = setTimeout(bind(this._performZoom, this), left);
  11601. stop(e);
  11602. },
  11603. _performZoom: function () {
  11604. var map = this._map,
  11605. zoom = map.getZoom(),
  11606. snap = this._map.options.zoomSnap || 0;
  11607. map._stop(); // stop panning and fly animations if any
  11608. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  11609. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  11610. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  11611. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  11612. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  11613. this._delta = 0;
  11614. this._startTime = null;
  11615. if (!delta) { return; }
  11616. if (map.options.scrollWheelZoom === 'center') {
  11617. map.setZoom(zoom + delta);
  11618. } else {
  11619. map.setZoomAround(this._lastMousePos, zoom + delta);
  11620. }
  11621. }
  11622. });
  11623. // @section Handlers
  11624. // @property scrollWheelZoom: Handler
  11625. // Scroll wheel zoom handler.
  11626. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  11627. /*
  11628. * L.Map.TapHold is used to simulate `contextmenu` event on long hold,
  11629. * which otherwise is not fired by mobile Safari.
  11630. */
  11631. var tapHoldDelay = 600;
  11632. // @namespace Map
  11633. // @section Interaction Options
  11634. Map.mergeOptions({
  11635. // @section Touch interaction options
  11636. // @option tapHold: Boolean
  11637. // Enables simulation of `contextmenu` event, default is `true` for mobile Safari.
  11638. tapHold: Browser.touchNative && Browser.safari && Browser.mobile,
  11639. // @option tapTolerance: Number = 15
  11640. // The max number of pixels a user can shift his finger during touch
  11641. // for it to be considered a valid tap.
  11642. tapTolerance: 15
  11643. });
  11644. var TapHold = Handler.extend({
  11645. addHooks: function () {
  11646. on(this._map._container, 'touchstart', this._onDown, this);
  11647. },
  11648. removeHooks: function () {
  11649. off(this._map._container, 'touchstart', this._onDown, this);
  11650. },
  11651. _onDown: function (e) {
  11652. clearTimeout(this._holdTimeout);
  11653. if (e.touches.length !== 1) { return; }
  11654. var first = e.touches[0];
  11655. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  11656. this._holdTimeout = setTimeout(bind(function () {
  11657. this._cancel();
  11658. if (!this._isTapValid()) { return; }
  11659. // prevent simulated mouse events https://w3c.github.io/touch-events/#mouse-events
  11660. on(document, 'touchend', preventDefault);
  11661. on(document, 'touchend touchcancel', this._cancelClickPrevent);
  11662. this._simulateEvent('contextmenu', first);
  11663. }, this), tapHoldDelay);
  11664. on(document, 'touchend touchcancel contextmenu', this._cancel, this);
  11665. on(document, 'touchmove', this._onMove, this);
  11666. },
  11667. _cancelClickPrevent: function cancelClickPrevent() {
  11668. off(document, 'touchend', preventDefault);
  11669. off(document, 'touchend touchcancel', cancelClickPrevent);
  11670. },
  11671. _cancel: function () {
  11672. clearTimeout(this._holdTimeout);
  11673. off(document, 'touchend touchcancel contextmenu', this._cancel, this);
  11674. off(document, 'touchmove', this._onMove, this);
  11675. },
  11676. _onMove: function (e) {
  11677. var first = e.touches[0];
  11678. this._newPos = new Point(first.clientX, first.clientY);
  11679. },
  11680. _isTapValid: function () {
  11681. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11682. },
  11683. _simulateEvent: function (type, e) {
  11684. var simulatedEvent = new MouseEvent(type, {
  11685. bubbles: true,
  11686. cancelable: true,
  11687. view: window,
  11688. // detail: 1,
  11689. screenX: e.screenX,
  11690. screenY: e.screenY,
  11691. clientX: e.clientX,
  11692. clientY: e.clientY,
  11693. // button: 2,
  11694. // buttons: 2
  11695. });
  11696. simulatedEvent._simulated = true;
  11697. e.target.dispatchEvent(simulatedEvent);
  11698. }
  11699. });
  11700. // @section Handlers
  11701. // @property tapHold: Handler
  11702. // Long tap handler to simulate `contextmenu` event (useful in mobile Safari).
  11703. Map.addInitHook('addHandler', 'tapHold', TapHold);
  11704. /*
  11705. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11706. */
  11707. // @namespace Map
  11708. // @section Interaction Options
  11709. Map.mergeOptions({
  11710. // @section Touch interaction options
  11711. // @option touchZoom: Boolean|String = *
  11712. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11713. // passed `'center'`, it will zoom to the center of the view regardless of
  11714. // where the touch events (fingers) were. Enabled for touch-capable web
  11715. // browsers.
  11716. touchZoom: Browser.touch,
  11717. // @option bounceAtZoomLimits: Boolean = true
  11718. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11719. // and then bounce back when pinch-zooming.
  11720. bounceAtZoomLimits: true
  11721. });
  11722. var TouchZoom = Handler.extend({
  11723. addHooks: function () {
  11724. addClass(this._map._container, 'leaflet-touch-zoom');
  11725. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11726. },
  11727. removeHooks: function () {
  11728. removeClass(this._map._container, 'leaflet-touch-zoom');
  11729. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11730. },
  11731. _onTouchStart: function (e) {
  11732. var map = this._map;
  11733. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  11734. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11735. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11736. this._centerPoint = map.getSize()._divideBy(2);
  11737. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11738. if (map.options.touchZoom !== 'center') {
  11739. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11740. }
  11741. this._startDist = p1.distanceTo(p2);
  11742. this._startZoom = map.getZoom();
  11743. this._moved = false;
  11744. this._zooming = true;
  11745. map._stop();
  11746. on(document, 'touchmove', this._onTouchMove, this);
  11747. on(document, 'touchend touchcancel', this._onTouchEnd, this);
  11748. preventDefault(e);
  11749. },
  11750. _onTouchMove: function (e) {
  11751. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  11752. var map = this._map,
  11753. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11754. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11755. scale = p1.distanceTo(p2) / this._startDist;
  11756. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11757. if (!map.options.bounceAtZoomLimits && (
  11758. (this._zoom < map.getMinZoom() && scale < 1) ||
  11759. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11760. this._zoom = map._limitZoom(this._zoom);
  11761. }
  11762. if (map.options.touchZoom === 'center') {
  11763. this._center = this._startLatLng;
  11764. if (scale === 1) { return; }
  11765. } else {
  11766. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11767. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11768. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  11769. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11770. }
  11771. if (!this._moved) {
  11772. map._moveStart(true, false);
  11773. this._moved = true;
  11774. }
  11775. cancelAnimFrame(this._animRequest);
  11776. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false}, undefined);
  11777. this._animRequest = requestAnimFrame(moveFn, this, true);
  11778. preventDefault(e);
  11779. },
  11780. _onTouchEnd: function () {
  11781. if (!this._moved || !this._zooming) {
  11782. this._zooming = false;
  11783. return;
  11784. }
  11785. this._zooming = false;
  11786. cancelAnimFrame(this._animRequest);
  11787. off(document, 'touchmove', this._onTouchMove, this);
  11788. off(document, 'touchend touchcancel', this._onTouchEnd, this);
  11789. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11790. if (this._map.options.zoomAnimation) {
  11791. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11792. } else {
  11793. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11794. }
  11795. }
  11796. });
  11797. // @section Handlers
  11798. // @property touchZoom: Handler
  11799. // Touch zoom handler.
  11800. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11801. Map.BoxZoom = BoxZoom;
  11802. Map.DoubleClickZoom = DoubleClickZoom;
  11803. Map.Drag = Drag;
  11804. Map.Keyboard = Keyboard;
  11805. Map.ScrollWheelZoom = ScrollWheelZoom;
  11806. Map.TapHold = TapHold;
  11807. Map.TouchZoom = TouchZoom;
  11808. export { Bounds, Browser, CRS, Canvas, Circle, CircleMarker, Class, Control, DivIcon, DivOverlay, DomEvent, DomUtil, Draggable, Evented, FeatureGroup, GeoJSON, GridLayer, Handler, Icon, ImageOverlay, LatLng, LatLngBounds, Layer, LayerGroup, LineUtil, Map, Marker, Mixin, Path, Point, PolyUtil, Polygon, Polyline, Popup, PosAnimation, index as Projection, Rectangle, Renderer, SVG, SVGOverlay, TileLayer, Tooltip, Transformation, Util, VideoOverlay, bind, toBounds as bounds, canvas, circle, circleMarker, control, divIcon, extend, featureGroup, geoJSON, geoJson, gridLayer, icon, imageOverlay, toLatLng as latLng, toLatLngBounds as latLngBounds, layerGroup, createMap as map, marker, toPoint as point, polygon, polyline, popup, rectangle, setOptions, stamp, svg, svgOverlay, tileLayer, tooltip, toTransformation as transformation, version, videoOverlay };
  11809. //# sourceMappingURL=leaflet-src.esm.js.map